Initial Sample.

This commit is contained in:
2024-06-03 20:23:50 +05:30
parent ef2b65f673
commit 5269ec3c66
2575 changed files with 282312 additions and 0 deletions

View File

@@ -0,0 +1,67 @@
import type { Maybe } from '../jsutils/Maybe';
import type { ASTNode, FieldNode } from '../language/ast';
import type { ASTVisitor } from '../language/visitor';
import type {
GraphQLArgument,
GraphQLCompositeType,
GraphQLEnumValue,
GraphQLField,
GraphQLInputType,
GraphQLOutputType,
GraphQLType,
} from '../type/definition';
import type { GraphQLDirective } from '../type/directives';
import type { GraphQLSchema } from '../type/schema';
/**
* TypeInfo is a utility class which, given a GraphQL schema, can keep track
* of the current field and type definitions at any point in a GraphQL document
* AST during a recursive descent by calling `enter(node)` and `leave(node)`.
*/
export declare class TypeInfo {
private _schema;
private _typeStack;
private _parentTypeStack;
private _inputTypeStack;
private _fieldDefStack;
private _defaultValueStack;
private _directive;
private _argument;
private _enumValue;
private _getFieldDef;
constructor(
schema: GraphQLSchema,
/**
* Initial type may be provided in rare cases to facilitate traversals
* beginning somewhere other than documents.
*/
initialType?: Maybe<GraphQLType>,
/** @deprecated will be removed in 17.0.0 */
getFieldDefFn?: GetFieldDefFn,
);
get [Symbol.toStringTag](): string;
getType(): Maybe<GraphQLOutputType>;
getParentType(): Maybe<GraphQLCompositeType>;
getInputType(): Maybe<GraphQLInputType>;
getParentInputType(): Maybe<GraphQLInputType>;
getFieldDef(): Maybe<GraphQLField<unknown, unknown>>;
getDefaultValue(): Maybe<unknown>;
getDirective(): Maybe<GraphQLDirective>;
getArgument(): Maybe<GraphQLArgument>;
getEnumValue(): Maybe<GraphQLEnumValue>;
enter(node: ASTNode): void;
leave(node: ASTNode): void;
}
declare type GetFieldDefFn = (
schema: GraphQLSchema,
parentType: GraphQLType,
fieldNode: FieldNode,
) => Maybe<GraphQLField<unknown, unknown>>;
/**
* Creates a new visitor instance which maintains a provided TypeInfo instance
* along with visiting visitor.
*/
export declare function visitWithTypeInfo(
typeInfo: TypeInfo,
visitor: ASTVisitor,
): ASTVisitor;
export {};

View File

@@ -0,0 +1,418 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.TypeInfo = void 0;
exports.visitWithTypeInfo = visitWithTypeInfo;
var _ast = require('../language/ast.js');
var _kinds = require('../language/kinds.js');
var _visitor = require('../language/visitor.js');
var _definition = require('../type/definition.js');
var _introspection = require('../type/introspection.js');
var _typeFromAST = require('./typeFromAST.js');
/**
* TypeInfo is a utility class which, given a GraphQL schema, can keep track
* of the current field and type definitions at any point in a GraphQL document
* AST during a recursive descent by calling `enter(node)` and `leave(node)`.
*/
class TypeInfo {
constructor(
schema,
/**
* Initial type may be provided in rare cases to facilitate traversals
* beginning somewhere other than documents.
*/
initialType,
/** @deprecated will be removed in 17.0.0 */
getFieldDefFn,
) {
this._schema = schema;
this._typeStack = [];
this._parentTypeStack = [];
this._inputTypeStack = [];
this._fieldDefStack = [];
this._defaultValueStack = [];
this._directive = null;
this._argument = null;
this._enumValue = null;
this._getFieldDef =
getFieldDefFn !== null && getFieldDefFn !== void 0
? getFieldDefFn
: getFieldDef;
if (initialType) {
if ((0, _definition.isInputType)(initialType)) {
this._inputTypeStack.push(initialType);
}
if ((0, _definition.isCompositeType)(initialType)) {
this._parentTypeStack.push(initialType);
}
if ((0, _definition.isOutputType)(initialType)) {
this._typeStack.push(initialType);
}
}
}
get [Symbol.toStringTag]() {
return 'TypeInfo';
}
getType() {
if (this._typeStack.length > 0) {
return this._typeStack[this._typeStack.length - 1];
}
}
getParentType() {
if (this._parentTypeStack.length > 0) {
return this._parentTypeStack[this._parentTypeStack.length - 1];
}
}
getInputType() {
if (this._inputTypeStack.length > 0) {
return this._inputTypeStack[this._inputTypeStack.length - 1];
}
}
getParentInputType() {
if (this._inputTypeStack.length > 1) {
return this._inputTypeStack[this._inputTypeStack.length - 2];
}
}
getFieldDef() {
if (this._fieldDefStack.length > 0) {
return this._fieldDefStack[this._fieldDefStack.length - 1];
}
}
getDefaultValue() {
if (this._defaultValueStack.length > 0) {
return this._defaultValueStack[this._defaultValueStack.length - 1];
}
}
getDirective() {
return this._directive;
}
getArgument() {
return this._argument;
}
getEnumValue() {
return this._enumValue;
}
enter(node) {
const schema = this._schema; // Note: many of the types below are explicitly typed as "unknown" to drop
// any assumptions of a valid schema to ensure runtime types are properly
// checked before continuing since TypeInfo is used as part of validation
// which occurs before guarantees of schema and document validity.
switch (node.kind) {
case _kinds.Kind.SELECTION_SET: {
const namedType = (0, _definition.getNamedType)(this.getType());
this._parentTypeStack.push(
(0, _definition.isCompositeType)(namedType) ? namedType : undefined,
);
break;
}
case _kinds.Kind.FIELD: {
const parentType = this.getParentType();
let fieldDef;
let fieldType;
if (parentType) {
fieldDef = this._getFieldDef(schema, parentType, node);
if (fieldDef) {
fieldType = fieldDef.type;
}
}
this._fieldDefStack.push(fieldDef);
this._typeStack.push(
(0, _definition.isOutputType)(fieldType) ? fieldType : undefined,
);
break;
}
case _kinds.Kind.DIRECTIVE:
this._directive = schema.getDirective(node.name.value);
break;
case _kinds.Kind.OPERATION_DEFINITION: {
const rootType = schema.getRootType(node.operation);
this._typeStack.push(
(0, _definition.isObjectType)(rootType) ? rootType : undefined,
);
break;
}
case _kinds.Kind.INLINE_FRAGMENT:
case _kinds.Kind.FRAGMENT_DEFINITION: {
const typeConditionAST = node.typeCondition;
const outputType = typeConditionAST
? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST)
: (0, _definition.getNamedType)(this.getType());
this._typeStack.push(
(0, _definition.isOutputType)(outputType) ? outputType : undefined,
);
break;
}
case _kinds.Kind.VARIABLE_DEFINITION: {
const inputType = (0, _typeFromAST.typeFromAST)(schema, node.type);
this._inputTypeStack.push(
(0, _definition.isInputType)(inputType) ? inputType : undefined,
);
break;
}
case _kinds.Kind.ARGUMENT: {
var _this$getDirective;
let argDef;
let argType;
const fieldOrDirective =
(_this$getDirective = this.getDirective()) !== null &&
_this$getDirective !== void 0
? _this$getDirective
: this.getFieldDef();
if (fieldOrDirective) {
argDef = fieldOrDirective.args.find(
(arg) => arg.name === node.name.value,
);
if (argDef) {
argType = argDef.type;
}
}
this._argument = argDef;
this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined);
this._inputTypeStack.push(
(0, _definition.isInputType)(argType) ? argType : undefined,
);
break;
}
case _kinds.Kind.LIST: {
const listType = (0, _definition.getNullableType)(this.getInputType());
const itemType = (0, _definition.isListType)(listType)
? listType.ofType
: listType; // List positions never have a default value.
this._defaultValueStack.push(undefined);
this._inputTypeStack.push(
(0, _definition.isInputType)(itemType) ? itemType : undefined,
);
break;
}
case _kinds.Kind.OBJECT_FIELD: {
const objectType = (0, _definition.getNamedType)(this.getInputType());
let inputFieldType;
let inputField;
if ((0, _definition.isInputObjectType)(objectType)) {
inputField = objectType.getFields()[node.name.value];
if (inputField) {
inputFieldType = inputField.type;
}
}
this._defaultValueStack.push(
inputField ? inputField.defaultValue : undefined,
);
this._inputTypeStack.push(
(0, _definition.isInputType)(inputFieldType)
? inputFieldType
: undefined,
);
break;
}
case _kinds.Kind.ENUM: {
const enumType = (0, _definition.getNamedType)(this.getInputType());
let enumValue;
if ((0, _definition.isEnumType)(enumType)) {
enumValue = enumType.getValue(node.value);
}
this._enumValue = enumValue;
break;
}
default: // Ignore other nodes
}
}
leave(node) {
switch (node.kind) {
case _kinds.Kind.SELECTION_SET:
this._parentTypeStack.pop();
break;
case _kinds.Kind.FIELD:
this._fieldDefStack.pop();
this._typeStack.pop();
break;
case _kinds.Kind.DIRECTIVE:
this._directive = null;
break;
case _kinds.Kind.OPERATION_DEFINITION:
case _kinds.Kind.INLINE_FRAGMENT:
case _kinds.Kind.FRAGMENT_DEFINITION:
this._typeStack.pop();
break;
case _kinds.Kind.VARIABLE_DEFINITION:
this._inputTypeStack.pop();
break;
case _kinds.Kind.ARGUMENT:
this._argument = null;
this._defaultValueStack.pop();
this._inputTypeStack.pop();
break;
case _kinds.Kind.LIST:
case _kinds.Kind.OBJECT_FIELD:
this._defaultValueStack.pop();
this._inputTypeStack.pop();
break;
case _kinds.Kind.ENUM:
this._enumValue = null;
break;
default: // Ignore other nodes
}
}
}
exports.TypeInfo = TypeInfo;
/**
* Not exactly the same as the executor's definition of getFieldDef, in this
* statically evaluated environment we do not always have an Object type,
* and need to handle Interface and Union types.
*/
function getFieldDef(schema, parentType, fieldNode) {
const name = fieldNode.name.value;
if (
name === _introspection.SchemaMetaFieldDef.name &&
schema.getQueryType() === parentType
) {
return _introspection.SchemaMetaFieldDef;
}
if (
name === _introspection.TypeMetaFieldDef.name &&
schema.getQueryType() === parentType
) {
return _introspection.TypeMetaFieldDef;
}
if (
name === _introspection.TypeNameMetaFieldDef.name &&
(0, _definition.isCompositeType)(parentType)
) {
return _introspection.TypeNameMetaFieldDef;
}
if (
(0, _definition.isObjectType)(parentType) ||
(0, _definition.isInterfaceType)(parentType)
) {
return parentType.getFields()[name];
}
}
/**
* Creates a new visitor instance which maintains a provided TypeInfo instance
* along with visiting visitor.
*/
function visitWithTypeInfo(typeInfo, visitor) {
return {
enter(...args) {
const node = args[0];
typeInfo.enter(node);
const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).enter;
if (fn) {
const result = fn.apply(visitor, args);
if (result !== undefined) {
typeInfo.leave(node);
if ((0, _ast.isNode)(result)) {
typeInfo.enter(result);
}
}
return result;
}
},
leave(...args) {
const node = args[0];
const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).leave;
let result;
if (fn) {
result = fn.apply(visitor, args);
}
typeInfo.leave(node);
return result;
},
};
}

View File

@@ -0,0 +1,395 @@
import { isNode } from '../language/ast.mjs';
import { Kind } from '../language/kinds.mjs';
import { getEnterLeaveForKind } from '../language/visitor.mjs';
import {
getNamedType,
getNullableType,
isCompositeType,
isEnumType,
isInputObjectType,
isInputType,
isInterfaceType,
isListType,
isObjectType,
isOutputType,
} from '../type/definition.mjs';
import {
SchemaMetaFieldDef,
TypeMetaFieldDef,
TypeNameMetaFieldDef,
} from '../type/introspection.mjs';
import { typeFromAST } from './typeFromAST.mjs';
/**
* TypeInfo is a utility class which, given a GraphQL schema, can keep track
* of the current field and type definitions at any point in a GraphQL document
* AST during a recursive descent by calling `enter(node)` and `leave(node)`.
*/
export class TypeInfo {
constructor(
schema,
/**
* Initial type may be provided in rare cases to facilitate traversals
* beginning somewhere other than documents.
*/
initialType,
/** @deprecated will be removed in 17.0.0 */
getFieldDefFn,
) {
this._schema = schema;
this._typeStack = [];
this._parentTypeStack = [];
this._inputTypeStack = [];
this._fieldDefStack = [];
this._defaultValueStack = [];
this._directive = null;
this._argument = null;
this._enumValue = null;
this._getFieldDef =
getFieldDefFn !== null && getFieldDefFn !== void 0
? getFieldDefFn
: getFieldDef;
if (initialType) {
if (isInputType(initialType)) {
this._inputTypeStack.push(initialType);
}
if (isCompositeType(initialType)) {
this._parentTypeStack.push(initialType);
}
if (isOutputType(initialType)) {
this._typeStack.push(initialType);
}
}
}
get [Symbol.toStringTag]() {
return 'TypeInfo';
}
getType() {
if (this._typeStack.length > 0) {
return this._typeStack[this._typeStack.length - 1];
}
}
getParentType() {
if (this._parentTypeStack.length > 0) {
return this._parentTypeStack[this._parentTypeStack.length - 1];
}
}
getInputType() {
if (this._inputTypeStack.length > 0) {
return this._inputTypeStack[this._inputTypeStack.length - 1];
}
}
getParentInputType() {
if (this._inputTypeStack.length > 1) {
return this._inputTypeStack[this._inputTypeStack.length - 2];
}
}
getFieldDef() {
if (this._fieldDefStack.length > 0) {
return this._fieldDefStack[this._fieldDefStack.length - 1];
}
}
getDefaultValue() {
if (this._defaultValueStack.length > 0) {
return this._defaultValueStack[this._defaultValueStack.length - 1];
}
}
getDirective() {
return this._directive;
}
getArgument() {
return this._argument;
}
getEnumValue() {
return this._enumValue;
}
enter(node) {
const schema = this._schema; // Note: many of the types below are explicitly typed as "unknown" to drop
// any assumptions of a valid schema to ensure runtime types are properly
// checked before continuing since TypeInfo is used as part of validation
// which occurs before guarantees of schema and document validity.
switch (node.kind) {
case Kind.SELECTION_SET: {
const namedType = getNamedType(this.getType());
this._parentTypeStack.push(
isCompositeType(namedType) ? namedType : undefined,
);
break;
}
case Kind.FIELD: {
const parentType = this.getParentType();
let fieldDef;
let fieldType;
if (parentType) {
fieldDef = this._getFieldDef(schema, parentType, node);
if (fieldDef) {
fieldType = fieldDef.type;
}
}
this._fieldDefStack.push(fieldDef);
this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined);
break;
}
case Kind.DIRECTIVE:
this._directive = schema.getDirective(node.name.value);
break;
case Kind.OPERATION_DEFINITION: {
const rootType = schema.getRootType(node.operation);
this._typeStack.push(isObjectType(rootType) ? rootType : undefined);
break;
}
case Kind.INLINE_FRAGMENT:
case Kind.FRAGMENT_DEFINITION: {
const typeConditionAST = node.typeCondition;
const outputType = typeConditionAST
? typeFromAST(schema, typeConditionAST)
: getNamedType(this.getType());
this._typeStack.push(isOutputType(outputType) ? outputType : undefined);
break;
}
case Kind.VARIABLE_DEFINITION: {
const inputType = typeFromAST(schema, node.type);
this._inputTypeStack.push(
isInputType(inputType) ? inputType : undefined,
);
break;
}
case Kind.ARGUMENT: {
var _this$getDirective;
let argDef;
let argType;
const fieldOrDirective =
(_this$getDirective = this.getDirective()) !== null &&
_this$getDirective !== void 0
? _this$getDirective
: this.getFieldDef();
if (fieldOrDirective) {
argDef = fieldOrDirective.args.find(
(arg) => arg.name === node.name.value,
);
if (argDef) {
argType = argDef.type;
}
}
this._argument = argDef;
this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined);
this._inputTypeStack.push(isInputType(argType) ? argType : undefined);
break;
}
case Kind.LIST: {
const listType = getNullableType(this.getInputType());
const itemType = isListType(listType) ? listType.ofType : listType; // List positions never have a default value.
this._defaultValueStack.push(undefined);
this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined);
break;
}
case Kind.OBJECT_FIELD: {
const objectType = getNamedType(this.getInputType());
let inputFieldType;
let inputField;
if (isInputObjectType(objectType)) {
inputField = objectType.getFields()[node.name.value];
if (inputField) {
inputFieldType = inputField.type;
}
}
this._defaultValueStack.push(
inputField ? inputField.defaultValue : undefined,
);
this._inputTypeStack.push(
isInputType(inputFieldType) ? inputFieldType : undefined,
);
break;
}
case Kind.ENUM: {
const enumType = getNamedType(this.getInputType());
let enumValue;
if (isEnumType(enumType)) {
enumValue = enumType.getValue(node.value);
}
this._enumValue = enumValue;
break;
}
default: // Ignore other nodes
}
}
leave(node) {
switch (node.kind) {
case Kind.SELECTION_SET:
this._parentTypeStack.pop();
break;
case Kind.FIELD:
this._fieldDefStack.pop();
this._typeStack.pop();
break;
case Kind.DIRECTIVE:
this._directive = null;
break;
case Kind.OPERATION_DEFINITION:
case Kind.INLINE_FRAGMENT:
case Kind.FRAGMENT_DEFINITION:
this._typeStack.pop();
break;
case Kind.VARIABLE_DEFINITION:
this._inputTypeStack.pop();
break;
case Kind.ARGUMENT:
this._argument = null;
this._defaultValueStack.pop();
this._inputTypeStack.pop();
break;
case Kind.LIST:
case Kind.OBJECT_FIELD:
this._defaultValueStack.pop();
this._inputTypeStack.pop();
break;
case Kind.ENUM:
this._enumValue = null;
break;
default: // Ignore other nodes
}
}
}
/**
* Not exactly the same as the executor's definition of getFieldDef, in this
* statically evaluated environment we do not always have an Object type,
* and need to handle Interface and Union types.
*/
function getFieldDef(schema, parentType, fieldNode) {
const name = fieldNode.name.value;
if (
name === SchemaMetaFieldDef.name &&
schema.getQueryType() === parentType
) {
return SchemaMetaFieldDef;
}
if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
return TypeMetaFieldDef;
}
if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) {
return TypeNameMetaFieldDef;
}
if (isObjectType(parentType) || isInterfaceType(parentType)) {
return parentType.getFields()[name];
}
}
/**
* Creates a new visitor instance which maintains a provided TypeInfo instance
* along with visiting visitor.
*/
export function visitWithTypeInfo(typeInfo, visitor) {
return {
enter(...args) {
const node = args[0];
typeInfo.enter(node);
const fn = getEnterLeaveForKind(visitor, node.kind).enter;
if (fn) {
const result = fn.apply(visitor, args);
if (result !== undefined) {
typeInfo.leave(node);
if (isNode(result)) {
typeInfo.enter(result);
}
}
return result;
}
},
leave(...args) {
const node = args[0];
const fn = getEnterLeaveForKind(visitor, node.kind).leave;
let result;
if (fn) {
result = fn.apply(visitor, args);
}
typeInfo.leave(node);
return result;
},
};
}

View File

@@ -0,0 +1,13 @@
import { GraphQLError } from '../error/GraphQLError';
/**
* Upholds the spec rules about naming.
* @deprecated Please use `assertName` instead. Will be removed in v17
*/
export declare function assertValidName(name: string): string;
/**
* Returns an Error if a name is invalid.
* @deprecated Please use `assertName` instead. Will be removed in v17
*/
export declare function isValidNameError(
name: string,
): GraphQLError | undefined;

View File

@@ -0,0 +1,51 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.assertValidName = assertValidName;
exports.isValidNameError = isValidNameError;
var _devAssert = require('../jsutils/devAssert.js');
var _GraphQLError = require('../error/GraphQLError.js');
var _assertName = require('../type/assertName.js');
/* c8 ignore start */
/**
* Upholds the spec rules about naming.
* @deprecated Please use `assertName` instead. Will be removed in v17
*/
function assertValidName(name) {
const error = isValidNameError(name);
if (error) {
throw error;
}
return name;
}
/**
* Returns an Error if a name is invalid.
* @deprecated Please use `assertName` instead. Will be removed in v17
*/
function isValidNameError(name) {
typeof name === 'string' ||
(0, _devAssert.devAssert)(false, 'Expected name to be a string.');
if (name.startsWith('__')) {
return new _GraphQLError.GraphQLError(
`Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`,
);
}
try {
(0, _assertName.assertName)(name);
} catch (error) {
return error;
}
}
/* c8 ignore stop */

View File

@@ -0,0 +1,40 @@
import { devAssert } from '../jsutils/devAssert.mjs';
import { GraphQLError } from '../error/GraphQLError.mjs';
import { assertName } from '../type/assertName.mjs';
/* c8 ignore start */
/**
* Upholds the spec rules about naming.
* @deprecated Please use `assertName` instead. Will be removed in v17
*/
export function assertValidName(name) {
const error = isValidNameError(name);
if (error) {
throw error;
}
return name;
}
/**
* Returns an Error if a name is invalid.
* @deprecated Please use `assertName` instead. Will be removed in v17
*/
export function isValidNameError(name) {
typeof name === 'string' || devAssert(false, 'Expected name to be a string.');
if (name.startsWith('__')) {
return new GraphQLError(
`Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`,
);
}
try {
assertName(name);
} catch (error) {
return error;
}
}
/* c8 ignore stop */

View File

@@ -0,0 +1,28 @@
import type { Maybe } from '../jsutils/Maybe';
import type { ValueNode } from '../language/ast';
import type { GraphQLInputType } from '../type/definition';
/**
* Produces a GraphQL Value AST given a JavaScript object.
* Function will match JavaScript/JSON values to GraphQL AST schema format
* by using suggested GraphQLInputType. For example:
*
* astFromValue("value", GraphQLString)
*
* A GraphQL type must be provided, which will be used to interpret different
* JavaScript values.
*
* | JSON Value | GraphQL Value |
* | ------------- | -------------------- |
* | Object | Input Object |
* | Array | List |
* | Boolean | Boolean |
* | String | String / Enum Value |
* | Number | Int / Float |
* | Unknown | Enum Value |
* | null | NullValue |
*
*/
export declare function astFromValue(
value: unknown,
type: GraphQLInputType,
): Maybe<ValueNode>;

View File

@@ -0,0 +1,190 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.astFromValue = astFromValue;
var _inspect = require('../jsutils/inspect.js');
var _invariant = require('../jsutils/invariant.js');
var _isIterableObject = require('../jsutils/isIterableObject.js');
var _isObjectLike = require('../jsutils/isObjectLike.js');
var _kinds = require('../language/kinds.js');
var _definition = require('../type/definition.js');
var _scalars = require('../type/scalars.js');
/**
* Produces a GraphQL Value AST given a JavaScript object.
* Function will match JavaScript/JSON values to GraphQL AST schema format
* by using suggested GraphQLInputType. For example:
*
* astFromValue("value", GraphQLString)
*
* A GraphQL type must be provided, which will be used to interpret different
* JavaScript values.
*
* | JSON Value | GraphQL Value |
* | ------------- | -------------------- |
* | Object | Input Object |
* | Array | List |
* | Boolean | Boolean |
* | String | String / Enum Value |
* | Number | Int / Float |
* | Unknown | Enum Value |
* | null | NullValue |
*
*/
function astFromValue(value, type) {
if ((0, _definition.isNonNullType)(type)) {
const astValue = astFromValue(value, type.ofType);
if (
(astValue === null || astValue === void 0 ? void 0 : astValue.kind) ===
_kinds.Kind.NULL
) {
return null;
}
return astValue;
} // only explicit null, not undefined, NaN
if (value === null) {
return {
kind: _kinds.Kind.NULL,
};
} // undefined
if (value === undefined) {
return null;
} // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
// the value is not an array, convert the value using the list's item type.
if ((0, _definition.isListType)(type)) {
const itemType = type.ofType;
if ((0, _isIterableObject.isIterableObject)(value)) {
const valuesNodes = [];
for (const item of value) {
const itemNode = astFromValue(item, itemType);
if (itemNode != null) {
valuesNodes.push(itemNode);
}
}
return {
kind: _kinds.Kind.LIST,
values: valuesNodes,
};
}
return astFromValue(value, itemType);
} // Populate the fields of the input object by creating ASTs from each value
// in the JavaScript object according to the fields in the input type.
if ((0, _definition.isInputObjectType)(type)) {
if (!(0, _isObjectLike.isObjectLike)(value)) {
return null;
}
const fieldNodes = [];
for (const field of Object.values(type.getFields())) {
const fieldValue = astFromValue(value[field.name], field.type);
if (fieldValue) {
fieldNodes.push({
kind: _kinds.Kind.OBJECT_FIELD,
name: {
kind: _kinds.Kind.NAME,
value: field.name,
},
value: fieldValue,
});
}
}
return {
kind: _kinds.Kind.OBJECT,
fields: fieldNodes,
};
}
if ((0, _definition.isLeafType)(type)) {
// Since value is an internally represented value, it must be serialized
// to an externally represented value before converting into an AST.
const serialized = type.serialize(value);
if (serialized == null) {
return null;
} // Others serialize based on their corresponding JavaScript scalar types.
if (typeof serialized === 'boolean') {
return {
kind: _kinds.Kind.BOOLEAN,
value: serialized,
};
} // JavaScript numbers can be Int or Float values.
if (typeof serialized === 'number' && Number.isFinite(serialized)) {
const stringNum = String(serialized);
return integerStringRegExp.test(stringNum)
? {
kind: _kinds.Kind.INT,
value: stringNum,
}
: {
kind: _kinds.Kind.FLOAT,
value: stringNum,
};
}
if (typeof serialized === 'string') {
// Enum types use Enum literals.
if ((0, _definition.isEnumType)(type)) {
return {
kind: _kinds.Kind.ENUM,
value: serialized,
};
} // ID types can use Int literals.
if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) {
return {
kind: _kinds.Kind.INT,
value: serialized,
};
}
return {
kind: _kinds.Kind.STRING,
value: serialized,
};
}
throw new TypeError(
`Cannot convert value to AST: ${(0, _inspect.inspect)(serialized)}.`,
);
}
/* c8 ignore next 3 */
// Not reachable, all possible types have been considered.
false ||
(0, _invariant.invariant)(
false,
'Unexpected input type: ' + (0, _inspect.inspect)(type),
);
}
/**
* IntValue:
* - NegativeSign? 0
* - NegativeSign? NonZeroDigit ( Digit+ )?
*/
const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/;

View File

@@ -0,0 +1,177 @@
import { inspect } from '../jsutils/inspect.mjs';
import { invariant } from '../jsutils/invariant.mjs';
import { isIterableObject } from '../jsutils/isIterableObject.mjs';
import { isObjectLike } from '../jsutils/isObjectLike.mjs';
import { Kind } from '../language/kinds.mjs';
import {
isEnumType,
isInputObjectType,
isLeafType,
isListType,
isNonNullType,
} from '../type/definition.mjs';
import { GraphQLID } from '../type/scalars.mjs';
/**
* Produces a GraphQL Value AST given a JavaScript object.
* Function will match JavaScript/JSON values to GraphQL AST schema format
* by using suggested GraphQLInputType. For example:
*
* astFromValue("value", GraphQLString)
*
* A GraphQL type must be provided, which will be used to interpret different
* JavaScript values.
*
* | JSON Value | GraphQL Value |
* | ------------- | -------------------- |
* | Object | Input Object |
* | Array | List |
* | Boolean | Boolean |
* | String | String / Enum Value |
* | Number | Int / Float |
* | Unknown | Enum Value |
* | null | NullValue |
*
*/
export function astFromValue(value, type) {
if (isNonNullType(type)) {
const astValue = astFromValue(value, type.ofType);
if (
(astValue === null || astValue === void 0 ? void 0 : astValue.kind) ===
Kind.NULL
) {
return null;
}
return astValue;
} // only explicit null, not undefined, NaN
if (value === null) {
return {
kind: Kind.NULL,
};
} // undefined
if (value === undefined) {
return null;
} // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
// the value is not an array, convert the value using the list's item type.
if (isListType(type)) {
const itemType = type.ofType;
if (isIterableObject(value)) {
const valuesNodes = [];
for (const item of value) {
const itemNode = astFromValue(item, itemType);
if (itemNode != null) {
valuesNodes.push(itemNode);
}
}
return {
kind: Kind.LIST,
values: valuesNodes,
};
}
return astFromValue(value, itemType);
} // Populate the fields of the input object by creating ASTs from each value
// in the JavaScript object according to the fields in the input type.
if (isInputObjectType(type)) {
if (!isObjectLike(value)) {
return null;
}
const fieldNodes = [];
for (const field of Object.values(type.getFields())) {
const fieldValue = astFromValue(value[field.name], field.type);
if (fieldValue) {
fieldNodes.push({
kind: Kind.OBJECT_FIELD,
name: {
kind: Kind.NAME,
value: field.name,
},
value: fieldValue,
});
}
}
return {
kind: Kind.OBJECT,
fields: fieldNodes,
};
}
if (isLeafType(type)) {
// Since value is an internally represented value, it must be serialized
// to an externally represented value before converting into an AST.
const serialized = type.serialize(value);
if (serialized == null) {
return null;
} // Others serialize based on their corresponding JavaScript scalar types.
if (typeof serialized === 'boolean') {
return {
kind: Kind.BOOLEAN,
value: serialized,
};
} // JavaScript numbers can be Int or Float values.
if (typeof serialized === 'number' && Number.isFinite(serialized)) {
const stringNum = String(serialized);
return integerStringRegExp.test(stringNum)
? {
kind: Kind.INT,
value: stringNum,
}
: {
kind: Kind.FLOAT,
value: stringNum,
};
}
if (typeof serialized === 'string') {
// Enum types use Enum literals.
if (isEnumType(type)) {
return {
kind: Kind.ENUM,
value: serialized,
};
} // ID types can use Int literals.
if (type === GraphQLID && integerStringRegExp.test(serialized)) {
return {
kind: Kind.INT,
value: serialized,
};
}
return {
kind: Kind.STRING,
value: serialized,
};
}
throw new TypeError(`Cannot convert value to AST: ${inspect(serialized)}.`);
}
/* c8 ignore next 3 */
// Not reachable, all possible types have been considered.
false || invariant(false, 'Unexpected input type: ' + inspect(type));
}
/**
* IntValue:
* - NegativeSign? 0
* - NegativeSign? NonZeroDigit ( Digit+ )?
*/
const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/;

View File

@@ -0,0 +1,35 @@
import type { DocumentNode } from '../language/ast';
import type { ParseOptions } from '../language/parser';
import type { Source } from '../language/source';
import type { GraphQLSchemaValidationOptions } from '../type/schema';
import { GraphQLSchema } from '../type/schema';
export interface BuildSchemaOptions extends GraphQLSchemaValidationOptions {
/**
* Set to true to assume the SDL is valid.
*
* Default: false
*/
assumeValidSDL?: boolean;
}
/**
* This takes the ast of a schema document produced by the parse function in
* src/language/parser.js.
*
* If no schema definition is provided, then it will look for types named Query,
* Mutation and Subscription.
*
* Given that AST it constructs a GraphQLSchema. The resulting schema
* has no resolve methods, so execution will use default resolvers.
*/
export declare function buildASTSchema(
documentAST: DocumentNode,
options?: BuildSchemaOptions,
): GraphQLSchema;
/**
* A helper function to build a GraphQLSchema directly from a source
* document.
*/
export declare function buildSchema(
source: string | Source,
options?: BuildSchemaOptions & ParseOptions,
): GraphQLSchema;

View File

@@ -0,0 +1,115 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.buildASTSchema = buildASTSchema;
exports.buildSchema = buildSchema;
var _devAssert = require('../jsutils/devAssert.js');
var _kinds = require('../language/kinds.js');
var _parser = require('../language/parser.js');
var _directives = require('../type/directives.js');
var _schema = require('../type/schema.js');
var _validate = require('../validation/validate.js');
var _extendSchema = require('./extendSchema.js');
/**
* This takes the ast of a schema document produced by the parse function in
* src/language/parser.js.
*
* If no schema definition is provided, then it will look for types named Query,
* Mutation and Subscription.
*
* Given that AST it constructs a GraphQLSchema. The resulting schema
* has no resolve methods, so execution will use default resolvers.
*/
function buildASTSchema(documentAST, options) {
(documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT) ||
(0, _devAssert.devAssert)(false, 'Must provide valid Document AST.');
if (
(options === null || options === void 0 ? void 0 : options.assumeValid) !==
true &&
(options === null || options === void 0
? void 0
: options.assumeValidSDL) !== true
) {
(0, _validate.assertValidSDL)(documentAST);
}
const emptySchemaConfig = {
description: undefined,
types: [],
directives: [],
extensions: Object.create(null),
extensionASTNodes: [],
assumeValid: false,
};
const config = (0, _extendSchema.extendSchemaImpl)(
emptySchemaConfig,
documentAST,
options,
);
if (config.astNode == null) {
for (const type of config.types) {
switch (type.name) {
// Note: While this could make early assertions to get the correctly
// typed values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
case 'Query':
// @ts-expect-error validated in `validateSchema`
config.query = type;
break;
case 'Mutation':
// @ts-expect-error validated in `validateSchema`
config.mutation = type;
break;
case 'Subscription':
// @ts-expect-error validated in `validateSchema`
config.subscription = type;
break;
}
}
}
const directives = [
...config.directives, // If specified directives were not explicitly declared, add them.
..._directives.specifiedDirectives.filter((stdDirective) =>
config.directives.every(
(directive) => directive.name !== stdDirective.name,
),
),
];
return new _schema.GraphQLSchema({ ...config, directives });
}
/**
* A helper function to build a GraphQLSchema directly from a source
* document.
*/
function buildSchema(source, options) {
const document = (0, _parser.parse)(source, {
noLocation:
options === null || options === void 0 ? void 0 : options.noLocation,
allowLegacyFragmentVariables:
options === null || options === void 0
? void 0
: options.allowLegacyFragmentVariables,
});
return buildASTSchema(document, {
assumeValidSDL:
options === null || options === void 0 ? void 0 : options.assumeValidSDL,
assumeValid:
options === null || options === void 0 ? void 0 : options.assumeValid,
});
}

View File

@@ -0,0 +1,97 @@
import { devAssert } from '../jsutils/devAssert.mjs';
import { Kind } from '../language/kinds.mjs';
import { parse } from '../language/parser.mjs';
import { specifiedDirectives } from '../type/directives.mjs';
import { GraphQLSchema } from '../type/schema.mjs';
import { assertValidSDL } from '../validation/validate.mjs';
import { extendSchemaImpl } from './extendSchema.mjs';
/**
* This takes the ast of a schema document produced by the parse function in
* src/language/parser.js.
*
* If no schema definition is provided, then it will look for types named Query,
* Mutation and Subscription.
*
* Given that AST it constructs a GraphQLSchema. The resulting schema
* has no resolve methods, so execution will use default resolvers.
*/
export function buildASTSchema(documentAST, options) {
(documentAST != null && documentAST.kind === Kind.DOCUMENT) ||
devAssert(false, 'Must provide valid Document AST.');
if (
(options === null || options === void 0 ? void 0 : options.assumeValid) !==
true &&
(options === null || options === void 0
? void 0
: options.assumeValidSDL) !== true
) {
assertValidSDL(documentAST);
}
const emptySchemaConfig = {
description: undefined,
types: [],
directives: [],
extensions: Object.create(null),
extensionASTNodes: [],
assumeValid: false,
};
const config = extendSchemaImpl(emptySchemaConfig, documentAST, options);
if (config.astNode == null) {
for (const type of config.types) {
switch (type.name) {
// Note: While this could make early assertions to get the correctly
// typed values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
case 'Query':
// @ts-expect-error validated in `validateSchema`
config.query = type;
break;
case 'Mutation':
// @ts-expect-error validated in `validateSchema`
config.mutation = type;
break;
case 'Subscription':
// @ts-expect-error validated in `validateSchema`
config.subscription = type;
break;
}
}
}
const directives = [
...config.directives, // If specified directives were not explicitly declared, add them.
...specifiedDirectives.filter((stdDirective) =>
config.directives.every(
(directive) => directive.name !== stdDirective.name,
),
),
];
return new GraphQLSchema({ ...config, directives });
}
/**
* A helper function to build a GraphQLSchema directly from a source
* document.
*/
export function buildSchema(source, options) {
const document = parse(source, {
noLocation:
options === null || options === void 0 ? void 0 : options.noLocation,
allowLegacyFragmentVariables:
options === null || options === void 0
? void 0
: options.allowLegacyFragmentVariables,
});
return buildASTSchema(document, {
assumeValidSDL:
options === null || options === void 0 ? void 0 : options.assumeValidSDL,
assumeValid:
options === null || options === void 0 ? void 0 : options.assumeValid,
});
}

View File

@@ -0,0 +1,19 @@
import type { GraphQLSchemaValidationOptions } from '../type/schema';
import { GraphQLSchema } from '../type/schema';
import type { IntrospectionQuery } from './getIntrospectionQuery';
/**
* Build a GraphQLSchema for use by client tools.
*
* Given the result of a client running the introspection query, creates and
* returns a GraphQLSchema instance which can be then used with all graphql-js
* tools, but cannot be used to execute a query, as introspection does not
* represent the "resolver", "parse" or "serialize" functions or any other
* server-internal mechanisms.
*
* This function expects a complete introspection result. Don't forget to check
* the "errors" field of a server response before calling this function.
*/
export declare function buildClientSchema(
introspection: IntrospectionQuery,
options?: GraphQLSchemaValidationOptions,
): GraphQLSchema;

View File

@@ -0,0 +1,386 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.buildClientSchema = buildClientSchema;
var _devAssert = require('../jsutils/devAssert.js');
var _inspect = require('../jsutils/inspect.js');
var _isObjectLike = require('../jsutils/isObjectLike.js');
var _keyValMap = require('../jsutils/keyValMap.js');
var _parser = require('../language/parser.js');
var _definition = require('../type/definition.js');
var _directives = require('../type/directives.js');
var _introspection = require('../type/introspection.js');
var _scalars = require('../type/scalars.js');
var _schema = require('../type/schema.js');
var _valueFromAST = require('./valueFromAST.js');
/**
* Build a GraphQLSchema for use by client tools.
*
* Given the result of a client running the introspection query, creates and
* returns a GraphQLSchema instance which can be then used with all graphql-js
* tools, but cannot be used to execute a query, as introspection does not
* represent the "resolver", "parse" or "serialize" functions or any other
* server-internal mechanisms.
*
* This function expects a complete introspection result. Don't forget to check
* the "errors" field of a server response before calling this function.
*/
function buildClientSchema(introspection, options) {
((0, _isObjectLike.isObjectLike)(introspection) &&
(0, _isObjectLike.isObjectLike)(introspection.__schema)) ||
(0, _devAssert.devAssert)(
false,
`Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${(0,
_inspect.inspect)(introspection)}.`,
); // Get the schema from the introspection result.
const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each.
const typeMap = (0, _keyValMap.keyValMap)(
schemaIntrospection.types,
(typeIntrospection) => typeIntrospection.name,
(typeIntrospection) => buildType(typeIntrospection),
); // Include standard types only if they are used.
for (const stdType of [
..._scalars.specifiedScalarTypes,
..._introspection.introspectionTypes,
]) {
if (typeMap[stdType.name]) {
typeMap[stdType.name] = stdType;
}
} // Get the root Query, Mutation, and Subscription types.
const queryType = schemaIntrospection.queryType
? getObjectType(schemaIntrospection.queryType)
: null;
const mutationType = schemaIntrospection.mutationType
? getObjectType(schemaIntrospection.mutationType)
: null;
const subscriptionType = schemaIntrospection.subscriptionType
? getObjectType(schemaIntrospection.subscriptionType)
: null; // Get the directives supported by Introspection, assuming empty-set if
// directives were not queried for.
const directives = schemaIntrospection.directives
? schemaIntrospection.directives.map(buildDirective)
: []; // Then produce and return a Schema with these types.
return new _schema.GraphQLSchema({
description: schemaIntrospection.description,
query: queryType,
mutation: mutationType,
subscription: subscriptionType,
types: Object.values(typeMap),
directives,
assumeValid:
options === null || options === void 0 ? void 0 : options.assumeValid,
}); // Given a type reference in introspection, return the GraphQLType instance.
// preferring cached instances before building new instances.
function getType(typeRef) {
if (typeRef.kind === _introspection.TypeKind.LIST) {
const itemRef = typeRef.ofType;
if (!itemRef) {
throw new Error('Decorated type deeper than introspection query.');
}
return new _definition.GraphQLList(getType(itemRef));
}
if (typeRef.kind === _introspection.TypeKind.NON_NULL) {
const nullableRef = typeRef.ofType;
if (!nullableRef) {
throw new Error('Decorated type deeper than introspection query.');
}
const nullableType = getType(nullableRef);
return new _definition.GraphQLNonNull(
(0, _definition.assertNullableType)(nullableType),
);
}
return getNamedType(typeRef);
}
function getNamedType(typeRef) {
const typeName = typeRef.name;
if (!typeName) {
throw new Error(
`Unknown type reference: ${(0, _inspect.inspect)(typeRef)}.`,
);
}
const type = typeMap[typeName];
if (!type) {
throw new Error(
`Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`,
);
}
return type;
}
function getObjectType(typeRef) {
return (0, _definition.assertObjectType)(getNamedType(typeRef));
}
function getInterfaceType(typeRef) {
return (0, _definition.assertInterfaceType)(getNamedType(typeRef));
} // Given a type's introspection result, construct the correct
// GraphQLType instance.
function buildType(type) {
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain
if (type != null && type.name != null && type.kind != null) {
// FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
switch (type.kind) {
case _introspection.TypeKind.SCALAR:
return buildScalarDef(type);
case _introspection.TypeKind.OBJECT:
return buildObjectDef(type);
case _introspection.TypeKind.INTERFACE:
return buildInterfaceDef(type);
case _introspection.TypeKind.UNION:
return buildUnionDef(type);
case _introspection.TypeKind.ENUM:
return buildEnumDef(type);
case _introspection.TypeKind.INPUT_OBJECT:
return buildInputObjectDef(type);
}
}
const typeStr = (0, _inspect.inspect)(type);
throw new Error(
`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`,
);
}
function buildScalarDef(scalarIntrospection) {
return new _definition.GraphQLScalarType({
name: scalarIntrospection.name,
description: scalarIntrospection.description,
specifiedByURL: scalarIntrospection.specifiedByURL,
});
}
function buildImplementationsList(implementingIntrospection) {
// TODO: Temporary workaround until GraphQL ecosystem will fully support
// 'interfaces' on interface types.
if (
implementingIntrospection.interfaces === null &&
implementingIntrospection.kind === _introspection.TypeKind.INTERFACE
) {
return [];
}
if (!implementingIntrospection.interfaces) {
const implementingIntrospectionStr = (0, _inspect.inspect)(
implementingIntrospection,
);
throw new Error(
`Introspection result missing interfaces: ${implementingIntrospectionStr}.`,
);
}
return implementingIntrospection.interfaces.map(getInterfaceType);
}
function buildObjectDef(objectIntrospection) {
return new _definition.GraphQLObjectType({
name: objectIntrospection.name,
description: objectIntrospection.description,
interfaces: () => buildImplementationsList(objectIntrospection),
fields: () => buildFieldDefMap(objectIntrospection),
});
}
function buildInterfaceDef(interfaceIntrospection) {
return new _definition.GraphQLInterfaceType({
name: interfaceIntrospection.name,
description: interfaceIntrospection.description,
interfaces: () => buildImplementationsList(interfaceIntrospection),
fields: () => buildFieldDefMap(interfaceIntrospection),
});
}
function buildUnionDef(unionIntrospection) {
if (!unionIntrospection.possibleTypes) {
const unionIntrospectionStr = (0, _inspect.inspect)(unionIntrospection);
throw new Error(
`Introspection result missing possibleTypes: ${unionIntrospectionStr}.`,
);
}
return new _definition.GraphQLUnionType({
name: unionIntrospection.name,
description: unionIntrospection.description,
types: () => unionIntrospection.possibleTypes.map(getObjectType),
});
}
function buildEnumDef(enumIntrospection) {
if (!enumIntrospection.enumValues) {
const enumIntrospectionStr = (0, _inspect.inspect)(enumIntrospection);
throw new Error(
`Introspection result missing enumValues: ${enumIntrospectionStr}.`,
);
}
return new _definition.GraphQLEnumType({
name: enumIntrospection.name,
description: enumIntrospection.description,
values: (0, _keyValMap.keyValMap)(
enumIntrospection.enumValues,
(valueIntrospection) => valueIntrospection.name,
(valueIntrospection) => ({
description: valueIntrospection.description,
deprecationReason: valueIntrospection.deprecationReason,
}),
),
});
}
function buildInputObjectDef(inputObjectIntrospection) {
if (!inputObjectIntrospection.inputFields) {
const inputObjectIntrospectionStr = (0, _inspect.inspect)(
inputObjectIntrospection,
);
throw new Error(
`Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`,
);
}
return new _definition.GraphQLInputObjectType({
name: inputObjectIntrospection.name,
description: inputObjectIntrospection.description,
fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields),
});
}
function buildFieldDefMap(typeIntrospection) {
if (!typeIntrospection.fields) {
throw new Error(
`Introspection result missing fields: ${(0, _inspect.inspect)(
typeIntrospection,
)}.`,
);
}
return (0, _keyValMap.keyValMap)(
typeIntrospection.fields,
(fieldIntrospection) => fieldIntrospection.name,
buildField,
);
}
function buildField(fieldIntrospection) {
const type = getType(fieldIntrospection.type);
if (!(0, _definition.isOutputType)(type)) {
const typeStr = (0, _inspect.inspect)(type);
throw new Error(
`Introspection must provide output type for fields, but received: ${typeStr}.`,
);
}
if (!fieldIntrospection.args) {
const fieldIntrospectionStr = (0, _inspect.inspect)(fieldIntrospection);
throw new Error(
`Introspection result missing field args: ${fieldIntrospectionStr}.`,
);
}
return {
description: fieldIntrospection.description,
deprecationReason: fieldIntrospection.deprecationReason,
type,
args: buildInputValueDefMap(fieldIntrospection.args),
};
}
function buildInputValueDefMap(inputValueIntrospections) {
return (0, _keyValMap.keyValMap)(
inputValueIntrospections,
(inputValue) => inputValue.name,
buildInputValue,
);
}
function buildInputValue(inputValueIntrospection) {
const type = getType(inputValueIntrospection.type);
if (!(0, _definition.isInputType)(type)) {
const typeStr = (0, _inspect.inspect)(type);
throw new Error(
`Introspection must provide input type for arguments, but received: ${typeStr}.`,
);
}
const defaultValue =
inputValueIntrospection.defaultValue != null
? (0, _valueFromAST.valueFromAST)(
(0, _parser.parseValue)(inputValueIntrospection.defaultValue),
type,
)
: undefined;
return {
description: inputValueIntrospection.description,
type,
defaultValue,
deprecationReason: inputValueIntrospection.deprecationReason,
};
}
function buildDirective(directiveIntrospection) {
if (!directiveIntrospection.args) {
const directiveIntrospectionStr = (0, _inspect.inspect)(
directiveIntrospection,
);
throw new Error(
`Introspection result missing directive args: ${directiveIntrospectionStr}.`,
);
}
if (!directiveIntrospection.locations) {
const directiveIntrospectionStr = (0, _inspect.inspect)(
directiveIntrospection,
);
throw new Error(
`Introspection result missing directive locations: ${directiveIntrospectionStr}.`,
);
}
return new _directives.GraphQLDirective({
name: directiveIntrospection.name,
description: directiveIntrospection.description,
isRepeatable: directiveIntrospection.isRepeatable,
locations: directiveIntrospection.locations.slice(),
args: buildInputValueDefMap(directiveIntrospection.args),
});
}
}

View File

@@ -0,0 +1,363 @@
import { devAssert } from '../jsutils/devAssert.mjs';
import { inspect } from '../jsutils/inspect.mjs';
import { isObjectLike } from '../jsutils/isObjectLike.mjs';
import { keyValMap } from '../jsutils/keyValMap.mjs';
import { parseValue } from '../language/parser.mjs';
import {
assertInterfaceType,
assertNullableType,
assertObjectType,
GraphQLEnumType,
GraphQLInputObjectType,
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLScalarType,
GraphQLUnionType,
isInputType,
isOutputType,
} from '../type/definition.mjs';
import { GraphQLDirective } from '../type/directives.mjs';
import { introspectionTypes, TypeKind } from '../type/introspection.mjs';
import { specifiedScalarTypes } from '../type/scalars.mjs';
import { GraphQLSchema } from '../type/schema.mjs';
import { valueFromAST } from './valueFromAST.mjs';
/**
* Build a GraphQLSchema for use by client tools.
*
* Given the result of a client running the introspection query, creates and
* returns a GraphQLSchema instance which can be then used with all graphql-js
* tools, but cannot be used to execute a query, as introspection does not
* represent the "resolver", "parse" or "serialize" functions or any other
* server-internal mechanisms.
*
* This function expects a complete introspection result. Don't forget to check
* the "errors" field of a server response before calling this function.
*/
export function buildClientSchema(introspection, options) {
(isObjectLike(introspection) && isObjectLike(introspection.__schema)) ||
devAssert(
false,
`Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${inspect(
introspection,
)}.`,
); // Get the schema from the introspection result.
const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each.
const typeMap = keyValMap(
schemaIntrospection.types,
(typeIntrospection) => typeIntrospection.name,
(typeIntrospection) => buildType(typeIntrospection),
); // Include standard types only if they are used.
for (const stdType of [...specifiedScalarTypes, ...introspectionTypes]) {
if (typeMap[stdType.name]) {
typeMap[stdType.name] = stdType;
}
} // Get the root Query, Mutation, and Subscription types.
const queryType = schemaIntrospection.queryType
? getObjectType(schemaIntrospection.queryType)
: null;
const mutationType = schemaIntrospection.mutationType
? getObjectType(schemaIntrospection.mutationType)
: null;
const subscriptionType = schemaIntrospection.subscriptionType
? getObjectType(schemaIntrospection.subscriptionType)
: null; // Get the directives supported by Introspection, assuming empty-set if
// directives were not queried for.
const directives = schemaIntrospection.directives
? schemaIntrospection.directives.map(buildDirective)
: []; // Then produce and return a Schema with these types.
return new GraphQLSchema({
description: schemaIntrospection.description,
query: queryType,
mutation: mutationType,
subscription: subscriptionType,
types: Object.values(typeMap),
directives,
assumeValid:
options === null || options === void 0 ? void 0 : options.assumeValid,
}); // Given a type reference in introspection, return the GraphQLType instance.
// preferring cached instances before building new instances.
function getType(typeRef) {
if (typeRef.kind === TypeKind.LIST) {
const itemRef = typeRef.ofType;
if (!itemRef) {
throw new Error('Decorated type deeper than introspection query.');
}
return new GraphQLList(getType(itemRef));
}
if (typeRef.kind === TypeKind.NON_NULL) {
const nullableRef = typeRef.ofType;
if (!nullableRef) {
throw new Error('Decorated type deeper than introspection query.');
}
const nullableType = getType(nullableRef);
return new GraphQLNonNull(assertNullableType(nullableType));
}
return getNamedType(typeRef);
}
function getNamedType(typeRef) {
const typeName = typeRef.name;
if (!typeName) {
throw new Error(`Unknown type reference: ${inspect(typeRef)}.`);
}
const type = typeMap[typeName];
if (!type) {
throw new Error(
`Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`,
);
}
return type;
}
function getObjectType(typeRef) {
return assertObjectType(getNamedType(typeRef));
}
function getInterfaceType(typeRef) {
return assertInterfaceType(getNamedType(typeRef));
} // Given a type's introspection result, construct the correct
// GraphQLType instance.
function buildType(type) {
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain
if (type != null && type.name != null && type.kind != null) {
// FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
switch (type.kind) {
case TypeKind.SCALAR:
return buildScalarDef(type);
case TypeKind.OBJECT:
return buildObjectDef(type);
case TypeKind.INTERFACE:
return buildInterfaceDef(type);
case TypeKind.UNION:
return buildUnionDef(type);
case TypeKind.ENUM:
return buildEnumDef(type);
case TypeKind.INPUT_OBJECT:
return buildInputObjectDef(type);
}
}
const typeStr = inspect(type);
throw new Error(
`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`,
);
}
function buildScalarDef(scalarIntrospection) {
return new GraphQLScalarType({
name: scalarIntrospection.name,
description: scalarIntrospection.description,
specifiedByURL: scalarIntrospection.specifiedByURL,
});
}
function buildImplementationsList(implementingIntrospection) {
// TODO: Temporary workaround until GraphQL ecosystem will fully support
// 'interfaces' on interface types.
if (
implementingIntrospection.interfaces === null &&
implementingIntrospection.kind === TypeKind.INTERFACE
) {
return [];
}
if (!implementingIntrospection.interfaces) {
const implementingIntrospectionStr = inspect(implementingIntrospection);
throw new Error(
`Introspection result missing interfaces: ${implementingIntrospectionStr}.`,
);
}
return implementingIntrospection.interfaces.map(getInterfaceType);
}
function buildObjectDef(objectIntrospection) {
return new GraphQLObjectType({
name: objectIntrospection.name,
description: objectIntrospection.description,
interfaces: () => buildImplementationsList(objectIntrospection),
fields: () => buildFieldDefMap(objectIntrospection),
});
}
function buildInterfaceDef(interfaceIntrospection) {
return new GraphQLInterfaceType({
name: interfaceIntrospection.name,
description: interfaceIntrospection.description,
interfaces: () => buildImplementationsList(interfaceIntrospection),
fields: () => buildFieldDefMap(interfaceIntrospection),
});
}
function buildUnionDef(unionIntrospection) {
if (!unionIntrospection.possibleTypes) {
const unionIntrospectionStr = inspect(unionIntrospection);
throw new Error(
`Introspection result missing possibleTypes: ${unionIntrospectionStr}.`,
);
}
return new GraphQLUnionType({
name: unionIntrospection.name,
description: unionIntrospection.description,
types: () => unionIntrospection.possibleTypes.map(getObjectType),
});
}
function buildEnumDef(enumIntrospection) {
if (!enumIntrospection.enumValues) {
const enumIntrospectionStr = inspect(enumIntrospection);
throw new Error(
`Introspection result missing enumValues: ${enumIntrospectionStr}.`,
);
}
return new GraphQLEnumType({
name: enumIntrospection.name,
description: enumIntrospection.description,
values: keyValMap(
enumIntrospection.enumValues,
(valueIntrospection) => valueIntrospection.name,
(valueIntrospection) => ({
description: valueIntrospection.description,
deprecationReason: valueIntrospection.deprecationReason,
}),
),
});
}
function buildInputObjectDef(inputObjectIntrospection) {
if (!inputObjectIntrospection.inputFields) {
const inputObjectIntrospectionStr = inspect(inputObjectIntrospection);
throw new Error(
`Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`,
);
}
return new GraphQLInputObjectType({
name: inputObjectIntrospection.name,
description: inputObjectIntrospection.description,
fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields),
});
}
function buildFieldDefMap(typeIntrospection) {
if (!typeIntrospection.fields) {
throw new Error(
`Introspection result missing fields: ${inspect(typeIntrospection)}.`,
);
}
return keyValMap(
typeIntrospection.fields,
(fieldIntrospection) => fieldIntrospection.name,
buildField,
);
}
function buildField(fieldIntrospection) {
const type = getType(fieldIntrospection.type);
if (!isOutputType(type)) {
const typeStr = inspect(type);
throw new Error(
`Introspection must provide output type for fields, but received: ${typeStr}.`,
);
}
if (!fieldIntrospection.args) {
const fieldIntrospectionStr = inspect(fieldIntrospection);
throw new Error(
`Introspection result missing field args: ${fieldIntrospectionStr}.`,
);
}
return {
description: fieldIntrospection.description,
deprecationReason: fieldIntrospection.deprecationReason,
type,
args: buildInputValueDefMap(fieldIntrospection.args),
};
}
function buildInputValueDefMap(inputValueIntrospections) {
return keyValMap(
inputValueIntrospections,
(inputValue) => inputValue.name,
buildInputValue,
);
}
function buildInputValue(inputValueIntrospection) {
const type = getType(inputValueIntrospection.type);
if (!isInputType(type)) {
const typeStr = inspect(type);
throw new Error(
`Introspection must provide input type for arguments, but received: ${typeStr}.`,
);
}
const defaultValue =
inputValueIntrospection.defaultValue != null
? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type)
: undefined;
return {
description: inputValueIntrospection.description,
type,
defaultValue,
deprecationReason: inputValueIntrospection.deprecationReason,
};
}
function buildDirective(directiveIntrospection) {
if (!directiveIntrospection.args) {
const directiveIntrospectionStr = inspect(directiveIntrospection);
throw new Error(
`Introspection result missing directive args: ${directiveIntrospectionStr}.`,
);
}
if (!directiveIntrospection.locations) {
const directiveIntrospectionStr = inspect(directiveIntrospection);
throw new Error(
`Introspection result missing directive locations: ${directiveIntrospectionStr}.`,
);
}
return new GraphQLDirective({
name: directiveIntrospection.name,
description: directiveIntrospection.description,
isRepeatable: directiveIntrospection.isRepeatable,
locations: directiveIntrospection.locations.slice(),
args: buildInputValueDefMap(directiveIntrospection.args),
});
}
}

View File

@@ -0,0 +1,16 @@
import { GraphQLError } from '../error/GraphQLError';
import type { GraphQLInputType } from '../type/definition';
declare type OnErrorCB = (
path: ReadonlyArray<string | number>,
invalidValue: unknown,
error: GraphQLError,
) => void;
/**
* Coerces a JavaScript value given a GraphQL Input Type.
*/
export declare function coerceInputValue(
inputValue: unknown,
type: GraphQLInputType,
onError?: OnErrorCB,
): unknown;
export {};

View File

@@ -0,0 +1,189 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.coerceInputValue = coerceInputValue;
var _didYouMean = require('../jsutils/didYouMean.js');
var _inspect = require('../jsutils/inspect.js');
var _invariant = require('../jsutils/invariant.js');
var _isIterableObject = require('../jsutils/isIterableObject.js');
var _isObjectLike = require('../jsutils/isObjectLike.js');
var _Path = require('../jsutils/Path.js');
var _printPathArray = require('../jsutils/printPathArray.js');
var _suggestionList = require('../jsutils/suggestionList.js');
var _GraphQLError = require('../error/GraphQLError.js');
var _definition = require('../type/definition.js');
/**
* Coerces a JavaScript value given a GraphQL Input Type.
*/
function coerceInputValue(inputValue, type, onError = defaultOnError) {
return coerceInputValueImpl(inputValue, type, onError, undefined);
}
function defaultOnError(path, invalidValue, error) {
let errorPrefix = 'Invalid value ' + (0, _inspect.inspect)(invalidValue);
if (path.length > 0) {
errorPrefix += ` at "value${(0, _printPathArray.printPathArray)(path)}"`;
}
error.message = errorPrefix + ': ' + error.message;
throw error;
}
function coerceInputValueImpl(inputValue, type, onError, path) {
if ((0, _definition.isNonNullType)(type)) {
if (inputValue != null) {
return coerceInputValueImpl(inputValue, type.ofType, onError, path);
}
onError(
(0, _Path.pathToArray)(path),
inputValue,
new _GraphQLError.GraphQLError(
`Expected non-nullable type "${(0, _inspect.inspect)(
type,
)}" not to be null.`,
),
);
return;
}
if (inputValue == null) {
// Explicitly return the value null.
return null;
}
if ((0, _definition.isListType)(type)) {
const itemType = type.ofType;
if ((0, _isIterableObject.isIterableObject)(inputValue)) {
return Array.from(inputValue, (itemValue, index) => {
const itemPath = (0, _Path.addPath)(path, index, undefined);
return coerceInputValueImpl(itemValue, itemType, onError, itemPath);
});
} // Lists accept a non-list value as a list of one.
return [coerceInputValueImpl(inputValue, itemType, onError, path)];
}
if ((0, _definition.isInputObjectType)(type)) {
if (!(0, _isObjectLike.isObjectLike)(inputValue)) {
onError(
(0, _Path.pathToArray)(path),
inputValue,
new _GraphQLError.GraphQLError(
`Expected type "${type.name}" to be an object.`,
),
);
return;
}
const coercedValue = {};
const fieldDefs = type.getFields();
for (const field of Object.values(fieldDefs)) {
const fieldValue = inputValue[field.name];
if (fieldValue === undefined) {
if (field.defaultValue !== undefined) {
coercedValue[field.name] = field.defaultValue;
} else if ((0, _definition.isNonNullType)(field.type)) {
const typeStr = (0, _inspect.inspect)(field.type);
onError(
(0, _Path.pathToArray)(path),
inputValue,
new _GraphQLError.GraphQLError(
`Field "${field.name}" of required type "${typeStr}" was not provided.`,
),
);
}
continue;
}
coercedValue[field.name] = coerceInputValueImpl(
fieldValue,
field.type,
onError,
(0, _Path.addPath)(path, field.name, type.name),
);
} // Ensure every provided field is defined.
for (const fieldName of Object.keys(inputValue)) {
if (!fieldDefs[fieldName]) {
const suggestions = (0, _suggestionList.suggestionList)(
fieldName,
Object.keys(type.getFields()),
);
onError(
(0, _Path.pathToArray)(path),
inputValue,
new _GraphQLError.GraphQLError(
`Field "${fieldName}" is not defined by type "${type.name}".` +
(0, _didYouMean.didYouMean)(suggestions),
),
);
}
}
return coercedValue;
}
if ((0, _definition.isLeafType)(type)) {
let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(),
// which can throw to indicate failure. If it throws, maintain a reference
// to the original error.
try {
parseResult = type.parseValue(inputValue);
} catch (error) {
if (error instanceof _GraphQLError.GraphQLError) {
onError((0, _Path.pathToArray)(path), inputValue, error);
} else {
onError(
(0, _Path.pathToArray)(path),
inputValue,
new _GraphQLError.GraphQLError(
`Expected type "${type.name}". ` + error.message,
{
originalError: error,
},
),
);
}
return;
}
if (parseResult === undefined) {
onError(
(0, _Path.pathToArray)(path),
inputValue,
new _GraphQLError.GraphQLError(`Expected type "${type.name}".`),
);
}
return parseResult;
}
/* c8 ignore next 3 */
// Not reachable, all possible types have been considered.
false ||
(0, _invariant.invariant)(
false,
'Unexpected input type: ' + (0, _inspect.inspect)(type),
);
}

View File

@@ -0,0 +1,167 @@
import { didYouMean } from '../jsutils/didYouMean.mjs';
import { inspect } from '../jsutils/inspect.mjs';
import { invariant } from '../jsutils/invariant.mjs';
import { isIterableObject } from '../jsutils/isIterableObject.mjs';
import { isObjectLike } from '../jsutils/isObjectLike.mjs';
import { addPath, pathToArray } from '../jsutils/Path.mjs';
import { printPathArray } from '../jsutils/printPathArray.mjs';
import { suggestionList } from '../jsutils/suggestionList.mjs';
import { GraphQLError } from '../error/GraphQLError.mjs';
import {
isInputObjectType,
isLeafType,
isListType,
isNonNullType,
} from '../type/definition.mjs';
/**
* Coerces a JavaScript value given a GraphQL Input Type.
*/
export function coerceInputValue(inputValue, type, onError = defaultOnError) {
return coerceInputValueImpl(inputValue, type, onError, undefined);
}
function defaultOnError(path, invalidValue, error) {
let errorPrefix = 'Invalid value ' + inspect(invalidValue);
if (path.length > 0) {
errorPrefix += ` at "value${printPathArray(path)}"`;
}
error.message = errorPrefix + ': ' + error.message;
throw error;
}
function coerceInputValueImpl(inputValue, type, onError, path) {
if (isNonNullType(type)) {
if (inputValue != null) {
return coerceInputValueImpl(inputValue, type.ofType, onError, path);
}
onError(
pathToArray(path),
inputValue,
new GraphQLError(
`Expected non-nullable type "${inspect(type)}" not to be null.`,
),
);
return;
}
if (inputValue == null) {
// Explicitly return the value null.
return null;
}
if (isListType(type)) {
const itemType = type.ofType;
if (isIterableObject(inputValue)) {
return Array.from(inputValue, (itemValue, index) => {
const itemPath = addPath(path, index, undefined);
return coerceInputValueImpl(itemValue, itemType, onError, itemPath);
});
} // Lists accept a non-list value as a list of one.
return [coerceInputValueImpl(inputValue, itemType, onError, path)];
}
if (isInputObjectType(type)) {
if (!isObjectLike(inputValue)) {
onError(
pathToArray(path),
inputValue,
new GraphQLError(`Expected type "${type.name}" to be an object.`),
);
return;
}
const coercedValue = {};
const fieldDefs = type.getFields();
for (const field of Object.values(fieldDefs)) {
const fieldValue = inputValue[field.name];
if (fieldValue === undefined) {
if (field.defaultValue !== undefined) {
coercedValue[field.name] = field.defaultValue;
} else if (isNonNullType(field.type)) {
const typeStr = inspect(field.type);
onError(
pathToArray(path),
inputValue,
new GraphQLError(
`Field "${field.name}" of required type "${typeStr}" was not provided.`,
),
);
}
continue;
}
coercedValue[field.name] = coerceInputValueImpl(
fieldValue,
field.type,
onError,
addPath(path, field.name, type.name),
);
} // Ensure every provided field is defined.
for (const fieldName of Object.keys(inputValue)) {
if (!fieldDefs[fieldName]) {
const suggestions = suggestionList(
fieldName,
Object.keys(type.getFields()),
);
onError(
pathToArray(path),
inputValue,
new GraphQLError(
`Field "${fieldName}" is not defined by type "${type.name}".` +
didYouMean(suggestions),
),
);
}
}
return coercedValue;
}
if (isLeafType(type)) {
let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(),
// which can throw to indicate failure. If it throws, maintain a reference
// to the original error.
try {
parseResult = type.parseValue(inputValue);
} catch (error) {
if (error instanceof GraphQLError) {
onError(pathToArray(path), inputValue, error);
} else {
onError(
pathToArray(path),
inputValue,
new GraphQLError(`Expected type "${type.name}". ` + error.message, {
originalError: error,
}),
);
}
return;
}
if (parseResult === undefined) {
onError(
pathToArray(path),
inputValue,
new GraphQLError(`Expected type "${type.name}".`),
);
}
return parseResult;
}
/* c8 ignore next 3 */
// Not reachable, all possible types have been considered.
false || invariant(false, 'Unexpected input type: ' + inspect(type));
}

View File

@@ -0,0 +1,9 @@
import type { DocumentNode } from '../language/ast';
/**
* Provided a collection of ASTs, presumably each from different files,
* concatenate the ASTs together into batched AST, useful for validating many
* GraphQL source files which together represent one conceptual application.
*/
export declare function concatAST(
documents: ReadonlyArray<DocumentNode>,
): DocumentNode;

View File

@@ -0,0 +1,26 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.concatAST = concatAST;
var _kinds = require('../language/kinds.js');
/**
* Provided a collection of ASTs, presumably each from different files,
* concatenate the ASTs together into batched AST, useful for validating many
* GraphQL source files which together represent one conceptual application.
*/
function concatAST(documents) {
const definitions = [];
for (const doc of documents) {
definitions.push(...doc.definitions);
}
return {
kind: _kinds.Kind.DOCUMENT,
definitions,
};
}

View File

@@ -0,0 +1,19 @@
import { Kind } from '../language/kinds.mjs';
/**
* Provided a collection of ASTs, presumably each from different files,
* concatenate the ASTs together into batched AST, useful for validating many
* GraphQL source files which together represent one conceptual application.
*/
export function concatAST(documents) {
const definitions = [];
for (const doc of documents) {
definitions.push(...doc.definitions);
}
return {
kind: Kind.DOCUMENT,
definitions,
};
}

View File

@@ -0,0 +1,40 @@
import type { DocumentNode } from '../language/ast';
import type {
GraphQLSchemaNormalizedConfig,
GraphQLSchemaValidationOptions,
} from '../type/schema';
import { GraphQLSchema } from '../type/schema';
interface Options extends GraphQLSchemaValidationOptions {
/**
* Set to true to assume the SDL is valid.
*
* Default: false
*/
assumeValidSDL?: boolean;
}
/**
* Produces a new schema given an existing schema and a document which may
* contain GraphQL type extensions and definitions. The original schema will
* remain unaltered.
*
* Because a schema represents a graph of references, a schema cannot be
* extended without effectively making an entire copy. We do not know until it's
* too late if subgraphs remain unchanged.
*
* This algorithm copies the provided schema, applying extensions while
* producing the copy. The original schema remains unaltered.
*/
export declare function extendSchema(
schema: GraphQLSchema,
documentAST: DocumentNode,
options?: Options,
): GraphQLSchema;
/**
* @internal
*/
export declare function extendSchemaImpl(
schemaConfig: GraphQLSchemaNormalizedConfig,
documentAST: DocumentNode,
options?: Options,
): GraphQLSchemaNormalizedConfig;
export {};

View File

@@ -0,0 +1,798 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.extendSchema = extendSchema;
exports.extendSchemaImpl = extendSchemaImpl;
var _devAssert = require('../jsutils/devAssert.js');
var _inspect = require('../jsutils/inspect.js');
var _invariant = require('../jsutils/invariant.js');
var _keyMap = require('../jsutils/keyMap.js');
var _mapValue = require('../jsutils/mapValue.js');
var _kinds = require('../language/kinds.js');
var _predicates = require('../language/predicates.js');
var _definition = require('../type/definition.js');
var _directives = require('../type/directives.js');
var _introspection = require('../type/introspection.js');
var _scalars = require('../type/scalars.js');
var _schema = require('../type/schema.js');
var _validate = require('../validation/validate.js');
var _values = require('../execution/values.js');
var _valueFromAST = require('./valueFromAST.js');
/**
* Produces a new schema given an existing schema and a document which may
* contain GraphQL type extensions and definitions. The original schema will
* remain unaltered.
*
* Because a schema represents a graph of references, a schema cannot be
* extended without effectively making an entire copy. We do not know until it's
* too late if subgraphs remain unchanged.
*
* This algorithm copies the provided schema, applying extensions while
* producing the copy. The original schema remains unaltered.
*/
function extendSchema(schema, documentAST, options) {
(0, _schema.assertSchema)(schema);
(documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT) ||
(0, _devAssert.devAssert)(false, 'Must provide valid Document AST.');
if (
(options === null || options === void 0 ? void 0 : options.assumeValid) !==
true &&
(options === null || options === void 0
? void 0
: options.assumeValidSDL) !== true
) {
(0, _validate.assertValidSDLExtension)(documentAST, schema);
}
const schemaConfig = schema.toConfig();
const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options);
return schemaConfig === extendedConfig
? schema
: new _schema.GraphQLSchema(extendedConfig);
}
/**
* @internal
*/
function extendSchemaImpl(schemaConfig, documentAST, options) {
var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid;
// Collect the type definitions and extensions found in the document.
const typeDefs = [];
const typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can
// have the same name. For example, a type named "skip".
const directiveDefs = [];
let schemaDef; // Schema extensions are collected which may add additional operation types.
const schemaExtensions = [];
for (const def of documentAST.definitions) {
if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) {
schemaDef = def;
} else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) {
schemaExtensions.push(def);
} else if ((0, _predicates.isTypeDefinitionNode)(def)) {
typeDefs.push(def);
} else if ((0, _predicates.isTypeExtensionNode)(def)) {
const extendedTypeName = def.name.value;
const existingTypeExtensions = typeExtensionsMap[extendedTypeName];
typeExtensionsMap[extendedTypeName] = existingTypeExtensions
? existingTypeExtensions.concat([def])
: [def];
} else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
directiveDefs.push(def);
}
} // If this document contains no new types, extensions, or directives then
// return the same unmodified GraphQLSchema instance.
if (
Object.keys(typeExtensionsMap).length === 0 &&
typeDefs.length === 0 &&
directiveDefs.length === 0 &&
schemaExtensions.length === 0 &&
schemaDef == null
) {
return schemaConfig;
}
const typeMap = Object.create(null);
for (const existingType of schemaConfig.types) {
typeMap[existingType.name] = extendNamedType(existingType);
}
for (const typeNode of typeDefs) {
var _stdTypeMap$name;
const name = typeNode.name.value;
typeMap[name] =
(_stdTypeMap$name = stdTypeMap[name]) !== null &&
_stdTypeMap$name !== void 0
? _stdTypeMap$name
: buildType(typeNode);
}
const operationTypes = {
// Get the extended root operation types.
query: schemaConfig.query && replaceNamedType(schemaConfig.query),
mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation),
subscription:
schemaConfig.subscription && replaceNamedType(schemaConfig.subscription),
// Then, incorporate schema definition and all schema extensions.
...(schemaDef && getOperationTypes([schemaDef])),
...getOperationTypes(schemaExtensions),
}; // Then produce and return a Schema config with these types.
return {
description:
(_schemaDef = schemaDef) === null || _schemaDef === void 0
? void 0
: (_schemaDef$descriptio = _schemaDef.description) === null ||
_schemaDef$descriptio === void 0
? void 0
: _schemaDef$descriptio.value,
...operationTypes,
types: Object.values(typeMap),
directives: [
...schemaConfig.directives.map(replaceDirective),
...directiveDefs.map(buildDirective),
],
extensions: Object.create(null),
astNode:
(_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0
? _schemaDef2
: schemaConfig.astNode,
extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions),
assumeValid:
(_options$assumeValid =
options === null || options === void 0
? void 0
: options.assumeValid) !== null && _options$assumeValid !== void 0
? _options$assumeValid
: false,
}; // Below are functions used for producing this schema that have closed over
// this scope and have access to the schema, cache, and newly defined types.
function replaceType(type) {
if ((0, _definition.isListType)(type)) {
// @ts-expect-error
return new _definition.GraphQLList(replaceType(type.ofType));
}
if ((0, _definition.isNonNullType)(type)) {
// @ts-expect-error
return new _definition.GraphQLNonNull(replaceType(type.ofType));
} // @ts-expect-error FIXME
return replaceNamedType(type);
}
function replaceNamedType(type) {
// Note: While this could make early assertions to get the correctly
// typed values, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
return typeMap[type.name];
}
function replaceDirective(directive) {
const config = directive.toConfig();
return new _directives.GraphQLDirective({
...config,
args: (0, _mapValue.mapValue)(config.args, extendArg),
});
}
function extendNamedType(type) {
if (
(0, _introspection.isIntrospectionType)(type) ||
(0, _scalars.isSpecifiedScalarType)(type)
) {
// Builtin types are not extended.
return type;
}
if ((0, _definition.isScalarType)(type)) {
return extendScalarType(type);
}
if ((0, _definition.isObjectType)(type)) {
return extendObjectType(type);
}
if ((0, _definition.isInterfaceType)(type)) {
return extendInterfaceType(type);
}
if ((0, _definition.isUnionType)(type)) {
return extendUnionType(type);
}
if ((0, _definition.isEnumType)(type)) {
return extendEnumType(type);
}
if ((0, _definition.isInputObjectType)(type)) {
return extendInputObjectType(type);
}
/* c8 ignore next 3 */
// Not reachable, all possible type definition nodes have been considered.
false ||
(0, _invariant.invariant)(
false,
'Unexpected type: ' + (0, _inspect.inspect)(type),
);
}
function extendInputObjectType(type) {
var _typeExtensionsMap$co;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null &&
_typeExtensionsMap$co !== void 0
? _typeExtensionsMap$co
: [];
return new _definition.GraphQLInputObjectType({
...config,
fields: () => ({
...(0, _mapValue.mapValue)(config.fields, (field) => ({
...field,
type: replaceType(field.type),
})),
...buildInputFieldMap(extensions),
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendEnumType(type) {
var _typeExtensionsMap$ty;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null &&
_typeExtensionsMap$ty !== void 0
? _typeExtensionsMap$ty
: [];
return new _definition.GraphQLEnumType({
...config,
values: { ...config.values, ...buildEnumValueMap(extensions) },
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendScalarType(type) {
var _typeExtensionsMap$co2;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null &&
_typeExtensionsMap$co2 !== void 0
? _typeExtensionsMap$co2
: [];
let specifiedByURL = config.specifiedByURL;
for (const extensionNode of extensions) {
var _getSpecifiedByURL;
specifiedByURL =
(_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null &&
_getSpecifiedByURL !== void 0
? _getSpecifiedByURL
: specifiedByURL;
}
return new _definition.GraphQLScalarType({
...config,
specifiedByURL,
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendObjectType(type) {
var _typeExtensionsMap$co3;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null &&
_typeExtensionsMap$co3 !== void 0
? _typeExtensionsMap$co3
: [];
return new _definition.GraphQLObjectType({
...config,
interfaces: () => [
...type.getInterfaces().map(replaceNamedType),
...buildInterfaces(extensions),
],
fields: () => ({
...(0, _mapValue.mapValue)(config.fields, extendField),
...buildFieldMap(extensions),
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendInterfaceType(type) {
var _typeExtensionsMap$co4;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null &&
_typeExtensionsMap$co4 !== void 0
? _typeExtensionsMap$co4
: [];
return new _definition.GraphQLInterfaceType({
...config,
interfaces: () => [
...type.getInterfaces().map(replaceNamedType),
...buildInterfaces(extensions),
],
fields: () => ({
...(0, _mapValue.mapValue)(config.fields, extendField),
...buildFieldMap(extensions),
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendUnionType(type) {
var _typeExtensionsMap$co5;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null &&
_typeExtensionsMap$co5 !== void 0
? _typeExtensionsMap$co5
: [];
return new _definition.GraphQLUnionType({
...config,
types: () => [
...type.getTypes().map(replaceNamedType),
...buildUnionTypes(extensions),
],
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendField(field) {
return {
...field,
type: replaceType(field.type),
args: field.args && (0, _mapValue.mapValue)(field.args, extendArg),
};
}
function extendArg(arg) {
return { ...arg, type: replaceType(arg.type) };
}
function getOperationTypes(nodes) {
const opTypes = {};
for (const node of nodes) {
var _node$operationTypes;
// FIXME: https://github.com/graphql/graphql-js/issues/2203
const operationTypesNodes =
/* c8 ignore next */
(_node$operationTypes = node.operationTypes) !== null &&
_node$operationTypes !== void 0
? _node$operationTypes
: [];
for (const operationType of operationTypesNodes) {
// Note: While this could make early assertions to get the correctly
// typed values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
// @ts-expect-error
opTypes[operationType.operation] = getNamedType(operationType.type);
}
}
return opTypes;
}
function getNamedType(node) {
var _stdTypeMap$name2;
const name = node.name.value;
const type =
(_stdTypeMap$name2 = stdTypeMap[name]) !== null &&
_stdTypeMap$name2 !== void 0
? _stdTypeMap$name2
: typeMap[name];
if (type === undefined) {
throw new Error(`Unknown type: "${name}".`);
}
return type;
}
function getWrappedType(node) {
if (node.kind === _kinds.Kind.LIST_TYPE) {
return new _definition.GraphQLList(getWrappedType(node.type));
}
if (node.kind === _kinds.Kind.NON_NULL_TYPE) {
return new _definition.GraphQLNonNull(getWrappedType(node.type));
}
return getNamedType(node);
}
function buildDirective(node) {
var _node$description;
return new _directives.GraphQLDirective({
name: node.name.value,
description:
(_node$description = node.description) === null ||
_node$description === void 0
? void 0
: _node$description.value,
// @ts-expect-error
locations: node.locations.map(({ value }) => value),
isRepeatable: node.repeatable,
args: buildArgumentMap(node.arguments),
astNode: node,
});
}
function buildFieldMap(nodes) {
const fieldConfigMap = Object.create(null);
for (const node of nodes) {
var _node$fields;
// FIXME: https://github.com/graphql/graphql-js/issues/2203
const nodeFields =
/* c8 ignore next */
(_node$fields = node.fields) !== null && _node$fields !== void 0
? _node$fields
: [];
for (const field of nodeFields) {
var _field$description;
fieldConfigMap[field.name.value] = {
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
type: getWrappedType(field.type),
description:
(_field$description = field.description) === null ||
_field$description === void 0
? void 0
: _field$description.value,
args: buildArgumentMap(field.arguments),
deprecationReason: getDeprecationReason(field),
astNode: field,
};
}
}
return fieldConfigMap;
}
function buildArgumentMap(args) {
// FIXME: https://github.com/graphql/graphql-js/issues/2203
const argsNodes =
/* c8 ignore next */
args !== null && args !== void 0 ? args : [];
const argConfigMap = Object.create(null);
for (const arg of argsNodes) {
var _arg$description;
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
const type = getWrappedType(arg.type);
argConfigMap[arg.name.value] = {
type,
description:
(_arg$description = arg.description) === null ||
_arg$description === void 0
? void 0
: _arg$description.value,
defaultValue: (0, _valueFromAST.valueFromAST)(arg.defaultValue, type),
deprecationReason: getDeprecationReason(arg),
astNode: arg,
};
}
return argConfigMap;
}
function buildInputFieldMap(nodes) {
const inputFieldMap = Object.create(null);
for (const node of nodes) {
var _node$fields2;
// FIXME: https://github.com/graphql/graphql-js/issues/2203
const fieldsNodes =
/* c8 ignore next */
(_node$fields2 = node.fields) !== null && _node$fields2 !== void 0
? _node$fields2
: [];
for (const field of fieldsNodes) {
var _field$description2;
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
const type = getWrappedType(field.type);
inputFieldMap[field.name.value] = {
type,
description:
(_field$description2 = field.description) === null ||
_field$description2 === void 0
? void 0
: _field$description2.value,
defaultValue: (0, _valueFromAST.valueFromAST)(
field.defaultValue,
type,
),
deprecationReason: getDeprecationReason(field),
astNode: field,
};
}
}
return inputFieldMap;
}
function buildEnumValueMap(nodes) {
const enumValueMap = Object.create(null);
for (const node of nodes) {
var _node$values;
// FIXME: https://github.com/graphql/graphql-js/issues/2203
const valuesNodes =
/* c8 ignore next */
(_node$values = node.values) !== null && _node$values !== void 0
? _node$values
: [];
for (const value of valuesNodes) {
var _value$description;
enumValueMap[value.name.value] = {
description:
(_value$description = value.description) === null ||
_value$description === void 0
? void 0
: _value$description.value,
deprecationReason: getDeprecationReason(value),
astNode: value,
};
}
}
return enumValueMap;
}
function buildInterfaces(nodes) {
// Note: While this could make assertions to get the correctly typed
// values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
// @ts-expect-error
return nodes.flatMap(
// FIXME: https://github.com/graphql/graphql-js/issues/2203
(node) => {
var _node$interfaces$map, _node$interfaces;
return (
/* c8 ignore next */
(_node$interfaces$map =
(_node$interfaces = node.interfaces) === null ||
_node$interfaces === void 0
? void 0
: _node$interfaces.map(getNamedType)) !== null &&
_node$interfaces$map !== void 0
? _node$interfaces$map
: []
);
},
);
}
function buildUnionTypes(nodes) {
// Note: While this could make assertions to get the correctly typed
// values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
// @ts-expect-error
return nodes.flatMap(
// FIXME: https://github.com/graphql/graphql-js/issues/2203
(node) => {
var _node$types$map, _node$types;
return (
/* c8 ignore next */
(_node$types$map =
(_node$types = node.types) === null || _node$types === void 0
? void 0
: _node$types.map(getNamedType)) !== null &&
_node$types$map !== void 0
? _node$types$map
: []
);
},
);
}
function buildType(astNode) {
var _typeExtensionsMap$na;
const name = astNode.name.value;
const extensionASTNodes =
(_typeExtensionsMap$na = typeExtensionsMap[name]) !== null &&
_typeExtensionsMap$na !== void 0
? _typeExtensionsMap$na
: [];
switch (astNode.kind) {
case _kinds.Kind.OBJECT_TYPE_DEFINITION: {
var _astNode$description;
const allNodes = [astNode, ...extensionASTNodes];
return new _definition.GraphQLObjectType({
name,
description:
(_astNode$description = astNode.description) === null ||
_astNode$description === void 0
? void 0
: _astNode$description.value,
interfaces: () => buildInterfaces(allNodes),
fields: () => buildFieldMap(allNodes),
astNode,
extensionASTNodes,
});
}
case _kinds.Kind.INTERFACE_TYPE_DEFINITION: {
var _astNode$description2;
const allNodes = [astNode, ...extensionASTNodes];
return new _definition.GraphQLInterfaceType({
name,
description:
(_astNode$description2 = astNode.description) === null ||
_astNode$description2 === void 0
? void 0
: _astNode$description2.value,
interfaces: () => buildInterfaces(allNodes),
fields: () => buildFieldMap(allNodes),
astNode,
extensionASTNodes,
});
}
case _kinds.Kind.ENUM_TYPE_DEFINITION: {
var _astNode$description3;
const allNodes = [astNode, ...extensionASTNodes];
return new _definition.GraphQLEnumType({
name,
description:
(_astNode$description3 = astNode.description) === null ||
_astNode$description3 === void 0
? void 0
: _astNode$description3.value,
values: buildEnumValueMap(allNodes),
astNode,
extensionASTNodes,
});
}
case _kinds.Kind.UNION_TYPE_DEFINITION: {
var _astNode$description4;
const allNodes = [astNode, ...extensionASTNodes];
return new _definition.GraphQLUnionType({
name,
description:
(_astNode$description4 = astNode.description) === null ||
_astNode$description4 === void 0
? void 0
: _astNode$description4.value,
types: () => buildUnionTypes(allNodes),
astNode,
extensionASTNodes,
});
}
case _kinds.Kind.SCALAR_TYPE_DEFINITION: {
var _astNode$description5;
return new _definition.GraphQLScalarType({
name,
description:
(_astNode$description5 = astNode.description) === null ||
_astNode$description5 === void 0
? void 0
: _astNode$description5.value,
specifiedByURL: getSpecifiedByURL(astNode),
astNode,
extensionASTNodes,
});
}
case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: {
var _astNode$description6;
const allNodes = [astNode, ...extensionASTNodes];
return new _definition.GraphQLInputObjectType({
name,
description:
(_astNode$description6 = astNode.description) === null ||
_astNode$description6 === void 0
? void 0
: _astNode$description6.value,
fields: () => buildInputFieldMap(allNodes),
astNode,
extensionASTNodes,
});
}
}
}
}
const stdTypeMap = (0, _keyMap.keyMap)(
[..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes],
(type) => type.name,
);
/**
* Given a field or enum value node, returns the string value for the
* deprecation reason.
*/
function getDeprecationReason(node) {
const deprecated = (0, _values.getDirectiveValues)(
_directives.GraphQLDeprecatedDirective,
node,
); // @ts-expect-error validated by `getDirectiveValues`
return deprecated === null || deprecated === void 0
? void 0
: deprecated.reason;
}
/**
* Given a scalar node, returns the string value for the specifiedByURL.
*/
function getSpecifiedByURL(node) {
const specifiedBy = (0, _values.getDirectiveValues)(
_directives.GraphQLSpecifiedByDirective,
node,
); // @ts-expect-error validated by `getDirectiveValues`
return specifiedBy === null || specifiedBy === void 0
? void 0
: specifiedBy.url;
}

View File

@@ -0,0 +1,789 @@
import { devAssert } from '../jsutils/devAssert.mjs';
import { inspect } from '../jsutils/inspect.mjs';
import { invariant } from '../jsutils/invariant.mjs';
import { keyMap } from '../jsutils/keyMap.mjs';
import { mapValue } from '../jsutils/mapValue.mjs';
import { Kind } from '../language/kinds.mjs';
import {
isTypeDefinitionNode,
isTypeExtensionNode,
} from '../language/predicates.mjs';
import {
GraphQLEnumType,
GraphQLInputObjectType,
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLScalarType,
GraphQLUnionType,
isEnumType,
isInputObjectType,
isInterfaceType,
isListType,
isNonNullType,
isObjectType,
isScalarType,
isUnionType,
} from '../type/definition.mjs';
import {
GraphQLDeprecatedDirective,
GraphQLDirective,
GraphQLSpecifiedByDirective,
} from '../type/directives.mjs';
import {
introspectionTypes,
isIntrospectionType,
} from '../type/introspection.mjs';
import {
isSpecifiedScalarType,
specifiedScalarTypes,
} from '../type/scalars.mjs';
import { assertSchema, GraphQLSchema } from '../type/schema.mjs';
import { assertValidSDLExtension } from '../validation/validate.mjs';
import { getDirectiveValues } from '../execution/values.mjs';
import { valueFromAST } from './valueFromAST.mjs';
/**
* Produces a new schema given an existing schema and a document which may
* contain GraphQL type extensions and definitions. The original schema will
* remain unaltered.
*
* Because a schema represents a graph of references, a schema cannot be
* extended without effectively making an entire copy. We do not know until it's
* too late if subgraphs remain unchanged.
*
* This algorithm copies the provided schema, applying extensions while
* producing the copy. The original schema remains unaltered.
*/
export function extendSchema(schema, documentAST, options) {
assertSchema(schema);
(documentAST != null && documentAST.kind === Kind.DOCUMENT) ||
devAssert(false, 'Must provide valid Document AST.');
if (
(options === null || options === void 0 ? void 0 : options.assumeValid) !==
true &&
(options === null || options === void 0
? void 0
: options.assumeValidSDL) !== true
) {
assertValidSDLExtension(documentAST, schema);
}
const schemaConfig = schema.toConfig();
const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options);
return schemaConfig === extendedConfig
? schema
: new GraphQLSchema(extendedConfig);
}
/**
* @internal
*/
export function extendSchemaImpl(schemaConfig, documentAST, options) {
var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid;
// Collect the type definitions and extensions found in the document.
const typeDefs = [];
const typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can
// have the same name. For example, a type named "skip".
const directiveDefs = [];
let schemaDef; // Schema extensions are collected which may add additional operation types.
const schemaExtensions = [];
for (const def of documentAST.definitions) {
if (def.kind === Kind.SCHEMA_DEFINITION) {
schemaDef = def;
} else if (def.kind === Kind.SCHEMA_EXTENSION) {
schemaExtensions.push(def);
} else if (isTypeDefinitionNode(def)) {
typeDefs.push(def);
} else if (isTypeExtensionNode(def)) {
const extendedTypeName = def.name.value;
const existingTypeExtensions = typeExtensionsMap[extendedTypeName];
typeExtensionsMap[extendedTypeName] = existingTypeExtensions
? existingTypeExtensions.concat([def])
: [def];
} else if (def.kind === Kind.DIRECTIVE_DEFINITION) {
directiveDefs.push(def);
}
} // If this document contains no new types, extensions, or directives then
// return the same unmodified GraphQLSchema instance.
if (
Object.keys(typeExtensionsMap).length === 0 &&
typeDefs.length === 0 &&
directiveDefs.length === 0 &&
schemaExtensions.length === 0 &&
schemaDef == null
) {
return schemaConfig;
}
const typeMap = Object.create(null);
for (const existingType of schemaConfig.types) {
typeMap[existingType.name] = extendNamedType(existingType);
}
for (const typeNode of typeDefs) {
var _stdTypeMap$name;
const name = typeNode.name.value;
typeMap[name] =
(_stdTypeMap$name = stdTypeMap[name]) !== null &&
_stdTypeMap$name !== void 0
? _stdTypeMap$name
: buildType(typeNode);
}
const operationTypes = {
// Get the extended root operation types.
query: schemaConfig.query && replaceNamedType(schemaConfig.query),
mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation),
subscription:
schemaConfig.subscription && replaceNamedType(schemaConfig.subscription),
// Then, incorporate schema definition and all schema extensions.
...(schemaDef && getOperationTypes([schemaDef])),
...getOperationTypes(schemaExtensions),
}; // Then produce and return a Schema config with these types.
return {
description:
(_schemaDef = schemaDef) === null || _schemaDef === void 0
? void 0
: (_schemaDef$descriptio = _schemaDef.description) === null ||
_schemaDef$descriptio === void 0
? void 0
: _schemaDef$descriptio.value,
...operationTypes,
types: Object.values(typeMap),
directives: [
...schemaConfig.directives.map(replaceDirective),
...directiveDefs.map(buildDirective),
],
extensions: Object.create(null),
astNode:
(_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0
? _schemaDef2
: schemaConfig.astNode,
extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions),
assumeValid:
(_options$assumeValid =
options === null || options === void 0
? void 0
: options.assumeValid) !== null && _options$assumeValid !== void 0
? _options$assumeValid
: false,
}; // Below are functions used for producing this schema that have closed over
// this scope and have access to the schema, cache, and newly defined types.
function replaceType(type) {
if (isListType(type)) {
// @ts-expect-error
return new GraphQLList(replaceType(type.ofType));
}
if (isNonNullType(type)) {
// @ts-expect-error
return new GraphQLNonNull(replaceType(type.ofType));
} // @ts-expect-error FIXME
return replaceNamedType(type);
}
function replaceNamedType(type) {
// Note: While this could make early assertions to get the correctly
// typed values, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
return typeMap[type.name];
}
function replaceDirective(directive) {
const config = directive.toConfig();
return new GraphQLDirective({
...config,
args: mapValue(config.args, extendArg),
});
}
function extendNamedType(type) {
if (isIntrospectionType(type) || isSpecifiedScalarType(type)) {
// Builtin types are not extended.
return type;
}
if (isScalarType(type)) {
return extendScalarType(type);
}
if (isObjectType(type)) {
return extendObjectType(type);
}
if (isInterfaceType(type)) {
return extendInterfaceType(type);
}
if (isUnionType(type)) {
return extendUnionType(type);
}
if (isEnumType(type)) {
return extendEnumType(type);
}
if (isInputObjectType(type)) {
return extendInputObjectType(type);
}
/* c8 ignore next 3 */
// Not reachable, all possible type definition nodes have been considered.
false || invariant(false, 'Unexpected type: ' + inspect(type));
}
function extendInputObjectType(type) {
var _typeExtensionsMap$co;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null &&
_typeExtensionsMap$co !== void 0
? _typeExtensionsMap$co
: [];
return new GraphQLInputObjectType({
...config,
fields: () => ({
...mapValue(config.fields, (field) => ({
...field,
type: replaceType(field.type),
})),
...buildInputFieldMap(extensions),
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendEnumType(type) {
var _typeExtensionsMap$ty;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null &&
_typeExtensionsMap$ty !== void 0
? _typeExtensionsMap$ty
: [];
return new GraphQLEnumType({
...config,
values: { ...config.values, ...buildEnumValueMap(extensions) },
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendScalarType(type) {
var _typeExtensionsMap$co2;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null &&
_typeExtensionsMap$co2 !== void 0
? _typeExtensionsMap$co2
: [];
let specifiedByURL = config.specifiedByURL;
for (const extensionNode of extensions) {
var _getSpecifiedByURL;
specifiedByURL =
(_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null &&
_getSpecifiedByURL !== void 0
? _getSpecifiedByURL
: specifiedByURL;
}
return new GraphQLScalarType({
...config,
specifiedByURL,
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendObjectType(type) {
var _typeExtensionsMap$co3;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null &&
_typeExtensionsMap$co3 !== void 0
? _typeExtensionsMap$co3
: [];
return new GraphQLObjectType({
...config,
interfaces: () => [
...type.getInterfaces().map(replaceNamedType),
...buildInterfaces(extensions),
],
fields: () => ({
...mapValue(config.fields, extendField),
...buildFieldMap(extensions),
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendInterfaceType(type) {
var _typeExtensionsMap$co4;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null &&
_typeExtensionsMap$co4 !== void 0
? _typeExtensionsMap$co4
: [];
return new GraphQLInterfaceType({
...config,
interfaces: () => [
...type.getInterfaces().map(replaceNamedType),
...buildInterfaces(extensions),
],
fields: () => ({
...mapValue(config.fields, extendField),
...buildFieldMap(extensions),
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendUnionType(type) {
var _typeExtensionsMap$co5;
const config = type.toConfig();
const extensions =
(_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null &&
_typeExtensionsMap$co5 !== void 0
? _typeExtensionsMap$co5
: [];
return new GraphQLUnionType({
...config,
types: () => [
...type.getTypes().map(replaceNamedType),
...buildUnionTypes(extensions),
],
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendField(field) {
return {
...field,
type: replaceType(field.type),
args: field.args && mapValue(field.args, extendArg),
};
}
function extendArg(arg) {
return { ...arg, type: replaceType(arg.type) };
}
function getOperationTypes(nodes) {
const opTypes = {};
for (const node of nodes) {
var _node$operationTypes;
// FIXME: https://github.com/graphql/graphql-js/issues/2203
const operationTypesNodes =
/* c8 ignore next */
(_node$operationTypes = node.operationTypes) !== null &&
_node$operationTypes !== void 0
? _node$operationTypes
: [];
for (const operationType of operationTypesNodes) {
// Note: While this could make early assertions to get the correctly
// typed values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
// @ts-expect-error
opTypes[operationType.operation] = getNamedType(operationType.type);
}
}
return opTypes;
}
function getNamedType(node) {
var _stdTypeMap$name2;
const name = node.name.value;
const type =
(_stdTypeMap$name2 = stdTypeMap[name]) !== null &&
_stdTypeMap$name2 !== void 0
? _stdTypeMap$name2
: typeMap[name];
if (type === undefined) {
throw new Error(`Unknown type: "${name}".`);
}
return type;
}
function getWrappedType(node) {
if (node.kind === Kind.LIST_TYPE) {
return new GraphQLList(getWrappedType(node.type));
}
if (node.kind === Kind.NON_NULL_TYPE) {
return new GraphQLNonNull(getWrappedType(node.type));
}
return getNamedType(node);
}
function buildDirective(node) {
var _node$description;
return new GraphQLDirective({
name: node.name.value,
description:
(_node$description = node.description) === null ||
_node$description === void 0
? void 0
: _node$description.value,
// @ts-expect-error
locations: node.locations.map(({ value }) => value),
isRepeatable: node.repeatable,
args: buildArgumentMap(node.arguments),
astNode: node,
});
}
function buildFieldMap(nodes) {
const fieldConfigMap = Object.create(null);
for (const node of nodes) {
var _node$fields;
// FIXME: https://github.com/graphql/graphql-js/issues/2203
const nodeFields =
/* c8 ignore next */
(_node$fields = node.fields) !== null && _node$fields !== void 0
? _node$fields
: [];
for (const field of nodeFields) {
var _field$description;
fieldConfigMap[field.name.value] = {
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
type: getWrappedType(field.type),
description:
(_field$description = field.description) === null ||
_field$description === void 0
? void 0
: _field$description.value,
args: buildArgumentMap(field.arguments),
deprecationReason: getDeprecationReason(field),
astNode: field,
};
}
}
return fieldConfigMap;
}
function buildArgumentMap(args) {
// FIXME: https://github.com/graphql/graphql-js/issues/2203
const argsNodes =
/* c8 ignore next */
args !== null && args !== void 0 ? args : [];
const argConfigMap = Object.create(null);
for (const arg of argsNodes) {
var _arg$description;
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
const type = getWrappedType(arg.type);
argConfigMap[arg.name.value] = {
type,
description:
(_arg$description = arg.description) === null ||
_arg$description === void 0
? void 0
: _arg$description.value,
defaultValue: valueFromAST(arg.defaultValue, type),
deprecationReason: getDeprecationReason(arg),
astNode: arg,
};
}
return argConfigMap;
}
function buildInputFieldMap(nodes) {
const inputFieldMap = Object.create(null);
for (const node of nodes) {
var _node$fields2;
// FIXME: https://github.com/graphql/graphql-js/issues/2203
const fieldsNodes =
/* c8 ignore next */
(_node$fields2 = node.fields) !== null && _node$fields2 !== void 0
? _node$fields2
: [];
for (const field of fieldsNodes) {
var _field$description2;
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
const type = getWrappedType(field.type);
inputFieldMap[field.name.value] = {
type,
description:
(_field$description2 = field.description) === null ||
_field$description2 === void 0
? void 0
: _field$description2.value,
defaultValue: valueFromAST(field.defaultValue, type),
deprecationReason: getDeprecationReason(field),
astNode: field,
};
}
}
return inputFieldMap;
}
function buildEnumValueMap(nodes) {
const enumValueMap = Object.create(null);
for (const node of nodes) {
var _node$values;
// FIXME: https://github.com/graphql/graphql-js/issues/2203
const valuesNodes =
/* c8 ignore next */
(_node$values = node.values) !== null && _node$values !== void 0
? _node$values
: [];
for (const value of valuesNodes) {
var _value$description;
enumValueMap[value.name.value] = {
description:
(_value$description = value.description) === null ||
_value$description === void 0
? void 0
: _value$description.value,
deprecationReason: getDeprecationReason(value),
astNode: value,
};
}
}
return enumValueMap;
}
function buildInterfaces(nodes) {
// Note: While this could make assertions to get the correctly typed
// values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
// @ts-expect-error
return nodes.flatMap(
// FIXME: https://github.com/graphql/graphql-js/issues/2203
(node) => {
var _node$interfaces$map, _node$interfaces;
return (
/* c8 ignore next */
(_node$interfaces$map =
(_node$interfaces = node.interfaces) === null ||
_node$interfaces === void 0
? void 0
: _node$interfaces.map(getNamedType)) !== null &&
_node$interfaces$map !== void 0
? _node$interfaces$map
: []
);
},
);
}
function buildUnionTypes(nodes) {
// Note: While this could make assertions to get the correctly typed
// values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
// @ts-expect-error
return nodes.flatMap(
// FIXME: https://github.com/graphql/graphql-js/issues/2203
(node) => {
var _node$types$map, _node$types;
return (
/* c8 ignore next */
(_node$types$map =
(_node$types = node.types) === null || _node$types === void 0
? void 0
: _node$types.map(getNamedType)) !== null &&
_node$types$map !== void 0
? _node$types$map
: []
);
},
);
}
function buildType(astNode) {
var _typeExtensionsMap$na;
const name = astNode.name.value;
const extensionASTNodes =
(_typeExtensionsMap$na = typeExtensionsMap[name]) !== null &&
_typeExtensionsMap$na !== void 0
? _typeExtensionsMap$na
: [];
switch (astNode.kind) {
case Kind.OBJECT_TYPE_DEFINITION: {
var _astNode$description;
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLObjectType({
name,
description:
(_astNode$description = astNode.description) === null ||
_astNode$description === void 0
? void 0
: _astNode$description.value,
interfaces: () => buildInterfaces(allNodes),
fields: () => buildFieldMap(allNodes),
astNode,
extensionASTNodes,
});
}
case Kind.INTERFACE_TYPE_DEFINITION: {
var _astNode$description2;
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLInterfaceType({
name,
description:
(_astNode$description2 = astNode.description) === null ||
_astNode$description2 === void 0
? void 0
: _astNode$description2.value,
interfaces: () => buildInterfaces(allNodes),
fields: () => buildFieldMap(allNodes),
astNode,
extensionASTNodes,
});
}
case Kind.ENUM_TYPE_DEFINITION: {
var _astNode$description3;
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLEnumType({
name,
description:
(_astNode$description3 = astNode.description) === null ||
_astNode$description3 === void 0
? void 0
: _astNode$description3.value,
values: buildEnumValueMap(allNodes),
astNode,
extensionASTNodes,
});
}
case Kind.UNION_TYPE_DEFINITION: {
var _astNode$description4;
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLUnionType({
name,
description:
(_astNode$description4 = astNode.description) === null ||
_astNode$description4 === void 0
? void 0
: _astNode$description4.value,
types: () => buildUnionTypes(allNodes),
astNode,
extensionASTNodes,
});
}
case Kind.SCALAR_TYPE_DEFINITION: {
var _astNode$description5;
return new GraphQLScalarType({
name,
description:
(_astNode$description5 = astNode.description) === null ||
_astNode$description5 === void 0
? void 0
: _astNode$description5.value,
specifiedByURL: getSpecifiedByURL(astNode),
astNode,
extensionASTNodes,
});
}
case Kind.INPUT_OBJECT_TYPE_DEFINITION: {
var _astNode$description6;
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLInputObjectType({
name,
description:
(_astNode$description6 = astNode.description) === null ||
_astNode$description6 === void 0
? void 0
: _astNode$description6.value,
fields: () => buildInputFieldMap(allNodes),
astNode,
extensionASTNodes,
});
}
}
}
}
const stdTypeMap = keyMap(
[...specifiedScalarTypes, ...introspectionTypes],
(type) => type.name,
);
/**
* Given a field or enum value node, returns the string value for the
* deprecation reason.
*/
function getDeprecationReason(node) {
const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node); // @ts-expect-error validated by `getDirectiveValues`
return deprecated === null || deprecated === void 0
? void 0
: deprecated.reason;
}
/**
* Given a scalar node, returns the string value for the specifiedByURL.
*/
function getSpecifiedByURL(node) {
const specifiedBy = getDirectiveValues(GraphQLSpecifiedByDirective, node); // @ts-expect-error validated by `getDirectiveValues`
return specifiedBy === null || specifiedBy === void 0
? void 0
: specifiedBy.url;
}

View File

@@ -0,0 +1,53 @@
import type { GraphQLSchema } from '../type/schema';
declare enum BreakingChangeType {
TYPE_REMOVED = 'TYPE_REMOVED',
TYPE_CHANGED_KIND = 'TYPE_CHANGED_KIND',
TYPE_REMOVED_FROM_UNION = 'TYPE_REMOVED_FROM_UNION',
VALUE_REMOVED_FROM_ENUM = 'VALUE_REMOVED_FROM_ENUM',
REQUIRED_INPUT_FIELD_ADDED = 'REQUIRED_INPUT_FIELD_ADDED',
IMPLEMENTED_INTERFACE_REMOVED = 'IMPLEMENTED_INTERFACE_REMOVED',
FIELD_REMOVED = 'FIELD_REMOVED',
FIELD_CHANGED_KIND = 'FIELD_CHANGED_KIND',
REQUIRED_ARG_ADDED = 'REQUIRED_ARG_ADDED',
ARG_REMOVED = 'ARG_REMOVED',
ARG_CHANGED_KIND = 'ARG_CHANGED_KIND',
DIRECTIVE_REMOVED = 'DIRECTIVE_REMOVED',
DIRECTIVE_ARG_REMOVED = 'DIRECTIVE_ARG_REMOVED',
REQUIRED_DIRECTIVE_ARG_ADDED = 'REQUIRED_DIRECTIVE_ARG_ADDED',
DIRECTIVE_REPEATABLE_REMOVED = 'DIRECTIVE_REPEATABLE_REMOVED',
DIRECTIVE_LOCATION_REMOVED = 'DIRECTIVE_LOCATION_REMOVED',
}
export { BreakingChangeType };
declare enum DangerousChangeType {
VALUE_ADDED_TO_ENUM = 'VALUE_ADDED_TO_ENUM',
TYPE_ADDED_TO_UNION = 'TYPE_ADDED_TO_UNION',
OPTIONAL_INPUT_FIELD_ADDED = 'OPTIONAL_INPUT_FIELD_ADDED',
OPTIONAL_ARG_ADDED = 'OPTIONAL_ARG_ADDED',
IMPLEMENTED_INTERFACE_ADDED = 'IMPLEMENTED_INTERFACE_ADDED',
ARG_DEFAULT_VALUE_CHANGE = 'ARG_DEFAULT_VALUE_CHANGE',
}
export { DangerousChangeType };
export interface BreakingChange {
type: BreakingChangeType;
description: string;
}
export interface DangerousChange {
type: DangerousChangeType;
description: string;
}
/**
* Given two schemas, returns an Array containing descriptions of all the types
* of breaking changes covered by the other functions down below.
*/
export declare function findBreakingChanges(
oldSchema: GraphQLSchema,
newSchema: GraphQLSchema,
): Array<BreakingChange>;
/**
* Given two schemas, returns an Array containing descriptions of all the types
* of potentially dangerous changes covered by the other functions down below.
*/
export declare function findDangerousChanges(
oldSchema: GraphQLSchema,
newSchema: GraphQLSchema,
): Array<DangerousChange>;

View File

@@ -0,0 +1,547 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.DangerousChangeType = exports.BreakingChangeType = void 0;
exports.findBreakingChanges = findBreakingChanges;
exports.findDangerousChanges = findDangerousChanges;
var _inspect = require('../jsutils/inspect.js');
var _invariant = require('../jsutils/invariant.js');
var _keyMap = require('../jsutils/keyMap.js');
var _printer = require('../language/printer.js');
var _definition = require('../type/definition.js');
var _scalars = require('../type/scalars.js');
var _astFromValue = require('./astFromValue.js');
var _sortValueNode = require('./sortValueNode.js');
var BreakingChangeType;
exports.BreakingChangeType = BreakingChangeType;
(function (BreakingChangeType) {
BreakingChangeType['TYPE_REMOVED'] = 'TYPE_REMOVED';
BreakingChangeType['TYPE_CHANGED_KIND'] = 'TYPE_CHANGED_KIND';
BreakingChangeType['TYPE_REMOVED_FROM_UNION'] = 'TYPE_REMOVED_FROM_UNION';
BreakingChangeType['VALUE_REMOVED_FROM_ENUM'] = 'VALUE_REMOVED_FROM_ENUM';
BreakingChangeType['REQUIRED_INPUT_FIELD_ADDED'] =
'REQUIRED_INPUT_FIELD_ADDED';
BreakingChangeType['IMPLEMENTED_INTERFACE_REMOVED'] =
'IMPLEMENTED_INTERFACE_REMOVED';
BreakingChangeType['FIELD_REMOVED'] = 'FIELD_REMOVED';
BreakingChangeType['FIELD_CHANGED_KIND'] = 'FIELD_CHANGED_KIND';
BreakingChangeType['REQUIRED_ARG_ADDED'] = 'REQUIRED_ARG_ADDED';
BreakingChangeType['ARG_REMOVED'] = 'ARG_REMOVED';
BreakingChangeType['ARG_CHANGED_KIND'] = 'ARG_CHANGED_KIND';
BreakingChangeType['DIRECTIVE_REMOVED'] = 'DIRECTIVE_REMOVED';
BreakingChangeType['DIRECTIVE_ARG_REMOVED'] = 'DIRECTIVE_ARG_REMOVED';
BreakingChangeType['REQUIRED_DIRECTIVE_ARG_ADDED'] =
'REQUIRED_DIRECTIVE_ARG_ADDED';
BreakingChangeType['DIRECTIVE_REPEATABLE_REMOVED'] =
'DIRECTIVE_REPEATABLE_REMOVED';
BreakingChangeType['DIRECTIVE_LOCATION_REMOVED'] =
'DIRECTIVE_LOCATION_REMOVED';
})(
BreakingChangeType || (exports.BreakingChangeType = BreakingChangeType = {}),
);
var DangerousChangeType;
exports.DangerousChangeType = DangerousChangeType;
(function (DangerousChangeType) {
DangerousChangeType['VALUE_ADDED_TO_ENUM'] = 'VALUE_ADDED_TO_ENUM';
DangerousChangeType['TYPE_ADDED_TO_UNION'] = 'TYPE_ADDED_TO_UNION';
DangerousChangeType['OPTIONAL_INPUT_FIELD_ADDED'] =
'OPTIONAL_INPUT_FIELD_ADDED';
DangerousChangeType['OPTIONAL_ARG_ADDED'] = 'OPTIONAL_ARG_ADDED';
DangerousChangeType['IMPLEMENTED_INTERFACE_ADDED'] =
'IMPLEMENTED_INTERFACE_ADDED';
DangerousChangeType['ARG_DEFAULT_VALUE_CHANGE'] = 'ARG_DEFAULT_VALUE_CHANGE';
})(
DangerousChangeType ||
(exports.DangerousChangeType = DangerousChangeType = {}),
);
/**
* Given two schemas, returns an Array containing descriptions of all the types
* of breaking changes covered by the other functions down below.
*/
function findBreakingChanges(oldSchema, newSchema) {
// @ts-expect-error
return findSchemaChanges(oldSchema, newSchema).filter(
(change) => change.type in BreakingChangeType,
);
}
/**
* Given two schemas, returns an Array containing descriptions of all the types
* of potentially dangerous changes covered by the other functions down below.
*/
function findDangerousChanges(oldSchema, newSchema) {
// @ts-expect-error
return findSchemaChanges(oldSchema, newSchema).filter(
(change) => change.type in DangerousChangeType,
);
}
function findSchemaChanges(oldSchema, newSchema) {
return [
...findTypeChanges(oldSchema, newSchema),
...findDirectiveChanges(oldSchema, newSchema),
];
}
function findDirectiveChanges(oldSchema, newSchema) {
const schemaChanges = [];
const directivesDiff = diff(
oldSchema.getDirectives(),
newSchema.getDirectives(),
);
for (const oldDirective of directivesDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.DIRECTIVE_REMOVED,
description: `${oldDirective.name} was removed.`,
});
}
for (const [oldDirective, newDirective] of directivesDiff.persisted) {
const argsDiff = diff(oldDirective.args, newDirective.args);
for (const newArg of argsDiff.added) {
if ((0, _definition.isRequiredArgument)(newArg)) {
schemaChanges.push({
type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED,
description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.`,
});
}
}
for (const oldArg of argsDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.DIRECTIVE_ARG_REMOVED,
description: `${oldArg.name} was removed from ${oldDirective.name}.`,
});
}
if (oldDirective.isRepeatable && !newDirective.isRepeatable) {
schemaChanges.push({
type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED,
description: `Repeatable flag was removed from ${oldDirective.name}.`,
});
}
for (const location of oldDirective.locations) {
if (!newDirective.locations.includes(location)) {
schemaChanges.push({
type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED,
description: `${location} was removed from ${oldDirective.name}.`,
});
}
}
}
return schemaChanges;
}
function findTypeChanges(oldSchema, newSchema) {
const schemaChanges = [];
const typesDiff = diff(
Object.values(oldSchema.getTypeMap()),
Object.values(newSchema.getTypeMap()),
);
for (const oldType of typesDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.TYPE_REMOVED,
description: (0, _scalars.isSpecifiedScalarType)(oldType)
? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.`
: `${oldType.name} was removed.`,
});
}
for (const [oldType, newType] of typesDiff.persisted) {
if (
(0, _definition.isEnumType)(oldType) &&
(0, _definition.isEnumType)(newType)
) {
schemaChanges.push(...findEnumTypeChanges(oldType, newType));
} else if (
(0, _definition.isUnionType)(oldType) &&
(0, _definition.isUnionType)(newType)
) {
schemaChanges.push(...findUnionTypeChanges(oldType, newType));
} else if (
(0, _definition.isInputObjectType)(oldType) &&
(0, _definition.isInputObjectType)(newType)
) {
schemaChanges.push(...findInputObjectTypeChanges(oldType, newType));
} else if (
(0, _definition.isObjectType)(oldType) &&
(0, _definition.isObjectType)(newType)
) {
schemaChanges.push(
...findFieldChanges(oldType, newType),
...findImplementedInterfacesChanges(oldType, newType),
);
} else if (
(0, _definition.isInterfaceType)(oldType) &&
(0, _definition.isInterfaceType)(newType)
) {
schemaChanges.push(
...findFieldChanges(oldType, newType),
...findImplementedInterfacesChanges(oldType, newType),
);
} else if (oldType.constructor !== newType.constructor) {
schemaChanges.push({
type: BreakingChangeType.TYPE_CHANGED_KIND,
description:
`${oldType.name} changed from ` +
`${typeKindName(oldType)} to ${typeKindName(newType)}.`,
});
}
}
return schemaChanges;
}
function findInputObjectTypeChanges(oldType, newType) {
const schemaChanges = [];
const fieldsDiff = diff(
Object.values(oldType.getFields()),
Object.values(newType.getFields()),
);
for (const newField of fieldsDiff.added) {
if ((0, _definition.isRequiredInputField)(newField)) {
schemaChanges.push({
type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED,
description: `A required field ${newField.name} on input type ${oldType.name} was added.`,
});
} else {
schemaChanges.push({
type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED,
description: `An optional field ${newField.name} on input type ${oldType.name} was added.`,
});
}
}
for (const oldField of fieldsDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.FIELD_REMOVED,
description: `${oldType.name}.${oldField.name} was removed.`,
});
}
for (const [oldField, newField] of fieldsDiff.persisted) {
const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(
oldField.type,
newField.type,
);
if (!isSafe) {
schemaChanges.push({
type: BreakingChangeType.FIELD_CHANGED_KIND,
description:
`${oldType.name}.${oldField.name} changed type from ` +
`${String(oldField.type)} to ${String(newField.type)}.`,
});
}
}
return schemaChanges;
}
function findUnionTypeChanges(oldType, newType) {
const schemaChanges = [];
const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes());
for (const newPossibleType of possibleTypesDiff.added) {
schemaChanges.push({
type: DangerousChangeType.TYPE_ADDED_TO_UNION,
description: `${newPossibleType.name} was added to union type ${oldType.name}.`,
});
}
for (const oldPossibleType of possibleTypesDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,
description: `${oldPossibleType.name} was removed from union type ${oldType.name}.`,
});
}
return schemaChanges;
}
function findEnumTypeChanges(oldType, newType) {
const schemaChanges = [];
const valuesDiff = diff(oldType.getValues(), newType.getValues());
for (const newValue of valuesDiff.added) {
schemaChanges.push({
type: DangerousChangeType.VALUE_ADDED_TO_ENUM,
description: `${newValue.name} was added to enum type ${oldType.name}.`,
});
}
for (const oldValue of valuesDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,
description: `${oldValue.name} was removed from enum type ${oldType.name}.`,
});
}
return schemaChanges;
}
function findImplementedInterfacesChanges(oldType, newType) {
const schemaChanges = [];
const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces());
for (const newInterface of interfacesDiff.added) {
schemaChanges.push({
type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED,
description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.`,
});
}
for (const oldInterface of interfacesDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED,
description: `${oldType.name} no longer implements interface ${oldInterface.name}.`,
});
}
return schemaChanges;
}
function findFieldChanges(oldType, newType) {
const schemaChanges = [];
const fieldsDiff = diff(
Object.values(oldType.getFields()),
Object.values(newType.getFields()),
);
for (const oldField of fieldsDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.FIELD_REMOVED,
description: `${oldType.name}.${oldField.name} was removed.`,
});
}
for (const [oldField, newField] of fieldsDiff.persisted) {
schemaChanges.push(...findArgChanges(oldType, oldField, newField));
const isSafe = isChangeSafeForObjectOrInterfaceField(
oldField.type,
newField.type,
);
if (!isSafe) {
schemaChanges.push({
type: BreakingChangeType.FIELD_CHANGED_KIND,
description:
`${oldType.name}.${oldField.name} changed type from ` +
`${String(oldField.type)} to ${String(newField.type)}.`,
});
}
}
return schemaChanges;
}
function findArgChanges(oldType, oldField, newField) {
const schemaChanges = [];
const argsDiff = diff(oldField.args, newField.args);
for (const oldArg of argsDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.ARG_REMOVED,
description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.`,
});
}
for (const [oldArg, newArg] of argsDiff.persisted) {
const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(
oldArg.type,
newArg.type,
);
if (!isSafe) {
schemaChanges.push({
type: BreakingChangeType.ARG_CHANGED_KIND,
description:
`${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` +
`${String(oldArg.type)} to ${String(newArg.type)}.`,
});
} else if (oldArg.defaultValue !== undefined) {
if (newArg.defaultValue === undefined) {
schemaChanges.push({
type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,
description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.`,
});
} else {
// Since we looking only for client's observable changes we should
// compare default values in the same representation as they are
// represented inside introspection.
const oldValueStr = stringifyValue(oldArg.defaultValue, oldArg.type);
const newValueStr = stringifyValue(newArg.defaultValue, newArg.type);
if (oldValueStr !== newValueStr) {
schemaChanges.push({
type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,
description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.`,
});
}
}
}
}
for (const newArg of argsDiff.added) {
if ((0, _definition.isRequiredArgument)(newArg)) {
schemaChanges.push({
type: BreakingChangeType.REQUIRED_ARG_ADDED,
description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`,
});
} else {
schemaChanges.push({
type: DangerousChangeType.OPTIONAL_ARG_ADDED,
description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`,
});
}
}
return schemaChanges;
}
function isChangeSafeForObjectOrInterfaceField(oldType, newType) {
if ((0, _definition.isListType)(oldType)) {
return (
// if they're both lists, make sure the underlying types are compatible
((0, _definition.isListType)(newType) &&
isChangeSafeForObjectOrInterfaceField(
oldType.ofType,
newType.ofType,
)) || // moving from nullable to non-null of the same underlying type is safe
((0, _definition.isNonNullType)(newType) &&
isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType))
);
}
if ((0, _definition.isNonNullType)(oldType)) {
// if they're both non-null, make sure the underlying types are compatible
return (
(0, _definition.isNonNullType)(newType) &&
isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType)
);
}
return (
// if they're both named types, see if their names are equivalent
((0, _definition.isNamedType)(newType) && oldType.name === newType.name) || // moving from nullable to non-null of the same underlying type is safe
((0, _definition.isNonNullType)(newType) &&
isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType))
);
}
function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) {
if ((0, _definition.isListType)(oldType)) {
// if they're both lists, make sure the underlying types are compatible
return (
(0, _definition.isListType)(newType) &&
isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType)
);
}
if ((0, _definition.isNonNullType)(oldType)) {
return (
// if they're both non-null, make sure the underlying types are
// compatible
((0, _definition.isNonNullType)(newType) &&
isChangeSafeForInputObjectFieldOrFieldArg(
oldType.ofType,
newType.ofType,
)) || // moving from non-null to nullable of the same underlying type is safe
(!(0, _definition.isNonNullType)(newType) &&
isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType))
);
} // if they're both named types, see if their names are equivalent
return (0, _definition.isNamedType)(newType) && oldType.name === newType.name;
}
function typeKindName(type) {
if ((0, _definition.isScalarType)(type)) {
return 'a Scalar type';
}
if ((0, _definition.isObjectType)(type)) {
return 'an Object type';
}
if ((0, _definition.isInterfaceType)(type)) {
return 'an Interface type';
}
if ((0, _definition.isUnionType)(type)) {
return 'a Union type';
}
if ((0, _definition.isEnumType)(type)) {
return 'an Enum type';
}
if ((0, _definition.isInputObjectType)(type)) {
return 'an Input type';
}
/* c8 ignore next 3 */
// Not reachable, all possible types have been considered.
false ||
(0, _invariant.invariant)(
false,
'Unexpected type: ' + (0, _inspect.inspect)(type),
);
}
function stringifyValue(value, type) {
const ast = (0, _astFromValue.astFromValue)(value, type);
ast != null || (0, _invariant.invariant)(false);
return (0, _printer.print)((0, _sortValueNode.sortValueNode)(ast));
}
function diff(oldArray, newArray) {
const added = [];
const removed = [];
const persisted = [];
const oldMap = (0, _keyMap.keyMap)(oldArray, ({ name }) => name);
const newMap = (0, _keyMap.keyMap)(newArray, ({ name }) => name);
for (const oldItem of oldArray) {
const newItem = newMap[oldItem.name];
if (newItem === undefined) {
removed.push(oldItem);
} else {
persisted.push([oldItem, newItem]);
}
}
for (const newItem of newArray) {
if (oldMap[newItem.name] === undefined) {
added.push(newItem);
}
}
return {
added,
persisted,
removed,
};
}

View File

@@ -0,0 +1,519 @@
import { inspect } from '../jsutils/inspect.mjs';
import { invariant } from '../jsutils/invariant.mjs';
import { keyMap } from '../jsutils/keyMap.mjs';
import { print } from '../language/printer.mjs';
import {
isEnumType,
isInputObjectType,
isInterfaceType,
isListType,
isNamedType,
isNonNullType,
isObjectType,
isRequiredArgument,
isRequiredInputField,
isScalarType,
isUnionType,
} from '../type/definition.mjs';
import { isSpecifiedScalarType } from '../type/scalars.mjs';
import { astFromValue } from './astFromValue.mjs';
import { sortValueNode } from './sortValueNode.mjs';
var BreakingChangeType;
(function (BreakingChangeType) {
BreakingChangeType['TYPE_REMOVED'] = 'TYPE_REMOVED';
BreakingChangeType['TYPE_CHANGED_KIND'] = 'TYPE_CHANGED_KIND';
BreakingChangeType['TYPE_REMOVED_FROM_UNION'] = 'TYPE_REMOVED_FROM_UNION';
BreakingChangeType['VALUE_REMOVED_FROM_ENUM'] = 'VALUE_REMOVED_FROM_ENUM';
BreakingChangeType['REQUIRED_INPUT_FIELD_ADDED'] =
'REQUIRED_INPUT_FIELD_ADDED';
BreakingChangeType['IMPLEMENTED_INTERFACE_REMOVED'] =
'IMPLEMENTED_INTERFACE_REMOVED';
BreakingChangeType['FIELD_REMOVED'] = 'FIELD_REMOVED';
BreakingChangeType['FIELD_CHANGED_KIND'] = 'FIELD_CHANGED_KIND';
BreakingChangeType['REQUIRED_ARG_ADDED'] = 'REQUIRED_ARG_ADDED';
BreakingChangeType['ARG_REMOVED'] = 'ARG_REMOVED';
BreakingChangeType['ARG_CHANGED_KIND'] = 'ARG_CHANGED_KIND';
BreakingChangeType['DIRECTIVE_REMOVED'] = 'DIRECTIVE_REMOVED';
BreakingChangeType['DIRECTIVE_ARG_REMOVED'] = 'DIRECTIVE_ARG_REMOVED';
BreakingChangeType['REQUIRED_DIRECTIVE_ARG_ADDED'] =
'REQUIRED_DIRECTIVE_ARG_ADDED';
BreakingChangeType['DIRECTIVE_REPEATABLE_REMOVED'] =
'DIRECTIVE_REPEATABLE_REMOVED';
BreakingChangeType['DIRECTIVE_LOCATION_REMOVED'] =
'DIRECTIVE_LOCATION_REMOVED';
})(BreakingChangeType || (BreakingChangeType = {}));
export { BreakingChangeType };
var DangerousChangeType;
(function (DangerousChangeType) {
DangerousChangeType['VALUE_ADDED_TO_ENUM'] = 'VALUE_ADDED_TO_ENUM';
DangerousChangeType['TYPE_ADDED_TO_UNION'] = 'TYPE_ADDED_TO_UNION';
DangerousChangeType['OPTIONAL_INPUT_FIELD_ADDED'] =
'OPTIONAL_INPUT_FIELD_ADDED';
DangerousChangeType['OPTIONAL_ARG_ADDED'] = 'OPTIONAL_ARG_ADDED';
DangerousChangeType['IMPLEMENTED_INTERFACE_ADDED'] =
'IMPLEMENTED_INTERFACE_ADDED';
DangerousChangeType['ARG_DEFAULT_VALUE_CHANGE'] = 'ARG_DEFAULT_VALUE_CHANGE';
})(DangerousChangeType || (DangerousChangeType = {}));
export { DangerousChangeType };
/**
* Given two schemas, returns an Array containing descriptions of all the types
* of breaking changes covered by the other functions down below.
*/
export function findBreakingChanges(oldSchema, newSchema) {
// @ts-expect-error
return findSchemaChanges(oldSchema, newSchema).filter(
(change) => change.type in BreakingChangeType,
);
}
/**
* Given two schemas, returns an Array containing descriptions of all the types
* of potentially dangerous changes covered by the other functions down below.
*/
export function findDangerousChanges(oldSchema, newSchema) {
// @ts-expect-error
return findSchemaChanges(oldSchema, newSchema).filter(
(change) => change.type in DangerousChangeType,
);
}
function findSchemaChanges(oldSchema, newSchema) {
return [
...findTypeChanges(oldSchema, newSchema),
...findDirectiveChanges(oldSchema, newSchema),
];
}
function findDirectiveChanges(oldSchema, newSchema) {
const schemaChanges = [];
const directivesDiff = diff(
oldSchema.getDirectives(),
newSchema.getDirectives(),
);
for (const oldDirective of directivesDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.DIRECTIVE_REMOVED,
description: `${oldDirective.name} was removed.`,
});
}
for (const [oldDirective, newDirective] of directivesDiff.persisted) {
const argsDiff = diff(oldDirective.args, newDirective.args);
for (const newArg of argsDiff.added) {
if (isRequiredArgument(newArg)) {
schemaChanges.push({
type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED,
description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.`,
});
}
}
for (const oldArg of argsDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.DIRECTIVE_ARG_REMOVED,
description: `${oldArg.name} was removed from ${oldDirective.name}.`,
});
}
if (oldDirective.isRepeatable && !newDirective.isRepeatable) {
schemaChanges.push({
type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED,
description: `Repeatable flag was removed from ${oldDirective.name}.`,
});
}
for (const location of oldDirective.locations) {
if (!newDirective.locations.includes(location)) {
schemaChanges.push({
type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED,
description: `${location} was removed from ${oldDirective.name}.`,
});
}
}
}
return schemaChanges;
}
function findTypeChanges(oldSchema, newSchema) {
const schemaChanges = [];
const typesDiff = diff(
Object.values(oldSchema.getTypeMap()),
Object.values(newSchema.getTypeMap()),
);
for (const oldType of typesDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.TYPE_REMOVED,
description: isSpecifiedScalarType(oldType)
? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.`
: `${oldType.name} was removed.`,
});
}
for (const [oldType, newType] of typesDiff.persisted) {
if (isEnumType(oldType) && isEnumType(newType)) {
schemaChanges.push(...findEnumTypeChanges(oldType, newType));
} else if (isUnionType(oldType) && isUnionType(newType)) {
schemaChanges.push(...findUnionTypeChanges(oldType, newType));
} else if (isInputObjectType(oldType) && isInputObjectType(newType)) {
schemaChanges.push(...findInputObjectTypeChanges(oldType, newType));
} else if (isObjectType(oldType) && isObjectType(newType)) {
schemaChanges.push(
...findFieldChanges(oldType, newType),
...findImplementedInterfacesChanges(oldType, newType),
);
} else if (isInterfaceType(oldType) && isInterfaceType(newType)) {
schemaChanges.push(
...findFieldChanges(oldType, newType),
...findImplementedInterfacesChanges(oldType, newType),
);
} else if (oldType.constructor !== newType.constructor) {
schemaChanges.push({
type: BreakingChangeType.TYPE_CHANGED_KIND,
description:
`${oldType.name} changed from ` +
`${typeKindName(oldType)} to ${typeKindName(newType)}.`,
});
}
}
return schemaChanges;
}
function findInputObjectTypeChanges(oldType, newType) {
const schemaChanges = [];
const fieldsDiff = diff(
Object.values(oldType.getFields()),
Object.values(newType.getFields()),
);
for (const newField of fieldsDiff.added) {
if (isRequiredInputField(newField)) {
schemaChanges.push({
type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED,
description: `A required field ${newField.name} on input type ${oldType.name} was added.`,
});
} else {
schemaChanges.push({
type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED,
description: `An optional field ${newField.name} on input type ${oldType.name} was added.`,
});
}
}
for (const oldField of fieldsDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.FIELD_REMOVED,
description: `${oldType.name}.${oldField.name} was removed.`,
});
}
for (const [oldField, newField] of fieldsDiff.persisted) {
const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(
oldField.type,
newField.type,
);
if (!isSafe) {
schemaChanges.push({
type: BreakingChangeType.FIELD_CHANGED_KIND,
description:
`${oldType.name}.${oldField.name} changed type from ` +
`${String(oldField.type)} to ${String(newField.type)}.`,
});
}
}
return schemaChanges;
}
function findUnionTypeChanges(oldType, newType) {
const schemaChanges = [];
const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes());
for (const newPossibleType of possibleTypesDiff.added) {
schemaChanges.push({
type: DangerousChangeType.TYPE_ADDED_TO_UNION,
description: `${newPossibleType.name} was added to union type ${oldType.name}.`,
});
}
for (const oldPossibleType of possibleTypesDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,
description: `${oldPossibleType.name} was removed from union type ${oldType.name}.`,
});
}
return schemaChanges;
}
function findEnumTypeChanges(oldType, newType) {
const schemaChanges = [];
const valuesDiff = diff(oldType.getValues(), newType.getValues());
for (const newValue of valuesDiff.added) {
schemaChanges.push({
type: DangerousChangeType.VALUE_ADDED_TO_ENUM,
description: `${newValue.name} was added to enum type ${oldType.name}.`,
});
}
for (const oldValue of valuesDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,
description: `${oldValue.name} was removed from enum type ${oldType.name}.`,
});
}
return schemaChanges;
}
function findImplementedInterfacesChanges(oldType, newType) {
const schemaChanges = [];
const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces());
for (const newInterface of interfacesDiff.added) {
schemaChanges.push({
type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED,
description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.`,
});
}
for (const oldInterface of interfacesDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED,
description: `${oldType.name} no longer implements interface ${oldInterface.name}.`,
});
}
return schemaChanges;
}
function findFieldChanges(oldType, newType) {
const schemaChanges = [];
const fieldsDiff = diff(
Object.values(oldType.getFields()),
Object.values(newType.getFields()),
);
for (const oldField of fieldsDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.FIELD_REMOVED,
description: `${oldType.name}.${oldField.name} was removed.`,
});
}
for (const [oldField, newField] of fieldsDiff.persisted) {
schemaChanges.push(...findArgChanges(oldType, oldField, newField));
const isSafe = isChangeSafeForObjectOrInterfaceField(
oldField.type,
newField.type,
);
if (!isSafe) {
schemaChanges.push({
type: BreakingChangeType.FIELD_CHANGED_KIND,
description:
`${oldType.name}.${oldField.name} changed type from ` +
`${String(oldField.type)} to ${String(newField.type)}.`,
});
}
}
return schemaChanges;
}
function findArgChanges(oldType, oldField, newField) {
const schemaChanges = [];
const argsDiff = diff(oldField.args, newField.args);
for (const oldArg of argsDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.ARG_REMOVED,
description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.`,
});
}
for (const [oldArg, newArg] of argsDiff.persisted) {
const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(
oldArg.type,
newArg.type,
);
if (!isSafe) {
schemaChanges.push({
type: BreakingChangeType.ARG_CHANGED_KIND,
description:
`${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` +
`${String(oldArg.type)} to ${String(newArg.type)}.`,
});
} else if (oldArg.defaultValue !== undefined) {
if (newArg.defaultValue === undefined) {
schemaChanges.push({
type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,
description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.`,
});
} else {
// Since we looking only for client's observable changes we should
// compare default values in the same representation as they are
// represented inside introspection.
const oldValueStr = stringifyValue(oldArg.defaultValue, oldArg.type);
const newValueStr = stringifyValue(newArg.defaultValue, newArg.type);
if (oldValueStr !== newValueStr) {
schemaChanges.push({
type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,
description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.`,
});
}
}
}
}
for (const newArg of argsDiff.added) {
if (isRequiredArgument(newArg)) {
schemaChanges.push({
type: BreakingChangeType.REQUIRED_ARG_ADDED,
description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`,
});
} else {
schemaChanges.push({
type: DangerousChangeType.OPTIONAL_ARG_ADDED,
description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`,
});
}
}
return schemaChanges;
}
function isChangeSafeForObjectOrInterfaceField(oldType, newType) {
if (isListType(oldType)) {
return (
// if they're both lists, make sure the underlying types are compatible
(isListType(newType) &&
isChangeSafeForObjectOrInterfaceField(
oldType.ofType,
newType.ofType,
)) || // moving from nullable to non-null of the same underlying type is safe
(isNonNullType(newType) &&
isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType))
);
}
if (isNonNullType(oldType)) {
// if they're both non-null, make sure the underlying types are compatible
return (
isNonNullType(newType) &&
isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType)
);
}
return (
// if they're both named types, see if their names are equivalent
(isNamedType(newType) && oldType.name === newType.name) || // moving from nullable to non-null of the same underlying type is safe
(isNonNullType(newType) &&
isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType))
);
}
function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) {
if (isListType(oldType)) {
// if they're both lists, make sure the underlying types are compatible
return (
isListType(newType) &&
isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType)
);
}
if (isNonNullType(oldType)) {
return (
// if they're both non-null, make sure the underlying types are
// compatible
(isNonNullType(newType) &&
isChangeSafeForInputObjectFieldOrFieldArg(
oldType.ofType,
newType.ofType,
)) || // moving from non-null to nullable of the same underlying type is safe
(!isNonNullType(newType) &&
isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType))
);
} // if they're both named types, see if their names are equivalent
return isNamedType(newType) && oldType.name === newType.name;
}
function typeKindName(type) {
if (isScalarType(type)) {
return 'a Scalar type';
}
if (isObjectType(type)) {
return 'an Object type';
}
if (isInterfaceType(type)) {
return 'an Interface type';
}
if (isUnionType(type)) {
return 'a Union type';
}
if (isEnumType(type)) {
return 'an Enum type';
}
if (isInputObjectType(type)) {
return 'an Input type';
}
/* c8 ignore next 3 */
// Not reachable, all possible types have been considered.
false || invariant(false, 'Unexpected type: ' + inspect(type));
}
function stringifyValue(value, type) {
const ast = astFromValue(value, type);
ast != null || invariant(false);
return print(sortValueNode(ast));
}
function diff(oldArray, newArray) {
const added = [];
const removed = [];
const persisted = [];
const oldMap = keyMap(oldArray, ({ name }) => name);
const newMap = keyMap(newArray, ({ name }) => name);
for (const oldItem of oldArray) {
const newItem = newMap[oldItem.name];
if (newItem === undefined) {
removed.push(oldItem);
} else {
persisted.push([oldItem, newItem]);
}
}
for (const newItem of newArray) {
if (oldMap[newItem.name] === undefined) {
added.push(newItem);
}
}
return {
added,
persisted,
removed,
};
}

View File

@@ -0,0 +1,182 @@
import type { Maybe } from '../jsutils/Maybe';
import type { DirectiveLocation } from '../language/directiveLocation';
export interface IntrospectionOptions {
/**
* Whether to include descriptions in the introspection result.
* Default: true
*/
descriptions?: boolean;
/**
* Whether to include `specifiedByURL` in the introspection result.
* Default: false
*/
specifiedByUrl?: boolean;
/**
* Whether to include `isRepeatable` flag on directives.
* Default: false
*/
directiveIsRepeatable?: boolean;
/**
* Whether to include `description` field on schema.
* Default: false
*/
schemaDescription?: boolean;
/**
* Whether target GraphQL server support deprecation of input values.
* Default: false
*/
inputValueDeprecation?: boolean;
}
/**
* Produce the GraphQL query recommended for a full schema introspection.
* Accepts optional IntrospectionOptions.
*/
export declare function getIntrospectionQuery(
options?: IntrospectionOptions,
): string;
export interface IntrospectionQuery {
readonly __schema: IntrospectionSchema;
}
export interface IntrospectionSchema {
readonly description?: Maybe<string>;
readonly queryType: IntrospectionNamedTypeRef<IntrospectionObjectType>;
readonly mutationType: Maybe<
IntrospectionNamedTypeRef<IntrospectionObjectType>
>;
readonly subscriptionType: Maybe<
IntrospectionNamedTypeRef<IntrospectionObjectType>
>;
readonly types: ReadonlyArray<IntrospectionType>;
readonly directives: ReadonlyArray<IntrospectionDirective>;
}
export declare type IntrospectionType =
| IntrospectionScalarType
| IntrospectionObjectType
| IntrospectionInterfaceType
| IntrospectionUnionType
| IntrospectionEnumType
| IntrospectionInputObjectType;
export declare type IntrospectionOutputType =
| IntrospectionScalarType
| IntrospectionObjectType
| IntrospectionInterfaceType
| IntrospectionUnionType
| IntrospectionEnumType;
export declare type IntrospectionInputType =
| IntrospectionScalarType
| IntrospectionEnumType
| IntrospectionInputObjectType;
export interface IntrospectionScalarType {
readonly kind: 'SCALAR';
readonly name: string;
readonly description?: Maybe<string>;
readonly specifiedByURL?: Maybe<string>;
}
export interface IntrospectionObjectType {
readonly kind: 'OBJECT';
readonly name: string;
readonly description?: Maybe<string>;
readonly fields: ReadonlyArray<IntrospectionField>;
readonly interfaces: ReadonlyArray<
IntrospectionNamedTypeRef<IntrospectionInterfaceType>
>;
}
export interface IntrospectionInterfaceType {
readonly kind: 'INTERFACE';
readonly name: string;
readonly description?: Maybe<string>;
readonly fields: ReadonlyArray<IntrospectionField>;
readonly interfaces: ReadonlyArray<
IntrospectionNamedTypeRef<IntrospectionInterfaceType>
>;
readonly possibleTypes: ReadonlyArray<
IntrospectionNamedTypeRef<IntrospectionObjectType>
>;
}
export interface IntrospectionUnionType {
readonly kind: 'UNION';
readonly name: string;
readonly description?: Maybe<string>;
readonly possibleTypes: ReadonlyArray<
IntrospectionNamedTypeRef<IntrospectionObjectType>
>;
}
export interface IntrospectionEnumType {
readonly kind: 'ENUM';
readonly name: string;
readonly description?: Maybe<string>;
readonly enumValues: ReadonlyArray<IntrospectionEnumValue>;
}
export interface IntrospectionInputObjectType {
readonly kind: 'INPUT_OBJECT';
readonly name: string;
readonly description?: Maybe<string>;
readonly inputFields: ReadonlyArray<IntrospectionInputValue>;
}
export interface IntrospectionListTypeRef<
T extends IntrospectionTypeRef = IntrospectionTypeRef,
> {
readonly kind: 'LIST';
readonly ofType: T;
}
export interface IntrospectionNonNullTypeRef<
T extends IntrospectionTypeRef = IntrospectionTypeRef,
> {
readonly kind: 'NON_NULL';
readonly ofType: T;
}
export declare type IntrospectionTypeRef =
| IntrospectionNamedTypeRef
| IntrospectionListTypeRef
| IntrospectionNonNullTypeRef<
IntrospectionNamedTypeRef | IntrospectionListTypeRef
>;
export declare type IntrospectionOutputTypeRef =
| IntrospectionNamedTypeRef<IntrospectionOutputType>
| IntrospectionListTypeRef<IntrospectionOutputTypeRef>
| IntrospectionNonNullTypeRef<
| IntrospectionNamedTypeRef<IntrospectionOutputType>
| IntrospectionListTypeRef<IntrospectionOutputTypeRef>
>;
export declare type IntrospectionInputTypeRef =
| IntrospectionNamedTypeRef<IntrospectionInputType>
| IntrospectionListTypeRef<IntrospectionInputTypeRef>
| IntrospectionNonNullTypeRef<
| IntrospectionNamedTypeRef<IntrospectionInputType>
| IntrospectionListTypeRef<IntrospectionInputTypeRef>
>;
export interface IntrospectionNamedTypeRef<
T extends IntrospectionType = IntrospectionType,
> {
readonly kind: T['kind'];
readonly name: string;
}
export interface IntrospectionField {
readonly name: string;
readonly description?: Maybe<string>;
readonly args: ReadonlyArray<IntrospectionInputValue>;
readonly type: IntrospectionOutputTypeRef;
readonly isDeprecated: boolean;
readonly deprecationReason: Maybe<string>;
}
export interface IntrospectionInputValue {
readonly name: string;
readonly description?: Maybe<string>;
readonly type: IntrospectionInputTypeRef;
readonly defaultValue: Maybe<string>;
readonly isDeprecated?: boolean;
readonly deprecationReason?: Maybe<string>;
}
export interface IntrospectionEnumValue {
readonly name: string;
readonly description?: Maybe<string>;
readonly isDeprecated: boolean;
readonly deprecationReason: Maybe<string>;
}
export interface IntrospectionDirective {
readonly name: string;
readonly description?: Maybe<string>;
readonly isRepeatable?: boolean;
readonly locations: ReadonlyArray<DirectiveLocation>;
readonly args: ReadonlyArray<IntrospectionInputValue>;
}

View File

@@ -0,0 +1,142 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.getIntrospectionQuery = getIntrospectionQuery;
/**
* Produce the GraphQL query recommended for a full schema introspection.
* Accepts optional IntrospectionOptions.
*/
function getIntrospectionQuery(options) {
const optionsWithDefault = {
descriptions: true,
specifiedByUrl: false,
directiveIsRepeatable: false,
schemaDescription: false,
inputValueDeprecation: false,
...options,
};
const descriptions = optionsWithDefault.descriptions ? 'description' : '';
const specifiedByUrl = optionsWithDefault.specifiedByUrl
? 'specifiedByURL'
: '';
const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable
? 'isRepeatable'
: '';
const schemaDescription = optionsWithDefault.schemaDescription
? descriptions
: '';
function inputDeprecation(str) {
return optionsWithDefault.inputValueDeprecation ? str : '';
}
return `
query IntrospectionQuery {
__schema {
${schemaDescription}
queryType { name }
mutationType { name }
subscriptionType { name }
types {
...FullType
}
directives {
name
${descriptions}
${directiveIsRepeatable}
locations
args${inputDeprecation('(includeDeprecated: true)')} {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
${descriptions}
${specifiedByUrl}
fields(includeDeprecated: true) {
name
${descriptions}
args${inputDeprecation('(includeDeprecated: true)')} {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields${inputDeprecation('(includeDeprecated: true)')} {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
${descriptions}
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
${descriptions}
type { ...TypeRef }
defaultValue
${inputDeprecation('isDeprecated')}
${inputDeprecation('deprecationReason')}
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
}
}
`;
}

View File

@@ -0,0 +1,135 @@
/**
* Produce the GraphQL query recommended for a full schema introspection.
* Accepts optional IntrospectionOptions.
*/
export function getIntrospectionQuery(options) {
const optionsWithDefault = {
descriptions: true,
specifiedByUrl: false,
directiveIsRepeatable: false,
schemaDescription: false,
inputValueDeprecation: false,
...options,
};
const descriptions = optionsWithDefault.descriptions ? 'description' : '';
const specifiedByUrl = optionsWithDefault.specifiedByUrl
? 'specifiedByURL'
: '';
const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable
? 'isRepeatable'
: '';
const schemaDescription = optionsWithDefault.schemaDescription
? descriptions
: '';
function inputDeprecation(str) {
return optionsWithDefault.inputValueDeprecation ? str : '';
}
return `
query IntrospectionQuery {
__schema {
${schemaDescription}
queryType { name }
mutationType { name }
subscriptionType { name }
types {
...FullType
}
directives {
name
${descriptions}
${directiveIsRepeatable}
locations
args${inputDeprecation('(includeDeprecated: true)')} {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
${descriptions}
${specifiedByUrl}
fields(includeDeprecated: true) {
name
${descriptions}
args${inputDeprecation('(includeDeprecated: true)')} {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields${inputDeprecation('(includeDeprecated: true)')} {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
${descriptions}
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
${descriptions}
type { ...TypeRef }
defaultValue
${inputDeprecation('isDeprecated')}
${inputDeprecation('deprecationReason')}
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
}
}
`;
}

View File

@@ -0,0 +1,11 @@
import type { Maybe } from '../jsutils/Maybe';
import type { DocumentNode, OperationDefinitionNode } from '../language/ast';
/**
* Returns an operation AST given a document AST and optionally an operation
* name. If a name is not provided, an operation is only returned if only one is
* provided in the document.
*/
export declare function getOperationAST(
documentAST: DocumentNode,
operationName?: Maybe<string>,
): Maybe<OperationDefinitionNode>;

View File

@@ -0,0 +1,43 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.getOperationAST = getOperationAST;
var _kinds = require('../language/kinds.js');
/**
* Returns an operation AST given a document AST and optionally an operation
* name. If a name is not provided, an operation is only returned if only one is
* provided in the document.
*/
function getOperationAST(documentAST, operationName) {
let operation = null;
for (const definition of documentAST.definitions) {
if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) {
var _definition$name;
if (operationName == null) {
// If no operation name was provided, only return an Operation if there
// is one defined in the document. Upon encountering the second, return
// null.
if (operation) {
return null;
}
operation = definition;
} else if (
((_definition$name = definition.name) === null ||
_definition$name === void 0
? void 0
: _definition$name.value) === operationName
) {
return definition;
}
}
}
return operation;
}

View File

@@ -0,0 +1,36 @@
import { Kind } from '../language/kinds.mjs';
/**
* Returns an operation AST given a document AST and optionally an operation
* name. If a name is not provided, an operation is only returned if only one is
* provided in the document.
*/
export function getOperationAST(documentAST, operationName) {
let operation = null;
for (const definition of documentAST.definitions) {
if (definition.kind === Kind.OPERATION_DEFINITION) {
var _definition$name;
if (operationName == null) {
// If no operation name was provided, only return an Operation if there
// is one defined in the document. Upon encountering the second, return
// null.
if (operation) {
return null;
}
operation = definition;
} else if (
((_definition$name = definition.name) === null ||
_definition$name === void 0
? void 0
: _definition$name.value) === operationName
) {
return definition;
}
}
}
return operation;
}

View File

@@ -0,0 +1,15 @@
import type {
OperationDefinitionNode,
OperationTypeDefinitionNode,
} from '../language/ast';
import type { GraphQLObjectType } from '../type/definition';
import type { GraphQLSchema } from '../type/schema';
/**
* Extracts the root type of the operation from the schema.
*
* @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17
*/
export declare function getOperationRootType(
schema: GraphQLSchema,
operation: OperationDefinitionNode | OperationTypeDefinitionNode,
): GraphQLObjectType;

View File

@@ -0,0 +1,67 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.getOperationRootType = getOperationRootType;
var _GraphQLError = require('../error/GraphQLError.js');
/**
* Extracts the root type of the operation from the schema.
*
* @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17
*/
function getOperationRootType(schema, operation) {
if (operation.operation === 'query') {
const queryType = schema.getQueryType();
if (!queryType) {
throw new _GraphQLError.GraphQLError(
'Schema does not define the required query root type.',
{
nodes: operation,
},
);
}
return queryType;
}
if (operation.operation === 'mutation') {
const mutationType = schema.getMutationType();
if (!mutationType) {
throw new _GraphQLError.GraphQLError(
'Schema is not configured for mutations.',
{
nodes: operation,
},
);
}
return mutationType;
}
if (operation.operation === 'subscription') {
const subscriptionType = schema.getSubscriptionType();
if (!subscriptionType) {
throw new _GraphQLError.GraphQLError(
'Schema is not configured for subscriptions.',
{
nodes: operation,
},
);
}
return subscriptionType;
}
throw new _GraphQLError.GraphQLError(
'Can only have query, mutation and subscription operations.',
{
nodes: operation,
},
);
}

View File

@@ -0,0 +1,54 @@
import { GraphQLError } from '../error/GraphQLError.mjs';
/**
* Extracts the root type of the operation from the schema.
*
* @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17
*/
export function getOperationRootType(schema, operation) {
if (operation.operation === 'query') {
const queryType = schema.getQueryType();
if (!queryType) {
throw new GraphQLError(
'Schema does not define the required query root type.',
{
nodes: operation,
},
);
}
return queryType;
}
if (operation.operation === 'mutation') {
const mutationType = schema.getMutationType();
if (!mutationType) {
throw new GraphQLError('Schema is not configured for mutations.', {
nodes: operation,
});
}
return mutationType;
}
if (operation.operation === 'subscription') {
const subscriptionType = schema.getSubscriptionType();
if (!subscriptionType) {
throw new GraphQLError('Schema is not configured for subscriptions.', {
nodes: operation,
});
}
return subscriptionType;
}
throw new GraphQLError(
'Can only have query, mutation and subscription operations.',
{
nodes: operation,
},
);
}

View File

@@ -0,0 +1,61 @@
export { getIntrospectionQuery } from './getIntrospectionQuery';
export type {
IntrospectionOptions,
IntrospectionQuery,
IntrospectionSchema,
IntrospectionType,
IntrospectionInputType,
IntrospectionOutputType,
IntrospectionScalarType,
IntrospectionObjectType,
IntrospectionInterfaceType,
IntrospectionUnionType,
IntrospectionEnumType,
IntrospectionInputObjectType,
IntrospectionTypeRef,
IntrospectionInputTypeRef,
IntrospectionOutputTypeRef,
IntrospectionNamedTypeRef,
IntrospectionListTypeRef,
IntrospectionNonNullTypeRef,
IntrospectionField,
IntrospectionInputValue,
IntrospectionEnumValue,
IntrospectionDirective,
} from './getIntrospectionQuery';
export { getOperationAST } from './getOperationAST';
export { getOperationRootType } from './getOperationRootType';
export { introspectionFromSchema } from './introspectionFromSchema';
export { buildClientSchema } from './buildClientSchema';
export { buildASTSchema, buildSchema } from './buildASTSchema';
export type { BuildSchemaOptions } from './buildASTSchema';
export { extendSchema } from './extendSchema';
export { lexicographicSortSchema } from './lexicographicSortSchema';
export {
printSchema,
printType,
printIntrospectionSchema,
} from './printSchema';
export { typeFromAST } from './typeFromAST';
export { valueFromAST } from './valueFromAST';
export { valueFromASTUntyped } from './valueFromASTUntyped';
export { astFromValue } from './astFromValue';
export { TypeInfo, visitWithTypeInfo } from './TypeInfo';
export { coerceInputValue } from './coerceInputValue';
export { concatAST } from './concatAST';
export { separateOperations } from './separateOperations';
export { stripIgnoredCharacters } from './stripIgnoredCharacters';
export {
isEqualType,
isTypeSubTypeOf,
doTypesOverlap,
} from './typeComparators';
export { assertValidName, isValidNameError } from './assertValidName';
export {
BreakingChangeType,
DangerousChangeType,
findBreakingChanges,
findDangerousChanges,
} from './findBreakingChanges';
export type { BreakingChange, DangerousChange } from './findBreakingChanges';
export type { TypedQueryDocumentNode } from './typedQueryDocumentNode';

View File

@@ -0,0 +1,233 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
Object.defineProperty(exports, 'BreakingChangeType', {
enumerable: true,
get: function () {
return _findBreakingChanges.BreakingChangeType;
},
});
Object.defineProperty(exports, 'DangerousChangeType', {
enumerable: true,
get: function () {
return _findBreakingChanges.DangerousChangeType;
},
});
Object.defineProperty(exports, 'TypeInfo', {
enumerable: true,
get: function () {
return _TypeInfo.TypeInfo;
},
});
Object.defineProperty(exports, 'assertValidName', {
enumerable: true,
get: function () {
return _assertValidName.assertValidName;
},
});
Object.defineProperty(exports, 'astFromValue', {
enumerable: true,
get: function () {
return _astFromValue.astFromValue;
},
});
Object.defineProperty(exports, 'buildASTSchema', {
enumerable: true,
get: function () {
return _buildASTSchema.buildASTSchema;
},
});
Object.defineProperty(exports, 'buildClientSchema', {
enumerable: true,
get: function () {
return _buildClientSchema.buildClientSchema;
},
});
Object.defineProperty(exports, 'buildSchema', {
enumerable: true,
get: function () {
return _buildASTSchema.buildSchema;
},
});
Object.defineProperty(exports, 'coerceInputValue', {
enumerable: true,
get: function () {
return _coerceInputValue.coerceInputValue;
},
});
Object.defineProperty(exports, 'concatAST', {
enumerable: true,
get: function () {
return _concatAST.concatAST;
},
});
Object.defineProperty(exports, 'doTypesOverlap', {
enumerable: true,
get: function () {
return _typeComparators.doTypesOverlap;
},
});
Object.defineProperty(exports, 'extendSchema', {
enumerable: true,
get: function () {
return _extendSchema.extendSchema;
},
});
Object.defineProperty(exports, 'findBreakingChanges', {
enumerable: true,
get: function () {
return _findBreakingChanges.findBreakingChanges;
},
});
Object.defineProperty(exports, 'findDangerousChanges', {
enumerable: true,
get: function () {
return _findBreakingChanges.findDangerousChanges;
},
});
Object.defineProperty(exports, 'getIntrospectionQuery', {
enumerable: true,
get: function () {
return _getIntrospectionQuery.getIntrospectionQuery;
},
});
Object.defineProperty(exports, 'getOperationAST', {
enumerable: true,
get: function () {
return _getOperationAST.getOperationAST;
},
});
Object.defineProperty(exports, 'getOperationRootType', {
enumerable: true,
get: function () {
return _getOperationRootType.getOperationRootType;
},
});
Object.defineProperty(exports, 'introspectionFromSchema', {
enumerable: true,
get: function () {
return _introspectionFromSchema.introspectionFromSchema;
},
});
Object.defineProperty(exports, 'isEqualType', {
enumerable: true,
get: function () {
return _typeComparators.isEqualType;
},
});
Object.defineProperty(exports, 'isTypeSubTypeOf', {
enumerable: true,
get: function () {
return _typeComparators.isTypeSubTypeOf;
},
});
Object.defineProperty(exports, 'isValidNameError', {
enumerable: true,
get: function () {
return _assertValidName.isValidNameError;
},
});
Object.defineProperty(exports, 'lexicographicSortSchema', {
enumerable: true,
get: function () {
return _lexicographicSortSchema.lexicographicSortSchema;
},
});
Object.defineProperty(exports, 'printIntrospectionSchema', {
enumerable: true,
get: function () {
return _printSchema.printIntrospectionSchema;
},
});
Object.defineProperty(exports, 'printSchema', {
enumerable: true,
get: function () {
return _printSchema.printSchema;
},
});
Object.defineProperty(exports, 'printType', {
enumerable: true,
get: function () {
return _printSchema.printType;
},
});
Object.defineProperty(exports, 'separateOperations', {
enumerable: true,
get: function () {
return _separateOperations.separateOperations;
},
});
Object.defineProperty(exports, 'stripIgnoredCharacters', {
enumerable: true,
get: function () {
return _stripIgnoredCharacters.stripIgnoredCharacters;
},
});
Object.defineProperty(exports, 'typeFromAST', {
enumerable: true,
get: function () {
return _typeFromAST.typeFromAST;
},
});
Object.defineProperty(exports, 'valueFromAST', {
enumerable: true,
get: function () {
return _valueFromAST.valueFromAST;
},
});
Object.defineProperty(exports, 'valueFromASTUntyped', {
enumerable: true,
get: function () {
return _valueFromASTUntyped.valueFromASTUntyped;
},
});
Object.defineProperty(exports, 'visitWithTypeInfo', {
enumerable: true,
get: function () {
return _TypeInfo.visitWithTypeInfo;
},
});
var _getIntrospectionQuery = require('./getIntrospectionQuery.js');
var _getOperationAST = require('./getOperationAST.js');
var _getOperationRootType = require('./getOperationRootType.js');
var _introspectionFromSchema = require('./introspectionFromSchema.js');
var _buildClientSchema = require('./buildClientSchema.js');
var _buildASTSchema = require('./buildASTSchema.js');
var _extendSchema = require('./extendSchema.js');
var _lexicographicSortSchema = require('./lexicographicSortSchema.js');
var _printSchema = require('./printSchema.js');
var _typeFromAST = require('./typeFromAST.js');
var _valueFromAST = require('./valueFromAST.js');
var _valueFromASTUntyped = require('./valueFromASTUntyped.js');
var _astFromValue = require('./astFromValue.js');
var _TypeInfo = require('./TypeInfo.js');
var _coerceInputValue = require('./coerceInputValue.js');
var _concatAST = require('./concatAST.js');
var _separateOperations = require('./separateOperations.js');
var _stripIgnoredCharacters = require('./stripIgnoredCharacters.js');
var _typeComparators = require('./typeComparators.js');
var _assertValidName = require('./assertValidName.js');
var _findBreakingChanges = require('./findBreakingChanges.js');

View File

@@ -0,0 +1,55 @@
// Produce the GraphQL query recommended for a full schema introspection.
export { getIntrospectionQuery } from './getIntrospectionQuery.mjs';
// Gets the target Operation from a Document.
export { getOperationAST } from './getOperationAST.mjs'; // Gets the Type for the target Operation AST.
export { getOperationRootType } from './getOperationRootType.mjs'; // Convert a GraphQLSchema to an IntrospectionQuery.
export { introspectionFromSchema } from './introspectionFromSchema.mjs'; // Build a GraphQLSchema from an introspection result.
export { buildClientSchema } from './buildClientSchema.mjs'; // Build a GraphQLSchema from GraphQL Schema language.
export { buildASTSchema, buildSchema } from './buildASTSchema.mjs';
// Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST.
export { extendSchema } from './extendSchema.mjs'; // Sort a GraphQLSchema.
export { lexicographicSortSchema } from './lexicographicSortSchema.mjs'; // Print a GraphQLSchema to GraphQL Schema language.
export {
printSchema,
printType,
printIntrospectionSchema,
} from './printSchema.mjs'; // Create a GraphQLType from a GraphQL language AST.
export { typeFromAST } from './typeFromAST.mjs'; // Create a JavaScript value from a GraphQL language AST with a type.
export { valueFromAST } from './valueFromAST.mjs'; // Create a JavaScript value from a GraphQL language AST without a type.
export { valueFromASTUntyped } from './valueFromASTUntyped.mjs'; // Create a GraphQL language AST from a JavaScript value.
export { astFromValue } from './astFromValue.mjs'; // A helper to use within recursive-descent visitors which need to be aware of the GraphQL type system.
export { TypeInfo, visitWithTypeInfo } from './TypeInfo.mjs'; // Coerces a JavaScript value to a GraphQL type, or produces errors.
export { coerceInputValue } from './coerceInputValue.mjs'; // Concatenates multiple AST together.
export { concatAST } from './concatAST.mjs'; // Separates an AST into an AST per Operation.
export { separateOperations } from './separateOperations.mjs'; // Strips characters that are not significant to the validity or execution of a GraphQL document.
export { stripIgnoredCharacters } from './stripIgnoredCharacters.mjs'; // Comparators for types
export {
isEqualType,
isTypeSubTypeOf,
doTypesOverlap,
} from './typeComparators.mjs'; // Asserts that a string is a valid GraphQL name
export { assertValidName, isValidNameError } from './assertValidName.mjs'; // Compares two GraphQLSchemas and detects breaking changes.
export {
BreakingChangeType,
DangerousChangeType,
findBreakingChanges,
findDangerousChanges,
} from './findBreakingChanges.mjs';

View File

@@ -0,0 +1,18 @@
import type { GraphQLSchema } from '../type/schema';
import type {
IntrospectionOptions,
IntrospectionQuery,
} from './getIntrospectionQuery';
/**
* Build an IntrospectionQuery from a GraphQLSchema
*
* IntrospectionQuery is useful for utilities that care about type and field
* relationships, but do not need to traverse through those relationships.
*
* This is the inverse of buildClientSchema. The primary use case is outside
* of the server context, for instance when doing schema comparisons.
*/
export declare function introspectionFromSchema(
schema: GraphQLSchema,
options?: IntrospectionOptions,
): IntrospectionQuery;

View File

@@ -0,0 +1,42 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.introspectionFromSchema = introspectionFromSchema;
var _invariant = require('../jsutils/invariant.js');
var _parser = require('../language/parser.js');
var _execute = require('../execution/execute.js');
var _getIntrospectionQuery = require('./getIntrospectionQuery.js');
/**
* Build an IntrospectionQuery from a GraphQLSchema
*
* IntrospectionQuery is useful for utilities that care about type and field
* relationships, but do not need to traverse through those relationships.
*
* This is the inverse of buildClientSchema. The primary use case is outside
* of the server context, for instance when doing schema comparisons.
*/
function introspectionFromSchema(schema, options) {
const optionsWithDefaults = {
specifiedByUrl: true,
directiveIsRepeatable: true,
schemaDescription: true,
inputValueDeprecation: true,
...options,
};
const document = (0, _parser.parse)(
(0, _getIntrospectionQuery.getIntrospectionQuery)(optionsWithDefaults),
);
const result = (0, _execute.executeSync)({
schema,
document,
});
(!result.errors && result.data) || (0, _invariant.invariant)(false);
return result.data;
}

View File

@@ -0,0 +1,30 @@
import { invariant } from '../jsutils/invariant.mjs';
import { parse } from '../language/parser.mjs';
import { executeSync } from '../execution/execute.mjs';
import { getIntrospectionQuery } from './getIntrospectionQuery.mjs';
/**
* Build an IntrospectionQuery from a GraphQLSchema
*
* IntrospectionQuery is useful for utilities that care about type and field
* relationships, but do not need to traverse through those relationships.
*
* This is the inverse of buildClientSchema. The primary use case is outside
* of the server context, for instance when doing schema comparisons.
*/
export function introspectionFromSchema(schema, options) {
const optionsWithDefaults = {
specifiedByUrl: true,
directiveIsRepeatable: true,
schemaDescription: true,
inputValueDeprecation: true,
...options,
};
const document = parse(getIntrospectionQuery(optionsWithDefaults));
const result = executeSync({
schema,
document,
});
(!result.errors && result.data) || invariant(false);
return result.data;
}

View File

@@ -0,0 +1,9 @@
import { GraphQLSchema } from '../type/schema';
/**
* Sort GraphQLSchema.
*
* This function returns a sorted copy of the given GraphQLSchema.
*/
export declare function lexicographicSortSchema(
schema: GraphQLSchema,
): GraphQLSchema;

View File

@@ -0,0 +1,177 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.lexicographicSortSchema = lexicographicSortSchema;
var _inspect = require('../jsutils/inspect.js');
var _invariant = require('../jsutils/invariant.js');
var _keyValMap = require('../jsutils/keyValMap.js');
var _naturalCompare = require('../jsutils/naturalCompare.js');
var _definition = require('../type/definition.js');
var _directives = require('../type/directives.js');
var _introspection = require('../type/introspection.js');
var _schema = require('../type/schema.js');
/**
* Sort GraphQLSchema.
*
* This function returns a sorted copy of the given GraphQLSchema.
*/
function lexicographicSortSchema(schema) {
const schemaConfig = schema.toConfig();
const typeMap = (0, _keyValMap.keyValMap)(
sortByName(schemaConfig.types),
(type) => type.name,
sortNamedType,
);
return new _schema.GraphQLSchema({
...schemaConfig,
types: Object.values(typeMap),
directives: sortByName(schemaConfig.directives).map(sortDirective),
query: replaceMaybeType(schemaConfig.query),
mutation: replaceMaybeType(schemaConfig.mutation),
subscription: replaceMaybeType(schemaConfig.subscription),
});
function replaceType(type) {
if ((0, _definition.isListType)(type)) {
// @ts-expect-error
return new _definition.GraphQLList(replaceType(type.ofType));
} else if ((0, _definition.isNonNullType)(type)) {
// @ts-expect-error
return new _definition.GraphQLNonNull(replaceType(type.ofType));
} // @ts-expect-error FIXME: TS Conversion
return replaceNamedType(type);
}
function replaceNamedType(type) {
return typeMap[type.name];
}
function replaceMaybeType(maybeType) {
return maybeType && replaceNamedType(maybeType);
}
function sortDirective(directive) {
const config = directive.toConfig();
return new _directives.GraphQLDirective({
...config,
locations: sortBy(config.locations, (x) => x),
args: sortArgs(config.args),
});
}
function sortArgs(args) {
return sortObjMap(args, (arg) => ({ ...arg, type: replaceType(arg.type) }));
}
function sortFields(fieldsMap) {
return sortObjMap(fieldsMap, (field) => ({
...field,
type: replaceType(field.type),
args: field.args && sortArgs(field.args),
}));
}
function sortInputFields(fieldsMap) {
return sortObjMap(fieldsMap, (field) => ({
...field,
type: replaceType(field.type),
}));
}
function sortTypes(array) {
return sortByName(array).map(replaceNamedType);
}
function sortNamedType(type) {
if (
(0, _definition.isScalarType)(type) ||
(0, _introspection.isIntrospectionType)(type)
) {
return type;
}
if ((0, _definition.isObjectType)(type)) {
const config = type.toConfig();
return new _definition.GraphQLObjectType({
...config,
interfaces: () => sortTypes(config.interfaces),
fields: () => sortFields(config.fields),
});
}
if ((0, _definition.isInterfaceType)(type)) {
const config = type.toConfig();
return new _definition.GraphQLInterfaceType({
...config,
interfaces: () => sortTypes(config.interfaces),
fields: () => sortFields(config.fields),
});
}
if ((0, _definition.isUnionType)(type)) {
const config = type.toConfig();
return new _definition.GraphQLUnionType({
...config,
types: () => sortTypes(config.types),
});
}
if ((0, _definition.isEnumType)(type)) {
const config = type.toConfig();
return new _definition.GraphQLEnumType({
...config,
values: sortObjMap(config.values, (value) => value),
});
}
if ((0, _definition.isInputObjectType)(type)) {
const config = type.toConfig();
return new _definition.GraphQLInputObjectType({
...config,
fields: () => sortInputFields(config.fields),
});
}
/* c8 ignore next 3 */
// Not reachable, all possible types have been considered.
false ||
(0, _invariant.invariant)(
false,
'Unexpected type: ' + (0, _inspect.inspect)(type),
);
}
}
function sortObjMap(map, sortValueFn) {
const sortedMap = Object.create(null);
for (const key of Object.keys(map).sort(_naturalCompare.naturalCompare)) {
sortedMap[key] = sortValueFn(map[key]);
}
return sortedMap;
}
function sortByName(array) {
return sortBy(array, (obj) => obj.name);
}
function sortBy(array, mapToKey) {
return array.slice().sort((obj1, obj2) => {
const key1 = mapToKey(obj1);
const key2 = mapToKey(obj2);
return (0, _naturalCompare.naturalCompare)(key1, key2);
});
}

View File

@@ -0,0 +1,172 @@
import { inspect } from '../jsutils/inspect.mjs';
import { invariant } from '../jsutils/invariant.mjs';
import { keyValMap } from '../jsutils/keyValMap.mjs';
import { naturalCompare } from '../jsutils/naturalCompare.mjs';
import {
GraphQLEnumType,
GraphQLInputObjectType,
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLUnionType,
isEnumType,
isInputObjectType,
isInterfaceType,
isListType,
isNonNullType,
isObjectType,
isScalarType,
isUnionType,
} from '../type/definition.mjs';
import { GraphQLDirective } from '../type/directives.mjs';
import { isIntrospectionType } from '../type/introspection.mjs';
import { GraphQLSchema } from '../type/schema.mjs';
/**
* Sort GraphQLSchema.
*
* This function returns a sorted copy of the given GraphQLSchema.
*/
export function lexicographicSortSchema(schema) {
const schemaConfig = schema.toConfig();
const typeMap = keyValMap(
sortByName(schemaConfig.types),
(type) => type.name,
sortNamedType,
);
return new GraphQLSchema({
...schemaConfig,
types: Object.values(typeMap),
directives: sortByName(schemaConfig.directives).map(sortDirective),
query: replaceMaybeType(schemaConfig.query),
mutation: replaceMaybeType(schemaConfig.mutation),
subscription: replaceMaybeType(schemaConfig.subscription),
});
function replaceType(type) {
if (isListType(type)) {
// @ts-expect-error
return new GraphQLList(replaceType(type.ofType));
} else if (isNonNullType(type)) {
// @ts-expect-error
return new GraphQLNonNull(replaceType(type.ofType));
} // @ts-expect-error FIXME: TS Conversion
return replaceNamedType(type);
}
function replaceNamedType(type) {
return typeMap[type.name];
}
function replaceMaybeType(maybeType) {
return maybeType && replaceNamedType(maybeType);
}
function sortDirective(directive) {
const config = directive.toConfig();
return new GraphQLDirective({
...config,
locations: sortBy(config.locations, (x) => x),
args: sortArgs(config.args),
});
}
function sortArgs(args) {
return sortObjMap(args, (arg) => ({ ...arg, type: replaceType(arg.type) }));
}
function sortFields(fieldsMap) {
return sortObjMap(fieldsMap, (field) => ({
...field,
type: replaceType(field.type),
args: field.args && sortArgs(field.args),
}));
}
function sortInputFields(fieldsMap) {
return sortObjMap(fieldsMap, (field) => ({
...field,
type: replaceType(field.type),
}));
}
function sortTypes(array) {
return sortByName(array).map(replaceNamedType);
}
function sortNamedType(type) {
if (isScalarType(type) || isIntrospectionType(type)) {
return type;
}
if (isObjectType(type)) {
const config = type.toConfig();
return new GraphQLObjectType({
...config,
interfaces: () => sortTypes(config.interfaces),
fields: () => sortFields(config.fields),
});
}
if (isInterfaceType(type)) {
const config = type.toConfig();
return new GraphQLInterfaceType({
...config,
interfaces: () => sortTypes(config.interfaces),
fields: () => sortFields(config.fields),
});
}
if (isUnionType(type)) {
const config = type.toConfig();
return new GraphQLUnionType({
...config,
types: () => sortTypes(config.types),
});
}
if (isEnumType(type)) {
const config = type.toConfig();
return new GraphQLEnumType({
...config,
values: sortObjMap(config.values, (value) => value),
});
}
if (isInputObjectType(type)) {
const config = type.toConfig();
return new GraphQLInputObjectType({
...config,
fields: () => sortInputFields(config.fields),
});
}
/* c8 ignore next 3 */
// Not reachable, all possible types have been considered.
false || invariant(false, 'Unexpected type: ' + inspect(type));
}
}
function sortObjMap(map, sortValueFn) {
const sortedMap = Object.create(null);
for (const key of Object.keys(map).sort(naturalCompare)) {
sortedMap[key] = sortValueFn(map[key]);
}
return sortedMap;
}
function sortByName(array) {
return sortBy(array, (obj) => obj.name);
}
function sortBy(array, mapToKey) {
return array.slice().sort((obj1, obj2) => {
const key1 = mapToKey(obj1);
const key2 = mapToKey(obj2);
return naturalCompare(key1, key2);
});
}

View File

@@ -0,0 +1,5 @@
import type { GraphQLNamedType } from '../type/definition';
import type { GraphQLSchema } from '../type/schema';
export declare function printSchema(schema: GraphQLSchema): string;
export declare function printIntrospectionSchema(schema: GraphQLSchema): string;
export declare function printType(type: GraphQLNamedType): string;

View File

@@ -0,0 +1,333 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.printIntrospectionSchema = printIntrospectionSchema;
exports.printSchema = printSchema;
exports.printType = printType;
var _inspect = require('../jsutils/inspect.js');
var _invariant = require('../jsutils/invariant.js');
var _blockString = require('../language/blockString.js');
var _kinds = require('../language/kinds.js');
var _printer = require('../language/printer.js');
var _definition = require('../type/definition.js');
var _directives = require('../type/directives.js');
var _introspection = require('../type/introspection.js');
var _scalars = require('../type/scalars.js');
var _astFromValue = require('./astFromValue.js');
function printSchema(schema) {
return printFilteredSchema(
schema,
(n) => !(0, _directives.isSpecifiedDirective)(n),
isDefinedType,
);
}
function printIntrospectionSchema(schema) {
return printFilteredSchema(
schema,
_directives.isSpecifiedDirective,
_introspection.isIntrospectionType,
);
}
function isDefinedType(type) {
return (
!(0, _scalars.isSpecifiedScalarType)(type) &&
!(0, _introspection.isIntrospectionType)(type)
);
}
function printFilteredSchema(schema, directiveFilter, typeFilter) {
const directives = schema.getDirectives().filter(directiveFilter);
const types = Object.values(schema.getTypeMap()).filter(typeFilter);
return [
printSchemaDefinition(schema),
...directives.map((directive) => printDirective(directive)),
...types.map((type) => printType(type)),
]
.filter(Boolean)
.join('\n\n');
}
function printSchemaDefinition(schema) {
if (schema.description == null && isSchemaOfCommonNames(schema)) {
return;
}
const operationTypes = [];
const queryType = schema.getQueryType();
if (queryType) {
operationTypes.push(` query: ${queryType.name}`);
}
const mutationType = schema.getMutationType();
if (mutationType) {
operationTypes.push(` mutation: ${mutationType.name}`);
}
const subscriptionType = schema.getSubscriptionType();
if (subscriptionType) {
operationTypes.push(` subscription: ${subscriptionType.name}`);
}
return printDescription(schema) + `schema {\n${operationTypes.join('\n')}\n}`;
}
/**
* GraphQL schema define root types for each type of operation. These types are
* the same as any other type and can be named in any manner, however there is
* a common naming convention:
*
* ```graphql
* schema {
* query: Query
* mutation: Mutation
* subscription: Subscription
* }
* ```
*
* When using this naming convention, the schema description can be omitted.
*/
function isSchemaOfCommonNames(schema) {
const queryType = schema.getQueryType();
if (queryType && queryType.name !== 'Query') {
return false;
}
const mutationType = schema.getMutationType();
if (mutationType && mutationType.name !== 'Mutation') {
return false;
}
const subscriptionType = schema.getSubscriptionType();
if (subscriptionType && subscriptionType.name !== 'Subscription') {
return false;
}
return true;
}
function printType(type) {
if ((0, _definition.isScalarType)(type)) {
return printScalar(type);
}
if ((0, _definition.isObjectType)(type)) {
return printObject(type);
}
if ((0, _definition.isInterfaceType)(type)) {
return printInterface(type);
}
if ((0, _definition.isUnionType)(type)) {
return printUnion(type);
}
if ((0, _definition.isEnumType)(type)) {
return printEnum(type);
}
if ((0, _definition.isInputObjectType)(type)) {
return printInputObject(type);
}
/* c8 ignore next 3 */
// Not reachable, all possible types have been considered.
false ||
(0, _invariant.invariant)(
false,
'Unexpected type: ' + (0, _inspect.inspect)(type),
);
}
function printScalar(type) {
return (
printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type)
);
}
function printImplementedInterfaces(type) {
const interfaces = type.getInterfaces();
return interfaces.length
? ' implements ' + interfaces.map((i) => i.name).join(' & ')
: '';
}
function printObject(type) {
return (
printDescription(type) +
`type ${type.name}` +
printImplementedInterfaces(type) +
printFields(type)
);
}
function printInterface(type) {
return (
printDescription(type) +
`interface ${type.name}` +
printImplementedInterfaces(type) +
printFields(type)
);
}
function printUnion(type) {
const types = type.getTypes();
const possibleTypes = types.length ? ' = ' + types.join(' | ') : '';
return printDescription(type) + 'union ' + type.name + possibleTypes;
}
function printEnum(type) {
const values = type
.getValues()
.map(
(value, i) =>
printDescription(value, ' ', !i) +
' ' +
value.name +
printDeprecated(value.deprecationReason),
);
return printDescription(type) + `enum ${type.name}` + printBlock(values);
}
function printInputObject(type) {
const fields = Object.values(type.getFields()).map(
(f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f),
);
return printDescription(type) + `input ${type.name}` + printBlock(fields);
}
function printFields(type) {
const fields = Object.values(type.getFields()).map(
(f, i) =>
printDescription(f, ' ', !i) +
' ' +
f.name +
printArgs(f.args, ' ') +
': ' +
String(f.type) +
printDeprecated(f.deprecationReason),
);
return printBlock(fields);
}
function printBlock(items) {
return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : '';
}
function printArgs(args, indentation = '') {
if (args.length === 0) {
return '';
} // If every arg does not have a description, print them on one line.
if (args.every((arg) => !arg.description)) {
return '(' + args.map(printInputValue).join(', ') + ')';
}
return (
'(\n' +
args
.map(
(arg, i) =>
printDescription(arg, ' ' + indentation, !i) +
' ' +
indentation +
printInputValue(arg),
)
.join('\n') +
'\n' +
indentation +
')'
);
}
function printInputValue(arg) {
const defaultAST = (0, _astFromValue.astFromValue)(
arg.defaultValue,
arg.type,
);
let argDecl = arg.name + ': ' + String(arg.type);
if (defaultAST) {
argDecl += ` = ${(0, _printer.print)(defaultAST)}`;
}
return argDecl + printDeprecated(arg.deprecationReason);
}
function printDirective(directive) {
return (
printDescription(directive) +
'directive @' +
directive.name +
printArgs(directive.args) +
(directive.isRepeatable ? ' repeatable' : '') +
' on ' +
directive.locations.join(' | ')
);
}
function printDeprecated(reason) {
if (reason == null) {
return '';
}
if (reason !== _directives.DEFAULT_DEPRECATION_REASON) {
const astValue = (0, _printer.print)({
kind: _kinds.Kind.STRING,
value: reason,
});
return ` @deprecated(reason: ${astValue})`;
}
return ' @deprecated';
}
function printSpecifiedByURL(scalar) {
if (scalar.specifiedByURL == null) {
return '';
}
const astValue = (0, _printer.print)({
kind: _kinds.Kind.STRING,
value: scalar.specifiedByURL,
});
return ` @specifiedBy(url: ${astValue})`;
}
function printDescription(def, indentation = '', firstInBlock = true) {
const { description } = def;
if (description == null) {
return '';
}
const blockString = (0, _printer.print)({
kind: _kinds.Kind.STRING,
value: description,
block: (0, _blockString.isPrintableAsBlockString)(description),
});
const prefix =
indentation && !firstInBlock ? '\n' + indentation : indentation;
return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n';
}

View File

@@ -0,0 +1,309 @@
import { inspect } from '../jsutils/inspect.mjs';
import { invariant } from '../jsutils/invariant.mjs';
import { isPrintableAsBlockString } from '../language/blockString.mjs';
import { Kind } from '../language/kinds.mjs';
import { print } from '../language/printer.mjs';
import {
isEnumType,
isInputObjectType,
isInterfaceType,
isObjectType,
isScalarType,
isUnionType,
} from '../type/definition.mjs';
import {
DEFAULT_DEPRECATION_REASON,
isSpecifiedDirective,
} from '../type/directives.mjs';
import { isIntrospectionType } from '../type/introspection.mjs';
import { isSpecifiedScalarType } from '../type/scalars.mjs';
import { astFromValue } from './astFromValue.mjs';
export function printSchema(schema) {
return printFilteredSchema(
schema,
(n) => !isSpecifiedDirective(n),
isDefinedType,
);
}
export function printIntrospectionSchema(schema) {
return printFilteredSchema(schema, isSpecifiedDirective, isIntrospectionType);
}
function isDefinedType(type) {
return !isSpecifiedScalarType(type) && !isIntrospectionType(type);
}
function printFilteredSchema(schema, directiveFilter, typeFilter) {
const directives = schema.getDirectives().filter(directiveFilter);
const types = Object.values(schema.getTypeMap()).filter(typeFilter);
return [
printSchemaDefinition(schema),
...directives.map((directive) => printDirective(directive)),
...types.map((type) => printType(type)),
]
.filter(Boolean)
.join('\n\n');
}
function printSchemaDefinition(schema) {
if (schema.description == null && isSchemaOfCommonNames(schema)) {
return;
}
const operationTypes = [];
const queryType = schema.getQueryType();
if (queryType) {
operationTypes.push(` query: ${queryType.name}`);
}
const mutationType = schema.getMutationType();
if (mutationType) {
operationTypes.push(` mutation: ${mutationType.name}`);
}
const subscriptionType = schema.getSubscriptionType();
if (subscriptionType) {
operationTypes.push(` subscription: ${subscriptionType.name}`);
}
return printDescription(schema) + `schema {\n${operationTypes.join('\n')}\n}`;
}
/**
* GraphQL schema define root types for each type of operation. These types are
* the same as any other type and can be named in any manner, however there is
* a common naming convention:
*
* ```graphql
* schema {
* query: Query
* mutation: Mutation
* subscription: Subscription
* }
* ```
*
* When using this naming convention, the schema description can be omitted.
*/
function isSchemaOfCommonNames(schema) {
const queryType = schema.getQueryType();
if (queryType && queryType.name !== 'Query') {
return false;
}
const mutationType = schema.getMutationType();
if (mutationType && mutationType.name !== 'Mutation') {
return false;
}
const subscriptionType = schema.getSubscriptionType();
if (subscriptionType && subscriptionType.name !== 'Subscription') {
return false;
}
return true;
}
export function printType(type) {
if (isScalarType(type)) {
return printScalar(type);
}
if (isObjectType(type)) {
return printObject(type);
}
if (isInterfaceType(type)) {
return printInterface(type);
}
if (isUnionType(type)) {
return printUnion(type);
}
if (isEnumType(type)) {
return printEnum(type);
}
if (isInputObjectType(type)) {
return printInputObject(type);
}
/* c8 ignore next 3 */
// Not reachable, all possible types have been considered.
false || invariant(false, 'Unexpected type: ' + inspect(type));
}
function printScalar(type) {
return (
printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type)
);
}
function printImplementedInterfaces(type) {
const interfaces = type.getInterfaces();
return interfaces.length
? ' implements ' + interfaces.map((i) => i.name).join(' & ')
: '';
}
function printObject(type) {
return (
printDescription(type) +
`type ${type.name}` +
printImplementedInterfaces(type) +
printFields(type)
);
}
function printInterface(type) {
return (
printDescription(type) +
`interface ${type.name}` +
printImplementedInterfaces(type) +
printFields(type)
);
}
function printUnion(type) {
const types = type.getTypes();
const possibleTypes = types.length ? ' = ' + types.join(' | ') : '';
return printDescription(type) + 'union ' + type.name + possibleTypes;
}
function printEnum(type) {
const values = type
.getValues()
.map(
(value, i) =>
printDescription(value, ' ', !i) +
' ' +
value.name +
printDeprecated(value.deprecationReason),
);
return printDescription(type) + `enum ${type.name}` + printBlock(values);
}
function printInputObject(type) {
const fields = Object.values(type.getFields()).map(
(f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f),
);
return printDescription(type) + `input ${type.name}` + printBlock(fields);
}
function printFields(type) {
const fields = Object.values(type.getFields()).map(
(f, i) =>
printDescription(f, ' ', !i) +
' ' +
f.name +
printArgs(f.args, ' ') +
': ' +
String(f.type) +
printDeprecated(f.deprecationReason),
);
return printBlock(fields);
}
function printBlock(items) {
return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : '';
}
function printArgs(args, indentation = '') {
if (args.length === 0) {
return '';
} // If every arg does not have a description, print them on one line.
if (args.every((arg) => !arg.description)) {
return '(' + args.map(printInputValue).join(', ') + ')';
}
return (
'(\n' +
args
.map(
(arg, i) =>
printDescription(arg, ' ' + indentation, !i) +
' ' +
indentation +
printInputValue(arg),
)
.join('\n') +
'\n' +
indentation +
')'
);
}
function printInputValue(arg) {
const defaultAST = astFromValue(arg.defaultValue, arg.type);
let argDecl = arg.name + ': ' + String(arg.type);
if (defaultAST) {
argDecl += ` = ${print(defaultAST)}`;
}
return argDecl + printDeprecated(arg.deprecationReason);
}
function printDirective(directive) {
return (
printDescription(directive) +
'directive @' +
directive.name +
printArgs(directive.args) +
(directive.isRepeatable ? ' repeatable' : '') +
' on ' +
directive.locations.join(' | ')
);
}
function printDeprecated(reason) {
if (reason == null) {
return '';
}
if (reason !== DEFAULT_DEPRECATION_REASON) {
const astValue = print({
kind: Kind.STRING,
value: reason,
});
return ` @deprecated(reason: ${astValue})`;
}
return ' @deprecated';
}
function printSpecifiedByURL(scalar) {
if (scalar.specifiedByURL == null) {
return '';
}
const astValue = print({
kind: Kind.STRING,
value: scalar.specifiedByURL,
});
return ` @specifiedBy(url: ${astValue})`;
}
function printDescription(def, indentation = '', firstInBlock = true) {
const { description } = def;
if (description == null) {
return '';
}
const blockString = print({
kind: Kind.STRING,
value: description,
block: isPrintableAsBlockString(description),
});
const prefix =
indentation && !firstInBlock ? '\n' + indentation : indentation;
return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n';
}

View File

@@ -0,0 +1,11 @@
import type { ObjMap } from '../jsutils/ObjMap';
import type { DocumentNode } from '../language/ast';
/**
* separateOperations accepts a single AST document which may contain many
* operations and fragments and returns a collection of AST documents each of
* which contains a single operation as well the fragment definitions it
* refers to.
*/
export declare function separateOperations(
documentAST: DocumentNode,
): ObjMap<DocumentNode>;

View File

@@ -0,0 +1,88 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.separateOperations = separateOperations;
var _kinds = require('../language/kinds.js');
var _visitor = require('../language/visitor.js');
/**
* separateOperations accepts a single AST document which may contain many
* operations and fragments and returns a collection of AST documents each of
* which contains a single operation as well the fragment definitions it
* refers to.
*/
function separateOperations(documentAST) {
const operations = [];
const depGraph = Object.create(null); // Populate metadata and build a dependency graph.
for (const definitionNode of documentAST.definitions) {
switch (definitionNode.kind) {
case _kinds.Kind.OPERATION_DEFINITION:
operations.push(definitionNode);
break;
case _kinds.Kind.FRAGMENT_DEFINITION:
depGraph[definitionNode.name.value] = collectDependencies(
definitionNode.selectionSet,
);
break;
default: // ignore non-executable definitions
}
} // For each operation, produce a new synthesized AST which includes only what
// is necessary for completing that operation.
const separatedDocumentASTs = Object.create(null);
for (const operation of operations) {
const dependencies = new Set();
for (const fragmentName of collectDependencies(operation.selectionSet)) {
collectTransitiveDependencies(dependencies, depGraph, fragmentName);
} // Provides the empty string for anonymous operations.
const operationName = operation.name ? operation.name.value : ''; // The list of definition nodes to be included for this operation, sorted
// to retain the same order as the original document.
separatedDocumentASTs[operationName] = {
kind: _kinds.Kind.DOCUMENT,
definitions: documentAST.definitions.filter(
(node) =>
node === operation ||
(node.kind === _kinds.Kind.FRAGMENT_DEFINITION &&
dependencies.has(node.name.value)),
),
};
}
return separatedDocumentASTs;
}
// From a dependency graph, collects a list of transitive dependencies by
// recursing through a dependency graph.
function collectTransitiveDependencies(collected, depGraph, fromName) {
if (!collected.has(fromName)) {
collected.add(fromName);
const immediateDeps = depGraph[fromName];
if (immediateDeps !== undefined) {
for (const toName of immediateDeps) {
collectTransitiveDependencies(collected, depGraph, toName);
}
}
}
}
function collectDependencies(selectionSet) {
const dependencies = [];
(0, _visitor.visit)(selectionSet, {
FragmentSpread(node) {
dependencies.push(node.name.value);
},
});
return dependencies;
}

View File

@@ -0,0 +1,80 @@
import { Kind } from '../language/kinds.mjs';
import { visit } from '../language/visitor.mjs';
/**
* separateOperations accepts a single AST document which may contain many
* operations and fragments and returns a collection of AST documents each of
* which contains a single operation as well the fragment definitions it
* refers to.
*/
export function separateOperations(documentAST) {
const operations = [];
const depGraph = Object.create(null); // Populate metadata and build a dependency graph.
for (const definitionNode of documentAST.definitions) {
switch (definitionNode.kind) {
case Kind.OPERATION_DEFINITION:
operations.push(definitionNode);
break;
case Kind.FRAGMENT_DEFINITION:
depGraph[definitionNode.name.value] = collectDependencies(
definitionNode.selectionSet,
);
break;
default: // ignore non-executable definitions
}
} // For each operation, produce a new synthesized AST which includes only what
// is necessary for completing that operation.
const separatedDocumentASTs = Object.create(null);
for (const operation of operations) {
const dependencies = new Set();
for (const fragmentName of collectDependencies(operation.selectionSet)) {
collectTransitiveDependencies(dependencies, depGraph, fragmentName);
} // Provides the empty string for anonymous operations.
const operationName = operation.name ? operation.name.value : ''; // The list of definition nodes to be included for this operation, sorted
// to retain the same order as the original document.
separatedDocumentASTs[operationName] = {
kind: Kind.DOCUMENT,
definitions: documentAST.definitions.filter(
(node) =>
node === operation ||
(node.kind === Kind.FRAGMENT_DEFINITION &&
dependencies.has(node.name.value)),
),
};
}
return separatedDocumentASTs;
}
// From a dependency graph, collects a list of transitive dependencies by
// recursing through a dependency graph.
function collectTransitiveDependencies(collected, depGraph, fromName) {
if (!collected.has(fromName)) {
collected.add(fromName);
const immediateDeps = depGraph[fromName];
if (immediateDeps !== undefined) {
for (const toName of immediateDeps) {
collectTransitiveDependencies(collected, depGraph, toName);
}
}
}
}
function collectDependencies(selectionSet) {
const dependencies = [];
visit(selectionSet, {
FragmentSpread(node) {
dependencies.push(node.name.value);
},
});
return dependencies;
}

View File

@@ -0,0 +1,9 @@
import type { ValueNode } from '../language/ast';
/**
* Sort ValueNode.
*
* This function returns a sorted copy of the given ValueNode.
*
* @internal
*/
export declare function sortValueNode(valueNode: ValueNode): ValueNode;

View File

@@ -0,0 +1,47 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.sortValueNode = sortValueNode;
var _naturalCompare = require('../jsutils/naturalCompare.js');
var _kinds = require('../language/kinds.js');
/**
* Sort ValueNode.
*
* This function returns a sorted copy of the given ValueNode.
*
* @internal
*/
function sortValueNode(valueNode) {
switch (valueNode.kind) {
case _kinds.Kind.OBJECT:
return { ...valueNode, fields: sortFields(valueNode.fields) };
case _kinds.Kind.LIST:
return { ...valueNode, values: valueNode.values.map(sortValueNode) };
case _kinds.Kind.INT:
case _kinds.Kind.FLOAT:
case _kinds.Kind.STRING:
case _kinds.Kind.BOOLEAN:
case _kinds.Kind.NULL:
case _kinds.Kind.ENUM:
case _kinds.Kind.VARIABLE:
return valueNode;
}
}
function sortFields(fields) {
return fields
.map((fieldNode) => ({
...fieldNode,
value: sortValueNode(fieldNode.value),
}))
.sort((fieldA, fieldB) =>
(0, _naturalCompare.naturalCompare)(fieldA.name.value, fieldB.name.value),
);
}

View File

@@ -0,0 +1,39 @@
import { naturalCompare } from '../jsutils/naturalCompare.mjs';
import { Kind } from '../language/kinds.mjs';
/**
* Sort ValueNode.
*
* This function returns a sorted copy of the given ValueNode.
*
* @internal
*/
export function sortValueNode(valueNode) {
switch (valueNode.kind) {
case Kind.OBJECT:
return { ...valueNode, fields: sortFields(valueNode.fields) };
case Kind.LIST:
return { ...valueNode, values: valueNode.values.map(sortValueNode) };
case Kind.INT:
case Kind.FLOAT:
case Kind.STRING:
case Kind.BOOLEAN:
case Kind.NULL:
case Kind.ENUM:
case Kind.VARIABLE:
return valueNode;
}
}
function sortFields(fields) {
return fields
.map((fieldNode) => ({
...fieldNode,
value: sortValueNode(fieldNode.value),
}))
.sort((fieldA, fieldB) =>
naturalCompare(fieldA.name.value, fieldB.name.value),
);
}

View File

@@ -0,0 +1,62 @@
import { Source } from '../language/source';
/**
* Strips characters that are not significant to the validity or execution
* of a GraphQL document:
* - UnicodeBOM
* - WhiteSpace
* - LineTerminator
* - Comment
* - Comma
* - BlockString indentation
*
* Note: It is required to have a delimiter character between neighboring
* non-punctuator tokens and this function always uses single space as delimiter.
*
* It is guaranteed that both input and output documents if parsed would result
* in the exact same AST except for nodes location.
*
* Warning: It is guaranteed that this function will always produce stable results.
* However, it's not guaranteed that it will stay the same between different
* releases due to bugfixes or changes in the GraphQL specification.
*
* Query example:
*
* ```graphql
* query SomeQuery($foo: String!, $bar: String) {
* someField(foo: $foo, bar: $bar) {
* a
* b {
* c
* d
* }
* }
* }
* ```
*
* Becomes:
*
* ```graphql
* query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}}
* ```
*
* SDL example:
*
* ```graphql
* """
* Type description
* """
* type Foo {
* """
* Field description
* """
* bar: String
* }
* ```
*
* Becomes:
*
* ```graphql
* """Type description""" type Foo{"""Field description""" bar:String}
* ```
*/
export declare function stripIgnoredCharacters(source: string | Source): string;

View File

@@ -0,0 +1,121 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.stripIgnoredCharacters = stripIgnoredCharacters;
var _blockString = require('../language/blockString.js');
var _lexer = require('../language/lexer.js');
var _source = require('../language/source.js');
var _tokenKind = require('../language/tokenKind.js');
/**
* Strips characters that are not significant to the validity or execution
* of a GraphQL document:
* - UnicodeBOM
* - WhiteSpace
* - LineTerminator
* - Comment
* - Comma
* - BlockString indentation
*
* Note: It is required to have a delimiter character between neighboring
* non-punctuator tokens and this function always uses single space as delimiter.
*
* It is guaranteed that both input and output documents if parsed would result
* in the exact same AST except for nodes location.
*
* Warning: It is guaranteed that this function will always produce stable results.
* However, it's not guaranteed that it will stay the same between different
* releases due to bugfixes or changes in the GraphQL specification.
*
* Query example:
*
* ```graphql
* query SomeQuery($foo: String!, $bar: String) {
* someField(foo: $foo, bar: $bar) {
* a
* b {
* c
* d
* }
* }
* }
* ```
*
* Becomes:
*
* ```graphql
* query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}}
* ```
*
* SDL example:
*
* ```graphql
* """
* Type description
* """
* type Foo {
* """
* Field description
* """
* bar: String
* }
* ```
*
* Becomes:
*
* ```graphql
* """Type description""" type Foo{"""Field description""" bar:String}
* ```
*/
function stripIgnoredCharacters(source) {
const sourceObj = (0, _source.isSource)(source)
? source
: new _source.Source(source);
const body = sourceObj.body;
const lexer = new _lexer.Lexer(sourceObj);
let strippedBody = '';
let wasLastAddedTokenNonPunctuator = false;
while (lexer.advance().kind !== _tokenKind.TokenKind.EOF) {
const currentToken = lexer.token;
const tokenKind = currentToken.kind;
/**
* Every two non-punctuator tokens should have space between them.
* Also prevent case of non-punctuator token following by spread resulting
* in invalid token (e.g. `1...` is invalid Float token).
*/
const isNonPunctuator = !(0, _lexer.isPunctuatorTokenKind)(
currentToken.kind,
);
if (wasLastAddedTokenNonPunctuator) {
if (
isNonPunctuator ||
currentToken.kind === _tokenKind.TokenKind.SPREAD
) {
strippedBody += ' ';
}
}
const tokenBody = body.slice(currentToken.start, currentToken.end);
if (tokenKind === _tokenKind.TokenKind.BLOCK_STRING) {
strippedBody += (0, _blockString.printBlockString)(currentToken.value, {
minimize: true,
});
} else {
strippedBody += tokenBody;
}
wasLastAddedTokenNonPunctuator = isNonPunctuator;
}
return strippedBody;
}

View File

@@ -0,0 +1,104 @@
import { printBlockString } from '../language/blockString.mjs';
import { isPunctuatorTokenKind, Lexer } from '../language/lexer.mjs';
import { isSource, Source } from '../language/source.mjs';
import { TokenKind } from '../language/tokenKind.mjs';
/**
* Strips characters that are not significant to the validity or execution
* of a GraphQL document:
* - UnicodeBOM
* - WhiteSpace
* - LineTerminator
* - Comment
* - Comma
* - BlockString indentation
*
* Note: It is required to have a delimiter character between neighboring
* non-punctuator tokens and this function always uses single space as delimiter.
*
* It is guaranteed that both input and output documents if parsed would result
* in the exact same AST except for nodes location.
*
* Warning: It is guaranteed that this function will always produce stable results.
* However, it's not guaranteed that it will stay the same between different
* releases due to bugfixes or changes in the GraphQL specification.
*
* Query example:
*
* ```graphql
* query SomeQuery($foo: String!, $bar: String) {
* someField(foo: $foo, bar: $bar) {
* a
* b {
* c
* d
* }
* }
* }
* ```
*
* Becomes:
*
* ```graphql
* query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}}
* ```
*
* SDL example:
*
* ```graphql
* """
* Type description
* """
* type Foo {
* """
* Field description
* """
* bar: String
* }
* ```
*
* Becomes:
*
* ```graphql
* """Type description""" type Foo{"""Field description""" bar:String}
* ```
*/
export function stripIgnoredCharacters(source) {
const sourceObj = isSource(source) ? source : new Source(source);
const body = sourceObj.body;
const lexer = new Lexer(sourceObj);
let strippedBody = '';
let wasLastAddedTokenNonPunctuator = false;
while (lexer.advance().kind !== TokenKind.EOF) {
const currentToken = lexer.token;
const tokenKind = currentToken.kind;
/**
* Every two non-punctuator tokens should have space between them.
* Also prevent case of non-punctuator token following by spread resulting
* in invalid token (e.g. `1...` is invalid Float token).
*/
const isNonPunctuator = !isPunctuatorTokenKind(currentToken.kind);
if (wasLastAddedTokenNonPunctuator) {
if (isNonPunctuator || currentToken.kind === TokenKind.SPREAD) {
strippedBody += ' ';
}
}
const tokenBody = body.slice(currentToken.start, currentToken.end);
if (tokenKind === TokenKind.BLOCK_STRING) {
strippedBody += printBlockString(currentToken.value, {
minimize: true,
});
} else {
strippedBody += tokenBody;
}
wasLastAddedTokenNonPunctuator = isNonPunctuator;
}
return strippedBody;
}

View File

@@ -0,0 +1,32 @@
import type { GraphQLCompositeType, GraphQLType } from '../type/definition';
import type { GraphQLSchema } from '../type/schema';
/**
* Provided two types, return true if the types are equal (invariant).
*/
export declare function isEqualType(
typeA: GraphQLType,
typeB: GraphQLType,
): boolean;
/**
* Provided a type and a super type, return true if the first type is either
* equal or a subset of the second super type (covariant).
*/
export declare function isTypeSubTypeOf(
schema: GraphQLSchema,
maybeSubType: GraphQLType,
superType: GraphQLType,
): boolean;
/**
* Provided two composite types, determine if they "overlap". Two composite
* types overlap when the Sets of possible concrete types for each intersect.
*
* This is often used to determine if a fragment of a given type could possibly
* be visited in a context of another type.
*
* This function is commutative.
*/
export declare function doTypesOverlap(
schema: GraphQLSchema,
typeA: GraphQLCompositeType,
typeB: GraphQLCompositeType,
): boolean;

View File

@@ -0,0 +1,116 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.doTypesOverlap = doTypesOverlap;
exports.isEqualType = isEqualType;
exports.isTypeSubTypeOf = isTypeSubTypeOf;
var _definition = require('../type/definition.js');
/**
* Provided two types, return true if the types are equal (invariant).
*/
function isEqualType(typeA, typeB) {
// Equivalent types are equal.
if (typeA === typeB) {
return true;
} // If either type is non-null, the other must also be non-null.
if (
(0, _definition.isNonNullType)(typeA) &&
(0, _definition.isNonNullType)(typeB)
) {
return isEqualType(typeA.ofType, typeB.ofType);
} // If either type is a list, the other must also be a list.
if (
(0, _definition.isListType)(typeA) &&
(0, _definition.isListType)(typeB)
) {
return isEqualType(typeA.ofType, typeB.ofType);
} // Otherwise the types are not equal.
return false;
}
/**
* Provided a type and a super type, return true if the first type is either
* equal or a subset of the second super type (covariant).
*/
function isTypeSubTypeOf(schema, maybeSubType, superType) {
// Equivalent type is a valid subtype
if (maybeSubType === superType) {
return true;
} // If superType is non-null, maybeSubType must also be non-null.
if ((0, _definition.isNonNullType)(superType)) {
if ((0, _definition.isNonNullType)(maybeSubType)) {
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
}
return false;
}
if ((0, _definition.isNonNullType)(maybeSubType)) {
// If superType is nullable, maybeSubType may be non-null or nullable.
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);
} // If superType type is a list, maybeSubType type must also be a list.
if ((0, _definition.isListType)(superType)) {
if ((0, _definition.isListType)(maybeSubType)) {
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
}
return false;
}
if ((0, _definition.isListType)(maybeSubType)) {
// If superType is not a list, maybeSubType must also be not a list.
return false;
} // If superType type is an abstract type, check if it is super type of maybeSubType.
// Otherwise, the child type is not a valid subtype of the parent type.
return (
(0, _definition.isAbstractType)(superType) &&
((0, _definition.isInterfaceType)(maybeSubType) ||
(0, _definition.isObjectType)(maybeSubType)) &&
schema.isSubType(superType, maybeSubType)
);
}
/**
* Provided two composite types, determine if they "overlap". Two composite
* types overlap when the Sets of possible concrete types for each intersect.
*
* This is often used to determine if a fragment of a given type could possibly
* be visited in a context of another type.
*
* This function is commutative.
*/
function doTypesOverlap(schema, typeA, typeB) {
// Equivalent types overlap
if (typeA === typeB) {
return true;
}
if ((0, _definition.isAbstractType)(typeA)) {
if ((0, _definition.isAbstractType)(typeB)) {
// If both types are abstract, then determine if there is any intersection
// between possible concrete types of each.
return schema
.getPossibleTypes(typeA)
.some((type) => schema.isSubType(typeB, type));
} // Determine if the latter type is a possible concrete type of the former.
return schema.isSubType(typeA, typeB);
}
if ((0, _definition.isAbstractType)(typeB)) {
// Determine if the former type is a possible concrete type of the latter.
return schema.isSubType(typeB, typeA);
} // Otherwise the types do not overlap.
return false;
}

View File

@@ -0,0 +1,106 @@
import {
isAbstractType,
isInterfaceType,
isListType,
isNonNullType,
isObjectType,
} from '../type/definition.mjs';
/**
* Provided two types, return true if the types are equal (invariant).
*/
export function isEqualType(typeA, typeB) {
// Equivalent types are equal.
if (typeA === typeB) {
return true;
} // If either type is non-null, the other must also be non-null.
if (isNonNullType(typeA) && isNonNullType(typeB)) {
return isEqualType(typeA.ofType, typeB.ofType);
} // If either type is a list, the other must also be a list.
if (isListType(typeA) && isListType(typeB)) {
return isEqualType(typeA.ofType, typeB.ofType);
} // Otherwise the types are not equal.
return false;
}
/**
* Provided a type and a super type, return true if the first type is either
* equal or a subset of the second super type (covariant).
*/
export function isTypeSubTypeOf(schema, maybeSubType, superType) {
// Equivalent type is a valid subtype
if (maybeSubType === superType) {
return true;
} // If superType is non-null, maybeSubType must also be non-null.
if (isNonNullType(superType)) {
if (isNonNullType(maybeSubType)) {
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
}
return false;
}
if (isNonNullType(maybeSubType)) {
// If superType is nullable, maybeSubType may be non-null or nullable.
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);
} // If superType type is a list, maybeSubType type must also be a list.
if (isListType(superType)) {
if (isListType(maybeSubType)) {
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
}
return false;
}
if (isListType(maybeSubType)) {
// If superType is not a list, maybeSubType must also be not a list.
return false;
} // If superType type is an abstract type, check if it is super type of maybeSubType.
// Otherwise, the child type is not a valid subtype of the parent type.
return (
isAbstractType(superType) &&
(isInterfaceType(maybeSubType) || isObjectType(maybeSubType)) &&
schema.isSubType(superType, maybeSubType)
);
}
/**
* Provided two composite types, determine if they "overlap". Two composite
* types overlap when the Sets of possible concrete types for each intersect.
*
* This is often used to determine if a fragment of a given type could possibly
* be visited in a context of another type.
*
* This function is commutative.
*/
export function doTypesOverlap(schema, typeA, typeB) {
// Equivalent types overlap
if (typeA === typeB) {
return true;
}
if (isAbstractType(typeA)) {
if (isAbstractType(typeB)) {
// If both types are abstract, then determine if there is any intersection
// between possible concrete types of each.
return schema
.getPossibleTypes(typeA)
.some((type) => schema.isSubType(typeB, type));
} // Determine if the latter type is a possible concrete type of the former.
return schema.isSubType(typeA, typeB);
}
if (isAbstractType(typeB)) {
// Determine if the former type is a possible concrete type of the latter.
return schema.isSubType(typeB, typeA);
} // Otherwise the types do not overlap.
return false;
}

View File

@@ -0,0 +1,32 @@
import type {
ListTypeNode,
NamedTypeNode,
NonNullTypeNode,
TypeNode,
} from '../language/ast';
import type { GraphQLNamedType, GraphQLType } from '../type/definition';
import { GraphQLList, GraphQLNonNull } from '../type/definition';
import type { GraphQLSchema } from '../type/schema';
/**
* Given a Schema and an AST node describing a type, return a GraphQLType
* definition which applies to that type. For example, if provided the parsed
* AST node for `[User]`, a GraphQLList instance will be returned, containing
* the type called "User" found in the schema. If a type called "User" is not
* found in the schema, then undefined will be returned.
*/
export declare function typeFromAST(
schema: GraphQLSchema,
typeNode: NamedTypeNode,
): GraphQLNamedType | undefined;
export declare function typeFromAST(
schema: GraphQLSchema,
typeNode: ListTypeNode,
): GraphQLList<any> | undefined;
export declare function typeFromAST(
schema: GraphQLSchema,
typeNode: NonNullTypeNode,
): GraphQLNonNull<any> | undefined;
export declare function typeFromAST(
schema: GraphQLSchema,
typeNode: TypeNode,
): GraphQLType | undefined;

View File

@@ -0,0 +1,27 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.typeFromAST = typeFromAST;
var _kinds = require('../language/kinds.js');
var _definition = require('../type/definition.js');
function typeFromAST(schema, typeNode) {
switch (typeNode.kind) {
case _kinds.Kind.LIST_TYPE: {
const innerType = typeFromAST(schema, typeNode.type);
return innerType && new _definition.GraphQLList(innerType);
}
case _kinds.Kind.NON_NULL_TYPE: {
const innerType = typeFromAST(schema, typeNode.type);
return innerType && new _definition.GraphQLNonNull(innerType);
}
case _kinds.Kind.NAMED_TYPE:
return schema.getType(typeNode.name.value);
}
}

View File

@@ -0,0 +1,18 @@
import { Kind } from '../language/kinds.mjs';
import { GraphQLList, GraphQLNonNull } from '../type/definition.mjs';
export function typeFromAST(schema, typeNode) {
switch (typeNode.kind) {
case Kind.LIST_TYPE: {
const innerType = typeFromAST(schema, typeNode.type);
return innerType && new GraphQLList(innerType);
}
case Kind.NON_NULL_TYPE: {
const innerType = typeFromAST(schema, typeNode.type);
return innerType && new GraphQLNonNull(innerType);
}
case Kind.NAMED_TYPE:
return schema.getType(typeNode.name.value);
}
}

View File

@@ -0,0 +1,22 @@
import type { DocumentNode, ExecutableDefinitionNode } from '../language/ast';
/**
* Wrapper type that contains DocumentNode and types that can be deduced from it.
*/
export interface TypedQueryDocumentNode<
TResponseData = {
[key: string]: any;
},
TRequestVariables = {
[key: string]: any;
},
> extends DocumentNode {
readonly definitions: ReadonlyArray<ExecutableDefinitionNode>;
/**
* This type is used to ensure that the variables you pass in to the query are assignable to Variables
* and that the Result is assignable to whatever you pass your result to. The method is never actually
* implemented, but the type is valid because we list it as optional
*/
__ensureTypesOfVariablesAndResultMatching?: (
variables: TRequestVariables,
) => TResponseData;
}

View File

@@ -0,0 +1,5 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,29 @@
import type { Maybe } from '../jsutils/Maybe';
import type { ObjMap } from '../jsutils/ObjMap';
import type { ValueNode } from '../language/ast';
import type { GraphQLInputType } from '../type/definition';
/**
* Produces a JavaScript value given a GraphQL Value AST.
*
* A GraphQL type must be provided, which will be used to interpret different
* GraphQL Value literals.
*
* Returns `undefined` when the value could not be validly coerced according to
* the provided type.
*
* | GraphQL Value | JSON Value |
* | -------------------- | ------------- |
* | Input Object | Object |
* | List | Array |
* | Boolean | Boolean |
* | String | String |
* | Int / Float | Number |
* | Enum Value | Unknown |
* | NullValue | null |
*
*/
export declare function valueFromAST(
valueNode: Maybe<ValueNode>,
type: GraphQLInputType,
variables?: Maybe<ObjMap<unknown>>,
): unknown;

View File

@@ -0,0 +1,185 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.valueFromAST = valueFromAST;
var _inspect = require('../jsutils/inspect.js');
var _invariant = require('../jsutils/invariant.js');
var _keyMap = require('../jsutils/keyMap.js');
var _kinds = require('../language/kinds.js');
var _definition = require('../type/definition.js');
/**
* Produces a JavaScript value given a GraphQL Value AST.
*
* A GraphQL type must be provided, which will be used to interpret different
* GraphQL Value literals.
*
* Returns `undefined` when the value could not be validly coerced according to
* the provided type.
*
* | GraphQL Value | JSON Value |
* | -------------------- | ------------- |
* | Input Object | Object |
* | List | Array |
* | Boolean | Boolean |
* | String | String |
* | Int / Float | Number |
* | Enum Value | Unknown |
* | NullValue | null |
*
*/
function valueFromAST(valueNode, type, variables) {
if (!valueNode) {
// When there is no node, then there is also no value.
// Importantly, this is different from returning the value null.
return;
}
if (valueNode.kind === _kinds.Kind.VARIABLE) {
const variableName = valueNode.name.value;
if (variables == null || variables[variableName] === undefined) {
// No valid return value.
return;
}
const variableValue = variables[variableName];
if (variableValue === null && (0, _definition.isNonNullType)(type)) {
return; // Invalid: intentionally return no value.
} // Note: This does no further checking that this variable is correct.
// This assumes that this query has been validated and the variable
// usage here is of the correct type.
return variableValue;
}
if ((0, _definition.isNonNullType)(type)) {
if (valueNode.kind === _kinds.Kind.NULL) {
return; // Invalid: intentionally return no value.
}
return valueFromAST(valueNode, type.ofType, variables);
}
if (valueNode.kind === _kinds.Kind.NULL) {
// This is explicitly returning the value null.
return null;
}
if ((0, _definition.isListType)(type)) {
const itemType = type.ofType;
if (valueNode.kind === _kinds.Kind.LIST) {
const coercedValues = [];
for (const itemNode of valueNode.values) {
if (isMissingVariable(itemNode, variables)) {
// If an array contains a missing variable, it is either coerced to
// null or if the item type is non-null, it considered invalid.
if ((0, _definition.isNonNullType)(itemType)) {
return; // Invalid: intentionally return no value.
}
coercedValues.push(null);
} else {
const itemValue = valueFromAST(itemNode, itemType, variables);
if (itemValue === undefined) {
return; // Invalid: intentionally return no value.
}
coercedValues.push(itemValue);
}
}
return coercedValues;
}
const coercedValue = valueFromAST(valueNode, itemType, variables);
if (coercedValue === undefined) {
return; // Invalid: intentionally return no value.
}
return [coercedValue];
}
if ((0, _definition.isInputObjectType)(type)) {
if (valueNode.kind !== _kinds.Kind.OBJECT) {
return; // Invalid: intentionally return no value.
}
const coercedObj = Object.create(null);
const fieldNodes = (0, _keyMap.keyMap)(
valueNode.fields,
(field) => field.name.value,
);
for (const field of Object.values(type.getFields())) {
const fieldNode = fieldNodes[field.name];
if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {
if (field.defaultValue !== undefined) {
coercedObj[field.name] = field.defaultValue;
} else if ((0, _definition.isNonNullType)(field.type)) {
return; // Invalid: intentionally return no value.
}
continue;
}
const fieldValue = valueFromAST(fieldNode.value, field.type, variables);
if (fieldValue === undefined) {
return; // Invalid: intentionally return no value.
}
coercedObj[field.name] = fieldValue;
}
return coercedObj;
}
if ((0, _definition.isLeafType)(type)) {
// Scalars and Enums fulfill parsing a literal value via parseLiteral().
// Invalid values represent a failure to parse correctly, in which case
// no value is returned.
let result;
try {
result = type.parseLiteral(valueNode, variables);
} catch (_error) {
return; // Invalid: intentionally return no value.
}
if (result === undefined) {
return; // Invalid: intentionally return no value.
}
return result;
}
/* c8 ignore next 3 */
// Not reachable, all possible input types have been considered.
false ||
(0, _invariant.invariant)(
false,
'Unexpected input type: ' + (0, _inspect.inspect)(type),
);
} // Returns true if the provided valueNode is a variable which is not defined
// in the set of variables.
function isMissingVariable(valueNode, variables) {
return (
valueNode.kind === _kinds.Kind.VARIABLE &&
(variables == null || variables[valueNode.name.value] === undefined)
);
}

View File

@@ -0,0 +1,172 @@
import { inspect } from '../jsutils/inspect.mjs';
import { invariant } from '../jsutils/invariant.mjs';
import { keyMap } from '../jsutils/keyMap.mjs';
import { Kind } from '../language/kinds.mjs';
import {
isInputObjectType,
isLeafType,
isListType,
isNonNullType,
} from '../type/definition.mjs';
/**
* Produces a JavaScript value given a GraphQL Value AST.
*
* A GraphQL type must be provided, which will be used to interpret different
* GraphQL Value literals.
*
* Returns `undefined` when the value could not be validly coerced according to
* the provided type.
*
* | GraphQL Value | JSON Value |
* | -------------------- | ------------- |
* | Input Object | Object |
* | List | Array |
* | Boolean | Boolean |
* | String | String |
* | Int / Float | Number |
* | Enum Value | Unknown |
* | NullValue | null |
*
*/
export function valueFromAST(valueNode, type, variables) {
if (!valueNode) {
// When there is no node, then there is also no value.
// Importantly, this is different from returning the value null.
return;
}
if (valueNode.kind === Kind.VARIABLE) {
const variableName = valueNode.name.value;
if (variables == null || variables[variableName] === undefined) {
// No valid return value.
return;
}
const variableValue = variables[variableName];
if (variableValue === null && isNonNullType(type)) {
return; // Invalid: intentionally return no value.
} // Note: This does no further checking that this variable is correct.
// This assumes that this query has been validated and the variable
// usage here is of the correct type.
return variableValue;
}
if (isNonNullType(type)) {
if (valueNode.kind === Kind.NULL) {
return; // Invalid: intentionally return no value.
}
return valueFromAST(valueNode, type.ofType, variables);
}
if (valueNode.kind === Kind.NULL) {
// This is explicitly returning the value null.
return null;
}
if (isListType(type)) {
const itemType = type.ofType;
if (valueNode.kind === Kind.LIST) {
const coercedValues = [];
for (const itemNode of valueNode.values) {
if (isMissingVariable(itemNode, variables)) {
// If an array contains a missing variable, it is either coerced to
// null or if the item type is non-null, it considered invalid.
if (isNonNullType(itemType)) {
return; // Invalid: intentionally return no value.
}
coercedValues.push(null);
} else {
const itemValue = valueFromAST(itemNode, itemType, variables);
if (itemValue === undefined) {
return; // Invalid: intentionally return no value.
}
coercedValues.push(itemValue);
}
}
return coercedValues;
}
const coercedValue = valueFromAST(valueNode, itemType, variables);
if (coercedValue === undefined) {
return; // Invalid: intentionally return no value.
}
return [coercedValue];
}
if (isInputObjectType(type)) {
if (valueNode.kind !== Kind.OBJECT) {
return; // Invalid: intentionally return no value.
}
const coercedObj = Object.create(null);
const fieldNodes = keyMap(valueNode.fields, (field) => field.name.value);
for (const field of Object.values(type.getFields())) {
const fieldNode = fieldNodes[field.name];
if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {
if (field.defaultValue !== undefined) {
coercedObj[field.name] = field.defaultValue;
} else if (isNonNullType(field.type)) {
return; // Invalid: intentionally return no value.
}
continue;
}
const fieldValue = valueFromAST(fieldNode.value, field.type, variables);
if (fieldValue === undefined) {
return; // Invalid: intentionally return no value.
}
coercedObj[field.name] = fieldValue;
}
return coercedObj;
}
if (isLeafType(type)) {
// Scalars and Enums fulfill parsing a literal value via parseLiteral().
// Invalid values represent a failure to parse correctly, in which case
// no value is returned.
let result;
try {
result = type.parseLiteral(valueNode, variables);
} catch (_error) {
return; // Invalid: intentionally return no value.
}
if (result === undefined) {
return; // Invalid: intentionally return no value.
}
return result;
}
/* c8 ignore next 3 */
// Not reachable, all possible input types have been considered.
false || invariant(false, 'Unexpected input type: ' + inspect(type));
} // Returns true if the provided valueNode is a variable which is not defined
// in the set of variables.
function isMissingVariable(valueNode, variables) {
return (
valueNode.kind === Kind.VARIABLE &&
(variables == null || variables[valueNode.name.value] === undefined)
);
}

View File

@@ -0,0 +1,23 @@
import type { Maybe } from '../jsutils/Maybe';
import type { ObjMap } from '../jsutils/ObjMap';
import type { ValueNode } from '../language/ast';
/**
* Produces a JavaScript value given a GraphQL Value AST.
*
* Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value
* will reflect the provided GraphQL value AST.
*
* | GraphQL Value | JavaScript Value |
* | -------------------- | ---------------- |
* | Input Object | Object |
* | List | Array |
* | Boolean | Boolean |
* | String / Enum | String |
* | Int / Float | Number |
* | Null | null |
*
*/
export declare function valueFromASTUntyped(
valueNode: ValueNode,
variables?: Maybe<ObjMap<unknown>>,
): unknown;

View File

@@ -0,0 +1,61 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.valueFromASTUntyped = valueFromASTUntyped;
var _keyValMap = require('../jsutils/keyValMap.js');
var _kinds = require('../language/kinds.js');
/**
* Produces a JavaScript value given a GraphQL Value AST.
*
* Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value
* will reflect the provided GraphQL value AST.
*
* | GraphQL Value | JavaScript Value |
* | -------------------- | ---------------- |
* | Input Object | Object |
* | List | Array |
* | Boolean | Boolean |
* | String / Enum | String |
* | Int / Float | Number |
* | Null | null |
*
*/
function valueFromASTUntyped(valueNode, variables) {
switch (valueNode.kind) {
case _kinds.Kind.NULL:
return null;
case _kinds.Kind.INT:
return parseInt(valueNode.value, 10);
case _kinds.Kind.FLOAT:
return parseFloat(valueNode.value);
case _kinds.Kind.STRING:
case _kinds.Kind.ENUM:
case _kinds.Kind.BOOLEAN:
return valueNode.value;
case _kinds.Kind.LIST:
return valueNode.values.map((node) =>
valueFromASTUntyped(node, variables),
);
case _kinds.Kind.OBJECT:
return (0, _keyValMap.keyValMap)(
valueNode.fields,
(field) => field.name.value,
(field) => valueFromASTUntyped(field.value, variables),
);
case _kinds.Kind.VARIABLE:
return variables === null || variables === void 0
? void 0
: variables[valueNode.name.value];
}
}

View File

@@ -0,0 +1,53 @@
import { keyValMap } from '../jsutils/keyValMap.mjs';
import { Kind } from '../language/kinds.mjs';
/**
* Produces a JavaScript value given a GraphQL Value AST.
*
* Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value
* will reflect the provided GraphQL value AST.
*
* | GraphQL Value | JavaScript Value |
* | -------------------- | ---------------- |
* | Input Object | Object |
* | List | Array |
* | Boolean | Boolean |
* | String / Enum | String |
* | Int / Float | Number |
* | Null | null |
*
*/
export function valueFromASTUntyped(valueNode, variables) {
switch (valueNode.kind) {
case Kind.NULL:
return null;
case Kind.INT:
return parseInt(valueNode.value, 10);
case Kind.FLOAT:
return parseFloat(valueNode.value);
case Kind.STRING:
case Kind.ENUM:
case Kind.BOOLEAN:
return valueNode.value;
case Kind.LIST:
return valueNode.values.map((node) =>
valueFromASTUntyped(node, variables),
);
case Kind.OBJECT:
return keyValMap(
valueNode.fields,
(field) => field.name.value,
(field) => valueFromASTUntyped(field.value, variables),
);
case Kind.VARIABLE:
return variables === null || variables === void 0
? void 0
: variables[valueNode.name.value];
}
}