diff options
Diffstat (limited to 'school/node_modules/graphql')
535 files changed, 67897 insertions, 0 deletions
diff --git a/school/node_modules/graphql/LICENSE b/school/node_modules/graphql/LICENSE new file mode 100644 index 0000000..7bbf892 --- /dev/null +++ b/school/node_modules/graphql/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) GraphQL Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/school/node_modules/graphql/README.md b/school/node_modules/graphql/README.md new file mode 100644 index 0000000..733e424 --- /dev/null +++ b/school/node_modules/graphql/README.md @@ -0,0 +1,177 @@ +# GraphQL.js + +The JavaScript reference implementation for GraphQL, a query language for APIs created by Facebook. + +[![npm version](https://badge.fury.io/js/graphql.svg)](https://badge.fury.io/js/graphql) +[![Build Status](https://github.com/graphql/graphql-js/workflows/CI/badge.svg?branch=master)](https://github.com/graphql/graphql-js/actions?query=branch%3Amaster) +[![Coverage Status](https://codecov.io/gh/graphql/graphql-js/branch/master/graph/badge.svg)](https://codecov.io/gh/graphql/graphql-js) + +See more complete documentation at https://graphql.org/ and +https://graphql.org/graphql-js/. + +Looking for help? Find resources [from the community](https://graphql.org/community/). + +## Getting Started + +A general overview of GraphQL is available in the +[README](https://github.com/graphql/graphql-spec/blob/master/README.md) for the +[Specification for GraphQL](https://github.com/graphql/graphql-spec). That overview +describes a simple set of GraphQL examples that exist as [tests](src/__tests__) +in this repository. A good way to get started with this repository is to walk +through that README and the corresponding tests in parallel. + +### Using GraphQL.js + +Install GraphQL.js from npm + +With npm: + +```sh +npm install --save graphql +``` + +or using yarn: + +```sh +yarn add graphql +``` + +GraphQL.js provides two important capabilities: building a type schema and +serving queries against that type schema. + +First, build a GraphQL type schema which maps to your codebase. + +```js +import { + graphql, + GraphQLSchema, + GraphQLObjectType, + GraphQLString, +} from 'graphql'; + +var schema = new GraphQLSchema({ + query: new GraphQLObjectType({ + name: 'RootQueryType', + fields: { + hello: { + type: GraphQLString, + resolve() { + return 'world'; + }, + }, + }, + }), +}); +``` + +This defines a simple schema, with one type and one field, that resolves +to a fixed value. The `resolve` function can return a value, a promise, +or an array of promises. A more complex example is included in the top-level [tests](src/__tests__) directory. + +Then, serve the result of a query against that type schema. + +```js +var query = '{ hello }'; + +graphql(schema, query).then((result) => { + // Prints + // { + // data: { hello: "world" } + // } + console.log(result); +}); +``` + +This runs a query fetching the one field defined. The `graphql` function will +first ensure the query is syntactically and semantically valid before executing +it, reporting errors otherwise. + +```js +var query = '{ BoyHowdy }'; + +graphql(schema, query).then((result) => { + // Prints + // { + // errors: [ + // { message: 'Cannot query field BoyHowdy on RootQueryType', + // locations: [ { line: 1, column: 3 } ] } + // ] + // } + console.log(result); +}); +``` + +**Note**: Please don't forget to set `NODE_ENV=production` if you are running a production server. It will disable some checks that can be useful during development but will significantly improve performance. + +### Want to ride the bleeding edge? + +The `npm` branch in this repository is automatically maintained to be the last +commit to `master` to pass all tests, in the same form found on npm. It is +recommended to use builds deployed to npm for many reasons, but if you want to use +the latest not-yet-released version of graphql-js, you can do so by depending +directly on this branch: + +``` +npm install graphql@git://github.com/graphql/graphql-js.git#npm +``` + +### Experimental features + +Each release of GraphQL.js will be accompanied by an experimental release containing support for the `@defer` and `@stream` directive proposal. We are hoping to get community feedback on these releases before the proposal is accepted into the GraphQL specification. You can use this experimental release of GraphQL.js by adding the following to your project's `package.json` file. + +``` +"graphql": "experimental-stream-defer" +``` + +Community feedback on this experimental release is much appreciated and can be provided on the [issue created for this purpose](https://github.com/graphql/graphql-js/issues/2848). + +### Using in a Browser + +GraphQL.js is a general-purpose library and can be used both in a Node server +and in the browser. As an example, the [GraphiQL](https://github.com/graphql/graphiql/) +tool is built with GraphQL.js! + +Building a project using GraphQL.js with [webpack](https://webpack.js.org) or +[rollup](https://github.com/rollup/rollup) should just work and only include +the portions of the library you use. This works because GraphQL.js is distributed +with both CommonJS (`require()`) and ESModule (`import`) files. Ensure that any +custom build configurations look for `.mjs` files! + +### Contributing + +We actively welcome pull requests. Learn how to [contribute](./.github/CONTRIBUTING.md). + +### Changelog + +Changes are tracked as [GitHub releases](https://github.com/graphql/graphql-js/releases). + +### License + +GraphQL.js is [MIT-licensed](./LICENSE). + +### Credits + +The `*.d.ts` files in this project are based on [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/54712a7e28090c5b1253b746d1878003c954f3ff/types/graphql) definitions written by: + +<!--- spell-checker:disable --> + +- TonyYang https://github.com/TonyPythoneer +- Caleb Meredith https://github.com/calebmer +- Dominic Watson https://github.com/intellix +- Firede https://github.com/firede +- Kepennar https://github.com/kepennar +- Mikhail Novikov https://github.com/freiksenet +- Ivan Goncharov https://github.com/IvanGoncharov +- Hagai Cohen https://github.com/DxCx +- Ricardo Portugal https://github.com/rportugal +- Tim Griesser https://github.com/tgriesser +- Dylan Stewart https://github.com/dyst5422 +- Alessio Dionisi https://github.com/adnsio +- Divyendu Singh https://github.com/divyenduz +- Brad Zacher https://github.com/bradzacher +- Curtis Layne https://github.com/clayne11 +- Jonathan Cardoso https://github.com/JCMais +- Pavel Lang https://github.com/langpavel +- Mark Caudill https://github.com/mc0 +- Martijn Walraven https://github.com/martijnwalraven +- Jed Mao https://github.com/jedmao diff --git a/school/node_modules/graphql/error/GraphQLError.d.ts b/school/node_modules/graphql/error/GraphQLError.d.ts new file mode 100644 index 0000000..95f39ba --- /dev/null +++ b/school/node_modules/graphql/error/GraphQLError.d.ts @@ -0,0 +1,91 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { ASTNode } from '../language/ast'; +import { Source } from '../language/source'; +import { SourceLocation } from '../language/location'; + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLErrorExtensions { + [attributeName: string]: any; +} + +/** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ +export class GraphQLError extends Error { + constructor( + message: string, + nodes?: Maybe<ReadonlyArray<ASTNode> | ASTNode>, + source?: Maybe<Source>, + positions?: Maybe<ReadonlyArray<number>>, + path?: Maybe<ReadonlyArray<string | number>>, + originalError?: Maybe<Error>, + extensions?: Maybe<GraphQLErrorExtensions>, + ); + + /** + * An array of { line, column } locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + readonly locations: ReadonlyArray<SourceLocation> | undefined; + + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + readonly path: ReadonlyArray<string | number> | undefined; + + /** + * An array of GraphQL AST Nodes corresponding to this error. + */ + readonly nodes: ReadonlyArray<ASTNode> | undefined; + + /** + * The source GraphQL document corresponding to this error. + * + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. + */ + readonly source: Source | undefined; + + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + readonly positions: ReadonlyArray<number> | undefined; + + /** + * The original error thrown from a field resolver during execution. + */ + readonly originalError: Error | undefined | null; + + /** + * Extension fields to add to the formatted error. + */ + readonly extensions: { [key: string]: any }; +} + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + */ +export function printError(error: GraphQLError): string; diff --git a/school/node_modules/graphql/error/GraphQLError.js b/school/node_modules/graphql/error/GraphQLError.js new file mode 100644 index 0000000..e4c6b8d --- /dev/null +++ b/school/node_modules/graphql/error/GraphQLError.js @@ -0,0 +1,252 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.printError = printError; +exports.GraphQLError = void 0; + +var _isObjectLike = _interopRequireDefault(require("../jsutils/isObjectLike.js")); + +var _symbols = require("../polyfills/symbols.js"); + +var _location = require("../language/location.js"); + +var _printLocation = require("../language/printLocation.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } + +function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +/** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ +var GraphQLError = /*#__PURE__*/function (_Error) { + _inherits(GraphQLError, _Error); + + var _super = _createSuper(GraphQLError); + + /** + * An array of { line, column } locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + + /** + * An array of GraphQL AST Nodes corresponding to this error. + */ + + /** + * The source GraphQL document for the first location of this error. + * + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. + */ + + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + + /** + * The original error thrown from a field resolver during execution. + */ + + /** + * Extension fields to add to the formatted error. + */ + function GraphQLError(message, nodes, source, positions, path, originalError, extensions) { + var _nodeLocations, _nodeLocations2, _nodeLocations3; + + var _this; + + _classCallCheck(this, GraphQLError); + + _this = _super.call(this, message); + _this.name = 'GraphQLError'; + _this.originalError = originalError !== null && originalError !== void 0 ? originalError : undefined; // Compute list of blame nodes. + + _this.nodes = undefinedIfEmpty(Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined); + var nodeLocations = []; + + for (var _i2 = 0, _ref3 = (_this$nodes = _this.nodes) !== null && _this$nodes !== void 0 ? _this$nodes : []; _i2 < _ref3.length; _i2++) { + var _this$nodes; + + var _ref4 = _ref3[_i2]; + var loc = _ref4.loc; + + if (loc != null) { + nodeLocations.push(loc); + } + } + + nodeLocations = undefinedIfEmpty(nodeLocations); // Compute locations in the source for the given nodes/positions. + + _this.source = source !== null && source !== void 0 ? source : (_nodeLocations = nodeLocations) === null || _nodeLocations === void 0 ? void 0 : _nodeLocations[0].source; + _this.positions = positions !== null && positions !== void 0 ? positions : (_nodeLocations2 = nodeLocations) === null || _nodeLocations2 === void 0 ? void 0 : _nodeLocations2.map(function (loc) { + return loc.start; + }); + _this.locations = positions && source ? positions.map(function (pos) { + return (0, _location.getLocation)(source, pos); + }) : (_nodeLocations3 = nodeLocations) === null || _nodeLocations3 === void 0 ? void 0 : _nodeLocations3.map(function (loc) { + return (0, _location.getLocation)(loc.source, loc.start); + }); + _this.path = path !== null && path !== void 0 ? path : undefined; + var originalExtensions = originalError === null || originalError === void 0 ? void 0 : originalError.extensions; + + if (extensions == null && (0, _isObjectLike.default)(originalExtensions)) { + _this.extensions = _objectSpread({}, originalExtensions); + } else { + _this.extensions = extensions !== null && extensions !== void 0 ? extensions : {}; + } // By being enumerable, JSON.stringify will include bellow properties in the resulting output. + // This ensures that the simplest possible GraphQL service adheres to the spec. + + + Object.defineProperties(_assertThisInitialized(_this), { + message: { + enumerable: true + }, + locations: { + enumerable: _this.locations != null + }, + path: { + enumerable: _this.path != null + }, + extensions: { + enumerable: _this.extensions != null && Object.keys(_this.extensions).length > 0 + }, + name: { + enumerable: false + }, + nodes: { + enumerable: false + }, + source: { + enumerable: false + }, + positions: { + enumerable: false + }, + originalError: { + enumerable: false + } + }); // Include (non-enumerable) stack trace. + + if (originalError !== null && originalError !== void 0 && originalError.stack) { + Object.defineProperty(_assertThisInitialized(_this), 'stack', { + value: originalError.stack, + writable: true, + configurable: true + }); + return _possibleConstructorReturn(_this); + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') + + + if (Error.captureStackTrace) { + Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError); + } else { + Object.defineProperty(_assertThisInitialized(_this), 'stack', { + value: Error().stack, + writable: true, + configurable: true + }); + } + + return _this; + } + + _createClass(GraphQLError, [{ + key: "toString", + value: function toString() { + return printError(this); + } // FIXME: workaround to not break chai comparisons, should be remove in v16 + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + + }, { + key: _symbols.SYMBOL_TO_STRING_TAG, + get: function get() { + return 'Object'; + } + }]); + + return GraphQLError; +}( /*#__PURE__*/_wrapNativeSuper(Error)); + +exports.GraphQLError = GraphQLError; + +function undefinedIfEmpty(array) { + return array === undefined || array.length === 0 ? undefined : array; +} +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + */ + + +function printError(error) { + var output = error.message; + + if (error.nodes) { + for (var _i4 = 0, _error$nodes2 = error.nodes; _i4 < _error$nodes2.length; _i4++) { + var node = _error$nodes2[_i4]; + + if (node.loc) { + output += '\n\n' + (0, _printLocation.printLocation)(node.loc); + } + } + } else if (error.source && error.locations) { + for (var _i6 = 0, _error$locations2 = error.locations; _i6 < _error$locations2.length; _i6++) { + var location = _error$locations2[_i6]; + output += '\n\n' + (0, _printLocation.printSourceLocation)(error.source, location); + } + } + + return output; +} diff --git a/school/node_modules/graphql/error/GraphQLError.js.flow b/school/node_modules/graphql/error/GraphQLError.js.flow new file mode 100644 index 0000000..3d23ca5 --- /dev/null +++ b/school/node_modules/graphql/error/GraphQLError.js.flow @@ -0,0 +1,194 @@ +// @flow strict +import isObjectLike from '../jsutils/isObjectLike'; +import { SYMBOL_TO_STRING_TAG } from '../polyfills/symbols'; + +import type { ASTNode } from '../language/ast'; +import type { Source } from '../language/source'; +import type { SourceLocation } from '../language/location'; +import { getLocation } from '../language/location'; +import { printLocation, printSourceLocation } from '../language/printLocation'; + +/** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ +export class GraphQLError extends Error { + /** + * An array of { line, column } locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + +locations: $ReadOnlyArray<SourceLocation> | void; + + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + +path: $ReadOnlyArray<string | number> | void; + + /** + * An array of GraphQL AST Nodes corresponding to this error. + */ + +nodes: $ReadOnlyArray<ASTNode> | void; + + /** + * The source GraphQL document for the first location of this error. + * + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. + */ + +source: Source | void; + + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + +positions: $ReadOnlyArray<number> | void; + + /** + * The original error thrown from a field resolver during execution. + */ + +originalError: Error | void | null; + + /** + * Extension fields to add to the formatted error. + */ + +extensions: { [key: string]: mixed, ... }; + + constructor( + message: string, + nodes?: $ReadOnlyArray<ASTNode> | ASTNode | void | null, + source?: ?Source, + positions?: ?$ReadOnlyArray<number>, + path?: ?$ReadOnlyArray<string | number>, + originalError?: ?(Error & { +extensions?: mixed, ... }), + extensions?: ?{ [key: string]: mixed, ... }, + ) { + super(message); + + this.name = 'GraphQLError'; + this.originalError = originalError ?? undefined; + + // Compute list of blame nodes. + this.nodes = undefinedIfEmpty( + Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined, + ); + + let nodeLocations = []; + for (const { loc } of this.nodes ?? []) { + if (loc != null) { + nodeLocations.push(loc); + } + } + nodeLocations = undefinedIfEmpty(nodeLocations); + + // Compute locations in the source for the given nodes/positions. + this.source = source ?? nodeLocations?.[0].source; + + this.positions = positions ?? nodeLocations?.map((loc) => loc.start); + + this.locations = + positions && source + ? positions.map((pos) => getLocation(source, pos)) + : nodeLocations?.map((loc) => getLocation(loc.source, loc.start)); + + this.path = path ?? undefined; + + const originalExtensions = originalError?.extensions; + + if (extensions == null && isObjectLike(originalExtensions)) { + this.extensions = { ...originalExtensions }; + } else { + this.extensions = extensions ?? {}; + } + + // By being enumerable, JSON.stringify will include bellow properties in the resulting output. + // This ensures that the simplest possible GraphQL service adheres to the spec. + Object.defineProperties((this: any), { + message: { enumerable: true }, + locations: { + enumerable: this.locations != null, + }, + path: { + enumerable: this.path != null, + }, + extensions: { + enumerable: + this.extensions != null && Object.keys(this.extensions).length > 0, + }, + name: { enumerable: false }, + nodes: { enumerable: false }, + source: { enumerable: false }, + positions: { enumerable: false }, + originalError: { enumerable: false }, + }); + + // Include (non-enumerable) stack trace. + if (originalError?.stack) { + Object.defineProperty(this, 'stack', { + value: originalError.stack, + writable: true, + configurable: true, + }); + return; + } + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') + if (Error.captureStackTrace) { + Error.captureStackTrace(this, GraphQLError); + } else { + Object.defineProperty(this, 'stack', { + value: Error().stack, + writable: true, + configurable: true, + }); + } + } + + toString(): string { + return printError(this); + } + + // FIXME: workaround to not break chai comparisons, should be remove in v16 + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + get [SYMBOL_TO_STRING_TAG](): string { + return 'Object'; + } +} + +function undefinedIfEmpty<T>( + array: $ReadOnlyArray<T> | void, +): $ReadOnlyArray<T> | void { + return array === undefined || array.length === 0 ? undefined : array; +} + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + */ +export function printError(error: GraphQLError): string { + let output = error.message; + + if (error.nodes) { + for (const node of error.nodes) { + if (node.loc) { + output += '\n\n' + printLocation(node.loc); + } + } + } else if (error.source && error.locations) { + for (const location of error.locations) { + output += '\n\n' + printSourceLocation(error.source, location); + } + } + + return output; +} diff --git a/school/node_modules/graphql/error/GraphQLError.mjs b/school/node_modules/graphql/error/GraphQLError.mjs new file mode 100644 index 0000000..34a30cc --- /dev/null +++ b/school/node_modules/graphql/error/GraphQLError.mjs @@ -0,0 +1,237 @@ +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } + +function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +import isObjectLike from "../jsutils/isObjectLike.mjs"; +import { SYMBOL_TO_STRING_TAG } from "../polyfills/symbols.mjs"; +import { getLocation } from "../language/location.mjs"; +import { printLocation, printSourceLocation } from "../language/printLocation.mjs"; +/** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ + +export var GraphQLError = /*#__PURE__*/function (_Error) { + _inherits(GraphQLError, _Error); + + var _super = _createSuper(GraphQLError); + + /** + * An array of { line, column } locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + + /** + * An array of GraphQL AST Nodes corresponding to this error. + */ + + /** + * The source GraphQL document for the first location of this error. + * + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. + */ + + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + + /** + * The original error thrown from a field resolver during execution. + */ + + /** + * Extension fields to add to the formatted error. + */ + function GraphQLError(message, nodes, source, positions, path, originalError, extensions) { + var _nodeLocations, _nodeLocations2, _nodeLocations3; + + var _this; + + _classCallCheck(this, GraphQLError); + + _this = _super.call(this, message); + _this.name = 'GraphQLError'; + _this.originalError = originalError !== null && originalError !== void 0 ? originalError : undefined; // Compute list of blame nodes. + + _this.nodes = undefinedIfEmpty(Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined); + var nodeLocations = []; + + for (var _i2 = 0, _ref3 = (_this$nodes = _this.nodes) !== null && _this$nodes !== void 0 ? _this$nodes : []; _i2 < _ref3.length; _i2++) { + var _this$nodes; + + var _ref4 = _ref3[_i2]; + var loc = _ref4.loc; + + if (loc != null) { + nodeLocations.push(loc); + } + } + + nodeLocations = undefinedIfEmpty(nodeLocations); // Compute locations in the source for the given nodes/positions. + + _this.source = source !== null && source !== void 0 ? source : (_nodeLocations = nodeLocations) === null || _nodeLocations === void 0 ? void 0 : _nodeLocations[0].source; + _this.positions = positions !== null && positions !== void 0 ? positions : (_nodeLocations2 = nodeLocations) === null || _nodeLocations2 === void 0 ? void 0 : _nodeLocations2.map(function (loc) { + return loc.start; + }); + _this.locations = positions && source ? positions.map(function (pos) { + return getLocation(source, pos); + }) : (_nodeLocations3 = nodeLocations) === null || _nodeLocations3 === void 0 ? void 0 : _nodeLocations3.map(function (loc) { + return getLocation(loc.source, loc.start); + }); + _this.path = path !== null && path !== void 0 ? path : undefined; + var originalExtensions = originalError === null || originalError === void 0 ? void 0 : originalError.extensions; + + if (extensions == null && isObjectLike(originalExtensions)) { + _this.extensions = _objectSpread({}, originalExtensions); + } else { + _this.extensions = extensions !== null && extensions !== void 0 ? extensions : {}; + } // By being enumerable, JSON.stringify will include bellow properties in the resulting output. + // This ensures that the simplest possible GraphQL service adheres to the spec. + + + Object.defineProperties(_assertThisInitialized(_this), { + message: { + enumerable: true + }, + locations: { + enumerable: _this.locations != null + }, + path: { + enumerable: _this.path != null + }, + extensions: { + enumerable: _this.extensions != null && Object.keys(_this.extensions).length > 0 + }, + name: { + enumerable: false + }, + nodes: { + enumerable: false + }, + source: { + enumerable: false + }, + positions: { + enumerable: false + }, + originalError: { + enumerable: false + } + }); // Include (non-enumerable) stack trace. + + if (originalError !== null && originalError !== void 0 && originalError.stack) { + Object.defineProperty(_assertThisInitialized(_this), 'stack', { + value: originalError.stack, + writable: true, + configurable: true + }); + return _possibleConstructorReturn(_this); + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') + + + if (Error.captureStackTrace) { + Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError); + } else { + Object.defineProperty(_assertThisInitialized(_this), 'stack', { + value: Error().stack, + writable: true, + configurable: true + }); + } + + return _this; + } + + _createClass(GraphQLError, [{ + key: "toString", + value: function toString() { + return printError(this); + } // FIXME: workaround to not break chai comparisons, should be remove in v16 + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + + }, { + key: SYMBOL_TO_STRING_TAG, + get: function get() { + return 'Object'; + } + }]); + + return GraphQLError; +}( /*#__PURE__*/_wrapNativeSuper(Error)); + +function undefinedIfEmpty(array) { + return array === undefined || array.length === 0 ? undefined : array; +} +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + */ + + +export function printError(error) { + var output = error.message; + + if (error.nodes) { + for (var _i4 = 0, _error$nodes2 = error.nodes; _i4 < _error$nodes2.length; _i4++) { + var node = _error$nodes2[_i4]; + + if (node.loc) { + output += '\n\n' + printLocation(node.loc); + } + } + } else if (error.source && error.locations) { + for (var _i6 = 0, _error$locations2 = error.locations; _i6 < _error$locations2.length; _i6++) { + var location = _error$locations2[_i6]; + output += '\n\n' + printSourceLocation(error.source, location); + } + } + + return output; +} diff --git a/school/node_modules/graphql/error/formatError.d.ts b/school/node_modules/graphql/error/formatError.d.ts new file mode 100644 index 0000000..fb3451b --- /dev/null +++ b/school/node_modules/graphql/error/formatError.d.ts @@ -0,0 +1,40 @@ +import { SourceLocation } from '../language/location'; + +import { GraphQLError } from './GraphQLError'; + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +export function formatError(error: GraphQLError): GraphQLFormattedError; + +/** + * @see https://github.com/graphql/graphql-spec/blob/master/spec/Section%207%20--%20Response.md#errors + */ +export interface GraphQLFormattedError< + TExtensions extends Record<string, any> = Record<string, any> +> { + /** + * A short, human-readable summary of the problem that **SHOULD NOT** change + * from occurrence to occurrence of the problem, except for purposes of + * localization. + */ + readonly message: string; + /** + * If an error can be associated to a particular point in the requested + * GraphQL document, it should contain a list of locations. + */ + readonly locations?: ReadonlyArray<SourceLocation>; + /** + * If an error can be associated to a particular field in the GraphQL result, + * it _must_ contain an entry with the key `path` that details the path of + * the response field which experienced the error. This allows clients to + * identify whether a null result is intentional or caused by a runtime error. + */ + readonly path?: ReadonlyArray<string | number>; + /** + * Reserved for implementors to extend the protocol however they see fit, + * and hence there are no additional restrictions on its contents. + */ + readonly extensions?: TExtensions; +} diff --git a/school/node_modules/graphql/error/formatError.js b/school/node_modules/graphql/error/formatError.js new file mode 100644 index 0000000..1e620fc --- /dev/null +++ b/school/node_modules/graphql/error/formatError.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.formatError = formatError; + +var _devAssert = _interopRequireDefault(require("../jsutils/devAssert.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +function formatError(error) { + var _error$message; + + error || (0, _devAssert.default)(0, 'Received null or undefined error.'); + var message = (_error$message = error.message) !== null && _error$message !== void 0 ? _error$message : 'An unknown error occurred.'; + var locations = error.locations; + var path = error.path; + var extensions = error.extensions; + return extensions && Object.keys(extensions).length > 0 ? { + message: message, + locations: locations, + path: path, + extensions: extensions + } : { + message: message, + locations: locations, + path: path + }; +} +/** + * @see https://github.com/graphql/graphql-spec/blob/master/spec/Section%207%20--%20Response.md#errors + */ diff --git a/school/node_modules/graphql/error/formatError.js.flow b/school/node_modules/graphql/error/formatError.js.flow new file mode 100644 index 0000000..0ca934b --- /dev/null +++ b/school/node_modules/graphql/error/formatError.js.flow @@ -0,0 +1,51 @@ +// @flow strict +import devAssert from '../jsutils/devAssert'; + +import type { SourceLocation } from '../language/location'; + +import type { GraphQLError } from './GraphQLError'; + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +export function formatError(error: GraphQLError): GraphQLFormattedError { + devAssert(error, 'Received null or undefined error.'); + const message = error.message ?? 'An unknown error occurred.'; + const locations = error.locations; + const path = error.path; + const extensions = error.extensions; + + return extensions && Object.keys(extensions).length > 0 + ? { message, locations, path, extensions } + : { message, locations, path }; +} + +/** + * @see https://github.com/graphql/graphql-spec/blob/master/spec/Section%207%20--%20Response.md#errors + */ +export type GraphQLFormattedError = {| + /** + * A short, human-readable summary of the problem that **SHOULD NOT** change + * from occurrence to occurrence of the problem, except for purposes of + * localization. + */ + +message: string, + /** + * If an error can be associated to a particular point in the requested + * GraphQL document, it should contain a list of locations. + */ + +locations: $ReadOnlyArray<SourceLocation> | void, + /** + * If an error can be associated to a particular field in the GraphQL result, + * it _must_ contain an entry with the key `path` that details the path of + * the response field which experienced the error. This allows clients to + * identify whether a null result is intentional or caused by a runtime error. + */ + +path: $ReadOnlyArray<string | number> | void, + /** + * Reserved for implementors to extend the protocol however they see fit, + * and hence there are no additional restrictions on its contents. + */ + +extensions?: { [key: string]: mixed, ... }, +|}; diff --git a/school/node_modules/graphql/error/formatError.mjs b/school/node_modules/graphql/error/formatError.mjs new file mode 100644 index 0000000..0da3f5e --- /dev/null +++ b/school/node_modules/graphql/error/formatError.mjs @@ -0,0 +1,28 @@ +import devAssert from "../jsutils/devAssert.mjs"; + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +export function formatError(error) { + var _error$message; + + error || devAssert(0, 'Received null or undefined error.'); + var message = (_error$message = error.message) !== null && _error$message !== void 0 ? _error$message : 'An unknown error occurred.'; + var locations = error.locations; + var path = error.path; + var extensions = error.extensions; + return extensions && Object.keys(extensions).length > 0 ? { + message: message, + locations: locations, + path: path, + extensions: extensions + } : { + message: message, + locations: locations, + path: path + }; +} +/** + * @see https://github.com/graphql/graphql-spec/blob/master/spec/Section%207%20--%20Response.md#errors + */ diff --git a/school/node_modules/graphql/error/index.d.ts b/school/node_modules/graphql/error/index.d.ts new file mode 100644 index 0000000..38f7b7e --- /dev/null +++ b/school/node_modules/graphql/error/index.d.ts @@ -0,0 +1,8 @@ +export { + GraphQLError, + GraphQLErrorExtensions, + printError, +} from './GraphQLError'; +export { syntaxError } from './syntaxError'; +export { locatedError } from './locatedError'; +export { formatError, GraphQLFormattedError } from './formatError'; diff --git a/school/node_modules/graphql/error/index.js b/school/node_modules/graphql/error/index.js new file mode 100644 index 0000000..ee164b8 --- /dev/null +++ b/school/node_modules/graphql/error/index.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "GraphQLError", { + enumerable: true, + get: function get() { + return _GraphQLError.GraphQLError; + } +}); +Object.defineProperty(exports, "printError", { + enumerable: true, + get: function get() { + return _GraphQLError.printError; + } +}); +Object.defineProperty(exports, "syntaxError", { + enumerable: true, + get: function get() { + return _syntaxError.syntaxError; + } +}); +Object.defineProperty(exports, "locatedError", { + enumerable: true, + get: function get() { + return _locatedError.locatedError; + } +}); +Object.defineProperty(exports, "formatError", { + enumerable: true, + get: function get() { + return _formatError.formatError; + } +}); + +var _GraphQLError = require("./GraphQLError.js"); + +var _syntaxError = require("./syntaxError.js"); + +var _locatedError = require("./locatedError.js"); + +var _formatError = require("./formatError.js"); diff --git a/school/node_modules/graphql/error/index.js.flow b/school/node_modules/graphql/error/index.js.flow new file mode 100644 index 0000000..eeaa96e --- /dev/null +++ b/school/node_modules/graphql/error/index.js.flow @@ -0,0 +1,9 @@ +// @flow strict +export { GraphQLError, printError } from './GraphQLError'; + +export { syntaxError } from './syntaxError'; + +export { locatedError } from './locatedError'; + +export { formatError } from './formatError'; +export type { GraphQLFormattedError } from './formatError'; diff --git a/school/node_modules/graphql/error/index.mjs b/school/node_modules/graphql/error/index.mjs new file mode 100644 index 0000000..5ac29d1 --- /dev/null +++ b/school/node_modules/graphql/error/index.mjs @@ -0,0 +1,4 @@ +export { GraphQLError, printError } from "./GraphQLError.mjs"; +export { syntaxError } from "./syntaxError.mjs"; +export { locatedError } from "./locatedError.mjs"; +export { formatError } from "./formatError.mjs"; diff --git a/school/node_modules/graphql/error/locatedError.d.ts b/school/node_modules/graphql/error/locatedError.d.ts new file mode 100644 index 0000000..8693757 --- /dev/null +++ b/school/node_modules/graphql/error/locatedError.d.ts @@ -0,0 +1,16 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { ASTNode } from '../language/ast'; + +import { GraphQLError } from './GraphQLError'; + +/** + * Given an arbitrary value, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + */ +export function locatedError( + rawOriginalError: any, + nodes: ASTNode | ReadonlyArray<ASTNode> | undefined, + path?: Maybe<ReadonlyArray<string | number>>, +): GraphQLError; diff --git a/school/node_modules/graphql/error/locatedError.js b/school/node_modules/graphql/error/locatedError.js new file mode 100644 index 0000000..658c439 --- /dev/null +++ b/school/node_modules/graphql/error/locatedError.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.locatedError = locatedError; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _GraphQLError = require("./GraphQLError.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Given an arbitrary value, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + */ +function locatedError(rawOriginalError, nodes, path) { + var _nodes; + + // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. + var originalError = rawOriginalError instanceof Error ? rawOriginalError : new Error('Unexpected error value: ' + (0, _inspect.default)(rawOriginalError)); // Note: this uses a brand-check to support GraphQL errors originating from other contexts. + + if (Array.isArray(originalError.path)) { + return originalError; + } + + return new _GraphQLError.GraphQLError(originalError.message, (_nodes = originalError.nodes) !== null && _nodes !== void 0 ? _nodes : nodes, originalError.source, originalError.positions, path, originalError); +} diff --git a/school/node_modules/graphql/error/locatedError.js.flow b/school/node_modules/graphql/error/locatedError.js.flow new file mode 100644 index 0000000..3ef40c8 --- /dev/null +++ b/school/node_modules/graphql/error/locatedError.js.flow @@ -0,0 +1,37 @@ +// @flow strict +import inspect from '../jsutils/inspect'; + +import type { ASTNode } from '../language/ast'; + +import { GraphQLError } from './GraphQLError'; + +/** + * Given an arbitrary value, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + */ +export function locatedError( + rawOriginalError: mixed, + nodes: ASTNode | $ReadOnlyArray<ASTNode> | void | null, + path?: ?$ReadOnlyArray<string | number>, +): GraphQLError { + // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. + const originalError: Error | GraphQLError = + rawOriginalError instanceof Error + ? rawOriginalError + : new Error('Unexpected error value: ' + inspect(rawOriginalError)); + + // Note: this uses a brand-check to support GraphQL errors originating from other contexts. + if (Array.isArray(originalError.path)) { + return (originalError: any); + } + + return new GraphQLError( + originalError.message, + (originalError: any).nodes ?? nodes, + (originalError: any).source, + (originalError: any).positions, + path, + originalError, + ); +} diff --git a/school/node_modules/graphql/error/locatedError.mjs b/school/node_modules/graphql/error/locatedError.mjs new file mode 100644 index 0000000..48f4d54 --- /dev/null +++ b/school/node_modules/graphql/error/locatedError.mjs @@ -0,0 +1,20 @@ +import inspect from "../jsutils/inspect.mjs"; +import { GraphQLError } from "./GraphQLError.mjs"; +/** + * Given an arbitrary value, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + */ + +export function locatedError(rawOriginalError, nodes, path) { + var _nodes; + + // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. + var originalError = rawOriginalError instanceof Error ? rawOriginalError : new Error('Unexpected error value: ' + inspect(rawOriginalError)); // Note: this uses a brand-check to support GraphQL errors originating from other contexts. + + if (Array.isArray(originalError.path)) { + return originalError; + } + + return new GraphQLError(originalError.message, (_nodes = originalError.nodes) !== null && _nodes !== void 0 ? _nodes : nodes, originalError.source, originalError.positions, path, originalError); +} diff --git a/school/node_modules/graphql/error/syntaxError.d.ts b/school/node_modules/graphql/error/syntaxError.d.ts new file mode 100644 index 0000000..1c5413c --- /dev/null +++ b/school/node_modules/graphql/error/syntaxError.d.ts @@ -0,0 +1,13 @@ +import { Source } from '../language/source'; + +import { GraphQLError } from './GraphQLError'; + +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ +export function syntaxError( + source: Source, + position: number, + description: string, +): GraphQLError; diff --git a/school/node_modules/graphql/error/syntaxError.js b/school/node_modules/graphql/error/syntaxError.js new file mode 100644 index 0000000..4804584 --- /dev/null +++ b/school/node_modules/graphql/error/syntaxError.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.syntaxError = syntaxError; + +var _GraphQLError = require("./GraphQLError.js"); + +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ +function syntaxError(source, position, description) { + return new _GraphQLError.GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]); +} diff --git a/school/node_modules/graphql/error/syntaxError.js.flow b/school/node_modules/graphql/error/syntaxError.js.flow new file mode 100644 index 0000000..cdddcc3 --- /dev/null +++ b/school/node_modules/graphql/error/syntaxError.js.flow @@ -0,0 +1,18 @@ +// @flow strict +import type { Source } from '../language/source'; + +import { GraphQLError } from './GraphQLError'; + +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ +export function syntaxError( + source: Source, + position: number, + description: string, +): GraphQLError { + return new GraphQLError(`Syntax Error: ${description}`, undefined, source, [ + position, + ]); +} diff --git a/school/node_modules/graphql/error/syntaxError.mjs b/school/node_modules/graphql/error/syntaxError.mjs new file mode 100644 index 0000000..33aae5a --- /dev/null +++ b/school/node_modules/graphql/error/syntaxError.mjs @@ -0,0 +1,9 @@ +import { GraphQLError } from "./GraphQLError.mjs"; +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ + +export function syntaxError(source, position, description) { + return new GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]); +} diff --git a/school/node_modules/graphql/execution/execute.d.ts b/school/node_modules/graphql/execution/execute.d.ts new file mode 100644 index 0000000..a20db8c --- /dev/null +++ b/school/node_modules/graphql/execution/execute.d.ts @@ -0,0 +1,195 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { PromiseOrValue } from '../jsutils/PromiseOrValue'; +import { Path } from '../jsutils/Path'; + +import { GraphQLError } from '../error/GraphQLError'; +import { GraphQLFormattedError } from '../error/formatError'; + +import { + DocumentNode, + OperationDefinitionNode, + SelectionSetNode, + FieldNode, + FragmentDefinitionNode, +} from '../language/ast'; +import { GraphQLSchema } from '../type/schema'; +import { + GraphQLField, + GraphQLFieldResolver, + GraphQLResolveInfo, + GraphQLTypeResolver, + GraphQLObjectType, +} from '../type/definition'; + +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + */ +export interface ExecutionContext { + schema: GraphQLSchema; + fragments: { [key: string]: FragmentDefinitionNode }; + rootValue: any; + contextValue: any; + operation: OperationDefinitionNode; + variableValues: { [key: string]: any }; + fieldResolver: GraphQLFieldResolver<any, any>; + errors: Array<GraphQLError>; +} + +/** + * The result of GraphQL execution. + * + * - `errors` is included when any errors occurred as a non-empty array. + * - `data` is the result of a successful execution of the query. + * - `extensions` is reserved for adding non-standard properties. + */ +export interface ExecutionResult< + TData = { [key: string]: any }, + TExtensions = { [key: string]: any } +> { + errors?: ReadonlyArray<GraphQLError>; + // TS_SPECIFIC: TData. Motivation: https://github.com/graphql/graphql-js/pull/2490#issuecomment-639154229 + data?: TData | null; + extensions?: TExtensions; +} + +export interface FormattedExecutionResult< + TData = { [key: string]: any }, + TExtensions = { [key: string]: any } +> { + errors?: ReadonlyArray<GraphQLFormattedError>; + // TS_SPECIFIC: TData. Motivation: https://github.com/graphql/graphql-js/pull/2490#issuecomment-639154229 + data?: TData | null; + extensions?: TExtensions; +} + +export interface ExecutionArgs { + schema: GraphQLSchema; + document: DocumentNode; + rootValue?: any; + contextValue?: any; + variableValues?: Maybe<{ [key: string]: any }>; + operationName?: Maybe<string>; + fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>; + typeResolver?: Maybe<GraphQLTypeResolver<any, any>>; +} + +/** + * Implements the "Evaluating requests" section of the GraphQL specification. + * + * Returns either a synchronous ExecutionResult (if all encountered resolvers + * are synchronous), or a Promise of an ExecutionResult that will eventually be + * resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + * + * Accepts either an object with named arguments, or individual arguments. + */ +export function execute(args: ExecutionArgs): PromiseOrValue<ExecutionResult>; +export function execute( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: any, + contextValue?: any, + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe<string>, + fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>, + typeResolver?: Maybe<GraphQLTypeResolver<any, any>>, +): PromiseOrValue<ExecutionResult>; + +/** + * Also implements the "Evaluating requests" section of the GraphQL specification. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ +export function executeSync(args: ExecutionArgs): ExecutionResult; + +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + */ +export function assertValidExecutionArguments( + schema: GraphQLSchema, + document: DocumentNode, + rawVariableValues: Maybe<{ [key: string]: any }>, +): void; + +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + */ +export function buildExecutionContext( + schema: GraphQLSchema, + document: DocumentNode, + rootValue: any, + contextValue: any, + rawVariableValues: Maybe<{ [key: string]: any }>, + operationName: Maybe<string>, + fieldResolver: Maybe<GraphQLFieldResolver<any, any>>, + typeResolver?: Maybe<GraphQLTypeResolver<any, any>>, +): ReadonlyArray<GraphQLError> | ExecutionContext; + +/** + * Given a selectionSet, adds all of the fields in that selection to + * the passed in map of fields, and returns it at the end. + * + * CollectFields requires the "runtime type" of an object. For a field which + * returns an Interface or Union type, the "runtime type" will be the actual + * Object type returned by that field. + */ +export function collectFields( + exeContext: ExecutionContext, + runtimeType: GraphQLObjectType, + selectionSet: SelectionSetNode, + fields: { [key: string]: Array<FieldNode> }, + visitedFragmentNames: { [key: string]: boolean }, +): { [key: string]: Array<FieldNode> }; + +export function buildResolveInfo( + exeContext: ExecutionContext, + fieldDef: GraphQLField<any, any>, + fieldNodes: ReadonlyArray<FieldNode>, + parentType: GraphQLObjectType, + path: Path, +): GraphQLResolveInfo; + +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ +export const defaultTypeResolver: GraphQLTypeResolver<any, any>; + +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context. + */ +export const defaultFieldResolver: GraphQLFieldResolver<any, any>; + +/** + * This method looks up the field on the given type definition. + * It has special casing for the two introspection fields, __schema + * and __typename. __typename is special because it can always be + * queried as a field, even in situations where no other fields + * are allowed, like on a Union. __schema could get automatically + * added to the query type, but that would require mutating type + * definitions, which would cause issues. + */ +export function getFieldDef( + schema: GraphQLSchema, + parentType: GraphQLObjectType, + fieldName: string, +): Maybe<GraphQLField<any, any>>; diff --git a/school/node_modules/graphql/execution/execute.js b/school/node_modules/graphql/execution/execute.js new file mode 100644 index 0000000..cf4e628 --- /dev/null +++ b/school/node_modules/graphql/execution/execute.js @@ -0,0 +1,866 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.execute = execute; +exports.executeSync = executeSync; +exports.assertValidExecutionArguments = assertValidExecutionArguments; +exports.buildExecutionContext = buildExecutionContext; +exports.collectFields = collectFields; +exports.buildResolveInfo = buildResolveInfo; +exports.getFieldDef = getFieldDef; +exports.defaultFieldResolver = exports.defaultTypeResolver = void 0; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _memoize = _interopRequireDefault(require("../jsutils/memoize3.js")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _devAssert = _interopRequireDefault(require("../jsutils/devAssert.js")); + +var _isPromise = _interopRequireDefault(require("../jsutils/isPromise.js")); + +var _isObjectLike = _interopRequireDefault(require("../jsutils/isObjectLike.js")); + +var _safeArrayFrom = _interopRequireDefault(require("../jsutils/safeArrayFrom.js")); + +var _promiseReduce = _interopRequireDefault(require("../jsutils/promiseReduce.js")); + +var _promiseForObject = _interopRequireDefault(require("../jsutils/promiseForObject.js")); + +var _Path = require("../jsutils/Path.js"); + +var _GraphQLError = require("../error/GraphQLError.js"); + +var _locatedError = require("../error/locatedError.js"); + +var _kinds = require("../language/kinds.js"); + +var _validate = require("../type/validate.js"); + +var _introspection = require("../type/introspection.js"); + +var _directives = require("../type/directives.js"); + +var _definition = require("../type/definition.js"); + +var _typeFromAST = require("../utilities/typeFromAST.js"); + +var _getOperationRootType = require("../utilities/getOperationRootType.js"); + +var _values = require("./values.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? executeImpl(argsOrSchema) : executeImpl({ + schema: argsOrSchema, + document: document, + rootValue: rootValue, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver, + typeResolver: typeResolver + }); +} +/** + * Also implements the "Evaluating requests" section of the GraphQL specification. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + + +function executeSync(args) { + var result = executeImpl(args); // Assert that the execution was synchronous. + + if ((0, _isPromise.default)(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function executeImpl(args) { + var schema = args.schema, + document = args.document, + rootValue = args.rootValue, + contextValue = args.contextValue, + variableValues = args.variableValues, + operationName = args.operationName, + fieldResolver = args.fieldResolver, + typeResolver = args.typeResolver; // If arguments are missing or incorrect, throw an error. + + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver); // Return early errors if execution context failed. + + if (Array.isArray(exeContext)) { + return { + errors: exeContext + }; + } // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + + + var data = executeOperation(exeContext, exeContext.operation, rootValue); + return buildResponse(exeContext, data); +} +/** + * Given a completed execution context and data, build the { errors, data } + * response defined by the "Response" section of the GraphQL specification. + */ + + +function buildResponse(exeContext, data) { + if ((0, _isPromise.default)(data)) { + return data.then(function (resolved) { + return buildResponse(exeContext, resolved); + }); + } + + return exeContext.errors.length === 0 ? { + data: data + } : { + errors: exeContext.errors, + data: data + }; +} +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + * + * @internal + */ + + +function assertValidExecutionArguments(schema, document, rawVariableValues) { + document || (0, _devAssert.default)(0, 'Must provide document.'); // If the schema used for execution is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object. + + rawVariableValues == null || (0, _isObjectLike.default)(rawVariableValues) || (0, _devAssert.default)(0, 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.'); +} +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + * + * @internal + */ + + +function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver, typeResolver) { + var _definition$name, _operation$variableDe; + + var operation; + var fragments = Object.create(null); + + for (var _i2 = 0, _document$definitions2 = document.definitions; _i2 < _document$definitions2.length; _i2++) { + var definition = _document$definitions2[_i2]; + + switch (definition.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + if (operationName == null) { + if (operation !== undefined) { + return [new _GraphQLError.GraphQLError('Must provide operation name if query contains multiple operations.')]; + } + + operation = definition; + } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) { + operation = definition; + } + + break; + + case _kinds.Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + } + } + + if (!operation) { + if (operationName != null) { + return [new _GraphQLError.GraphQLError("Unknown operation named \"".concat(operationName, "\"."))]; + } + + return [new _GraphQLError.GraphQLError('Must provide an operation.')]; + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + + var variableDefinitions = (_operation$variableDe = operation.variableDefinitions) !== null && _operation$variableDe !== void 0 ? _operation$variableDe : []; + var coercedVariableValues = (0, _values.getVariableValues)(schema, variableDefinitions, rawVariableValues !== null && rawVariableValues !== void 0 ? rawVariableValues : {}, { + maxErrors: 50 + }); + + if (coercedVariableValues.errors) { + return coercedVariableValues.errors; + } + + return { + schema: schema, + fragments: fragments, + rootValue: rootValue, + contextValue: contextValue, + operation: operation, + variableValues: coercedVariableValues.coerced, + fieldResolver: fieldResolver !== null && fieldResolver !== void 0 ? fieldResolver : defaultFieldResolver, + typeResolver: typeResolver !== null && typeResolver !== void 0 ? typeResolver : defaultTypeResolver, + errors: [] + }; +} +/** + * Implements the "Evaluating operations" section of the spec. + */ + + +function executeOperation(exeContext, operation, rootValue) { + var type = (0, _getOperationRootType.getOperationRootType)(exeContext.schema, operation); + var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null)); + var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. + + try { + var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields); + + if ((0, _isPromise.default)(result)) { + return result.then(undefined, function (error) { + exeContext.errors.push(error); + return Promise.resolve(null); + }); + } + + return result; + } catch (error) { + exeContext.errors.push(error); + return null; + } +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "write" mode. + */ + + +function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { + return (0, _promiseReduce.default)(Object.keys(fields), function (results, responseName) { + var fieldNodes = fields[responseName]; + var fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result === undefined) { + return results; + } + + if ((0, _isPromise.default)(result)) { + return result.then(function (resolvedResult) { + results[responseName] = resolvedResult; + return results; + }); + } + + results[responseName] = result; + return results; + }, Object.create(null)); +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "read" mode. + */ + + +function executeFields(exeContext, parentType, sourceValue, path, fields) { + var results = Object.create(null); + var containsPromise = false; + + for (var _i4 = 0, _Object$keys2 = Object.keys(fields); _i4 < _Object$keys2.length; _i4++) { + var responseName = _Object$keys2[_i4]; + var fieldNodes = fields[responseName]; + var fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result !== undefined) { + results[responseName] = result; + + if ((0, _isPromise.default)(result)) { + containsPromise = true; + } + } + } // If there are no promises, we can just return the object + + + if (!containsPromise) { + return results; + } // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + + + return (0, _promiseForObject.default)(results); +} +/** + * Given a selectionSet, adds all of the fields in that selection to + * the passed in map of fields, and returns it at the end. + * + * CollectFields requires the "runtime type" of an object. For a field which + * returns an Interface or Union type, the "runtime type" will be the actual + * Object type returned by that field. + * + * @internal + */ + + +function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) { + for (var _i6 = 0, _selectionSet$selecti2 = selectionSet.selections; _i6 < _selectionSet$selecti2.length; _i6++) { + var selection = _selectionSet$selecti2[_i6]; + + switch (selection.kind) { + case _kinds.Kind.FIELD: + { + if (!shouldIncludeNode(exeContext, selection)) { + continue; + } + + var name = getFieldEntryKey(selection); + + if (!fields[name]) { + fields[name] = []; + } + + fields[name].push(selection); + break; + } + + case _kinds.Kind.INLINE_FRAGMENT: + { + if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames); + break; + } + + case _kinds.Kind.FRAGMENT_SPREAD: + { + var fragName = selection.name.value; + + if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) { + continue; + } + + visitedFragmentNames[fragName] = true; + var fragment = exeContext.fragments[fragName]; + + if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames); + break; + } + } + } + + return fields; +} +/** + * Determines if a field should be included based on the @include and @skip + * directives, where @skip has higher precedence than @include. + */ + + +function shouldIncludeNode(exeContext, node) { + var skip = (0, _values.getDirectiveValues)(_directives.GraphQLSkipDirective, node, exeContext.variableValues); + + if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) { + return false; + } + + var include = (0, _values.getDirectiveValues)(_directives.GraphQLIncludeDirective, node, exeContext.variableValues); + + if ((include === null || include === void 0 ? void 0 : include.if) === false) { + return false; + } + + return true; +} +/** + * Determines if a fragment is applicable to the given type. + */ + + +function doesFragmentConditionMatch(exeContext, fragment, type) { + var typeConditionNode = fragment.typeCondition; + + if (!typeConditionNode) { + return true; + } + + var conditionalType = (0, _typeFromAST.typeFromAST)(exeContext.schema, typeConditionNode); + + if (conditionalType === type) { + return true; + } + + if ((0, _definition.isAbstractType)(conditionalType)) { + return exeContext.schema.isSubType(conditionalType, type); + } + + return false; +} +/** + * Implements the logic to compute the key of a given field's entry + */ + + +function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; +} +/** + * Resolves the field on the given source object. In particular, this + * figures out the value that the field returns by calling its resolve function, + * then calls completeValue to complete promises, serialize scalars, or execute + * the sub-selection-set for objects. + */ + + +function resolveField(exeContext, parentType, source, fieldNodes, path) { + var _fieldDef$resolve; + + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName); + + if (!fieldDef) { + return; + } + + var returnType = fieldDef.type; + var resolveFn = (_fieldDef$resolve = fieldDef.resolve) !== null && _fieldDef$resolve !== void 0 ? _fieldDef$resolve : exeContext.fieldResolver; + var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal or abrupt (error). + + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + var args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + var _contextValue = exeContext.contextValue; + var result = resolveFn(source, args, _contextValue, info); + var completed; + + if ((0, _isPromise.default)(result)) { + completed = result.then(function (resolved) { + return completeValue(exeContext, returnType, fieldNodes, info, path, resolved); + }); + } else { + completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); + } + + if ((0, _isPromise.default)(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, function (rawError) { + var error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(path)); + return handleFieldError(error, returnType, exeContext); + }); + } + + return completed; + } catch (rawError) { + var error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(path)); + return handleFieldError(error, returnType, exeContext); + } +} +/** + * @internal + */ + + +function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes: fieldNodes, + returnType: fieldDef.type, + parentType: parentType, + path: path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues + }; +} + +function handleFieldError(error, returnType, exeContext) { + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if ((0, _definition.isNonNullType)(returnType)) { + throw error; + } // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + + + exeContext.errors.push(error); + return null; +} +/** + * Implements the instructions for completeValue as defined in the + * "Field entries" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by evaluating all sub-selections. + */ + + +function completeValue(exeContext, returnType, fieldNodes, info, path, result) { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + + + if ((0, _definition.isNonNullType)(returnType)) { + var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); + + if (completed === null) { + throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")); + } + + return completed; + } // If result value is null or undefined then return null. + + + if (result == null) { + return null; + } // If field type is List, complete each item in the list with the inner type + + + if ((0, _definition.isListType)(returnType)) { + return completeListValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + + + if ((0, _definition.isLeafType)(returnType)) { + return completeLeafValue(returnType, result); + } // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + + + if ((0, _definition.isAbstractType)(returnType)) { + return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is Object, execute and complete all sub-selections. + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if ((0, _definition.isObjectType)(returnType)) { + return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); + } // istanbul ignore next (Not reachable. All possible output types have been considered) + + + false || (0, _invariant.default)(0, 'Cannot complete value of unexpected output type: ' + (0, _inspect.default)(returnType)); +} +/** + * Complete a list value by completing each item in the list with the + * inner type + */ + + +function completeListValue(exeContext, returnType, fieldNodes, info, path, result) { + // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + var itemType = returnType.ofType; + var containsPromise = false; + var completedResults = (0, _safeArrayFrom.default)(result, function (item, index) { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + var itemPath = (0, _Path.addPath)(path, index, undefined); + + try { + var completedItem; + + if ((0, _isPromise.default)(item)) { + completedItem = item.then(function (resolved) { + return completeValue(exeContext, itemType, fieldNodes, info, itemPath, resolved); + }); + } else { + completedItem = completeValue(exeContext, itemType, fieldNodes, info, itemPath, item); + } + + if ((0, _isPromise.default)(completedItem)) { + containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + + return completedItem.then(undefined, function (rawError) { + var error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(itemPath)); + return handleFieldError(error, itemType, exeContext); + }); + } + + return completedItem; + } catch (rawError) { + var error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(itemPath)); + return handleFieldError(error, itemType, exeContext); + } + }); + + if (completedResults == null) { + throw new _GraphQLError.GraphQLError("Expected Iterable, but did not find one for field \"".concat(info.parentType.name, ".").concat(info.fieldName, "\".")); + } + + return containsPromise ? Promise.all(completedResults) : completedResults; +} +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ + + +function completeLeafValue(returnType, result) { + var serializedResult = returnType.serialize(result); + + if (serializedResult === undefined) { + throw new Error("Expected a value of type \"".concat((0, _inspect.default)(returnType), "\" but ") + "received: ".concat((0, _inspect.default)(result))); + } + + return serializedResult; +} +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ + + +function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) { + var _returnType$resolveTy; + + var resolveTypeFn = (_returnType$resolveTy = returnType.resolveType) !== null && _returnType$resolveTy !== void 0 ? _returnType$resolveTy : exeContext.typeResolver; + var contextValue = exeContext.contextValue; + var runtimeType = resolveTypeFn(result, contextValue, info, returnType); + + if ((0, _isPromise.default)(runtimeType)) { + return runtimeType.then(function (resolvedRuntimeType) { + return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); + }); + } + + return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); +} + +function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) { + if (runtimeTypeOrName == null) { + throw new _GraphQLError.GraphQLError("Abstract type \"".concat(returnType.name, "\" must resolve to an Object type at runtime for field \"").concat(info.parentType.name, ".").concat(info.fieldName, "\". Either the \"").concat(returnType.name, "\" type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function."), fieldNodes); + } // FIXME: temporary workaround until support for passing object types would be removed in v16.0.0 + + + var runtimeTypeName = (0, _definition.isNamedType)(runtimeTypeOrName) ? runtimeTypeOrName.name : runtimeTypeOrName; + + if (typeof runtimeTypeName !== 'string') { + throw new _GraphQLError.GraphQLError("Abstract type \"".concat(returnType.name, "\" must resolve to an Object type at runtime for field \"").concat(info.parentType.name, ".").concat(info.fieldName, "\" with ") + "value ".concat((0, _inspect.default)(result), ", received \"").concat((0, _inspect.default)(runtimeTypeOrName), "\".")); + } + + var runtimeType = exeContext.schema.getType(runtimeTypeName); + + if (runtimeType == null) { + throw new _GraphQLError.GraphQLError("Abstract type \"".concat(returnType.name, "\" was resolve to a type \"").concat(runtimeTypeName, "\" that does not exist inside schema."), fieldNodes); + } + + if (!(0, _definition.isObjectType)(runtimeType)) { + throw new _GraphQLError.GraphQLError("Abstract type \"".concat(returnType.name, "\" was resolve to a non-object type \"").concat(runtimeTypeName, "\"."), fieldNodes); + } + + if (!exeContext.schema.isSubType(returnType, runtimeType)) { + throw new _GraphQLError.GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type for \"").concat(returnType.name, "\"."), fieldNodes); + } + + return runtimeType; +} +/** + * Complete an Object value by executing all sub-selections. + */ + + +function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) { + // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + if (returnType.isTypeOf) { + var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + + if ((0, _isPromise.default)(isTypeOf)) { + return isTypeOf.then(function (resolvedIsTypeOf) { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); +} + +function invalidReturnTypeError(returnType, result, fieldNodes) { + return new _GraphQLError.GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat((0, _inspect.default)(result), "."), fieldNodes); +} + +function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) { + // Collect sub-fields to execute to complete this value. + var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ + + +var collectSubfields = (0, _memoize.default)(_collectSubfields); + +function _collectSubfields(exeContext, returnType, fieldNodes) { + var subFieldNodes = Object.create(null); + var visitedFragmentNames = Object.create(null); + + for (var _i8 = 0; _i8 < fieldNodes.length; _i8++) { + var node = fieldNodes[_i8]; + + if (node.selectionSet) { + subFieldNodes = collectFields(exeContext, returnType, node.selectionSet, subFieldNodes, visitedFragmentNames); + } + } + + return subFieldNodes; +} +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ + + +var defaultTypeResolver = function defaultTypeResolver(value, contextValue, info, abstractType) { + // First, look for `__typename`. + if ((0, _isObjectLike.default)(value) && typeof value.__typename === 'string') { + return value.__typename; + } // Otherwise, test each possible type. + + + var possibleTypes = info.schema.getPossibleTypes(abstractType); + var promisedIsTypeOfResults = []; + + for (var i = 0; i < possibleTypes.length; i++) { + var type = possibleTypes[i]; + + if (type.isTypeOf) { + var isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if ((0, _isPromise.default)(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type.name; + } + } + } + + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) { + for (var _i9 = 0; _i9 < isTypeOfResults.length; _i9++) { + if (isTypeOfResults[_i9]) { + return possibleTypes[_i9].name; + } + } + }); + } +}; +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ + + +exports.defaultTypeResolver = defaultTypeResolver; + +var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) { + // ensure source is a value for which property access is acceptable. + if ((0, _isObjectLike.default)(source) || typeof source === 'function') { + var property = source[info.fieldName]; + + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + + return property; + } +}; +/** + * This method looks up the field on the given type definition. + * It has special casing for the three introspection fields, + * __schema, __type and __typename. __typename is special because + * it can always be queried as a field, even in situations where no + * other fields are allowed, like on a Union. __schema and __type + * could get automatically added to the query type, but that would + * require mutating type definitions, which would cause issues. + * + * @internal + */ + + +exports.defaultFieldResolver = defaultFieldResolver; + +function getFieldDef(schema, parentType, fieldName) { + if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.SchemaMetaFieldDef; + } else if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.TypeMetaFieldDef; + } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) { + return _introspection.TypeNameMetaFieldDef; + } + + return parentType.getFields()[fieldName]; +} diff --git a/school/node_modules/graphql/execution/execute.js.flow b/school/node_modules/graphql/execution/execute.js.flow new file mode 100644 index 0000000..604061d --- /dev/null +++ b/school/node_modules/graphql/execution/execute.js.flow @@ -0,0 +1,1246 @@ +// @flow strict +import type { Path } from '../jsutils/Path'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { PromiseOrValue } from '../jsutils/PromiseOrValue'; +import inspect from '../jsutils/inspect'; +import memoize3 from '../jsutils/memoize3'; +import invariant from '../jsutils/invariant'; +import devAssert from '../jsutils/devAssert'; +import isPromise from '../jsutils/isPromise'; +import isObjectLike from '../jsutils/isObjectLike'; +import safeArrayFrom from '../jsutils/safeArrayFrom'; +import promiseReduce from '../jsutils/promiseReduce'; +import promiseForObject from '../jsutils/promiseForObject'; +import { addPath, pathToArray } from '../jsutils/Path'; + +import type { GraphQLFormattedError } from '../error/formatError'; +import { GraphQLError } from '../error/GraphQLError'; +import { locatedError } from '../error/locatedError'; + +import type { + DocumentNode, + OperationDefinitionNode, + SelectionSetNode, + FieldNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, +} from '../language/ast'; +import { Kind } from '../language/kinds'; + +import type { GraphQLSchema } from '../type/schema'; +import type { + GraphQLObjectType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLAbstractType, + GraphQLField, + GraphQLFieldResolver, + GraphQLResolveInfo, + GraphQLTypeResolver, + GraphQLList, +} from '../type/definition'; +import { assertValidSchema } from '../type/validate'; +import { + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from '../type/introspection'; +import { + GraphQLIncludeDirective, + GraphQLSkipDirective, +} from '../type/directives'; +import { + isNamedType, + isObjectType, + isAbstractType, + isLeafType, + isListType, + isNonNullType, +} from '../type/definition'; + +import { typeFromAST } from '../utilities/typeFromAST'; +import { getOperationRootType } from '../utilities/getOperationRootType'; + +import { + getVariableValues, + getArgumentValues, + getDirectiveValues, +} from './values'; + +/** + * Terminology + * + * "Definitions" are the generic name for top-level statements in the document. + * Examples of this include: + * 1) Operations (such as a query) + * 2) Fragments + * + * "Operations" are a generic name for requests in the document. + * Examples of this include: + * 1) query, + * 2) mutation + * + * "Selections" are the definitions that can appear legally and at + * single level of the query. These include: + * 1) field references e.g "a" + * 2) fragment "spreads" e.g. "...c" + * 3) inline fragment "spreads" e.g. "...on Type { a }" + */ + +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + */ +export type ExecutionContext = {| + schema: GraphQLSchema, + fragments: ObjMap<FragmentDefinitionNode>, + rootValue: mixed, + contextValue: mixed, + operation: OperationDefinitionNode, + variableValues: { [variable: string]: mixed, ... }, + fieldResolver: GraphQLFieldResolver<any, any>, + typeResolver: GraphQLTypeResolver<any, any>, + errors: Array<GraphQLError>, +|}; + +/** + * The result of GraphQL execution. + * + * - `errors` is included when any errors occurred as a non-empty array. + * - `data` is the result of a successful execution of the query. + * - `extensions` is reserved for adding non-standard properties. + */ +export type ExecutionResult = {| + errors?: $ReadOnlyArray<GraphQLError>, + data?: ObjMap<mixed> | null, + extensions?: ObjMap<mixed>, +|}; + +export type FormattedExecutionResult = {| + errors?: $ReadOnlyArray<GraphQLFormattedError>, + data?: ObjMap<mixed> | null, + extensions?: ObjMap<mixed>, +|}; + +export type ExecutionArgs = {| + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ +[variable: string]: mixed, ... }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver<any, any>, + typeResolver?: ?GraphQLTypeResolver<any, any>, +|}; + +/** + * Implements the "Evaluating requests" section of the GraphQL specification. + * + * Returns either a synchronous ExecutionResult (if all encountered resolvers + * are synchronous), or a Promise of an ExecutionResult that will eventually be + * resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + * + * Accepts either an object with named arguments, or individual arguments. + */ +declare function execute( + ExecutionArgs, + ..._: [] +): PromiseOrValue<ExecutionResult>; +/* eslint-disable no-redeclare */ +declare function execute( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ +[variable: string]: mixed, ... }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver<any, any>, + typeResolver?: ?GraphQLTypeResolver<any, any>, +): PromiseOrValue<ExecutionResult>; +export function execute( + argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, +) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 + ? executeImpl(argsOrSchema) + : executeImpl({ + schema: argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + }); +} + +/** + * Also implements the "Evaluating requests" section of the GraphQL specification. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ +export function executeSync(args: ExecutionArgs): ExecutionResult { + const result = executeImpl(args); + + // Assert that the execution was synchronous. + if (isPromise(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function executeImpl(args: ExecutionArgs): PromiseOrValue<ExecutionResult> { + const { + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + } = args; + + // If arguments are missing or incorrect, throw an error. + assertValidExecutionArguments(schema, document, variableValues); + + // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + const exeContext = buildExecutionContext( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + ); + + // Return early errors if execution context failed. + if (Array.isArray(exeContext)) { + return { errors: exeContext }; + } + + // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + const data = executeOperation(exeContext, exeContext.operation, rootValue); + return buildResponse(exeContext, data); +} + +/** + * Given a completed execution context and data, build the { errors, data } + * response defined by the "Response" section of the GraphQL specification. + */ +function buildResponse( + exeContext: ExecutionContext, + data: PromiseOrValue<ObjMap<mixed> | null>, +): PromiseOrValue<ExecutionResult> { + if (isPromise(data)) { + return data.then((resolved) => buildResponse(exeContext, resolved)); + } + return exeContext.errors.length === 0 + ? { data } + : { errors: exeContext.errors, data }; +} + +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + * + * @internal + */ +export function assertValidExecutionArguments( + schema: GraphQLSchema, + document: DocumentNode, + rawVariableValues: ?{ +[variable: string]: mixed, ... }, +): void { + devAssert(document, 'Must provide document.'); + + // If the schema used for execution is invalid, throw an error. + assertValidSchema(schema); + + // Variables, if provided, must be an object. + devAssert( + rawVariableValues == null || isObjectLike(rawVariableValues), + 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.', + ); +} + +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + * + * @internal + */ +export function buildExecutionContext( + schema: GraphQLSchema, + document: DocumentNode, + rootValue: mixed, + contextValue: mixed, + rawVariableValues: ?{ +[variable: string]: mixed, ... }, + operationName: ?string, + fieldResolver: ?GraphQLFieldResolver<mixed, mixed>, + typeResolver?: ?GraphQLTypeResolver<mixed, mixed>, +): $ReadOnlyArray<GraphQLError> | ExecutionContext { + let operation: OperationDefinitionNode | void; + const fragments: ObjMap<FragmentDefinitionNode> = Object.create(null); + for (const definition of document.definitions) { + switch (definition.kind) { + case Kind.OPERATION_DEFINITION: + if (operationName == null) { + if (operation !== undefined) { + return [ + new GraphQLError( + 'Must provide operation name if query contains multiple operations.', + ), + ]; + } + operation = definition; + } else if (definition.name?.value === operationName) { + operation = definition; + } + break; + case Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + } + } + + if (!operation) { + if (operationName != null) { + return [new GraphQLError(`Unknown operation named "${operationName}".`)]; + } + return [new GraphQLError('Must provide an operation.')]; + } + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const variableDefinitions = operation.variableDefinitions ?? []; + + const coercedVariableValues = getVariableValues( + schema, + variableDefinitions, + rawVariableValues ?? {}, + { maxErrors: 50 }, + ); + + if (coercedVariableValues.errors) { + return coercedVariableValues.errors; + } + + return { + schema, + fragments, + rootValue, + contextValue, + operation, + variableValues: coercedVariableValues.coerced, + fieldResolver: fieldResolver ?? defaultFieldResolver, + typeResolver: typeResolver ?? defaultTypeResolver, + errors: [], + }; +} + +/** + * Implements the "Evaluating operations" section of the spec. + */ +function executeOperation( + exeContext: ExecutionContext, + operation: OperationDefinitionNode, + rootValue: mixed, +): PromiseOrValue<ObjMap<mixed> | null> { + const type = getOperationRootType(exeContext.schema, operation); + const fields = collectFields( + exeContext, + type, + operation.selectionSet, + Object.create(null), + Object.create(null), + ); + + const path = undefined; + + // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. + try { + const result = + operation.operation === 'mutation' + ? executeFieldsSerially(exeContext, type, rootValue, path, fields) + : executeFields(exeContext, type, rootValue, path, fields); + if (isPromise(result)) { + return result.then(undefined, (error) => { + exeContext.errors.push(error); + return Promise.resolve(null); + }); + } + return result; + } catch (error) { + exeContext.errors.push(error); + return null; + } +} + +/** + * Implements the "Evaluating selection sets" section of the spec + * for "write" mode. + */ +function executeFieldsSerially( + exeContext: ExecutionContext, + parentType: GraphQLObjectType, + sourceValue: mixed, + path: Path | void, + fields: ObjMap<Array<FieldNode>>, +): PromiseOrValue<ObjMap<mixed>> { + return promiseReduce( + Object.keys(fields), + (results, responseName) => { + const fieldNodes = fields[responseName]; + const fieldPath = addPath(path, responseName, parentType.name); + const result = resolveField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); + if (result === undefined) { + return results; + } + if (isPromise(result)) { + return result.then((resolvedResult) => { + results[responseName] = resolvedResult; + return results; + }); + } + results[responseName] = result; + return results; + }, + Object.create(null), + ); +} + +/** + * Implements the "Evaluating selection sets" section of the spec + * for "read" mode. + */ +function executeFields( + exeContext: ExecutionContext, + parentType: GraphQLObjectType, + sourceValue: mixed, + path: Path | void, + fields: ObjMap<Array<FieldNode>>, +): PromiseOrValue<ObjMap<mixed>> { + const results = Object.create(null); + let containsPromise = false; + + for (const responseName of Object.keys(fields)) { + const fieldNodes = fields[responseName]; + const fieldPath = addPath(path, responseName, parentType.name); + const result = resolveField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); + + if (result !== undefined) { + results[responseName] = result; + if (isPromise(result)) { + containsPromise = true; + } + } + } + + // If there are no promises, we can just return the object + if (!containsPromise) { + return results; + } + + // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + return promiseForObject(results); +} + +/** + * Given a selectionSet, adds all of the fields in that selection to + * the passed in map of fields, and returns it at the end. + * + * CollectFields requires the "runtime type" of an object. For a field which + * returns an Interface or Union type, the "runtime type" will be the actual + * Object type returned by that field. + * + * @internal + */ +export function collectFields( + exeContext: ExecutionContext, + runtimeType: GraphQLObjectType, + selectionSet: SelectionSetNode, + fields: ObjMap<Array<FieldNode>>, + visitedFragmentNames: ObjMap<boolean>, +): ObjMap<Array<FieldNode>> { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case Kind.FIELD: { + if (!shouldIncludeNode(exeContext, selection)) { + continue; + } + const name = getFieldEntryKey(selection); + if (!fields[name]) { + fields[name] = []; + } + fields[name].push(selection); + break; + } + case Kind.INLINE_FRAGMENT: { + if ( + !shouldIncludeNode(exeContext, selection) || + !doesFragmentConditionMatch(exeContext, selection, runtimeType) + ) { + continue; + } + collectFields( + exeContext, + runtimeType, + selection.selectionSet, + fields, + visitedFragmentNames, + ); + break; + } + case Kind.FRAGMENT_SPREAD: { + const fragName = selection.name.value; + if ( + visitedFragmentNames[fragName] || + !shouldIncludeNode(exeContext, selection) + ) { + continue; + } + visitedFragmentNames[fragName] = true; + const fragment = exeContext.fragments[fragName]; + if ( + !fragment || + !doesFragmentConditionMatch(exeContext, fragment, runtimeType) + ) { + continue; + } + collectFields( + exeContext, + runtimeType, + fragment.selectionSet, + fields, + visitedFragmentNames, + ); + break; + } + } + } + return fields; +} + +/** + * Determines if a field should be included based on the @include and @skip + * directives, where @skip has higher precedence than @include. + */ +function shouldIncludeNode( + exeContext: ExecutionContext, + node: FragmentSpreadNode | FieldNode | InlineFragmentNode, +): boolean { + const skip = getDirectiveValues( + GraphQLSkipDirective, + node, + exeContext.variableValues, + ); + if (skip?.if === true) { + return false; + } + + const include = getDirectiveValues( + GraphQLIncludeDirective, + node, + exeContext.variableValues, + ); + if (include?.if === false) { + return false; + } + return true; +} + +/** + * Determines if a fragment is applicable to the given type. + */ +function doesFragmentConditionMatch( + exeContext: ExecutionContext, + fragment: FragmentDefinitionNode | InlineFragmentNode, + type: GraphQLObjectType, +): boolean { + const typeConditionNode = fragment.typeCondition; + if (!typeConditionNode) { + return true; + } + const conditionalType = typeFromAST(exeContext.schema, typeConditionNode); + if (conditionalType === type) { + return true; + } + if (isAbstractType(conditionalType)) { + return exeContext.schema.isSubType(conditionalType, type); + } + return false; +} + +/** + * Implements the logic to compute the key of a given field's entry + */ +function getFieldEntryKey(node: FieldNode): string { + return node.alias ? node.alias.value : node.name.value; +} + +/** + * Resolves the field on the given source object. In particular, this + * figures out the value that the field returns by calling its resolve function, + * then calls completeValue to complete promises, serialize scalars, or execute + * the sub-selection-set for objects. + */ +function resolveField( + exeContext: ExecutionContext, + parentType: GraphQLObjectType, + source: mixed, + fieldNodes: $ReadOnlyArray<FieldNode>, + path: Path, +): PromiseOrValue<mixed> { + const fieldNode = fieldNodes[0]; + const fieldName = fieldNode.name.value; + + const fieldDef = getFieldDef(exeContext.schema, parentType, fieldName); + if (!fieldDef) { + return; + } + + const returnType = fieldDef.type; + const resolveFn = fieldDef.resolve ?? exeContext.fieldResolver; + + const info = buildResolveInfo( + exeContext, + fieldDef, + fieldNodes, + parentType, + path, + ); + + // Get the resolve function, regardless of if its result is normal or abrupt (error). + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + const args = getArgumentValues( + fieldDef, + fieldNodes[0], + exeContext.variableValues, + ); + + // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + const contextValue = exeContext.contextValue; + + const result = resolveFn(source, args, contextValue, info); + + let completed; + if (isPromise(result)) { + completed = result.then((resolved) => + completeValue(exeContext, returnType, fieldNodes, info, path, resolved), + ); + } else { + completed = completeValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + if (isPromise(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, (rawError) => { + const error = locatedError(rawError, fieldNodes, pathToArray(path)); + return handleFieldError(error, returnType, exeContext); + }); + } + return completed; + } catch (rawError) { + const error = locatedError(rawError, fieldNodes, pathToArray(path)); + return handleFieldError(error, returnType, exeContext); + } +} + +/** + * @internal + */ +export function buildResolveInfo( + exeContext: ExecutionContext, + fieldDef: GraphQLField<mixed, mixed>, + fieldNodes: $ReadOnlyArray<FieldNode>, + parentType: GraphQLObjectType, + path: Path, +): GraphQLResolveInfo { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes, + returnType: fieldDef.type, + parentType, + path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues, + }; +} + +function handleFieldError( + error: GraphQLError, + returnType: GraphQLOutputType, + exeContext: ExecutionContext, +): null { + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if (isNonNullType(returnType)) { + throw error; + } + + // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + exeContext.errors.push(error); + return null; +} + +/** + * Implements the instructions for completeValue as defined in the + * "Field entries" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by evaluating all sub-selections. + */ +function completeValue( + exeContext: ExecutionContext, + returnType: GraphQLOutputType, + fieldNodes: $ReadOnlyArray<FieldNode>, + info: GraphQLResolveInfo, + path: Path, + result: mixed, +): PromiseOrValue<mixed> { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } + + // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + if (isNonNullType(returnType)) { + const completed = completeValue( + exeContext, + returnType.ofType, + fieldNodes, + info, + path, + result, + ); + if (completed === null) { + throw new Error( + `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`, + ); + } + return completed; + } + + // If result value is null or undefined then return null. + if (result == null) { + return null; + } + + // If field type is List, complete each item in the list with the inner type + if (isListType(returnType)) { + return completeListValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + if (isLeafType(returnType)) { + return completeLeafValue(returnType, result); + } + + // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + if (isAbstractType(returnType)) { + return completeAbstractValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + // If field type is Object, execute and complete all sub-selections. + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + if (isObjectType(returnType)) { + return completeObjectValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + // istanbul ignore next (Not reachable. All possible output types have been considered) + invariant( + false, + 'Cannot complete value of unexpected output type: ' + + inspect((returnType: empty)), + ); +} + +/** + * Complete a list value by completing each item in the list with the + * inner type + */ +function completeListValue( + exeContext: ExecutionContext, + returnType: GraphQLList<GraphQLOutputType>, + fieldNodes: $ReadOnlyArray<FieldNode>, + info: GraphQLResolveInfo, + path: Path, + result: mixed, +): PromiseOrValue<$ReadOnlyArray<mixed>> { + // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + const itemType = returnType.ofType; + let containsPromise = false; + const completedResults = safeArrayFrom(result, (item, index) => { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + const itemPath = addPath(path, index, undefined); + try { + let completedItem; + if (isPromise(item)) { + completedItem = item.then((resolved) => + completeValue( + exeContext, + itemType, + fieldNodes, + info, + itemPath, + resolved, + ), + ); + } else { + completedItem = completeValue( + exeContext, + itemType, + fieldNodes, + info, + itemPath, + item, + ); + } + + if (isPromise(completedItem)) { + containsPromise = true; + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completedItem.then(undefined, (rawError) => { + const error = locatedError( + rawError, + fieldNodes, + pathToArray(itemPath), + ); + return handleFieldError(error, itemType, exeContext); + }); + } + return completedItem; + } catch (rawError) { + const error = locatedError(rawError, fieldNodes, pathToArray(itemPath)); + return handleFieldError(error, itemType, exeContext); + } + }); + + if (completedResults == null) { + throw new GraphQLError( + `Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`, + ); + } + + return containsPromise ? Promise.all(completedResults) : completedResults; +} + +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ +function completeLeafValue(returnType: GraphQLLeafType, result: mixed): mixed { + const serializedResult = returnType.serialize(result); + if (serializedResult === undefined) { + throw new Error( + `Expected a value of type "${inspect(returnType)}" but ` + + `received: ${inspect(result)}`, + ); + } + return serializedResult; +} + +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ +function completeAbstractValue( + exeContext: ExecutionContext, + returnType: GraphQLAbstractType, + fieldNodes: $ReadOnlyArray<FieldNode>, + info: GraphQLResolveInfo, + path: Path, + result: mixed, +): PromiseOrValue<ObjMap<mixed>> { + const resolveTypeFn = returnType.resolveType ?? exeContext.typeResolver; + const contextValue = exeContext.contextValue; + const runtimeType = resolveTypeFn(result, contextValue, info, returnType); + + if (isPromise(runtimeType)) { + return runtimeType.then((resolvedRuntimeType) => + completeObjectValue( + exeContext, + ensureValidRuntimeType( + resolvedRuntimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ), + ); + } + + return completeObjectValue( + exeContext, + ensureValidRuntimeType( + runtimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ); +} + +function ensureValidRuntimeType( + runtimeTypeOrName: mixed, + exeContext: ExecutionContext, + returnType: GraphQLAbstractType, + fieldNodes: $ReadOnlyArray<FieldNode>, + info: GraphQLResolveInfo, + result: mixed, +): GraphQLObjectType { + if (runtimeTypeOrName == null) { + throw new GraphQLError( + `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}". Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`, + fieldNodes, + ); + } + + // FIXME: temporary workaround until support for passing object types would be removed in v16.0.0 + const runtimeTypeName = isNamedType(runtimeTypeOrName) + ? runtimeTypeOrName.name + : runtimeTypeOrName; + + if (typeof runtimeTypeName !== 'string') { + throw new GraphQLError( + `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` + + `value ${inspect(result)}, received "${inspect(runtimeTypeOrName)}".`, + ); + } + + const runtimeType = exeContext.schema.getType(runtimeTypeName); + if (runtimeType == null) { + throw new GraphQLError( + `Abstract type "${returnType.name}" was resolve to a type "${runtimeTypeName}" that does not exist inside schema.`, + fieldNodes, + ); + } + + if (!isObjectType(runtimeType)) { + throw new GraphQLError( + `Abstract type "${returnType.name}" was resolve to a non-object type "${runtimeTypeName}".`, + fieldNodes, + ); + } + + if (!exeContext.schema.isSubType(returnType, runtimeType)) { + throw new GraphQLError( + `Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`, + fieldNodes, + ); + } + + return runtimeType; +} + +/** + * Complete an Object value by executing all sub-selections. + */ +function completeObjectValue( + exeContext: ExecutionContext, + returnType: GraphQLObjectType, + fieldNodes: $ReadOnlyArray<FieldNode>, + info: GraphQLResolveInfo, + path: Path, + result: mixed, +): PromiseOrValue<ObjMap<mixed>> { + // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + if (returnType.isTypeOf) { + const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + + if (isPromise(isTypeOf)) { + return isTypeOf.then((resolvedIsTypeOf) => { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + return collectAndExecuteSubfields( + exeContext, + returnType, + fieldNodes, + path, + result, + ); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return collectAndExecuteSubfields( + exeContext, + returnType, + fieldNodes, + path, + result, + ); +} + +function invalidReturnTypeError( + returnType: GraphQLObjectType, + result: mixed, + fieldNodes: $ReadOnlyArray<FieldNode>, +): GraphQLError { + return new GraphQLError( + `Expected value of type "${returnType.name}" but got: ${inspect(result)}.`, + fieldNodes, + ); +} + +function collectAndExecuteSubfields( + exeContext: ExecutionContext, + returnType: GraphQLObjectType, + fieldNodes: $ReadOnlyArray<FieldNode>, + path: Path, + result: mixed, +): PromiseOrValue<ObjMap<mixed>> { + // Collect sub-fields to execute to complete this value. + const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} + +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ +const collectSubfields = memoize3(_collectSubfields); +function _collectSubfields( + exeContext: ExecutionContext, + returnType: GraphQLObjectType, + fieldNodes: $ReadOnlyArray<FieldNode>, +): ObjMap<Array<FieldNode>> { + let subFieldNodes = Object.create(null); + const visitedFragmentNames = Object.create(null); + for (const node of fieldNodes) { + if (node.selectionSet) { + subFieldNodes = collectFields( + exeContext, + returnType, + node.selectionSet, + subFieldNodes, + visitedFragmentNames, + ); + } + } + return subFieldNodes; +} + +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ +export const defaultTypeResolver: GraphQLTypeResolver<mixed, mixed> = function ( + value, + contextValue, + info, + abstractType, +) { + // First, look for `__typename`. + if (isObjectLike(value) && typeof value.__typename === 'string') { + return value.__typename; + } + + // Otherwise, test each possible type. + const possibleTypes = info.schema.getPossibleTypes(abstractType); + const promisedIsTypeOfResults = []; + + for (let i = 0; i < possibleTypes.length; i++) { + const type = possibleTypes[i]; + + if (type.isTypeOf) { + const isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if (isPromise(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type.name; + } + } + } + + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then((isTypeOfResults) => { + for (let i = 0; i < isTypeOfResults.length; i++) { + if (isTypeOfResults[i]) { + return possibleTypes[i].name; + } + } + }); + } +}; + +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ +export const defaultFieldResolver: GraphQLFieldResolver< + mixed, + mixed, +> = function (source: any, args, contextValue, info) { + // ensure source is a value for which property access is acceptable. + if (isObjectLike(source) || typeof source === 'function') { + const property = source[info.fieldName]; + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + return property; + } +}; + +/** + * This method looks up the field on the given type definition. + * It has special casing for the three introspection fields, + * __schema, __type and __typename. __typename is special because + * it can always be queried as a field, even in situations where no + * other fields are allowed, like on a Union. __schema and __type + * could get automatically added to the query type, but that would + * require mutating type definitions, which would cause issues. + * + * @internal + */ +export function getFieldDef( + schema: GraphQLSchema, + parentType: GraphQLObjectType, + fieldName: string, +): ?GraphQLField<mixed, mixed> { + if ( + fieldName === SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return SchemaMetaFieldDef; + } else if ( + fieldName === TypeMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return TypeMetaFieldDef; + } else if (fieldName === TypeNameMetaFieldDef.name) { + return TypeNameMetaFieldDef; + } + return parentType.getFields()[fieldName]; +} diff --git a/school/node_modules/graphql/execution/execute.mjs b/school/node_modules/graphql/execution/execute.mjs new file mode 100644 index 0000000..9cf5b92 --- /dev/null +++ b/school/node_modules/graphql/execution/execute.mjs @@ -0,0 +1,847 @@ +import inspect from "../jsutils/inspect.mjs"; +import memoize3 from "../jsutils/memoize3.mjs"; +import invariant from "../jsutils/invariant.mjs"; +import devAssert from "../jsutils/devAssert.mjs"; +import isPromise from "../jsutils/isPromise.mjs"; +import isObjectLike from "../jsutils/isObjectLike.mjs"; +import safeArrayFrom from "../jsutils/safeArrayFrom.mjs"; +import promiseReduce from "../jsutils/promiseReduce.mjs"; +import promiseForObject from "../jsutils/promiseForObject.mjs"; +import { addPath, pathToArray } from "../jsutils/Path.mjs"; +import { GraphQLError } from "../error/GraphQLError.mjs"; +import { locatedError } from "../error/locatedError.mjs"; +import { Kind } from "../language/kinds.mjs"; +import { assertValidSchema } from "../type/validate.mjs"; +import { SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from "../type/introspection.mjs"; +import { GraphQLIncludeDirective, GraphQLSkipDirective } from "../type/directives.mjs"; +import { isNamedType, isObjectType, isAbstractType, isLeafType, isListType, isNonNullType } from "../type/definition.mjs"; +import { typeFromAST } from "../utilities/typeFromAST.mjs"; +import { getOperationRootType } from "../utilities/getOperationRootType.mjs"; +import { getVariableValues, getArgumentValues, getDirectiveValues } from "./values.mjs"; +/** + * Terminology + * + * "Definitions" are the generic name for top-level statements in the document. + * Examples of this include: + * 1) Operations (such as a query) + * 2) Fragments + * + * "Operations" are a generic name for requests in the document. + * Examples of this include: + * 1) query, + * 2) mutation + * + * "Selections" are the definitions that can appear legally and at + * single level of the query. These include: + * 1) field references e.g "a" + * 2) fragment "spreads" e.g. "...c" + * 3) inline fragment "spreads" e.g. "...on Type { a }" + */ + +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + */ + +export function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? executeImpl(argsOrSchema) : executeImpl({ + schema: argsOrSchema, + document: document, + rootValue: rootValue, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver, + typeResolver: typeResolver + }); +} +/** + * Also implements the "Evaluating requests" section of the GraphQL specification. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + +export function executeSync(args) { + var result = executeImpl(args); // Assert that the execution was synchronous. + + if (isPromise(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function executeImpl(args) { + var schema = args.schema, + document = args.document, + rootValue = args.rootValue, + contextValue = args.contextValue, + variableValues = args.variableValues, + operationName = args.operationName, + fieldResolver = args.fieldResolver, + typeResolver = args.typeResolver; // If arguments are missing or incorrect, throw an error. + + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver); // Return early errors if execution context failed. + + if (Array.isArray(exeContext)) { + return { + errors: exeContext + }; + } // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + + + var data = executeOperation(exeContext, exeContext.operation, rootValue); + return buildResponse(exeContext, data); +} +/** + * Given a completed execution context and data, build the { errors, data } + * response defined by the "Response" section of the GraphQL specification. + */ + + +function buildResponse(exeContext, data) { + if (isPromise(data)) { + return data.then(function (resolved) { + return buildResponse(exeContext, resolved); + }); + } + + return exeContext.errors.length === 0 ? { + data: data + } : { + errors: exeContext.errors, + data: data + }; +} +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + * + * @internal + */ + + +export function assertValidExecutionArguments(schema, document, rawVariableValues) { + document || devAssert(0, 'Must provide document.'); // If the schema used for execution is invalid, throw an error. + + assertValidSchema(schema); // Variables, if provided, must be an object. + + rawVariableValues == null || isObjectLike(rawVariableValues) || devAssert(0, 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.'); +} +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + * + * @internal + */ + +export function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver, typeResolver) { + var _definition$name, _operation$variableDe; + + var operation; + var fragments = Object.create(null); + + for (var _i2 = 0, _document$definitions2 = document.definitions; _i2 < _document$definitions2.length; _i2++) { + var definition = _document$definitions2[_i2]; + + switch (definition.kind) { + case Kind.OPERATION_DEFINITION: + if (operationName == null) { + if (operation !== undefined) { + return [new GraphQLError('Must provide operation name if query contains multiple operations.')]; + } + + operation = definition; + } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) { + operation = definition; + } + + break; + + case Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + } + } + + if (!operation) { + if (operationName != null) { + return [new GraphQLError("Unknown operation named \"".concat(operationName, "\"."))]; + } + + return [new GraphQLError('Must provide an operation.')]; + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + + var variableDefinitions = (_operation$variableDe = operation.variableDefinitions) !== null && _operation$variableDe !== void 0 ? _operation$variableDe : []; + var coercedVariableValues = getVariableValues(schema, variableDefinitions, rawVariableValues !== null && rawVariableValues !== void 0 ? rawVariableValues : {}, { + maxErrors: 50 + }); + + if (coercedVariableValues.errors) { + return coercedVariableValues.errors; + } + + return { + schema: schema, + fragments: fragments, + rootValue: rootValue, + contextValue: contextValue, + operation: operation, + variableValues: coercedVariableValues.coerced, + fieldResolver: fieldResolver !== null && fieldResolver !== void 0 ? fieldResolver : defaultFieldResolver, + typeResolver: typeResolver !== null && typeResolver !== void 0 ? typeResolver : defaultTypeResolver, + errors: [] + }; +} +/** + * Implements the "Evaluating operations" section of the spec. + */ + +function executeOperation(exeContext, operation, rootValue) { + var type = getOperationRootType(exeContext.schema, operation); + var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null)); + var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. + + try { + var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields); + + if (isPromise(result)) { + return result.then(undefined, function (error) { + exeContext.errors.push(error); + return Promise.resolve(null); + }); + } + + return result; + } catch (error) { + exeContext.errors.push(error); + return null; + } +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "write" mode. + */ + + +function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { + return promiseReduce(Object.keys(fields), function (results, responseName) { + var fieldNodes = fields[responseName]; + var fieldPath = addPath(path, responseName, parentType.name); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result === undefined) { + return results; + } + + if (isPromise(result)) { + return result.then(function (resolvedResult) { + results[responseName] = resolvedResult; + return results; + }); + } + + results[responseName] = result; + return results; + }, Object.create(null)); +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "read" mode. + */ + + +function executeFields(exeContext, parentType, sourceValue, path, fields) { + var results = Object.create(null); + var containsPromise = false; + + for (var _i4 = 0, _Object$keys2 = Object.keys(fields); _i4 < _Object$keys2.length; _i4++) { + var responseName = _Object$keys2[_i4]; + var fieldNodes = fields[responseName]; + var fieldPath = addPath(path, responseName, parentType.name); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result !== undefined) { + results[responseName] = result; + + if (isPromise(result)) { + containsPromise = true; + } + } + } // If there are no promises, we can just return the object + + + if (!containsPromise) { + return results; + } // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + + + return promiseForObject(results); +} +/** + * Given a selectionSet, adds all of the fields in that selection to + * the passed in map of fields, and returns it at the end. + * + * CollectFields requires the "runtime type" of an object. For a field which + * returns an Interface or Union type, the "runtime type" will be the actual + * Object type returned by that field. + * + * @internal + */ + + +export function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) { + for (var _i6 = 0, _selectionSet$selecti2 = selectionSet.selections; _i6 < _selectionSet$selecti2.length; _i6++) { + var selection = _selectionSet$selecti2[_i6]; + + switch (selection.kind) { + case Kind.FIELD: + { + if (!shouldIncludeNode(exeContext, selection)) { + continue; + } + + var name = getFieldEntryKey(selection); + + if (!fields[name]) { + fields[name] = []; + } + + fields[name].push(selection); + break; + } + + case Kind.INLINE_FRAGMENT: + { + if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames); + break; + } + + case Kind.FRAGMENT_SPREAD: + { + var fragName = selection.name.value; + + if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) { + continue; + } + + visitedFragmentNames[fragName] = true; + var fragment = exeContext.fragments[fragName]; + + if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames); + break; + } + } + } + + return fields; +} +/** + * Determines if a field should be included based on the @include and @skip + * directives, where @skip has higher precedence than @include. + */ + +function shouldIncludeNode(exeContext, node) { + var skip = getDirectiveValues(GraphQLSkipDirective, node, exeContext.variableValues); + + if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) { + return false; + } + + var include = getDirectiveValues(GraphQLIncludeDirective, node, exeContext.variableValues); + + if ((include === null || include === void 0 ? void 0 : include.if) === false) { + return false; + } + + return true; +} +/** + * Determines if a fragment is applicable to the given type. + */ + + +function doesFragmentConditionMatch(exeContext, fragment, type) { + var typeConditionNode = fragment.typeCondition; + + if (!typeConditionNode) { + return true; + } + + var conditionalType = typeFromAST(exeContext.schema, typeConditionNode); + + if (conditionalType === type) { + return true; + } + + if (isAbstractType(conditionalType)) { + return exeContext.schema.isSubType(conditionalType, type); + } + + return false; +} +/** + * Implements the logic to compute the key of a given field's entry + */ + + +function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; +} +/** + * Resolves the field on the given source object. In particular, this + * figures out the value that the field returns by calling its resolve function, + * then calls completeValue to complete promises, serialize scalars, or execute + * the sub-selection-set for objects. + */ + + +function resolveField(exeContext, parentType, source, fieldNodes, path) { + var _fieldDef$resolve; + + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName); + + if (!fieldDef) { + return; + } + + var returnType = fieldDef.type; + var resolveFn = (_fieldDef$resolve = fieldDef.resolve) !== null && _fieldDef$resolve !== void 0 ? _fieldDef$resolve : exeContext.fieldResolver; + var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal or abrupt (error). + + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + var args = getArgumentValues(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + var _contextValue = exeContext.contextValue; + var result = resolveFn(source, args, _contextValue, info); + var completed; + + if (isPromise(result)) { + completed = result.then(function (resolved) { + return completeValue(exeContext, returnType, fieldNodes, info, path, resolved); + }); + } else { + completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); + } + + if (isPromise(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, function (rawError) { + var error = locatedError(rawError, fieldNodes, pathToArray(path)); + return handleFieldError(error, returnType, exeContext); + }); + } + + return completed; + } catch (rawError) { + var error = locatedError(rawError, fieldNodes, pathToArray(path)); + return handleFieldError(error, returnType, exeContext); + } +} +/** + * @internal + */ + + +export function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes: fieldNodes, + returnType: fieldDef.type, + parentType: parentType, + path: path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues + }; +} + +function handleFieldError(error, returnType, exeContext) { + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if (isNonNullType(returnType)) { + throw error; + } // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + + + exeContext.errors.push(error); + return null; +} +/** + * Implements the instructions for completeValue as defined in the + * "Field entries" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by evaluating all sub-selections. + */ + + +function completeValue(exeContext, returnType, fieldNodes, info, path, result) { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + + + if (isNonNullType(returnType)) { + var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); + + if (completed === null) { + throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")); + } + + return completed; + } // If result value is null or undefined then return null. + + + if (result == null) { + return null; + } // If field type is List, complete each item in the list with the inner type + + + if (isListType(returnType)) { + return completeListValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + + + if (isLeafType(returnType)) { + return completeLeafValue(returnType, result); + } // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + + + if (isAbstractType(returnType)) { + return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is Object, execute and complete all sub-selections. + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if (isObjectType(returnType)) { + return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); + } // istanbul ignore next (Not reachable. All possible output types have been considered) + + + false || invariant(0, 'Cannot complete value of unexpected output type: ' + inspect(returnType)); +} +/** + * Complete a list value by completing each item in the list with the + * inner type + */ + + +function completeListValue(exeContext, returnType, fieldNodes, info, path, result) { + // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + var itemType = returnType.ofType; + var containsPromise = false; + var completedResults = safeArrayFrom(result, function (item, index) { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + var itemPath = addPath(path, index, undefined); + + try { + var completedItem; + + if (isPromise(item)) { + completedItem = item.then(function (resolved) { + return completeValue(exeContext, itemType, fieldNodes, info, itemPath, resolved); + }); + } else { + completedItem = completeValue(exeContext, itemType, fieldNodes, info, itemPath, item); + } + + if (isPromise(completedItem)) { + containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + + return completedItem.then(undefined, function (rawError) { + var error = locatedError(rawError, fieldNodes, pathToArray(itemPath)); + return handleFieldError(error, itemType, exeContext); + }); + } + + return completedItem; + } catch (rawError) { + var error = locatedError(rawError, fieldNodes, pathToArray(itemPath)); + return handleFieldError(error, itemType, exeContext); + } + }); + + if (completedResults == null) { + throw new GraphQLError("Expected Iterable, but did not find one for field \"".concat(info.parentType.name, ".").concat(info.fieldName, "\".")); + } + + return containsPromise ? Promise.all(completedResults) : completedResults; +} +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ + + +function completeLeafValue(returnType, result) { + var serializedResult = returnType.serialize(result); + + if (serializedResult === undefined) { + throw new Error("Expected a value of type \"".concat(inspect(returnType), "\" but ") + "received: ".concat(inspect(result))); + } + + return serializedResult; +} +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ + + +function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) { + var _returnType$resolveTy; + + var resolveTypeFn = (_returnType$resolveTy = returnType.resolveType) !== null && _returnType$resolveTy !== void 0 ? _returnType$resolveTy : exeContext.typeResolver; + var contextValue = exeContext.contextValue; + var runtimeType = resolveTypeFn(result, contextValue, info, returnType); + + if (isPromise(runtimeType)) { + return runtimeType.then(function (resolvedRuntimeType) { + return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); + }); + } + + return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); +} + +function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) { + if (runtimeTypeOrName == null) { + throw new GraphQLError("Abstract type \"".concat(returnType.name, "\" must resolve to an Object type at runtime for field \"").concat(info.parentType.name, ".").concat(info.fieldName, "\". Either the \"").concat(returnType.name, "\" type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function."), fieldNodes); + } // FIXME: temporary workaround until support for passing object types would be removed in v16.0.0 + + + var runtimeTypeName = isNamedType(runtimeTypeOrName) ? runtimeTypeOrName.name : runtimeTypeOrName; + + if (typeof runtimeTypeName !== 'string') { + throw new GraphQLError("Abstract type \"".concat(returnType.name, "\" must resolve to an Object type at runtime for field \"").concat(info.parentType.name, ".").concat(info.fieldName, "\" with ") + "value ".concat(inspect(result), ", received \"").concat(inspect(runtimeTypeOrName), "\".")); + } + + var runtimeType = exeContext.schema.getType(runtimeTypeName); + + if (runtimeType == null) { + throw new GraphQLError("Abstract type \"".concat(returnType.name, "\" was resolve to a type \"").concat(runtimeTypeName, "\" that does not exist inside schema."), fieldNodes); + } + + if (!isObjectType(runtimeType)) { + throw new GraphQLError("Abstract type \"".concat(returnType.name, "\" was resolve to a non-object type \"").concat(runtimeTypeName, "\"."), fieldNodes); + } + + if (!exeContext.schema.isSubType(returnType, runtimeType)) { + throw new GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type for \"").concat(returnType.name, "\"."), fieldNodes); + } + + return runtimeType; +} +/** + * Complete an Object value by executing all sub-selections. + */ + + +function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) { + // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + if (returnType.isTypeOf) { + var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + + if (isPromise(isTypeOf)) { + return isTypeOf.then(function (resolvedIsTypeOf) { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); +} + +function invalidReturnTypeError(returnType, result, fieldNodes) { + return new GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat(inspect(result), "."), fieldNodes); +} + +function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) { + // Collect sub-fields to execute to complete this value. + var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ + + +var collectSubfields = memoize3(_collectSubfields); + +function _collectSubfields(exeContext, returnType, fieldNodes) { + var subFieldNodes = Object.create(null); + var visitedFragmentNames = Object.create(null); + + for (var _i8 = 0; _i8 < fieldNodes.length; _i8++) { + var node = fieldNodes[_i8]; + + if (node.selectionSet) { + subFieldNodes = collectFields(exeContext, returnType, node.selectionSet, subFieldNodes, visitedFragmentNames); + } + } + + return subFieldNodes; +} +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ + + +export var defaultTypeResolver = function defaultTypeResolver(value, contextValue, info, abstractType) { + // First, look for `__typename`. + if (isObjectLike(value) && typeof value.__typename === 'string') { + return value.__typename; + } // Otherwise, test each possible type. + + + var possibleTypes = info.schema.getPossibleTypes(abstractType); + var promisedIsTypeOfResults = []; + + for (var i = 0; i < possibleTypes.length; i++) { + var type = possibleTypes[i]; + + if (type.isTypeOf) { + var isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if (isPromise(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type.name; + } + } + } + + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) { + for (var _i9 = 0; _i9 < isTypeOfResults.length; _i9++) { + if (isTypeOfResults[_i9]) { + return possibleTypes[_i9].name; + } + } + }); + } +}; +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ + +export var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) { + // ensure source is a value for which property access is acceptable. + if (isObjectLike(source) || typeof source === 'function') { + var property = source[info.fieldName]; + + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + + return property; + } +}; +/** + * This method looks up the field on the given type definition. + * It has special casing for the three introspection fields, + * __schema, __type and __typename. __typename is special because + * it can always be queried as a field, even in situations where no + * other fields are allowed, like on a Union. __schema and __type + * could get automatically added to the query type, but that would + * require mutating type definitions, which would cause issues. + * + * @internal + */ + +export function getFieldDef(schema, parentType, fieldName) { + if (fieldName === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return SchemaMetaFieldDef; + } else if (fieldName === TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return TypeMetaFieldDef; + } else if (fieldName === TypeNameMetaFieldDef.name) { + return TypeNameMetaFieldDef; + } + + return parentType.getFields()[fieldName]; +} diff --git a/school/node_modules/graphql/execution/index.d.ts b/school/node_modules/graphql/execution/index.d.ts new file mode 100644 index 0000000..d70ba3a --- /dev/null +++ b/school/node_modules/graphql/execution/index.d.ts @@ -0,0 +1,13 @@ +export { pathToArray as responsePathAsArray } from '../jsutils/Path'; + +export { + execute, + executeSync, + defaultFieldResolver, + defaultTypeResolver, + ExecutionArgs, + ExecutionResult, + FormattedExecutionResult, +} from './execute'; + +export { getDirectiveValues } from './values'; diff --git a/school/node_modules/graphql/execution/index.js b/school/node_modules/graphql/execution/index.js new file mode 100644 index 0000000..3d5fe46 --- /dev/null +++ b/school/node_modules/graphql/execution/index.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "responsePathAsArray", { + enumerable: true, + get: function get() { + return _Path.pathToArray; + } +}); +Object.defineProperty(exports, "execute", { + enumerable: true, + get: function get() { + return _execute.execute; + } +}); +Object.defineProperty(exports, "executeSync", { + enumerable: true, + get: function get() { + return _execute.executeSync; + } +}); +Object.defineProperty(exports, "defaultFieldResolver", { + enumerable: true, + get: function get() { + return _execute.defaultFieldResolver; + } +}); +Object.defineProperty(exports, "defaultTypeResolver", { + enumerable: true, + get: function get() { + return _execute.defaultTypeResolver; + } +}); +Object.defineProperty(exports, "getDirectiveValues", { + enumerable: true, + get: function get() { + return _values.getDirectiveValues; + } +}); + +var _Path = require("../jsutils/Path.js"); + +var _execute = require("./execute.js"); + +var _values = require("./values.js"); diff --git a/school/node_modules/graphql/execution/index.js.flow b/school/node_modules/graphql/execution/index.js.flow new file mode 100644 index 0000000..c8a2ee1 --- /dev/null +++ b/school/node_modules/graphql/execution/index.js.flow @@ -0,0 +1,17 @@ +// @flow strict +export { pathToArray as responsePathAsArray } from '../jsutils/Path'; + +export { + execute, + executeSync, + defaultFieldResolver, + defaultTypeResolver, +} from './execute'; + +export type { + ExecutionArgs, + ExecutionResult, + FormattedExecutionResult, +} from './execute'; + +export { getDirectiveValues } from './values'; diff --git a/school/node_modules/graphql/execution/index.mjs b/school/node_modules/graphql/execution/index.mjs new file mode 100644 index 0000000..f8c087d --- /dev/null +++ b/school/node_modules/graphql/execution/index.mjs @@ -0,0 +1,3 @@ +export { pathToArray as responsePathAsArray } from "../jsutils/Path.mjs"; +export { execute, executeSync, defaultFieldResolver, defaultTypeResolver } from "./execute.mjs"; +export { getDirectiveValues } from "./values.mjs"; diff --git a/school/node_modules/graphql/execution/values.d.ts b/school/node_modules/graphql/execution/values.d.ts new file mode 100644 index 0000000..8b17b54 --- /dev/null +++ b/school/node_modules/graphql/execution/values.d.ts @@ -0,0 +1,65 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { GraphQLError } from '../error/GraphQLError'; +import { + FieldNode, + DirectiveNode, + VariableDefinitionNode, +} from '../language/ast'; + +import { GraphQLDirective } from '../type/directives'; +import { GraphQLSchema } from '../type/schema'; +import { GraphQLField } from '../type/definition'; + +type CoercedVariableValues = + | { errors: ReadonlyArray<GraphQLError>; coerced?: never } + | { errors?: never; coerced: { [key: string]: any } }; + +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getVariableValues( + schema: GraphQLSchema, + varDefNodes: ReadonlyArray<VariableDefinitionNode>, + inputs: { [key: string]: any }, + options?: { maxErrors?: number }, +): CoercedVariableValues; + +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getArgumentValues( + def: GraphQLField<any, any> | GraphQLDirective, + node: FieldNode | DirectiveNode, + variableValues?: Maybe<{ [key: string]: any }>, +): { [key: string]: any }; + +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getDirectiveValues( + directiveDef: GraphQLDirective, + node: { + readonly directives?: ReadonlyArray<DirectiveNode>; + }, + variableValues?: Maybe<{ [key: string]: any }>, +): undefined | { [key: string]: any }; diff --git a/school/node_modules/graphql/execution/values.js b/school/node_modules/graphql/execution/values.js new file mode 100644 index 0000000..ac4bba9 --- /dev/null +++ b/school/node_modules/graphql/execution/values.js @@ -0,0 +1,228 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getVariableValues = getVariableValues; +exports.getArgumentValues = getArgumentValues; +exports.getDirectiveValues = getDirectiveValues; + +var _find = _interopRequireDefault(require("../polyfills/find.js")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _printPathArray = _interopRequireDefault(require("../jsutils/printPathArray.js")); + +var _GraphQLError = require("../error/GraphQLError.js"); + +var _kinds = require("../language/kinds.js"); + +var _printer = require("../language/printer.js"); + +var _definition = require("../type/definition.js"); + +var _typeFromAST = require("../utilities/typeFromAST.js"); + +var _valueFromAST = require("../utilities/valueFromAST.js"); + +var _coerceInputValue = require("../utilities/coerceInputValue.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * + * @internal + */ +function getVariableValues(schema, varDefNodes, inputs, options) { + var errors = []; + var maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors; + + try { + var coerced = coerceVariableValues(schema, varDefNodes, inputs, function (error) { + if (maxErrors != null && errors.length >= maxErrors) { + throw new _GraphQLError.GraphQLError('Too many errors processing variables, error limit reached. Execution aborted.'); + } + + errors.push(error); + }); + + if (errors.length === 0) { + return { + coerced: coerced + }; + } + } catch (error) { + errors.push(error); + } + + return { + errors: errors + }; +} + +function coerceVariableValues(schema, varDefNodes, inputs, onError) { + var coercedValues = {}; + + var _loop = function _loop(_i2) { + var varDefNode = varDefNodes[_i2]; + var varName = varDefNode.variable.name.value; + var varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type); + + if (!(0, _definition.isInputType)(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + var varTypeStr = (0, _printer.print)(varDefNode.type); + onError(new _GraphQLError.GraphQLError("Variable \"$".concat(varName, "\" expected value of type \"").concat(varTypeStr, "\" which cannot be used as an input type."), varDefNode.type)); + return "continue"; + } + + if (!hasOwnProperty(inputs, varName)) { + if (varDefNode.defaultValue) { + coercedValues[varName] = (0, _valueFromAST.valueFromAST)(varDefNode.defaultValue, varType); + } else if ((0, _definition.isNonNullType)(varType)) { + var _varTypeStr = (0, _inspect.default)(varType); + + onError(new _GraphQLError.GraphQLError("Variable \"$".concat(varName, "\" of required type \"").concat(_varTypeStr, "\" was not provided."), varDefNode)); + } + + return "continue"; + } + + var value = inputs[varName]; + + if (value === null && (0, _definition.isNonNullType)(varType)) { + var _varTypeStr2 = (0, _inspect.default)(varType); + + onError(new _GraphQLError.GraphQLError("Variable \"$".concat(varName, "\" of non-null type \"").concat(_varTypeStr2, "\" must not be null."), varDefNode)); + return "continue"; + } + + coercedValues[varName] = (0, _coerceInputValue.coerceInputValue)(value, varType, function (path, invalidValue, error) { + var prefix = "Variable \"$".concat(varName, "\" got invalid value ") + (0, _inspect.default)(invalidValue); + + if (path.length > 0) { + prefix += " at \"".concat(varName).concat((0, _printPathArray.default)(path), "\""); + } + + onError(new _GraphQLError.GraphQLError(prefix + '; ' + error.message, varDefNode, undefined, undefined, undefined, error.originalError)); + }); + }; + + for (var _i2 = 0; _i2 < varDefNodes.length; _i2++) { + var _ret = _loop(_i2); + + if (_ret === "continue") continue; + } + + return coercedValues; +} +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * + * @internal + */ + + +function getArgumentValues(def, node, variableValues) { + var _node$arguments; + + var coercedValues = {}; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + var argumentNodes = (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 ? _node$arguments : []; + var argNodeMap = (0, _keyMap.default)(argumentNodes, function (arg) { + return arg.name.value; + }); + + for (var _i4 = 0, _def$args2 = def.args; _i4 < _def$args2.length; _i4++) { + var argDef = _def$args2[_i4]; + var name = argDef.name; + var argType = argDef.type; + var argumentNode = argNodeMap[name]; + + if (!argumentNode) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + 'was not provided.', node); + } + + continue; + } + + var valueNode = argumentNode.value; + var isNull = valueNode.kind === _kinds.Kind.NULL; + + if (valueNode.kind === _kinds.Kind.VARIABLE) { + var variableName = valueNode.name.value; + + if (variableValues == null || !hasOwnProperty(variableValues, variableName)) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + "was provided the variable \"$".concat(variableName, "\" which was not provided a runtime value."), valueNode); + } + + continue; + } + + isNull = variableValues[variableName] == null; + } + + if (isNull && (0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat((0, _inspect.default)(argType), "\" ") + 'must not be null.', valueNode); + } + + var coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues); + + if (coercedValue === undefined) { + // Note: ValuesOfCorrectTypeRule validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat((0, _printer.print)(valueNode), "."), valueNode); + } + + coercedValues[name] = coercedValue; + } + + return coercedValues; +} +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + + +function getDirectiveValues(directiveDef, node, variableValues) { + var directiveNode = node.directives && (0, _find.default)(node.directives, function (directive) { + return directive.name.value === directiveDef.name; + }); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} diff --git a/school/node_modules/graphql/execution/values.js.flow b/school/node_modules/graphql/execution/values.js.flow new file mode 100644 index 0000000..ef3e390 --- /dev/null +++ b/school/node_modules/graphql/execution/values.js.flow @@ -0,0 +1,267 @@ +// @flow strict +import find from '../polyfills/find'; + +import type { ObjMap } from '../jsutils/ObjMap'; +import keyMap from '../jsutils/keyMap'; +import inspect from '../jsutils/inspect'; +import printPathArray from '../jsutils/printPathArray'; + +import { GraphQLError } from '../error/GraphQLError'; + +import type { + FieldNode, + DirectiveNode, + VariableDefinitionNode, +} from '../language/ast'; +import { Kind } from '../language/kinds'; +import { print } from '../language/printer'; + +import type { GraphQLSchema } from '../type/schema'; +import type { GraphQLField } from '../type/definition'; +import type { GraphQLDirective } from '../type/directives'; +import { isInputType, isNonNullType } from '../type/definition'; + +import { typeFromAST } from '../utilities/typeFromAST'; +import { valueFromAST } from '../utilities/valueFromAST'; +import { coerceInputValue } from '../utilities/coerceInputValue'; + +type CoercedVariableValues = + | {| errors: $ReadOnlyArray<GraphQLError> |} + | {| coerced: { [variable: string]: mixed, ... } |}; + +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * + * @internal + */ +export function getVariableValues( + schema: GraphQLSchema, + varDefNodes: $ReadOnlyArray<VariableDefinitionNode>, + inputs: { +[variable: string]: mixed, ... }, + options?: {| maxErrors?: number |}, +): CoercedVariableValues { + const errors = []; + const maxErrors = options?.maxErrors; + try { + const coerced = coerceVariableValues( + schema, + varDefNodes, + inputs, + (error) => { + if (maxErrors != null && errors.length >= maxErrors) { + throw new GraphQLError( + 'Too many errors processing variables, error limit reached. Execution aborted.', + ); + } + errors.push(error); + }, + ); + + if (errors.length === 0) { + return { coerced }; + } + } catch (error) { + errors.push(error); + } + + return { errors }; +} + +function coerceVariableValues( + schema: GraphQLSchema, + varDefNodes: $ReadOnlyArray<VariableDefinitionNode>, + inputs: { +[variable: string]: mixed, ... }, + onError: (GraphQLError) => void, +): { [variable: string]: mixed, ... } { + const coercedValues = {}; + for (const varDefNode of varDefNodes) { + const varName = varDefNode.variable.name.value; + const varType = typeFromAST(schema, varDefNode.type); + if (!isInputType(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + const varTypeStr = print(varDefNode.type); + onError( + new GraphQLError( + `Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, + varDefNode.type, + ), + ); + continue; + } + + if (!hasOwnProperty(inputs, varName)) { + if (varDefNode.defaultValue) { + coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType); + } else if (isNonNullType(varType)) { + const varTypeStr = inspect(varType); + onError( + new GraphQLError( + `Variable "$${varName}" of required type "${varTypeStr}" was not provided.`, + varDefNode, + ), + ); + } + continue; + } + + const value = inputs[varName]; + if (value === null && isNonNullType(varType)) { + const varTypeStr = inspect(varType); + onError( + new GraphQLError( + `Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`, + varDefNode, + ), + ); + continue; + } + + coercedValues[varName] = coerceInputValue( + value, + varType, + (path, invalidValue, error) => { + let prefix = + `Variable "$${varName}" got invalid value ` + inspect(invalidValue); + if (path.length > 0) { + prefix += ` at "${varName}${printPathArray(path)}"`; + } + onError( + new GraphQLError( + prefix + '; ' + error.message, + varDefNode, + undefined, + undefined, + undefined, + error.originalError, + ), + ); + }, + ); + } + + return coercedValues; +} + +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * + * @internal + */ +export function getArgumentValues( + def: GraphQLField<mixed, mixed> | GraphQLDirective, + node: FieldNode | DirectiveNode, + variableValues?: ?ObjMap<mixed>, +): { [argument: string]: mixed, ... } { + const coercedValues = {}; + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const argumentNodes = node.arguments ?? []; + const argNodeMap = keyMap(argumentNodes, (arg) => arg.name.value); + + for (const argDef of def.args) { + const name = argDef.name; + const argType = argDef.type; + const argumentNode = argNodeMap[name]; + + if (!argumentNode) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if (isNonNullType(argType)) { + throw new GraphQLError( + `Argument "${name}" of required type "${inspect(argType)}" ` + + 'was not provided.', + node, + ); + } + continue; + } + + const valueNode = argumentNode.value; + let isNull = valueNode.kind === Kind.NULL; + + if (valueNode.kind === Kind.VARIABLE) { + const variableName = valueNode.name.value; + if ( + variableValues == null || + !hasOwnProperty(variableValues, variableName) + ) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if (isNonNullType(argType)) { + throw new GraphQLError( + `Argument "${name}" of required type "${inspect(argType)}" ` + + `was provided the variable "$${variableName}" which was not provided a runtime value.`, + valueNode, + ); + } + continue; + } + isNull = variableValues[variableName] == null; + } + + if (isNull && isNonNullType(argType)) { + throw new GraphQLError( + `Argument "${name}" of non-null type "${inspect(argType)}" ` + + 'must not be null.', + valueNode, + ); + } + + const coercedValue = valueFromAST(valueNode, argType, variableValues); + if (coercedValue === undefined) { + // Note: ValuesOfCorrectTypeRule validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new GraphQLError( + `Argument "${name}" has invalid value ${print(valueNode)}.`, + valueNode, + ); + } + coercedValues[name] = coercedValue; + } + return coercedValues; +} + +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getDirectiveValues( + directiveDef: GraphQLDirective, + node: { +directives?: $ReadOnlyArray<DirectiveNode>, ... }, + variableValues?: ?ObjMap<mixed>, +): void | { [argument: string]: mixed, ... } { + const directiveNode = + node.directives && + find( + node.directives, + (directive) => directive.name.value === directiveDef.name, + ); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +function hasOwnProperty(obj: mixed, prop: string): boolean { + return Object.prototype.hasOwnProperty.call(obj, prop); +} diff --git a/school/node_modules/graphql/execution/values.mjs b/school/node_modules/graphql/execution/values.mjs new file mode 100644 index 0000000..485a210 --- /dev/null +++ b/school/node_modules/graphql/execution/values.mjs @@ -0,0 +1,206 @@ +import find from "../polyfills/find.mjs"; +import keyMap from "../jsutils/keyMap.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import printPathArray from "../jsutils/printPathArray.mjs"; +import { GraphQLError } from "../error/GraphQLError.mjs"; +import { Kind } from "../language/kinds.mjs"; +import { print } from "../language/printer.mjs"; +import { isInputType, isNonNullType } from "../type/definition.mjs"; +import { typeFromAST } from "../utilities/typeFromAST.mjs"; +import { valueFromAST } from "../utilities/valueFromAST.mjs"; +import { coerceInputValue } from "../utilities/coerceInputValue.mjs"; + +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * + * @internal + */ +export function getVariableValues(schema, varDefNodes, inputs, options) { + var errors = []; + var maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors; + + try { + var coerced = coerceVariableValues(schema, varDefNodes, inputs, function (error) { + if (maxErrors != null && errors.length >= maxErrors) { + throw new GraphQLError('Too many errors processing variables, error limit reached. Execution aborted.'); + } + + errors.push(error); + }); + + if (errors.length === 0) { + return { + coerced: coerced + }; + } + } catch (error) { + errors.push(error); + } + + return { + errors: errors + }; +} + +function coerceVariableValues(schema, varDefNodes, inputs, onError) { + var coercedValues = {}; + + var _loop = function _loop(_i2) { + var varDefNode = varDefNodes[_i2]; + var varName = varDefNode.variable.name.value; + var varType = typeFromAST(schema, varDefNode.type); + + if (!isInputType(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + var varTypeStr = print(varDefNode.type); + onError(new GraphQLError("Variable \"$".concat(varName, "\" expected value of type \"").concat(varTypeStr, "\" which cannot be used as an input type."), varDefNode.type)); + return "continue"; + } + + if (!hasOwnProperty(inputs, varName)) { + if (varDefNode.defaultValue) { + coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType); + } else if (isNonNullType(varType)) { + var _varTypeStr = inspect(varType); + + onError(new GraphQLError("Variable \"$".concat(varName, "\" of required type \"").concat(_varTypeStr, "\" was not provided."), varDefNode)); + } + + return "continue"; + } + + var value = inputs[varName]; + + if (value === null && isNonNullType(varType)) { + var _varTypeStr2 = inspect(varType); + + onError(new GraphQLError("Variable \"$".concat(varName, "\" of non-null type \"").concat(_varTypeStr2, "\" must not be null."), varDefNode)); + return "continue"; + } + + coercedValues[varName] = coerceInputValue(value, varType, function (path, invalidValue, error) { + var prefix = "Variable \"$".concat(varName, "\" got invalid value ") + inspect(invalidValue); + + if (path.length > 0) { + prefix += " at \"".concat(varName).concat(printPathArray(path), "\""); + } + + onError(new GraphQLError(prefix + '; ' + error.message, varDefNode, undefined, undefined, undefined, error.originalError)); + }); + }; + + for (var _i2 = 0; _i2 < varDefNodes.length; _i2++) { + var _ret = _loop(_i2); + + if (_ret === "continue") continue; + } + + return coercedValues; +} +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * + * @internal + */ + + +export function getArgumentValues(def, node, variableValues) { + var _node$arguments; + + var coercedValues = {}; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + var argumentNodes = (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 ? _node$arguments : []; + var argNodeMap = keyMap(argumentNodes, function (arg) { + return arg.name.value; + }); + + for (var _i4 = 0, _def$args2 = def.args; _i4 < _def$args2.length; _i4++) { + var argDef = _def$args2[_i4]; + var name = argDef.name; + var argType = argDef.type; + var argumentNode = argNodeMap[name]; + + if (!argumentNode) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if (isNonNullType(argType)) { + throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + 'was not provided.', node); + } + + continue; + } + + var valueNode = argumentNode.value; + var isNull = valueNode.kind === Kind.NULL; + + if (valueNode.kind === Kind.VARIABLE) { + var variableName = valueNode.name.value; + + if (variableValues == null || !hasOwnProperty(variableValues, variableName)) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if (isNonNullType(argType)) { + throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + "was provided the variable \"$".concat(variableName, "\" which was not provided a runtime value."), valueNode); + } + + continue; + } + + isNull = variableValues[variableName] == null; + } + + if (isNull && isNonNullType(argType)) { + throw new GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat(inspect(argType), "\" ") + 'must not be null.', valueNode); + } + + var coercedValue = valueFromAST(valueNode, argType, variableValues); + + if (coercedValue === undefined) { + // Note: ValuesOfCorrectTypeRule validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat(print(valueNode), "."), valueNode); + } + + coercedValues[name] = coercedValue; + } + + return coercedValues; +} +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + +export function getDirectiveValues(directiveDef, node, variableValues) { + var directiveNode = node.directives && find(node.directives, function (directive) { + return directive.name.value === directiveDef.name; + }); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} diff --git a/school/node_modules/graphql/graphql.d.ts b/school/node_modules/graphql/graphql.d.ts new file mode 100644 index 0000000..8ba8ef7 --- /dev/null +++ b/school/node_modules/graphql/graphql.d.ts @@ -0,0 +1,82 @@ +import { Maybe } from './jsutils/Maybe'; + +import { Source } from './language/source'; +import { GraphQLSchema } from './type/schema'; +import { GraphQLFieldResolver, GraphQLTypeResolver } from './type/definition'; +import { ExecutionResult } from './execution/execute'; + +/** + * This is the primary entry point function for fulfilling GraphQL operations + * by parsing, validating, and executing a GraphQL document along side a + * GraphQL schema. + * + * More sophisticated GraphQL servers, such as those which persist queries, + * may wish to separate the validation and execution phases to a static time + * tooling step, and a server runtime step. + * + * Accepts either an object with named arguments, or individual arguments: + * + * schema: + * The GraphQL type system to use when validating and executing a query. + * source: + * A GraphQL language formatted string representing the requested operation. + * rootValue: + * The value provided as the first argument to resolver functions on the top + * level type (e.g. the query object type). + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. + * variableValues: + * A mapping of variable name to runtime value to use for all variables + * defined in the requestString. + * operationName: + * The name of the operation to use if requestString contains multiple + * possible operations. Can be omitted if requestString contains only + * one operation. + * fieldResolver: + * A resolver function to use when one is not provided by the schema. + * If not provided, the default field resolver is used (which looks for a + * value or method on the source value with the field's name). + */ +export interface GraphQLArgs { + schema: GraphQLSchema; + source: string | Source; + rootValue?: any; + contextValue?: any; + variableValues?: Maybe<{ [key: string]: any }>; + operationName?: Maybe<string>; + fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>; + typeResolver?: Maybe<GraphQLTypeResolver<any, any>>; +} + +export function graphql(args: GraphQLArgs): Promise<ExecutionResult>; +export function graphql( + schema: GraphQLSchema, + source: Source | string, + rootValue?: any, + contextValue?: any, + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe<string>, + fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>, + typeResolver?: Maybe<GraphQLTypeResolver<any, any>>, +): Promise<ExecutionResult>; + +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ +export function graphqlSync(args: GraphQLArgs): ExecutionResult; +export function graphqlSync( + schema: GraphQLSchema, + source: Source | string, + rootValue?: any, + contextValue?: any, + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe<string>, + fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>, + typeResolver?: Maybe<GraphQLTypeResolver<any, any>>, +): ExecutionResult; diff --git a/school/node_modules/graphql/graphql.js b/school/node_modules/graphql/graphql.js new file mode 100644 index 0000000..f5f4b1d --- /dev/null +++ b/school/node_modules/graphql/graphql.js @@ -0,0 +1,118 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.graphql = graphql; +exports.graphqlSync = graphqlSync; + +var _isPromise = _interopRequireDefault(require("./jsutils/isPromise.js")); + +var _parser = require("./language/parser.js"); + +var _validate = require("./validation/validate.js"); + +var _validate2 = require("./type/validate.js"); + +var _execute = require("./execution/execute.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) { + var _arguments = arguments; + + /* eslint-enable no-redeclare */ + // Always return a Promise for a consistent API. + return new Promise(function (resolve) { + return resolve( // Extract arguments from object args if provided. + _arguments.length === 1 ? graphqlImpl(argsOrSchema) : graphqlImpl({ + schema: argsOrSchema, + source: source, + rootValue: rootValue, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver, + typeResolver: typeResolver + })); + }); +} +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + + +function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + var result = arguments.length === 1 ? graphqlImpl(argsOrSchema) : graphqlImpl({ + schema: argsOrSchema, + source: source, + rootValue: rootValue, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver, + typeResolver: typeResolver + }); // Assert that the execution was synchronous. + + if ((0, _isPromise.default)(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function graphqlImpl(args) { + var schema = args.schema, + source = args.source, + rootValue = args.rootValue, + contextValue = args.contextValue, + variableValues = args.variableValues, + operationName = args.operationName, + fieldResolver = args.fieldResolver, + typeResolver = args.typeResolver; // Validate Schema + + var schemaValidationErrors = (0, _validate2.validateSchema)(schema); + + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors + }; + } // Parse + + + var document; + + try { + document = (0, _parser.parse)(source); + } catch (syntaxError) { + return { + errors: [syntaxError] + }; + } // Validate + + + var validationErrors = (0, _validate.validate)(schema, document); + + if (validationErrors.length > 0) { + return { + errors: validationErrors + }; + } // Execute + + + return (0, _execute.execute)({ + schema: schema, + document: document, + rootValue: rootValue, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver, + typeResolver: typeResolver + }); +} diff --git a/school/node_modules/graphql/graphql.js.flow b/school/node_modules/graphql/graphql.js.flow new file mode 100644 index 0000000..cc24308 --- /dev/null +++ b/school/node_modules/graphql/graphql.js.flow @@ -0,0 +1,207 @@ +// @flow strict +import type { PromiseOrValue } from './jsutils/PromiseOrValue'; +import isPromise from './jsutils/isPromise'; + +import type { Source } from './language/source'; +import { parse } from './language/parser'; + +import { validate } from './validation/validate'; + +import type { + GraphQLFieldResolver, + GraphQLTypeResolver, +} from './type/definition'; +import type { GraphQLSchema } from './type/schema'; +import { validateSchema } from './type/validate'; + +import type { ExecutionResult } from './execution/execute'; +import { execute } from './execution/execute'; + +/** + * This is the primary entry point function for fulfilling GraphQL operations + * by parsing, validating, and executing a GraphQL document along side a + * GraphQL schema. + * + * More sophisticated GraphQL servers, such as those which persist queries, + * may wish to separate the validation and execution phases to a static time + * tooling step, and a server runtime step. + * + * Accepts either an object with named arguments, or individual arguments: + * + * schema: + * The GraphQL type system to use when validating and executing a query. + * source: + * A GraphQL language formatted string representing the requested operation. + * rootValue: + * The value provided as the first argument to resolver functions on the top + * level type (e.g. the query object type). + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. + * variableValues: + * A mapping of variable name to runtime value to use for all variables + * defined in the requestString. + * operationName: + * The name of the operation to use if requestString contains multiple + * possible operations. Can be omitted if requestString contains only + * one operation. + * fieldResolver: + * A resolver function to use when one is not provided by the schema. + * If not provided, the default field resolver is used (which looks for a + * value or method on the source value with the field's name). + * typeResolver: + * A type resolver function to use when none is provided by the schema. + * If not provided, the default type resolver is used (which looks for a + * `__typename` field or alternatively calls the `isTypeOf` method). + */ +export type GraphQLArgs = {| + schema: GraphQLSchema, + source: string | Source, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ +[variable: string]: mixed, ... }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver<any, any>, + typeResolver?: ?GraphQLTypeResolver<any, any>, +|}; +declare function graphql(GraphQLArgs, ..._: []): Promise<ExecutionResult>; +/* eslint-disable no-redeclare */ +declare function graphql( + schema: GraphQLSchema, + source: Source | string, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ +[variable: string]: mixed, ... }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver<any, any>, + typeResolver?: ?GraphQLTypeResolver<any, any>, +): Promise<ExecutionResult>; +export function graphql( + argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, +) { + /* eslint-enable no-redeclare */ + // Always return a Promise for a consistent API. + return new Promise((resolve) => + resolve( + // Extract arguments from object args if provided. + arguments.length === 1 + ? graphqlImpl(argsOrSchema) + : graphqlImpl({ + schema: argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + }), + ), + ); +} + +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ +declare function graphqlSync(GraphQLArgs, ..._: []): ExecutionResult; +/* eslint-disable no-redeclare */ +declare function graphqlSync( + schema: GraphQLSchema, + source: Source | string, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ +[variable: string]: mixed, ... }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver<any, any>, + typeResolver?: ?GraphQLTypeResolver<any, any>, +): ExecutionResult; +export function graphqlSync( + argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, +) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + const result = + arguments.length === 1 + ? graphqlImpl(argsOrSchema) + : graphqlImpl({ + schema: argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + }); + + // Assert that the execution was synchronous. + if (isPromise(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function graphqlImpl(args: GraphQLArgs): PromiseOrValue<ExecutionResult> { + const { + schema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + } = args; + + // Validate Schema + const schemaValidationErrors = validateSchema(schema); + if (schemaValidationErrors.length > 0) { + return { errors: schemaValidationErrors }; + } + + // Parse + let document; + try { + document = parse(source); + } catch (syntaxError) { + return { errors: [syntaxError] }; + } + + // Validate + const validationErrors = validate(schema, document); + if (validationErrors.length > 0) { + return { errors: validationErrors }; + } + + // Execute + return execute({ + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + }); +} diff --git a/school/node_modules/graphql/graphql.mjs b/school/node_modules/graphql/graphql.mjs new file mode 100644 index 0000000..aa3cb91 --- /dev/null +++ b/school/node_modules/graphql/graphql.mjs @@ -0,0 +1,142 @@ +import isPromise from "./jsutils/isPromise.mjs"; +import { parse } from "./language/parser.mjs"; +import { validate } from "./validation/validate.mjs"; +import { validateSchema } from "./type/validate.mjs"; +import { execute } from "./execution/execute.mjs"; +/** + * This is the primary entry point function for fulfilling GraphQL operations + * by parsing, validating, and executing a GraphQL document along side a + * GraphQL schema. + * + * More sophisticated GraphQL servers, such as those which persist queries, + * may wish to separate the validation and execution phases to a static time + * tooling step, and a server runtime step. + * + * Accepts either an object with named arguments, or individual arguments: + * + * schema: + * The GraphQL type system to use when validating and executing a query. + * source: + * A GraphQL language formatted string representing the requested operation. + * rootValue: + * The value provided as the first argument to resolver functions on the top + * level type (e.g. the query object type). + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. + * variableValues: + * A mapping of variable name to runtime value to use for all variables + * defined in the requestString. + * operationName: + * The name of the operation to use if requestString contains multiple + * possible operations. Can be omitted if requestString contains only + * one operation. + * fieldResolver: + * A resolver function to use when one is not provided by the schema. + * If not provided, the default field resolver is used (which looks for a + * value or method on the source value with the field's name). + * typeResolver: + * A type resolver function to use when none is provided by the schema. + * If not provided, the default type resolver is used (which looks for a + * `__typename` field or alternatively calls the `isTypeOf` method). + */ + +export function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) { + var _arguments = arguments; + + /* eslint-enable no-redeclare */ + // Always return a Promise for a consistent API. + return new Promise(function (resolve) { + return resolve( // Extract arguments from object args if provided. + _arguments.length === 1 ? graphqlImpl(argsOrSchema) : graphqlImpl({ + schema: argsOrSchema, + source: source, + rootValue: rootValue, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver, + typeResolver: typeResolver + })); + }); +} +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + +export function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + var result = arguments.length === 1 ? graphqlImpl(argsOrSchema) : graphqlImpl({ + schema: argsOrSchema, + source: source, + rootValue: rootValue, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver, + typeResolver: typeResolver + }); // Assert that the execution was synchronous. + + if (isPromise(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function graphqlImpl(args) { + var schema = args.schema, + source = args.source, + rootValue = args.rootValue, + contextValue = args.contextValue, + variableValues = args.variableValues, + operationName = args.operationName, + fieldResolver = args.fieldResolver, + typeResolver = args.typeResolver; // Validate Schema + + var schemaValidationErrors = validateSchema(schema); + + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors + }; + } // Parse + + + var document; + + try { + document = parse(source); + } catch (syntaxError) { + return { + errors: [syntaxError] + }; + } // Validate + + + var validationErrors = validate(schema, document); + + if (validationErrors.length > 0) { + return { + errors: validationErrors + }; + } // Execute + + + return execute({ + schema: schema, + document: document, + rootValue: rootValue, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver, + typeResolver: typeResolver + }); +} diff --git a/school/node_modules/graphql/index.d.ts b/school/node_modules/graphql/index.d.ts new file mode 100644 index 0000000..e0707ad --- /dev/null +++ b/school/node_modules/graphql/index.d.ts @@ -0,0 +1,469 @@ +// Minimum TypeScript Version: 2.6 + +/** + * GraphQL.js provides a reference implementation for the GraphQL specification + * but is also a useful utility for operating on GraphQL files and building + * sophisticated tools. + * + * This primary module exports a general purpose function for fulfilling all + * steps of the GraphQL specification in a single operation, but also includes + * utilities for every part of the GraphQL specification: + * + * - Parsing the GraphQL language. + * - Building a GraphQL type schema. + * - Validating a GraphQL request against a type schema. + * - Executing a GraphQL request against a type schema. + * + * This also includes utility functions for operating on GraphQL types and + * GraphQL documents to facilitate building tools. + * + * You may also import from each sub-directory directly. For example, the + * following two import statements are equivalent: + * + * import { parse } from 'graphql'; + * import { parse } from 'graphql/language'; + */ + +// The GraphQL.js version info. +export { version, versionInfo } from './version'; + +// The primary entry point into fulfilling a GraphQL request. +export { GraphQLArgs, graphql, graphqlSync } from './graphql'; + +// Create and operate on GraphQL type definitions and schema. +export { + // Definitions + GraphQLSchema, + GraphQLDirective, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, + // Standard GraphQL Scalars + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, + // Built-in Directives defined by the Spec + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + // "Enum" of Type Kinds + TypeKind, + // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, + // GraphQL Types for introspection. + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, + // Predicates + isSchema, + isDirective, + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, + isSpecifiedScalarType, + isIntrospectionType, + isSpecifiedDirective, + // Assertions + assertSchema, + assertDirective, + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, + // Un-modifiers + getNullableType, + getNamedType, + // Validate GraphQL schema. + validateSchema, + assertValidSchema, +} from './type/index'; + +export { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + Thunk, + GraphQLNamedInputType, + GraphQLNamedOutputType, + GraphQLSchemaConfig, + GraphQLSchemaExtensions, + GraphQLDirectiveConfig, + GraphQLDirectiveExtensions, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLArgumentExtensions, + GraphQLEnumTypeConfig, + GraphQLEnumTypeExtensions, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueExtensions, + GraphQLEnumValueConfigMap, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldExtensions, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldExtensions, + GraphQLInputFieldConfigMap, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInputObjectTypeExtensions, + GraphQLInterfaceTypeConfig, + GraphQLInterfaceTypeExtensions, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLObjectTypeExtensions, + GraphQLResolveInfo, + ResponsePath, + GraphQLScalarTypeConfig, + GraphQLScalarTypeExtensions, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLUnionTypeExtensions, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from './type/index'; + +// Parse and operate on GraphQL language source files. +export { + Token, + Source, + Location, + getLocation, + // Print source location + printLocation, + printSourceLocation, + // Lex + Lexer, + TokenKind, + // Parse + parse, + parseValue, + parseType, + // Print + print, + // Visit + visit, + visitInParallel, + getVisitFn, + BREAK, + Kind, + DirectiveLocation, + // Predicates + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, +} from './language/index'; + +export { + ParseOptions, + SourceLocation, + TokenKindEnum, + KindEnum, + DirectiveLocationEnum, + // Visitor utilities + ASTVisitor, + Visitor, + VisitFn, + VisitorKeyMap, + ASTVisitorKeyMap, + // AST nodes + ASTNode, + ASTKindToNode, + // Each kind of AST node + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from './language/index'; + +// Execute GraphQL queries. +export { + execute, + executeSync, + defaultFieldResolver, + defaultTypeResolver, + responsePathAsArray, + getDirectiveValues, + ExecutionArgs, + ExecutionResult, + FormattedExecutionResult, +} from './execution/index'; + +export { + subscribe, + createSourceEventStream, + SubscriptionArgs, +} from './subscription/index'; + +// Validate GraphQL documents. +export { + validate, + ValidationContext, + // All validation rules in the GraphQL Specification. + specifiedRules, + // Individual validation rules. + ExecutableDefinitionsRule, + FieldsOnCorrectTypeRule, + FragmentsOnCompositeTypesRule, + KnownArgumentNamesRule, + KnownDirectivesRule, + KnownFragmentNamesRule, + KnownTypeNamesRule, + LoneAnonymousOperationRule, + NoFragmentCyclesRule, + NoUndefinedVariablesRule, + NoUnusedFragmentsRule, + NoUnusedVariablesRule, + OverlappingFieldsCanBeMergedRule, + PossibleFragmentSpreadsRule, + ProvidedRequiredArgumentsRule, + ScalarLeafsRule, + SingleFieldSubscriptionsRule, + UniqueArgumentNamesRule, + UniqueDirectivesPerLocationRule, + UniqueFragmentNamesRule, + UniqueInputFieldNamesRule, + UniqueOperationNamesRule, + UniqueVariableNamesRule, + ValuesOfCorrectTypeRule, + VariablesAreInputTypesRule, + VariablesInAllowedPositionRule, + // SDL-specific validation rules + LoneSchemaDefinitionRule, + UniqueOperationTypesRule, + UniqueTypeNamesRule, + UniqueEnumValueNamesRule, + UniqueFieldDefinitionNamesRule, + UniqueDirectiveNamesRule, + PossibleTypeExtensionsRule, + // Custom validation rules + NoDeprecatedCustomRule, + NoSchemaIntrospectionCustomRule, + ValidationRule, +} from './validation/index'; + +// Create, format, and print GraphQL errors. +export { + GraphQLError, + syntaxError, + locatedError, + printError, + formatError, + GraphQLFormattedError, + GraphQLErrorExtensions, +} from './error/index'; + +// Utilities for operating on GraphQL type schema and parsed sources. +export { + // Produce the GraphQL query recommended for a full schema introspection. + // Accepts optional IntrospectionOptions. + getIntrospectionQuery, + // Gets the target Operation from a Document. + getOperationAST, + // Gets the Type for the target Operation AST. + getOperationRootType, + // Convert a GraphQLSchema to an IntrospectionQuery. + introspectionFromSchema, + // Build a GraphQLSchema from an introspection result. + buildClientSchema, + // Build a GraphQLSchema from a parsed GraphQL Schema language AST. + buildASTSchema, + // Build a GraphQLSchema from a GraphQL schema language document. + buildSchema, + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16. + getDescription, + // Extends an existing GraphQLSchema from a parsed GraphQL Schema + // language AST. + extendSchema, + // Sort a GraphQLSchema. + lexicographicSortSchema, + // Print a GraphQLSchema to GraphQL Schema language. + printSchema, + // Print a GraphQLType to GraphQL Schema language. + printType, + // Prints the built-in introspection schema in the Schema Language + // format. + printIntrospectionSchema, + // Create a GraphQLType from a GraphQL language AST. + typeFromAST, + // Create a JavaScript value from a GraphQL language AST with a Type. + valueFromAST, + // Create a JavaScript value from a GraphQL language AST without a Type. + valueFromASTUntyped, + // Create a GraphQL language AST from a JavaScript value. + astFromValue, + // A helper to use within recursive-descent visitors which need to be aware of + // the GraphQL type system. + TypeInfo, + visitWithTypeInfo, + // Coerces a JavaScript value to a GraphQL type, or produces errors. + coerceInputValue, + // Concatenates multiple AST together. + concatAST, + // Separates an AST into an AST per Operation. + separateOperations, + // Strips characters that are not significant to the validity or execution + // of a GraphQL document. + stripIgnoredCharacters, + // Comparators for types + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, + // Asserts a string is a valid GraphQL name. + assertValidName, + // Determine if a string is a valid GraphQL name. + isValidNameError, + // Compares two GraphQLSchemas and detects breaking changes. + BreakingChangeType, + DangerousChangeType, + findBreakingChanges, + findDangerousChanges, + // @deprecated: Report all deprecated usage within a GraphQL document. + findDeprecatedUsages, +} from './utilities/index'; + +export { + IntrospectionOptions, + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionInputType, + IntrospectionOutputType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionInputTypeRef, + IntrospectionOutputTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, + BuildSchemaOptions, + BreakingChange, + DangerousChange, + TypedQueryDocumentNode, +} from './utilities/index'; diff --git a/school/node_modules/graphql/index.js b/school/node_modules/graphql/index.js new file mode 100644 index 0000000..8822148 --- /dev/null +++ b/school/node_modules/graphql/index.js @@ -0,0 +1,1205 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function get() { + return _version.version; + } +}); +Object.defineProperty(exports, "versionInfo", { + enumerable: true, + get: function get() { + return _version.versionInfo; + } +}); +Object.defineProperty(exports, "graphql", { + enumerable: true, + get: function get() { + return _graphql.graphql; + } +}); +Object.defineProperty(exports, "graphqlSync", { + enumerable: true, + get: function get() { + return _graphql.graphqlSync; + } +}); +Object.defineProperty(exports, "GraphQLSchema", { + enumerable: true, + get: function get() { + return _index.GraphQLSchema; + } +}); +Object.defineProperty(exports, "GraphQLDirective", { + enumerable: true, + get: function get() { + return _index.GraphQLDirective; + } +}); +Object.defineProperty(exports, "GraphQLScalarType", { + enumerable: true, + get: function get() { + return _index.GraphQLScalarType; + } +}); +Object.defineProperty(exports, "GraphQLObjectType", { + enumerable: true, + get: function get() { + return _index.GraphQLObjectType; + } +}); +Object.defineProperty(exports, "GraphQLInterfaceType", { + enumerable: true, + get: function get() { + return _index.GraphQLInterfaceType; + } +}); +Object.defineProperty(exports, "GraphQLUnionType", { + enumerable: true, + get: function get() { + return _index.GraphQLUnionType; + } +}); +Object.defineProperty(exports, "GraphQLEnumType", { + enumerable: true, + get: function get() { + return _index.GraphQLEnumType; + } +}); +Object.defineProperty(exports, "GraphQLInputObjectType", { + enumerable: true, + get: function get() { + return _index.GraphQLInputObjectType; + } +}); +Object.defineProperty(exports, "GraphQLList", { + enumerable: true, + get: function get() { + return _index.GraphQLList; + } +}); +Object.defineProperty(exports, "GraphQLNonNull", { + enumerable: true, + get: function get() { + return _index.GraphQLNonNull; + } +}); +Object.defineProperty(exports, "specifiedScalarTypes", { + enumerable: true, + get: function get() { + return _index.specifiedScalarTypes; + } +}); +Object.defineProperty(exports, "GraphQLInt", { + enumerable: true, + get: function get() { + return _index.GraphQLInt; + } +}); +Object.defineProperty(exports, "GraphQLFloat", { + enumerable: true, + get: function get() { + return _index.GraphQLFloat; + } +}); +Object.defineProperty(exports, "GraphQLString", { + enumerable: true, + get: function get() { + return _index.GraphQLString; + } +}); +Object.defineProperty(exports, "GraphQLBoolean", { + enumerable: true, + get: function get() { + return _index.GraphQLBoolean; + } +}); +Object.defineProperty(exports, "GraphQLID", { + enumerable: true, + get: function get() { + return _index.GraphQLID; + } +}); +Object.defineProperty(exports, "specifiedDirectives", { + enumerable: true, + get: function get() { + return _index.specifiedDirectives; + } +}); +Object.defineProperty(exports, "GraphQLIncludeDirective", { + enumerable: true, + get: function get() { + return _index.GraphQLIncludeDirective; + } +}); +Object.defineProperty(exports, "GraphQLSkipDirective", { + enumerable: true, + get: function get() { + return _index.GraphQLSkipDirective; + } +}); +Object.defineProperty(exports, "GraphQLDeprecatedDirective", { + enumerable: true, + get: function get() { + return _index.GraphQLDeprecatedDirective; + } +}); +Object.defineProperty(exports, "GraphQLSpecifiedByDirective", { + enumerable: true, + get: function get() { + return _index.GraphQLSpecifiedByDirective; + } +}); +Object.defineProperty(exports, "TypeKind", { + enumerable: true, + get: function get() { + return _index.TypeKind; + } +}); +Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", { + enumerable: true, + get: function get() { + return _index.DEFAULT_DEPRECATION_REASON; + } +}); +Object.defineProperty(exports, "introspectionTypes", { + enumerable: true, + get: function get() { + return _index.introspectionTypes; + } +}); +Object.defineProperty(exports, "__Schema", { + enumerable: true, + get: function get() { + return _index.__Schema; + } +}); +Object.defineProperty(exports, "__Directive", { + enumerable: true, + get: function get() { + return _index.__Directive; + } +}); +Object.defineProperty(exports, "__DirectiveLocation", { + enumerable: true, + get: function get() { + return _index.__DirectiveLocation; + } +}); +Object.defineProperty(exports, "__Type", { + enumerable: true, + get: function get() { + return _index.__Type; + } +}); +Object.defineProperty(exports, "__Field", { + enumerable: true, + get: function get() { + return _index.__Field; + } +}); +Object.defineProperty(exports, "__InputValue", { + enumerable: true, + get: function get() { + return _index.__InputValue; + } +}); +Object.defineProperty(exports, "__EnumValue", { + enumerable: true, + get: function get() { + return _index.__EnumValue; + } +}); +Object.defineProperty(exports, "__TypeKind", { + enumerable: true, + get: function get() { + return _index.__TypeKind; + } +}); +Object.defineProperty(exports, "SchemaMetaFieldDef", { + enumerable: true, + get: function get() { + return _index.SchemaMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeMetaFieldDef", { + enumerable: true, + get: function get() { + return _index.TypeMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeNameMetaFieldDef", { + enumerable: true, + get: function get() { + return _index.TypeNameMetaFieldDef; + } +}); +Object.defineProperty(exports, "isSchema", { + enumerable: true, + get: function get() { + return _index.isSchema; + } +}); +Object.defineProperty(exports, "isDirective", { + enumerable: true, + get: function get() { + return _index.isDirective; + } +}); +Object.defineProperty(exports, "isType", { + enumerable: true, + get: function get() { + return _index.isType; + } +}); +Object.defineProperty(exports, "isScalarType", { + enumerable: true, + get: function get() { + return _index.isScalarType; + } +}); +Object.defineProperty(exports, "isObjectType", { + enumerable: true, + get: function get() { + return _index.isObjectType; + } +}); +Object.defineProperty(exports, "isInterfaceType", { + enumerable: true, + get: function get() { + return _index.isInterfaceType; + } +}); +Object.defineProperty(exports, "isUnionType", { + enumerable: true, + get: function get() { + return _index.isUnionType; + } +}); +Object.defineProperty(exports, "isEnumType", { + enumerable: true, + get: function get() { + return _index.isEnumType; + } +}); +Object.defineProperty(exports, "isInputObjectType", { + enumerable: true, + get: function get() { + return _index.isInputObjectType; + } +}); +Object.defineProperty(exports, "isListType", { + enumerable: true, + get: function get() { + return _index.isListType; + } +}); +Object.defineProperty(exports, "isNonNullType", { + enumerable: true, + get: function get() { + return _index.isNonNullType; + } +}); +Object.defineProperty(exports, "isInputType", { + enumerable: true, + get: function get() { + return _index.isInputType; + } +}); +Object.defineProperty(exports, "isOutputType", { + enumerable: true, + get: function get() { + return _index.isOutputType; + } +}); +Object.defineProperty(exports, "isLeafType", { + enumerable: true, + get: function get() { + return _index.isLeafType; + } +}); +Object.defineProperty(exports, "isCompositeType", { + enumerable: true, + get: function get() { + return _index.isCompositeType; + } +}); +Object.defineProperty(exports, "isAbstractType", { + enumerable: true, + get: function get() { + return _index.isAbstractType; + } +}); +Object.defineProperty(exports, "isWrappingType", { + enumerable: true, + get: function get() { + return _index.isWrappingType; + } +}); +Object.defineProperty(exports, "isNullableType", { + enumerable: true, + get: function get() { + return _index.isNullableType; + } +}); +Object.defineProperty(exports, "isNamedType", { + enumerable: true, + get: function get() { + return _index.isNamedType; + } +}); +Object.defineProperty(exports, "isRequiredArgument", { + enumerable: true, + get: function get() { + return _index.isRequiredArgument; + } +}); +Object.defineProperty(exports, "isRequiredInputField", { + enumerable: true, + get: function get() { + return _index.isRequiredInputField; + } +}); +Object.defineProperty(exports, "isSpecifiedScalarType", { + enumerable: true, + get: function get() { + return _index.isSpecifiedScalarType; + } +}); +Object.defineProperty(exports, "isIntrospectionType", { + enumerable: true, + get: function get() { + return _index.isIntrospectionType; + } +}); +Object.defineProperty(exports, "isSpecifiedDirective", { + enumerable: true, + get: function get() { + return _index.isSpecifiedDirective; + } +}); +Object.defineProperty(exports, "assertSchema", { + enumerable: true, + get: function get() { + return _index.assertSchema; + } +}); +Object.defineProperty(exports, "assertDirective", { + enumerable: true, + get: function get() { + return _index.assertDirective; + } +}); +Object.defineProperty(exports, "assertType", { + enumerable: true, + get: function get() { + return _index.assertType; + } +}); +Object.defineProperty(exports, "assertScalarType", { + enumerable: true, + get: function get() { + return _index.assertScalarType; + } +}); +Object.defineProperty(exports, "assertObjectType", { + enumerable: true, + get: function get() { + return _index.assertObjectType; + } +}); +Object.defineProperty(exports, "assertInterfaceType", { + enumerable: true, + get: function get() { + return _index.assertInterfaceType; + } +}); +Object.defineProperty(exports, "assertUnionType", { + enumerable: true, + get: function get() { + return _index.assertUnionType; + } +}); +Object.defineProperty(exports, "assertEnumType", { + enumerable: true, + get: function get() { + return _index.assertEnumType; + } +}); +Object.defineProperty(exports, "assertInputObjectType", { + enumerable: true, + get: function get() { + return _index.assertInputObjectType; + } +}); +Object.defineProperty(exports, "assertListType", { + enumerable: true, + get: function get() { + return _index.assertListType; + } +}); +Object.defineProperty(exports, "assertNonNullType", { + enumerable: true, + get: function get() { + return _index.assertNonNullType; + } +}); +Object.defineProperty(exports, "assertInputType", { + enumerable: true, + get: function get() { + return _index.assertInputType; + } +}); +Object.defineProperty(exports, "assertOutputType", { + enumerable: true, + get: function get() { + return _index.assertOutputType; + } +}); +Object.defineProperty(exports, "assertLeafType", { + enumerable: true, + get: function get() { + return _index.assertLeafType; + } +}); +Object.defineProperty(exports, "assertCompositeType", { + enumerable: true, + get: function get() { + return _index.assertCompositeType; + } +}); +Object.defineProperty(exports, "assertAbstractType", { + enumerable: true, + get: function get() { + return _index.assertAbstractType; + } +}); +Object.defineProperty(exports, "assertWrappingType", { + enumerable: true, + get: function get() { + return _index.assertWrappingType; + } +}); +Object.defineProperty(exports, "assertNullableType", { + enumerable: true, + get: function get() { + return _index.assertNullableType; + } +}); +Object.defineProperty(exports, "assertNamedType", { + enumerable: true, + get: function get() { + return _index.assertNamedType; + } +}); +Object.defineProperty(exports, "getNullableType", { + enumerable: true, + get: function get() { + return _index.getNullableType; + } +}); +Object.defineProperty(exports, "getNamedType", { + enumerable: true, + get: function get() { + return _index.getNamedType; + } +}); +Object.defineProperty(exports, "validateSchema", { + enumerable: true, + get: function get() { + return _index.validateSchema; + } +}); +Object.defineProperty(exports, "assertValidSchema", { + enumerable: true, + get: function get() { + return _index.assertValidSchema; + } +}); +Object.defineProperty(exports, "Token", { + enumerable: true, + get: function get() { + return _index2.Token; + } +}); +Object.defineProperty(exports, "Source", { + enumerable: true, + get: function get() { + return _index2.Source; + } +}); +Object.defineProperty(exports, "Location", { + enumerable: true, + get: function get() { + return _index2.Location; + } +}); +Object.defineProperty(exports, "getLocation", { + enumerable: true, + get: function get() { + return _index2.getLocation; + } +}); +Object.defineProperty(exports, "printLocation", { + enumerable: true, + get: function get() { + return _index2.printLocation; + } +}); +Object.defineProperty(exports, "printSourceLocation", { + enumerable: true, + get: function get() { + return _index2.printSourceLocation; + } +}); +Object.defineProperty(exports, "Lexer", { + enumerable: true, + get: function get() { + return _index2.Lexer; + } +}); +Object.defineProperty(exports, "TokenKind", { + enumerable: true, + get: function get() { + return _index2.TokenKind; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _index2.parse; + } +}); +Object.defineProperty(exports, "parseValue", { + enumerable: true, + get: function get() { + return _index2.parseValue; + } +}); +Object.defineProperty(exports, "parseType", { + enumerable: true, + get: function get() { + return _index2.parseType; + } +}); +Object.defineProperty(exports, "print", { + enumerable: true, + get: function get() { + return _index2.print; + } +}); +Object.defineProperty(exports, "visit", { + enumerable: true, + get: function get() { + return _index2.visit; + } +}); +Object.defineProperty(exports, "visitInParallel", { + enumerable: true, + get: function get() { + return _index2.visitInParallel; + } +}); +Object.defineProperty(exports, "getVisitFn", { + enumerable: true, + get: function get() { + return _index2.getVisitFn; + } +}); +Object.defineProperty(exports, "BREAK", { + enumerable: true, + get: function get() { + return _index2.BREAK; + } +}); +Object.defineProperty(exports, "Kind", { + enumerable: true, + get: function get() { + return _index2.Kind; + } +}); +Object.defineProperty(exports, "DirectiveLocation", { + enumerable: true, + get: function get() { + return _index2.DirectiveLocation; + } +}); +Object.defineProperty(exports, "isDefinitionNode", { + enumerable: true, + get: function get() { + return _index2.isDefinitionNode; + } +}); +Object.defineProperty(exports, "isExecutableDefinitionNode", { + enumerable: true, + get: function get() { + return _index2.isExecutableDefinitionNode; + } +}); +Object.defineProperty(exports, "isSelectionNode", { + enumerable: true, + get: function get() { + return _index2.isSelectionNode; + } +}); +Object.defineProperty(exports, "isValueNode", { + enumerable: true, + get: function get() { + return _index2.isValueNode; + } +}); +Object.defineProperty(exports, "isTypeNode", { + enumerable: true, + get: function get() { + return _index2.isTypeNode; + } +}); +Object.defineProperty(exports, "isTypeSystemDefinitionNode", { + enumerable: true, + get: function get() { + return _index2.isTypeSystemDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeDefinitionNode", { + enumerable: true, + get: function get() { + return _index2.isTypeDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeSystemExtensionNode", { + enumerable: true, + get: function get() { + return _index2.isTypeSystemExtensionNode; + } +}); +Object.defineProperty(exports, "isTypeExtensionNode", { + enumerable: true, + get: function get() { + return _index2.isTypeExtensionNode; + } +}); +Object.defineProperty(exports, "execute", { + enumerable: true, + get: function get() { + return _index3.execute; + } +}); +Object.defineProperty(exports, "executeSync", { + enumerable: true, + get: function get() { + return _index3.executeSync; + } +}); +Object.defineProperty(exports, "defaultFieldResolver", { + enumerable: true, + get: function get() { + return _index3.defaultFieldResolver; + } +}); +Object.defineProperty(exports, "defaultTypeResolver", { + enumerable: true, + get: function get() { + return _index3.defaultTypeResolver; + } +}); +Object.defineProperty(exports, "responsePathAsArray", { + enumerable: true, + get: function get() { + return _index3.responsePathAsArray; + } +}); +Object.defineProperty(exports, "getDirectiveValues", { + enumerable: true, + get: function get() { + return _index3.getDirectiveValues; + } +}); +Object.defineProperty(exports, "subscribe", { + enumerable: true, + get: function get() { + return _index4.subscribe; + } +}); +Object.defineProperty(exports, "createSourceEventStream", { + enumerable: true, + get: function get() { + return _index4.createSourceEventStream; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function get() { + return _index5.validate; + } +}); +Object.defineProperty(exports, "ValidationContext", { + enumerable: true, + get: function get() { + return _index5.ValidationContext; + } +}); +Object.defineProperty(exports, "specifiedRules", { + enumerable: true, + get: function get() { + return _index5.specifiedRules; + } +}); +Object.defineProperty(exports, "ExecutableDefinitionsRule", { + enumerable: true, + get: function get() { + return _index5.ExecutableDefinitionsRule; + } +}); +Object.defineProperty(exports, "FieldsOnCorrectTypeRule", { + enumerable: true, + get: function get() { + return _index5.FieldsOnCorrectTypeRule; + } +}); +Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", { + enumerable: true, + get: function get() { + return _index5.FragmentsOnCompositeTypesRule; + } +}); +Object.defineProperty(exports, "KnownArgumentNamesRule", { + enumerable: true, + get: function get() { + return _index5.KnownArgumentNamesRule; + } +}); +Object.defineProperty(exports, "KnownDirectivesRule", { + enumerable: true, + get: function get() { + return _index5.KnownDirectivesRule; + } +}); +Object.defineProperty(exports, "KnownFragmentNamesRule", { + enumerable: true, + get: function get() { + return _index5.KnownFragmentNamesRule; + } +}); +Object.defineProperty(exports, "KnownTypeNamesRule", { + enumerable: true, + get: function get() { + return _index5.KnownTypeNamesRule; + } +}); +Object.defineProperty(exports, "LoneAnonymousOperationRule", { + enumerable: true, + get: function get() { + return _index5.LoneAnonymousOperationRule; + } +}); +Object.defineProperty(exports, "NoFragmentCyclesRule", { + enumerable: true, + get: function get() { + return _index5.NoFragmentCyclesRule; + } +}); +Object.defineProperty(exports, "NoUndefinedVariablesRule", { + enumerable: true, + get: function get() { + return _index5.NoUndefinedVariablesRule; + } +}); +Object.defineProperty(exports, "NoUnusedFragmentsRule", { + enumerable: true, + get: function get() { + return _index5.NoUnusedFragmentsRule; + } +}); +Object.defineProperty(exports, "NoUnusedVariablesRule", { + enumerable: true, + get: function get() { + return _index5.NoUnusedVariablesRule; + } +}); +Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", { + enumerable: true, + get: function get() { + return _index5.OverlappingFieldsCanBeMergedRule; + } +}); +Object.defineProperty(exports, "PossibleFragmentSpreadsRule", { + enumerable: true, + get: function get() { + return _index5.PossibleFragmentSpreadsRule; + } +}); +Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", { + enumerable: true, + get: function get() { + return _index5.ProvidedRequiredArgumentsRule; + } +}); +Object.defineProperty(exports, "ScalarLeafsRule", { + enumerable: true, + get: function get() { + return _index5.ScalarLeafsRule; + } +}); +Object.defineProperty(exports, "SingleFieldSubscriptionsRule", { + enumerable: true, + get: function get() { + return _index5.SingleFieldSubscriptionsRule; + } +}); +Object.defineProperty(exports, "UniqueArgumentNamesRule", { + enumerable: true, + get: function get() { + return _index5.UniqueArgumentNamesRule; + } +}); +Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", { + enumerable: true, + get: function get() { + return _index5.UniqueDirectivesPerLocationRule; + } +}); +Object.defineProperty(exports, "UniqueFragmentNamesRule", { + enumerable: true, + get: function get() { + return _index5.UniqueFragmentNamesRule; + } +}); +Object.defineProperty(exports, "UniqueInputFieldNamesRule", { + enumerable: true, + get: function get() { + return _index5.UniqueInputFieldNamesRule; + } +}); +Object.defineProperty(exports, "UniqueOperationNamesRule", { + enumerable: true, + get: function get() { + return _index5.UniqueOperationNamesRule; + } +}); +Object.defineProperty(exports, "UniqueVariableNamesRule", { + enumerable: true, + get: function get() { + return _index5.UniqueVariableNamesRule; + } +}); +Object.defineProperty(exports, "ValuesOfCorrectTypeRule", { + enumerable: true, + get: function get() { + return _index5.ValuesOfCorrectTypeRule; + } +}); +Object.defineProperty(exports, "VariablesAreInputTypesRule", { + enumerable: true, + get: function get() { + return _index5.VariablesAreInputTypesRule; + } +}); +Object.defineProperty(exports, "VariablesInAllowedPositionRule", { + enumerable: true, + get: function get() { + return _index5.VariablesInAllowedPositionRule; + } +}); +Object.defineProperty(exports, "LoneSchemaDefinitionRule", { + enumerable: true, + get: function get() { + return _index5.LoneSchemaDefinitionRule; + } +}); +Object.defineProperty(exports, "UniqueOperationTypesRule", { + enumerable: true, + get: function get() { + return _index5.UniqueOperationTypesRule; + } +}); +Object.defineProperty(exports, "UniqueTypeNamesRule", { + enumerable: true, + get: function get() { + return _index5.UniqueTypeNamesRule; + } +}); +Object.defineProperty(exports, "UniqueEnumValueNamesRule", { + enumerable: true, + get: function get() { + return _index5.UniqueEnumValueNamesRule; + } +}); +Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", { + enumerable: true, + get: function get() { + return _index5.UniqueFieldDefinitionNamesRule; + } +}); +Object.defineProperty(exports, "UniqueDirectiveNamesRule", { + enumerable: true, + get: function get() { + return _index5.UniqueDirectiveNamesRule; + } +}); +Object.defineProperty(exports, "PossibleTypeExtensionsRule", { + enumerable: true, + get: function get() { + return _index5.PossibleTypeExtensionsRule; + } +}); +Object.defineProperty(exports, "NoDeprecatedCustomRule", { + enumerable: true, + get: function get() { + return _index5.NoDeprecatedCustomRule; + } +}); +Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", { + enumerable: true, + get: function get() { + return _index5.NoSchemaIntrospectionCustomRule; + } +}); +Object.defineProperty(exports, "GraphQLError", { + enumerable: true, + get: function get() { + return _index6.GraphQLError; + } +}); +Object.defineProperty(exports, "syntaxError", { + enumerable: true, + get: function get() { + return _index6.syntaxError; + } +}); +Object.defineProperty(exports, "locatedError", { + enumerable: true, + get: function get() { + return _index6.locatedError; + } +}); +Object.defineProperty(exports, "printError", { + enumerable: true, + get: function get() { + return _index6.printError; + } +}); +Object.defineProperty(exports, "formatError", { + enumerable: true, + get: function get() { + return _index6.formatError; + } +}); +Object.defineProperty(exports, "getIntrospectionQuery", { + enumerable: true, + get: function get() { + return _index7.getIntrospectionQuery; + } +}); +Object.defineProperty(exports, "getOperationAST", { + enumerable: true, + get: function get() { + return _index7.getOperationAST; + } +}); +Object.defineProperty(exports, "getOperationRootType", { + enumerable: true, + get: function get() { + return _index7.getOperationRootType; + } +}); +Object.defineProperty(exports, "introspectionFromSchema", { + enumerable: true, + get: function get() { + return _index7.introspectionFromSchema; + } +}); +Object.defineProperty(exports, "buildClientSchema", { + enumerable: true, + get: function get() { + return _index7.buildClientSchema; + } +}); +Object.defineProperty(exports, "buildASTSchema", { + enumerable: true, + get: function get() { + return _index7.buildASTSchema; + } +}); +Object.defineProperty(exports, "buildSchema", { + enumerable: true, + get: function get() { + return _index7.buildSchema; + } +}); +Object.defineProperty(exports, "getDescription", { + enumerable: true, + get: function get() { + return _index7.getDescription; + } +}); +Object.defineProperty(exports, "extendSchema", { + enumerable: true, + get: function get() { + return _index7.extendSchema; + } +}); +Object.defineProperty(exports, "lexicographicSortSchema", { + enumerable: true, + get: function get() { + return _index7.lexicographicSortSchema; + } +}); +Object.defineProperty(exports, "printSchema", { + enumerable: true, + get: function get() { + return _index7.printSchema; + } +}); +Object.defineProperty(exports, "printType", { + enumerable: true, + get: function get() { + return _index7.printType; + } +}); +Object.defineProperty(exports, "printIntrospectionSchema", { + enumerable: true, + get: function get() { + return _index7.printIntrospectionSchema; + } +}); +Object.defineProperty(exports, "typeFromAST", { + enumerable: true, + get: function get() { + return _index7.typeFromAST; + } +}); +Object.defineProperty(exports, "valueFromAST", { + enumerable: true, + get: function get() { + return _index7.valueFromAST; + } +}); +Object.defineProperty(exports, "valueFromASTUntyped", { + enumerable: true, + get: function get() { + return _index7.valueFromASTUntyped; + } +}); +Object.defineProperty(exports, "astFromValue", { + enumerable: true, + get: function get() { + return _index7.astFromValue; + } +}); +Object.defineProperty(exports, "TypeInfo", { + enumerable: true, + get: function get() { + return _index7.TypeInfo; + } +}); +Object.defineProperty(exports, "visitWithTypeInfo", { + enumerable: true, + get: function get() { + return _index7.visitWithTypeInfo; + } +}); +Object.defineProperty(exports, "coerceInputValue", { + enumerable: true, + get: function get() { + return _index7.coerceInputValue; + } +}); +Object.defineProperty(exports, "concatAST", { + enumerable: true, + get: function get() { + return _index7.concatAST; + } +}); +Object.defineProperty(exports, "separateOperations", { + enumerable: true, + get: function get() { + return _index7.separateOperations; + } +}); +Object.defineProperty(exports, "stripIgnoredCharacters", { + enumerable: true, + get: function get() { + return _index7.stripIgnoredCharacters; + } +}); +Object.defineProperty(exports, "isEqualType", { + enumerable: true, + get: function get() { + return _index7.isEqualType; + } +}); +Object.defineProperty(exports, "isTypeSubTypeOf", { + enumerable: true, + get: function get() { + return _index7.isTypeSubTypeOf; + } +}); +Object.defineProperty(exports, "doTypesOverlap", { + enumerable: true, + get: function get() { + return _index7.doTypesOverlap; + } +}); +Object.defineProperty(exports, "assertValidName", { + enumerable: true, + get: function get() { + return _index7.assertValidName; + } +}); +Object.defineProperty(exports, "isValidNameError", { + enumerable: true, + get: function get() { + return _index7.isValidNameError; + } +}); +Object.defineProperty(exports, "BreakingChangeType", { + enumerable: true, + get: function get() { + return _index7.BreakingChangeType; + } +}); +Object.defineProperty(exports, "DangerousChangeType", { + enumerable: true, + get: function get() { + return _index7.DangerousChangeType; + } +}); +Object.defineProperty(exports, "findBreakingChanges", { + enumerable: true, + get: function get() { + return _index7.findBreakingChanges; + } +}); +Object.defineProperty(exports, "findDangerousChanges", { + enumerable: true, + get: function get() { + return _index7.findDangerousChanges; + } +}); +Object.defineProperty(exports, "findDeprecatedUsages", { + enumerable: true, + get: function get() { + return _index7.findDeprecatedUsages; + } +}); + +var _version = require("./version.js"); + +var _graphql = require("./graphql.js"); + +var _index = require("./type/index.js"); + +var _index2 = require("./language/index.js"); + +var _index3 = require("./execution/index.js"); + +var _index4 = require("./subscription/index.js"); + +var _index5 = require("./validation/index.js"); + +var _index6 = require("./error/index.js"); + +var _index7 = require("./utilities/index.js"); diff --git a/school/node_modules/graphql/index.js.flow b/school/node_modules/graphql/index.js.flow new file mode 100644 index 0000000..5ae3ebd --- /dev/null +++ b/school/node_modules/graphql/index.js.flow @@ -0,0 +1,456 @@ +// @flow strict +/** + * GraphQL.js provides a reference implementation for the GraphQL specification + * but is also a useful utility for operating on GraphQL files and building + * sophisticated tools. + * + * This primary module exports a general purpose function for fulfilling all + * steps of the GraphQL specification in a single operation, but also includes + * utilities for every part of the GraphQL specification: + * + * - Parsing the GraphQL language. + * - Building a GraphQL type schema. + * - Validating a GraphQL request against a type schema. + * - Executing a GraphQL request against a type schema. + * + * This also includes utility functions for operating on GraphQL types and + * GraphQL documents to facilitate building tools. + * + * You may also import from each sub-directory directly. For example, the + * following two import statements are equivalent: + * + * import { parse } from 'graphql'; + * import { parse } from 'graphql/language'; + */ + +// The GraphQL.js version info. +export { version, versionInfo } from './version'; + +// The primary entry point into fulfilling a GraphQL request. +export type { GraphQLArgs } from './graphql'; +export { graphql, graphqlSync } from './graphql'; + +// Create and operate on GraphQL type definitions and schema. +export { + // Definitions + GraphQLSchema, + GraphQLDirective, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, + // Standard GraphQL Scalars + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, + // Built-in Directives defined by the Spec + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + // "Enum" of Type Kinds + TypeKind, + // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, + // GraphQL Types for introspection. + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, + // Predicates + isSchema, + isDirective, + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, + isSpecifiedScalarType, + isIntrospectionType, + isSpecifiedDirective, + // Assertions + assertSchema, + assertDirective, + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, + // Un-modifiers + getNullableType, + getNamedType, + // Validate GraphQL schema. + validateSchema, + assertValidSchema, +} from './type/index'; + +export type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + Thunk, + GraphQLNamedInputType, + GraphQLNamedOutputType, + GraphQLSchemaConfig, + GraphQLDirectiveConfig, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLEnumTypeConfig, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueConfigMap, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldConfigMap, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInterfaceTypeConfig, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLResolveInfo, + ResponsePath, + GraphQLScalarTypeConfig, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from './type/index'; + +// Parse and operate on GraphQL language source files. +export { + Token, + Source, + Location, + getLocation, + // Print source location + printLocation, + printSourceLocation, + // Lex + Lexer, + TokenKind, + // Parse + parse, + parseValue, + parseType, + // Print + print, + // Visit + visit, + visitInParallel, + getVisitFn, + BREAK, + Kind, + DirectiveLocation, + // Predicates + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, +} from './language/index'; + +export type { + ParseOptions, + SourceLocation, + TokenKindEnum, + KindEnum, + DirectiveLocationEnum, + // Visitor utilities + ASTVisitor, + Visitor, + VisitFn, + VisitorKeyMap, + // AST nodes + ASTNode, + ASTKindToNode, + // Each kind of AST node + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from './language/index'; + +// Execute GraphQL queries. +export { + execute, + executeSync, + defaultFieldResolver, + defaultTypeResolver, + responsePathAsArray, + getDirectiveValues, +} from './execution/index'; + +export type { + ExecutionArgs, + ExecutionResult, + FormattedExecutionResult, +} from './execution/index'; + +export { subscribe, createSourceEventStream } from './subscription/index'; +export type { SubscriptionArgs } from './subscription/index'; + +// Validate GraphQL documents. +export { + validate, + ValidationContext, + // All validation rules in the GraphQL Specification. + specifiedRules, + // Individual validation rules. + ExecutableDefinitionsRule, + FieldsOnCorrectTypeRule, + FragmentsOnCompositeTypesRule, + KnownArgumentNamesRule, + KnownDirectivesRule, + KnownFragmentNamesRule, + KnownTypeNamesRule, + LoneAnonymousOperationRule, + NoFragmentCyclesRule, + NoUndefinedVariablesRule, + NoUnusedFragmentsRule, + NoUnusedVariablesRule, + OverlappingFieldsCanBeMergedRule, + PossibleFragmentSpreadsRule, + ProvidedRequiredArgumentsRule, + ScalarLeafsRule, + SingleFieldSubscriptionsRule, + UniqueArgumentNamesRule, + UniqueDirectivesPerLocationRule, + UniqueFragmentNamesRule, + UniqueInputFieldNamesRule, + UniqueOperationNamesRule, + UniqueVariableNamesRule, + ValuesOfCorrectTypeRule, + VariablesAreInputTypesRule, + VariablesInAllowedPositionRule, + // SDL-specific validation rules + LoneSchemaDefinitionRule, + UniqueOperationTypesRule, + UniqueTypeNamesRule, + UniqueEnumValueNamesRule, + UniqueFieldDefinitionNamesRule, + UniqueDirectiveNamesRule, + PossibleTypeExtensionsRule, + // Custom validation rules + NoDeprecatedCustomRule, + NoSchemaIntrospectionCustomRule, +} from './validation/index'; + +export type { ValidationRule } from './validation/index'; + +// Create, format, and print GraphQL errors. +export { + GraphQLError, + syntaxError, + locatedError, + printError, + formatError, +} from './error/index'; + +export type { GraphQLFormattedError } from './error/index'; + +// Utilities for operating on GraphQL type schema and parsed sources. +export { + // Produce the GraphQL query recommended for a full schema introspection. + // Accepts optional IntrospectionOptions. + getIntrospectionQuery, + // Gets the target Operation from a Document. + getOperationAST, + // Gets the Type for the target Operation AST. + getOperationRootType, + // Convert a GraphQLSchema to an IntrospectionQuery. + introspectionFromSchema, + // Build a GraphQLSchema from an introspection result. + buildClientSchema, + // Build a GraphQLSchema from a parsed GraphQL Schema language AST. + buildASTSchema, + // Build a GraphQLSchema from a GraphQL schema language document. + buildSchema, + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16. + getDescription, + // Extends an existing GraphQLSchema from a parsed GraphQL Schema + // language AST. + extendSchema, + // Sort a GraphQLSchema. + lexicographicSortSchema, + // Print a GraphQLSchema to GraphQL Schema language. + printSchema, + // Print a GraphQLType to GraphQL Schema language. + printType, + // Prints the built-in introspection schema in the Schema Language + // format. + printIntrospectionSchema, + // Create a GraphQLType from a GraphQL language AST. + typeFromAST, + // Create a JavaScript value from a GraphQL language AST with a Type. + valueFromAST, + // Create a JavaScript value from a GraphQL language AST without a Type. + valueFromASTUntyped, + // Create a GraphQL language AST from a JavaScript value. + astFromValue, + // A helper to use within recursive-descent visitors which need to be aware of + // the GraphQL type system. + TypeInfo, + visitWithTypeInfo, + // Coerces a JavaScript value to a GraphQL type, or produces errors. + coerceInputValue, + // Concatenates multiple AST together. + concatAST, + // Separates an AST into an AST per Operation. + separateOperations, + // Strips characters that are not significant to the validity or execution + // of a GraphQL document. + stripIgnoredCharacters, + // Comparators for types + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, + // Asserts a string is a valid GraphQL name. + assertValidName, + // Determine if a string is a valid GraphQL name. + isValidNameError, + // Compares two GraphQLSchemas and detects breaking changes. + BreakingChangeType, + DangerousChangeType, + findBreakingChanges, + findDangerousChanges, + // @deprecated: Report all deprecated usage within a GraphQL document. + findDeprecatedUsages, +} from './utilities/index'; + +export type { + IntrospectionOptions, + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionInputType, + IntrospectionOutputType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionInputTypeRef, + IntrospectionOutputTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, + BuildSchemaOptions, + BreakingChange, + DangerousChange, +} from './utilities/index'; diff --git a/school/node_modules/graphql/index.mjs b/school/node_modules/graphql/index.mjs new file mode 100644 index 0000000..952630a --- /dev/null +++ b/school/node_modules/graphql/index.mjs @@ -0,0 +1,94 @@ +/** + * GraphQL.js provides a reference implementation for the GraphQL specification + * but is also a useful utility for operating on GraphQL files and building + * sophisticated tools. + * + * This primary module exports a general purpose function for fulfilling all + * steps of the GraphQL specification in a single operation, but also includes + * utilities for every part of the GraphQL specification: + * + * - Parsing the GraphQL language. + * - Building a GraphQL type schema. + * - Validating a GraphQL request against a type schema. + * - Executing a GraphQL request against a type schema. + * + * This also includes utility functions for operating on GraphQL types and + * GraphQL documents to facilitate building tools. + * + * You may also import from each sub-directory directly. For example, the + * following two import statements are equivalent: + * + * import { parse } from 'graphql'; + * import { parse } from 'graphql/language'; + */ +// The GraphQL.js version info. +export { version, versionInfo } from "./version.mjs"; // The primary entry point into fulfilling a GraphQL request. + +export { graphql, graphqlSync } from "./graphql.mjs"; // Create and operate on GraphQL type definitions and schema. + +export { // Definitions +GraphQLSchema, GraphQLDirective, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull // Standard GraphQL Scalars +, specifiedScalarTypes, GraphQLInt, GraphQLFloat, GraphQLString, GraphQLBoolean, GraphQLID // Built-in Directives defined by the Spec +, specifiedDirectives, GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, GraphQLSpecifiedByDirective // "Enum" of Type Kinds +, TypeKind // Constant Deprecation Reason +, DEFAULT_DEPRECATION_REASON // GraphQL Types for introspection. +, introspectionTypes, __Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind // Meta-field definitions. +, SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef // Predicates +, isSchema, isDirective, isType, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isListType, isNonNullType, isInputType, isOutputType, isLeafType, isCompositeType, isAbstractType, isWrappingType, isNullableType, isNamedType, isRequiredArgument, isRequiredInputField, isSpecifiedScalarType, isIntrospectionType, isSpecifiedDirective // Assertions +, assertSchema, assertDirective, assertType, assertScalarType, assertObjectType, assertInterfaceType, assertUnionType, assertEnumType, assertInputObjectType, assertListType, assertNonNullType, assertInputType, assertOutputType, assertLeafType, assertCompositeType, assertAbstractType, assertWrappingType, assertNullableType, assertNamedType // Un-modifiers +, getNullableType, getNamedType // Validate GraphQL schema. +, validateSchema, assertValidSchema } from "./type/index.mjs"; +// Parse and operate on GraphQL language source files. +export { Token, Source, Location, getLocation // Print source location +, printLocation, printSourceLocation // Lex +, Lexer, TokenKind // Parse +, parse, parseValue, parseType // Print +, print // Visit +, visit, visitInParallel, getVisitFn, BREAK, Kind, DirectiveLocation // Predicates +, isDefinitionNode, isExecutableDefinitionNode, isSelectionNode, isValueNode, isTypeNode, isTypeSystemDefinitionNode, isTypeDefinitionNode, isTypeSystemExtensionNode, isTypeExtensionNode } from "./language/index.mjs"; +// Execute GraphQL queries. +export { execute, executeSync, defaultFieldResolver, defaultTypeResolver, responsePathAsArray, getDirectiveValues } from "./execution/index.mjs"; +export { subscribe, createSourceEventStream } from "./subscription/index.mjs"; +// Validate GraphQL documents. +export { validate, ValidationContext // All validation rules in the GraphQL Specification. +, specifiedRules // Individual validation rules. +, ExecutableDefinitionsRule, FieldsOnCorrectTypeRule, FragmentsOnCompositeTypesRule, KnownArgumentNamesRule, KnownDirectivesRule, KnownFragmentNamesRule, KnownTypeNamesRule, LoneAnonymousOperationRule, NoFragmentCyclesRule, NoUndefinedVariablesRule, NoUnusedFragmentsRule, NoUnusedVariablesRule, OverlappingFieldsCanBeMergedRule, PossibleFragmentSpreadsRule, ProvidedRequiredArgumentsRule, ScalarLeafsRule, SingleFieldSubscriptionsRule, UniqueArgumentNamesRule, UniqueDirectivesPerLocationRule, UniqueFragmentNamesRule, UniqueInputFieldNamesRule, UniqueOperationNamesRule, UniqueVariableNamesRule, ValuesOfCorrectTypeRule, VariablesAreInputTypesRule, VariablesInAllowedPositionRule // SDL-specific validation rules +, LoneSchemaDefinitionRule, UniqueOperationTypesRule, UniqueTypeNamesRule, UniqueEnumValueNamesRule, UniqueFieldDefinitionNamesRule, UniqueDirectiveNamesRule, PossibleTypeExtensionsRule // Custom validation rules +, NoDeprecatedCustomRule, NoSchemaIntrospectionCustomRule } from "./validation/index.mjs"; +// Create, format, and print GraphQL errors. +export { GraphQLError, syntaxError, locatedError, printError, formatError } from "./error/index.mjs"; +// Utilities for operating on GraphQL type schema and parsed sources. +export { // Produce the GraphQL query recommended for a full schema introspection. +// Accepts optional IntrospectionOptions. +getIntrospectionQuery // Gets the target Operation from a Document. +, getOperationAST // Gets the Type for the target Operation AST. +, getOperationRootType // Convert a GraphQLSchema to an IntrospectionQuery. +, introspectionFromSchema // Build a GraphQLSchema from an introspection result. +, buildClientSchema // Build a GraphQLSchema from a parsed GraphQL Schema language AST. +, buildASTSchema // Build a GraphQLSchema from a GraphQL schema language document. +, buildSchema // @deprecated: Get the description from a schema AST node and supports legacy +// syntax for specifying descriptions - will be removed in v16. +, getDescription // Extends an existing GraphQLSchema from a parsed GraphQL Schema +// language AST. +, extendSchema // Sort a GraphQLSchema. +, lexicographicSortSchema // Print a GraphQLSchema to GraphQL Schema language. +, printSchema // Print a GraphQLType to GraphQL Schema language. +, printType // Prints the built-in introspection schema in the Schema Language +// format. +, printIntrospectionSchema // Create a GraphQLType from a GraphQL language AST. +, typeFromAST // Create a JavaScript value from a GraphQL language AST with a Type. +, valueFromAST // Create a JavaScript value from a GraphQL language AST without a Type. +, valueFromASTUntyped // Create a GraphQL language AST from a JavaScript value. +, astFromValue // A helper to use within recursive-descent visitors which need to be aware of +// the GraphQL type system. +, TypeInfo, visitWithTypeInfo // Coerces a JavaScript value to a GraphQL type, or produces errors. +, coerceInputValue // Concatenates multiple AST together. +, concatAST // Separates an AST into an AST per Operation. +, separateOperations // Strips characters that are not significant to the validity or execution +// of a GraphQL document. +, stripIgnoredCharacters // Comparators for types +, isEqualType, isTypeSubTypeOf, doTypesOverlap // Asserts a string is a valid GraphQL name. +, assertValidName // Determine if a string is a valid GraphQL name. +, isValidNameError // Compares two GraphQLSchemas and detects breaking changes. +, BreakingChangeType, DangerousChangeType, findBreakingChanges, findDangerousChanges // @deprecated: Report all deprecated usage within a GraphQL document. +, findDeprecatedUsages } from "./utilities/index.mjs"; diff --git a/school/node_modules/graphql/jsutils/Maybe.d.ts b/school/node_modules/graphql/jsutils/Maybe.d.ts new file mode 100644 index 0000000..e8b5e21 --- /dev/null +++ b/school/node_modules/graphql/jsutils/Maybe.d.ts @@ -0,0 +1,2 @@ +// Conveniently represents flow's "Maybe" type https://flow.org/en/docs/types/maybe/ +export type Maybe<T> = null | undefined | T; diff --git a/school/node_modules/graphql/jsutils/ObjMap.js b/school/node_modules/graphql/jsutils/ObjMap.js new file mode 100644 index 0000000..3918c74 --- /dev/null +++ b/school/node_modules/graphql/jsutils/ObjMap.js @@ -0,0 +1 @@ +"use strict"; diff --git a/school/node_modules/graphql/jsutils/ObjMap.js.flow b/school/node_modules/graphql/jsutils/ObjMap.js.flow new file mode 100644 index 0000000..a37d728 --- /dev/null +++ b/school/node_modules/graphql/jsutils/ObjMap.js.flow @@ -0,0 +1,8 @@ +// @flow strict +export type ObjMap<T> = { [key: string]: T, __proto__: null, ... }; +export type ObjMapLike<T> = ObjMap<T> | { [key: string]: T, ... }; + +export type ReadOnlyObjMap<T> = { +[key: string]: T, __proto__: null, ... }; +export type ReadOnlyObjMapLike<T> = + | ReadOnlyObjMap<T> + | { +[key: string]: T, ... }; diff --git a/school/node_modules/graphql/jsutils/ObjMap.mjs b/school/node_modules/graphql/jsutils/ObjMap.mjs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/school/node_modules/graphql/jsutils/ObjMap.mjs @@ -0,0 +1 @@ + diff --git a/school/node_modules/graphql/jsutils/Path.d.ts b/school/node_modules/graphql/jsutils/Path.d.ts new file mode 100644 index 0000000..9a2233d --- /dev/null +++ b/school/node_modules/graphql/jsutils/Path.d.ts @@ -0,0 +1,19 @@ +export interface Path { + prev: Path | undefined; + key: string | number; + typename: string | undefined; +} + +/** + * Given a Path and a key, return a new Path containing the new key. + */ +export function addPath( + prev: Path | undefined, + key: string | number, + typename: string | undefined, +): Path; + +/** + * Given a Path, return an Array of the path keys. + */ +export function pathToArray(path: Path): Array<string | number>; diff --git a/school/node_modules/graphql/jsutils/Path.js b/school/node_modules/graphql/jsutils/Path.js new file mode 100644 index 0000000..9eb2517 --- /dev/null +++ b/school/node_modules/graphql/jsutils/Path.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.addPath = addPath; +exports.pathToArray = pathToArray; + +/** + * Given a Path and a key, return a new Path containing the new key. + */ +function addPath(prev, key, typename) { + return { + prev: prev, + key: key, + typename: typename + }; +} +/** + * Given a Path, return an Array of the path keys. + */ + + +function pathToArray(path) { + var flattened = []; + var curr = path; + + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + + return flattened.reverse(); +} diff --git a/school/node_modules/graphql/jsutils/Path.js.flow b/school/node_modules/graphql/jsutils/Path.js.flow new file mode 100644 index 0000000..4b0e23c --- /dev/null +++ b/school/node_modules/graphql/jsutils/Path.js.flow @@ -0,0 +1,30 @@ +// @flow strict +export type Path = {| + +prev: Path | void, + +key: string | number, + +typename: string | void, +|}; + +/** + * Given a Path and a key, return a new Path containing the new key. + */ +export function addPath( + prev: $ReadOnly<Path> | void, + key: string | number, + typename: string | void, +): Path { + return { prev, key, typename }; +} + +/** + * Given a Path, return an Array of the path keys. + */ +export function pathToArray(path: ?$ReadOnly<Path>): Array<string | number> { + const flattened = []; + let curr = path; + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + return flattened.reverse(); +} diff --git a/school/node_modules/graphql/jsutils/Path.mjs b/school/node_modules/graphql/jsutils/Path.mjs new file mode 100644 index 0000000..af448f0 --- /dev/null +++ b/school/node_modules/graphql/jsutils/Path.mjs @@ -0,0 +1,25 @@ +/** + * Given a Path and a key, return a new Path containing the new key. + */ +export function addPath(prev, key, typename) { + return { + prev: prev, + key: key, + typename: typename + }; +} +/** + * Given a Path, return an Array of the path keys. + */ + +export function pathToArray(path) { + var flattened = []; + var curr = path; + + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + + return flattened.reverse(); +} diff --git a/school/node_modules/graphql/jsutils/PromiseOrValue.d.ts b/school/node_modules/graphql/jsutils/PromiseOrValue.d.ts new file mode 100644 index 0000000..6b2517e --- /dev/null +++ b/school/node_modules/graphql/jsutils/PromiseOrValue.d.ts @@ -0,0 +1 @@ +export type PromiseOrValue<T> = Promise<T> | T; diff --git a/school/node_modules/graphql/jsutils/PromiseOrValue.js b/school/node_modules/graphql/jsutils/PromiseOrValue.js new file mode 100644 index 0000000..3918c74 --- /dev/null +++ b/school/node_modules/graphql/jsutils/PromiseOrValue.js @@ -0,0 +1 @@ +"use strict"; diff --git a/school/node_modules/graphql/jsutils/PromiseOrValue.js.flow b/school/node_modules/graphql/jsutils/PromiseOrValue.js.flow new file mode 100644 index 0000000..dc8df50 --- /dev/null +++ b/school/node_modules/graphql/jsutils/PromiseOrValue.js.flow @@ -0,0 +1,2 @@ +// @flow strict +export type PromiseOrValue<+T> = Promise<T> | T; diff --git a/school/node_modules/graphql/jsutils/PromiseOrValue.mjs b/school/node_modules/graphql/jsutils/PromiseOrValue.mjs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/school/node_modules/graphql/jsutils/PromiseOrValue.mjs @@ -0,0 +1 @@ + diff --git a/school/node_modules/graphql/jsutils/defineInspect.js b/school/node_modules/graphql/jsutils/defineInspect.js new file mode 100644 index 0000000..9bcdcf5 --- /dev/null +++ b/school/node_modules/graphql/jsutils/defineInspect.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = defineInspect; + +var _invariant = _interopRequireDefault(require("./invariant.js")); + +var _nodejsCustomInspectSymbol = _interopRequireDefault(require("./nodejsCustomInspectSymbol.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The `defineInspect()` function defines `inspect()` prototype method as alias of `toJSON` + */ +function defineInspect(classObject) { + var fn = classObject.prototype.toJSON; + typeof fn === 'function' || (0, _invariant.default)(0); + classObject.prototype.inspect = fn; // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2317') + + if (_nodejsCustomInspectSymbol.default) { + classObject.prototype[_nodejsCustomInspectSymbol.default] = fn; + } +} diff --git a/school/node_modules/graphql/jsutils/defineInspect.js.flow b/school/node_modules/graphql/jsutils/defineInspect.js.flow new file mode 100644 index 0000000..5359f76 --- /dev/null +++ b/school/node_modules/graphql/jsutils/defineInspect.js.flow @@ -0,0 +1,20 @@ +// @flow strict +import invariant from './invariant'; +import nodejsCustomInspectSymbol from './nodejsCustomInspectSymbol'; + +/** + * The `defineInspect()` function defines `inspect()` prototype method as alias of `toJSON` + */ +export default function defineInspect( + classObject: Class<any> | ((...args: Array<any>) => mixed), +): void { + const fn = classObject.prototype.toJSON; + invariant(typeof fn === 'function'); + + classObject.prototype.inspect = fn; + + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2317') + if (nodejsCustomInspectSymbol) { + classObject.prototype[nodejsCustomInspectSymbol] = fn; + } +} diff --git a/school/node_modules/graphql/jsutils/defineInspect.mjs b/school/node_modules/graphql/jsutils/defineInspect.mjs new file mode 100644 index 0000000..33f6fdb --- /dev/null +++ b/school/node_modules/graphql/jsutils/defineInspect.mjs @@ -0,0 +1,15 @@ +import invariant from "./invariant.mjs"; +import nodejsCustomInspectSymbol from "./nodejsCustomInspectSymbol.mjs"; +/** + * The `defineInspect()` function defines `inspect()` prototype method as alias of `toJSON` + */ + +export default function defineInspect(classObject) { + var fn = classObject.prototype.toJSON; + typeof fn === 'function' || invariant(0); + classObject.prototype.inspect = fn; // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2317') + + if (nodejsCustomInspectSymbol) { + classObject.prototype[nodejsCustomInspectSymbol] = fn; + } +} diff --git a/school/node_modules/graphql/jsutils/devAssert.js b/school/node_modules/graphql/jsutils/devAssert.js new file mode 100644 index 0000000..25e6d11 --- /dev/null +++ b/school/node_modules/graphql/jsutils/devAssert.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = devAssert; + +function devAssert(condition, message) { + var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js') + + if (!booleanCondition) { + throw new Error(message); + } +} diff --git a/school/node_modules/graphql/jsutils/devAssert.js.flow b/school/node_modules/graphql/jsutils/devAssert.js.flow new file mode 100644 index 0000000..691eae7 --- /dev/null +++ b/school/node_modules/graphql/jsutils/devAssert.js.flow @@ -0,0 +1,8 @@ +// @flow strict +export default function devAssert(condition: mixed, message: string): void { + const booleanCondition = Boolean(condition); + // istanbul ignore else (See transformation done in './resources/inlineInvariant.js') + if (!booleanCondition) { + throw new Error(message); + } +} diff --git a/school/node_modules/graphql/jsutils/devAssert.mjs b/school/node_modules/graphql/jsutils/devAssert.mjs new file mode 100644 index 0000000..e19b7eb --- /dev/null +++ b/school/node_modules/graphql/jsutils/devAssert.mjs @@ -0,0 +1,7 @@ +export default function devAssert(condition, message) { + var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js') + + if (!booleanCondition) { + throw new Error(message); + } +} diff --git a/school/node_modules/graphql/jsutils/didYouMean.js b/school/node_modules/graphql/jsutils/didYouMean.js new file mode 100644 index 0000000..d6b0d90 --- /dev/null +++ b/school/node_modules/graphql/jsutils/didYouMean.js @@ -0,0 +1,42 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = didYouMean; +var MAX_SUGGESTIONS = 5; +/** + * Given [ A, B, C ] return ' Did you mean A, B, or C?'. + */ + +// eslint-disable-next-line no-redeclare +function didYouMean(firstArg, secondArg) { + var _ref = typeof firstArg === 'string' ? [firstArg, secondArg] : [undefined, firstArg], + subMessage = _ref[0], + suggestionsArg = _ref[1]; + + var message = ' Did you mean '; + + if (subMessage) { + message += subMessage + ' '; + } + + var suggestions = suggestionsArg.map(function (x) { + return "\"".concat(x, "\""); + }); + + switch (suggestions.length) { + case 0: + return ''; + + case 1: + return message + suggestions[0] + '?'; + + case 2: + return message + suggestions[0] + ' or ' + suggestions[1] + '?'; + } + + var selected = suggestions.slice(0, MAX_SUGGESTIONS); + var lastItem = selected.pop(); + return message + selected.join(', ') + ', or ' + lastItem + '?'; +} diff --git a/school/node_modules/graphql/jsutils/didYouMean.js.flow b/school/node_modules/graphql/jsutils/didYouMean.js.flow new file mode 100644 index 0000000..fc4e9e1 --- /dev/null +++ b/school/node_modules/graphql/jsutils/didYouMean.js.flow @@ -0,0 +1,39 @@ +// @flow strict +const MAX_SUGGESTIONS = 5; + +/** + * Given [ A, B, C ] return ' Did you mean A, B, or C?'. + */ +declare function didYouMean(suggestions: $ReadOnlyArray<string>): string; +// eslint-disable-next-line no-redeclare +declare function didYouMean( + subMessage: string, + suggestions: $ReadOnlyArray<string>, +): string; + +// eslint-disable-next-line no-redeclare +export default function didYouMean(firstArg, secondArg) { + const [subMessage, suggestionsArg] = + typeof firstArg === 'string' + ? [firstArg, secondArg] + : [undefined, firstArg]; + + let message = ' Did you mean '; + if (subMessage) { + message += subMessage + ' '; + } + + const suggestions = suggestionsArg.map((x) => `"${x}"`); + switch (suggestions.length) { + case 0: + return ''; + case 1: + return message + suggestions[0] + '?'; + case 2: + return message + suggestions[0] + ' or ' + suggestions[1] + '?'; + } + + const selected = suggestions.slice(0, MAX_SUGGESTIONS); + const lastItem = selected.pop(); + return message + selected.join(', ') + ', or ' + lastItem + '?'; +} diff --git a/school/node_modules/graphql/jsutils/didYouMean.mjs b/school/node_modules/graphql/jsutils/didYouMean.mjs new file mode 100644 index 0000000..19e26cc --- /dev/null +++ b/school/node_modules/graphql/jsutils/didYouMean.mjs @@ -0,0 +1,36 @@ +var MAX_SUGGESTIONS = 5; +/** + * Given [ A, B, C ] return ' Did you mean A, B, or C?'. + */ + +// eslint-disable-next-line no-redeclare +export default function didYouMean(firstArg, secondArg) { + var _ref = typeof firstArg === 'string' ? [firstArg, secondArg] : [undefined, firstArg], + subMessage = _ref[0], + suggestionsArg = _ref[1]; + + var message = ' Did you mean '; + + if (subMessage) { + message += subMessage + ' '; + } + + var suggestions = suggestionsArg.map(function (x) { + return "\"".concat(x, "\""); + }); + + switch (suggestions.length) { + case 0: + return ''; + + case 1: + return message + suggestions[0] + '?'; + + case 2: + return message + suggestions[0] + ' or ' + suggestions[1] + '?'; + } + + var selected = suggestions.slice(0, MAX_SUGGESTIONS); + var lastItem = selected.pop(); + return message + selected.join(', ') + ', or ' + lastItem + '?'; +} diff --git a/school/node_modules/graphql/jsutils/identityFunc.js b/school/node_modules/graphql/jsutils/identityFunc.js new file mode 100644 index 0000000..630772f --- /dev/null +++ b/school/node_modules/graphql/jsutils/identityFunc.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = identityFunc; + +/** + * Returns the first argument it receives. + */ +function identityFunc(x) { + return x; +} diff --git a/school/node_modules/graphql/jsutils/identityFunc.js.flow b/school/node_modules/graphql/jsutils/identityFunc.js.flow new file mode 100644 index 0000000..a37961e --- /dev/null +++ b/school/node_modules/graphql/jsutils/identityFunc.js.flow @@ -0,0 +1,7 @@ +// @flow strict +/** + * Returns the first argument it receives. + */ +export default function identityFunc<T>(x: T): T { + return x; +} diff --git a/school/node_modules/graphql/jsutils/identityFunc.mjs b/school/node_modules/graphql/jsutils/identityFunc.mjs new file mode 100644 index 0000000..daf2391 --- /dev/null +++ b/school/node_modules/graphql/jsutils/identityFunc.mjs @@ -0,0 +1,6 @@ +/** + * Returns the first argument it receives. + */ +export default function identityFunc(x) { + return x; +} diff --git a/school/node_modules/graphql/jsutils/inspect.js b/school/node_modules/graphql/jsutils/inspect.js new file mode 100644 index 0000000..8d3a16c --- /dev/null +++ b/school/node_modules/graphql/jsutils/inspect.js @@ -0,0 +1,133 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = inspect; + +var _nodejsCustomInspectSymbol = _interopRequireDefault(require("./nodejsCustomInspectSymbol.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +var MAX_ARRAY_LENGTH = 10; +var MAX_RECURSIVE_DEPTH = 2; +/** + * Used to print values in error messages. + */ + +function inspect(value) { + return formatValue(value, []); +} + +function formatValue(value, seenValues) { + switch (_typeof(value)) { + case 'string': + return JSON.stringify(value); + + case 'function': + return value.name ? "[function ".concat(value.name, "]") : '[function]'; + + case 'object': + if (value === null) { + return 'null'; + } + + return formatObjectValue(value, seenValues); + + default: + return String(value); + } +} + +function formatObjectValue(value, previouslySeenValues) { + if (previouslySeenValues.indexOf(value) !== -1) { + return '[Circular]'; + } + + var seenValues = [].concat(previouslySeenValues, [value]); + var customInspectFn = getCustomFn(value); + + if (customInspectFn !== undefined) { + var customValue = customInspectFn.call(value); // check for infinite recursion + + if (customValue !== value) { + return typeof customValue === 'string' ? customValue : formatValue(customValue, seenValues); + } + } else if (Array.isArray(value)) { + return formatArray(value, seenValues); + } + + return formatObject(value, seenValues); +} + +function formatObject(object, seenValues) { + var keys = Object.keys(object); + + if (keys.length === 0) { + return '{}'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[' + getObjectTag(object) + ']'; + } + + var properties = keys.map(function (key) { + var value = formatValue(object[key], seenValues); + return key + ': ' + value; + }); + return '{ ' + properties.join(', ') + ' }'; +} + +function formatArray(array, seenValues) { + if (array.length === 0) { + return '[]'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[Array]'; + } + + var len = Math.min(MAX_ARRAY_LENGTH, array.length); + var remaining = array.length - len; + var items = []; + + for (var i = 0; i < len; ++i) { + items.push(formatValue(array[i], seenValues)); + } + + if (remaining === 1) { + items.push('... 1 more item'); + } else if (remaining > 1) { + items.push("... ".concat(remaining, " more items")); + } + + return '[' + items.join(', ') + ']'; +} + +function getCustomFn(object) { + var customInspectFn = object[String(_nodejsCustomInspectSymbol.default)]; + + if (typeof customInspectFn === 'function') { + return customInspectFn; + } + + if (typeof object.inspect === 'function') { + return object.inspect; + } +} + +function getObjectTag(object) { + var tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, ''); + + if (tag === 'Object' && typeof object.constructor === 'function') { + var name = object.constructor.name; + + if (typeof name === 'string' && name !== '') { + return name; + } + } + + return tag; +} diff --git a/school/node_modules/graphql/jsutils/inspect.js.flow b/school/node_modules/graphql/jsutils/inspect.js.flow new file mode 100644 index 0000000..77a2b2c --- /dev/null +++ b/school/node_modules/graphql/jsutils/inspect.js.flow @@ -0,0 +1,128 @@ +// @flow strict +/* eslint-disable flowtype/no-weak-types */ +import nodejsCustomInspectSymbol from './nodejsCustomInspectSymbol'; + +const MAX_ARRAY_LENGTH = 10; +const MAX_RECURSIVE_DEPTH = 2; + +/** + * Used to print values in error messages. + */ +export default function inspect(value: mixed): string { + return formatValue(value, []); +} + +function formatValue(value: mixed, seenValues: Array<mixed>): string { + switch (typeof value) { + case 'string': + return JSON.stringify(value); + case 'function': + return value.name ? `[function ${value.name}]` : '[function]'; + case 'object': + if (value === null) { + return 'null'; + } + return formatObjectValue(value, seenValues); + default: + return String(value); + } +} + +function formatObjectValue( + value: Object, + previouslySeenValues: Array<mixed>, +): string { + if (previouslySeenValues.indexOf(value) !== -1) { + return '[Circular]'; + } + + const seenValues = [...previouslySeenValues, value]; + const customInspectFn = getCustomFn(value); + + if (customInspectFn !== undefined) { + const customValue = customInspectFn.call(value); + + // check for infinite recursion + if (customValue !== value) { + return typeof customValue === 'string' + ? customValue + : formatValue(customValue, seenValues); + } + } else if (Array.isArray(value)) { + return formatArray(value, seenValues); + } + + return formatObject(value, seenValues); +} + +function formatObject(object: Object, seenValues: Array<mixed>): string { + const keys = Object.keys(object); + if (keys.length === 0) { + return '{}'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[' + getObjectTag(object) + ']'; + } + + const properties = keys.map((key) => { + const value = formatValue(object[key], seenValues); + return key + ': ' + value; + }); + + return '{ ' + properties.join(', ') + ' }'; +} + +function formatArray(array: Array<mixed>, seenValues: Array<mixed>): string { + if (array.length === 0) { + return '[]'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[Array]'; + } + + const len = Math.min(MAX_ARRAY_LENGTH, array.length); + const remaining = array.length - len; + const items = []; + + for (let i = 0; i < len; ++i) { + items.push(formatValue(array[i], seenValues)); + } + + if (remaining === 1) { + items.push('... 1 more item'); + } else if (remaining > 1) { + items.push(`... ${remaining} more items`); + } + + return '[' + items.join(', ') + ']'; +} + +function getCustomFn(object: Object) { + const customInspectFn = object[String(nodejsCustomInspectSymbol)]; + + if (typeof customInspectFn === 'function') { + return customInspectFn; + } + + if (typeof object.inspect === 'function') { + return object.inspect; + } +} + +function getObjectTag(object: Object): string { + const tag = Object.prototype.toString + .call(object) + .replace(/^\[object /, '') + .replace(/]$/, ''); + + if (tag === 'Object' && typeof object.constructor === 'function') { + const name = object.constructor.name; + if (typeof name === 'string' && name !== '') { + return name; + } + } + + return tag; +} diff --git a/school/node_modules/graphql/jsutils/inspect.mjs b/school/node_modules/graphql/jsutils/inspect.mjs new file mode 100644 index 0000000..caaf7dc --- /dev/null +++ b/school/node_modules/graphql/jsutils/inspect.mjs @@ -0,0 +1,124 @@ +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/* eslint-disable flowtype/no-weak-types */ +import nodejsCustomInspectSymbol from "./nodejsCustomInspectSymbol.mjs"; +var MAX_ARRAY_LENGTH = 10; +var MAX_RECURSIVE_DEPTH = 2; +/** + * Used to print values in error messages. + */ + +export default function inspect(value) { + return formatValue(value, []); +} + +function formatValue(value, seenValues) { + switch (_typeof(value)) { + case 'string': + return JSON.stringify(value); + + case 'function': + return value.name ? "[function ".concat(value.name, "]") : '[function]'; + + case 'object': + if (value === null) { + return 'null'; + } + + return formatObjectValue(value, seenValues); + + default: + return String(value); + } +} + +function formatObjectValue(value, previouslySeenValues) { + if (previouslySeenValues.indexOf(value) !== -1) { + return '[Circular]'; + } + + var seenValues = [].concat(previouslySeenValues, [value]); + var customInspectFn = getCustomFn(value); + + if (customInspectFn !== undefined) { + var customValue = customInspectFn.call(value); // check for infinite recursion + + if (customValue !== value) { + return typeof customValue === 'string' ? customValue : formatValue(customValue, seenValues); + } + } else if (Array.isArray(value)) { + return formatArray(value, seenValues); + } + + return formatObject(value, seenValues); +} + +function formatObject(object, seenValues) { + var keys = Object.keys(object); + + if (keys.length === 0) { + return '{}'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[' + getObjectTag(object) + ']'; + } + + var properties = keys.map(function (key) { + var value = formatValue(object[key], seenValues); + return key + ': ' + value; + }); + return '{ ' + properties.join(', ') + ' }'; +} + +function formatArray(array, seenValues) { + if (array.length === 0) { + return '[]'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[Array]'; + } + + var len = Math.min(MAX_ARRAY_LENGTH, array.length); + var remaining = array.length - len; + var items = []; + + for (var i = 0; i < len; ++i) { + items.push(formatValue(array[i], seenValues)); + } + + if (remaining === 1) { + items.push('... 1 more item'); + } else if (remaining > 1) { + items.push("... ".concat(remaining, " more items")); + } + + return '[' + items.join(', ') + ']'; +} + +function getCustomFn(object) { + var customInspectFn = object[String(nodejsCustomInspectSymbol)]; + + if (typeof customInspectFn === 'function') { + return customInspectFn; + } + + if (typeof object.inspect === 'function') { + return object.inspect; + } +} + +function getObjectTag(object) { + var tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, ''); + + if (tag === 'Object' && typeof object.constructor === 'function') { + var name = object.constructor.name; + + if (typeof name === 'string' && name !== '') { + return name; + } + } + + return tag; +} diff --git a/school/node_modules/graphql/jsutils/instanceOf.js b/school/node_modules/graphql/jsutils/instanceOf.js new file mode 100644 index 0000000..7098094 --- /dev/null +++ b/school/node_modules/graphql/jsutils/instanceOf.js @@ -0,0 +1,42 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _inspect = _interopRequireDefault(require("./inspect.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production +// See: https://webpack.js.org/guides/production/ +var _default = process.env.NODE_ENV === 'production' ? // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') +// eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + return value instanceof constructor; +} : // eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; + } + + if (_typeof(value) === 'object' && value !== null) { + var _value$constructor; + + var className = constructor.prototype[Symbol.toStringTag]; + var valueClassName = // We still need to support constructor's name to detect conflicts with older versions of this library. + Symbol.toStringTag in value ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name; + + if (className === valueClassName) { + var stringifiedValue = (0, _inspect.default)(value); + throw new Error("Cannot use ".concat(className, " \"").concat(stringifiedValue, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.")); + } + } + + return false; +}; + +exports.default = _default; diff --git a/school/node_modules/graphql/jsutils/instanceOf.js.flow b/school/node_modules/graphql/jsutils/instanceOf.js.flow new file mode 100644 index 0000000..58faa02 --- /dev/null +++ b/school/node_modules/graphql/jsutils/instanceOf.js.flow @@ -0,0 +1,52 @@ +// @flow strict +import inspect from './inspect'; + +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + */ +declare function instanceOf( + value: mixed, + constructor: mixed, +): boolean %checks(value instanceof constructor); + +// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production +// See: https://webpack.js.org/guides/production/ +export default process.env.NODE_ENV === 'production' + ? // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') + // eslint-disable-next-line no-shadow + function instanceOf(value: mixed, constructor: mixed): boolean { + return value instanceof constructor; + } + : // eslint-disable-next-line no-shadow + function instanceOf(value: any, constructor: any): boolean { + if (value instanceof constructor) { + return true; + } + if (typeof value === 'object' && value !== null) { + const className = constructor.prototype[Symbol.toStringTag]; + const valueClassName = + // We still need to support constructor's name to detect conflicts with older versions of this library. + Symbol.toStringTag in value + ? value[Symbol.toStringTag] + : value.constructor?.name; + if (className === valueClassName) { + const stringifiedValue = inspect(value); + throw new Error( + `Cannot use ${className} "${stringifiedValue}" from another module or realm. + +Ensure that there is only one instance of "graphql" in the node_modules +directory. If different versions of "graphql" are the dependencies of other +relied on modules, use "resolutions" to ensure only one version is installed. + +https://yarnpkg.com/en/docs/selective-version-resolutions + +Duplicate "graphql" modules cannot be used at the same time since different +versions may have different capabilities and behavior. The data from one +version used in the function from another could produce confusing and +spurious results.`, + ); + } + } + return false; + }; diff --git a/school/node_modules/graphql/jsutils/instanceOf.mjs b/school/node_modules/graphql/jsutils/instanceOf.mjs new file mode 100644 index 0000000..ff46fca --- /dev/null +++ b/school/node_modules/graphql/jsutils/instanceOf.mjs @@ -0,0 +1,35 @@ +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +import inspect from "./inspect.mjs"; +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + */ + +// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production +// See: https://webpack.js.org/guides/production/ +export default process.env.NODE_ENV === 'production' ? // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') +// eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + return value instanceof constructor; +} : // eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; + } + + if (_typeof(value) === 'object' && value !== null) { + var _value$constructor; + + var className = constructor.prototype[Symbol.toStringTag]; + var valueClassName = // We still need to support constructor's name to detect conflicts with older versions of this library. + Symbol.toStringTag in value ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name; + + if (className === valueClassName) { + var stringifiedValue = inspect(value); + throw new Error("Cannot use ".concat(className, " \"").concat(stringifiedValue, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.")); + } + } + + return false; +}; diff --git a/school/node_modules/graphql/jsutils/invariant.js b/school/node_modules/graphql/jsutils/invariant.js new file mode 100644 index 0000000..2e9e16b --- /dev/null +++ b/school/node_modules/graphql/jsutils/invariant.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = invariant; + +function invariant(condition, message) { + var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js') + + if (!booleanCondition) { + throw new Error(message != null ? message : 'Unexpected invariant triggered.'); + } +} diff --git a/school/node_modules/graphql/jsutils/invariant.js.flow b/school/node_modules/graphql/jsutils/invariant.js.flow new file mode 100644 index 0000000..6268571 --- /dev/null +++ b/school/node_modules/graphql/jsutils/invariant.js.flow @@ -0,0 +1,10 @@ +// @flow strict +export default function invariant(condition: mixed, message?: string): void { + const booleanCondition = Boolean(condition); + // istanbul ignore else (See transformation done in './resources/inlineInvariant.js') + if (!booleanCondition) { + throw new Error( + message != null ? message : 'Unexpected invariant triggered.', + ); + } +} diff --git a/school/node_modules/graphql/jsutils/invariant.mjs b/school/node_modules/graphql/jsutils/invariant.mjs new file mode 100644 index 0000000..f1aa4a6 --- /dev/null +++ b/school/node_modules/graphql/jsutils/invariant.mjs @@ -0,0 +1,7 @@ +export default function invariant(condition, message) { + var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js') + + if (!booleanCondition) { + throw new Error(message != null ? message : 'Unexpected invariant triggered.'); + } +} diff --git a/school/node_modules/graphql/jsutils/isAsyncIterable.js b/school/node_modules/graphql/jsutils/isAsyncIterable.js new file mode 100644 index 0000000..3f59f2b --- /dev/null +++ b/school/node_modules/graphql/jsutils/isAsyncIterable.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isAsyncIterable; + +var _symbols = require("../polyfills/symbols.js"); + +// eslint-disable-next-line no-redeclare +function isAsyncIterable(maybeAsyncIterable) { + return typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0 ? void 0 : maybeAsyncIterable[_symbols.SYMBOL_ASYNC_ITERATOR]) === 'function'; +} diff --git a/school/node_modules/graphql/jsutils/isAsyncIterable.js.flow b/school/node_modules/graphql/jsutils/isAsyncIterable.js.flow new file mode 100644 index 0000000..e81f94e --- /dev/null +++ b/school/node_modules/graphql/jsutils/isAsyncIterable.js.flow @@ -0,0 +1,14 @@ +// @flow strict +import { SYMBOL_ASYNC_ITERATOR } from '../polyfills/symbols'; + +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method. + */ +declare function isAsyncIterable(value: mixed): boolean %checks(value instanceof + AsyncIterable); + +// eslint-disable-next-line no-redeclare +export default function isAsyncIterable(maybeAsyncIterable) { + return typeof maybeAsyncIterable?.[SYMBOL_ASYNC_ITERATOR] === 'function'; +} diff --git a/school/node_modules/graphql/jsutils/isAsyncIterable.mjs b/school/node_modules/graphql/jsutils/isAsyncIterable.mjs new file mode 100644 index 0000000..444e87c --- /dev/null +++ b/school/node_modules/graphql/jsutils/isAsyncIterable.mjs @@ -0,0 +1,10 @@ +import { SYMBOL_ASYNC_ITERATOR } from "../polyfills/symbols.mjs"; +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method. + */ + +// eslint-disable-next-line no-redeclare +export default function isAsyncIterable(maybeAsyncIterable) { + return typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0 ? void 0 : maybeAsyncIterable[SYMBOL_ASYNC_ITERATOR]) === 'function'; +} diff --git a/school/node_modules/graphql/jsutils/isObjectLike.js b/school/node_modules/graphql/jsutils/isObjectLike.js new file mode 100644 index 0000000..19c9a89 --- /dev/null +++ b/school/node_modules/graphql/jsutils/isObjectLike.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isObjectLike; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Return true if `value` is object-like. A value is object-like if it's not + * `null` and has a `typeof` result of "object". + */ +function isObjectLike(value) { + return _typeof(value) == 'object' && value !== null; +} diff --git a/school/node_modules/graphql/jsutils/isObjectLike.js.flow b/school/node_modules/graphql/jsutils/isObjectLike.js.flow new file mode 100644 index 0000000..86886ab --- /dev/null +++ b/school/node_modules/graphql/jsutils/isObjectLike.js.flow @@ -0,0 +1,8 @@ +// @flow strict +/** + * Return true if `value` is object-like. A value is object-like if it's not + * `null` and has a `typeof` result of "object". + */ +export default function isObjectLike(value: mixed): boolean %checks { + return typeof value == 'object' && value !== null; +} diff --git a/school/node_modules/graphql/jsutils/isObjectLike.mjs b/school/node_modules/graphql/jsutils/isObjectLike.mjs new file mode 100644 index 0000000..41dc3cd --- /dev/null +++ b/school/node_modules/graphql/jsutils/isObjectLike.mjs @@ -0,0 +1,9 @@ +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Return true if `value` is object-like. A value is object-like if it's not + * `null` and has a `typeof` result of "object". + */ +export default function isObjectLike(value) { + return _typeof(value) == 'object' && value !== null; +} diff --git a/school/node_modules/graphql/jsutils/isPromise.js b/school/node_modules/graphql/jsutils/isPromise.js new file mode 100644 index 0000000..bca6ccc --- /dev/null +++ b/school/node_modules/graphql/jsutils/isPromise.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isPromise; + +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ +// eslint-disable-next-line no-redeclare +function isPromise(value) { + return typeof (value === null || value === void 0 ? void 0 : value.then) === 'function'; +} diff --git a/school/node_modules/graphql/jsutils/isPromise.js.flow b/school/node_modules/graphql/jsutils/isPromise.js.flow new file mode 100644 index 0000000..f5c9f75 --- /dev/null +++ b/school/node_modules/graphql/jsutils/isPromise.js.flow @@ -0,0 +1,12 @@ +// @flow strict +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ +declare function isPromise(value: mixed): boolean %checks(value instanceof + Promise); + +// eslint-disable-next-line no-redeclare +export default function isPromise(value) { + return typeof value?.then === 'function'; +} diff --git a/school/node_modules/graphql/jsutils/isPromise.mjs b/school/node_modules/graphql/jsutils/isPromise.mjs new file mode 100644 index 0000000..2d9079b --- /dev/null +++ b/school/node_modules/graphql/jsutils/isPromise.mjs @@ -0,0 +1,8 @@ +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ +// eslint-disable-next-line no-redeclare +export default function isPromise(value) { + return typeof (value === null || value === void 0 ? void 0 : value.then) === 'function'; +} diff --git a/school/node_modules/graphql/jsutils/keyMap.js b/school/node_modules/graphql/jsutils/keyMap.js new file mode 100644 index 0000000..c067210 --- /dev/null +++ b/school/node_modules/graphql/jsutils/keyMap.js @@ -0,0 +1,36 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = keyMap; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } } + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { name: 'Jenny', num: '857-6309' } + * const jennyEntry = entriesByName['Jenny'] + * + */ +function keyMap(list, keyFn) { + return list.reduce(function (map, item) { + map[keyFn(item)] = item; + return map; + }, Object.create(null)); +} diff --git a/school/node_modules/graphql/jsutils/keyMap.js.flow b/school/node_modules/graphql/jsutils/keyMap.js.flow new file mode 100644 index 0000000..b165360 --- /dev/null +++ b/school/node_modules/graphql/jsutils/keyMap.js.flow @@ -0,0 +1,35 @@ +// @flow strict +import type { ObjMap } from './ObjMap'; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } } + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { name: 'Jenny', num: '857-6309' } + * const jennyEntry = entriesByName['Jenny'] + * + */ +export default function keyMap<T>( + list: $ReadOnlyArray<T>, + keyFn: (item: T) => string, +): ObjMap<T> { + return list.reduce((map, item) => { + map[keyFn(item)] = item; + return map; + }, Object.create(null)); +} diff --git a/school/node_modules/graphql/jsutils/keyMap.mjs b/school/node_modules/graphql/jsutils/keyMap.mjs new file mode 100644 index 0000000..567dd86 --- /dev/null +++ b/school/node_modules/graphql/jsutils/keyMap.mjs @@ -0,0 +1,29 @@ +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } } + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { name: 'Jenny', num: '857-6309' } + * const jennyEntry = entriesByName['Jenny'] + * + */ +export default function keyMap(list, keyFn) { + return list.reduce(function (map, item) { + map[keyFn(item)] = item; + return map; + }, Object.create(null)); +} diff --git a/school/node_modules/graphql/jsutils/keyValMap.js b/school/node_modules/graphql/jsutils/keyValMap.js new file mode 100644 index 0000000..0b2dab5 --- /dev/null +++ b/school/node_modules/graphql/jsutils/keyValMap.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = keyValMap; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * + */ +function keyValMap(list, keyFn, valFn) { + return list.reduce(function (map, item) { + map[keyFn(item)] = valFn(item); + return map; + }, Object.create(null)); +} diff --git a/school/node_modules/graphql/jsutils/keyValMap.js.flow b/school/node_modules/graphql/jsutils/keyValMap.js.flow new file mode 100644 index 0000000..d3aa602 --- /dev/null +++ b/school/node_modules/graphql/jsutils/keyValMap.js.flow @@ -0,0 +1,30 @@ +// @flow strict +import type { ObjMap } from './ObjMap'; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * + */ +export default function keyValMap<T, V>( + list: $ReadOnlyArray<T>, + keyFn: (item: T) => string, + valFn: (item: T) => V, +): ObjMap<V> { + return list.reduce((map, item) => { + map[keyFn(item)] = valFn(item); + return map; + }, Object.create(null)); +} diff --git a/school/node_modules/graphql/jsutils/keyValMap.mjs b/school/node_modules/graphql/jsutils/keyValMap.mjs new file mode 100644 index 0000000..5061c66 --- /dev/null +++ b/school/node_modules/graphql/jsutils/keyValMap.mjs @@ -0,0 +1,23 @@ +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * + */ +export default function keyValMap(list, keyFn, valFn) { + return list.reduce(function (map, item) { + map[keyFn(item)] = valFn(item); + return map; + }, Object.create(null)); +} diff --git a/school/node_modules/graphql/jsutils/mapValue.js b/school/node_modules/graphql/jsutils/mapValue.js new file mode 100644 index 0000000..77d9038 --- /dev/null +++ b/school/node_modules/graphql/jsutils/mapValue.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapValue; + +var _objectEntries3 = _interopRequireDefault(require("../polyfills/objectEntries.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Creates an object map with the same keys as `map` and values generated by + * running each value of `map` thru `fn`. + */ +function mapValue(map, fn) { + var result = Object.create(null); + + for (var _i2 = 0, _objectEntries2 = (0, _objectEntries3.default)(map); _i2 < _objectEntries2.length; _i2++) { + var _ref2 = _objectEntries2[_i2]; + var _key = _ref2[0]; + var _value = _ref2[1]; + result[_key] = fn(_value, _key); + } + + return result; +} diff --git a/school/node_modules/graphql/jsutils/mapValue.js.flow b/school/node_modules/graphql/jsutils/mapValue.js.flow new file mode 100644 index 0000000..d6b5da4 --- /dev/null +++ b/school/node_modules/graphql/jsutils/mapValue.js.flow @@ -0,0 +1,20 @@ +// @flow strict +import objectEntries from '../polyfills/objectEntries'; + +import type { ObjMap } from './ObjMap'; + +/** + * Creates an object map with the same keys as `map` and values generated by + * running each value of `map` thru `fn`. + */ +export default function mapValue<T, V>( + map: ObjMap<T>, + fn: (value: T, key: string) => V, +): ObjMap<V> { + const result = Object.create(null); + + for (const [key, value] of objectEntries(map)) { + result[key] = fn(value, key); + } + return result; +} diff --git a/school/node_modules/graphql/jsutils/mapValue.mjs b/school/node_modules/graphql/jsutils/mapValue.mjs new file mode 100644 index 0000000..7992abb --- /dev/null +++ b/school/node_modules/graphql/jsutils/mapValue.mjs @@ -0,0 +1,18 @@ +import objectEntries from "../polyfills/objectEntries.mjs"; + +/** + * Creates an object map with the same keys as `map` and values generated by + * running each value of `map` thru `fn`. + */ +export default function mapValue(map, fn) { + var result = Object.create(null); + + for (var _i2 = 0, _objectEntries2 = objectEntries(map); _i2 < _objectEntries2.length; _i2++) { + var _ref2 = _objectEntries2[_i2]; + var _key = _ref2[0]; + var _value = _ref2[1]; + result[_key] = fn(_value, _key); + } + + return result; +} diff --git a/school/node_modules/graphql/jsutils/memoize3.js b/school/node_modules/graphql/jsutils/memoize3.js new file mode 100644 index 0000000..db98f3f --- /dev/null +++ b/school/node_modules/graphql/jsutils/memoize3.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = memoize3; + +/** + * Memoizes the provided three-argument function. + */ +function memoize3(fn) { + var cache0; + return function memoized(a1, a2, a3) { + if (!cache0) { + cache0 = new WeakMap(); + } + + var cache1 = cache0.get(a1); + var cache2; + + if (cache1) { + cache2 = cache1.get(a2); + + if (cache2) { + var cachedValue = cache2.get(a3); + + if (cachedValue !== undefined) { + return cachedValue; + } + } + } else { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + + if (!cache2) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + + var newValue = fn(a1, a2, a3); + cache2.set(a3, newValue); + return newValue; + }; +} diff --git a/school/node_modules/graphql/jsutils/memoize3.js.flow b/school/node_modules/graphql/jsutils/memoize3.js.flow new file mode 100644 index 0000000..cd4ccd5 --- /dev/null +++ b/school/node_modules/graphql/jsutils/memoize3.js.flow @@ -0,0 +1,39 @@ +// @flow strict +/** + * Memoizes the provided three-argument function. + */ +export default function memoize3< + A1: { ... } | $ReadOnlyArray<mixed>, + A2: { ... } | $ReadOnlyArray<mixed>, + A3: { ... } | $ReadOnlyArray<mixed>, + R: mixed, +>(fn: (A1, A2, A3) => R): (A1, A2, A3) => R { + let cache0; + + return function memoized(a1, a2, a3) { + if (!cache0) { + cache0 = new WeakMap(); + } + let cache1 = cache0.get(a1); + let cache2; + if (cache1) { + cache2 = cache1.get(a2); + if (cache2) { + const cachedValue = cache2.get(a3); + if (cachedValue !== undefined) { + return cachedValue; + } + } + } else { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + if (!cache2) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + const newValue = fn(a1, a2, a3); + cache2.set(a3, newValue); + return newValue; + }; +} diff --git a/school/node_modules/graphql/jsutils/memoize3.mjs b/school/node_modules/graphql/jsutils/memoize3.mjs new file mode 100644 index 0000000..cfaeb77 --- /dev/null +++ b/school/node_modules/graphql/jsutils/memoize3.mjs @@ -0,0 +1,38 @@ +/** + * Memoizes the provided three-argument function. + */ +export default function memoize3(fn) { + var cache0; + return function memoized(a1, a2, a3) { + if (!cache0) { + cache0 = new WeakMap(); + } + + var cache1 = cache0.get(a1); + var cache2; + + if (cache1) { + cache2 = cache1.get(a2); + + if (cache2) { + var cachedValue = cache2.get(a3); + + if (cachedValue !== undefined) { + return cachedValue; + } + } + } else { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + + if (!cache2) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + + var newValue = fn(a1, a2, a3); + cache2.set(a3, newValue); + return newValue; + }; +} diff --git a/school/node_modules/graphql/jsutils/naturalCompare.js b/school/node_modules/graphql/jsutils/naturalCompare.js new file mode 100644 index 0000000..bd8ef34 --- /dev/null +++ b/school/node_modules/graphql/jsutils/naturalCompare.js @@ -0,0 +1,69 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = naturalCompare; + +/** + * Returns a number indicating whether a reference string comes before, or after, + * or is the same as the given string in natural sort order. + * + * See: https://en.wikipedia.org/wiki/Natural_sort_order + * + */ +function naturalCompare(aStr, bStr) { + var aIdx = 0; + var bIdx = 0; + + while (aIdx < aStr.length && bIdx < bStr.length) { + var aChar = aStr.charCodeAt(aIdx); + var bChar = bStr.charCodeAt(bIdx); + + if (isDigit(aChar) && isDigit(bChar)) { + var aNum = 0; + + do { + ++aIdx; + aNum = aNum * 10 + aChar - DIGIT_0; + aChar = aStr.charCodeAt(aIdx); + } while (isDigit(aChar) && aNum > 0); + + var bNum = 0; + + do { + ++bIdx; + bNum = bNum * 10 + bChar - DIGIT_0; + bChar = bStr.charCodeAt(bIdx); + } while (isDigit(bChar) && bNum > 0); + + if (aNum < bNum) { + return -1; + } + + if (aNum > bNum) { + return 1; + } + } else { + if (aChar < bChar) { + return -1; + } + + if (aChar > bChar) { + return 1; + } + + ++aIdx; + ++bIdx; + } + } + + return aStr.length - bStr.length; +} + +var DIGIT_0 = 48; +var DIGIT_9 = 57; + +function isDigit(code) { + return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; +} diff --git a/school/node_modules/graphql/jsutils/naturalCompare.js.flow b/school/node_modules/graphql/jsutils/naturalCompare.js.flow new file mode 100644 index 0000000..556e613 --- /dev/null +++ b/school/node_modules/graphql/jsutils/naturalCompare.js.flow @@ -0,0 +1,59 @@ +// @flow strict +/** + * Returns a number indicating whether a reference string comes before, or after, + * or is the same as the given string in natural sort order. + * + * See: https://en.wikipedia.org/wiki/Natural_sort_order + * + */ +export default function naturalCompare(aStr: string, bStr: string): number { + let aIdx = 0; + let bIdx = 0; + + while (aIdx < aStr.length && bIdx < bStr.length) { + let aChar = aStr.charCodeAt(aIdx); + let bChar = bStr.charCodeAt(bIdx); + + if (isDigit(aChar) && isDigit(bChar)) { + let aNum = 0; + do { + ++aIdx; + aNum = aNum * 10 + aChar - DIGIT_0; + aChar = aStr.charCodeAt(aIdx); + } while (isDigit(aChar) && aNum > 0); + + let bNum = 0; + do { + ++bIdx; + bNum = bNum * 10 + bChar - DIGIT_0; + bChar = bStr.charCodeAt(bIdx); + } while (isDigit(bChar) && bNum > 0); + + if (aNum < bNum) { + return -1; + } + + if (aNum > bNum) { + return 1; + } + } else { + if (aChar < bChar) { + return -1; + } + if (aChar > bChar) { + return 1; + } + ++aIdx; + ++bIdx; + } + } + + return aStr.length - bStr.length; +} + +const DIGIT_0 = 48; +const DIGIT_9 = 57; + +function isDigit(code: number): boolean { + return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; +} diff --git a/school/node_modules/graphql/jsutils/naturalCompare.mjs b/school/node_modules/graphql/jsutils/naturalCompare.mjs new file mode 100644 index 0000000..4313627 --- /dev/null +++ b/school/node_modules/graphql/jsutils/naturalCompare.mjs @@ -0,0 +1,61 @@ +/** + * Returns a number indicating whether a reference string comes before, or after, + * or is the same as the given string in natural sort order. + * + * See: https://en.wikipedia.org/wiki/Natural_sort_order + * + */ +export default function naturalCompare(aStr, bStr) { + var aIdx = 0; + var bIdx = 0; + + while (aIdx < aStr.length && bIdx < bStr.length) { + var aChar = aStr.charCodeAt(aIdx); + var bChar = bStr.charCodeAt(bIdx); + + if (isDigit(aChar) && isDigit(bChar)) { + var aNum = 0; + + do { + ++aIdx; + aNum = aNum * 10 + aChar - DIGIT_0; + aChar = aStr.charCodeAt(aIdx); + } while (isDigit(aChar) && aNum > 0); + + var bNum = 0; + + do { + ++bIdx; + bNum = bNum * 10 + bChar - DIGIT_0; + bChar = bStr.charCodeAt(bIdx); + } while (isDigit(bChar) && bNum > 0); + + if (aNum < bNum) { + return -1; + } + + if (aNum > bNum) { + return 1; + } + } else { + if (aChar < bChar) { + return -1; + } + + if (aChar > bChar) { + return 1; + } + + ++aIdx; + ++bIdx; + } + } + + return aStr.length - bStr.length; +} +var DIGIT_0 = 48; +var DIGIT_9 = 57; + +function isDigit(code) { + return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; +} diff --git a/school/node_modules/graphql/jsutils/nodejsCustomInspectSymbol.js b/school/node_modules/graphql/jsutils/nodejsCustomInspectSymbol.js new file mode 100644 index 0000000..3a12833 --- /dev/null +++ b/school/node_modules/graphql/jsutils/nodejsCustomInspectSymbol.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') +var nodejsCustomInspectSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined; +var _default = nodejsCustomInspectSymbol; +exports.default = _default; diff --git a/school/node_modules/graphql/jsutils/nodejsCustomInspectSymbol.js.flow b/school/node_modules/graphql/jsutils/nodejsCustomInspectSymbol.js.flow new file mode 100644 index 0000000..114489c --- /dev/null +++ b/school/node_modules/graphql/jsutils/nodejsCustomInspectSymbol.js.flow @@ -0,0 +1,8 @@ +// @flow strict +// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') +const nodejsCustomInspectSymbol = + typeof Symbol === 'function' && typeof Symbol.for === 'function' + ? Symbol.for('nodejs.util.inspect.custom') + : undefined; + +export default nodejsCustomInspectSymbol; diff --git a/school/node_modules/graphql/jsutils/nodejsCustomInspectSymbol.mjs b/school/node_modules/graphql/jsutils/nodejsCustomInspectSymbol.mjs new file mode 100644 index 0000000..afaf3e6 --- /dev/null +++ b/school/node_modules/graphql/jsutils/nodejsCustomInspectSymbol.mjs @@ -0,0 +1,3 @@ +// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') +var nodejsCustomInspectSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined; +export default nodejsCustomInspectSymbol; diff --git a/school/node_modules/graphql/jsutils/printPathArray.js b/school/node_modules/graphql/jsutils/printPathArray.js new file mode 100644 index 0000000..31224eb --- /dev/null +++ b/school/node_modules/graphql/jsutils/printPathArray.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = printPathArray; + +/** + * Build a string describing the path. + */ +function printPathArray(path) { + return path.map(function (key) { + return typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key; + }).join(''); +} diff --git a/school/node_modules/graphql/jsutils/printPathArray.js.flow b/school/node_modules/graphql/jsutils/printPathArray.js.flow new file mode 100644 index 0000000..552a415 --- /dev/null +++ b/school/node_modules/graphql/jsutils/printPathArray.js.flow @@ -0,0 +1,13 @@ +// @flow strict +/** + * Build a string describing the path. + */ +export default function printPathArray( + path: $ReadOnlyArray<string | number>, +): string { + return path + .map((key) => + typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key, + ) + .join(''); +} diff --git a/school/node_modules/graphql/jsutils/printPathArray.mjs b/school/node_modules/graphql/jsutils/printPathArray.mjs new file mode 100644 index 0000000..6bf077a --- /dev/null +++ b/school/node_modules/graphql/jsutils/printPathArray.mjs @@ -0,0 +1,8 @@ +/** + * Build a string describing the path. + */ +export default function printPathArray(path) { + return path.map(function (key) { + return typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key; + }).join(''); +} diff --git a/school/node_modules/graphql/jsutils/promiseForObject.js b/school/node_modules/graphql/jsutils/promiseForObject.js new file mode 100644 index 0000000..f291f9b --- /dev/null +++ b/school/node_modules/graphql/jsutils/promiseForObject.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = promiseForObject; + +/** + * This function transforms a JS object `ObjMap<Promise<T>>` into + * a `Promise<ObjMap<T>>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ +function promiseForObject(object) { + var keys = Object.keys(object); + var valuesAndPromises = keys.map(function (name) { + return object[name]; + }); + return Promise.all(valuesAndPromises).then(function (values) { + return values.reduce(function (resolvedObject, value, i) { + resolvedObject[keys[i]] = value; + return resolvedObject; + }, Object.create(null)); + }); +} diff --git a/school/node_modules/graphql/jsutils/promiseForObject.js.flow b/school/node_modules/graphql/jsutils/promiseForObject.js.flow new file mode 100644 index 0000000..5c2c65b --- /dev/null +++ b/school/node_modules/graphql/jsutils/promiseForObject.js.flow @@ -0,0 +1,22 @@ +// @flow strict +import type { ObjMap } from './ObjMap'; + +/** + * This function transforms a JS object `ObjMap<Promise<T>>` into + * a `Promise<ObjMap<T>>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ +export default function promiseForObject<T>( + object: ObjMap<Promise<T>>, +): Promise<ObjMap<T>> { + const keys = Object.keys(object); + const valuesAndPromises = keys.map((name) => object[name]); + return Promise.all(valuesAndPromises).then((values) => + values.reduce((resolvedObject, value, i) => { + resolvedObject[keys[i]] = value; + return resolvedObject; + }, Object.create(null)), + ); +} diff --git a/school/node_modules/graphql/jsutils/promiseForObject.mjs b/school/node_modules/graphql/jsutils/promiseForObject.mjs new file mode 100644 index 0000000..ee36ed4 --- /dev/null +++ b/school/node_modules/graphql/jsutils/promiseForObject.mjs @@ -0,0 +1,19 @@ +/** + * This function transforms a JS object `ObjMap<Promise<T>>` into + * a `Promise<ObjMap<T>>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ +export default function promiseForObject(object) { + var keys = Object.keys(object); + var valuesAndPromises = keys.map(function (name) { + return object[name]; + }); + return Promise.all(valuesAndPromises).then(function (values) { + return values.reduce(function (resolvedObject, value, i) { + resolvedObject[keys[i]] = value; + return resolvedObject; + }, Object.create(null)); + }); +} diff --git a/school/node_modules/graphql/jsutils/promiseReduce.js b/school/node_modules/graphql/jsutils/promiseReduce.js new file mode 100644 index 0000000..6606926 --- /dev/null +++ b/school/node_modules/graphql/jsutils/promiseReduce.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = promiseReduce; + +var _isPromise = _interopRequireDefault(require("./isPromise.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ +function promiseReduce(values, callback, initialValue) { + return values.reduce(function (previous, value) { + return (0, _isPromise.default)(previous) ? previous.then(function (resolved) { + return callback(resolved, value); + }) : callback(previous, value); + }, initialValue); +} diff --git a/school/node_modules/graphql/jsutils/promiseReduce.js.flow b/school/node_modules/graphql/jsutils/promiseReduce.js.flow new file mode 100644 index 0000000..ea333bc --- /dev/null +++ b/school/node_modules/graphql/jsutils/promiseReduce.js.flow @@ -0,0 +1,25 @@ +// @flow strict +import type { PromiseOrValue } from './PromiseOrValue'; + +import isPromise from './isPromise'; + +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ +export default function promiseReduce<T, U>( + values: $ReadOnlyArray<T>, + callback: (U, T) => PromiseOrValue<U>, + initialValue: PromiseOrValue<U>, +): PromiseOrValue<U> { + return values.reduce( + (previous, value) => + isPromise(previous) + ? previous.then((resolved) => callback(resolved, value)) + : callback(previous, value), + initialValue, + ); +} diff --git a/school/node_modules/graphql/jsutils/promiseReduce.mjs b/school/node_modules/graphql/jsutils/promiseReduce.mjs new file mode 100644 index 0000000..db99d5d --- /dev/null +++ b/school/node_modules/graphql/jsutils/promiseReduce.mjs @@ -0,0 +1,16 @@ +import isPromise from "./isPromise.mjs"; +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ + +export default function promiseReduce(values, callback, initialValue) { + return values.reduce(function (previous, value) { + return isPromise(previous) ? previous.then(function (resolved) { + return callback(resolved, value); + }) : callback(previous, value); + }, initialValue); +} diff --git a/school/node_modules/graphql/jsutils/safeArrayFrom.js b/school/node_modules/graphql/jsutils/safeArrayFrom.js new file mode 100644 index 0000000..3c80dee --- /dev/null +++ b/school/node_modules/graphql/jsutils/safeArrayFrom.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = safeArrayFrom; + +var _symbols = require("../polyfills/symbols.js"); + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Safer version of `Array.from` that return `null` if value isn't convertible to array. + * Also protects against Array-like objects without items. + * + * @example + * + * safeArrayFrom([ 1, 2, 3 ]) // [1, 2, 3] + * safeArrayFrom('ABC') // null + * safeArrayFrom({ length: 1 }) // null + * safeArrayFrom({ length: 1, 0: 'Alpha' }) // ['Alpha'] + * safeArrayFrom({ key: 'value' }) // null + * safeArrayFrom(new Map()) // [] + * + */ +function safeArrayFrom(collection) { + var mapFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (item) { + return item; + }; + + if (collection == null || _typeof(collection) !== 'object') { + return null; + } + + if (Array.isArray(collection)) { + return collection.map(mapFn); + } // Is Iterable? + + + var iteratorMethod = collection[_symbols.SYMBOL_ITERATOR]; + + if (typeof iteratorMethod === 'function') { + // $FlowFixMe[incompatible-use] + var iterator = iteratorMethod.call(collection); + var result = []; + var step; + + for (var i = 0; !(step = iterator.next()).done; ++i) { + result.push(mapFn(step.value, i)); + } + + return result; + } // Is Array like? + + + var length = collection.length; + + if (typeof length === 'number' && length >= 0 && length % 1 === 0) { + var _result = []; + + for (var _i = 0; _i < length; ++_i) { + if (!Object.prototype.hasOwnProperty.call(collection, _i)) { + return null; + } + + _result.push(mapFn(collection[String(_i)], _i)); + } + + return _result; + } + + return null; +} diff --git a/school/node_modules/graphql/jsutils/safeArrayFrom.js.flow b/school/node_modules/graphql/jsutils/safeArrayFrom.js.flow new file mode 100644 index 0000000..db2bdea --- /dev/null +++ b/school/node_modules/graphql/jsutils/safeArrayFrom.js.flow @@ -0,0 +1,59 @@ +// @flow strict +import { SYMBOL_ITERATOR } from '../polyfills/symbols'; + +/** + * Safer version of `Array.from` that return `null` if value isn't convertible to array. + * Also protects against Array-like objects without items. + * + * @example + * + * safeArrayFrom([ 1, 2, 3 ]) // [1, 2, 3] + * safeArrayFrom('ABC') // null + * safeArrayFrom({ length: 1 }) // null + * safeArrayFrom({ length: 1, 0: 'Alpha' }) // ['Alpha'] + * safeArrayFrom({ key: 'value' }) // null + * safeArrayFrom(new Map()) // [] + * + */ +export default function safeArrayFrom<T>( + collection: mixed, + mapFn: (elem: mixed, index: number) => T = (item) => ((item: any): T), +): Array<T> | null { + if (collection == null || typeof collection !== 'object') { + return null; + } + + if (Array.isArray(collection)) { + return collection.map(mapFn); + } + + // Is Iterable? + const iteratorMethod = collection[SYMBOL_ITERATOR]; + if (typeof iteratorMethod === 'function') { + // $FlowFixMe[incompatible-use] + const iterator = iteratorMethod.call(collection); + const result = []; + let step; + + for (let i = 0; !(step = iterator.next()).done; ++i) { + result.push(mapFn(step.value, i)); + } + return result; + } + + // Is Array like? + const length = collection.length; + if (typeof length === 'number' && length >= 0 && length % 1 === 0) { + const result = []; + for (let i = 0; i < length; ++i) { + if (!Object.prototype.hasOwnProperty.call(collection, i)) { + return null; + } + result.push(mapFn(collection[String(i)], i)); + } + + return result; + } + + return null; +} diff --git a/school/node_modules/graphql/jsutils/safeArrayFrom.mjs b/school/node_modules/graphql/jsutils/safeArrayFrom.mjs new file mode 100644 index 0000000..f8b357d --- /dev/null +++ b/school/node_modules/graphql/jsutils/safeArrayFrom.mjs @@ -0,0 +1,66 @@ +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +import { SYMBOL_ITERATOR } from "../polyfills/symbols.mjs"; +/** + * Safer version of `Array.from` that return `null` if value isn't convertible to array. + * Also protects against Array-like objects without items. + * + * @example + * + * safeArrayFrom([ 1, 2, 3 ]) // [1, 2, 3] + * safeArrayFrom('ABC') // null + * safeArrayFrom({ length: 1 }) // null + * safeArrayFrom({ length: 1, 0: 'Alpha' }) // ['Alpha'] + * safeArrayFrom({ key: 'value' }) // null + * safeArrayFrom(new Map()) // [] + * + */ + +export default function safeArrayFrom(collection) { + var mapFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (item) { + return item; + }; + + if (collection == null || _typeof(collection) !== 'object') { + return null; + } + + if (Array.isArray(collection)) { + return collection.map(mapFn); + } // Is Iterable? + + + var iteratorMethod = collection[SYMBOL_ITERATOR]; + + if (typeof iteratorMethod === 'function') { + // $FlowFixMe[incompatible-use] + var iterator = iteratorMethod.call(collection); + var result = []; + var step; + + for (var i = 0; !(step = iterator.next()).done; ++i) { + result.push(mapFn(step.value, i)); + } + + return result; + } // Is Array like? + + + var length = collection.length; + + if (typeof length === 'number' && length >= 0 && length % 1 === 0) { + var _result = []; + + for (var _i = 0; _i < length; ++_i) { + if (!Object.prototype.hasOwnProperty.call(collection, _i)) { + return null; + } + + _result.push(mapFn(collection[String(_i)], _i)); + } + + return _result; + } + + return null; +} diff --git a/school/node_modules/graphql/jsutils/suggestionList.js b/school/node_modules/graphql/jsutils/suggestionList.js new file mode 100644 index 0000000..6d38ff6 --- /dev/null +++ b/school/node_modules/graphql/jsutils/suggestionList.js @@ -0,0 +1,141 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = suggestionList; + +var _naturalCompare = _interopRequireDefault(require("./naturalCompare.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ +function suggestionList(input, options) { + var optionsByDistance = Object.create(null); + var lexicalDistance = new LexicalDistance(input); + var threshold = Math.floor(input.length * 0.4) + 1; + + for (var _i2 = 0; _i2 < options.length; _i2++) { + var option = options[_i2]; + var distance = lexicalDistance.measure(option, threshold); + + if (distance !== undefined) { + optionsByDistance[option] = distance; + } + } + + return Object.keys(optionsByDistance).sort(function (a, b) { + var distanceDiff = optionsByDistance[a] - optionsByDistance[b]; + return distanceDiff !== 0 ? distanceDiff : (0, _naturalCompare.default)(a, b); + }); +} +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + */ + + +var LexicalDistance = /*#__PURE__*/function () { + function LexicalDistance(input) { + this._input = input; + this._inputLowerCase = input.toLowerCase(); + this._inputArray = stringToArray(this._inputLowerCase); + this._rows = [new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0)]; + } + + var _proto = LexicalDistance.prototype; + + _proto.measure = function measure(option, threshold) { + if (this._input === option) { + return 0; + } + + var optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit + + if (this._inputLowerCase === optionLowerCase) { + return 1; + } + + var a = stringToArray(optionLowerCase); + var b = this._inputArray; + + if (a.length < b.length) { + var tmp = a; + a = b; + b = tmp; + } + + var aLength = a.length; + var bLength = b.length; + + if (aLength - bLength > threshold) { + return undefined; + } + + var rows = this._rows; + + for (var j = 0; j <= bLength; j++) { + rows[0][j] = j; + } + + for (var i = 1; i <= aLength; i++) { + var upRow = rows[(i - 1) % 3]; + var currentRow = rows[i % 3]; + var smallestCell = currentRow[0] = i; + + for (var _j = 1; _j <= bLength; _j++) { + var cost = a[i - 1] === b[_j - 1] ? 0 : 1; + var currentCell = Math.min(upRow[_j] + 1, // delete + currentRow[_j - 1] + 1, // insert + upRow[_j - 1] + cost // substitute + ); + + if (i > 1 && _j > 1 && a[i - 1] === b[_j - 2] && a[i - 2] === b[_j - 1]) { + // transposition + var doubleDiagonalCell = rows[(i - 2) % 3][_j - 2]; + currentCell = Math.min(currentCell, doubleDiagonalCell + 1); + } + + if (currentCell < smallestCell) { + smallestCell = currentCell; + } + + currentRow[_j] = currentCell; + } // Early exit, since distance can't go smaller than smallest element of the previous row. + + + if (smallestCell > threshold) { + return undefined; + } + } + + var distance = rows[aLength % 3][bLength]; + return distance <= threshold ? distance : undefined; + }; + + return LexicalDistance; +}(); + +function stringToArray(str) { + var strLength = str.length; + var array = new Array(strLength); + + for (var i = 0; i < strLength; ++i) { + array[i] = str.charCodeAt(i); + } + + return array; +} diff --git a/school/node_modules/graphql/jsutils/suggestionList.js.flow b/school/node_modules/graphql/jsutils/suggestionList.js.flow new file mode 100644 index 0000000..017e779 --- /dev/null +++ b/school/node_modules/graphql/jsutils/suggestionList.js.flow @@ -0,0 +1,138 @@ +// @flow strict +import naturalCompare from './naturalCompare'; + +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ +export default function suggestionList( + input: string, + options: $ReadOnlyArray<string>, +): Array<string> { + const optionsByDistance = Object.create(null); + const lexicalDistance = new LexicalDistance(input); + + const threshold = Math.floor(input.length * 0.4) + 1; + for (const option of options) { + const distance = lexicalDistance.measure(option, threshold); + if (distance !== undefined) { + optionsByDistance[option] = distance; + } + } + + return Object.keys(optionsByDistance).sort((a, b) => { + const distanceDiff = optionsByDistance[a] - optionsByDistance[b]; + return distanceDiff !== 0 ? distanceDiff : naturalCompare(a, b); + }); +} + +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + */ +class LexicalDistance { + _input: string; + _inputLowerCase: string; + _inputArray: Array<number>; + _rows: [Array<number>, Array<number>, Array<number>]; + + constructor(input: string) { + this._input = input; + this._inputLowerCase = input.toLowerCase(); + this._inputArray = stringToArray(this._inputLowerCase); + + this._rows = [ + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0), + ]; + } + + measure(option: string, threshold: number): number | void { + if (this._input === option) { + return 0; + } + + const optionLowerCase = option.toLowerCase(); + + // Any case change counts as a single edit + if (this._inputLowerCase === optionLowerCase) { + return 1; + } + + let a = stringToArray(optionLowerCase); + let b = this._inputArray; + + if (a.length < b.length) { + const tmp = a; + a = b; + b = tmp; + } + const aLength = a.length; + const bLength = b.length; + + if (aLength - bLength > threshold) { + return undefined; + } + + const rows = this._rows; + for (let j = 0; j <= bLength; j++) { + rows[0][j] = j; + } + + for (let i = 1; i <= aLength; i++) { + const upRow = rows[(i - 1) % 3]; + const currentRow = rows[i % 3]; + + let smallestCell = (currentRow[0] = i); + for (let j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + + let currentCell = Math.min( + upRow[j] + 1, // delete + currentRow[j - 1] + 1, // insert + upRow[j - 1] + cost, // substitute + ); + + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + // transposition + const doubleDiagonalCell = rows[(i - 2) % 3][j - 2]; + currentCell = Math.min(currentCell, doubleDiagonalCell + 1); + } + + if (currentCell < smallestCell) { + smallestCell = currentCell; + } + + currentRow[j] = currentCell; + } + + // Early exit, since distance can't go smaller than smallest element of the previous row. + if (smallestCell > threshold) { + return undefined; + } + } + + const distance = rows[aLength % 3][bLength]; + return distance <= threshold ? distance : undefined; + } +} + +function stringToArray(str: string): Array<number> { + const strLength = str.length; + const array = new Array(strLength); + for (let i = 0; i < strLength; ++i) { + array[i] = str.charCodeAt(i); + } + return array; +} diff --git a/school/node_modules/graphql/jsutils/suggestionList.mjs b/school/node_modules/graphql/jsutils/suggestionList.mjs new file mode 100644 index 0000000..154560a --- /dev/null +++ b/school/node_modules/graphql/jsutils/suggestionList.mjs @@ -0,0 +1,131 @@ +import naturalCompare from "./naturalCompare.mjs"; +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ + +export default function suggestionList(input, options) { + var optionsByDistance = Object.create(null); + var lexicalDistance = new LexicalDistance(input); + var threshold = Math.floor(input.length * 0.4) + 1; + + for (var _i2 = 0; _i2 < options.length; _i2++) { + var option = options[_i2]; + var distance = lexicalDistance.measure(option, threshold); + + if (distance !== undefined) { + optionsByDistance[option] = distance; + } + } + + return Object.keys(optionsByDistance).sort(function (a, b) { + var distanceDiff = optionsByDistance[a] - optionsByDistance[b]; + return distanceDiff !== 0 ? distanceDiff : naturalCompare(a, b); + }); +} +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + */ + +var LexicalDistance = /*#__PURE__*/function () { + function LexicalDistance(input) { + this._input = input; + this._inputLowerCase = input.toLowerCase(); + this._inputArray = stringToArray(this._inputLowerCase); + this._rows = [new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0)]; + } + + var _proto = LexicalDistance.prototype; + + _proto.measure = function measure(option, threshold) { + if (this._input === option) { + return 0; + } + + var optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit + + if (this._inputLowerCase === optionLowerCase) { + return 1; + } + + var a = stringToArray(optionLowerCase); + var b = this._inputArray; + + if (a.length < b.length) { + var tmp = a; + a = b; + b = tmp; + } + + var aLength = a.length; + var bLength = b.length; + + if (aLength - bLength > threshold) { + return undefined; + } + + var rows = this._rows; + + for (var j = 0; j <= bLength; j++) { + rows[0][j] = j; + } + + for (var i = 1; i <= aLength; i++) { + var upRow = rows[(i - 1) % 3]; + var currentRow = rows[i % 3]; + var smallestCell = currentRow[0] = i; + + for (var _j = 1; _j <= bLength; _j++) { + var cost = a[i - 1] === b[_j - 1] ? 0 : 1; + var currentCell = Math.min(upRow[_j] + 1, // delete + currentRow[_j - 1] + 1, // insert + upRow[_j - 1] + cost // substitute + ); + + if (i > 1 && _j > 1 && a[i - 1] === b[_j - 2] && a[i - 2] === b[_j - 1]) { + // transposition + var doubleDiagonalCell = rows[(i - 2) % 3][_j - 2]; + currentCell = Math.min(currentCell, doubleDiagonalCell + 1); + } + + if (currentCell < smallestCell) { + smallestCell = currentCell; + } + + currentRow[_j] = currentCell; + } // Early exit, since distance can't go smaller than smallest element of the previous row. + + + if (smallestCell > threshold) { + return undefined; + } + } + + var distance = rows[aLength % 3][bLength]; + return distance <= threshold ? distance : undefined; + }; + + return LexicalDistance; +}(); + +function stringToArray(str) { + var strLength = str.length; + var array = new Array(strLength); + + for (var i = 0; i < strLength; ++i) { + array[i] = str.charCodeAt(i); + } + + return array; +} diff --git a/school/node_modules/graphql/jsutils/toObjMap.js b/school/node_modules/graphql/jsutils/toObjMap.js new file mode 100644 index 0000000..1768d74 --- /dev/null +++ b/school/node_modules/graphql/jsutils/toObjMap.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = toObjMap; + +var _objectEntries3 = _interopRequireDefault(require("../polyfills/objectEntries.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function toObjMap(obj) { + /* eslint-enable no-redeclare */ + if (Object.getPrototypeOf(obj) === null) { + return obj; + } + + var map = Object.create(null); + + for (var _i2 = 0, _objectEntries2 = (0, _objectEntries3.default)(obj); _i2 < _objectEntries2.length; _i2++) { + var _ref2 = _objectEntries2[_i2]; + var key = _ref2[0]; + var value = _ref2[1]; + map[key] = value; + } + + return map; +} diff --git a/school/node_modules/graphql/jsutils/toObjMap.js.flow b/school/node_modules/graphql/jsutils/toObjMap.js.flow new file mode 100644 index 0000000..81c1113 --- /dev/null +++ b/school/node_modules/graphql/jsutils/toObjMap.js.flow @@ -0,0 +1,26 @@ +// @flow strict +import objectEntries from '../polyfills/objectEntries'; + +import type { + ObjMap, + ObjMapLike, + ReadOnlyObjMap, + ReadOnlyObjMapLike, +} from './ObjMap'; + +/* eslint-disable no-redeclare */ +declare function toObjMap<T>(obj: ObjMapLike<T>): ObjMap<T>; +declare function toObjMap<T>(obj: ReadOnlyObjMapLike<T>): ReadOnlyObjMap<T>; + +export default function toObjMap(obj) { + /* eslint-enable no-redeclare */ + if (Object.getPrototypeOf(obj) === null) { + return obj; + } + + const map = Object.create(null); + for (const [key, value] of objectEntries(obj)) { + map[key] = value; + } + return map; +} diff --git a/school/node_modules/graphql/jsutils/toObjMap.mjs b/school/node_modules/graphql/jsutils/toObjMap.mjs new file mode 100644 index 0000000..b0ddf05 --- /dev/null +++ b/school/node_modules/graphql/jsutils/toObjMap.mjs @@ -0,0 +1,18 @@ +import objectEntries from "../polyfills/objectEntries.mjs"; +export default function toObjMap(obj) { + /* eslint-enable no-redeclare */ + if (Object.getPrototypeOf(obj) === null) { + return obj; + } + + var map = Object.create(null); + + for (var _i2 = 0, _objectEntries2 = objectEntries(obj); _i2 < _objectEntries2.length; _i2++) { + var _ref2 = _objectEntries2[_i2]; + var key = _ref2[0]; + var value = _ref2[1]; + map[key] = value; + } + + return map; +} diff --git a/school/node_modules/graphql/language/ast.d.ts b/school/node_modules/graphql/language/ast.d.ts new file mode 100644 index 0000000..61cb9f4 --- /dev/null +++ b/school/node_modules/graphql/language/ast.d.ts @@ -0,0 +1,602 @@ +import { Source } from './source'; +import { TokenKindEnum } from './tokenKind'; + +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +export class Location { + /** + * The character offset at which this Node begins. + */ + readonly start: number; + + /** + * The character offset at which this Node ends. + */ + readonly end: number; + + /** + * The Token at which this Node begins. + */ + readonly startToken: Token; + + /** + * The Token at which this Node ends. + */ + readonly endToken: Token; + + /** + * The Source document the AST represents. + */ + readonly source: Source; + + constructor(startToken: Token, endToken: Token, source: Source); + + toJSON(): { start: number; end: number }; +} + +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ +export class Token { + /** + * The kind of Token. + */ + readonly kind: TokenKindEnum; + + /** + * The character offset at which this Node begins. + */ + readonly start: number; + + /** + * The character offset at which this Node ends. + */ + readonly end: number; + + /** + * The 1-indexed line number on which this Token appears. + */ + readonly line: number; + + /** + * The 1-indexed column number at which this Token begins. + */ + readonly column: number; + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + */ + readonly value: string | undefined; + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. <SOF> is always the first node and <EOF> + * the last. + */ + readonly prev: Token | null; + readonly next: Token | null; + + constructor( + kind: TokenKindEnum, + start: number, + end: number, + line: number, + column: number, + prev: Token | null, + value?: string, + ); + + toJSON(): { + kind: TokenKindEnum; + value: string | undefined; + line: number; + column: number; + }; +} + +/** + * @internal + */ +export function isNode(maybeNode: any): maybeNode is ASTNode; + +/** + * The list of all possible AST node types. + */ +export type ASTNode = + | NameNode + | DocumentNode + | OperationDefinitionNode + | VariableDefinitionNode + | VariableNode + | SelectionSetNode + | FieldNode + | ArgumentNode + | FragmentSpreadNode + | InlineFragmentNode + | FragmentDefinitionNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode + | ObjectFieldNode + | DirectiveNode + | NamedTypeNode + | ListTypeNode + | NonNullTypeNode + | SchemaDefinitionNode + | OperationTypeDefinitionNode + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | FieldDefinitionNode + | InputValueDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | EnumValueDefinitionNode + | InputObjectTypeDefinitionNode + | DirectiveDefinitionNode + | SchemaExtensionNode + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode; + +/** + * Utility type listing all nodes indexed by their kind. + */ +export interface ASTKindToNode { + Name: NameNode; + Document: DocumentNode; + OperationDefinition: OperationDefinitionNode; + VariableDefinition: VariableDefinitionNode; + Variable: VariableNode; + SelectionSet: SelectionSetNode; + Field: FieldNode; + Argument: ArgumentNode; + FragmentSpread: FragmentSpreadNode; + InlineFragment: InlineFragmentNode; + FragmentDefinition: FragmentDefinitionNode; + IntValue: IntValueNode; + FloatValue: FloatValueNode; + StringValue: StringValueNode; + BooleanValue: BooleanValueNode; + NullValue: NullValueNode; + EnumValue: EnumValueNode; + ListValue: ListValueNode; + ObjectValue: ObjectValueNode; + ObjectField: ObjectFieldNode; + Directive: DirectiveNode; + NamedType: NamedTypeNode; + ListType: ListTypeNode; + NonNullType: NonNullTypeNode; + SchemaDefinition: SchemaDefinitionNode; + OperationTypeDefinition: OperationTypeDefinitionNode; + ScalarTypeDefinition: ScalarTypeDefinitionNode; + ObjectTypeDefinition: ObjectTypeDefinitionNode; + FieldDefinition: FieldDefinitionNode; + InputValueDefinition: InputValueDefinitionNode; + InterfaceTypeDefinition: InterfaceTypeDefinitionNode; + UnionTypeDefinition: UnionTypeDefinitionNode; + EnumTypeDefinition: EnumTypeDefinitionNode; + EnumValueDefinition: EnumValueDefinitionNode; + InputObjectTypeDefinition: InputObjectTypeDefinitionNode; + DirectiveDefinition: DirectiveDefinitionNode; + SchemaExtension: SchemaExtensionNode; + ScalarTypeExtension: ScalarTypeExtensionNode; + ObjectTypeExtension: ObjectTypeExtensionNode; + InterfaceTypeExtension: InterfaceTypeExtensionNode; + UnionTypeExtension: UnionTypeExtensionNode; + EnumTypeExtension: EnumTypeExtensionNode; + InputObjectTypeExtension: InputObjectTypeExtensionNode; +} + +// Name + +export interface NameNode { + readonly kind: 'Name'; + readonly loc?: Location; + readonly value: string; +} + +// Document + +export interface DocumentNode { + readonly kind: 'Document'; + readonly loc?: Location; + readonly definitions: ReadonlyArray<DefinitionNode>; +} + +export type DefinitionNode = + | ExecutableDefinitionNode + | TypeSystemDefinitionNode + | TypeSystemExtensionNode; + +export type ExecutableDefinitionNode = + | OperationDefinitionNode + | FragmentDefinitionNode; + +export interface OperationDefinitionNode { + readonly kind: 'OperationDefinition'; + readonly loc?: Location; + readonly operation: OperationTypeNode; + readonly name?: NameNode; + readonly variableDefinitions?: ReadonlyArray<VariableDefinitionNode>; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly selectionSet: SelectionSetNode; +} + +export type OperationTypeNode = 'query' | 'mutation' | 'subscription'; + +export interface VariableDefinitionNode { + readonly kind: 'VariableDefinition'; + readonly loc?: Location; + readonly variable: VariableNode; + readonly type: TypeNode; + readonly defaultValue?: ValueNode; + readonly directives?: ReadonlyArray<DirectiveNode>; +} + +export interface VariableNode { + readonly kind: 'Variable'; + readonly loc?: Location; + readonly name: NameNode; +} + +export interface SelectionSetNode { + kind: 'SelectionSet'; + loc?: Location; + selections: ReadonlyArray<SelectionNode>; +} + +export type SelectionNode = FieldNode | FragmentSpreadNode | InlineFragmentNode; + +export interface FieldNode { + readonly kind: 'Field'; + readonly loc?: Location; + readonly alias?: NameNode; + readonly name: NameNode; + readonly arguments?: ReadonlyArray<ArgumentNode>; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly selectionSet?: SelectionSetNode; +} + +export interface ArgumentNode { + readonly kind: 'Argument'; + readonly loc?: Location; + readonly name: NameNode; + readonly value: ValueNode; +} + +// Fragments + +export interface FragmentSpreadNode { + readonly kind: 'FragmentSpread'; + readonly loc?: Location; + readonly name: NameNode; + readonly directives?: ReadonlyArray<DirectiveNode>; +} + +export interface InlineFragmentNode { + readonly kind: 'InlineFragment'; + readonly loc?: Location; + readonly typeCondition?: NamedTypeNode; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly selectionSet: SelectionSetNode; +} + +export interface FragmentDefinitionNode { + readonly kind: 'FragmentDefinition'; + readonly loc?: Location; + readonly name: NameNode; + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + readonly variableDefinitions?: ReadonlyArray<VariableDefinitionNode>; + readonly typeCondition: NamedTypeNode; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly selectionSet: SelectionSetNode; +} + +// Values + +export type ValueNode = + | VariableNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode; + +export interface IntValueNode { + readonly kind: 'IntValue'; + readonly loc?: Location; + readonly value: string; +} + +export interface FloatValueNode { + readonly kind: 'FloatValue'; + readonly loc?: Location; + readonly value: string; +} + +export interface StringValueNode { + readonly kind: 'StringValue'; + readonly loc?: Location; + readonly value: string; + readonly block?: boolean; +} + +export interface BooleanValueNode { + readonly kind: 'BooleanValue'; + readonly loc?: Location; + readonly value: boolean; +} + +export interface NullValueNode { + readonly kind: 'NullValue'; + readonly loc?: Location; +} + +export interface EnumValueNode { + readonly kind: 'EnumValue'; + readonly loc?: Location; + readonly value: string; +} + +export interface ListValueNode { + readonly kind: 'ListValue'; + readonly loc?: Location; + readonly values: ReadonlyArray<ValueNode>; +} + +export interface ObjectValueNode { + readonly kind: 'ObjectValue'; + readonly loc?: Location; + readonly fields: ReadonlyArray<ObjectFieldNode>; +} + +export interface ObjectFieldNode { + readonly kind: 'ObjectField'; + readonly loc?: Location; + readonly name: NameNode; + readonly value: ValueNode; +} + +// Directives + +export interface DirectiveNode { + readonly kind: 'Directive'; + readonly loc?: Location; + readonly name: NameNode; + readonly arguments?: ReadonlyArray<ArgumentNode>; +} + +// Type Reference + +export type TypeNode = NamedTypeNode | ListTypeNode | NonNullTypeNode; + +export interface NamedTypeNode { + readonly kind: 'NamedType'; + readonly loc?: Location; + readonly name: NameNode; +} + +export interface ListTypeNode { + readonly kind: 'ListType'; + readonly loc?: Location; + readonly type: TypeNode; +} + +export interface NonNullTypeNode { + readonly kind: 'NonNullType'; + readonly loc?: Location; + readonly type: NamedTypeNode | ListTypeNode; +} + +// Type System Definition + +export type TypeSystemDefinitionNode = + | SchemaDefinitionNode + | TypeDefinitionNode + | DirectiveDefinitionNode; + +export interface SchemaDefinitionNode { + readonly kind: 'SchemaDefinition'; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly operationTypes: ReadonlyArray<OperationTypeDefinitionNode>; +} + +export interface OperationTypeDefinitionNode { + readonly kind: 'OperationTypeDefinition'; + readonly loc?: Location; + readonly operation: OperationTypeNode; + readonly type: NamedTypeNode; +} + +// Type Definition + +export type TypeDefinitionNode = + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | InputObjectTypeDefinitionNode; + +export interface ScalarTypeDefinitionNode { + readonly kind: 'ScalarTypeDefinition'; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly directives?: ReadonlyArray<DirectiveNode>; +} + +export interface ObjectTypeDefinitionNode { + readonly kind: 'ObjectTypeDefinition'; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly interfaces?: ReadonlyArray<NamedTypeNode>; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly fields?: ReadonlyArray<FieldDefinitionNode>; +} + +export interface FieldDefinitionNode { + readonly kind: 'FieldDefinition'; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly arguments?: ReadonlyArray<InputValueDefinitionNode>; + readonly type: TypeNode; + readonly directives?: ReadonlyArray<DirectiveNode>; +} + +export interface InputValueDefinitionNode { + readonly kind: 'InputValueDefinition'; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly type: TypeNode; + readonly defaultValue?: ValueNode; + readonly directives?: ReadonlyArray<DirectiveNode>; +} + +export interface InterfaceTypeDefinitionNode { + readonly kind: 'InterfaceTypeDefinition'; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly interfaces?: ReadonlyArray<NamedTypeNode>; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly fields?: ReadonlyArray<FieldDefinitionNode>; +} + +export interface UnionTypeDefinitionNode { + readonly kind: 'UnionTypeDefinition'; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly types?: ReadonlyArray<NamedTypeNode>; +} + +export interface EnumTypeDefinitionNode { + readonly kind: 'EnumTypeDefinition'; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly values?: ReadonlyArray<EnumValueDefinitionNode>; +} + +export interface EnumValueDefinitionNode { + readonly kind: 'EnumValueDefinition'; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly directives?: ReadonlyArray<DirectiveNode>; +} + +export interface InputObjectTypeDefinitionNode { + readonly kind: 'InputObjectTypeDefinition'; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly fields?: ReadonlyArray<InputValueDefinitionNode>; +} + +// Directive Definitions + +export interface DirectiveDefinitionNode { + readonly kind: 'DirectiveDefinition'; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly arguments?: ReadonlyArray<InputValueDefinitionNode>; + readonly repeatable: boolean; + readonly locations: ReadonlyArray<NameNode>; +} + +// Type System Extensions + +export type TypeSystemExtensionNode = SchemaExtensionNode | TypeExtensionNode; + +export interface SchemaExtensionNode { + readonly kind: 'SchemaExtension'; + readonly loc?: Location; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly operationTypes?: ReadonlyArray<OperationTypeDefinitionNode>; +} + +// Type Extensions + +export type TypeExtensionNode = + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode; + +export interface ScalarTypeExtensionNode { + readonly kind: 'ScalarTypeExtension'; + readonly loc?: Location; + readonly name: NameNode; + readonly directives?: ReadonlyArray<DirectiveNode>; +} + +export interface ObjectTypeExtensionNode { + readonly kind: 'ObjectTypeExtension'; + readonly loc?: Location; + readonly name: NameNode; + readonly interfaces?: ReadonlyArray<NamedTypeNode>; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly fields?: ReadonlyArray<FieldDefinitionNode>; +} + +export interface InterfaceTypeExtensionNode { + readonly kind: 'InterfaceTypeExtension'; + readonly loc?: Location; + readonly name: NameNode; + readonly interfaces?: ReadonlyArray<NamedTypeNode>; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly fields?: ReadonlyArray<FieldDefinitionNode>; +} + +export interface UnionTypeExtensionNode { + readonly kind: 'UnionTypeExtension'; + readonly loc?: Location; + readonly name: NameNode; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly types?: ReadonlyArray<NamedTypeNode>; +} + +export interface EnumTypeExtensionNode { + readonly kind: 'EnumTypeExtension'; + readonly loc?: Location; + readonly name: NameNode; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly values?: ReadonlyArray<EnumValueDefinitionNode>; +} + +export interface InputObjectTypeExtensionNode { + readonly kind: 'InputObjectTypeExtension'; + readonly loc?: Location; + readonly name: NameNode; + readonly directives?: ReadonlyArray<DirectiveNode>; + readonly fields?: ReadonlyArray<InputValueDefinitionNode>; +} diff --git a/school/node_modules/graphql/language/ast.js b/school/node_modules/graphql/language/ast.js new file mode 100644 index 0000000..3f8eef2 --- /dev/null +++ b/school/node_modules/graphql/language/ast.js @@ -0,0 +1,132 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isNode = isNode; +exports.Token = exports.Location = void 0; + +var _defineInspect = _interopRequireDefault(require("../jsutils/defineInspect.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +var Location = /*#__PURE__*/function () { + /** + * The character offset at which this Node begins. + */ + + /** + * The character offset at which this Node ends. + */ + + /** + * The Token at which this Node begins. + */ + + /** + * The Token at which this Node ends. + */ + + /** + * The Source document the AST represents. + */ + function Location(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; + } + + var _proto = Location.prototype; + + _proto.toJSON = function toJSON() { + return { + start: this.start, + end: this.end + }; + }; + + return Location; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + + +exports.Location = Location; +(0, _defineInspect.default)(Location); +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ + +var Token = /*#__PURE__*/function () { + /** + * The kind of Token. + */ + + /** + * The character offset at which this Node begins. + */ + + /** + * The character offset at which this Node ends. + */ + + /** + * The 1-indexed line number on which this Token appears. + */ + + /** + * The 1-indexed column number at which this Token begins. + */ + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + */ + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. <SOF> is always the first node and <EOF> + * the last. + */ + function Token(kind, start, end, line, column, prev, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; + this.value = value; + this.prev = prev; + this.next = null; + } + + var _proto2 = Token.prototype; + + _proto2.toJSON = function toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column + }; + }; + + return Token; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + + +exports.Token = Token; +(0, _defineInspect.default)(Token); +/** + * @internal + */ + +function isNode(maybeNode) { + return maybeNode != null && typeof maybeNode.kind === 'string'; +} +/** + * The list of all possible AST node types. + */ diff --git a/school/node_modules/graphql/language/ast.js.flow b/school/node_modules/graphql/language/ast.js.flow new file mode 100644 index 0000000..42ea6e3 --- /dev/null +++ b/school/node_modules/graphql/language/ast.js.flow @@ -0,0 +1,637 @@ +// @flow strict +import defineInspect from '../jsutils/defineInspect'; + +import type { Source } from './source'; +import type { TokenKindEnum } from './tokenKind'; + +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +export class Location { + /** + * The character offset at which this Node begins. + */ + +start: number; + + /** + * The character offset at which this Node ends. + */ + +end: number; + + /** + * The Token at which this Node begins. + */ + +startToken: Token; + + /** + * The Token at which this Node ends. + */ + +endToken: Token; + + /** + * The Source document the AST represents. + */ + +source: Source; + + constructor(startToken: Token, endToken: Token, source: Source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; + } + + toJSON(): {| start: number, end: number |} { + return { start: this.start, end: this.end }; + } +} + +// Print a simplified form when appearing in `inspect` and `util.inspect`. +defineInspect(Location); + +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ +export class Token { + /** + * The kind of Token. + */ + +kind: TokenKindEnum; + + /** + * The character offset at which this Node begins. + */ + +start: number; + + /** + * The character offset at which this Node ends. + */ + +end: number; + + /** + * The 1-indexed line number on which this Token appears. + */ + +line: number; + + /** + * The 1-indexed column number at which this Token begins. + */ + +column: number; + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + */ + +value: string | void; + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. <SOF> is always the first node and <EOF> + * the last. + */ + +prev: Token | null; + +next: Token | null; + + constructor( + kind: TokenKindEnum, + start: number, + end: number, + line: number, + column: number, + prev: Token | null, + value?: string, + ) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; + this.value = value; + this.prev = prev; + this.next = null; + } + + toJSON(): {| + kind: TokenKindEnum, + value: string | void, + line: number, + column: number, + |} { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column, + }; + } +} + +// Print a simplified form when appearing in `inspect` and `util.inspect`. +defineInspect(Token); + +/** + * @internal + */ +export function isNode(maybeNode: mixed): boolean %checks { + return maybeNode != null && typeof maybeNode.kind === 'string'; +} + +/** + * The list of all possible AST node types. + */ +export type ASTNode = + | NameNode + | DocumentNode + | OperationDefinitionNode + | VariableDefinitionNode + | VariableNode + | SelectionSetNode + | FieldNode + | ArgumentNode + | FragmentSpreadNode + | InlineFragmentNode + | FragmentDefinitionNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode + | ObjectFieldNode + | DirectiveNode + | NamedTypeNode + | ListTypeNode + | NonNullTypeNode + | SchemaDefinitionNode + | OperationTypeDefinitionNode + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | FieldDefinitionNode + | InputValueDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | EnumValueDefinitionNode + | InputObjectTypeDefinitionNode + | DirectiveDefinitionNode + | SchemaExtensionNode + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode; + +/** + * Utility type listing all nodes indexed by their kind. + */ +export type ASTKindToNode = {| + Name: NameNode, + Document: DocumentNode, + OperationDefinition: OperationDefinitionNode, + VariableDefinition: VariableDefinitionNode, + Variable: VariableNode, + SelectionSet: SelectionSetNode, + Field: FieldNode, + Argument: ArgumentNode, + FragmentSpread: FragmentSpreadNode, + InlineFragment: InlineFragmentNode, + FragmentDefinition: FragmentDefinitionNode, + IntValue: IntValueNode, + FloatValue: FloatValueNode, + StringValue: StringValueNode, + BooleanValue: BooleanValueNode, + NullValue: NullValueNode, + EnumValue: EnumValueNode, + ListValue: ListValueNode, + ObjectValue: ObjectValueNode, + ObjectField: ObjectFieldNode, + Directive: DirectiveNode, + NamedType: NamedTypeNode, + ListType: ListTypeNode, + NonNullType: NonNullTypeNode, + SchemaDefinition: SchemaDefinitionNode, + OperationTypeDefinition: OperationTypeDefinitionNode, + ScalarTypeDefinition: ScalarTypeDefinitionNode, + ObjectTypeDefinition: ObjectTypeDefinitionNode, + FieldDefinition: FieldDefinitionNode, + InputValueDefinition: InputValueDefinitionNode, + InterfaceTypeDefinition: InterfaceTypeDefinitionNode, + UnionTypeDefinition: UnionTypeDefinitionNode, + EnumTypeDefinition: EnumTypeDefinitionNode, + EnumValueDefinition: EnumValueDefinitionNode, + InputObjectTypeDefinition: InputObjectTypeDefinitionNode, + DirectiveDefinition: DirectiveDefinitionNode, + SchemaExtension: SchemaExtensionNode, + ScalarTypeExtension: ScalarTypeExtensionNode, + ObjectTypeExtension: ObjectTypeExtensionNode, + InterfaceTypeExtension: InterfaceTypeExtensionNode, + UnionTypeExtension: UnionTypeExtensionNode, + EnumTypeExtension: EnumTypeExtensionNode, + InputObjectTypeExtension: InputObjectTypeExtensionNode, +|}; + +// Name + +export type NameNode = {| + +kind: 'Name', + +loc?: Location, + +value: string, +|}; + +// Document + +export type DocumentNode = {| + +kind: 'Document', + +loc?: Location, + +definitions: $ReadOnlyArray<DefinitionNode>, +|}; + +export type DefinitionNode = + | ExecutableDefinitionNode + | TypeSystemDefinitionNode + | TypeSystemExtensionNode; + +export type ExecutableDefinitionNode = + | OperationDefinitionNode + | FragmentDefinitionNode; + +export type OperationDefinitionNode = {| + +kind: 'OperationDefinition', + +loc?: Location, + +operation: OperationTypeNode, + +name?: NameNode, + +variableDefinitions?: $ReadOnlyArray<VariableDefinitionNode>, + +directives?: $ReadOnlyArray<DirectiveNode>, + +selectionSet: SelectionSetNode, +|}; + +export type OperationTypeNode = 'query' | 'mutation' | 'subscription'; + +export type VariableDefinitionNode = {| + +kind: 'VariableDefinition', + +loc?: Location, + +variable: VariableNode, + +type: TypeNode, + +defaultValue?: ValueNode, + +directives?: $ReadOnlyArray<DirectiveNode>, +|}; + +export type VariableNode = {| + +kind: 'Variable', + +loc?: Location, + +name: NameNode, +|}; + +export type SelectionSetNode = {| + kind: 'SelectionSet', + loc?: Location, + selections: $ReadOnlyArray<SelectionNode>, +|}; + +export type SelectionNode = FieldNode | FragmentSpreadNode | InlineFragmentNode; + +export type FieldNode = {| + +kind: 'Field', + +loc?: Location, + +alias?: NameNode, + +name: NameNode, + +arguments?: $ReadOnlyArray<ArgumentNode>, + +directives?: $ReadOnlyArray<DirectiveNode>, + +selectionSet?: SelectionSetNode, +|}; + +export type ArgumentNode = {| + +kind: 'Argument', + +loc?: Location, + +name: NameNode, + +value: ValueNode, +|}; + +// Fragments + +export type FragmentSpreadNode = {| + +kind: 'FragmentSpread', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray<DirectiveNode>, +|}; + +export type InlineFragmentNode = {| + +kind: 'InlineFragment', + +loc?: Location, + +typeCondition?: NamedTypeNode, + +directives?: $ReadOnlyArray<DirectiveNode>, + +selectionSet: SelectionSetNode, +|}; + +export type FragmentDefinitionNode = {| + +kind: 'FragmentDefinition', + +loc?: Location, + +name: NameNode, + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + +variableDefinitions?: $ReadOnlyArray<VariableDefinitionNode>, + +typeCondition: NamedTypeNode, + +directives?: $ReadOnlyArray<DirectiveNode>, + +selectionSet: SelectionSetNode, +|}; + +// Values + +export type ValueNode = + | VariableNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode; + +export type IntValueNode = {| + +kind: 'IntValue', + +loc?: Location, + +value: string, +|}; + +export type FloatValueNode = {| + +kind: 'FloatValue', + +loc?: Location, + +value: string, +|}; + +export type StringValueNode = {| + +kind: 'StringValue', + +loc?: Location, + +value: string, + +block?: boolean, +|}; + +export type BooleanValueNode = {| + +kind: 'BooleanValue', + +loc?: Location, + +value: boolean, +|}; + +export type NullValueNode = {| + +kind: 'NullValue', + +loc?: Location, +|}; + +export type EnumValueNode = {| + +kind: 'EnumValue', + +loc?: Location, + +value: string, +|}; + +export type ListValueNode = {| + +kind: 'ListValue', + +loc?: Location, + +values: $ReadOnlyArray<ValueNode>, +|}; + +export type ObjectValueNode = {| + +kind: 'ObjectValue', + +loc?: Location, + +fields: $ReadOnlyArray<ObjectFieldNode>, +|}; + +export type ObjectFieldNode = {| + +kind: 'ObjectField', + +loc?: Location, + +name: NameNode, + +value: ValueNode, +|}; + +// Directives + +export type DirectiveNode = {| + +kind: 'Directive', + +loc?: Location, + +name: NameNode, + +arguments?: $ReadOnlyArray<ArgumentNode>, +|}; + +// Type Reference + +export type TypeNode = NamedTypeNode | ListTypeNode | NonNullTypeNode; + +export type NamedTypeNode = {| + +kind: 'NamedType', + +loc?: Location, + +name: NameNode, +|}; + +export type ListTypeNode = {| + +kind: 'ListType', + +loc?: Location, + +type: TypeNode, +|}; + +export type NonNullTypeNode = {| + +kind: 'NonNullType', + +loc?: Location, + +type: NamedTypeNode | ListTypeNode, +|}; + +// Type System Definition + +export type TypeSystemDefinitionNode = + | SchemaDefinitionNode + | TypeDefinitionNode + | DirectiveDefinitionNode; + +export type SchemaDefinitionNode = {| + +kind: 'SchemaDefinition', + +loc?: Location, + +description?: StringValueNode, + +directives?: $ReadOnlyArray<DirectiveNode>, + +operationTypes: $ReadOnlyArray<OperationTypeDefinitionNode>, +|}; + +export type OperationTypeDefinitionNode = {| + +kind: 'OperationTypeDefinition', + +loc?: Location, + +operation: OperationTypeNode, + +type: NamedTypeNode, +|}; + +// Type Definition + +export type TypeDefinitionNode = + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | InputObjectTypeDefinitionNode; + +export type ScalarTypeDefinitionNode = {| + +kind: 'ScalarTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray<DirectiveNode>, +|}; + +export type ObjectTypeDefinitionNode = {| + +kind: 'ObjectTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +interfaces?: $ReadOnlyArray<NamedTypeNode>, + +directives?: $ReadOnlyArray<DirectiveNode>, + +fields?: $ReadOnlyArray<FieldDefinitionNode>, +|}; + +export type FieldDefinitionNode = {| + +kind: 'FieldDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +arguments?: $ReadOnlyArray<InputValueDefinitionNode>, + +type: TypeNode, + +directives?: $ReadOnlyArray<DirectiveNode>, +|}; + +export type InputValueDefinitionNode = {| + +kind: 'InputValueDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +type: TypeNode, + +defaultValue?: ValueNode, + +directives?: $ReadOnlyArray<DirectiveNode>, +|}; + +export type InterfaceTypeDefinitionNode = {| + +kind: 'InterfaceTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +interfaces?: $ReadOnlyArray<NamedTypeNode>, + +directives?: $ReadOnlyArray<DirectiveNode>, + +fields?: $ReadOnlyArray<FieldDefinitionNode>, +|}; + +export type UnionTypeDefinitionNode = {| + +kind: 'UnionTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray<DirectiveNode>, + +types?: $ReadOnlyArray<NamedTypeNode>, +|}; + +export type EnumTypeDefinitionNode = {| + +kind: 'EnumTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray<DirectiveNode>, + +values?: $ReadOnlyArray<EnumValueDefinitionNode>, +|}; + +export type EnumValueDefinitionNode = {| + +kind: 'EnumValueDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray<DirectiveNode>, +|}; + +export type InputObjectTypeDefinitionNode = {| + +kind: 'InputObjectTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray<DirectiveNode>, + +fields?: $ReadOnlyArray<InputValueDefinitionNode>, +|}; + +// Directive Definitions + +export type DirectiveDefinitionNode = {| + +kind: 'DirectiveDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +arguments?: $ReadOnlyArray<InputValueDefinitionNode>, + +repeatable: boolean, + +locations: $ReadOnlyArray<NameNode>, +|}; + +// Type System Extensions + +export type TypeSystemExtensionNode = SchemaExtensionNode | TypeExtensionNode; + +export type SchemaExtensionNode = {| + +kind: 'SchemaExtension', + +loc?: Location, + +directives?: $ReadOnlyArray<DirectiveNode>, + +operationTypes?: $ReadOnlyArray<OperationTypeDefinitionNode>, +|}; + +// Type Extensions + +export type TypeExtensionNode = + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode; + +export type ScalarTypeExtensionNode = {| + +kind: 'ScalarTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray<DirectiveNode>, +|}; + +export type ObjectTypeExtensionNode = {| + +kind: 'ObjectTypeExtension', + +loc?: Location, + +name: NameNode, + +interfaces?: $ReadOnlyArray<NamedTypeNode>, + +directives?: $ReadOnlyArray<DirectiveNode>, + +fields?: $ReadOnlyArray<FieldDefinitionNode>, +|}; + +export type InterfaceTypeExtensionNode = {| + +kind: 'InterfaceTypeExtension', + +loc?: Location, + +name: NameNode, + +interfaces?: $ReadOnlyArray<NamedTypeNode>, + +directives?: $ReadOnlyArray<DirectiveNode>, + +fields?: $ReadOnlyArray<FieldDefinitionNode>, +|}; + +export type UnionTypeExtensionNode = {| + +kind: 'UnionTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray<DirectiveNode>, + +types?: $ReadOnlyArray<NamedTypeNode>, +|}; + +export type EnumTypeExtensionNode = {| + +kind: 'EnumTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray<DirectiveNode>, + +values?: $ReadOnlyArray<EnumValueDefinitionNode>, +|}; + +export type InputObjectTypeExtensionNode = {| + +kind: 'InputObjectTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray<DirectiveNode>, + +fields?: $ReadOnlyArray<InputValueDefinitionNode>, +|}; diff --git a/school/node_modules/graphql/language/ast.mjs b/school/node_modules/graphql/language/ast.mjs new file mode 100644 index 0000000..6085488 --- /dev/null +++ b/school/node_modules/graphql/language/ast.mjs @@ -0,0 +1,118 @@ +import defineInspect from "../jsutils/defineInspect.mjs"; + +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +export var Location = /*#__PURE__*/function () { + /** + * The character offset at which this Node begins. + */ + + /** + * The character offset at which this Node ends. + */ + + /** + * The Token at which this Node begins. + */ + + /** + * The Token at which this Node ends. + */ + + /** + * The Source document the AST represents. + */ + function Location(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; + } + + var _proto = Location.prototype; + + _proto.toJSON = function toJSON() { + return { + start: this.start, + end: this.end + }; + }; + + return Location; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +defineInspect(Location); +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ + +export var Token = /*#__PURE__*/function () { + /** + * The kind of Token. + */ + + /** + * The character offset at which this Node begins. + */ + + /** + * The character offset at which this Node ends. + */ + + /** + * The 1-indexed line number on which this Token appears. + */ + + /** + * The 1-indexed column number at which this Token begins. + */ + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + */ + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. <SOF> is always the first node and <EOF> + * the last. + */ + function Token(kind, start, end, line, column, prev, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; + this.value = value; + this.prev = prev; + this.next = null; + } + + var _proto2 = Token.prototype; + + _proto2.toJSON = function toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column + }; + }; + + return Token; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +defineInspect(Token); +/** + * @internal + */ + +export function isNode(maybeNode) { + return maybeNode != null && typeof maybeNode.kind === 'string'; +} +/** + * The list of all possible AST node types. + */ diff --git a/school/node_modules/graphql/language/blockString.d.ts b/school/node_modules/graphql/language/blockString.d.ts new file mode 100644 index 0000000..70ffc66 --- /dev/null +++ b/school/node_modules/graphql/language/blockString.d.ts @@ -0,0 +1,23 @@ +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + */ +export function dedentBlockStringValue(rawString: string): string; + +/** + * @internal + */ +export function getBlockStringIndentation(body: string): number; + +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + */ +export function printBlockString( + value: string, + indentation?: string, + preferMultipleLines?: boolean, +): string; diff --git a/school/node_modules/graphql/language/blockString.js b/school/node_modules/graphql/language/blockString.js new file mode 100644 index 0000000..a195041 --- /dev/null +++ b/school/node_modules/graphql/language/blockString.js @@ -0,0 +1,134 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.dedentBlockStringValue = dedentBlockStringValue; +exports.getBlockStringIndentation = getBlockStringIndentation; +exports.printBlockString = printBlockString; + +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + * + * @internal + */ +function dedentBlockStringValue(rawString) { + // Expand a block string's raw value into independent lines. + var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first. + + var commonIndent = getBlockStringIndentation(rawString); + + if (commonIndent !== 0) { + for (var i = 1; i < lines.length; i++) { + lines[i] = lines[i].slice(commonIndent); + } + } // Remove leading and trailing blank lines. + + + var startLine = 0; + + while (startLine < lines.length && isBlank(lines[startLine])) { + ++startLine; + } + + var endLine = lines.length; + + while (endLine > startLine && isBlank(lines[endLine - 1])) { + --endLine; + } // Return a string of the lines joined with U+000A. + + + return lines.slice(startLine, endLine).join('\n'); +} + +function isBlank(str) { + for (var i = 0; i < str.length; ++i) { + if (str[i] !== ' ' && str[i] !== '\t') { + return false; + } + } + + return true; +} +/** + * @internal + */ + + +function getBlockStringIndentation(value) { + var _commonIndent; + + var isFirstLine = true; + var isEmptyLine = true; + var indent = 0; + var commonIndent = null; + + for (var i = 0; i < value.length; ++i) { + switch (value.charCodeAt(i)) { + case 13: + // \r + if (value.charCodeAt(i + 1) === 10) { + ++i; // skip \r\n as one symbol + } + + // falls through + + case 10: + // \n + isFirstLine = false; + isEmptyLine = true; + indent = 0; + break; + + case 9: // \t + + case 32: + // <space> + ++indent; + break; + + default: + if (isEmptyLine && !isFirstLine && (commonIndent === null || indent < commonIndent)) { + commonIndent = indent; + } + + isEmptyLine = false; + } + } + + return (_commonIndent = commonIndent) !== null && _commonIndent !== void 0 ? _commonIndent : 0; +} +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + * + * @internal + */ + + +function printBlockString(value) { + var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + var preferMultipleLines = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var isSingleLine = value.indexOf('\n') === -1; + var hasLeadingSpace = value[0] === ' ' || value[0] === '\t'; + var hasTrailingQuote = value[value.length - 1] === '"'; + var hasTrailingSlash = value[value.length - 1] === '\\'; + var printAsMultipleLines = !isSingleLine || hasTrailingQuote || hasTrailingSlash || preferMultipleLines; + var result = ''; // Format a multi-line block quote to account for leading space. + + if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) { + result += '\n' + indentation; + } + + result += indentation ? value.replace(/\n/g, '\n' + indentation) : value; + + if (printAsMultipleLines) { + result += '\n'; + } + + return '"""' + result.replace(/"""/g, '\\"""') + '"""'; +} diff --git a/school/node_modules/graphql/language/blockString.js.flow b/school/node_modules/graphql/language/blockString.js.flow new file mode 100644 index 0000000..2c967c3 --- /dev/null +++ b/school/node_modules/graphql/language/blockString.js.flow @@ -0,0 +1,121 @@ +// @flow strict +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + * + * @internal + */ +export function dedentBlockStringValue(rawString: string): string { + // Expand a block string's raw value into independent lines. + const lines = rawString.split(/\r\n|[\n\r]/g); + + // Remove common indentation from all lines but first. + const commonIndent = getBlockStringIndentation(rawString); + + if (commonIndent !== 0) { + for (let i = 1; i < lines.length; i++) { + lines[i] = lines[i].slice(commonIndent); + } + } + + // Remove leading and trailing blank lines. + let startLine = 0; + while (startLine < lines.length && isBlank(lines[startLine])) { + ++startLine; + } + + let endLine = lines.length; + while (endLine > startLine && isBlank(lines[endLine - 1])) { + --endLine; + } + + // Return a string of the lines joined with U+000A. + return lines.slice(startLine, endLine).join('\n'); +} + +function isBlank(str: string): boolean { + for (let i = 0; i < str.length; ++i) { + if (str[i] !== ' ' && str[i] !== '\t') { + return false; + } + } + + return true; +} + +/** + * @internal + */ +export function getBlockStringIndentation(value: string): number { + let isFirstLine = true; + let isEmptyLine = true; + let indent = 0; + let commonIndent = null; + + for (let i = 0; i < value.length; ++i) { + switch (value.charCodeAt(i)) { + case 13: // \r + if (value.charCodeAt(i + 1) === 10) { + ++i; // skip \r\n as one symbol + } + // falls through + case 10: // \n + isFirstLine = false; + isEmptyLine = true; + indent = 0; + break; + case 9: // \t + case 32: // <space> + ++indent; + break; + default: + if ( + isEmptyLine && + !isFirstLine && + (commonIndent === null || indent < commonIndent) + ) { + commonIndent = indent; + } + isEmptyLine = false; + } + } + + return commonIndent ?? 0; +} + +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + * + * @internal + */ +export function printBlockString( + value: string, + indentation: string = '', + preferMultipleLines: boolean = false, +): string { + const isSingleLine = value.indexOf('\n') === -1; + const hasLeadingSpace = value[0] === ' ' || value[0] === '\t'; + const hasTrailingQuote = value[value.length - 1] === '"'; + const hasTrailingSlash = value[value.length - 1] === '\\'; + const printAsMultipleLines = + !isSingleLine || + hasTrailingQuote || + hasTrailingSlash || + preferMultipleLines; + + let result = ''; + // Format a multi-line block quote to account for leading space. + if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) { + result += '\n' + indentation; + } + result += indentation ? value.replace(/\n/g, '\n' + indentation) : value; + if (printAsMultipleLines) { + result += '\n'; + } + + return '"""' + result.replace(/"""/g, '\\"""') + '"""'; +} diff --git a/school/node_modules/graphql/language/blockString.mjs b/school/node_modules/graphql/language/blockString.mjs new file mode 100644 index 0000000..9ee1098 --- /dev/null +++ b/school/node_modules/graphql/language/blockString.mjs @@ -0,0 +1,124 @@ +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + * + * @internal + */ +export function dedentBlockStringValue(rawString) { + // Expand a block string's raw value into independent lines. + var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first. + + var commonIndent = getBlockStringIndentation(rawString); + + if (commonIndent !== 0) { + for (var i = 1; i < lines.length; i++) { + lines[i] = lines[i].slice(commonIndent); + } + } // Remove leading and trailing blank lines. + + + var startLine = 0; + + while (startLine < lines.length && isBlank(lines[startLine])) { + ++startLine; + } + + var endLine = lines.length; + + while (endLine > startLine && isBlank(lines[endLine - 1])) { + --endLine; + } // Return a string of the lines joined with U+000A. + + + return lines.slice(startLine, endLine).join('\n'); +} + +function isBlank(str) { + for (var i = 0; i < str.length; ++i) { + if (str[i] !== ' ' && str[i] !== '\t') { + return false; + } + } + + return true; +} +/** + * @internal + */ + + +export function getBlockStringIndentation(value) { + var _commonIndent; + + var isFirstLine = true; + var isEmptyLine = true; + var indent = 0; + var commonIndent = null; + + for (var i = 0; i < value.length; ++i) { + switch (value.charCodeAt(i)) { + case 13: + // \r + if (value.charCodeAt(i + 1) === 10) { + ++i; // skip \r\n as one symbol + } + + // falls through + + case 10: + // \n + isFirstLine = false; + isEmptyLine = true; + indent = 0; + break; + + case 9: // \t + + case 32: + // <space> + ++indent; + break; + + default: + if (isEmptyLine && !isFirstLine && (commonIndent === null || indent < commonIndent)) { + commonIndent = indent; + } + + isEmptyLine = false; + } + } + + return (_commonIndent = commonIndent) !== null && _commonIndent !== void 0 ? _commonIndent : 0; +} +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + * + * @internal + */ + +export function printBlockString(value) { + var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + var preferMultipleLines = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var isSingleLine = value.indexOf('\n') === -1; + var hasLeadingSpace = value[0] === ' ' || value[0] === '\t'; + var hasTrailingQuote = value[value.length - 1] === '"'; + var hasTrailingSlash = value[value.length - 1] === '\\'; + var printAsMultipleLines = !isSingleLine || hasTrailingQuote || hasTrailingSlash || preferMultipleLines; + var result = ''; // Format a multi-line block quote to account for leading space. + + if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) { + result += '\n' + indentation; + } + + result += indentation ? value.replace(/\n/g, '\n' + indentation) : value; + + if (printAsMultipleLines) { + result += '\n'; + } + + return '"""' + result.replace(/"""/g, '\\"""') + '"""'; +} diff --git a/school/node_modules/graphql/language/directiveLocation.d.ts b/school/node_modules/graphql/language/directiveLocation.d.ts new file mode 100644 index 0000000..225e129 --- /dev/null +++ b/school/node_modules/graphql/language/directiveLocation.d.ts @@ -0,0 +1,32 @@ +/** + * The set of allowed directive location values. + */ +export const DirectiveLocation: { + // Request Definitions + QUERY: 'QUERY'; + MUTATION: 'MUTATION'; + SUBSCRIPTION: 'SUBSCRIPTION'; + FIELD: 'FIELD'; + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION'; + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD'; + INLINE_FRAGMENT: 'INLINE_FRAGMENT'; + VARIABLE_DEFINITION: 'VARIABLE_DEFINITION'; + + // Type System Definitions + SCHEMA: 'SCHEMA'; + SCALAR: 'SCALAR'; + OBJECT: 'OBJECT'; + FIELD_DEFINITION: 'FIELD_DEFINITION'; + ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION'; + INTERFACE: 'INTERFACE'; + UNION: 'UNION'; + ENUM: 'ENUM'; + ENUM_VALUE: 'ENUM_VALUE'; + INPUT_OBJECT: 'INPUT_OBJECT'; + INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION'; +}; + +/** + * The enum type representing the directive location values. + */ +export type DirectiveLocationEnum = typeof DirectiveLocation[keyof typeof DirectiveLocation]; diff --git a/school/node_modules/graphql/language/directiveLocation.js b/school/node_modules/graphql/language/directiveLocation.js new file mode 100644 index 0000000..57bb417 --- /dev/null +++ b/school/node_modules/graphql/language/directiveLocation.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.DirectiveLocation = void 0; + +/** + * The set of allowed directive location values. + */ +var DirectiveLocation = Object.freeze({ + // Request Definitions + QUERY: 'QUERY', + MUTATION: 'MUTATION', + SUBSCRIPTION: 'SUBSCRIPTION', + FIELD: 'FIELD', + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', + INLINE_FRAGMENT: 'INLINE_FRAGMENT', + VARIABLE_DEFINITION: 'VARIABLE_DEFINITION', + // Type System Definitions + SCHEMA: 'SCHEMA', + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + FIELD_DEFINITION: 'FIELD_DEFINITION', + ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + ENUM_VALUE: 'ENUM_VALUE', + INPUT_OBJECT: 'INPUT_OBJECT', + INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION' +}); +/** + * The enum type representing the directive location values. + */ + +exports.DirectiveLocation = DirectiveLocation; diff --git a/school/node_modules/graphql/language/directiveLocation.js.flow b/school/node_modules/graphql/language/directiveLocation.js.flow new file mode 100644 index 0000000..3534059 --- /dev/null +++ b/school/node_modules/graphql/language/directiveLocation.js.flow @@ -0,0 +1,32 @@ +// @flow strict +/** + * The set of allowed directive location values. + */ +export const DirectiveLocation = Object.freeze({ + // Request Definitions + QUERY: 'QUERY', + MUTATION: 'MUTATION', + SUBSCRIPTION: 'SUBSCRIPTION', + FIELD: 'FIELD', + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', + INLINE_FRAGMENT: 'INLINE_FRAGMENT', + VARIABLE_DEFINITION: 'VARIABLE_DEFINITION', + // Type System Definitions + SCHEMA: 'SCHEMA', + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + FIELD_DEFINITION: 'FIELD_DEFINITION', + ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + ENUM_VALUE: 'ENUM_VALUE', + INPUT_OBJECT: 'INPUT_OBJECT', + INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION', +}); + +/** + * The enum type representing the directive location values. + */ +export type DirectiveLocationEnum = $Values<typeof DirectiveLocation>; diff --git a/school/node_modules/graphql/language/directiveLocation.mjs b/school/node_modules/graphql/language/directiveLocation.mjs new file mode 100644 index 0000000..82823b7 --- /dev/null +++ b/school/node_modules/graphql/language/directiveLocation.mjs @@ -0,0 +1,29 @@ +/** + * The set of allowed directive location values. + */ +export var DirectiveLocation = Object.freeze({ + // Request Definitions + QUERY: 'QUERY', + MUTATION: 'MUTATION', + SUBSCRIPTION: 'SUBSCRIPTION', + FIELD: 'FIELD', + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', + INLINE_FRAGMENT: 'INLINE_FRAGMENT', + VARIABLE_DEFINITION: 'VARIABLE_DEFINITION', + // Type System Definitions + SCHEMA: 'SCHEMA', + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + FIELD_DEFINITION: 'FIELD_DEFINITION', + ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + ENUM_VALUE: 'ENUM_VALUE', + INPUT_OBJECT: 'INPUT_OBJECT', + INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION' +}); +/** + * The enum type representing the directive location values. + */ diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/grammar.d.ts b/school/node_modules/graphql/language/experimentalOnlineParser/grammar.d.ts new file mode 100644 index 0000000..6e71a66 --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/grammar.d.ts @@ -0,0 +1,1006 @@ +export interface GraphQLGrammarType { + [name: string]: GraphQLGrammarRule; +} + +export type GraphQLGrammarRule = + | GraphQLGrammarRuleName + | GraphQLGrammarRuleConstraint + | GraphQLGrammarConstraintsSet; + +export type GraphQLGrammarRuleName = string; + +export type GraphQLGrammarRuleConstraint = + | GraphQLGrammarTokenConstraint + | GraphQLGrammarOfTypeConstraint + | GraphQLGrammarListOfTypeConstraint + | GraphQLGrammarPeekConstraint; + +export type GraphQLGrammarConstraintsSet = Array< + GraphQLGrammarRuleName | GraphQLGrammarRuleConstraint +>; + +export interface GraphQLGrammarBaseRuleConstraint { + butNot?: GraphQLGrammarTokenConstraint | Array<GraphQLGrammarTokenConstraint>; + optional?: boolean; + eatNextOnFail?: boolean; +} + +export interface GraphQLGrammarTokenConstraint + extends GraphQLGrammarBaseRuleConstraint { + token: + | '!' + | '$' + | '&' + | '(' + | ')' + | '...' + | ':' + | '=' + | '@' + | '[' + | ']' + | '{' + | '}' + | '|' + | 'Name' + | 'Int' + | 'Float' + | 'String' + | 'BlockString' + | 'Comment'; + ofValue?: string; + oneOf?: Array<string>; + tokenName?: string; + definitionName?: boolean; + typeName?: boolean; +} + +export interface GraphQLGrammarOfTypeConstraint + extends GraphQLGrammarBaseRuleConstraint { + ofType: GraphQLGrammarRule; + tokenName?: string; +} + +export interface GraphQLGrammarListOfTypeConstraint + extends GraphQLGrammarBaseRuleConstraint { + listOfType: GraphQLGrammarRuleName; +} + +export interface GraphQLGrammarPeekConstraint + extends GraphQLGrammarBaseRuleConstraint { + peek: Array<GraphQLGrammarPeekConstraintCondition>; +} + +export interface GraphQLGrammarPeekConstraintCondition { + ifCondition: GraphQLGrammarTokenConstraint; + expect: GraphQLGrammarRule; + end?: boolean; +} + +const grammar: GraphQLGrammarType = { + Name: { token: 'Name' }, + String: { token: 'String' }, + BlockString: { token: 'BlockString' }, + + Document: { listOfType: 'Definition' }, + Definition: { + peek: [ + { + ifCondition: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'], + }, + expect: 'OperationDefinition', + }, + { + ifCondition: { token: 'Name', ofValue: 'fragment' }, + expect: 'FragmentDefinition', + }, + { + ifCondition: { + token: 'Name', + oneOf: [ + 'schema', + 'scalar', + 'type', + 'interface', + 'union', + 'enum', + 'input', + 'directive', + ], + }, + expect: 'TypeSystemDefinition', + }, + { + ifCondition: { token: 'Name', ofValue: 'extend' }, + expect: 'TypeSystemExtension', + }, + { + ifCondition: { token: '{' }, + expect: 'OperationDefinition', + }, + { + ifCondition: 'String', + expect: 'TypeSystemDefinition', + }, + { + ifCondition: 'BlockString', + expect: 'TypeSystemDefinition', + }, + ], + }, + + OperationDefinition: { + peek: [ + { + ifCondition: { token: '{' }, + expect: 'SelectionSet', + }, + { + ifCondition: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'], + }, + expect: [ + 'OperationType', + { + token: 'Name', + optional: true, + tokenName: 'OperationName', + definitionName: true, + }, + { ofType: 'VariableDefinitions', optional: true }, + { ofType: 'Directives', optional: true }, + 'SelectionSet', + ], + }, + ], + }, + OperationType: { + ofType: 'OperationTypeName', + }, + OperationTypeName: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'], + definitionName: true, + }, + SelectionSet: [{ token: '{' }, { listOfType: 'Selection' }, { token: '}' }], + Selection: { + peek: [ + { + ifCondition: { token: '...' }, + expect: 'Fragment', + }, + { + ifCondition: { token: 'Name' }, + expect: 'Field', + }, + ], + }, + + Field: [ + { + ofType: 'Alias', + optional: true, + eatNextOnFail: true, + definitionName: true, + }, + { token: 'Name', tokenName: 'FieldName', definitionName: true }, + { ofType: 'Arguments', optional: true }, + { ofType: 'Directives', optional: true }, + { ofType: 'SelectionSet', optional: true }, + ], + + Arguments: [{ token: '(' }, { listOfType: 'Argument' }, { token: ')' }], + Argument: [ + { token: 'Name', tokenName: 'ArgumentName', definitionName: true }, + { token: ':' }, + 'Value', + ], + + Alias: [ + { token: 'Name', tokenName: 'AliasName', definitionName: true }, + { token: ':' }, + ], + + Fragment: [ + { token: '...' }, + { + peek: [ + { + ifCondition: 'FragmentName', + expect: 'FragmentSpread', + }, + { + ifCondition: { token: 'Name', ofValue: 'on' }, + expect: 'InlineFragment', + }, + { + ifCondition: { token: '@' }, + expect: 'InlineFragment', + }, + { + ifCondition: { token: '{' }, + expect: 'InlineFragment', + }, + ], + }, + ], + + FragmentSpread: ['FragmentName', { ofType: 'Directives', optional: true }], + FragmentDefinition: [ + { + token: 'Name', + ofValue: 'fragment', + tokenName: 'FragmentDefinitionKeyword', + }, + 'FragmentName', + 'TypeCondition', + { ofType: 'Directives', optional: true }, + 'SelectionSet', + ], + FragmentName: { + token: 'Name', + butNot: { token: 'Name', ofValue: 'on' }, + definitionName: true, + }, + + TypeCondition: [ + { token: 'Name', ofValue: 'on', tokenName: 'OnKeyword' }, + 'TypeName', + ], + + InlineFragment: [ + { ofType: 'TypeCondition', optional: true }, + { ofType: 'Directives', optional: true }, + 'SelectionSet', + ], + + Value: { + peek: [ + { + ifCondition: { token: '$' }, + expect: 'Variable', + }, + { + ifCondition: 'IntValue', + expect: { ofType: 'IntValue', tokenName: 'NumberValue' }, + }, + { + ifCondition: 'FloatValue', + expect: { ofType: 'FloatValue', tokenName: 'NumberValue' }, + }, + { + ifCondition: 'BooleanValue', + expect: { ofType: 'BooleanValue', tokenName: 'BooleanValue' }, + }, + { + ifCondition: 'EnumValue', + expect: { ofType: 'EnumValue', tokenName: 'EnumValue' }, + }, + { + ifCondition: 'String', + expect: { ofType: 'String', tokenName: 'StringValue' }, + }, + { + ifCondition: 'BlockString', + expect: { ofType: 'BlockString', tokenName: 'StringValue' }, + }, + { + ifCondition: 'NullValue', + expect: { ofType: 'NullValue', tokenName: 'NullValue' }, + }, + { + ifCondition: { token: '[' }, + expect: 'ListValue', + }, + { + ifCondition: { token: '{' }, + expect: 'ObjectValue', + }, + ], + }, + + ConstValue: { + peek: [ + { + ifCondition: 'IntValue', + expect: { ofType: 'IntValue' }, + }, + { + ifCondition: 'FloatValue', + expect: { ofType: 'FloatValue' }, + }, + { + ifCondition: 'BooleanValue', + expect: 'BooleanValue', + }, + { + ifCondition: 'EnumValue', + expect: 'EnumValue', + }, + { + ifCondition: 'String', + expect: { ofType: 'String', tokenName: 'StringValue' }, + }, + { + ifCondition: 'BlockString', + expect: { token: 'BlockString', tokenName: 'StringValue' }, + }, + { + ifCondition: 'NullValue', + expect: 'NullValue', + }, + { + ifCondition: { token: '[' }, + expect: 'ConstListValue', + }, + { + ifCondition: { token: '{' }, + expect: 'ObjectValue', + }, + ], + }, + + IntValue: { token: 'Int' }, + + FloatValue: { token: 'Float' }, + + StringValue: { + peek: [ + { + ifCondition: { token: 'String' }, + expect: { token: 'String', tokenName: 'StringValue' }, + }, + { + ifCondition: { token: 'BlockString' }, + expect: { token: 'BlockString', tokenName: 'StringValue' }, + }, + ], + }, + + BooleanValue: { + token: 'Name', + oneOf: ['true', 'false'], + tokenName: 'BooleanValue', + }, + + NullValue: { + token: 'Name', + ofValue: 'null', + tokenName: 'NullValue', + }, + + EnumValue: { + token: 'Name', + butNot: { token: 'Name', oneOf: ['null', 'true', 'false'] }, + tokenName: 'EnumValue', + }, + + ListValue: [ + { token: '[' }, + { listOfType: 'Value', optional: true }, + { token: ']' }, + ], + + ConstListValue: [ + { token: '[' }, + { listOfType: 'ConstValue', optional: true }, + { token: ']' }, + ], + + ObjectValue: [ + { token: '{' }, + { listOfType: 'ObjectField', optional: true }, + { token: '}' }, + ], + ObjectField: [ + { token: 'Name', tokenName: 'ObjectFieldName' }, + { token: ':' }, + { ofType: 'ConstValue' }, + ], + + Variable: [ + { token: '$', tokenName: 'VariableName' }, + { token: 'Name', tokenName: 'VariableName' }, + ], + VariableDefinitions: [ + { token: '(' }, + { listOfType: 'VariableDefinition' }, + { token: ')' }, + ], + VariableDefinition: [ + 'Variable', + { token: ':' }, + 'Type', + { ofType: 'DefaultValue', optional: true }, + ], + DefaultValue: [{ token: '=' }, 'ConstValue'], + + TypeName: { token: 'Name', tokenName: 'TypeName', typeName: true }, + + Type: { + peek: [ + { + ifCondition: { token: 'Name' }, + expect: ['TypeName', { token: '!', optional: true }], + }, + { + ifCondition: { token: '[' }, + expect: 'ListType', + }, + ], + }, + ListType: [ + { token: '[' }, + { listOfType: 'Type' }, + { token: ']' }, + { token: '!', optional: true }, + ], + + Directives: { listOfType: 'Directive' }, + Directive: [ + { token: '@', tokenName: 'DirectiveName' }, + { token: 'Name', tokenName: 'DirectiveName' }, + { ofType: 'Arguments', optional: true }, + ], + + TypeSystemDefinition: [ + { ofType: 'Description', optional: true }, + { + peek: [ + { + ifCondition: { + target: 'Name', + ofValue: 'schema', + }, + expect: 'SchemaDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'scalar', + }, + expect: 'ScalarTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'type', + }, + expect: 'ObjectTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'interface', + }, + expect: 'InterfaceTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'union', + }, + expect: 'UnionTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'enum', + }, + expect: 'EnumTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'input', + }, + expect: 'InputObjectTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'directive', + }, + expect: 'DirectiveDefinition', + }, + ], + }, + ], + + TypeSystemExtension: { + peek: [ + { + ifCondition: { + target: 'Name', + ofValue: 'schema', + }, + expect: 'SchemaExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'scalar', + }, + expect: 'ScalarTypeExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'type', + }, + expect: 'ObjectTypeExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'interface', + }, + expect: 'InterfaceTypeExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'union', + }, + expect: 'UnionTypeExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'enum', + }, + expect: 'EnumTypeExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'input', + }, + expect: 'InputObjectTypeExtension', + }, + ], + }, + + SchemaDefinition: [ + { + token: 'Name', + ofValue: 'schema', + tokenName: 'SchemaDefinitionKeyword', + }, + { ofType: 'Directives', optional: true }, + { token: '{' }, + { listOfType: 'RootOperationTypeDefinition' }, + { token: '}' }, + ], + RootOperationTypeDefinition: [ + 'OperationType', + { token: ':' }, + { token: 'Name', tokenName: 'OperationTypeDefinitionName' }, + ], + + SchemaExtension: [ + { token: 'Name', ofValue: 'extend' }, + { token: 'Name', ofValue: 'schema' }, + 'Name', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { + ofType: [ + { token: '{' }, + { listOfType: 'RootOperationTypeDefinition' }, + { token: '}' }, + ], + optional: true, + }, + ], + }, + { + ifCondition: { token: '{' }, + expect: [ + { token: '{' }, + { listOfType: 'RootOperationTypeDefinition' }, + { token: '}' }, + ], + }, + ], + }, + ], + + Description: 'StringValue', + + ScalarTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'scalar', + tokenName: 'ScalarDefinitionKeyword', + }, + 'TypeName', + { ofType: 'Directives', optional: true }, + ], + + ScalarTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'scalar', + tokenName: 'ScalarDefinitionKeyword', + }, + 'TypeName', + 'Directives', + ], + + ObjectTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'type', + tokenName: 'TypeDefinitionKeyword', + }, + 'TypeName', + { ofType: 'ImplementsInterfaces', optional: true }, + { ofType: 'Directives', optional: true }, + { ofType: 'FieldsDefinition', optional: true }, + ], + ImplementsInterfaces: [ + { + token: 'Name', + ofValue: 'implements', + tokenName: 'ImplementsKeyword', + }, + { token: '&', optional: true }, + 'TypeName', + { + listOfType: 'ImplementsAdditionalInterfaceName', + optional: true, + }, + ], + ImplementsAdditionalInterfaceName: [{ token: '&' }, 'TypeName'], + FieldsDefinition: [ + { token: '{' }, + { listOfType: 'FieldDefinition' }, + { token: '}' }, + ], + FieldDefinition: [ + { ofType: 'Description', optional: true }, + { token: 'Name', tokenName: 'AliasName', definitionName: true }, + { ofType: 'ArgumentsDefinition', optional: true }, + { token: ':' }, + 'Type', + { ofType: 'Directives', optional: true }, + ], + + ArgumentsDefinition: [ + { token: '(' }, + { listOfType: 'InputValueDefinition' }, + { token: ')' }, + ], + InputValueDefinition: [ + { ofType: 'Description', optional: true }, + { token: 'Name', tokenName: 'ArgumentName' }, + { token: ':' }, + 'Type', + { ofType: 'DefaultValue', optional: true }, + { ofType: 'Directives', optional: true }, + ], + + ObjectTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'type', + tokenName: 'TypeDefinitionKeyword', + }, + 'TypeName', + { + peek: [ + { + ifCondition: { token: 'Name', ofValue: 'interface' }, + expect: [ + 'ImplementsInterfaces', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'FieldsDefinition', optional: true }, + ], + }, + { + ifCondition: { token: '{' }, + expect: 'FieldsDefinition', + }, + ], + optional: true, + }, + ], + }, + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'FieldsDefinition', optional: true }, + ], + }, + { + ifCondition: { token: '{' }, + expect: 'FieldsDefinition', + }, + ], + }, + ], + + InterfaceTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'interface', + tokenName: 'InterfaceDefinitionKeyword', + }, + 'TypeName', + { ofType: 'Directives', optional: true }, + { ofType: 'FieldsDefinition', optional: true }, + ], + + InterfaceTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'interface', + tokenName: 'InterfaceDefinitionKeyword', + }, + 'TypeName', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'FieldsDefinition', optional: true }, + ], + }, + { + ifCondition: { token: '{' }, + expect: 'FieldsDefinition', + }, + ], + }, + ], + + UnionTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'union', + tokenName: 'UnionDefinitionKeyword', + }, + 'TypeName', + { ofType: 'Directives', optional: true }, + { ofType: 'UnionMemberTypes', optional: true }, + ], + + UnionMemberTypes: [ + { token: '=' }, + { token: '|', optional: true }, + 'Name', + { + listOfType: 'UnionMemberAdditionalTypeName', + optional: true, + }, + ], + + UnionMemberAdditionalTypeName: [{ token: '|' }, 'TypeName'], + + UnionTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'union', + tokenName: 'UnionDefinitionKeyword', + }, + 'TypeName', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'UnionMemberTypes', optional: true }, + ], + }, + { + ifCondition: { token: '=' }, + expect: 'UnionMemberTypes', + }, + ], + }, + ], + + EnumTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'enum', + tokenName: 'EnumDefinitionKeyword', + }, + 'TypeName', + { ofType: 'Directives', optional: true }, + { ofType: 'EnumValuesDefinition', optional: true }, + ], + EnumValuesDefinition: [ + { token: '{' }, + { listOfType: 'EnumValueDefinition' }, + { token: '}' }, + ], + EnumValueDefinition: [ + { ofType: 'Description', optional: true }, + 'EnumValue', + { ofType: 'Directives', optional: true }, + ], + + EnumTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'enum', + tokenName: 'EnumDefinitionKeyword', + }, + 'TypeName', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'EnumValuesDefinition', optional: true }, + ], + }, + { + ifCondition: { token: '{' }, + expect: 'EnumValuesDefinition', + }, + ], + }, + ], + + InputObjectTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'input', + tokenName: 'InputDefinitionKeyword', + }, + 'TypeName', + { ofType: 'Directives', optional: true }, + { ofType: 'InputFieldsDefinition', optional: true }, + ], + InputFieldsDefinition: [ + { token: '{' }, + { listOfType: 'InputValueDefinition' }, + { token: '}' }, + ], + + InputObjectTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'input', + tokenName: 'InputDefinitionKeyword', + }, + 'TypeName', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'InputFieldsDefinition', optional: true }, + ], + }, + { + ifCondition: { token: '{' }, + expect: 'InputFieldsDefinition', + }, + ], + }, + ], + + DirectiveDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'directive', + tokenName: 'DirectiveDefinitionKeyword', + }, + { token: '@', tokenName: 'DirectiveName' }, + { token: 'Name', tokenName: 'DirectiveName' }, + { ofType: 'ArgumentsDefinition', optional: true }, + { token: 'Name', ofValue: 'on', tokenName: 'OnKeyword' }, + 'DirectiveLocations', + ], + DirectiveLocations: [ + { token: '|', optional: true }, + 'DirectiveLocation', + { + listOfType: 'DirectiveLocationAdditionalName', + optional: true, + }, + ], + DirectiveLocationAdditionalName: [{ token: '|' }, 'DirectiveLocation'], + DirectiveLocation: { + peek: [ + { + ifCondition: 'ExecutableDirectiveLocation', + expect: 'ExecutableDirectiveLocation', + }, + { + ifCondition: 'TypeSystemDirectiveLocation', + expect: 'TypeSystemDirectiveLocation', + }, + ], + }, + ExecutableDirectiveLocation: { + token: 'Name', + oneOf: [ + 'QUERY', + 'MUTATION', + 'SUBSCRIPTION', + 'FIELD', + 'FRAGMENT_DEFINITION', + 'FRAGMENT_SPREAD', + 'INLINE_FRAGMENT', + ], + tokenName: 'EnumValue', + }, + TypeSystemDirectiveLocation: { + token: 'Name', + oneOf: [ + 'SCHEMA', + 'SCALAR', + 'OBJECT', + 'FIELD_DEFINITION', + 'ARGUMENT_DEFINITION', + 'INTERFACE', + 'UNION', + 'ENUM', + 'ENUM_VALUE', + 'INPUT_OBJECT', + 'INPUT_FIELD_DEFINITION', + ], + tokenName: 'EnumValue', + }, +}; + +export default grammar; diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/grammar.js b/school/node_modules/graphql/language/experimentalOnlineParser/grammar.js new file mode 100644 index 0000000..45c8f7a --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/grammar.js @@ -0,0 +1,987 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var grammar = { + Name: { + token: 'Name' + }, + String: { + token: 'String' + }, + BlockString: { + token: 'BlockString' + }, + Document: { + listOfType: 'Definition' + }, + Definition: { + peek: [{ + ifCondition: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'] + }, + expect: 'OperationDefinition' + }, { + ifCondition: { + token: 'Name', + ofValue: 'fragment' + }, + expect: 'FragmentDefinition' + }, { + ifCondition: { + token: 'Name', + oneOf: ['schema', 'scalar', 'type', 'interface', 'union', 'enum', 'input', 'directive'] + }, + expect: 'TypeSystemDefinition' + }, { + ifCondition: { + token: 'Name', + ofValue: 'extend' + }, + expect: 'TypeSystemExtension' + }, { + ifCondition: { + token: '{' + }, + expect: 'OperationDefinition' + }, { + ifCondition: 'String', + expect: 'TypeSystemDefinition' + }, { + ifCondition: 'BlockString', + expect: 'TypeSystemDefinition' + }] + }, + OperationDefinition: { + peek: [{ + ifCondition: { + token: '{' + }, + expect: 'SelectionSet' + }, { + ifCondition: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'] + }, + expect: ['OperationType', { + token: 'Name', + optional: true, + tokenName: 'OperationName', + definitionName: true + }, { + ofType: 'VariableDefinitions', + optional: true + }, { + ofType: 'Directives', + optional: true + }, 'SelectionSet'] + }] + }, + OperationType: { + ofType: 'OperationTypeName' + }, + OperationTypeName: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'], + definitionName: true + }, + SelectionSet: [{ + token: '{' + }, { + listOfType: 'Selection' + }, { + token: '}' + }], + Selection: { + peek: [{ + ifCondition: { + token: '...' + }, + expect: 'Fragment' + }, { + ifCondition: { + token: 'Name' + }, + expect: 'Field' + }] + }, + Field: [{ + ofType: 'Alias', + optional: true, + eatNextOnFail: true, + definitionName: true + }, { + token: 'Name', + tokenName: 'FieldName', + definitionName: true + }, { + ofType: 'Arguments', + optional: true + }, { + ofType: 'Directives', + optional: true + }, { + ofType: 'SelectionSet', + optional: true + }], + Arguments: [{ + token: '(' + }, { + listOfType: 'Argument' + }, { + token: ')' + }], + Argument: [{ + token: 'Name', + tokenName: 'ArgumentName', + definitionName: true + }, { + token: ':' + }, 'Value'], + Alias: [{ + token: 'Name', + tokenName: 'AliasName', + definitionName: true + }, { + token: ':' + }], + Fragment: [{ + token: '...' + }, { + peek: [{ + ifCondition: 'FragmentName', + expect: 'FragmentSpread' + }, { + ifCondition: { + token: 'Name', + ofValue: 'on' + }, + expect: 'InlineFragment' + }, { + ifCondition: { + token: '@' + }, + expect: 'InlineFragment' + }, { + ifCondition: { + token: '{' + }, + expect: 'InlineFragment' + }] + }], + FragmentSpread: ['FragmentName', { + ofType: 'Directives', + optional: true + }], + FragmentDefinition: [{ + token: 'Name', + ofValue: 'fragment', + tokenName: 'FragmentDefinitionKeyword' + }, 'FragmentName', 'TypeCondition', { + ofType: 'Directives', + optional: true + }, 'SelectionSet'], + FragmentName: { + token: 'Name', + butNot: { + token: 'Name', + ofValue: 'on' + }, + definitionName: true + }, + TypeCondition: [{ + token: 'Name', + ofValue: 'on', + tokenName: 'OnKeyword' + }, 'TypeName'], + InlineFragment: [{ + ofType: 'TypeCondition', + optional: true + }, { + ofType: 'Directives', + optional: true + }, 'SelectionSet'], + Value: { + peek: [{ + ifCondition: { + token: '$' + }, + expect: 'Variable' + }, { + ifCondition: 'IntValue', + expect: { + ofType: 'IntValue', + tokenName: 'NumberValue' + } + }, { + ifCondition: 'FloatValue', + expect: { + ofType: 'FloatValue', + tokenName: 'NumberValue' + } + }, { + ifCondition: 'BooleanValue', + expect: { + ofType: 'BooleanValue', + tokenName: 'BooleanValue' + } + }, { + ifCondition: 'EnumValue', + expect: { + ofType: 'EnumValue', + tokenName: 'EnumValue' + } + }, { + ifCondition: 'String', + expect: { + ofType: 'String', + tokenName: 'StringValue' + } + }, { + ifCondition: 'BlockString', + expect: { + ofType: 'BlockString', + tokenName: 'StringValue' + } + }, { + ifCondition: 'NullValue', + expect: { + ofType: 'NullValue', + tokenName: 'NullValue' + } + }, { + ifCondition: { + token: '[' + }, + expect: 'ListValue' + }, { + ifCondition: { + token: '{' + }, + expect: 'ObjectValue' + }] + }, + ConstValue: { + peek: [{ + ifCondition: 'IntValue', + expect: { + ofType: 'IntValue' + } + }, { + ifCondition: 'FloatValue', + expect: { + ofType: 'FloatValue' + } + }, { + ifCondition: 'BooleanValue', + expect: 'BooleanValue' + }, { + ifCondition: 'EnumValue', + expect: 'EnumValue' + }, { + ifCondition: 'String', + expect: { + ofType: 'String', + tokenName: 'StringValue' + } + }, { + ifCondition: 'BlockString', + expect: { + token: 'BlockString', + tokenName: 'StringValue' + } + }, { + ifCondition: 'NullValue', + expect: 'NullValue' + }, { + ifCondition: { + token: '[' + }, + expect: 'ConstListValue' + }, { + ifCondition: { + token: '{' + }, + expect: 'ObjectValue' + }] + }, + IntValue: { + token: 'Int' + }, + FloatValue: { + token: 'Float' + }, + StringValue: { + peek: [{ + ifCondition: { + token: 'String' + }, + expect: { + token: 'String', + tokenName: 'StringValue' + } + }, { + ifCondition: { + token: 'BlockString' + }, + expect: { + token: 'BlockString', + tokenName: 'StringValue' + } + }] + }, + BooleanValue: { + token: 'Name', + oneOf: ['true', 'false'], + tokenName: 'BooleanValue' + }, + NullValue: { + token: 'Name', + ofValue: 'null', + tokenName: 'NullValue' + }, + EnumValue: { + token: 'Name', + butNot: { + token: 'Name', + oneOf: ['null', 'true', 'false'] + }, + tokenName: 'EnumValue' + }, + ListValue: [{ + token: '[' + }, { + listOfType: 'Value', + optional: true + }, { + token: ']' + }], + ConstListValue: [{ + token: '[' + }, { + listOfType: 'ConstValue', + optional: true + }, { + token: ']' + }], + ObjectValue: [{ + token: '{' + }, { + listOfType: 'ObjectField', + optional: true + }, { + token: '}' + }], + ObjectField: [{ + token: 'Name', + tokenName: 'ObjectFieldName' + }, { + token: ':' + }, { + ofType: 'ConstValue' + }], + Variable: [{ + token: '$', + tokenName: 'VariableName' + }, { + token: 'Name', + tokenName: 'VariableName' + }], + VariableDefinitions: [{ + token: '(' + }, { + listOfType: 'VariableDefinition' + }, { + token: ')' + }], + VariableDefinition: ['Variable', { + token: ':' + }, 'Type', { + ofType: 'DefaultValue', + optional: true + }], + DefaultValue: [{ + token: '=' + }, 'ConstValue'], + TypeName: { + token: 'Name', + tokenName: 'TypeName', + typeName: true + }, + Type: { + peek: [{ + ifCondition: { + token: 'Name' + }, + expect: ['TypeName', { + token: '!', + optional: true + }] + }, { + ifCondition: { + token: '[' + }, + expect: 'ListType' + }] + }, + ListType: [{ + token: '[' + }, { + listOfType: 'Type' + }, { + token: ']' + }, { + token: '!', + optional: true + }], + Directives: { + listOfType: 'Directive' + }, + Directive: [{ + token: '@', + tokenName: 'DirectiveName' + }, { + token: 'Name', + tokenName: 'DirectiveName' + }, { + ofType: 'Arguments', + optional: true + }], + TypeSystemDefinition: [{ + ofType: 'Description', + optional: true + }, { + peek: [{ + ifCondition: { + target: 'Name', + ofValue: 'schema' + }, + expect: 'SchemaDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'scalar' + }, + expect: 'ScalarTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'type' + }, + expect: 'ObjectTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'interface' + }, + expect: 'InterfaceTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'union' + }, + expect: 'UnionTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'enum' + }, + expect: 'EnumTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'input' + }, + expect: 'InputObjectTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'directive' + }, + expect: 'DirectiveDefinition' + }] + }], + TypeSystemExtension: { + peek: [{ + ifCondition: { + target: 'Name', + ofValue: 'schema' + }, + expect: 'SchemaExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'scalar' + }, + expect: 'ScalarTypeExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'type' + }, + expect: 'ObjectTypeExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'interface' + }, + expect: 'InterfaceTypeExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'union' + }, + expect: 'UnionTypeExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'enum' + }, + expect: 'EnumTypeExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'input' + }, + expect: 'InputObjectTypeExtension' + }] + }, + SchemaDefinition: [{ + token: 'Name', + ofValue: 'schema', + tokenName: 'SchemaDefinitionKeyword' + }, { + ofType: 'Directives', + optional: true + }, { + token: '{' + }, { + listOfType: 'RootOperationTypeDefinition' + }, { + token: '}' + }], + RootOperationTypeDefinition: ['OperationType', { + token: ':' + }, { + token: 'Name', + tokenName: 'OperationTypeDefinitionName' + }], + SchemaExtension: [{ + token: 'Name', + ofValue: 'extend' + }, { + token: 'Name', + ofValue: 'schema' + }, 'Name', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: [{ + token: '{' + }, { + listOfType: 'RootOperationTypeDefinition' + }, { + token: '}' + }], + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: [{ + token: '{' + }, { + listOfType: 'RootOperationTypeDefinition' + }, { + token: '}' + }] + }] + }], + Description: 'StringValue', + ScalarTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'scalar', + tokenName: 'ScalarDefinitionKeyword' + }, 'TypeName', { + ofType: 'Directives', + optional: true + }], + ScalarTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'scalar', + tokenName: 'ScalarDefinitionKeyword' + }, 'TypeName', 'Directives'], + ObjectTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'type', + tokenName: 'TypeDefinitionKeyword' + }, 'TypeName', { + ofType: 'ImplementsInterfaces', + optional: true + }, { + ofType: 'Directives', + optional: true + }, { + ofType: 'FieldsDefinition', + optional: true + }], + ImplementsInterfaces: [{ + token: 'Name', + ofValue: 'implements', + tokenName: 'ImplementsKeyword' + }, { + token: '&', + optional: true + }, 'TypeName', { + listOfType: 'ImplementsAdditionalInterfaceName', + optional: true + }], + ImplementsAdditionalInterfaceName: [{ + token: '&' + }, 'TypeName'], + FieldsDefinition: [{ + token: '{' + }, { + listOfType: 'FieldDefinition' + }, { + token: '}' + }], + FieldDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + tokenName: 'AliasName', + definitionName: true + }, { + ofType: 'ArgumentsDefinition', + optional: true + }, { + token: ':' + }, 'Type', { + ofType: 'Directives', + optional: true + }], + ArgumentsDefinition: [{ + token: '(' + }, { + listOfType: 'InputValueDefinition' + }, { + token: ')' + }], + InputValueDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + tokenName: 'ArgumentName' + }, { + token: ':' + }, 'Type', { + ofType: 'DefaultValue', + optional: true + }, { + ofType: 'Directives', + optional: true + }], + ObjectTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'type', + tokenName: 'TypeDefinitionKeyword' + }, 'TypeName', { + peek: [{ + ifCondition: { + token: 'Name', + ofValue: 'interface' + }, + expect: ['ImplementsInterfaces', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'FieldsDefinition', + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: 'FieldsDefinition' + }], + optional: true + }] + }, { + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'FieldsDefinition', + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: 'FieldsDefinition' + }] + }], + InterfaceTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'interface', + tokenName: 'InterfaceDefinitionKeyword' + }, 'TypeName', { + ofType: 'Directives', + optional: true + }, { + ofType: 'FieldsDefinition', + optional: true + }], + InterfaceTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'interface', + tokenName: 'InterfaceDefinitionKeyword' + }, 'TypeName', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'FieldsDefinition', + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: 'FieldsDefinition' + }] + }], + UnionTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'union', + tokenName: 'UnionDefinitionKeyword' + }, 'TypeName', { + ofType: 'Directives', + optional: true + }, { + ofType: 'UnionMemberTypes', + optional: true + }], + UnionMemberTypes: [{ + token: '=' + }, { + token: '|', + optional: true + }, 'Name', { + listOfType: 'UnionMemberAdditionalTypeName', + optional: true + }], + UnionMemberAdditionalTypeName: [{ + token: '|' + }, 'TypeName'], + UnionTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'union', + tokenName: 'UnionDefinitionKeyword' + }, 'TypeName', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'UnionMemberTypes', + optional: true + }] + }, { + ifCondition: { + token: '=' + }, + expect: 'UnionMemberTypes' + }] + }], + EnumTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'enum', + tokenName: 'EnumDefinitionKeyword' + }, 'TypeName', { + ofType: 'Directives', + optional: true + }, { + ofType: 'EnumValuesDefinition', + optional: true + }], + EnumValuesDefinition: [{ + token: '{' + }, { + listOfType: 'EnumValueDefinition' + }, { + token: '}' + }], + EnumValueDefinition: [{ + ofType: 'Description', + optional: true + }, 'EnumValue', { + ofType: 'Directives', + optional: true + }], + EnumTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'enum', + tokenName: 'EnumDefinitionKeyword' + }, 'TypeName', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'EnumValuesDefinition', + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: 'EnumValuesDefinition' + }] + }], + InputObjectTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'input', + tokenName: 'InputDefinitionKeyword' + }, 'TypeName', { + ofType: 'Directives', + optional: true + }, { + ofType: 'InputFieldsDefinition', + optional: true + }], + InputFieldsDefinition: [{ + token: '{' + }, { + listOfType: 'InputValueDefinition' + }, { + token: '}' + }], + InputObjectTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'input', + tokenName: 'InputDefinitionKeyword' + }, 'TypeName', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'InputFieldsDefinition', + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: 'InputFieldsDefinition' + }] + }], + DirectiveDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'directive', + tokenName: 'DirectiveDefinitionKeyword' + }, { + token: '@', + tokenName: 'DirectiveName' + }, { + token: 'Name', + tokenName: 'DirectiveName' + }, { + ofType: 'ArgumentsDefinition', + optional: true + }, { + token: 'Name', + ofValue: 'on', + tokenName: 'OnKeyword' + }, 'DirectiveLocations'], + DirectiveLocations: [{ + token: '|', + optional: true + }, 'DirectiveLocation', { + listOfType: 'DirectiveLocationAdditionalName', + optional: true + }], + DirectiveLocationAdditionalName: [{ + token: '|' + }, 'DirectiveLocation'], + DirectiveLocation: { + peek: [{ + ifCondition: 'ExecutableDirectiveLocation', + expect: 'ExecutableDirectiveLocation' + }, { + ifCondition: 'TypeSystemDirectiveLocation', + expect: 'TypeSystemDirectiveLocation' + }] + }, + ExecutableDirectiveLocation: { + token: 'Name', + oneOf: ['QUERY', 'MUTATION', 'SUBSCRIPTION', 'FIELD', 'FRAGMENT_DEFINITION', 'FRAGMENT_SPREAD', 'INLINE_FRAGMENT'], + tokenName: 'EnumValue' + }, + TypeSystemDirectiveLocation: { + token: 'Name', + oneOf: ['SCHEMA', 'SCALAR', 'OBJECT', 'FIELD_DEFINITION', 'ARGUMENT_DEFINITION', 'INTERFACE', 'UNION', 'ENUM', 'ENUM_VALUE', 'INPUT_OBJECT', 'INPUT_FIELD_DEFINITION'], + tokenName: 'EnumValue' + } // FIXME: enforce proper typing + +}; +var _default = grammar; +exports.default = _default; diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/grammar.js.flow b/school/node_modules/graphql/language/experimentalOnlineParser/grammar.js.flow new file mode 100644 index 0000000..f1d2f10 --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/grammar.js.flow @@ -0,0 +1,1000 @@ +// @flow strict +export type GraphQLGrammarType = {| + [name: string]: GraphQLGrammarRule, +|}; +export type GraphQLGrammarRuleName = string; +export type GraphQLGrammarRuleConstraint = + | GraphQLGrammarTokenConstraint + | GraphQLGrammarOfTypeConstraint + | GraphQLGrammarListOfTypeConstraint + | GraphQLGrammarPeekConstraint; +export type GraphQLGrammarConstraintsSet = Array< + GraphQLGrammarRuleName | GraphQLGrammarRuleConstraint, +>; +export type GraphQLGrammarRule = + | GraphQLGrammarRuleName + | GraphQLGrammarRuleConstraint + | GraphQLGrammarConstraintsSet; +export interface GraphQLGrammarBaseRuleConstraint { + butNot?: + | ?GraphQLGrammarTokenConstraint + | ?Array<GraphQLGrammarTokenConstraint>; + optional?: boolean; + eatNextOnFail?: boolean; +} +export interface GraphQLGrammarTokenConstraint + extends GraphQLGrammarBaseRuleConstraint { + token: + | '!' + | '$' + | '&' + | '(' + | ')' + | '...' + | ':' + | '=' + | '@' + | '[' + | ']' + | '{' + | '}' + | '|' + | 'Name' + | 'Int' + | 'Float' + | 'String' + | 'BlockString' + | 'Comment'; + ofValue?: ?string; + oneOf?: ?Array<string>; + tokenName?: string; + definitionName?: boolean; + typeName?: boolean; +} +export interface GraphQLGrammarOfTypeConstraint + extends GraphQLGrammarBaseRuleConstraint { + ofType: GraphQLGrammarRule; + tokenName?: string; +} +export interface GraphQLGrammarListOfTypeConstraint + extends GraphQLGrammarBaseRuleConstraint { + listOfType: GraphQLGrammarRuleName; +} +export interface GraphQLGrammarPeekConstraint + extends GraphQLGrammarBaseRuleConstraint { + peek: Array<GraphQLGrammarPeekConstraintCondition>; +} +export interface GraphQLGrammarPeekConstraintCondition { + ifCondition: GraphQLGrammarTokenConstraint; + expect: GraphQLGrammarRule; + end?: boolean; +} + +const grammar: GraphQLGrammarType = ({ + Name: { token: 'Name' }, + String: { token: 'String' }, + BlockString: { token: 'BlockString' }, + + Document: { listOfType: 'Definition' }, + Definition: { + peek: [ + { + ifCondition: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'], + }, + expect: 'OperationDefinition', + }, + { + ifCondition: { token: 'Name', ofValue: 'fragment' }, + expect: 'FragmentDefinition', + }, + { + ifCondition: { + token: 'Name', + oneOf: [ + 'schema', + 'scalar', + 'type', + 'interface', + 'union', + 'enum', + 'input', + 'directive', + ], + }, + expect: 'TypeSystemDefinition', + }, + { + ifCondition: { token: 'Name', ofValue: 'extend' }, + expect: 'TypeSystemExtension', + }, + { + ifCondition: { token: '{' }, + expect: 'OperationDefinition', + }, + { + ifCondition: 'String', + expect: 'TypeSystemDefinition', + }, + { + ifCondition: 'BlockString', + expect: 'TypeSystemDefinition', + }, + ], + }, + + OperationDefinition: { + peek: [ + { + ifCondition: { token: '{' }, + expect: 'SelectionSet', + }, + { + ifCondition: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'], + }, + expect: [ + 'OperationType', + { + token: 'Name', + optional: true, + tokenName: 'OperationName', + definitionName: true, + }, + { ofType: 'VariableDefinitions', optional: true }, + { ofType: 'Directives', optional: true }, + 'SelectionSet', + ], + }, + ], + }, + OperationType: { + ofType: 'OperationTypeName', + }, + OperationTypeName: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'], + definitionName: true, + }, + SelectionSet: [{ token: '{' }, { listOfType: 'Selection' }, { token: '}' }], + Selection: { + peek: [ + { + ifCondition: { token: '...' }, + expect: 'Fragment', + }, + { + ifCondition: { token: 'Name' }, + expect: 'Field', + }, + ], + }, + + Field: [ + { + ofType: 'Alias', + optional: true, + eatNextOnFail: true, + definitionName: true, + }, + { token: 'Name', tokenName: 'FieldName', definitionName: true }, + { ofType: 'Arguments', optional: true }, + { ofType: 'Directives', optional: true }, + { ofType: 'SelectionSet', optional: true }, + ], + + Arguments: [{ token: '(' }, { listOfType: 'Argument' }, { token: ')' }], + Argument: [ + { token: 'Name', tokenName: 'ArgumentName', definitionName: true }, + { token: ':' }, + 'Value', + ], + + Alias: [ + { token: 'Name', tokenName: 'AliasName', definitionName: true }, + { token: ':' }, + ], + + Fragment: [ + { token: '...' }, + { + peek: [ + { + ifCondition: 'FragmentName', + expect: 'FragmentSpread', + }, + { + ifCondition: { token: 'Name', ofValue: 'on' }, + expect: 'InlineFragment', + }, + { + ifCondition: { token: '@' }, + expect: 'InlineFragment', + }, + { + ifCondition: { token: '{' }, + expect: 'InlineFragment', + }, + ], + }, + ], + + FragmentSpread: ['FragmentName', { ofType: 'Directives', optional: true }], + FragmentDefinition: [ + { + token: 'Name', + ofValue: 'fragment', + tokenName: 'FragmentDefinitionKeyword', + }, + 'FragmentName', + 'TypeCondition', + { ofType: 'Directives', optional: true }, + 'SelectionSet', + ], + FragmentName: { + token: 'Name', + butNot: { token: 'Name', ofValue: 'on' }, + definitionName: true, + }, + + TypeCondition: [ + { token: 'Name', ofValue: 'on', tokenName: 'OnKeyword' }, + 'TypeName', + ], + + InlineFragment: [ + { ofType: 'TypeCondition', optional: true }, + { ofType: 'Directives', optional: true }, + 'SelectionSet', + ], + + Value: { + peek: [ + { + ifCondition: { token: '$' }, + expect: 'Variable', + }, + { + ifCondition: 'IntValue', + expect: { ofType: 'IntValue', tokenName: 'NumberValue' }, + }, + { + ifCondition: 'FloatValue', + expect: { ofType: 'FloatValue', tokenName: 'NumberValue' }, + }, + { + ifCondition: 'BooleanValue', + expect: { ofType: 'BooleanValue', tokenName: 'BooleanValue' }, + }, + { + ifCondition: 'EnumValue', + expect: { ofType: 'EnumValue', tokenName: 'EnumValue' }, + }, + { + ifCondition: 'String', + expect: { ofType: 'String', tokenName: 'StringValue' }, + }, + { + ifCondition: 'BlockString', + expect: { ofType: 'BlockString', tokenName: 'StringValue' }, + }, + { + ifCondition: 'NullValue', + expect: { ofType: 'NullValue', tokenName: 'NullValue' }, + }, + { + ifCondition: { token: '[' }, + expect: 'ListValue', + }, + { + ifCondition: { token: '{' }, + expect: 'ObjectValue', + }, + ], + }, + + ConstValue: { + peek: [ + { + ifCondition: 'IntValue', + expect: { ofType: 'IntValue' }, + }, + { + ifCondition: 'FloatValue', + expect: { ofType: 'FloatValue' }, + }, + { + ifCondition: 'BooleanValue', + expect: 'BooleanValue', + }, + { + ifCondition: 'EnumValue', + expect: 'EnumValue', + }, + { + ifCondition: 'String', + expect: { ofType: 'String', tokenName: 'StringValue' }, + }, + { + ifCondition: 'BlockString', + expect: { token: 'BlockString', tokenName: 'StringValue' }, + }, + { + ifCondition: 'NullValue', + expect: 'NullValue', + }, + { + ifCondition: { token: '[' }, + expect: 'ConstListValue', + }, + { + ifCondition: { token: '{' }, + expect: 'ObjectValue', + }, + ], + }, + + IntValue: { token: 'Int' }, + + FloatValue: { token: 'Float' }, + + StringValue: { + peek: [ + { + ifCondition: { token: 'String' }, + expect: { token: 'String', tokenName: 'StringValue' }, + }, + { + ifCondition: { token: 'BlockString' }, + expect: { token: 'BlockString', tokenName: 'StringValue' }, + }, + ], + }, + + BooleanValue: { + token: 'Name', + oneOf: ['true', 'false'], + tokenName: 'BooleanValue', + }, + + NullValue: { + token: 'Name', + ofValue: 'null', + tokenName: 'NullValue', + }, + + EnumValue: { + token: 'Name', + butNot: { token: 'Name', oneOf: ['null', 'true', 'false'] }, + tokenName: 'EnumValue', + }, + + ListValue: [ + { token: '[' }, + { listOfType: 'Value', optional: true }, + { token: ']' }, + ], + + ConstListValue: [ + { token: '[' }, + { listOfType: 'ConstValue', optional: true }, + { token: ']' }, + ], + + ObjectValue: [ + { token: '{' }, + { listOfType: 'ObjectField', optional: true }, + { token: '}' }, + ], + ObjectField: [ + { token: 'Name', tokenName: 'ObjectFieldName' }, + { token: ':' }, + { ofType: 'ConstValue' }, + ], + + Variable: [ + { token: '$', tokenName: 'VariableName' }, + { token: 'Name', tokenName: 'VariableName' }, + ], + VariableDefinitions: [ + { token: '(' }, + { listOfType: 'VariableDefinition' }, + { token: ')' }, + ], + VariableDefinition: [ + 'Variable', + { token: ':' }, + 'Type', + { ofType: 'DefaultValue', optional: true }, + ], + DefaultValue: [{ token: '=' }, 'ConstValue'], + + TypeName: { token: 'Name', tokenName: 'TypeName', typeName: true }, + + Type: { + peek: [ + { + ifCondition: { token: 'Name' }, + expect: ['TypeName', { token: '!', optional: true }], + }, + { + ifCondition: { token: '[' }, + expect: 'ListType', + }, + ], + }, + ListType: [ + { token: '[' }, + { listOfType: 'Type' }, + { token: ']' }, + { token: '!', optional: true }, + ], + + Directives: { listOfType: 'Directive' }, + Directive: [ + { token: '@', tokenName: 'DirectiveName' }, + { token: 'Name', tokenName: 'DirectiveName' }, + { ofType: 'Arguments', optional: true }, + ], + + TypeSystemDefinition: [ + { ofType: 'Description', optional: true }, + { + peek: [ + { + ifCondition: { + target: 'Name', + ofValue: 'schema', + }, + expect: 'SchemaDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'scalar', + }, + expect: 'ScalarTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'type', + }, + expect: 'ObjectTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'interface', + }, + expect: 'InterfaceTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'union', + }, + expect: 'UnionTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'enum', + }, + expect: 'EnumTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'input', + }, + expect: 'InputObjectTypeDefinition', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'directive', + }, + expect: 'DirectiveDefinition', + }, + ], + }, + ], + + TypeSystemExtension: { + peek: [ + { + ifCondition: { + target: 'Name', + ofValue: 'schema', + }, + expect: 'SchemaExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'scalar', + }, + expect: 'ScalarTypeExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'type', + }, + expect: 'ObjectTypeExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'interface', + }, + expect: 'InterfaceTypeExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'union', + }, + expect: 'UnionTypeExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'enum', + }, + expect: 'EnumTypeExtension', + }, + { + ifCondition: { + target: 'Name', + ofValue: 'input', + }, + expect: 'InputObjectTypeExtension', + }, + ], + }, + + SchemaDefinition: [ + { + token: 'Name', + ofValue: 'schema', + tokenName: 'SchemaDefinitionKeyword', + }, + { ofType: 'Directives', optional: true }, + { token: '{' }, + { listOfType: 'RootOperationTypeDefinition' }, + { token: '}' }, + ], + RootOperationTypeDefinition: [ + 'OperationType', + { token: ':' }, + { token: 'Name', tokenName: 'OperationTypeDefinitionName' }, + ], + + SchemaExtension: [ + { token: 'Name', ofValue: 'extend' }, + { token: 'Name', ofValue: 'schema' }, + 'Name', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { + ofType: [ + { token: '{' }, + { listOfType: 'RootOperationTypeDefinition' }, + { token: '}' }, + ], + optional: true, + }, + ], + }, + { + ifCondition: { token: '{' }, + expect: [ + { token: '{' }, + { listOfType: 'RootOperationTypeDefinition' }, + { token: '}' }, + ], + }, + ], + }, + ], + + Description: 'StringValue', + + ScalarTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'scalar', + tokenName: 'ScalarDefinitionKeyword', + }, + 'TypeName', + { ofType: 'Directives', optional: true }, + ], + + ScalarTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'scalar', + tokenName: 'ScalarDefinitionKeyword', + }, + 'TypeName', + 'Directives', + ], + + ObjectTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'type', + tokenName: 'TypeDefinitionKeyword', + }, + 'TypeName', + { ofType: 'ImplementsInterfaces', optional: true }, + { ofType: 'Directives', optional: true }, + { ofType: 'FieldsDefinition', optional: true }, + ], + ImplementsInterfaces: [ + { + token: 'Name', + ofValue: 'implements', + tokenName: 'ImplementsKeyword', + }, + { token: '&', optional: true }, + 'TypeName', + { + listOfType: 'ImplementsAdditionalInterfaceName', + optional: true, + }, + ], + ImplementsAdditionalInterfaceName: [{ token: '&' }, 'TypeName'], + FieldsDefinition: [ + { token: '{' }, + { listOfType: 'FieldDefinition' }, + { token: '}' }, + ], + FieldDefinition: [ + { ofType: 'Description', optional: true }, + { token: 'Name', tokenName: 'AliasName', definitionName: true }, + { ofType: 'ArgumentsDefinition', optional: true }, + { token: ':' }, + 'Type', + { ofType: 'Directives', optional: true }, + ], + + ArgumentsDefinition: [ + { token: '(' }, + { listOfType: 'InputValueDefinition' }, + { token: ')' }, + ], + InputValueDefinition: [ + { ofType: 'Description', optional: true }, + { token: 'Name', tokenName: 'ArgumentName' }, + { token: ':' }, + 'Type', + { ofType: 'DefaultValue', optional: true }, + { ofType: 'Directives', optional: true }, + ], + + ObjectTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'type', + tokenName: 'TypeDefinitionKeyword', + }, + 'TypeName', + { + peek: [ + { + ifCondition: { token: 'Name', ofValue: 'interface' }, + expect: [ + 'ImplementsInterfaces', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'FieldsDefinition', optional: true }, + ], + }, + { + ifCondition: { token: '{' }, + expect: 'FieldsDefinition', + }, + ], + optional: true, + }, + ], + }, + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'FieldsDefinition', optional: true }, + ], + }, + { + ifCondition: { token: '{' }, + expect: 'FieldsDefinition', + }, + ], + }, + ], + + InterfaceTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'interface', + tokenName: 'InterfaceDefinitionKeyword', + }, + 'TypeName', + { ofType: 'Directives', optional: true }, + { ofType: 'FieldsDefinition', optional: true }, + ], + + InterfaceTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'interface', + tokenName: 'InterfaceDefinitionKeyword', + }, + 'TypeName', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'FieldsDefinition', optional: true }, + ], + }, + { + ifCondition: { token: '{' }, + expect: 'FieldsDefinition', + }, + ], + }, + ], + + UnionTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'union', + tokenName: 'UnionDefinitionKeyword', + }, + 'TypeName', + { ofType: 'Directives', optional: true }, + { ofType: 'UnionMemberTypes', optional: true }, + ], + + UnionMemberTypes: [ + { token: '=' }, + { token: '|', optional: true }, + 'Name', + { + listOfType: 'UnionMemberAdditionalTypeName', + optional: true, + }, + ], + + UnionMemberAdditionalTypeName: [{ token: '|' }, 'TypeName'], + + UnionTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'union', + tokenName: 'UnionDefinitionKeyword', + }, + 'TypeName', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'UnionMemberTypes', optional: true }, + ], + }, + { + ifCondition: { token: '=' }, + expect: 'UnionMemberTypes', + }, + ], + }, + ], + + EnumTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'enum', + tokenName: 'EnumDefinitionKeyword', + }, + 'TypeName', + { ofType: 'Directives', optional: true }, + { ofType: 'EnumValuesDefinition', optional: true }, + ], + EnumValuesDefinition: [ + { token: '{' }, + { listOfType: 'EnumValueDefinition' }, + { token: '}' }, + ], + EnumValueDefinition: [ + { ofType: 'Description', optional: true }, + 'EnumValue', + { ofType: 'Directives', optional: true }, + ], + + EnumTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'enum', + tokenName: 'EnumDefinitionKeyword', + }, + 'TypeName', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'EnumValuesDefinition', optional: true }, + ], + }, + { + ifCondition: { token: '{' }, + expect: 'EnumValuesDefinition', + }, + ], + }, + ], + + InputObjectTypeDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'input', + tokenName: 'InputDefinitionKeyword', + }, + 'TypeName', + { ofType: 'Directives', optional: true }, + { ofType: 'InputFieldsDefinition', optional: true }, + ], + InputFieldsDefinition: [ + { token: '{' }, + { listOfType: 'InputValueDefinition' }, + { token: '}' }, + ], + + InputObjectTypeExtension: [ + { + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword', + }, + { + token: 'Name', + ofValue: 'input', + tokenName: 'InputDefinitionKeyword', + }, + 'TypeName', + { + peek: [ + { + ifCondition: { token: '@' }, + expect: [ + 'Directives', + { ofType: 'InputFieldsDefinition', optional: true }, + ], + }, + { + ifCondition: { token: '{' }, + expect: 'InputFieldsDefinition', + }, + ], + }, + ], + + DirectiveDefinition: [ + { ofType: 'Description', optional: true }, + { + token: 'Name', + ofValue: 'directive', + tokenName: 'DirectiveDefinitionKeyword', + }, + { token: '@', tokenName: 'DirectiveName' }, + { token: 'Name', tokenName: 'DirectiveName' }, + { ofType: 'ArgumentsDefinition', optional: true }, + { token: 'Name', ofValue: 'on', tokenName: 'OnKeyword' }, + 'DirectiveLocations', + ], + DirectiveLocations: [ + { token: '|', optional: true }, + 'DirectiveLocation', + { + listOfType: 'DirectiveLocationAdditionalName', + optional: true, + }, + ], + DirectiveLocationAdditionalName: [{ token: '|' }, 'DirectiveLocation'], + DirectiveLocation: { + peek: [ + { + ifCondition: 'ExecutableDirectiveLocation', + expect: 'ExecutableDirectiveLocation', + }, + { + ifCondition: 'TypeSystemDirectiveLocation', + expect: 'TypeSystemDirectiveLocation', + }, + ], + }, + ExecutableDirectiveLocation: { + token: 'Name', + oneOf: [ + 'QUERY', + 'MUTATION', + 'SUBSCRIPTION', + 'FIELD', + 'FRAGMENT_DEFINITION', + 'FRAGMENT_SPREAD', + 'INLINE_FRAGMENT', + ], + tokenName: 'EnumValue', + }, + TypeSystemDirectiveLocation: { + token: 'Name', + oneOf: [ + 'SCHEMA', + 'SCALAR', + 'OBJECT', + 'FIELD_DEFINITION', + 'ARGUMENT_DEFINITION', + 'INTERFACE', + 'UNION', + 'ENUM', + 'ENUM_VALUE', + 'INPUT_OBJECT', + 'INPUT_FIELD_DEFINITION', + ], + tokenName: 'EnumValue', + }, + // FIXME: enforce proper typing +}: any); + +export default grammar; diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/grammar.mjs b/school/node_modules/graphql/language/experimentalOnlineParser/grammar.mjs new file mode 100644 index 0000000..a31907e --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/grammar.mjs @@ -0,0 +1,980 @@ +var grammar = { + Name: { + token: 'Name' + }, + String: { + token: 'String' + }, + BlockString: { + token: 'BlockString' + }, + Document: { + listOfType: 'Definition' + }, + Definition: { + peek: [{ + ifCondition: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'] + }, + expect: 'OperationDefinition' + }, { + ifCondition: { + token: 'Name', + ofValue: 'fragment' + }, + expect: 'FragmentDefinition' + }, { + ifCondition: { + token: 'Name', + oneOf: ['schema', 'scalar', 'type', 'interface', 'union', 'enum', 'input', 'directive'] + }, + expect: 'TypeSystemDefinition' + }, { + ifCondition: { + token: 'Name', + ofValue: 'extend' + }, + expect: 'TypeSystemExtension' + }, { + ifCondition: { + token: '{' + }, + expect: 'OperationDefinition' + }, { + ifCondition: 'String', + expect: 'TypeSystemDefinition' + }, { + ifCondition: 'BlockString', + expect: 'TypeSystemDefinition' + }] + }, + OperationDefinition: { + peek: [{ + ifCondition: { + token: '{' + }, + expect: 'SelectionSet' + }, { + ifCondition: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'] + }, + expect: ['OperationType', { + token: 'Name', + optional: true, + tokenName: 'OperationName', + definitionName: true + }, { + ofType: 'VariableDefinitions', + optional: true + }, { + ofType: 'Directives', + optional: true + }, 'SelectionSet'] + }] + }, + OperationType: { + ofType: 'OperationTypeName' + }, + OperationTypeName: { + token: 'Name', + oneOf: ['query', 'mutation', 'subscription'], + definitionName: true + }, + SelectionSet: [{ + token: '{' + }, { + listOfType: 'Selection' + }, { + token: '}' + }], + Selection: { + peek: [{ + ifCondition: { + token: '...' + }, + expect: 'Fragment' + }, { + ifCondition: { + token: 'Name' + }, + expect: 'Field' + }] + }, + Field: [{ + ofType: 'Alias', + optional: true, + eatNextOnFail: true, + definitionName: true + }, { + token: 'Name', + tokenName: 'FieldName', + definitionName: true + }, { + ofType: 'Arguments', + optional: true + }, { + ofType: 'Directives', + optional: true + }, { + ofType: 'SelectionSet', + optional: true + }], + Arguments: [{ + token: '(' + }, { + listOfType: 'Argument' + }, { + token: ')' + }], + Argument: [{ + token: 'Name', + tokenName: 'ArgumentName', + definitionName: true + }, { + token: ':' + }, 'Value'], + Alias: [{ + token: 'Name', + tokenName: 'AliasName', + definitionName: true + }, { + token: ':' + }], + Fragment: [{ + token: '...' + }, { + peek: [{ + ifCondition: 'FragmentName', + expect: 'FragmentSpread' + }, { + ifCondition: { + token: 'Name', + ofValue: 'on' + }, + expect: 'InlineFragment' + }, { + ifCondition: { + token: '@' + }, + expect: 'InlineFragment' + }, { + ifCondition: { + token: '{' + }, + expect: 'InlineFragment' + }] + }], + FragmentSpread: ['FragmentName', { + ofType: 'Directives', + optional: true + }], + FragmentDefinition: [{ + token: 'Name', + ofValue: 'fragment', + tokenName: 'FragmentDefinitionKeyword' + }, 'FragmentName', 'TypeCondition', { + ofType: 'Directives', + optional: true + }, 'SelectionSet'], + FragmentName: { + token: 'Name', + butNot: { + token: 'Name', + ofValue: 'on' + }, + definitionName: true + }, + TypeCondition: [{ + token: 'Name', + ofValue: 'on', + tokenName: 'OnKeyword' + }, 'TypeName'], + InlineFragment: [{ + ofType: 'TypeCondition', + optional: true + }, { + ofType: 'Directives', + optional: true + }, 'SelectionSet'], + Value: { + peek: [{ + ifCondition: { + token: '$' + }, + expect: 'Variable' + }, { + ifCondition: 'IntValue', + expect: { + ofType: 'IntValue', + tokenName: 'NumberValue' + } + }, { + ifCondition: 'FloatValue', + expect: { + ofType: 'FloatValue', + tokenName: 'NumberValue' + } + }, { + ifCondition: 'BooleanValue', + expect: { + ofType: 'BooleanValue', + tokenName: 'BooleanValue' + } + }, { + ifCondition: 'EnumValue', + expect: { + ofType: 'EnumValue', + tokenName: 'EnumValue' + } + }, { + ifCondition: 'String', + expect: { + ofType: 'String', + tokenName: 'StringValue' + } + }, { + ifCondition: 'BlockString', + expect: { + ofType: 'BlockString', + tokenName: 'StringValue' + } + }, { + ifCondition: 'NullValue', + expect: { + ofType: 'NullValue', + tokenName: 'NullValue' + } + }, { + ifCondition: { + token: '[' + }, + expect: 'ListValue' + }, { + ifCondition: { + token: '{' + }, + expect: 'ObjectValue' + }] + }, + ConstValue: { + peek: [{ + ifCondition: 'IntValue', + expect: { + ofType: 'IntValue' + } + }, { + ifCondition: 'FloatValue', + expect: { + ofType: 'FloatValue' + } + }, { + ifCondition: 'BooleanValue', + expect: 'BooleanValue' + }, { + ifCondition: 'EnumValue', + expect: 'EnumValue' + }, { + ifCondition: 'String', + expect: { + ofType: 'String', + tokenName: 'StringValue' + } + }, { + ifCondition: 'BlockString', + expect: { + token: 'BlockString', + tokenName: 'StringValue' + } + }, { + ifCondition: 'NullValue', + expect: 'NullValue' + }, { + ifCondition: { + token: '[' + }, + expect: 'ConstListValue' + }, { + ifCondition: { + token: '{' + }, + expect: 'ObjectValue' + }] + }, + IntValue: { + token: 'Int' + }, + FloatValue: { + token: 'Float' + }, + StringValue: { + peek: [{ + ifCondition: { + token: 'String' + }, + expect: { + token: 'String', + tokenName: 'StringValue' + } + }, { + ifCondition: { + token: 'BlockString' + }, + expect: { + token: 'BlockString', + tokenName: 'StringValue' + } + }] + }, + BooleanValue: { + token: 'Name', + oneOf: ['true', 'false'], + tokenName: 'BooleanValue' + }, + NullValue: { + token: 'Name', + ofValue: 'null', + tokenName: 'NullValue' + }, + EnumValue: { + token: 'Name', + butNot: { + token: 'Name', + oneOf: ['null', 'true', 'false'] + }, + tokenName: 'EnumValue' + }, + ListValue: [{ + token: '[' + }, { + listOfType: 'Value', + optional: true + }, { + token: ']' + }], + ConstListValue: [{ + token: '[' + }, { + listOfType: 'ConstValue', + optional: true + }, { + token: ']' + }], + ObjectValue: [{ + token: '{' + }, { + listOfType: 'ObjectField', + optional: true + }, { + token: '}' + }], + ObjectField: [{ + token: 'Name', + tokenName: 'ObjectFieldName' + }, { + token: ':' + }, { + ofType: 'ConstValue' + }], + Variable: [{ + token: '$', + tokenName: 'VariableName' + }, { + token: 'Name', + tokenName: 'VariableName' + }], + VariableDefinitions: [{ + token: '(' + }, { + listOfType: 'VariableDefinition' + }, { + token: ')' + }], + VariableDefinition: ['Variable', { + token: ':' + }, 'Type', { + ofType: 'DefaultValue', + optional: true + }], + DefaultValue: [{ + token: '=' + }, 'ConstValue'], + TypeName: { + token: 'Name', + tokenName: 'TypeName', + typeName: true + }, + Type: { + peek: [{ + ifCondition: { + token: 'Name' + }, + expect: ['TypeName', { + token: '!', + optional: true + }] + }, { + ifCondition: { + token: '[' + }, + expect: 'ListType' + }] + }, + ListType: [{ + token: '[' + }, { + listOfType: 'Type' + }, { + token: ']' + }, { + token: '!', + optional: true + }], + Directives: { + listOfType: 'Directive' + }, + Directive: [{ + token: '@', + tokenName: 'DirectiveName' + }, { + token: 'Name', + tokenName: 'DirectiveName' + }, { + ofType: 'Arguments', + optional: true + }], + TypeSystemDefinition: [{ + ofType: 'Description', + optional: true + }, { + peek: [{ + ifCondition: { + target: 'Name', + ofValue: 'schema' + }, + expect: 'SchemaDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'scalar' + }, + expect: 'ScalarTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'type' + }, + expect: 'ObjectTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'interface' + }, + expect: 'InterfaceTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'union' + }, + expect: 'UnionTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'enum' + }, + expect: 'EnumTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'input' + }, + expect: 'InputObjectTypeDefinition' + }, { + ifCondition: { + target: 'Name', + ofValue: 'directive' + }, + expect: 'DirectiveDefinition' + }] + }], + TypeSystemExtension: { + peek: [{ + ifCondition: { + target: 'Name', + ofValue: 'schema' + }, + expect: 'SchemaExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'scalar' + }, + expect: 'ScalarTypeExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'type' + }, + expect: 'ObjectTypeExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'interface' + }, + expect: 'InterfaceTypeExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'union' + }, + expect: 'UnionTypeExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'enum' + }, + expect: 'EnumTypeExtension' + }, { + ifCondition: { + target: 'Name', + ofValue: 'input' + }, + expect: 'InputObjectTypeExtension' + }] + }, + SchemaDefinition: [{ + token: 'Name', + ofValue: 'schema', + tokenName: 'SchemaDefinitionKeyword' + }, { + ofType: 'Directives', + optional: true + }, { + token: '{' + }, { + listOfType: 'RootOperationTypeDefinition' + }, { + token: '}' + }], + RootOperationTypeDefinition: ['OperationType', { + token: ':' + }, { + token: 'Name', + tokenName: 'OperationTypeDefinitionName' + }], + SchemaExtension: [{ + token: 'Name', + ofValue: 'extend' + }, { + token: 'Name', + ofValue: 'schema' + }, 'Name', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: [{ + token: '{' + }, { + listOfType: 'RootOperationTypeDefinition' + }, { + token: '}' + }], + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: [{ + token: '{' + }, { + listOfType: 'RootOperationTypeDefinition' + }, { + token: '}' + }] + }] + }], + Description: 'StringValue', + ScalarTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'scalar', + tokenName: 'ScalarDefinitionKeyword' + }, 'TypeName', { + ofType: 'Directives', + optional: true + }], + ScalarTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'scalar', + tokenName: 'ScalarDefinitionKeyword' + }, 'TypeName', 'Directives'], + ObjectTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'type', + tokenName: 'TypeDefinitionKeyword' + }, 'TypeName', { + ofType: 'ImplementsInterfaces', + optional: true + }, { + ofType: 'Directives', + optional: true + }, { + ofType: 'FieldsDefinition', + optional: true + }], + ImplementsInterfaces: [{ + token: 'Name', + ofValue: 'implements', + tokenName: 'ImplementsKeyword' + }, { + token: '&', + optional: true + }, 'TypeName', { + listOfType: 'ImplementsAdditionalInterfaceName', + optional: true + }], + ImplementsAdditionalInterfaceName: [{ + token: '&' + }, 'TypeName'], + FieldsDefinition: [{ + token: '{' + }, { + listOfType: 'FieldDefinition' + }, { + token: '}' + }], + FieldDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + tokenName: 'AliasName', + definitionName: true + }, { + ofType: 'ArgumentsDefinition', + optional: true + }, { + token: ':' + }, 'Type', { + ofType: 'Directives', + optional: true + }], + ArgumentsDefinition: [{ + token: '(' + }, { + listOfType: 'InputValueDefinition' + }, { + token: ')' + }], + InputValueDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + tokenName: 'ArgumentName' + }, { + token: ':' + }, 'Type', { + ofType: 'DefaultValue', + optional: true + }, { + ofType: 'Directives', + optional: true + }], + ObjectTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'type', + tokenName: 'TypeDefinitionKeyword' + }, 'TypeName', { + peek: [{ + ifCondition: { + token: 'Name', + ofValue: 'interface' + }, + expect: ['ImplementsInterfaces', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'FieldsDefinition', + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: 'FieldsDefinition' + }], + optional: true + }] + }, { + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'FieldsDefinition', + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: 'FieldsDefinition' + }] + }], + InterfaceTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'interface', + tokenName: 'InterfaceDefinitionKeyword' + }, 'TypeName', { + ofType: 'Directives', + optional: true + }, { + ofType: 'FieldsDefinition', + optional: true + }], + InterfaceTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'interface', + tokenName: 'InterfaceDefinitionKeyword' + }, 'TypeName', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'FieldsDefinition', + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: 'FieldsDefinition' + }] + }], + UnionTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'union', + tokenName: 'UnionDefinitionKeyword' + }, 'TypeName', { + ofType: 'Directives', + optional: true + }, { + ofType: 'UnionMemberTypes', + optional: true + }], + UnionMemberTypes: [{ + token: '=' + }, { + token: '|', + optional: true + }, 'Name', { + listOfType: 'UnionMemberAdditionalTypeName', + optional: true + }], + UnionMemberAdditionalTypeName: [{ + token: '|' + }, 'TypeName'], + UnionTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'union', + tokenName: 'UnionDefinitionKeyword' + }, 'TypeName', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'UnionMemberTypes', + optional: true + }] + }, { + ifCondition: { + token: '=' + }, + expect: 'UnionMemberTypes' + }] + }], + EnumTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'enum', + tokenName: 'EnumDefinitionKeyword' + }, 'TypeName', { + ofType: 'Directives', + optional: true + }, { + ofType: 'EnumValuesDefinition', + optional: true + }], + EnumValuesDefinition: [{ + token: '{' + }, { + listOfType: 'EnumValueDefinition' + }, { + token: '}' + }], + EnumValueDefinition: [{ + ofType: 'Description', + optional: true + }, 'EnumValue', { + ofType: 'Directives', + optional: true + }], + EnumTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'enum', + tokenName: 'EnumDefinitionKeyword' + }, 'TypeName', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'EnumValuesDefinition', + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: 'EnumValuesDefinition' + }] + }], + InputObjectTypeDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'input', + tokenName: 'InputDefinitionKeyword' + }, 'TypeName', { + ofType: 'Directives', + optional: true + }, { + ofType: 'InputFieldsDefinition', + optional: true + }], + InputFieldsDefinition: [{ + token: '{' + }, { + listOfType: 'InputValueDefinition' + }, { + token: '}' + }], + InputObjectTypeExtension: [{ + token: 'Name', + ofValue: 'extend', + tokenName: 'ExtendDefinitionKeyword' + }, { + token: 'Name', + ofValue: 'input', + tokenName: 'InputDefinitionKeyword' + }, 'TypeName', { + peek: [{ + ifCondition: { + token: '@' + }, + expect: ['Directives', { + ofType: 'InputFieldsDefinition', + optional: true + }] + }, { + ifCondition: { + token: '{' + }, + expect: 'InputFieldsDefinition' + }] + }], + DirectiveDefinition: [{ + ofType: 'Description', + optional: true + }, { + token: 'Name', + ofValue: 'directive', + tokenName: 'DirectiveDefinitionKeyword' + }, { + token: '@', + tokenName: 'DirectiveName' + }, { + token: 'Name', + tokenName: 'DirectiveName' + }, { + ofType: 'ArgumentsDefinition', + optional: true + }, { + token: 'Name', + ofValue: 'on', + tokenName: 'OnKeyword' + }, 'DirectiveLocations'], + DirectiveLocations: [{ + token: '|', + optional: true + }, 'DirectiveLocation', { + listOfType: 'DirectiveLocationAdditionalName', + optional: true + }], + DirectiveLocationAdditionalName: [{ + token: '|' + }, 'DirectiveLocation'], + DirectiveLocation: { + peek: [{ + ifCondition: 'ExecutableDirectiveLocation', + expect: 'ExecutableDirectiveLocation' + }, { + ifCondition: 'TypeSystemDirectiveLocation', + expect: 'TypeSystemDirectiveLocation' + }] + }, + ExecutableDirectiveLocation: { + token: 'Name', + oneOf: ['QUERY', 'MUTATION', 'SUBSCRIPTION', 'FIELD', 'FRAGMENT_DEFINITION', 'FRAGMENT_SPREAD', 'INLINE_FRAGMENT'], + tokenName: 'EnumValue' + }, + TypeSystemDirectiveLocation: { + token: 'Name', + oneOf: ['SCHEMA', 'SCALAR', 'OBJECT', 'FIELD_DEFINITION', 'ARGUMENT_DEFINITION', 'INTERFACE', 'UNION', 'ENUM', 'ENUM_VALUE', 'INPUT_OBJECT', 'INPUT_FIELD_DEFINITION'], + tokenName: 'EnumValue' + } // FIXME: enforce proper typing + +}; +export default grammar; diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/index.d.ts b/school/node_modules/graphql/language/experimentalOnlineParser/index.d.ts new file mode 100644 index 0000000..039446a --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/index.d.ts @@ -0,0 +1,6 @@ +export { + OnlineParser, + RuleKind, + TokenKind, + OnlineParserState, +} from './onlineParser'; diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/index.js b/school/node_modules/graphql/language/experimentalOnlineParser/index.js new file mode 100644 index 0000000..dd38694 --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/index.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "OnlineParser", { + enumerable: true, + get: function get() { + return _onlineParser.OnlineParser; + } +}); +Object.defineProperty(exports, "RuleKind", { + enumerable: true, + get: function get() { + return _onlineParser.RuleKind; + } +}); +Object.defineProperty(exports, "TokenKind", { + enumerable: true, + get: function get() { + return _onlineParser.TokenKind; + } +}); +Object.defineProperty(exports, "OnlineParserState", { + enumerable: true, + get: function get() { + return _onlineParser.OnlineParserState; + } +}); + +var _onlineParser = require("./onlineParser.js"); diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/index.js.flow b/school/node_modules/graphql/language/experimentalOnlineParser/index.js.flow new file mode 100644 index 0000000..90e34f2 --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/index.js.flow @@ -0,0 +1,7 @@ +// @flow strict +export { + OnlineParser, + RuleKind, + TokenKind, + OnlineParserState, +} from './onlineParser'; diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/index.mjs b/school/node_modules/graphql/language/experimentalOnlineParser/index.mjs new file mode 100644 index 0000000..a82cbe8 --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/index.mjs @@ -0,0 +1 @@ +export { OnlineParser, RuleKind, TokenKind, OnlineParserState } from "./onlineParser.mjs"; diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.d.ts b/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.d.ts new file mode 100644 index 0000000..9570b9e --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.d.ts @@ -0,0 +1,125 @@ +import { Lexer } from '../lexer'; + +import { + GraphQLGrammarTokenConstraint, + GraphQLGrammarOfTypeConstraint, + GraphQLGrammarListOfTypeConstraint, + GraphQLGrammarPeekConstraint, + GraphQLGrammarConstraintsSet, +} from './grammar'; + +interface BaseOnlineParserRule { + kind: string; + name?: string; + depth: number; + step: number; + expanded: boolean; + state: string; + optional?: boolean; + eatNextOnFail?: boolean; +} +interface TokenOnlineParserRule + extends BaseOnlineParserRule, + GraphQLGrammarTokenConstraint {} +interface OfTypeOnlineParserRule + extends BaseOnlineParserRule, + GraphQLGrammarOfTypeConstraint {} +interface ListOfTypeOnlineParserRule + extends BaseOnlineParserRule, + GraphQLGrammarListOfTypeConstraint {} +interface PeekOnlineParserRule + extends BaseOnlineParserRule, + GraphQLGrammarPeekConstraint { + index: number; + matched: boolean; +} +interface ConstraintsSetOnlineParserRule extends BaseOnlineParserRule { + constraintsSet: boolean; + constraints: GraphQLGrammarConstraintsSet; +} + +type OnlineParserRule = + | TokenOnlineParserRule + | OfTypeOnlineParserRule + | ListOfTypeOnlineParserRule + | PeekOnlineParserRule + | ConstraintsSetOnlineParserRule; + +export interface OnlineParserState { + rules: Array<OnlineParserRule>; + kind: () => string; + step: () => number; + levels: Array<number>; + indentLevel: number | undefined; + name: string | null; + type: string | null; +} + +interface Token { + kind: string; + value?: string; + tokenName?: string | undefined; + ruleName?: string | undefined; +} + +type OnlineParserConfig = { + tabSize: number; +}; + +type OnlineParserConfigOption = { + tabSize?: number; +}; + +export class OnlineParser { + state: OnlineParserState; + _lexer: Lexer; + _config: OnlineParserConfig; + constructor( + source: string, + state?: OnlineParserState, + config?: OnlineParserConfigOption, + ); + static startState(): OnlineParserState; + static copyState(state: OnlineParserState): OnlineParserState; + sol(): boolean; + parseToken(): Token; + indentation(): number; + private readonly _parseTokenConstraint; + private readonly _parseListOfTypeConstraint; + private readonly _parseOfTypeConstraint; + private readonly _parsePeekConstraint; + private readonly _parseConstraintsSetRule; + private readonly _matchToken; + private readonly _butNot; + private readonly _transformLexerToken; + private readonly _getNextRule; + private readonly _popMatchedRule; + private readonly _rollbackRule; + private readonly _pushRule; + private readonly _getRuleKind; + private readonly _advanceToken; + private readonly _lookAhead; +} + +export const TokenKind: { + NAME: string; + INT: string; + FLOAT: string; + STRING: string; + BLOCK_STRING: string; + COMMENT: string; + PUNCTUATION: string; + EOF: string; + INVALID: string; +}; + +export const RuleKind: { + TOKEN_CONSTRAINT: string; + OF_TYPE_CONSTRAINT: string; + LIST_OF_TYPE_CONSTRAINT: string; + PEEK_CONSTRAINT: string; + CONSTRAINTS_SET: string; + CONSTRAINTS_SET_ROOT: string; + RULE_NAME: string; + INVALID: string; +}; diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.js b/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.js new file mode 100644 index 0000000..8fc0707 --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.js @@ -0,0 +1,604 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OnlineParser = exports.RuleKind = exports.TokenKind = void 0; + +var _lexer = require("../lexer.js"); + +var _source = require("../source.js"); + +var _grammar = _interopRequireDefault(require("./grammar.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var TokenKind = { + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment', + PUNCTUATION: 'Punctuation', + EOF: '<EOF>', + INVALID: 'Invalid' +}; +exports.TokenKind = TokenKind; +var RuleKind = { + TOKEN_CONSTRAINT: 'TokenConstraint', + OF_TYPE_CONSTRAINT: 'OfTypeConstraint', + LIST_OF_TYPE_CONSTRAINT: 'ListOfTypeConstraint', + PEEK_CONSTRAINT: 'PeekConstraint', + CONSTRAINTS_SET: 'ConstraintsSet', + CONSTRAINTS_SET_ROOT: 'ConstraintsSetRoot', + RULE_NAME: 'RuleName', + INVALID: 'Invalid' +}; +exports.RuleKind = RuleKind; + +var OnlineParser = /*#__PURE__*/function () { + function OnlineParser(source, state, config) { + var _config$tabSize; + + this.state = state || OnlineParser.startState(); + this._config = { + tabSize: (_config$tabSize = config === null || config === void 0 ? void 0 : config.tabSize) !== null && _config$tabSize !== void 0 ? _config$tabSize : 2 + }; + this._lexer = new _lexer.Lexer(new _source.Source(source)); + } + + OnlineParser.startState = function startState() { + return { + rules: [// $FlowFixMe[cannot-spread-interface] + _objectSpread(_objectSpread({ + name: 'Document', + state: 'Document', + kind: 'ListOfTypeConstraint' + }, _grammar.default.Document), {}, { + expanded: false, + depth: 1, + step: 1 + })], + name: null, + type: null, + levels: [], + indentLevel: 0, + kind: function kind() { + var _this$rules; + + return ((_this$rules = this.rules[this.rules.length - 1]) === null || _this$rules === void 0 ? void 0 : _this$rules.state) || ''; + }, + step: function step() { + var _this$rules2; + + return ((_this$rules2 = this.rules[this.rules.length - 1]) === null || _this$rules2 === void 0 ? void 0 : _this$rules2.step) || 0; + } + }; + }; + + OnlineParser.copyState = function copyState(state) { + return { + name: state.name, + type: state.type, + rules: JSON.parse(JSON.stringify(state.rules)), + levels: [].concat(state.levels), + indentLevel: state.indentLevel, + kind: function kind() { + var _this$rules3; + + return ((_this$rules3 = this.rules[this.rules.length - 1]) === null || _this$rules3 === void 0 ? void 0 : _this$rules3.state) || ''; + }, + step: function step() { + var _this$rules4; + + return ((_this$rules4 = this.rules[this.rules.length - 1]) === null || _this$rules4 === void 0 ? void 0 : _this$rules4.step) || 0; + } + }; + }; + + var _proto = OnlineParser.prototype; + + _proto.sol = function sol() { + return this._lexer.source.locationOffset.line === 1 && this._lexer.source.locationOffset.column === 1; + }; + + _proto.parseToken = function parseToken() { + var rule = this._getNextRule(); + + if (this.sol()) { + this.state.indentLevel = Math.floor(this.indentation() / this._config.tabSize); + } + + if (!rule) { + return { + kind: TokenKind.INVALID, + value: '' + }; + } + + var token; + + if (this._lookAhead().kind === '<EOF>') { + return { + kind: TokenKind.EOF, + value: '', + ruleName: rule.name + }; + } + + switch (rule.kind) { + case RuleKind.TOKEN_CONSTRAINT: + token = this._parseTokenConstraint(rule); + break; + + case RuleKind.LIST_OF_TYPE_CONSTRAINT: + token = this._parseListOfTypeConstraint(rule); + break; + + case RuleKind.OF_TYPE_CONSTRAINT: + token = this._parseOfTypeConstraint(rule); + break; + + case RuleKind.PEEK_CONSTRAINT: + token = this._parsePeekConstraint(rule); + break; + + case RuleKind.CONSTRAINTS_SET_ROOT: + token = this._parseConstraintsSetRule(rule); + break; + + default: + return { + kind: TokenKind.INVALID, + value: '', + ruleName: rule.name + }; + } + + if (token && token.kind === TokenKind.INVALID) { + if (rule.optional === true) { + this.state.rules.pop(); + } else { + this._rollbackRule(); + } + + return this.parseToken() || token; + } + + return token; + }; + + _proto.indentation = function indentation() { + var match = this._lexer.source.body.match(/\s*/); + + var indent = 0; + + if (match && match.length === 0) { + var whiteSpaces = match[0]; + var pos = 0; + + while (whiteSpaces.length > pos) { + if (whiteSpaces.charCodeAt(pos) === 9) { + indent += 2; + } else { + indent++; + } + + pos++; + } + } + + return indent; + }; + + _proto._parseTokenConstraint = function _parseTokenConstraint(rule) { + rule.expanded = true; + + var token = this._lookAhead(); + + if (!this._matchToken(token, rule)) { + return { + kind: TokenKind.INVALID, + value: '', + tokenName: rule.tokenName, + ruleName: rule.name + }; + } + + this._advanceToken(); + + var parserToken = this._transformLexerToken(token, rule); + + this._popMatchedRule(parserToken); + + return parserToken; + }; + + _proto._parseListOfTypeConstraint = function _parseListOfTypeConstraint(rule) { + this._pushRule(_grammar.default[rule.listOfType], rule.depth + 1, rule.listOfType, 1, rule.state); + + rule.expanded = true; + var token = this.parseToken(); + return token; + }; + + _proto._parseOfTypeConstraint = function _parseOfTypeConstraint(rule) { + if (rule.expanded) { + this._popMatchedRule(); + + return this.parseToken(); + } + + this._pushRule(rule.ofType, rule.depth + 1, rule.tokenName, 1, rule.state); + + rule.expanded = true; + var token = this.parseToken(); + return token; + }; + + _proto._parsePeekConstraint = function _parsePeekConstraint(rule) { + if (rule.expanded) { + this._popMatchedRule(); + + return this.parseToken(); + } + + while (!rule.matched && rule.index < rule.peek.length - 1) { + rule.index++; + var constraint = rule.peek[rule.index]; + var ifCondition = constraint.ifCondition; + + if (typeof ifCondition === 'string') { + ifCondition = _grammar.default[ifCondition]; + } + + var token = this._lookAhead(); + + if (ifCondition && this._matchToken(token, ifCondition)) { + rule.matched = true; + rule.expanded = true; + + this._pushRule(constraint.expect, rule.depth + 1, '', 1, rule.state); + + token = this.parseToken(); + return token; + } + } + + return { + kind: TokenKind.INVALID, + value: '', + ruleName: rule.name + }; + }; + + _proto._parseConstraintsSetRule = function _parseConstraintsSetRule(rule) { + if (rule.expanded) { + this._popMatchedRule(); + + return this.parseToken(); + } + + for (var index = rule.constraints.length - 1; index >= 0; index--) { + this._pushRule(rule.constraints[index], rule.depth + 1, '', index, rule.state); + } + + rule.expanded = true; + return this.parseToken(); + }; + + _proto._matchToken = function _matchToken(token, rule) { + if (typeof token.value === 'string') { + if (typeof rule.ofValue === 'string' && token.value !== rule.ofValue || Array.isArray(rule.oneOf) && !rule.oneOf.includes(token.value) || typeof rule.ofValue !== 'string' && !Array.isArray(rule.oneOf) && token.kind !== rule.token) { + return false; + } + + return this._butNot(token, rule); + } + + if (token.kind !== rule.token) { + return false; + } + + return this._butNot(token, rule); + }; + + _proto._butNot = function _butNot(token, rule) { + var _this = this; + + if (rule.butNot) { + if (Array.isArray(rule.butNot)) { + if (rule.butNot.reduce(function (matched, constraint) { + return matched || _this._matchToken(token, constraint); + }, false)) { + return false; + } + + return true; + } + + return !this._matchToken(token, rule.butNot); + } + + return true; + }; + + _proto._transformLexerToken = function _transformLexerToken(lexerToken, rule) { + var token; + var ruleName = rule.name || ''; + var tokenName = rule.tokenName || ''; + + if (lexerToken.kind === '<EOF>' || lexerToken.value !== undefined) { + token = { + kind: lexerToken.kind, + value: lexerToken.value || '', + tokenName: tokenName, + ruleName: ruleName + }; + + if (token.kind === TokenKind.STRING) { + token.value = "\"".concat(token.value, "\""); + } else if (token.kind === TokenKind.BLOCK_STRING) { + token.value = "\"\"\"".concat(token.value, "\"\"\""); + } + } else { + token = { + kind: TokenKind.PUNCTUATION, + value: lexerToken.kind, + tokenName: tokenName, + ruleName: ruleName + }; + + if (/^[{([]/.test(token.value)) { + if (this.state.indentLevel !== undefined) { + this.state.levels = this.state.levels.concat(this.state.indentLevel + 1); + } + } else if (/^[})\]]/.test(token.value)) { + this.state.levels.pop(); + } + } + + return token; + }; + + _proto._getNextRule = function _getNextRule() { + return this.state.rules[this.state.rules.length - 1] || null; + }; + + _proto._popMatchedRule = function _popMatchedRule(token) { + var rule = this.state.rules.pop(); + + if (!rule) { + return; + } + + if (token && rule.kind === RuleKind.TOKEN_CONSTRAINT) { + var constraint = rule; + + if (typeof constraint.definitionName === 'string') { + this.state.name = token.value || null; + } else if (typeof constraint.typeName === 'string') { + this.state.type = token.value || null; + } + } + + var nextRule = this._getNextRule(); + + if (!nextRule) { + return; + } + + if (nextRule.depth === rule.depth - 1 && nextRule.expanded && nextRule.kind === RuleKind.CONSTRAINTS_SET_ROOT) { + this.state.rules.pop(); + } + + if (nextRule.depth === rule.depth - 1 && nextRule.expanded && nextRule.kind === RuleKind.LIST_OF_TYPE_CONSTRAINT) { + nextRule.expanded = false; + nextRule.optional = true; + } + }; + + _proto._rollbackRule = function _rollbackRule() { + var _this2 = this; + + if (!this.state.rules.length) { + return; + } + + var popRule = function popRule() { + var lastPoppedRule = _this2.state.rules.pop(); + + if (lastPoppedRule.eatNextOnFail === true) { + _this2.state.rules.pop(); + } + }; + + var poppedRule = this.state.rules.pop(); + + if (!poppedRule) { + return; + } + + var popped = 0; + + var nextRule = this._getNextRule(); + + while (nextRule && (poppedRule.kind !== RuleKind.LIST_OF_TYPE_CONSTRAINT || nextRule.expanded) && nextRule.depth > poppedRule.depth - 1) { + this.state.rules.pop(); + popped++; + nextRule = this._getNextRule(); + } + + if (nextRule && nextRule.expanded) { + if (nextRule.optional === true) { + popRule(); + } else { + if (nextRule.kind === RuleKind.LIST_OF_TYPE_CONSTRAINT && popped === 1) { + this.state.rules.pop(); + return; + } + + this._rollbackRule(); + } + } + }; + + _proto._pushRule = function _pushRule(baseRule, depth, name, step, state) { + var _this$_getNextRule, _this$_getNextRule2, _this$_getNextRule3, _this$_getNextRule4, _this$_getNextRule5, _this$_getNextRule6, _this$_getNextRule7, _this$_getNextRule8, _this$_getNextRule9, _this$_getNextRule10; + + this.state.name = null; + this.state.type = null; + var rule = baseRule; + + switch (this._getRuleKind(rule)) { + case RuleKind.RULE_NAME: + rule = rule; + + this._pushRule(_grammar.default[rule], depth, (typeof name === 'string' ? name : undefined) || rule, step, state); + + break; + + case RuleKind.CONSTRAINTS_SET: + rule = rule; + this.state.rules.push({ + name: name || '', + depth: depth, + expanded: false, + constraints: rule, + constraintsSet: true, + kind: RuleKind.CONSTRAINTS_SET_ROOT, + state: (typeof name === 'string' ? name : undefined) || (typeof state === 'string' ? state : undefined) || ((_this$_getNextRule = this._getNextRule()) === null || _this$_getNextRule === void 0 ? void 0 : _this$_getNextRule.state) || '', + step: typeof step === 'number' ? step : (((_this$_getNextRule2 = this._getNextRule()) === null || _this$_getNextRule2 === void 0 ? void 0 : _this$_getNextRule2.step) || 0) + 1 + }); + break; + + case RuleKind.OF_TYPE_CONSTRAINT: + rule = rule; + this.state.rules.push({ + name: name || '', + ofType: rule.ofType, + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + depth: depth, + expanded: false, + kind: RuleKind.OF_TYPE_CONSTRAINT, + state: (typeof rule.tokenName === 'string' ? rule.tokenName : undefined) || (typeof name === 'string' ? name : undefined) || (typeof state === 'string' ? state : undefined) || ((_this$_getNextRule3 = this._getNextRule()) === null || _this$_getNextRule3 === void 0 ? void 0 : _this$_getNextRule3.state) || '', + step: typeof step === 'number' ? step : (((_this$_getNextRule4 = this._getNextRule()) === null || _this$_getNextRule4 === void 0 ? void 0 : _this$_getNextRule4.step) || 0) + 1 + }); + break; + + case RuleKind.LIST_OF_TYPE_CONSTRAINT: + rule = rule; + this.state.rules.push({ + listOfType: rule.listOfType, + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + name: name || '', + depth: depth, + expanded: false, + kind: RuleKind.LIST_OF_TYPE_CONSTRAINT, + state: (typeof name === 'string' ? name : undefined) || (typeof state === 'string' ? state : undefined) || ((_this$_getNextRule5 = this._getNextRule()) === null || _this$_getNextRule5 === void 0 ? void 0 : _this$_getNextRule5.state) || '', + step: typeof step === 'number' ? step : (((_this$_getNextRule6 = this._getNextRule()) === null || _this$_getNextRule6 === void 0 ? void 0 : _this$_getNextRule6.step) || 0) + 1 + }); + break; + + case RuleKind.TOKEN_CONSTRAINT: + rule = rule; + this.state.rules.push({ + token: rule.token, + ofValue: rule.ofValue, + oneOf: rule.oneOf, + definitionName: Boolean(rule.definitionName), + typeName: Boolean(rule.typeName), + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + name: name || '', + depth: depth, + expanded: false, + kind: RuleKind.TOKEN_CONSTRAINT, + state: (typeof rule.tokenName === 'string' ? rule.tokenName : undefined) || (typeof state === 'string' ? state : undefined) || ((_this$_getNextRule7 = this._getNextRule()) === null || _this$_getNextRule7 === void 0 ? void 0 : _this$_getNextRule7.state) || '', + step: typeof step === 'number' ? step : (((_this$_getNextRule8 = this._getNextRule()) === null || _this$_getNextRule8 === void 0 ? void 0 : _this$_getNextRule8.step) || 0) + 1 + }); + break; + + case RuleKind.PEEK_CONSTRAINT: + rule = rule; + this.state.rules.push({ + peek: rule.peek, + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + name: name || '', + depth: depth, + index: -1, + matched: false, + expanded: false, + kind: RuleKind.PEEK_CONSTRAINT, + state: (typeof state === 'string' ? state : undefined) || ((_this$_getNextRule9 = this._getNextRule()) === null || _this$_getNextRule9 === void 0 ? void 0 : _this$_getNextRule9.state) || '', + step: typeof step === 'number' ? step : (((_this$_getNextRule10 = this._getNextRule()) === null || _this$_getNextRule10 === void 0 ? void 0 : _this$_getNextRule10.step) || 0) + 1 + }); + break; + } + }; + + _proto._getRuleKind = function _getRuleKind(rule) { + if (Array.isArray(rule)) { + return RuleKind.CONSTRAINTS_SET; + } + + if (rule.constraintsSet === true) { + return RuleKind.CONSTRAINTS_SET_ROOT; + } + + if (typeof rule === 'string') { + return RuleKind.RULE_NAME; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'ofType')) { + return RuleKind.OF_TYPE_CONSTRAINT; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'listOfType')) { + return RuleKind.LIST_OF_TYPE_CONSTRAINT; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'peek')) { + return RuleKind.PEEK_CONSTRAINT; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'token')) { + return RuleKind.TOKEN_CONSTRAINT; + } + + return RuleKind.INVALID; + }; + + _proto._advanceToken = function _advanceToken() { + return this._lexer.advance(); + }; + + _proto._lookAhead = function _lookAhead() { + try { + return this._lexer.lookahead(); + } catch (err) { + return { + kind: TokenKind.INVALID, + value: '' + }; + } + }; + + return OnlineParser; +}(); + +exports.OnlineParser = OnlineParser; diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.js.flow b/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.js.flow new file mode 100644 index 0000000..eae6e89 --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.js.flow @@ -0,0 +1,723 @@ +// @flow strict +import { Lexer } from '../lexer'; +import { Source } from '../source'; + +import GraphQLGrammar from './grammar'; +import type { + GraphQLGrammarRule, + GraphQLGrammarRuleName, + GraphQLGrammarRuleConstraint, + GraphQLGrammarTokenConstraint, + GraphQLGrammarOfTypeConstraint, + GraphQLGrammarListOfTypeConstraint, + GraphQLGrammarPeekConstraint, + GraphQLGrammarConstraintsSet, +} from './grammar'; + +export const TokenKind = { + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment', + PUNCTUATION: 'Punctuation', + EOF: '<EOF>', + INVALID: 'Invalid', +}; + +export const RuleKind = { + TOKEN_CONSTRAINT: 'TokenConstraint', + OF_TYPE_CONSTRAINT: 'OfTypeConstraint', + LIST_OF_TYPE_CONSTRAINT: 'ListOfTypeConstraint', + PEEK_CONSTRAINT: 'PeekConstraint', + CONSTRAINTS_SET: 'ConstraintsSet', + CONSTRAINTS_SET_ROOT: 'ConstraintsSetRoot', + RULE_NAME: 'RuleName', + INVALID: 'Invalid', +}; + +interface BaseOnlineParserRule { + kind: string; + name?: string; + depth: number; + step: number; + expanded: boolean; + state: string; + optional?: boolean; + eatNextOnFail?: boolean; +} +interface TokenOnlineParserRule + extends BaseOnlineParserRule, + GraphQLGrammarTokenConstraint {} +interface OfTypeOnlineParserRule + extends BaseOnlineParserRule, + GraphQLGrammarOfTypeConstraint {} +interface ListOfTypeOnlineParserRule + extends BaseOnlineParserRule, + GraphQLGrammarListOfTypeConstraint {} +interface PeekOnlineParserRule + extends BaseOnlineParserRule, + GraphQLGrammarPeekConstraint { + index: number; + matched: boolean; +} +interface ConstraintsSetOnlineParserRule extends BaseOnlineParserRule { + constraintsSet: boolean; + constraints: GraphQLGrammarConstraintsSet; +} + +type OnlineParserRule = + | TokenOnlineParserRule + | OfTypeOnlineParserRule + | ListOfTypeOnlineParserRule + | PeekOnlineParserRule + | ConstraintsSetOnlineParserRule; + +export type OnlineParserState = {| + rules: Array<OnlineParserRule>, + kind: () => string, + step: () => number, + levels: Array<number>, + indentLevel: number, + name: string | null, + type: string | null, +|}; + +type Token = {| + kind: string, + value: string, + tokenName?: ?string, + ruleName?: ?string, +|}; + +type LexerToken = {| + kind: string, + value: ?string, +|}; + +type OnlineParserConfig = {| + tabSize: number, +|}; + +type OnlineParserConfigOption = {| + tabSize: ?number, +|}; + +export class OnlineParser { + state: OnlineParserState; + _lexer: Lexer; + _config: OnlineParserConfig; + + constructor( + source: string, + state?: OnlineParserState, + config?: OnlineParserConfigOption, + ) { + this.state = state || OnlineParser.startState(); + this._config = { + tabSize: config?.tabSize ?? 2, + }; + this._lexer = new Lexer(new Source(source)); + } + + static startState(): OnlineParserState { + return { + rules: [ + // $FlowFixMe[cannot-spread-interface] + { + name: 'Document', + state: 'Document', + kind: 'ListOfTypeConstraint', + ...GraphQLGrammar.Document, + expanded: false, + depth: 1, + step: 1, + }, + ], + name: null, + type: null, + levels: [], + indentLevel: 0, + kind(): string { + return this.rules[this.rules.length - 1]?.state || ''; + }, + step(): number { + return this.rules[this.rules.length - 1]?.step || 0; + }, + }; + } + + static copyState(state: OnlineParserState): OnlineParserState { + return { + name: state.name, + type: state.type, + rules: JSON.parse(JSON.stringify(state.rules)), + levels: [...state.levels], + indentLevel: state.indentLevel, + kind(): string { + return this.rules[this.rules.length - 1]?.state || ''; + }, + step(): number { + return this.rules[this.rules.length - 1]?.step || 0; + }, + }; + } + + sol(): boolean { + return ( + this._lexer.source.locationOffset.line === 1 && + this._lexer.source.locationOffset.column === 1 + ); + } + + parseToken(): Token { + const rule = (this._getNextRule(): any); + + if (this.sol()) { + this.state.indentLevel = Math.floor( + this.indentation() / this._config.tabSize, + ); + } + + if (!rule) { + return { + kind: TokenKind.INVALID, + value: '', + }; + } + + let token; + + if (this._lookAhead().kind === '<EOF>') { + return { + kind: TokenKind.EOF, + value: '', + ruleName: rule.name, + }; + } + + switch (rule.kind) { + case RuleKind.TOKEN_CONSTRAINT: + token = this._parseTokenConstraint(rule); + break; + case RuleKind.LIST_OF_TYPE_CONSTRAINT: + token = this._parseListOfTypeConstraint(rule); + break; + case RuleKind.OF_TYPE_CONSTRAINT: + token = this._parseOfTypeConstraint(rule); + break; + case RuleKind.PEEK_CONSTRAINT: + token = this._parsePeekConstraint(rule); + break; + case RuleKind.CONSTRAINTS_SET_ROOT: + token = this._parseConstraintsSetRule(rule); + break; + default: + return { + kind: TokenKind.INVALID, + value: '', + ruleName: rule.name, + }; + } + + if (token && token.kind === TokenKind.INVALID) { + if (rule.optional === true) { + this.state.rules.pop(); + } else { + this._rollbackRule(); + } + + return this.parseToken() || token; + } + + return token; + } + + indentation(): number { + const match = this._lexer.source.body.match(/\s*/); + let indent = 0; + + if (match && match.length === 0) { + const whiteSpaces = match[0]; + let pos = 0; + while (whiteSpaces.length > pos) { + if (whiteSpaces.charCodeAt(pos) === 9) { + indent += 2; + } else { + indent++; + } + pos++; + } + } + + return indent; + } + + _parseTokenConstraint(rule: TokenOnlineParserRule): Token { + rule.expanded = true; + + const token = this._lookAhead(); + + if (!this._matchToken(token, rule)) { + return { + kind: TokenKind.INVALID, + value: '', + tokenName: rule.tokenName, + ruleName: rule.name, + }; + } + + this._advanceToken(); + const parserToken = this._transformLexerToken(token, rule); + this._popMatchedRule(parserToken); + + return parserToken; + } + + _parseListOfTypeConstraint(rule: ListOfTypeOnlineParserRule): Token { + this._pushRule( + GraphQLGrammar[rule.listOfType], + rule.depth + 1, + rule.listOfType, + 1, + rule.state, + ); + + rule.expanded = true; + + const token = this.parseToken(); + + return token; + } + + _parseOfTypeConstraint(rule: OfTypeOnlineParserRule): Token { + if (rule.expanded) { + this._popMatchedRule(); + return this.parseToken(); + } + + this._pushRule(rule.ofType, rule.depth + 1, rule.tokenName, 1, rule.state); + rule.expanded = true; + + const token = this.parseToken(); + + return token; + } + + _parsePeekConstraint(rule: PeekOnlineParserRule): Token { + if (rule.expanded) { + this._popMatchedRule(); + return this.parseToken(); + } + + while (!rule.matched && rule.index < rule.peek.length - 1) { + rule.index++; + const constraint = rule.peek[rule.index]; + + let { ifCondition } = constraint; + if (typeof ifCondition === 'string') { + ifCondition = GraphQLGrammar[ifCondition]; + } + + let token = this._lookAhead(); + if (ifCondition && this._matchToken(token, ifCondition)) { + rule.matched = true; + rule.expanded = true; + this._pushRule(constraint.expect, rule.depth + 1, '', 1, rule.state); + + token = this.parseToken(); + + return token; + } + } + + return { + kind: TokenKind.INVALID, + value: '', + ruleName: rule.name, + }; + } + + _parseConstraintsSetRule(rule: ConstraintsSetOnlineParserRule): Token { + if (rule.expanded) { + this._popMatchedRule(); + return this.parseToken(); + } + + for (let index = rule.constraints.length - 1; index >= 0; index--) { + this._pushRule( + rule.constraints[index], + rule.depth + 1, + '', + index, + rule.state, + ); + } + rule.expanded = true; + + return this.parseToken(); + } + + _matchToken( + token: Token | LexerToken, + rule: GraphQLGrammarTokenConstraint, + ): boolean { + if (typeof token.value === 'string') { + if ( + (typeof rule.ofValue === 'string' && token.value !== rule.ofValue) || + (Array.isArray(rule.oneOf) && !rule.oneOf.includes(token.value)) || + (typeof rule.ofValue !== 'string' && + !Array.isArray(rule.oneOf) && + token.kind !== rule.token) + ) { + return false; + } + + return this._butNot(token, rule); + } + + if (token.kind !== rule.token) { + return false; + } + + return this._butNot(token, rule); + } + + _butNot( + token: Token | LexerToken, + rule: GraphQLGrammarRuleConstraint, + ): boolean { + if (rule.butNot) { + if (Array.isArray(rule.butNot)) { + if ( + rule.butNot.reduce( + (matched, constraint) => + matched || this._matchToken(token, constraint), + false, + ) + ) { + return false; + } + + return true; + } + + return !this._matchToken(token, rule.butNot); + } + + return true; + } + + _transformLexerToken(lexerToken: LexerToken, rule: any): Token { + let token; + const ruleName = rule.name || ''; + const tokenName = rule.tokenName || ''; + + if (lexerToken.kind === '<EOF>' || lexerToken.value !== undefined) { + token = { + kind: lexerToken.kind, + value: lexerToken.value || '', + tokenName, + ruleName, + }; + + if (token.kind === TokenKind.STRING) { + token.value = `"${token.value}"`; + } else if (token.kind === TokenKind.BLOCK_STRING) { + token.value = `"""${token.value}"""`; + } + } else { + token = { + kind: TokenKind.PUNCTUATION, + value: lexerToken.kind, + tokenName, + ruleName, + }; + + if (/^[{([]/.test(token.value)) { + if (this.state.indentLevel !== undefined) { + this.state.levels = this.state.levels.concat( + this.state.indentLevel + 1, + ); + } + } else if (/^[})\]]/.test(token.value)) { + this.state.levels.pop(); + } + } + + return token; + } + + _getNextRule(): OnlineParserRule | null { + return this.state.rules[this.state.rules.length - 1] || null; + } + + _popMatchedRule(token: ?Token) { + const rule = this.state.rules.pop(); + if (!rule) { + return; + } + + if (token && rule.kind === RuleKind.TOKEN_CONSTRAINT) { + const constraint = rule; + if (typeof constraint.definitionName === 'string') { + this.state.name = token.value || null; + } else if (typeof constraint.typeName === 'string') { + this.state.type = token.value || null; + } + } + + const nextRule = this._getNextRule(); + if (!nextRule) { + return; + } + + if ( + nextRule.depth === rule.depth - 1 && + nextRule.expanded && + nextRule.kind === RuleKind.CONSTRAINTS_SET_ROOT + ) { + this.state.rules.pop(); + } + + if ( + nextRule.depth === rule.depth - 1 && + nextRule.expanded && + nextRule.kind === RuleKind.LIST_OF_TYPE_CONSTRAINT + ) { + nextRule.expanded = false; + nextRule.optional = true; + } + } + + _rollbackRule() { + if (!this.state.rules.length) { + return; + } + + const popRule = () => { + const lastPoppedRule = this.state.rules.pop(); + + if (lastPoppedRule.eatNextOnFail === true) { + this.state.rules.pop(); + } + }; + + const poppedRule = this.state.rules.pop(); + if (!poppedRule) { + return; + } + + let popped = 0; + let nextRule = this._getNextRule(); + while ( + nextRule && + (poppedRule.kind !== RuleKind.LIST_OF_TYPE_CONSTRAINT || + nextRule.expanded) && + nextRule.depth > poppedRule.depth - 1 + ) { + this.state.rules.pop(); + popped++; + nextRule = this._getNextRule(); + } + + if (nextRule && nextRule.expanded) { + if (nextRule.optional === true) { + popRule(); + } else { + if ( + nextRule.kind === RuleKind.LIST_OF_TYPE_CONSTRAINT && + popped === 1 + ) { + this.state.rules.pop(); + return; + } + this._rollbackRule(); + } + } + } + + _pushRule( + baseRule: any, + depth: number, + name?: string, + step?: number, + state?: string, + ) { + this.state.name = null; + this.state.type = null; + let rule = baseRule; + + switch (this._getRuleKind(rule)) { + case RuleKind.RULE_NAME: + rule = (rule: GraphQLGrammarRuleName); + this._pushRule( + GraphQLGrammar[rule], + depth, + (typeof name === 'string' ? name : undefined) || rule, + step, + state, + ); + break; + case RuleKind.CONSTRAINTS_SET: + rule = (rule: GraphQLGrammarConstraintsSet); + this.state.rules.push({ + name: name || '', + depth, + expanded: false, + constraints: rule, + constraintsSet: true, + kind: RuleKind.CONSTRAINTS_SET_ROOT, + state: + (typeof name === 'string' ? name : undefined) || + (typeof state === 'string' ? state : undefined) || + this._getNextRule()?.state || + '', + step: + typeof step === 'number' + ? step + : (this._getNextRule()?.step || 0) + 1, + }); + break; + case RuleKind.OF_TYPE_CONSTRAINT: + rule = (rule: GraphQLGrammarOfTypeConstraint); + this.state.rules.push({ + name: name || '', + ofType: rule.ofType, + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + depth, + expanded: false, + kind: RuleKind.OF_TYPE_CONSTRAINT, + state: + (typeof rule.tokenName === 'string' ? rule.tokenName : undefined) || + (typeof name === 'string' ? name : undefined) || + (typeof state === 'string' ? state : undefined) || + this._getNextRule()?.state || + '', + step: + typeof step === 'number' + ? step + : (this._getNextRule()?.step || 0) + 1, + }); + break; + case RuleKind.LIST_OF_TYPE_CONSTRAINT: + rule = (rule: GraphQLGrammarListOfTypeConstraint); + this.state.rules.push({ + listOfType: rule.listOfType, + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + name: name || '', + depth, + expanded: false, + kind: RuleKind.LIST_OF_TYPE_CONSTRAINT, + state: + (typeof name === 'string' ? name : undefined) || + (typeof state === 'string' ? state : undefined) || + this._getNextRule()?.state || + '', + step: + typeof step === 'number' + ? step + : (this._getNextRule()?.step || 0) + 1, + }); + break; + case RuleKind.TOKEN_CONSTRAINT: + rule = (rule: GraphQLGrammarTokenConstraint); + this.state.rules.push({ + token: rule.token, + ofValue: rule.ofValue, + oneOf: rule.oneOf, + definitionName: Boolean(rule.definitionName), + typeName: Boolean(rule.typeName), + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + name: name || '', + depth, + expanded: false, + kind: RuleKind.TOKEN_CONSTRAINT, + state: + (typeof rule.tokenName === 'string' ? rule.tokenName : undefined) || + (typeof state === 'string' ? state : undefined) || + this._getNextRule()?.state || + '', + step: + typeof step === 'number' + ? step + : (this._getNextRule()?.step || 0) + 1, + }); + break; + case RuleKind.PEEK_CONSTRAINT: + rule = (rule: GraphQLGrammarPeekConstraint); + this.state.rules.push({ + peek: rule.peek, + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + name: name || '', + depth, + index: -1, + matched: false, + expanded: false, + kind: RuleKind.PEEK_CONSTRAINT, + state: + (typeof state === 'string' ? state : undefined) || + this._getNextRule()?.state || + '', + step: + typeof step === 'number' + ? step + : (this._getNextRule()?.step || 0) + 1, + }); + break; + } + } + + _getRuleKind(rule: GraphQLGrammarRule | OnlineParserRule): string { + if (Array.isArray(rule)) { + return RuleKind.CONSTRAINTS_SET; + } + + if (rule.constraintsSet === true) { + return RuleKind.CONSTRAINTS_SET_ROOT; + } + + if (typeof rule === 'string') { + return RuleKind.RULE_NAME; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'ofType')) { + return RuleKind.OF_TYPE_CONSTRAINT; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'listOfType')) { + return RuleKind.LIST_OF_TYPE_CONSTRAINT; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'peek')) { + return RuleKind.PEEK_CONSTRAINT; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'token')) { + return RuleKind.TOKEN_CONSTRAINT; + } + + return RuleKind.INVALID; + } + + _advanceToken(): LexerToken { + return (this._lexer.advance(): any); + } + + _lookAhead(): LexerToken { + try { + return (this._lexer.lookahead(): any); + } catch (err) { + return { kind: TokenKind.INVALID, value: '' }; + } + } +} diff --git a/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.mjs b/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.mjs new file mode 100644 index 0000000..bd5e2fd --- /dev/null +++ b/school/node_modules/graphql/language/experimentalOnlineParser/onlineParser.mjs @@ -0,0 +1,587 @@ +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +import { Lexer } from "../lexer.mjs"; +import { Source } from "../source.mjs"; +import GraphQLGrammar from "./grammar.mjs"; +export var TokenKind = { + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment', + PUNCTUATION: 'Punctuation', + EOF: '<EOF>', + INVALID: 'Invalid' +}; +export var RuleKind = { + TOKEN_CONSTRAINT: 'TokenConstraint', + OF_TYPE_CONSTRAINT: 'OfTypeConstraint', + LIST_OF_TYPE_CONSTRAINT: 'ListOfTypeConstraint', + PEEK_CONSTRAINT: 'PeekConstraint', + CONSTRAINTS_SET: 'ConstraintsSet', + CONSTRAINTS_SET_ROOT: 'ConstraintsSetRoot', + RULE_NAME: 'RuleName', + INVALID: 'Invalid' +}; +export var OnlineParser = /*#__PURE__*/function () { + function OnlineParser(source, state, config) { + var _config$tabSize; + + this.state = state || OnlineParser.startState(); + this._config = { + tabSize: (_config$tabSize = config === null || config === void 0 ? void 0 : config.tabSize) !== null && _config$tabSize !== void 0 ? _config$tabSize : 2 + }; + this._lexer = new Lexer(new Source(source)); + } + + OnlineParser.startState = function startState() { + return { + rules: [// $FlowFixMe[cannot-spread-interface] + _objectSpread(_objectSpread({ + name: 'Document', + state: 'Document', + kind: 'ListOfTypeConstraint' + }, GraphQLGrammar.Document), {}, { + expanded: false, + depth: 1, + step: 1 + })], + name: null, + type: null, + levels: [], + indentLevel: 0, + kind: function kind() { + var _this$rules; + + return ((_this$rules = this.rules[this.rules.length - 1]) === null || _this$rules === void 0 ? void 0 : _this$rules.state) || ''; + }, + step: function step() { + var _this$rules2; + + return ((_this$rules2 = this.rules[this.rules.length - 1]) === null || _this$rules2 === void 0 ? void 0 : _this$rules2.step) || 0; + } + }; + }; + + OnlineParser.copyState = function copyState(state) { + return { + name: state.name, + type: state.type, + rules: JSON.parse(JSON.stringify(state.rules)), + levels: [].concat(state.levels), + indentLevel: state.indentLevel, + kind: function kind() { + var _this$rules3; + + return ((_this$rules3 = this.rules[this.rules.length - 1]) === null || _this$rules3 === void 0 ? void 0 : _this$rules3.state) || ''; + }, + step: function step() { + var _this$rules4; + + return ((_this$rules4 = this.rules[this.rules.length - 1]) === null || _this$rules4 === void 0 ? void 0 : _this$rules4.step) || 0; + } + }; + }; + + var _proto = OnlineParser.prototype; + + _proto.sol = function sol() { + return this._lexer.source.locationOffset.line === 1 && this._lexer.source.locationOffset.column === 1; + }; + + _proto.parseToken = function parseToken() { + var rule = this._getNextRule(); + + if (this.sol()) { + this.state.indentLevel = Math.floor(this.indentation() / this._config.tabSize); + } + + if (!rule) { + return { + kind: TokenKind.INVALID, + value: '' + }; + } + + var token; + + if (this._lookAhead().kind === '<EOF>') { + return { + kind: TokenKind.EOF, + value: '', + ruleName: rule.name + }; + } + + switch (rule.kind) { + case RuleKind.TOKEN_CONSTRAINT: + token = this._parseTokenConstraint(rule); + break; + + case RuleKind.LIST_OF_TYPE_CONSTRAINT: + token = this._parseListOfTypeConstraint(rule); + break; + + case RuleKind.OF_TYPE_CONSTRAINT: + token = this._parseOfTypeConstraint(rule); + break; + + case RuleKind.PEEK_CONSTRAINT: + token = this._parsePeekConstraint(rule); + break; + + case RuleKind.CONSTRAINTS_SET_ROOT: + token = this._parseConstraintsSetRule(rule); + break; + + default: + return { + kind: TokenKind.INVALID, + value: '', + ruleName: rule.name + }; + } + + if (token && token.kind === TokenKind.INVALID) { + if (rule.optional === true) { + this.state.rules.pop(); + } else { + this._rollbackRule(); + } + + return this.parseToken() || token; + } + + return token; + }; + + _proto.indentation = function indentation() { + var match = this._lexer.source.body.match(/\s*/); + + var indent = 0; + + if (match && match.length === 0) { + var whiteSpaces = match[0]; + var pos = 0; + + while (whiteSpaces.length > pos) { + if (whiteSpaces.charCodeAt(pos) === 9) { + indent += 2; + } else { + indent++; + } + + pos++; + } + } + + return indent; + }; + + _proto._parseTokenConstraint = function _parseTokenConstraint(rule) { + rule.expanded = true; + + var token = this._lookAhead(); + + if (!this._matchToken(token, rule)) { + return { + kind: TokenKind.INVALID, + value: '', + tokenName: rule.tokenName, + ruleName: rule.name + }; + } + + this._advanceToken(); + + var parserToken = this._transformLexerToken(token, rule); + + this._popMatchedRule(parserToken); + + return parserToken; + }; + + _proto._parseListOfTypeConstraint = function _parseListOfTypeConstraint(rule) { + this._pushRule(GraphQLGrammar[rule.listOfType], rule.depth + 1, rule.listOfType, 1, rule.state); + + rule.expanded = true; + var token = this.parseToken(); + return token; + }; + + _proto._parseOfTypeConstraint = function _parseOfTypeConstraint(rule) { + if (rule.expanded) { + this._popMatchedRule(); + + return this.parseToken(); + } + + this._pushRule(rule.ofType, rule.depth + 1, rule.tokenName, 1, rule.state); + + rule.expanded = true; + var token = this.parseToken(); + return token; + }; + + _proto._parsePeekConstraint = function _parsePeekConstraint(rule) { + if (rule.expanded) { + this._popMatchedRule(); + + return this.parseToken(); + } + + while (!rule.matched && rule.index < rule.peek.length - 1) { + rule.index++; + var constraint = rule.peek[rule.index]; + var ifCondition = constraint.ifCondition; + + if (typeof ifCondition === 'string') { + ifCondition = GraphQLGrammar[ifCondition]; + } + + var token = this._lookAhead(); + + if (ifCondition && this._matchToken(token, ifCondition)) { + rule.matched = true; + rule.expanded = true; + + this._pushRule(constraint.expect, rule.depth + 1, '', 1, rule.state); + + token = this.parseToken(); + return token; + } + } + + return { + kind: TokenKind.INVALID, + value: '', + ruleName: rule.name + }; + }; + + _proto._parseConstraintsSetRule = function _parseConstraintsSetRule(rule) { + if (rule.expanded) { + this._popMatchedRule(); + + return this.parseToken(); + } + + for (var index = rule.constraints.length - 1; index >= 0; index--) { + this._pushRule(rule.constraints[index], rule.depth + 1, '', index, rule.state); + } + + rule.expanded = true; + return this.parseToken(); + }; + + _proto._matchToken = function _matchToken(token, rule) { + if (typeof token.value === 'string') { + if (typeof rule.ofValue === 'string' && token.value !== rule.ofValue || Array.isArray(rule.oneOf) && !rule.oneOf.includes(token.value) || typeof rule.ofValue !== 'string' && !Array.isArray(rule.oneOf) && token.kind !== rule.token) { + return false; + } + + return this._butNot(token, rule); + } + + if (token.kind !== rule.token) { + return false; + } + + return this._butNot(token, rule); + }; + + _proto._butNot = function _butNot(token, rule) { + var _this = this; + + if (rule.butNot) { + if (Array.isArray(rule.butNot)) { + if (rule.butNot.reduce(function (matched, constraint) { + return matched || _this._matchToken(token, constraint); + }, false)) { + return false; + } + + return true; + } + + return !this._matchToken(token, rule.butNot); + } + + return true; + }; + + _proto._transformLexerToken = function _transformLexerToken(lexerToken, rule) { + var token; + var ruleName = rule.name || ''; + var tokenName = rule.tokenName || ''; + + if (lexerToken.kind === '<EOF>' || lexerToken.value !== undefined) { + token = { + kind: lexerToken.kind, + value: lexerToken.value || '', + tokenName: tokenName, + ruleName: ruleName + }; + + if (token.kind === TokenKind.STRING) { + token.value = "\"".concat(token.value, "\""); + } else if (token.kind === TokenKind.BLOCK_STRING) { + token.value = "\"\"\"".concat(token.value, "\"\"\""); + } + } else { + token = { + kind: TokenKind.PUNCTUATION, + value: lexerToken.kind, + tokenName: tokenName, + ruleName: ruleName + }; + + if (/^[{([]/.test(token.value)) { + if (this.state.indentLevel !== undefined) { + this.state.levels = this.state.levels.concat(this.state.indentLevel + 1); + } + } else if (/^[})\]]/.test(token.value)) { + this.state.levels.pop(); + } + } + + return token; + }; + + _proto._getNextRule = function _getNextRule() { + return this.state.rules[this.state.rules.length - 1] || null; + }; + + _proto._popMatchedRule = function _popMatchedRule(token) { + var rule = this.state.rules.pop(); + + if (!rule) { + return; + } + + if (token && rule.kind === RuleKind.TOKEN_CONSTRAINT) { + var constraint = rule; + + if (typeof constraint.definitionName === 'string') { + this.state.name = token.value || null; + } else if (typeof constraint.typeName === 'string') { + this.state.type = token.value || null; + } + } + + var nextRule = this._getNextRule(); + + if (!nextRule) { + return; + } + + if (nextRule.depth === rule.depth - 1 && nextRule.expanded && nextRule.kind === RuleKind.CONSTRAINTS_SET_ROOT) { + this.state.rules.pop(); + } + + if (nextRule.depth === rule.depth - 1 && nextRule.expanded && nextRule.kind === RuleKind.LIST_OF_TYPE_CONSTRAINT) { + nextRule.expanded = false; + nextRule.optional = true; + } + }; + + _proto._rollbackRule = function _rollbackRule() { + var _this2 = this; + + if (!this.state.rules.length) { + return; + } + + var popRule = function popRule() { + var lastPoppedRule = _this2.state.rules.pop(); + + if (lastPoppedRule.eatNextOnFail === true) { + _this2.state.rules.pop(); + } + }; + + var poppedRule = this.state.rules.pop(); + + if (!poppedRule) { + return; + } + + var popped = 0; + + var nextRule = this._getNextRule(); + + while (nextRule && (poppedRule.kind !== RuleKind.LIST_OF_TYPE_CONSTRAINT || nextRule.expanded) && nextRule.depth > poppedRule.depth - 1) { + this.state.rules.pop(); + popped++; + nextRule = this._getNextRule(); + } + + if (nextRule && nextRule.expanded) { + if (nextRule.optional === true) { + popRule(); + } else { + if (nextRule.kind === RuleKind.LIST_OF_TYPE_CONSTRAINT && popped === 1) { + this.state.rules.pop(); + return; + } + + this._rollbackRule(); + } + } + }; + + _proto._pushRule = function _pushRule(baseRule, depth, name, step, state) { + var _this$_getNextRule, _this$_getNextRule2, _this$_getNextRule3, _this$_getNextRule4, _this$_getNextRule5, _this$_getNextRule6, _this$_getNextRule7, _this$_getNextRule8, _this$_getNextRule9, _this$_getNextRule10; + + this.state.name = null; + this.state.type = null; + var rule = baseRule; + + switch (this._getRuleKind(rule)) { + case RuleKind.RULE_NAME: + rule = rule; + + this._pushRule(GraphQLGrammar[rule], depth, (typeof name === 'string' ? name : undefined) || rule, step, state); + + break; + + case RuleKind.CONSTRAINTS_SET: + rule = rule; + this.state.rules.push({ + name: name || '', + depth: depth, + expanded: false, + constraints: rule, + constraintsSet: true, + kind: RuleKind.CONSTRAINTS_SET_ROOT, + state: (typeof name === 'string' ? name : undefined) || (typeof state === 'string' ? state : undefined) || ((_this$_getNextRule = this._getNextRule()) === null || _this$_getNextRule === void 0 ? void 0 : _this$_getNextRule.state) || '', + step: typeof step === 'number' ? step : (((_this$_getNextRule2 = this._getNextRule()) === null || _this$_getNextRule2 === void 0 ? void 0 : _this$_getNextRule2.step) || 0) + 1 + }); + break; + + case RuleKind.OF_TYPE_CONSTRAINT: + rule = rule; + this.state.rules.push({ + name: name || '', + ofType: rule.ofType, + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + depth: depth, + expanded: false, + kind: RuleKind.OF_TYPE_CONSTRAINT, + state: (typeof rule.tokenName === 'string' ? rule.tokenName : undefined) || (typeof name === 'string' ? name : undefined) || (typeof state === 'string' ? state : undefined) || ((_this$_getNextRule3 = this._getNextRule()) === null || _this$_getNextRule3 === void 0 ? void 0 : _this$_getNextRule3.state) || '', + step: typeof step === 'number' ? step : (((_this$_getNextRule4 = this._getNextRule()) === null || _this$_getNextRule4 === void 0 ? void 0 : _this$_getNextRule4.step) || 0) + 1 + }); + break; + + case RuleKind.LIST_OF_TYPE_CONSTRAINT: + rule = rule; + this.state.rules.push({ + listOfType: rule.listOfType, + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + name: name || '', + depth: depth, + expanded: false, + kind: RuleKind.LIST_OF_TYPE_CONSTRAINT, + state: (typeof name === 'string' ? name : undefined) || (typeof state === 'string' ? state : undefined) || ((_this$_getNextRule5 = this._getNextRule()) === null || _this$_getNextRule5 === void 0 ? void 0 : _this$_getNextRule5.state) || '', + step: typeof step === 'number' ? step : (((_this$_getNextRule6 = this._getNextRule()) === null || _this$_getNextRule6 === void 0 ? void 0 : _this$_getNextRule6.step) || 0) + 1 + }); + break; + + case RuleKind.TOKEN_CONSTRAINT: + rule = rule; + this.state.rules.push({ + token: rule.token, + ofValue: rule.ofValue, + oneOf: rule.oneOf, + definitionName: Boolean(rule.definitionName), + typeName: Boolean(rule.typeName), + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + name: name || '', + depth: depth, + expanded: false, + kind: RuleKind.TOKEN_CONSTRAINT, + state: (typeof rule.tokenName === 'string' ? rule.tokenName : undefined) || (typeof state === 'string' ? state : undefined) || ((_this$_getNextRule7 = this._getNextRule()) === null || _this$_getNextRule7 === void 0 ? void 0 : _this$_getNextRule7.state) || '', + step: typeof step === 'number' ? step : (((_this$_getNextRule8 = this._getNextRule()) === null || _this$_getNextRule8 === void 0 ? void 0 : _this$_getNextRule8.step) || 0) + 1 + }); + break; + + case RuleKind.PEEK_CONSTRAINT: + rule = rule; + this.state.rules.push({ + peek: rule.peek, + optional: Boolean(rule.optional), + butNot: rule.butNot, + eatNextOnFail: Boolean(rule.eatNextOnFail), + name: name || '', + depth: depth, + index: -1, + matched: false, + expanded: false, + kind: RuleKind.PEEK_CONSTRAINT, + state: (typeof state === 'string' ? state : undefined) || ((_this$_getNextRule9 = this._getNextRule()) === null || _this$_getNextRule9 === void 0 ? void 0 : _this$_getNextRule9.state) || '', + step: typeof step === 'number' ? step : (((_this$_getNextRule10 = this._getNextRule()) === null || _this$_getNextRule10 === void 0 ? void 0 : _this$_getNextRule10.step) || 0) + 1 + }); + break; + } + }; + + _proto._getRuleKind = function _getRuleKind(rule) { + if (Array.isArray(rule)) { + return RuleKind.CONSTRAINTS_SET; + } + + if (rule.constraintsSet === true) { + return RuleKind.CONSTRAINTS_SET_ROOT; + } + + if (typeof rule === 'string') { + return RuleKind.RULE_NAME; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'ofType')) { + return RuleKind.OF_TYPE_CONSTRAINT; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'listOfType')) { + return RuleKind.LIST_OF_TYPE_CONSTRAINT; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'peek')) { + return RuleKind.PEEK_CONSTRAINT; + } + + if (Object.prototype.hasOwnProperty.call(rule, 'token')) { + return RuleKind.TOKEN_CONSTRAINT; + } + + return RuleKind.INVALID; + }; + + _proto._advanceToken = function _advanceToken() { + return this._lexer.advance(); + }; + + _proto._lookAhead = function _lookAhead() { + try { + return this._lexer.lookahead(); + } catch (err) { + return { + kind: TokenKind.INVALID, + value: '' + }; + } + }; + + return OnlineParser; +}(); diff --git a/school/node_modules/graphql/language/index.d.ts b/school/node_modules/graphql/language/index.d.ts new file mode 100644 index 0000000..8de9321 --- /dev/null +++ b/school/node_modules/graphql/language/index.d.ts @@ -0,0 +1,96 @@ +export { Source } from './source'; +export { getLocation, SourceLocation } from './location'; + +export { printLocation, printSourceLocation } from './printLocation'; + +export { Kind, KindEnum } from './kinds'; +export { TokenKind, TokenKindEnum } from './tokenKind'; +export { Lexer } from './lexer'; +export { parse, parseValue, parseType, ParseOptions } from './parser'; +export { print } from './printer'; +export { + visit, + visitInParallel, + getVisitFn, + BREAK, + ASTVisitor, + Visitor, + VisitFn, + VisitorKeyMap, + ASTVisitorKeyMap, +} from './visitor'; + +export { + Location, + Token, + ASTNode, + ASTKindToNode, + // Each kind of AST node + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from './ast'; + +export { + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, +} from './predicates'; + +export { DirectiveLocation, DirectiveLocationEnum } from './directiveLocation'; diff --git a/school/node_modules/graphql/language/index.js b/school/node_modules/graphql/language/index.js new file mode 100644 index 0000000..63e564d --- /dev/null +++ b/school/node_modules/graphql/language/index.js @@ -0,0 +1,191 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "Source", { + enumerable: true, + get: function get() { + return _source.Source; + } +}); +Object.defineProperty(exports, "getLocation", { + enumerable: true, + get: function get() { + return _location.getLocation; + } +}); +Object.defineProperty(exports, "printLocation", { + enumerable: true, + get: function get() { + return _printLocation.printLocation; + } +}); +Object.defineProperty(exports, "printSourceLocation", { + enumerable: true, + get: function get() { + return _printLocation.printSourceLocation; + } +}); +Object.defineProperty(exports, "Kind", { + enumerable: true, + get: function get() { + return _kinds.Kind; + } +}); +Object.defineProperty(exports, "TokenKind", { + enumerable: true, + get: function get() { + return _tokenKind.TokenKind; + } +}); +Object.defineProperty(exports, "Lexer", { + enumerable: true, + get: function get() { + return _lexer.Lexer; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _parser.parse; + } +}); +Object.defineProperty(exports, "parseValue", { + enumerable: true, + get: function get() { + return _parser.parseValue; + } +}); +Object.defineProperty(exports, "parseType", { + enumerable: true, + get: function get() { + return _parser.parseType; + } +}); +Object.defineProperty(exports, "print", { + enumerable: true, + get: function get() { + return _printer.print; + } +}); +Object.defineProperty(exports, "visit", { + enumerable: true, + get: function get() { + return _visitor.visit; + } +}); +Object.defineProperty(exports, "visitInParallel", { + enumerable: true, + get: function get() { + return _visitor.visitInParallel; + } +}); +Object.defineProperty(exports, "getVisitFn", { + enumerable: true, + get: function get() { + return _visitor.getVisitFn; + } +}); +Object.defineProperty(exports, "BREAK", { + enumerable: true, + get: function get() { + return _visitor.BREAK; + } +}); +Object.defineProperty(exports, "Location", { + enumerable: true, + get: function get() { + return _ast.Location; + } +}); +Object.defineProperty(exports, "Token", { + enumerable: true, + get: function get() { + return _ast.Token; + } +}); +Object.defineProperty(exports, "isDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isDefinitionNode; + } +}); +Object.defineProperty(exports, "isExecutableDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isExecutableDefinitionNode; + } +}); +Object.defineProperty(exports, "isSelectionNode", { + enumerable: true, + get: function get() { + return _predicates.isSelectionNode; + } +}); +Object.defineProperty(exports, "isValueNode", { + enumerable: true, + get: function get() { + return _predicates.isValueNode; + } +}); +Object.defineProperty(exports, "isTypeNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeNode; + } +}); +Object.defineProperty(exports, "isTypeSystemDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeSystemDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeSystemExtensionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeSystemExtensionNode; + } +}); +Object.defineProperty(exports, "isTypeExtensionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeExtensionNode; + } +}); +Object.defineProperty(exports, "DirectiveLocation", { + enumerable: true, + get: function get() { + return _directiveLocation.DirectiveLocation; + } +}); + +var _source = require("./source.js"); + +var _location = require("./location.js"); + +var _printLocation = require("./printLocation.js"); + +var _kinds = require("./kinds.js"); + +var _tokenKind = require("./tokenKind.js"); + +var _lexer = require("./lexer.js"); + +var _parser = require("./parser.js"); + +var _printer = require("./printer.js"); + +var _visitor = require("./visitor.js"); + +var _ast = require("./ast.js"); + +var _predicates = require("./predicates.js"); + +var _directiveLocation = require("./directiveLocation.js"); diff --git a/school/node_modules/graphql/language/index.js.flow b/school/node_modules/graphql/language/index.js.flow new file mode 100644 index 0000000..c604e46 --- /dev/null +++ b/school/node_modules/graphql/language/index.js.flow @@ -0,0 +1,98 @@ +// @flow strict +export { Source } from './source'; + +export { getLocation } from './location'; +export type { SourceLocation } from './location'; + +export { printLocation, printSourceLocation } from './printLocation'; + +export { Kind } from './kinds'; +export type { KindEnum } from './kinds'; + +export { TokenKind } from './tokenKind'; +export type { TokenKindEnum } from './tokenKind'; + +export { Lexer } from './lexer'; + +export { parse, parseValue, parseType } from './parser'; +export type { ParseOptions } from './parser'; + +export { print } from './printer'; + +export { visit, visitInParallel, getVisitFn, BREAK } from './visitor'; +export type { ASTVisitor, Visitor, VisitFn, VisitorKeyMap } from './visitor'; + +export { Location, Token } from './ast'; +export type { + ASTNode, + ASTKindToNode, + // Each kind of AST node + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from './ast'; + +export { + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, +} from './predicates'; + +export { DirectiveLocation } from './directiveLocation'; +export type { DirectiveLocationEnum } from './directiveLocation'; diff --git a/school/node_modules/graphql/language/index.mjs b/school/node_modules/graphql/language/index.mjs new file mode 100644 index 0000000..682e1a8 --- /dev/null +++ b/school/node_modules/graphql/language/index.mjs @@ -0,0 +1,12 @@ +export { Source } from "./source.mjs"; +export { getLocation } from "./location.mjs"; +export { printLocation, printSourceLocation } from "./printLocation.mjs"; +export { Kind } from "./kinds.mjs"; +export { TokenKind } from "./tokenKind.mjs"; +export { Lexer } from "./lexer.mjs"; +export { parse, parseValue, parseType } from "./parser.mjs"; +export { print } from "./printer.mjs"; +export { visit, visitInParallel, getVisitFn, BREAK } from "./visitor.mjs"; +export { Location, Token } from "./ast.mjs"; +export { isDefinitionNode, isExecutableDefinitionNode, isSelectionNode, isValueNode, isTypeNode, isTypeSystemDefinitionNode, isTypeDefinitionNode, isTypeSystemExtensionNode, isTypeExtensionNode } from "./predicates.mjs"; +export { DirectiveLocation } from "./directiveLocation.mjs"; diff --git a/school/node_modules/graphql/language/kinds.d.ts b/school/node_modules/graphql/language/kinds.d.ts new file mode 100644 index 0000000..35a7239 --- /dev/null +++ b/school/node_modules/graphql/language/kinds.d.ts @@ -0,0 +1,74 @@ +/** + * The set of allowed kind values for AST nodes. + */ +export const Kind: { + // Name + NAME: 'Name'; + + // Document + DOCUMENT: 'Document'; + OPERATION_DEFINITION: 'OperationDefinition'; + VARIABLE_DEFINITION: 'VariableDefinition'; + SELECTION_SET: 'SelectionSet'; + FIELD: 'Field'; + ARGUMENT: 'Argument'; + + // Fragments + FRAGMENT_SPREAD: 'FragmentSpread'; + INLINE_FRAGMENT: 'InlineFragment'; + FRAGMENT_DEFINITION: 'FragmentDefinition'; + + // Values + VARIABLE: 'Variable'; + INT: 'IntValue'; + FLOAT: 'FloatValue'; + STRING: 'StringValue'; + BOOLEAN: 'BooleanValue'; + NULL: 'NullValue'; + ENUM: 'EnumValue'; + LIST: 'ListValue'; + OBJECT: 'ObjectValue'; + OBJECT_FIELD: 'ObjectField'; + + // Directives + DIRECTIVE: 'Directive'; + + // Types + NAMED_TYPE: 'NamedType'; + LIST_TYPE: 'ListType'; + NON_NULL_TYPE: 'NonNullType'; + + // Type System Definitions + SCHEMA_DEFINITION: 'SchemaDefinition'; + OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition'; + + // Type Definitions + SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition'; + OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition'; + FIELD_DEFINITION: 'FieldDefinition'; + INPUT_VALUE_DEFINITION: 'InputValueDefinition'; + INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition'; + UNION_TYPE_DEFINITION: 'UnionTypeDefinition'; + ENUM_TYPE_DEFINITION: 'EnumTypeDefinition'; + ENUM_VALUE_DEFINITION: 'EnumValueDefinition'; + INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition'; + + // Directive Definitions + DIRECTIVE_DEFINITION: 'DirectiveDefinition'; + + // Type System Extensions + SCHEMA_EXTENSION: 'SchemaExtension'; + + // Type Extensions + SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension'; + OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension'; + INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension'; + UNION_TYPE_EXTENSION: 'UnionTypeExtension'; + ENUM_TYPE_EXTENSION: 'EnumTypeExtension'; + INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension'; +}; + +/** + * The enum type representing the possible kind values of AST nodes. + */ +export type KindEnum = typeof Kind[keyof typeof Kind]; diff --git a/school/node_modules/graphql/language/kinds.js b/school/node_modules/graphql/language/kinds.js new file mode 100644 index 0000000..32b90c4 --- /dev/null +++ b/school/node_modules/graphql/language/kinds.js @@ -0,0 +1,71 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Kind = void 0; + +/** + * The set of allowed kind values for AST nodes. + */ +var Kind = Object.freeze({ + // Name + NAME: 'Name', + // Document + DOCUMENT: 'Document', + OPERATION_DEFINITION: 'OperationDefinition', + VARIABLE_DEFINITION: 'VariableDefinition', + SELECTION_SET: 'SelectionSet', + FIELD: 'Field', + ARGUMENT: 'Argument', + // Fragments + FRAGMENT_SPREAD: 'FragmentSpread', + INLINE_FRAGMENT: 'InlineFragment', + FRAGMENT_DEFINITION: 'FragmentDefinition', + // Values + VARIABLE: 'Variable', + INT: 'IntValue', + FLOAT: 'FloatValue', + STRING: 'StringValue', + BOOLEAN: 'BooleanValue', + NULL: 'NullValue', + ENUM: 'EnumValue', + LIST: 'ListValue', + OBJECT: 'ObjectValue', + OBJECT_FIELD: 'ObjectField', + // Directives + DIRECTIVE: 'Directive', + // Types + NAMED_TYPE: 'NamedType', + LIST_TYPE: 'ListType', + NON_NULL_TYPE: 'NonNullType', + // Type System Definitions + SCHEMA_DEFINITION: 'SchemaDefinition', + OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition', + // Type Definitions + SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition', + OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition', + FIELD_DEFINITION: 'FieldDefinition', + INPUT_VALUE_DEFINITION: 'InputValueDefinition', + INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition', + UNION_TYPE_DEFINITION: 'UnionTypeDefinition', + ENUM_TYPE_DEFINITION: 'EnumTypeDefinition', + ENUM_VALUE_DEFINITION: 'EnumValueDefinition', + INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition', + // Directive Definitions + DIRECTIVE_DEFINITION: 'DirectiveDefinition', + // Type System Extensions + SCHEMA_EXTENSION: 'SchemaExtension', + // Type Extensions + SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension', + OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension', + INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension', + UNION_TYPE_EXTENSION: 'UnionTypeExtension', + ENUM_TYPE_EXTENSION: 'EnumTypeExtension', + INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension' +}); +/** + * The enum type representing the possible kind values of AST nodes. + */ + +exports.Kind = Kind; diff --git a/school/node_modules/graphql/language/kinds.js.flow b/school/node_modules/graphql/language/kinds.js.flow new file mode 100644 index 0000000..8826fa1 --- /dev/null +++ b/school/node_modules/graphql/language/kinds.js.flow @@ -0,0 +1,75 @@ +// @flow strict +/** + * The set of allowed kind values for AST nodes. + */ +export const Kind = Object.freeze({ + // Name + NAME: 'Name', + + // Document + DOCUMENT: 'Document', + OPERATION_DEFINITION: 'OperationDefinition', + VARIABLE_DEFINITION: 'VariableDefinition', + SELECTION_SET: 'SelectionSet', + FIELD: 'Field', + ARGUMENT: 'Argument', + + // Fragments + FRAGMENT_SPREAD: 'FragmentSpread', + INLINE_FRAGMENT: 'InlineFragment', + FRAGMENT_DEFINITION: 'FragmentDefinition', + + // Values + VARIABLE: 'Variable', + INT: 'IntValue', + FLOAT: 'FloatValue', + STRING: 'StringValue', + BOOLEAN: 'BooleanValue', + NULL: 'NullValue', + ENUM: 'EnumValue', + LIST: 'ListValue', + OBJECT: 'ObjectValue', + OBJECT_FIELD: 'ObjectField', + + // Directives + DIRECTIVE: 'Directive', + + // Types + NAMED_TYPE: 'NamedType', + LIST_TYPE: 'ListType', + NON_NULL_TYPE: 'NonNullType', + + // Type System Definitions + SCHEMA_DEFINITION: 'SchemaDefinition', + OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition', + + // Type Definitions + SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition', + OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition', + FIELD_DEFINITION: 'FieldDefinition', + INPUT_VALUE_DEFINITION: 'InputValueDefinition', + INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition', + UNION_TYPE_DEFINITION: 'UnionTypeDefinition', + ENUM_TYPE_DEFINITION: 'EnumTypeDefinition', + ENUM_VALUE_DEFINITION: 'EnumValueDefinition', + INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition', + + // Directive Definitions + DIRECTIVE_DEFINITION: 'DirectiveDefinition', + + // Type System Extensions + SCHEMA_EXTENSION: 'SchemaExtension', + + // Type Extensions + SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension', + OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension', + INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension', + UNION_TYPE_EXTENSION: 'UnionTypeExtension', + ENUM_TYPE_EXTENSION: 'EnumTypeExtension', + INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension', +}); + +/** + * The enum type representing the possible kind values of AST nodes. + */ +export type KindEnum = $Values<typeof Kind>; diff --git a/school/node_modules/graphql/language/kinds.mjs b/school/node_modules/graphql/language/kinds.mjs new file mode 100644 index 0000000..b439c71 --- /dev/null +++ b/school/node_modules/graphql/language/kinds.mjs @@ -0,0 +1,62 @@ +/** + * The set of allowed kind values for AST nodes. + */ +export var Kind = Object.freeze({ + // Name + NAME: 'Name', + // Document + DOCUMENT: 'Document', + OPERATION_DEFINITION: 'OperationDefinition', + VARIABLE_DEFINITION: 'VariableDefinition', + SELECTION_SET: 'SelectionSet', + FIELD: 'Field', + ARGUMENT: 'Argument', + // Fragments + FRAGMENT_SPREAD: 'FragmentSpread', + INLINE_FRAGMENT: 'InlineFragment', + FRAGMENT_DEFINITION: 'FragmentDefinition', + // Values + VARIABLE: 'Variable', + INT: 'IntValue', + FLOAT: 'FloatValue', + STRING: 'StringValue', + BOOLEAN: 'BooleanValue', + NULL: 'NullValue', + ENUM: 'EnumValue', + LIST: 'ListValue', + OBJECT: 'ObjectValue', + OBJECT_FIELD: 'ObjectField', + // Directives + DIRECTIVE: 'Directive', + // Types + NAMED_TYPE: 'NamedType', + LIST_TYPE: 'ListType', + NON_NULL_TYPE: 'NonNullType', + // Type System Definitions + SCHEMA_DEFINITION: 'SchemaDefinition', + OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition', + // Type Definitions + SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition', + OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition', + FIELD_DEFINITION: 'FieldDefinition', + INPUT_VALUE_DEFINITION: 'InputValueDefinition', + INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition', + UNION_TYPE_DEFINITION: 'UnionTypeDefinition', + ENUM_TYPE_DEFINITION: 'EnumTypeDefinition', + ENUM_VALUE_DEFINITION: 'EnumValueDefinition', + INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition', + // Directive Definitions + DIRECTIVE_DEFINITION: 'DirectiveDefinition', + // Type System Extensions + SCHEMA_EXTENSION: 'SchemaExtension', + // Type Extensions + SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension', + OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension', + INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension', + UNION_TYPE_EXTENSION: 'UnionTypeExtension', + ENUM_TYPE_EXTENSION: 'EnumTypeExtension', + INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension' +}); +/** + * The enum type representing the possible kind values of AST nodes. + */ diff --git a/school/node_modules/graphql/language/lexer.d.ts b/school/node_modules/graphql/language/lexer.d.ts new file mode 100644 index 0000000..40dbf9a --- /dev/null +++ b/school/node_modules/graphql/language/lexer.d.ts @@ -0,0 +1,58 @@ +import { Token } from './ast'; +import { Source } from './source'; +import { TokenKindEnum } from './tokenKind'; + +/** + * Given a Source object, this returns a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +export class Lexer { + source: Source; + + /** + * The previously focused non-ignored token. + */ + lastToken: Token; + + /** + * The currently focused non-ignored token. + */ + token: Token; + + /** + * The (1-indexed) line containing the current token. + */ + line: number; + + /** + * The character offset at which the current line begins. + */ + lineStart: number; + + constructor(source: Source); + + /** + * Advances the token stream to the next non-ignored token. + */ + advance(): Token; + + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the state of Lexer. + */ + lookahead(): Token; +} + +/** + * @internal + */ +export function isPunctuatorToken(token: Token): boolean; + +/** + * @internal + */ +export function isPunctuatorTokenKind(kind: TokenKindEnum): boolean; diff --git a/school/node_modules/graphql/language/lexer.js b/school/node_modules/graphql/language/lexer.js new file mode 100644 index 0000000..7b2ee16 --- /dev/null +++ b/school/node_modules/graphql/language/lexer.js @@ -0,0 +1,690 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isPunctuatorTokenKind = isPunctuatorTokenKind; +exports.Lexer = void 0; + +var _syntaxError = require("../error/syntaxError.js"); + +var _ast = require("./ast.js"); + +var _tokenKind = require("./tokenKind.js"); + +var _blockString = require("./blockString.js"); + +/** + * Given a Source object, creates a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +var Lexer = /*#__PURE__*/function () { + /** + * The previously focused non-ignored token. + */ + + /** + * The currently focused non-ignored token. + */ + + /** + * The (1-indexed) line containing the current token. + */ + + /** + * The character offset at which the current line begins. + */ + function Lexer(source) { + var startOfFileToken = new _ast.Token(_tokenKind.TokenKind.SOF, 0, 0, 0, 0, null); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + this.line = 1; + this.lineStart = 0; + } + /** + * Advances the token stream to the next non-ignored token. + */ + + + var _proto = Lexer.prototype; + + _proto.advance = function advance() { + this.lastToken = this.token; + var token = this.token = this.lookahead(); + return token; + } + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the state of Lexer. + */ + ; + + _proto.lookahead = function lookahead() { + var token = this.token; + + if (token.kind !== _tokenKind.TokenKind.EOF) { + do { + var _token$next; + + // Note: next is only mutable during parsing, so we cast to allow this. + token = (_token$next = token.next) !== null && _token$next !== void 0 ? _token$next : token.next = readToken(this, token); + } while (token.kind === _tokenKind.TokenKind.COMMENT); + } + + return token; + }; + + return Lexer; +}(); +/** + * @internal + */ + + +exports.Lexer = Lexer; + +function isPunctuatorTokenKind(kind) { + return kind === _tokenKind.TokenKind.BANG || kind === _tokenKind.TokenKind.DOLLAR || kind === _tokenKind.TokenKind.AMP || kind === _tokenKind.TokenKind.PAREN_L || kind === _tokenKind.TokenKind.PAREN_R || kind === _tokenKind.TokenKind.SPREAD || kind === _tokenKind.TokenKind.COLON || kind === _tokenKind.TokenKind.EQUALS || kind === _tokenKind.TokenKind.AT || kind === _tokenKind.TokenKind.BRACKET_L || kind === _tokenKind.TokenKind.BRACKET_R || kind === _tokenKind.TokenKind.BRACE_L || kind === _tokenKind.TokenKind.PIPE || kind === _tokenKind.TokenKind.BRACE_R; +} + +function printCharCode(code) { + return (// NaN/undefined represents access beyond the end of the file. + isNaN(code) ? _tokenKind.TokenKind.EOF : // Trust JSON for ASCII. + code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form. + "\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"") + ); +} +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace until it finds the next lexable token, then lexes + * punctuators immediately or calls the appropriate helper function for more + * complicated tokens. + */ + + +function readToken(lexer, prev) { + var source = lexer.source; + var body = source.body; + var bodyLength = body.length; + var pos = prev.end; + + while (pos < bodyLength) { + var code = body.charCodeAt(pos); + var _line = lexer.line; + + var _col = 1 + pos - lexer.lineStart; // SourceCharacter + + + switch (code) { + case 0xfeff: // <BOM> + + case 9: // \t + + case 32: // <space> + + case 44: + // , + ++pos; + continue; + + case 10: + // \n + ++pos; + ++lexer.line; + lexer.lineStart = pos; + continue; + + case 13: + // \r + if (body.charCodeAt(pos + 1) === 10) { + pos += 2; + } else { + ++pos; + } + + ++lexer.line; + lexer.lineStart = pos; + continue; + + case 33: + // ! + return new _ast.Token(_tokenKind.TokenKind.BANG, pos, pos + 1, _line, _col, prev); + + case 35: + // # + return readComment(source, pos, _line, _col, prev); + + case 36: + // $ + return new _ast.Token(_tokenKind.TokenKind.DOLLAR, pos, pos + 1, _line, _col, prev); + + case 38: + // & + return new _ast.Token(_tokenKind.TokenKind.AMP, pos, pos + 1, _line, _col, prev); + + case 40: + // ( + return new _ast.Token(_tokenKind.TokenKind.PAREN_L, pos, pos + 1, _line, _col, prev); + + case 41: + // ) + return new _ast.Token(_tokenKind.TokenKind.PAREN_R, pos, pos + 1, _line, _col, prev); + + case 46: + // . + if (body.charCodeAt(pos + 1) === 46 && body.charCodeAt(pos + 2) === 46) { + return new _ast.Token(_tokenKind.TokenKind.SPREAD, pos, pos + 3, _line, _col, prev); + } + + break; + + case 58: + // : + return new _ast.Token(_tokenKind.TokenKind.COLON, pos, pos + 1, _line, _col, prev); + + case 61: + // = + return new _ast.Token(_tokenKind.TokenKind.EQUALS, pos, pos + 1, _line, _col, prev); + + case 64: + // @ + return new _ast.Token(_tokenKind.TokenKind.AT, pos, pos + 1, _line, _col, prev); + + case 91: + // [ + return new _ast.Token(_tokenKind.TokenKind.BRACKET_L, pos, pos + 1, _line, _col, prev); + + case 93: + // ] + return new _ast.Token(_tokenKind.TokenKind.BRACKET_R, pos, pos + 1, _line, _col, prev); + + case 123: + // { + return new _ast.Token(_tokenKind.TokenKind.BRACE_L, pos, pos + 1, _line, _col, prev); + + case 124: + // | + return new _ast.Token(_tokenKind.TokenKind.PIPE, pos, pos + 1, _line, _col, prev); + + case 125: + // } + return new _ast.Token(_tokenKind.TokenKind.BRACE_R, pos, pos + 1, _line, _col, prev); + + case 34: + // " + if (body.charCodeAt(pos + 1) === 34 && body.charCodeAt(pos + 2) === 34) { + return readBlockString(source, pos, _line, _col, prev, lexer); + } + + return readString(source, pos, _line, _col, prev); + + case 45: // - + + case 48: // 0 + + case 49: // 1 + + case 50: // 2 + + case 51: // 3 + + case 52: // 4 + + case 53: // 5 + + case 54: // 6 + + case 55: // 7 + + case 56: // 8 + + case 57: + // 9 + return readNumber(source, pos, code, _line, _col, prev); + + case 65: // A + + case 66: // B + + case 67: // C + + case 68: // D + + case 69: // E + + case 70: // F + + case 71: // G + + case 72: // H + + case 73: // I + + case 74: // J + + case 75: // K + + case 76: // L + + case 77: // M + + case 78: // N + + case 79: // O + + case 80: // P + + case 81: // Q + + case 82: // R + + case 83: // S + + case 84: // T + + case 85: // U + + case 86: // V + + case 87: // W + + case 88: // X + + case 89: // Y + + case 90: // Z + + case 95: // _ + + case 97: // a + + case 98: // b + + case 99: // c + + case 100: // d + + case 101: // e + + case 102: // f + + case 103: // g + + case 104: // h + + case 105: // i + + case 106: // j + + case 107: // k + + case 108: // l + + case 109: // m + + case 110: // n + + case 111: // o + + case 112: // p + + case 113: // q + + case 114: // r + + case 115: // s + + case 116: // t + + case 117: // u + + case 118: // v + + case 119: // w + + case 120: // x + + case 121: // y + + case 122: + // z + return readName(source, pos, _line, _col, prev); + } + + throw (0, _syntaxError.syntaxError)(source, pos, unexpectedCharacterMessage(code)); + } + + var line = lexer.line; + var col = 1 + pos - lexer.lineStart; + return new _ast.Token(_tokenKind.TokenKind.EOF, bodyLength, bodyLength, line, col, prev); +} +/** + * Report a message that an unexpected character was encountered. + */ + + +function unexpectedCharacterMessage(code) { + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + return "Cannot contain the invalid character ".concat(printCharCode(code), "."); + } + + if (code === 39) { + // ' + return 'Unexpected single quote character (\'), did you mean to use a double quote (")?'; + } + + return "Cannot parse the unexpected character ".concat(printCharCode(code), "."); +} +/** + * Reads a comment token from the source file. + * + * #[\u0009\u0020-\uFFFF]* + */ + + +function readComment(source, start, line, col, prev) { + var body = source.body; + var code; + var position = start; + + do { + code = body.charCodeAt(++position); + } while (!isNaN(code) && ( // SourceCharacter but not LineTerminator + code > 0x001f || code === 0x0009)); + + return new _ast.Token(_tokenKind.TokenKind.COMMENT, start, position, line, col, prev, body.slice(start + 1, position)); +} +/** + * Reads a number token from the source file, either a float + * or an int depending on whether a decimal point appears. + * + * Int: -?(0|[1-9][0-9]*) + * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? + */ + + +function readNumber(source, start, firstCode, line, col, prev) { + var body = source.body; + var code = firstCode; + var position = start; + var isFloat = false; + + if (code === 45) { + // - + code = body.charCodeAt(++position); + } + + if (code === 48) { + // 0 + code = body.charCodeAt(++position); + + if (code >= 48 && code <= 57) { + throw (0, _syntaxError.syntaxError)(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), ".")); + } + } else { + position = readDigits(source, position, code); + code = body.charCodeAt(position); + } + + if (code === 46) { + // . + isFloat = true; + code = body.charCodeAt(++position); + position = readDigits(source, position, code); + code = body.charCodeAt(position); + } + + if (code === 69 || code === 101) { + // E e + isFloat = true; + code = body.charCodeAt(++position); + + if (code === 43 || code === 45) { + // + - + code = body.charCodeAt(++position); + } + + position = readDigits(source, position, code); + code = body.charCodeAt(position); + } // Numbers cannot be followed by . or NameStart + + + if (code === 46 || isNameStart(code)) { + throw (0, _syntaxError.syntaxError)(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), ".")); + } + + return new _ast.Token(isFloat ? _tokenKind.TokenKind.FLOAT : _tokenKind.TokenKind.INT, start, position, line, col, prev, body.slice(start, position)); +} +/** + * Returns the new position in the source after reading digits. + */ + + +function readDigits(source, start, firstCode) { + var body = source.body; + var position = start; + var code = firstCode; + + if (code >= 48 && code <= 57) { + // 0 - 9 + do { + code = body.charCodeAt(++position); + } while (code >= 48 && code <= 57); // 0 - 9 + + + return position; + } + + throw (0, _syntaxError.syntaxError)(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), ".")); +} +/** + * Reads a string token from the source file. + * + * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*" + */ + + +function readString(source, start, line, col, prev) { + var body = source.body; + var position = start + 1; + var chunkStart = position; + var code = 0; + var value = ''; + + while (position < body.length && !isNaN(code = body.charCodeAt(position)) && // not LineTerminator + code !== 0x000a && code !== 0x000d) { + // Closing Quote (") + if (code === 34) { + value += body.slice(chunkStart, position); + return new _ast.Token(_tokenKind.TokenKind.STRING, start, position + 1, line, col, prev, value); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009) { + throw (0, _syntaxError.syntaxError)(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } + + ++position; + + if (code === 92) { + // \ + value += body.slice(chunkStart, position - 1); + code = body.charCodeAt(position); + + switch (code) { + case 34: + value += '"'; + break; + + case 47: + value += '/'; + break; + + case 92: + value += '\\'; + break; + + case 98: + value += '\b'; + break; + + case 102: + value += '\f'; + break; + + case 110: + value += '\n'; + break; + + case 114: + value += '\r'; + break; + + case 116: + value += '\t'; + break; + + case 117: + { + // uXXXX + var charCode = uniCharCode(body.charCodeAt(position + 1), body.charCodeAt(position + 2), body.charCodeAt(position + 3), body.charCodeAt(position + 4)); + + if (charCode < 0) { + var invalidSequence = body.slice(position + 1, position + 5); + throw (0, _syntaxError.syntaxError)(source, position, "Invalid character escape sequence: \\u".concat(invalidSequence, ".")); + } + + value += String.fromCharCode(charCode); + position += 4; + break; + } + + default: + throw (0, _syntaxError.syntaxError)(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), ".")); + } + + ++position; + chunkStart = position; + } + } + + throw (0, _syntaxError.syntaxError)(source, position, 'Unterminated string.'); +} +/** + * Reads a block string token from the source file. + * + * """("?"?(\\"""|\\(?!=""")|[^"\\]))*""" + */ + + +function readBlockString(source, start, line, col, prev, lexer) { + var body = source.body; + var position = start + 3; + var chunkStart = position; + var code = 0; + var rawValue = ''; + + while (position < body.length && !isNaN(code = body.charCodeAt(position))) { + // Closing Triple-Quote (""") + if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) { + rawValue += body.slice(chunkStart, position); + return new _ast.Token(_tokenKind.TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, (0, _blockString.dedentBlockStringValue)(rawValue)); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + throw (0, _syntaxError.syntaxError)(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } + + if (code === 10) { + // new line + ++position; + ++lexer.line; + lexer.lineStart = position; + } else if (code === 13) { + // carriage return + if (body.charCodeAt(position + 1) === 10) { + position += 2; + } else { + ++position; + } + + ++lexer.line; + lexer.lineStart = position; + } else if ( // Escape Triple-Quote (\""") + code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) { + rawValue += body.slice(chunkStart, position) + '"""'; + position += 4; + chunkStart = position; + } else { + ++position; + } + } + + throw (0, _syntaxError.syntaxError)(source, position, 'Unterminated string.'); +} +/** + * Converts four hexadecimal chars to the integer that the + * string represents. For example, uniCharCode('0','0','0','f') + * will return 15, and uniCharCode('0','0','f','f') returns 255. + * + * Returns a negative number on error, if a char was invalid. + * + * This is implemented by noting that char2hex() returns -1 on error, + * which means the result of ORing the char2hex() will also be negative. + */ + + +function uniCharCode(a, b, c, d) { + return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d); +} +/** + * Converts a hex character to its integer value. + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 on error. + */ + + +function char2hex(a) { + return a >= 48 && a <= 57 ? a - 48 // 0-9 + : a >= 65 && a <= 70 ? a - 55 // A-F + : a >= 97 && a <= 102 ? a - 87 // a-f + : -1; +} +/** + * Reads an alphanumeric + underscore name from the source. + * + * [_A-Za-z][_0-9A-Za-z]* + */ + + +function readName(source, start, line, col, prev) { + var body = source.body; + var bodyLength = body.length; + var position = start + 1; + var code = 0; + + while (position !== bodyLength && !isNaN(code = body.charCodeAt(position)) && (code === 95 || // _ + code >= 48 && code <= 57 || // 0-9 + code >= 65 && code <= 90 || // A-Z + code >= 97 && code <= 122) // a-z + ) { + ++position; + } + + return new _ast.Token(_tokenKind.TokenKind.NAME, start, position, line, col, prev, body.slice(start, position)); +} // _ A-Z a-z + + +function isNameStart(code) { + return code === 95 || code >= 65 && code <= 90 || code >= 97 && code <= 122; +} diff --git a/school/node_modules/graphql/language/lexer.js.flow b/school/node_modules/graphql/language/lexer.js.flow new file mode 100644 index 0000000..32dba0c --- /dev/null +++ b/school/node_modules/graphql/language/lexer.js.flow @@ -0,0 +1,701 @@ +// @flow strict +import { syntaxError } from '../error/syntaxError'; + +import type { Source } from './source'; +import type { TokenKindEnum } from './tokenKind'; +import { Token } from './ast'; +import { TokenKind } from './tokenKind'; +import { dedentBlockStringValue } from './blockString'; + +/** + * Given a Source object, creates a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +export class Lexer { + source: Source; + + /** + * The previously focused non-ignored token. + */ + lastToken: Token; + + /** + * The currently focused non-ignored token. + */ + token: Token; + + /** + * The (1-indexed) line containing the current token. + */ + line: number; + + /** + * The character offset at which the current line begins. + */ + lineStart: number; + + constructor(source: Source) { + const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0, null); + + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + this.line = 1; + this.lineStart = 0; + } + + /** + * Advances the token stream to the next non-ignored token. + */ + advance(): Token { + this.lastToken = this.token; + const token = (this.token = this.lookahead()); + return token; + } + + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the state of Lexer. + */ + lookahead(): Token { + let token = this.token; + if (token.kind !== TokenKind.EOF) { + do { + // Note: next is only mutable during parsing, so we cast to allow this. + token = token.next ?? ((token: any).next = readToken(this, token)); + } while (token.kind === TokenKind.COMMENT); + } + return token; + } +} + +/** + * @internal + */ +export function isPunctuatorTokenKind(kind: TokenKindEnum): boolean %checks { + return ( + kind === TokenKind.BANG || + kind === TokenKind.DOLLAR || + kind === TokenKind.AMP || + kind === TokenKind.PAREN_L || + kind === TokenKind.PAREN_R || + kind === TokenKind.SPREAD || + kind === TokenKind.COLON || + kind === TokenKind.EQUALS || + kind === TokenKind.AT || + kind === TokenKind.BRACKET_L || + kind === TokenKind.BRACKET_R || + kind === TokenKind.BRACE_L || + kind === TokenKind.PIPE || + kind === TokenKind.BRACE_R + ); +} + +function printCharCode(code: number): string { + return ( + // NaN/undefined represents access beyond the end of the file. + isNaN(code) + ? TokenKind.EOF + : // Trust JSON for ASCII. + code < 0x007f + ? JSON.stringify(String.fromCharCode(code)) + : // Otherwise print the escaped form. + `"\\u${('00' + code.toString(16).toUpperCase()).slice(-4)}"` + ); +} + +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace until it finds the next lexable token, then lexes + * punctuators immediately or calls the appropriate helper function for more + * complicated tokens. + */ +function readToken(lexer: Lexer, prev: Token): Token { + const source = lexer.source; + const body = source.body; + const bodyLength = body.length; + + let pos = prev.end; + while (pos < bodyLength) { + const code = body.charCodeAt(pos); + + const line = lexer.line; + const col = 1 + pos - lexer.lineStart; + + // SourceCharacter + switch (code) { + case 0xfeff: // <BOM> + case 9: // \t + case 32: // <space> + case 44: // , + ++pos; + continue; + case 10: // \n + ++pos; + ++lexer.line; + lexer.lineStart = pos; + continue; + case 13: // \r + if (body.charCodeAt(pos + 1) === 10) { + pos += 2; + } else { + ++pos; + } + ++lexer.line; + lexer.lineStart = pos; + continue; + case 33: // ! + return new Token(TokenKind.BANG, pos, pos + 1, line, col, prev); + case 35: // # + return readComment(source, pos, line, col, prev); + case 36: // $ + return new Token(TokenKind.DOLLAR, pos, pos + 1, line, col, prev); + case 38: // & + return new Token(TokenKind.AMP, pos, pos + 1, line, col, prev); + case 40: // ( + return new Token(TokenKind.PAREN_L, pos, pos + 1, line, col, prev); + case 41: // ) + return new Token(TokenKind.PAREN_R, pos, pos + 1, line, col, prev); + case 46: // . + if ( + body.charCodeAt(pos + 1) === 46 && + body.charCodeAt(pos + 2) === 46 + ) { + return new Token(TokenKind.SPREAD, pos, pos + 3, line, col, prev); + } + break; + case 58: // : + return new Token(TokenKind.COLON, pos, pos + 1, line, col, prev); + case 61: // = + return new Token(TokenKind.EQUALS, pos, pos + 1, line, col, prev); + case 64: // @ + return new Token(TokenKind.AT, pos, pos + 1, line, col, prev); + case 91: // [ + return new Token(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev); + case 93: // ] + return new Token(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev); + case 123: // { + return new Token(TokenKind.BRACE_L, pos, pos + 1, line, col, prev); + case 124: // | + return new Token(TokenKind.PIPE, pos, pos + 1, line, col, prev); + case 125: // } + return new Token(TokenKind.BRACE_R, pos, pos + 1, line, col, prev); + case 34: // " + if ( + body.charCodeAt(pos + 1) === 34 && + body.charCodeAt(pos + 2) === 34 + ) { + return readBlockString(source, pos, line, col, prev, lexer); + } + return readString(source, pos, line, col, prev); + case 45: // - + case 48: // 0 + case 49: // 1 + case 50: // 2 + case 51: // 3 + case 52: // 4 + case 53: // 5 + case 54: // 6 + case 55: // 7 + case 56: // 8 + case 57: // 9 + return readNumber(source, pos, code, line, col, prev); + case 65: // A + case 66: // B + case 67: // C + case 68: // D + case 69: // E + case 70: // F + case 71: // G + case 72: // H + case 73: // I + case 74: // J + case 75: // K + case 76: // L + case 77: // M + case 78: // N + case 79: // O + case 80: // P + case 81: // Q + case 82: // R + case 83: // S + case 84: // T + case 85: // U + case 86: // V + case 87: // W + case 88: // X + case 89: // Y + case 90: // Z + case 95: // _ + case 97: // a + case 98: // b + case 99: // c + case 100: // d + case 101: // e + case 102: // f + case 103: // g + case 104: // h + case 105: // i + case 106: // j + case 107: // k + case 108: // l + case 109: // m + case 110: // n + case 111: // o + case 112: // p + case 113: // q + case 114: // r + case 115: // s + case 116: // t + case 117: // u + case 118: // v + case 119: // w + case 120: // x + case 121: // y + case 122: // z + return readName(source, pos, line, col, prev); + } + + throw syntaxError(source, pos, unexpectedCharacterMessage(code)); + } + + const line = lexer.line; + const col = 1 + pos - lexer.lineStart; + return new Token(TokenKind.EOF, bodyLength, bodyLength, line, col, prev); +} + +/** + * Report a message that an unexpected character was encountered. + */ +function unexpectedCharacterMessage(code: number): string { + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + return `Cannot contain the invalid character ${printCharCode(code)}.`; + } + + if (code === 39) { + // ' + return 'Unexpected single quote character (\'), did you mean to use a double quote (")?'; + } + + return `Cannot parse the unexpected character ${printCharCode(code)}.`; +} + +/** + * Reads a comment token from the source file. + * + * #[\u0009\u0020-\uFFFF]* + */ +function readComment( + source: Source, + start: number, + line: number, + col: number, + prev: Token | null, +): Token { + const body = source.body; + let code; + let position = start; + + do { + code = body.charCodeAt(++position); + } while ( + !isNaN(code) && + // SourceCharacter but not LineTerminator + (code > 0x001f || code === 0x0009) + ); + + return new Token( + TokenKind.COMMENT, + start, + position, + line, + col, + prev, + body.slice(start + 1, position), + ); +} + +/** + * Reads a number token from the source file, either a float + * or an int depending on whether a decimal point appears. + * + * Int: -?(0|[1-9][0-9]*) + * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? + */ +function readNumber( + source: Source, + start: number, + firstCode: number, + line: number, + col: number, + prev: Token | null, +): Token { + const body = source.body; + let code = firstCode; + let position = start; + let isFloat = false; + + if (code === 45) { + // - + code = body.charCodeAt(++position); + } + + if (code === 48) { + // 0 + code = body.charCodeAt(++position); + if (code >= 48 && code <= 57) { + throw syntaxError( + source, + position, + `Invalid number, unexpected digit after 0: ${printCharCode(code)}.`, + ); + } + } else { + position = readDigits(source, position, code); + code = body.charCodeAt(position); + } + + if (code === 46) { + // . + isFloat = true; + + code = body.charCodeAt(++position); + position = readDigits(source, position, code); + code = body.charCodeAt(position); + } + + if (code === 69 || code === 101) { + // E e + isFloat = true; + + code = body.charCodeAt(++position); + if (code === 43 || code === 45) { + // + - + code = body.charCodeAt(++position); + } + position = readDigits(source, position, code); + code = body.charCodeAt(position); + } + + // Numbers cannot be followed by . or NameStart + if (code === 46 || isNameStart(code)) { + throw syntaxError( + source, + position, + `Invalid number, expected digit but got: ${printCharCode(code)}.`, + ); + } + + return new Token( + isFloat ? TokenKind.FLOAT : TokenKind.INT, + start, + position, + line, + col, + prev, + body.slice(start, position), + ); +} + +/** + * Returns the new position in the source after reading digits. + */ +function readDigits(source: Source, start: number, firstCode: number): number { + const body = source.body; + let position = start; + let code = firstCode; + if (code >= 48 && code <= 57) { + // 0 - 9 + do { + code = body.charCodeAt(++position); + } while (code >= 48 && code <= 57); // 0 - 9 + return position; + } + throw syntaxError( + source, + position, + `Invalid number, expected digit but got: ${printCharCode(code)}.`, + ); +} + +/** + * Reads a string token from the source file. + * + * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*" + */ +function readString( + source: Source, + start: number, + line: number, + col: number, + prev: Token | null, +): Token { + const body = source.body; + let position = start + 1; + let chunkStart = position; + let code = 0; + let value = ''; + + while ( + position < body.length && + !isNaN((code = body.charCodeAt(position))) && + // not LineTerminator + code !== 0x000a && + code !== 0x000d + ) { + // Closing Quote (") + if (code === 34) { + value += body.slice(chunkStart, position); + return new Token( + TokenKind.STRING, + start, + position + 1, + line, + col, + prev, + value, + ); + } + + // SourceCharacter + if (code < 0x0020 && code !== 0x0009) { + throw syntaxError( + source, + position, + `Invalid character within String: ${printCharCode(code)}.`, + ); + } + + ++position; + if (code === 92) { + // \ + value += body.slice(chunkStart, position - 1); + code = body.charCodeAt(position); + switch (code) { + case 34: + value += '"'; + break; + case 47: + value += '/'; + break; + case 92: + value += '\\'; + break; + case 98: + value += '\b'; + break; + case 102: + value += '\f'; + break; + case 110: + value += '\n'; + break; + case 114: + value += '\r'; + break; + case 116: + value += '\t'; + break; + case 117: { + // uXXXX + const charCode = uniCharCode( + body.charCodeAt(position + 1), + body.charCodeAt(position + 2), + body.charCodeAt(position + 3), + body.charCodeAt(position + 4), + ); + if (charCode < 0) { + const invalidSequence = body.slice(position + 1, position + 5); + throw syntaxError( + source, + position, + `Invalid character escape sequence: \\u${invalidSequence}.`, + ); + } + value += String.fromCharCode(charCode); + position += 4; + break; + } + default: + throw syntaxError( + source, + position, + `Invalid character escape sequence: \\${String.fromCharCode( + code, + )}.`, + ); + } + ++position; + chunkStart = position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} + +/** + * Reads a block string token from the source file. + * + * """("?"?(\\"""|\\(?!=""")|[^"\\]))*""" + */ +function readBlockString( + source: Source, + start: number, + line: number, + col: number, + prev: Token | null, + lexer: Lexer, +): Token { + const body = source.body; + let position = start + 3; + let chunkStart = position; + let code = 0; + let rawValue = ''; + + while (position < body.length && !isNaN((code = body.charCodeAt(position)))) { + // Closing Triple-Quote (""") + if ( + code === 34 && + body.charCodeAt(position + 1) === 34 && + body.charCodeAt(position + 2) === 34 + ) { + rawValue += body.slice(chunkStart, position); + return new Token( + TokenKind.BLOCK_STRING, + start, + position + 3, + line, + col, + prev, + dedentBlockStringValue(rawValue), + ); + } + + // SourceCharacter + if ( + code < 0x0020 && + code !== 0x0009 && + code !== 0x000a && + code !== 0x000d + ) { + throw syntaxError( + source, + position, + `Invalid character within String: ${printCharCode(code)}.`, + ); + } + + if (code === 10) { + // new line + ++position; + ++lexer.line; + lexer.lineStart = position; + } else if (code === 13) { + // carriage return + if (body.charCodeAt(position + 1) === 10) { + position += 2; + } else { + ++position; + } + ++lexer.line; + lexer.lineStart = position; + } else if ( + // Escape Triple-Quote (\""") + code === 92 && + body.charCodeAt(position + 1) === 34 && + body.charCodeAt(position + 2) === 34 && + body.charCodeAt(position + 3) === 34 + ) { + rawValue += body.slice(chunkStart, position) + '"""'; + position += 4; + chunkStart = position; + } else { + ++position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} + +/** + * Converts four hexadecimal chars to the integer that the + * string represents. For example, uniCharCode('0','0','0','f') + * will return 15, and uniCharCode('0','0','f','f') returns 255. + * + * Returns a negative number on error, if a char was invalid. + * + * This is implemented by noting that char2hex() returns -1 on error, + * which means the result of ORing the char2hex() will also be negative. + */ +function uniCharCode(a: number, b: number, c: number, d: number): number { + return ( + (char2hex(a) << 12) | (char2hex(b) << 8) | (char2hex(c) << 4) | char2hex(d) + ); +} + +/** + * Converts a hex character to its integer value. + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 on error. + */ +function char2hex(a: number): number { + return a >= 48 && a <= 57 + ? a - 48 // 0-9 + : a >= 65 && a <= 70 + ? a - 55 // A-F + : a >= 97 && a <= 102 + ? a - 87 // a-f + : -1; +} + +/** + * Reads an alphanumeric + underscore name from the source. + * + * [_A-Za-z][_0-9A-Za-z]* + */ +function readName( + source: Source, + start: number, + line: number, + col: number, + prev: Token | null, +): Token { + const body = source.body; + const bodyLength = body.length; + let position = start + 1; + let code = 0; + while ( + position !== bodyLength && + !isNaN((code = body.charCodeAt(position))) && + (code === 95 || // _ + (code >= 48 && code <= 57) || // 0-9 + (code >= 65 && code <= 90) || // A-Z + (code >= 97 && code <= 122)) // a-z + ) { + ++position; + } + return new Token( + TokenKind.NAME, + start, + position, + line, + col, + prev, + body.slice(start, position), + ); +} + +// _ A-Z a-z +function isNameStart(code: number): boolean { + return ( + code === 95 || (code >= 65 && code <= 90) || (code >= 97 && code <= 122) + ); +} diff --git a/school/node_modules/graphql/language/lexer.mjs b/school/node_modules/graphql/language/lexer.mjs new file mode 100644 index 0000000..a970631 --- /dev/null +++ b/school/node_modules/graphql/language/lexer.mjs @@ -0,0 +1,676 @@ +import { syntaxError } from "../error/syntaxError.mjs"; +import { Token } from "./ast.mjs"; +import { TokenKind } from "./tokenKind.mjs"; +import { dedentBlockStringValue } from "./blockString.mjs"; +/** + * Given a Source object, creates a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ + +export var Lexer = /*#__PURE__*/function () { + /** + * The previously focused non-ignored token. + */ + + /** + * The currently focused non-ignored token. + */ + + /** + * The (1-indexed) line containing the current token. + */ + + /** + * The character offset at which the current line begins. + */ + function Lexer(source) { + var startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0, null); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + this.line = 1; + this.lineStart = 0; + } + /** + * Advances the token stream to the next non-ignored token. + */ + + + var _proto = Lexer.prototype; + + _proto.advance = function advance() { + this.lastToken = this.token; + var token = this.token = this.lookahead(); + return token; + } + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the state of Lexer. + */ + ; + + _proto.lookahead = function lookahead() { + var token = this.token; + + if (token.kind !== TokenKind.EOF) { + do { + var _token$next; + + // Note: next is only mutable during parsing, so we cast to allow this. + token = (_token$next = token.next) !== null && _token$next !== void 0 ? _token$next : token.next = readToken(this, token); + } while (token.kind === TokenKind.COMMENT); + } + + return token; + }; + + return Lexer; +}(); +/** + * @internal + */ + +export function isPunctuatorTokenKind(kind) { + return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R; +} + +function printCharCode(code) { + return (// NaN/undefined represents access beyond the end of the file. + isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII. + code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form. + "\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"") + ); +} +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace until it finds the next lexable token, then lexes + * punctuators immediately or calls the appropriate helper function for more + * complicated tokens. + */ + + +function readToken(lexer, prev) { + var source = lexer.source; + var body = source.body; + var bodyLength = body.length; + var pos = prev.end; + + while (pos < bodyLength) { + var code = body.charCodeAt(pos); + var _line = lexer.line; + + var _col = 1 + pos - lexer.lineStart; // SourceCharacter + + + switch (code) { + case 0xfeff: // <BOM> + + case 9: // \t + + case 32: // <space> + + case 44: + // , + ++pos; + continue; + + case 10: + // \n + ++pos; + ++lexer.line; + lexer.lineStart = pos; + continue; + + case 13: + // \r + if (body.charCodeAt(pos + 1) === 10) { + pos += 2; + } else { + ++pos; + } + + ++lexer.line; + lexer.lineStart = pos; + continue; + + case 33: + // ! + return new Token(TokenKind.BANG, pos, pos + 1, _line, _col, prev); + + case 35: + // # + return readComment(source, pos, _line, _col, prev); + + case 36: + // $ + return new Token(TokenKind.DOLLAR, pos, pos + 1, _line, _col, prev); + + case 38: + // & + return new Token(TokenKind.AMP, pos, pos + 1, _line, _col, prev); + + case 40: + // ( + return new Token(TokenKind.PAREN_L, pos, pos + 1, _line, _col, prev); + + case 41: + // ) + return new Token(TokenKind.PAREN_R, pos, pos + 1, _line, _col, prev); + + case 46: + // . + if (body.charCodeAt(pos + 1) === 46 && body.charCodeAt(pos + 2) === 46) { + return new Token(TokenKind.SPREAD, pos, pos + 3, _line, _col, prev); + } + + break; + + case 58: + // : + return new Token(TokenKind.COLON, pos, pos + 1, _line, _col, prev); + + case 61: + // = + return new Token(TokenKind.EQUALS, pos, pos + 1, _line, _col, prev); + + case 64: + // @ + return new Token(TokenKind.AT, pos, pos + 1, _line, _col, prev); + + case 91: + // [ + return new Token(TokenKind.BRACKET_L, pos, pos + 1, _line, _col, prev); + + case 93: + // ] + return new Token(TokenKind.BRACKET_R, pos, pos + 1, _line, _col, prev); + + case 123: + // { + return new Token(TokenKind.BRACE_L, pos, pos + 1, _line, _col, prev); + + case 124: + // | + return new Token(TokenKind.PIPE, pos, pos + 1, _line, _col, prev); + + case 125: + // } + return new Token(TokenKind.BRACE_R, pos, pos + 1, _line, _col, prev); + + case 34: + // " + if (body.charCodeAt(pos + 1) === 34 && body.charCodeAt(pos + 2) === 34) { + return readBlockString(source, pos, _line, _col, prev, lexer); + } + + return readString(source, pos, _line, _col, prev); + + case 45: // - + + case 48: // 0 + + case 49: // 1 + + case 50: // 2 + + case 51: // 3 + + case 52: // 4 + + case 53: // 5 + + case 54: // 6 + + case 55: // 7 + + case 56: // 8 + + case 57: + // 9 + return readNumber(source, pos, code, _line, _col, prev); + + case 65: // A + + case 66: // B + + case 67: // C + + case 68: // D + + case 69: // E + + case 70: // F + + case 71: // G + + case 72: // H + + case 73: // I + + case 74: // J + + case 75: // K + + case 76: // L + + case 77: // M + + case 78: // N + + case 79: // O + + case 80: // P + + case 81: // Q + + case 82: // R + + case 83: // S + + case 84: // T + + case 85: // U + + case 86: // V + + case 87: // W + + case 88: // X + + case 89: // Y + + case 90: // Z + + case 95: // _ + + case 97: // a + + case 98: // b + + case 99: // c + + case 100: // d + + case 101: // e + + case 102: // f + + case 103: // g + + case 104: // h + + case 105: // i + + case 106: // j + + case 107: // k + + case 108: // l + + case 109: // m + + case 110: // n + + case 111: // o + + case 112: // p + + case 113: // q + + case 114: // r + + case 115: // s + + case 116: // t + + case 117: // u + + case 118: // v + + case 119: // w + + case 120: // x + + case 121: // y + + case 122: + // z + return readName(source, pos, _line, _col, prev); + } + + throw syntaxError(source, pos, unexpectedCharacterMessage(code)); + } + + var line = lexer.line; + var col = 1 + pos - lexer.lineStart; + return new Token(TokenKind.EOF, bodyLength, bodyLength, line, col, prev); +} +/** + * Report a message that an unexpected character was encountered. + */ + + +function unexpectedCharacterMessage(code) { + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + return "Cannot contain the invalid character ".concat(printCharCode(code), "."); + } + + if (code === 39) { + // ' + return 'Unexpected single quote character (\'), did you mean to use a double quote (")?'; + } + + return "Cannot parse the unexpected character ".concat(printCharCode(code), "."); +} +/** + * Reads a comment token from the source file. + * + * #[\u0009\u0020-\uFFFF]* + */ + + +function readComment(source, start, line, col, prev) { + var body = source.body; + var code; + var position = start; + + do { + code = body.charCodeAt(++position); + } while (!isNaN(code) && ( // SourceCharacter but not LineTerminator + code > 0x001f || code === 0x0009)); + + return new Token(TokenKind.COMMENT, start, position, line, col, prev, body.slice(start + 1, position)); +} +/** + * Reads a number token from the source file, either a float + * or an int depending on whether a decimal point appears. + * + * Int: -?(0|[1-9][0-9]*) + * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? + */ + + +function readNumber(source, start, firstCode, line, col, prev) { + var body = source.body; + var code = firstCode; + var position = start; + var isFloat = false; + + if (code === 45) { + // - + code = body.charCodeAt(++position); + } + + if (code === 48) { + // 0 + code = body.charCodeAt(++position); + + if (code >= 48 && code <= 57) { + throw syntaxError(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), ".")); + } + } else { + position = readDigits(source, position, code); + code = body.charCodeAt(position); + } + + if (code === 46) { + // . + isFloat = true; + code = body.charCodeAt(++position); + position = readDigits(source, position, code); + code = body.charCodeAt(position); + } + + if (code === 69 || code === 101) { + // E e + isFloat = true; + code = body.charCodeAt(++position); + + if (code === 43 || code === 45) { + // + - + code = body.charCodeAt(++position); + } + + position = readDigits(source, position, code); + code = body.charCodeAt(position); + } // Numbers cannot be followed by . or NameStart + + + if (code === 46 || isNameStart(code)) { + throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), ".")); + } + + return new Token(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, body.slice(start, position)); +} +/** + * Returns the new position in the source after reading digits. + */ + + +function readDigits(source, start, firstCode) { + var body = source.body; + var position = start; + var code = firstCode; + + if (code >= 48 && code <= 57) { + // 0 - 9 + do { + code = body.charCodeAt(++position); + } while (code >= 48 && code <= 57); // 0 - 9 + + + return position; + } + + throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), ".")); +} +/** + * Reads a string token from the source file. + * + * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*" + */ + + +function readString(source, start, line, col, prev) { + var body = source.body; + var position = start + 1; + var chunkStart = position; + var code = 0; + var value = ''; + + while (position < body.length && !isNaN(code = body.charCodeAt(position)) && // not LineTerminator + code !== 0x000a && code !== 0x000d) { + // Closing Quote (") + if (code === 34) { + value += body.slice(chunkStart, position); + return new Token(TokenKind.STRING, start, position + 1, line, col, prev, value); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009) { + throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } + + ++position; + + if (code === 92) { + // \ + value += body.slice(chunkStart, position - 1); + code = body.charCodeAt(position); + + switch (code) { + case 34: + value += '"'; + break; + + case 47: + value += '/'; + break; + + case 92: + value += '\\'; + break; + + case 98: + value += '\b'; + break; + + case 102: + value += '\f'; + break; + + case 110: + value += '\n'; + break; + + case 114: + value += '\r'; + break; + + case 116: + value += '\t'; + break; + + case 117: + { + // uXXXX + var charCode = uniCharCode(body.charCodeAt(position + 1), body.charCodeAt(position + 2), body.charCodeAt(position + 3), body.charCodeAt(position + 4)); + + if (charCode < 0) { + var invalidSequence = body.slice(position + 1, position + 5); + throw syntaxError(source, position, "Invalid character escape sequence: \\u".concat(invalidSequence, ".")); + } + + value += String.fromCharCode(charCode); + position += 4; + break; + } + + default: + throw syntaxError(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), ".")); + } + + ++position; + chunkStart = position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} +/** + * Reads a block string token from the source file. + * + * """("?"?(\\"""|\\(?!=""")|[^"\\]))*""" + */ + + +function readBlockString(source, start, line, col, prev, lexer) { + var body = source.body; + var position = start + 3; + var chunkStart = position; + var code = 0; + var rawValue = ''; + + while (position < body.length && !isNaN(code = body.charCodeAt(position))) { + // Closing Triple-Quote (""") + if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) { + rawValue += body.slice(chunkStart, position); + return new Token(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, dedentBlockStringValue(rawValue)); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } + + if (code === 10) { + // new line + ++position; + ++lexer.line; + lexer.lineStart = position; + } else if (code === 13) { + // carriage return + if (body.charCodeAt(position + 1) === 10) { + position += 2; + } else { + ++position; + } + + ++lexer.line; + lexer.lineStart = position; + } else if ( // Escape Triple-Quote (\""") + code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) { + rawValue += body.slice(chunkStart, position) + '"""'; + position += 4; + chunkStart = position; + } else { + ++position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} +/** + * Converts four hexadecimal chars to the integer that the + * string represents. For example, uniCharCode('0','0','0','f') + * will return 15, and uniCharCode('0','0','f','f') returns 255. + * + * Returns a negative number on error, if a char was invalid. + * + * This is implemented by noting that char2hex() returns -1 on error, + * which means the result of ORing the char2hex() will also be negative. + */ + + +function uniCharCode(a, b, c, d) { + return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d); +} +/** + * Converts a hex character to its integer value. + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 on error. + */ + + +function char2hex(a) { + return a >= 48 && a <= 57 ? a - 48 // 0-9 + : a >= 65 && a <= 70 ? a - 55 // A-F + : a >= 97 && a <= 102 ? a - 87 // a-f + : -1; +} +/** + * Reads an alphanumeric + underscore name from the source. + * + * [_A-Za-z][_0-9A-Za-z]* + */ + + +function readName(source, start, line, col, prev) { + var body = source.body; + var bodyLength = body.length; + var position = start + 1; + var code = 0; + + while (position !== bodyLength && !isNaN(code = body.charCodeAt(position)) && (code === 95 || // _ + code >= 48 && code <= 57 || // 0-9 + code >= 65 && code <= 90 || // A-Z + code >= 97 && code <= 122) // a-z + ) { + ++position; + } + + return new Token(TokenKind.NAME, start, position, line, col, prev, body.slice(start, position)); +} // _ A-Z a-z + + +function isNameStart(code) { + return code === 95 || code >= 65 && code <= 90 || code >= 97 && code <= 122; +} diff --git a/school/node_modules/graphql/language/location.d.ts b/school/node_modules/graphql/language/location.d.ts new file mode 100644 index 0000000..a41e82f --- /dev/null +++ b/school/node_modules/graphql/language/location.d.ts @@ -0,0 +1,15 @@ +import { Source } from './source'; + +/** + * Represents a location in a Source. + */ +export interface SourceLocation { + readonly line: number; + readonly column: number; +} + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +export function getLocation(source: Source, position: number): SourceLocation; diff --git a/school/node_modules/graphql/language/location.js b/school/node_modules/graphql/language/location.js new file mode 100644 index 0000000..27d87c3 --- /dev/null +++ b/school/node_modules/graphql/language/location.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getLocation = getLocation; + +/** + * Represents a location in a Source. + */ + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +function getLocation(source, position) { + var lineRegexp = /\r\n|[\n\r]/g; + var line = 1; + var column = position + 1; + var match; + + while ((match = lineRegexp.exec(source.body)) && match.index < position) { + line += 1; + column = position + 1 - (match.index + match[0].length); + } + + return { + line: line, + column: column + }; +} diff --git a/school/node_modules/graphql/language/location.js.flow b/school/node_modules/graphql/language/location.js.flow new file mode 100644 index 0000000..94b77f1 --- /dev/null +++ b/school/node_modules/graphql/language/location.js.flow @@ -0,0 +1,26 @@ +// @flow strict +import type { Source } from './source'; + +/** + * Represents a location in a Source. + */ +export type SourceLocation = {| + +line: number, + +column: number, +|}; + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +export function getLocation(source: Source, position: number): SourceLocation { + const lineRegexp = /\r\n|[\n\r]/g; + let line = 1; + let column = position + 1; + let match; + while ((match = lineRegexp.exec(source.body)) && match.index < position) { + line += 1; + column = position + 1 - (match.index + match[0].length); + } + return { line, column }; +} diff --git a/school/node_modules/graphql/language/location.mjs b/school/node_modules/graphql/language/location.mjs new file mode 100644 index 0000000..e578ef0 --- /dev/null +++ b/school/node_modules/graphql/language/location.mjs @@ -0,0 +1,24 @@ +/** + * Represents a location in a Source. + */ + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +export function getLocation(source, position) { + var lineRegexp = /\r\n|[\n\r]/g; + var line = 1; + var column = position + 1; + var match; + + while ((match = lineRegexp.exec(source.body)) && match.index < position) { + line += 1; + column = position + 1 - (match.index + match[0].length); + } + + return { + line: line, + column: column + }; +} diff --git a/school/node_modules/graphql/language/parser.d.ts b/school/node_modules/graphql/language/parser.d.ts new file mode 100644 index 0000000..49db417 --- /dev/null +++ b/school/node_modules/graphql/language/parser.d.ts @@ -0,0 +1,543 @@ +import { Maybe } from '../jsutils/Maybe'; +import { GraphQLError } from '..'; + +import { TokenKindEnum } from './tokenKind'; +import { Source } from './source'; +import { + TypeNode, + ValueNode, + DocumentNode, + Token, + Location, + NameNode, + DirectiveDefinitionNode, + InputObjectTypeExtensionNode, + EnumTypeExtensionNode, + UnionTypeExtensionNode, + InterfaceTypeExtensionNode, + ObjectTypeExtensionNode, + ScalarTypeExtensionNode, + SchemaExtensionNode, + TypeSystemExtensionNode, + InputValueDefinitionNode, + InputObjectTypeDefinitionNode, + EnumValueDefinitionNode, + EnumTypeDefinitionNode, + NamedTypeNode, + UnionTypeDefinitionNode, + InterfaceTypeDefinitionNode, + FieldDefinitionNode, + ObjectTypeDefinitionNode, + ScalarTypeDefinitionNode, + OperationTypeDefinitionNode, + SchemaDefinitionNode, + StringValueNode, + DirectiveNode, + ObjectFieldNode, + ObjectValueNode, + FragmentSpreadNode, + InlineFragmentNode, + ArgumentNode, + FieldNode, + SelectionNode, + SelectionSetNode, + VariableNode, + VariableDefinitionNode, + OperationTypeNode, + OperationDefinitionNode, + DefinitionNode, + FragmentDefinitionNode, + ListValueNode, +} from './ast'; +import { Lexer } from './lexer'; + +/** + * Configuration options to control parser behavior + */ +export interface ParseOptions { + /** + * By default, the parser creates AST nodes that know the location + * in the source that they correspond to. This configuration flag + * disables that behavior for performance or testing. + */ + noLocation?: boolean; + + /** + * If enabled, the parser will parse empty fields sets in the Schema + * Definition Language. Otherwise, the parser will follow the current + * specification. + * + * This option is provided to ease adoption of the final SDL specification + * and will be removed in v16. + */ + allowLegacySDLEmptyFields?: boolean; + + /** + * If enabled, the parser will parse implemented interfaces with no `&` + * character between each interface. Otherwise, the parser will follow the + * current specification. + * + * This option is provided to ease adoption of the final SDL specification + * and will be removed in v16. + */ + allowLegacySDLImplementsInterfaces?: boolean; + + /** + * EXPERIMENTAL: + * + * If enabled, the parser will understand and parse variable definitions + * contained in a fragment definition. They'll be represented in the + * `variableDefinitions` field of the FragmentDefinitionNode. + * + * The syntax is identical to normal, query-defined variables. For example: + * + * fragment A($var: Boolean = false) on T { + * ... + * } + * + * Note: this feature is experimental and may change or be removed in the + * future. + */ + experimentalFragmentVariables?: boolean; +} + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +export function parse( + source: string | Source, + options?: ParseOptions, +): DocumentNode; + +/** + * Given a string containing a GraphQL value, parse the AST for that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + */ +export function parseValue( + source: string | Source, + options?: ParseOptions, +): ValueNode; + +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ +export function parseType( + source: string | Source, + options?: ParseOptions, +): TypeNode; + +export class Parser { + protected _lexer: Lexer; + protected _options?: ParseOptions; + constructor(source: string | Source, options?: ParseOptions); + + /** + * Converts a name lex token into a name parse node. + */ + parseName(): NameNode; + /** + * Document : Definition+ + */ + parseDocument(): DocumentNode; + /** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + * + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + * + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ + parseDefinition(): DefinitionNode; + /** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ + parseOperationDefinition(): OperationDefinitionNode; + /** + * OperationType : one of query mutation subscription + */ + parseOperationType(): OperationTypeNode; + /** + * VariableDefinitions : ( VariableDefinition+ ) + */ + parseVariableDefinitions(): Array<VariableDefinitionNode>; + /** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ + parseVariableDefinition(): VariableDefinitionNode; + /** + * Variable : $ Name + */ + parseVariable(): VariableNode; + /** + * ``` + * SelectionSet : { Selection+ } + * ``` + */ + parseSelectionSet(): SelectionSetNode; + /** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ + parseSelection(): SelectionNode; + /** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ + parseField(): FieldNode; + /** + * Arguments[Const] : ( Argument[?Const]+ ) + */ + parseArguments(): Array<ArgumentNode>; + /** + * Argument[Const] : Name : Value[?Const] + */ + parseArgument(): ArgumentNode; + /** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ + parseFragment(): FragmentSpreadNode | InlineFragmentNode; + /** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ + parseFragmentDefinition(): FragmentDefinitionNode; + /** + * FragmentName : Name but not `on` + */ + parseFragmentName(): NameNode; + /** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ + parseValueLiteral(): ValueNode; + parseStringLiteral(): StringValueNode; + /** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ + parseList(): ListValueNode; + /** + * ``` + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + * ``` + */ + parseObject(isConst: boolean): ObjectValueNode; + /** + * ObjectField[Const] : Name : Value[?Const] + */ + parseObjectField: ObjectFieldNode; + /** + * Directives[Const] : Directive[?Const]+ + */ + parseDirectives(): Array<DirectiveNode>; + /** + * ``` + * Directive[Const] : @ Name Arguments[?Const]? + * ``` + */ + parseDirective(): DirectiveNode; + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + parseTypeReference(): TypeNode; + /** + * NamedType : Name + */ + parseNamedType(): NamedTypeNode; + peekDescription(): boolean; + /** + * Description : StringValue + */ + parseDescription(): undefined | StringValueNode; + /** + * ``` + * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } + * ``` + */ + parseSchemaDefinition(): SchemaDefinitionNode; + /** + * OperationTypeDefinition : OperationType : NamedType + */ + parseOperationTypeDefinition(): OperationTypeDefinitionNode; + /** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ + parseScalarTypeDefinition(): ScalarTypeDefinitionNode; + /** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ + parseObjectTypeDefinition(): ObjectTypeDefinitionNode; + /** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ + parseImplementsInterfaces(): Array<NamedTypeNode>; + /** + * ``` + * FieldsDefinition : { FieldDefinition+ } + * ``` + */ + parseFieldsDefinition(): Array<FieldDefinitionNode>; + /** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ + parseFieldDefinition(): FieldDefinitionNode; + /** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ + parseArgumentDefs(): Array<InputValueDefinitionNode>; + /** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ + parseInputValueDef(): InputValueDefinitionNode; + /** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ + parseInterfaceTypeDefinition(): InterfaceTypeDefinitionNode; + /** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ + parseUnionTypeDefinition(): UnionTypeDefinitionNode; + /** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ + parseUnionMemberTypes(): Array<NamedTypeNode>; + /** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ + parseEnumTypeDefinition(): EnumTypeDefinitionNode; + /** + * ``` + * EnumValuesDefinition : { EnumValueDefinition+ } + * ``` + */ + parseEnumValuesDefinition(): Array<EnumValueDefinitionNode>; + /** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + */ + parseEnumValueDefinition(): EnumValueDefinitionNode; + /** + * EnumValue : Name but not `true`, `false` or `null` + */ + parseEnumValueName(): NameNode; + /** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ + parseInputObjectTypeDefinition(): InputObjectTypeDefinitionNode; + /** + * ``` + * InputFieldsDefinition : { InputValueDefinition+ } + * ``` + */ + parseInputFieldsDefinition(): Array<InputValueDefinitionNode>; + /** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ + parseTypeSystemExtension(): TypeSystemExtensionNode; + /** + * ``` + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + * ``` + */ + parseSchemaExtension(): SchemaExtensionNode; + /** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ + parseScalarTypeExtension(): ScalarTypeExtensionNode; + /** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ + parseObjectTypeExtension(): ObjectTypeExtensionNode; + /** + * InterfaceTypeExtension : + * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend interface Name ImplementsInterfaces? Directives[Const] + * - extend interface Name ImplementsInterfaces + */ + parseInterfaceTypeExtension(): InterfaceTypeExtensionNode; + /** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ + parseUnionTypeExtension(): UnionTypeExtensionNode; + /** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ + parseEnumTypeExtension(): EnumTypeExtensionNode; + /** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ + parseInputObjectTypeExtension(): InputObjectTypeExtensionNode; + /** + * ``` + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations + * ``` + */ + parseDirectiveDefinition(): DirectiveDefinitionNode; + /** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ + parseDirectiveLocations(): Array<NameNode>; + parseDirectiveLocation(): NameNode; + /** + * Returns a location object, used to identify the place in the source that created a given parsed object. + */ + loc(startToken: Token): Location | undefined; + /** + * Determines if the next token is of a given kind + */ + peek(kind: TokenKindEnum): boolean; + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and throw an error. + */ + expectToken(kind: TokenKindEnum): Token; + /** + * If the next token is of the given kind, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + */ + expectOptionalToken(kind: TokenKindEnum): boolean; + /** + * If the next token is a given keyword, advance the lexer. + * Otherwise, do not change the parser state and throw an error. + */ + expectKeyword(value: string): void; + /** + * If the next token is a given keyword, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + */ + expectOptionalKeyword(value: string): boolean; + /** + * Helper function for creating an error when an unexpected lexed token is encountered. + */ + unexpected(atToken?: Maybe<Token>): GraphQLError; + /** + * Returns a possibly empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + any<T>( + openKind: TokenKindEnum, + parseFn: () => T, + closeKind: TokenKindEnum, + ): Array<T>; + /** + * Returns a list of parse nodes, determined by the parseFn. + * It can be empty only if open token is missing otherwise it will always return non-empty list + * that begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + optionalMany<T>( + openKind: TokenKindEnum, + parseFn: () => T, + closeKind: TokenKindEnum, + ): Array<T>; + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + many<T>( + openKind: TokenKindEnum, + parseFn: () => T, + closeKind: TokenKindEnum, + ): Array<T>; + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. + * Advances the parser to the next lex token after last item in the list. + */ + delimitedMany<T>(delimiterKind: TokenKindEnum, parseFn: () => T): Array<T>; +} diff --git a/school/node_modules/graphql/language/parser.js b/school/node_modules/graphql/language/parser.js new file mode 100644 index 0000000..cef9a77 --- /dev/null +++ b/school/node_modules/graphql/language/parser.js @@ -0,0 +1,1566 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parse = parse; +exports.parseValue = parseValue; +exports.parseType = parseType; +exports.Parser = void 0; + +var _syntaxError = require("../error/syntaxError.js"); + +var _kinds = require("./kinds.js"); + +var _ast = require("./ast.js"); + +var _tokenKind = require("./tokenKind.js"); + +var _source = require("./source.js"); + +var _directiveLocation = require("./directiveLocation.js"); + +var _lexer = require("./lexer.js"); + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +function parse(source, options) { + var parser = new Parser(source, options); + return parser.parseDocument(); +} +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ + + +function parseValue(source, options) { + var parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + var value = parser.parseValueLiteral(false); + parser.expectToken(_tokenKind.TokenKind.EOF); + return value; +} +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ + + +function parseType(source, options) { + var parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + var type = parser.parseTypeReference(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return type; +} +/** + * This class is exported only to assist people in implementing their own parsers + * without duplicating too much code and should be used only as last resort for cases + * such as experimental syntax or if certain features could not be contributed upstream. + * + * It is still part of the internal API and is versioned, so any changes to it are never + * considered breaking changes. If you still need to support multiple versions of the + * library, please use the `versionInfo` variable for version detection. + * + * @internal + */ + + +var Parser = /*#__PURE__*/function () { + function Parser(source, options) { + var sourceObj = (0, _source.isSource)(source) ? source : new _source.Source(source); + this._lexer = new _lexer.Lexer(sourceObj); + this._options = options; + } + /** + * Converts a name lex token into a name parse node. + */ + + + var _proto = Parser.prototype; + + _proto.parseName = function parseName() { + var token = this.expectToken(_tokenKind.TokenKind.NAME); + return { + kind: _kinds.Kind.NAME, + value: token.value, + loc: this.loc(token) + }; + } // Implements the parsing rules in the Document section. + + /** + * Document : Definition+ + */ + ; + + _proto.parseDocument = function parseDocument() { + var start = this._lexer.token; + return { + kind: _kinds.Kind.DOCUMENT, + definitions: this.many(_tokenKind.TokenKind.SOF, this.parseDefinition, _tokenKind.TokenKind.EOF), + loc: this.loc(start) + }; + } + /** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + * + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + */ + ; + + _proto.parseDefinition = function parseDefinition() { + if (this.peek(_tokenKind.TokenKind.NAME)) { + switch (this._lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + return this.parseOperationDefinition(); + + case 'fragment': + return this.parseFragmentDefinition(); + + case 'schema': + case 'scalar': + case 'type': + case 'interface': + case 'union': + case 'enum': + case 'input': + case 'directive': + return this.parseTypeSystemDefinition(); + + case 'extend': + return this.parseTypeSystemExtension(); + } + } else if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return this.parseOperationDefinition(); + } else if (this.peekDescription()) { + return this.parseTypeSystemDefinition(); + } + + throw this.unexpected(); + } // Implements the parsing rules in the Operations section. + + /** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ + ; + + _proto.parseOperationDefinition = function parseOperationDefinition() { + var start = this._lexer.token; + + if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation: 'query', + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: this.parseSelectionSet(), + loc: this.loc(start) + }; + } + + var operation = this.parseOperationType(); + var name; + + if (this.peek(_tokenKind.TokenKind.NAME)) { + name = this.parseName(); + } + + return { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation: operation, + name: name, + variableDefinitions: this.parseVariableDefinitions(), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start) + }; + } + /** + * OperationType : one of query mutation subscription + */ + ; + + _proto.parseOperationType = function parseOperationType() { + var operationToken = this.expectToken(_tokenKind.TokenKind.NAME); + + switch (operationToken.value) { + case 'query': + return 'query'; + + case 'mutation': + return 'mutation'; + + case 'subscription': + return 'subscription'; + } + + throw this.unexpected(operationToken); + } + /** + * VariableDefinitions : ( VariableDefinition+ ) + */ + ; + + _proto.parseVariableDefinitions = function parseVariableDefinitions() { + return this.optionalMany(_tokenKind.TokenKind.PAREN_L, this.parseVariableDefinition, _tokenKind.TokenKind.PAREN_R); + } + /** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ + ; + + _proto.parseVariableDefinition = function parseVariableDefinition() { + var start = this._lexer.token; + return { + kind: _kinds.Kind.VARIABLE_DEFINITION, + variable: this.parseVariable(), + type: (this.expectToken(_tokenKind.TokenKind.COLON), this.parseTypeReference()), + defaultValue: this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) ? this.parseValueLiteral(true) : undefined, + directives: this.parseDirectives(true), + loc: this.loc(start) + }; + } + /** + * Variable : $ Name + */ + ; + + _proto.parseVariable = function parseVariable() { + var start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.DOLLAR); + return { + kind: _kinds.Kind.VARIABLE, + name: this.parseName(), + loc: this.loc(start) + }; + } + /** + * SelectionSet : { Selection+ } + */ + ; + + _proto.parseSelectionSet = function parseSelectionSet() { + var start = this._lexer.token; + return { + kind: _kinds.Kind.SELECTION_SET, + selections: this.many(_tokenKind.TokenKind.BRACE_L, this.parseSelection, _tokenKind.TokenKind.BRACE_R), + loc: this.loc(start) + }; + } + /** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ + ; + + _proto.parseSelection = function parseSelection() { + return this.peek(_tokenKind.TokenKind.SPREAD) ? this.parseFragment() : this.parseField(); + } + /** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ + ; + + _proto.parseField = function parseField() { + var start = this._lexer.token; + var nameOrAlias = this.parseName(); + var alias; + var name; + + if (this.expectOptionalToken(_tokenKind.TokenKind.COLON)) { + alias = nameOrAlias; + name = this.parseName(); + } else { + name = nameOrAlias; + } + + return { + kind: _kinds.Kind.FIELD, + alias: alias, + name: name, + arguments: this.parseArguments(false), + directives: this.parseDirectives(false), + selectionSet: this.peek(_tokenKind.TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined, + loc: this.loc(start) + }; + } + /** + * Arguments[Const] : ( Argument[?Const]+ ) + */ + ; + + _proto.parseArguments = function parseArguments(isConst) { + var item = isConst ? this.parseConstArgument : this.parseArgument; + return this.optionalMany(_tokenKind.TokenKind.PAREN_L, item, _tokenKind.TokenKind.PAREN_R); + } + /** + * Argument[Const] : Name : Value[?Const] + */ + ; + + _proto.parseArgument = function parseArgument() { + var start = this._lexer.token; + var name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return { + kind: _kinds.Kind.ARGUMENT, + name: name, + value: this.parseValueLiteral(false), + loc: this.loc(start) + }; + }; + + _proto.parseConstArgument = function parseConstArgument() { + var start = this._lexer.token; + return { + kind: _kinds.Kind.ARGUMENT, + name: this.parseName(), + value: (this.expectToken(_tokenKind.TokenKind.COLON), this.parseValueLiteral(true)), + loc: this.loc(start) + }; + } // Implements the parsing rules in the Fragments section. + + /** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ + ; + + _proto.parseFragment = function parseFragment() { + var start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.SPREAD); + var hasTypeCondition = this.expectOptionalKeyword('on'); + + if (!hasTypeCondition && this.peek(_tokenKind.TokenKind.NAME)) { + return { + kind: _kinds.Kind.FRAGMENT_SPREAD, + name: this.parseFragmentName(), + directives: this.parseDirectives(false), + loc: this.loc(start) + }; + } + + return { + kind: _kinds.Kind.INLINE_FRAGMENT, + typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start) + }; + } + /** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ + ; + + _proto.parseFragmentDefinition = function parseFragmentDefinition() { + var _this$_options; + + var start = this._lexer.token; + this.expectKeyword('fragment'); // Experimental support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + + if (((_this$_options = this._options) === null || _this$_options === void 0 ? void 0 : _this$_options.experimentalFragmentVariables) === true) { + return { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + variableDefinitions: this.parseVariableDefinitions(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start) + }; + } + + return { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start) + }; + } + /** + * FragmentName : Name but not `on` + */ + ; + + _proto.parseFragmentName = function parseFragmentName() { + if (this._lexer.token.value === 'on') { + throw this.unexpected(); + } + + return this.parseName(); + } // Implements the parsing rules in the Values section. + + /** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ + ; + + _proto.parseValueLiteral = function parseValueLiteral(isConst) { + var token = this._lexer.token; + + switch (token.kind) { + case _tokenKind.TokenKind.BRACKET_L: + return this.parseList(isConst); + + case _tokenKind.TokenKind.BRACE_L: + return this.parseObject(isConst); + + case _tokenKind.TokenKind.INT: + this._lexer.advance(); + + return { + kind: _kinds.Kind.INT, + value: token.value, + loc: this.loc(token) + }; + + case _tokenKind.TokenKind.FLOAT: + this._lexer.advance(); + + return { + kind: _kinds.Kind.FLOAT, + value: token.value, + loc: this.loc(token) + }; + + case _tokenKind.TokenKind.STRING: + case _tokenKind.TokenKind.BLOCK_STRING: + return this.parseStringLiteral(); + + case _tokenKind.TokenKind.NAME: + this._lexer.advance(); + + switch (token.value) { + case 'true': + return { + kind: _kinds.Kind.BOOLEAN, + value: true, + loc: this.loc(token) + }; + + case 'false': + return { + kind: _kinds.Kind.BOOLEAN, + value: false, + loc: this.loc(token) + }; + + case 'null': + return { + kind: _kinds.Kind.NULL, + loc: this.loc(token) + }; + + default: + return { + kind: _kinds.Kind.ENUM, + value: token.value, + loc: this.loc(token) + }; + } + + case _tokenKind.TokenKind.DOLLAR: + if (!isConst) { + return this.parseVariable(); + } + + break; + } + + throw this.unexpected(); + }; + + _proto.parseStringLiteral = function parseStringLiteral() { + var token = this._lexer.token; + + this._lexer.advance(); + + return { + kind: _kinds.Kind.STRING, + value: token.value, + block: token.kind === _tokenKind.TokenKind.BLOCK_STRING, + loc: this.loc(token) + }; + } + /** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ + ; + + _proto.parseList = function parseList(isConst) { + var _this = this; + + var start = this._lexer.token; + + var item = function item() { + return _this.parseValueLiteral(isConst); + }; + + return { + kind: _kinds.Kind.LIST, + values: this.any(_tokenKind.TokenKind.BRACKET_L, item, _tokenKind.TokenKind.BRACKET_R), + loc: this.loc(start) + }; + } + /** + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + */ + ; + + _proto.parseObject = function parseObject(isConst) { + var _this2 = this; + + var start = this._lexer.token; + + var item = function item() { + return _this2.parseObjectField(isConst); + }; + + return { + kind: _kinds.Kind.OBJECT, + fields: this.any(_tokenKind.TokenKind.BRACE_L, item, _tokenKind.TokenKind.BRACE_R), + loc: this.loc(start) + }; + } + /** + * ObjectField[Const] : Name : Value[?Const] + */ + ; + + _proto.parseObjectField = function parseObjectField(isConst) { + var start = this._lexer.token; + var name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return { + kind: _kinds.Kind.OBJECT_FIELD, + name: name, + value: this.parseValueLiteral(isConst), + loc: this.loc(start) + }; + } // Implements the parsing rules in the Directives section. + + /** + * Directives[Const] : Directive[?Const]+ + */ + ; + + _proto.parseDirectives = function parseDirectives(isConst) { + var directives = []; + + while (this.peek(_tokenKind.TokenKind.AT)) { + directives.push(this.parseDirective(isConst)); + } + + return directives; + } + /** + * Directive[Const] : @ Name Arguments[?Const]? + */ + ; + + _proto.parseDirective = function parseDirective(isConst) { + var start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.AT); + return { + kind: _kinds.Kind.DIRECTIVE, + name: this.parseName(), + arguments: this.parseArguments(isConst), + loc: this.loc(start) + }; + } // Implements the parsing rules in the Types section. + + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + ; + + _proto.parseTypeReference = function parseTypeReference() { + var start = this._lexer.token; + var type; + + if (this.expectOptionalToken(_tokenKind.TokenKind.BRACKET_L)) { + type = this.parseTypeReference(); + this.expectToken(_tokenKind.TokenKind.BRACKET_R); + type = { + kind: _kinds.Kind.LIST_TYPE, + type: type, + loc: this.loc(start) + }; + } else { + type = this.parseNamedType(); + } + + if (this.expectOptionalToken(_tokenKind.TokenKind.BANG)) { + return { + kind: _kinds.Kind.NON_NULL_TYPE, + type: type, + loc: this.loc(start) + }; + } + + return type; + } + /** + * NamedType : Name + */ + ; + + _proto.parseNamedType = function parseNamedType() { + var start = this._lexer.token; + return { + kind: _kinds.Kind.NAMED_TYPE, + name: this.parseName(), + loc: this.loc(start) + }; + } // Implements the parsing rules in the Type Definition section. + + /** + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ + ; + + _proto.parseTypeSystemDefinition = function parseTypeSystemDefinition() { + // Many definitions begin with a description and require a lookahead. + var keywordToken = this.peekDescription() ? this._lexer.lookahead() : this._lexer.token; + + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaDefinition(); + + case 'scalar': + return this.parseScalarTypeDefinition(); + + case 'type': + return this.parseObjectTypeDefinition(); + + case 'interface': + return this.parseInterfaceTypeDefinition(); + + case 'union': + return this.parseUnionTypeDefinition(); + + case 'enum': + return this.parseEnumTypeDefinition(); + + case 'input': + return this.parseInputObjectTypeDefinition(); + + case 'directive': + return this.parseDirectiveDefinition(); + } + } + + throw this.unexpected(keywordToken); + }; + + _proto.peekDescription = function peekDescription() { + return this.peek(_tokenKind.TokenKind.STRING) || this.peek(_tokenKind.TokenKind.BLOCK_STRING); + } + /** + * Description : StringValue + */ + ; + + _proto.parseDescription = function parseDescription() { + if (this.peekDescription()) { + return this.parseStringLiteral(); + } + } + /** + * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } + */ + ; + + _proto.parseSchemaDefinition = function parseSchemaDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('schema'); + var directives = this.parseDirectives(true); + var operationTypes = this.many(_tokenKind.TokenKind.BRACE_L, this.parseOperationTypeDefinition, _tokenKind.TokenKind.BRACE_R); + return { + kind: _kinds.Kind.SCHEMA_DEFINITION, + description: description, + directives: directives, + operationTypes: operationTypes, + loc: this.loc(start) + }; + } + /** + * OperationTypeDefinition : OperationType : NamedType + */ + ; + + _proto.parseOperationTypeDefinition = function parseOperationTypeDefinition() { + var start = this._lexer.token; + var operation = this.parseOperationType(); + this.expectToken(_tokenKind.TokenKind.COLON); + var type = this.parseNamedType(); + return { + kind: _kinds.Kind.OPERATION_TYPE_DEFINITION, + operation: operation, + type: type, + loc: this.loc(start) + }; + } + /** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ + ; + + _proto.parseScalarTypeDefinition = function parseScalarTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('scalar'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + return { + kind: _kinds.Kind.SCALAR_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: this.loc(start) + }; + } + /** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ + ; + + _proto.parseObjectTypeDefinition = function parseObjectTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('type'); + var name = this.parseName(); + var interfaces = this.parseImplementsInterfaces(); + var directives = this.parseDirectives(true); + var fields = this.parseFieldsDefinition(); + return { + kind: _kinds.Kind.OBJECT_TYPE_DEFINITION, + description: description, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ + ; + + _proto.parseImplementsInterfaces = function parseImplementsInterfaces() { + var _this$_options2; + + if (!this.expectOptionalKeyword('implements')) { + return []; + } + + if (((_this$_options2 = this._options) === null || _this$_options2 === void 0 ? void 0 : _this$_options2.allowLegacySDLImplementsInterfaces) === true) { + var types = []; // Optional leading ampersand + + this.expectOptionalToken(_tokenKind.TokenKind.AMP); + + do { + types.push(this.parseNamedType()); + } while (this.expectOptionalToken(_tokenKind.TokenKind.AMP) || this.peek(_tokenKind.TokenKind.NAME)); + + return types; + } + + return this.delimitedMany(_tokenKind.TokenKind.AMP, this.parseNamedType); + } + /** + * FieldsDefinition : { FieldDefinition+ } + */ + ; + + _proto.parseFieldsDefinition = function parseFieldsDefinition() { + var _this$_options3; + + // Legacy support for the SDL? + if (((_this$_options3 = this._options) === null || _this$_options3 === void 0 ? void 0 : _this$_options3.allowLegacySDLEmptyFields) === true && this.peek(_tokenKind.TokenKind.BRACE_L) && this._lexer.lookahead().kind === _tokenKind.TokenKind.BRACE_R) { + this._lexer.advance(); + + this._lexer.advance(); + + return []; + } + + return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseFieldDefinition, _tokenKind.TokenKind.BRACE_R); + } + /** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ + ; + + _proto.parseFieldDefinition = function parseFieldDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + var name = this.parseName(); + var args = this.parseArgumentDefs(); + this.expectToken(_tokenKind.TokenKind.COLON); + var type = this.parseTypeReference(); + var directives = this.parseDirectives(true); + return { + kind: _kinds.Kind.FIELD_DEFINITION, + description: description, + name: name, + arguments: args, + type: type, + directives: directives, + loc: this.loc(start) + }; + } + /** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ + ; + + _proto.parseArgumentDefs = function parseArgumentDefs() { + return this.optionalMany(_tokenKind.TokenKind.PAREN_L, this.parseInputValueDef, _tokenKind.TokenKind.PAREN_R); + } + /** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ + ; + + _proto.parseInputValueDef = function parseInputValueDef() { + var start = this._lexer.token; + var description = this.parseDescription(); + var name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + var type = this.parseTypeReference(); + var defaultValue; + + if (this.expectOptionalToken(_tokenKind.TokenKind.EQUALS)) { + defaultValue = this.parseValueLiteral(true); + } + + var directives = this.parseDirectives(true); + return { + kind: _kinds.Kind.INPUT_VALUE_DEFINITION, + description: description, + name: name, + type: type, + defaultValue: defaultValue, + directives: directives, + loc: this.loc(start) + }; + } + /** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ + ; + + _proto.parseInterfaceTypeDefinition = function parseInterfaceTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('interface'); + var name = this.parseName(); + var interfaces = this.parseImplementsInterfaces(); + var directives = this.parseDirectives(true); + var fields = this.parseFieldsDefinition(); + return { + kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION, + description: description, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ + ; + + _proto.parseUnionTypeDefinition = function parseUnionTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('union'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var types = this.parseUnionMemberTypes(); + return { + kind: _kinds.Kind.UNION_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + types: types, + loc: this.loc(start) + }; + } + /** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ + ; + + _proto.parseUnionMemberTypes = function parseUnionMemberTypes() { + return this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) ? this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseNamedType) : []; + } + /** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ + ; + + _proto.parseEnumTypeDefinition = function parseEnumTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('enum'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var values = this.parseEnumValuesDefinition(); + return { + kind: _kinds.Kind.ENUM_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + values: values, + loc: this.loc(start) + }; + } + /** + * EnumValuesDefinition : { EnumValueDefinition+ } + */ + ; + + _proto.parseEnumValuesDefinition = function parseEnumValuesDefinition() { + return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseEnumValueDefinition, _tokenKind.TokenKind.BRACE_R); + } + /** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * EnumValue : Name + */ + ; + + _proto.parseEnumValueDefinition = function parseEnumValueDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + var name = this.parseName(); + var directives = this.parseDirectives(true); + return { + kind: _kinds.Kind.ENUM_VALUE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: this.loc(start) + }; + } + /** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ + ; + + _proto.parseInputObjectTypeDefinition = function parseInputObjectTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('input'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var fields = this.parseInputFieldsDefinition(); + return { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * InputFieldsDefinition : { InputValueDefinition+ } + */ + ; + + _proto.parseInputFieldsDefinition = function parseInputFieldsDefinition() { + return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseInputValueDef, _tokenKind.TokenKind.BRACE_R); + } + /** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ + ; + + _proto.parseTypeSystemExtension = function parseTypeSystemExtension() { + var keywordToken = this._lexer.lookahead(); + + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaExtension(); + + case 'scalar': + return this.parseScalarTypeExtension(); + + case 'type': + return this.parseObjectTypeExtension(); + + case 'interface': + return this.parseInterfaceTypeExtension(); + + case 'union': + return this.parseUnionTypeExtension(); + + case 'enum': + return this.parseEnumTypeExtension(); + + case 'input': + return this.parseInputObjectTypeExtension(); + } + } + + throw this.unexpected(keywordToken); + } + /** + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + */ + ; + + _proto.parseSchemaExtension = function parseSchemaExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('schema'); + var directives = this.parseDirectives(true); + var operationTypes = this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseOperationTypeDefinition, _tokenKind.TokenKind.BRACE_R); + + if (directives.length === 0 && operationTypes.length === 0) { + throw this.unexpected(); + } + + return { + kind: _kinds.Kind.SCHEMA_EXTENSION, + directives: directives, + operationTypes: operationTypes, + loc: this.loc(start) + }; + } + /** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ + ; + + _proto.parseScalarTypeExtension = function parseScalarTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('scalar'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + + if (directives.length === 0) { + throw this.unexpected(); + } + + return { + kind: _kinds.Kind.SCALAR_TYPE_EXTENSION, + name: name, + directives: directives, + loc: this.loc(start) + }; + } + /** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ + ; + + _proto.parseObjectTypeExtension = function parseObjectTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('type'); + var name = this.parseName(); + var interfaces = this.parseImplementsInterfaces(); + var directives = this.parseDirectives(true); + var fields = this.parseFieldsDefinition(); + + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + + return { + kind: _kinds.Kind.OBJECT_TYPE_EXTENSION, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * InterfaceTypeExtension : + * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend interface Name ImplementsInterfaces? Directives[Const] + * - extend interface Name ImplementsInterfaces + */ + ; + + _proto.parseInterfaceTypeExtension = function parseInterfaceTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('interface'); + var name = this.parseName(); + var interfaces = this.parseImplementsInterfaces(); + var directives = this.parseDirectives(true); + var fields = this.parseFieldsDefinition(); + + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + + return { + kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ + ; + + _proto.parseUnionTypeExtension = function parseUnionTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('union'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var types = this.parseUnionMemberTypes(); + + if (directives.length === 0 && types.length === 0) { + throw this.unexpected(); + } + + return { + kind: _kinds.Kind.UNION_TYPE_EXTENSION, + name: name, + directives: directives, + types: types, + loc: this.loc(start) + }; + } + /** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ + ; + + _proto.parseEnumTypeExtension = function parseEnumTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('enum'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var values = this.parseEnumValuesDefinition(); + + if (directives.length === 0 && values.length === 0) { + throw this.unexpected(); + } + + return { + kind: _kinds.Kind.ENUM_TYPE_EXTENSION, + name: name, + directives: directives, + values: values, + loc: this.loc(start) + }; + } + /** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ + ; + + _proto.parseInputObjectTypeExtension = function parseInputObjectTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('input'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var fields = this.parseInputFieldsDefinition(); + + if (directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + + return { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, + name: name, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations + */ + ; + + _proto.parseDirectiveDefinition = function parseDirectiveDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('directive'); + this.expectToken(_tokenKind.TokenKind.AT); + var name = this.parseName(); + var args = this.parseArgumentDefs(); + var repeatable = this.expectOptionalKeyword('repeatable'); + this.expectKeyword('on'); + var locations = this.parseDirectiveLocations(); + return { + kind: _kinds.Kind.DIRECTIVE_DEFINITION, + description: description, + name: name, + arguments: args, + repeatable: repeatable, + locations: locations, + loc: this.loc(start) + }; + } + /** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ + ; + + _proto.parseDirectiveLocations = function parseDirectiveLocations() { + return this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseDirectiveLocation); + } + /* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ + ; + + _proto.parseDirectiveLocation = function parseDirectiveLocation() { + var start = this._lexer.token; + var name = this.parseName(); + + if (_directiveLocation.DirectiveLocation[name.value] !== undefined) { + return name; + } + + throw this.unexpected(start); + } // Core parsing utility functions + + /** + * Returns a location object, used to identify the place in the source that created a given parsed object. + */ + ; + + _proto.loc = function loc(startToken) { + var _this$_options4; + + if (((_this$_options4 = this._options) === null || _this$_options4 === void 0 ? void 0 : _this$_options4.noLocation) !== true) { + return new _ast.Location(startToken, this._lexer.lastToken, this._lexer.source); + } + } + /** + * Determines if the next token is of a given kind + */ + ; + + _proto.peek = function peek(kind) { + return this._lexer.token.kind === kind; + } + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and throw an error. + */ + ; + + _proto.expectToken = function expectToken(kind) { + var token = this._lexer.token; + + if (token.kind === kind) { + this._lexer.advance(); + + return token; + } + + throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, "Expected ".concat(getTokenKindDesc(kind), ", found ").concat(getTokenDesc(token), ".")); + } + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and return undefined. + */ + ; + + _proto.expectOptionalToken = function expectOptionalToken(kind) { + var token = this._lexer.token; + + if (token.kind === kind) { + this._lexer.advance(); + + return token; + } + + return undefined; + } + /** + * If the next token is a given keyword, advance the lexer. + * Otherwise, do not change the parser state and throw an error. + */ + ; + + _proto.expectKeyword = function expectKeyword(value) { + var token = this._lexer.token; + + if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { + this._lexer.advance(); + } else { + throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat(getTokenDesc(token), ".")); + } + } + /** + * If the next token is a given keyword, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + */ + ; + + _proto.expectOptionalKeyword = function expectOptionalKeyword(value) { + var token = this._lexer.token; + + if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { + this._lexer.advance(); + + return true; + } + + return false; + } + /** + * Helper function for creating an error when an unexpected lexed token is encountered. + */ + ; + + _proto.unexpected = function unexpected(atToken) { + var token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token; + return (0, _syntaxError.syntaxError)(this._lexer.source, token.start, "Unexpected ".concat(getTokenDesc(token), ".")); + } + /** + * Returns a possibly empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + ; + + _proto.any = function any(openKind, parseFn, closeKind) { + this.expectToken(openKind); + var nodes = []; + + while (!this.expectOptionalToken(closeKind)) { + nodes.push(parseFn.call(this)); + } + + return nodes; + } + /** + * Returns a list of parse nodes, determined by the parseFn. + * It can be empty only if open token is missing otherwise it will always return non-empty list + * that begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + ; + + _proto.optionalMany = function optionalMany(openKind, parseFn, closeKind) { + if (this.expectOptionalToken(openKind)) { + var nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + + return nodes; + } + + return []; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + ; + + _proto.many = function many(openKind, parseFn, closeKind) { + this.expectToken(openKind); + var nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + + return nodes; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. + * Advances the parser to the next lex token after last item in the list. + */ + ; + + _proto.delimitedMany = function delimitedMany(delimiterKind, parseFn) { + this.expectOptionalToken(delimiterKind); + var nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (this.expectOptionalToken(delimiterKind)); + + return nodes; + }; + + return Parser; +}(); +/** + * A helper function to describe a token as a string for debugging. + */ + + +exports.Parser = Parser; + +function getTokenDesc(token) { + var value = token.value; + return getTokenKindDesc(token.kind) + (value != null ? " \"".concat(value, "\"") : ''); +} +/** + * A helper function to describe a token kind as a string for debugging. + */ + + +function getTokenKindDesc(kind) { + return (0, _lexer.isPunctuatorTokenKind)(kind) ? "\"".concat(kind, "\"") : kind; +} diff --git a/school/node_modules/graphql/language/parser.js.flow b/school/node_modules/graphql/language/parser.js.flow new file mode 100644 index 0000000..ee8bd3e --- /dev/null +++ b/school/node_modules/graphql/language/parser.js.flow @@ -0,0 +1,1568 @@ +// @flow strict +import type { GraphQLError } from '../error/GraphQLError'; +import { syntaxError } from '../error/syntaxError'; + +import type { TokenKindEnum } from './tokenKind'; +import type { + Token, + NameNode, + VariableNode, + DocumentNode, + DefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + StringValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from './ast'; +import { Kind } from './kinds'; +import { Location } from './ast'; +import { TokenKind } from './tokenKind'; +import { Source, isSource } from './source'; +import { DirectiveLocation } from './directiveLocation'; +import { Lexer, isPunctuatorTokenKind } from './lexer'; + +/** + * Configuration options to control parser behavior + */ +export type ParseOptions = {| + /** + * By default, the parser creates AST nodes that know the location + * in the source that they correspond to. This configuration flag + * disables that behavior for performance or testing. + */ + noLocation?: boolean, + + /** + * If enabled, the parser will parse empty fields sets in the Schema + * Definition Language. Otherwise, the parser will follow the current + * specification. + * + * This option is provided to ease adoption of the final SDL specification + * and will be removed in v16. + */ + allowLegacySDLEmptyFields?: boolean, + + /** + * If enabled, the parser will parse implemented interfaces with no `&` + * character between each interface. Otherwise, the parser will follow the + * current specification. + * + * This option is provided to ease adoption of the final SDL specification + * and will be removed in v16. + */ + allowLegacySDLImplementsInterfaces?: boolean, + + /** + * EXPERIMENTAL: + * + * If enabled, the parser will understand and parse variable definitions + * contained in a fragment definition. They'll be represented in the + * `variableDefinitions` field of the FragmentDefinitionNode. + * + * The syntax is identical to normal, query-defined variables. For example: + * + * fragment A($var: Boolean = false) on T { + * ... + * } + * + * Note: this feature is experimental and may change or be removed in the + * future. + */ + experimentalFragmentVariables?: boolean, +|}; + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +export function parse( + source: string | Source, + options?: ParseOptions, +): DocumentNode { + const parser = new Parser(source, options); + return parser.parseDocument(); +} + +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ +export function parseValue( + source: string | Source, + options?: ParseOptions, +): ValueNode { + const parser = new Parser(source, options); + parser.expectToken(TokenKind.SOF); + const value = parser.parseValueLiteral(false); + parser.expectToken(TokenKind.EOF); + return value; +} + +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ +export function parseType( + source: string | Source, + options?: ParseOptions, +): TypeNode { + const parser = new Parser(source, options); + parser.expectToken(TokenKind.SOF); + const type = parser.parseTypeReference(); + parser.expectToken(TokenKind.EOF); + return type; +} + +/** + * This class is exported only to assist people in implementing their own parsers + * without duplicating too much code and should be used only as last resort for cases + * such as experimental syntax or if certain features could not be contributed upstream. + * + * It is still part of the internal API and is versioned, so any changes to it are never + * considered breaking changes. If you still need to support multiple versions of the + * library, please use the `versionInfo` variable for version detection. + * + * @internal + */ +export class Parser { + _options: ?ParseOptions; + _lexer: Lexer; + + constructor(source: string | Source, options?: ParseOptions) { + const sourceObj = isSource(source) ? source : new Source(source); + + this._lexer = new Lexer(sourceObj); + this._options = options; + } + + /** + * Converts a name lex token into a name parse node. + */ + parseName(): NameNode { + const token = this.expectToken(TokenKind.NAME); + return { + kind: Kind.NAME, + value: ((token.value: any): string), + loc: this.loc(token), + }; + } + + // Implements the parsing rules in the Document section. + + /** + * Document : Definition+ + */ + parseDocument(): DocumentNode { + const start = this._lexer.token; + return { + kind: Kind.DOCUMENT, + definitions: this.many( + TokenKind.SOF, + this.parseDefinition, + TokenKind.EOF, + ), + loc: this.loc(start), + }; + } + + /** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + * + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + */ + parseDefinition(): DefinitionNode { + if (this.peek(TokenKind.NAME)) { + switch (this._lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + return this.parseOperationDefinition(); + case 'fragment': + return this.parseFragmentDefinition(); + case 'schema': + case 'scalar': + case 'type': + case 'interface': + case 'union': + case 'enum': + case 'input': + case 'directive': + return this.parseTypeSystemDefinition(); + case 'extend': + return this.parseTypeSystemExtension(); + } + } else if (this.peek(TokenKind.BRACE_L)) { + return this.parseOperationDefinition(); + } else if (this.peekDescription()) { + return this.parseTypeSystemDefinition(); + } + + throw this.unexpected(); + } + + // Implements the parsing rules in the Operations section. + + /** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ + parseOperationDefinition(): OperationDefinitionNode { + const start = this._lexer.token; + if (this.peek(TokenKind.BRACE_L)) { + return { + kind: Kind.OPERATION_DEFINITION, + operation: 'query', + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: this.parseSelectionSet(), + loc: this.loc(start), + }; + } + const operation = this.parseOperationType(); + let name; + if (this.peek(TokenKind.NAME)) { + name = this.parseName(); + } + return { + kind: Kind.OPERATION_DEFINITION, + operation, + name, + variableDefinitions: this.parseVariableDefinitions(), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start), + }; + } + + /** + * OperationType : one of query mutation subscription + */ + parseOperationType(): OperationTypeNode { + const operationToken = this.expectToken(TokenKind.NAME); + switch (operationToken.value) { + case 'query': + return 'query'; + case 'mutation': + return 'mutation'; + case 'subscription': + return 'subscription'; + } + + throw this.unexpected(operationToken); + } + + /** + * VariableDefinitions : ( VariableDefinition+ ) + */ + parseVariableDefinitions(): Array<VariableDefinitionNode> { + return this.optionalMany( + TokenKind.PAREN_L, + this.parseVariableDefinition, + TokenKind.PAREN_R, + ); + } + + /** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ + parseVariableDefinition(): VariableDefinitionNode { + const start = this._lexer.token; + return { + kind: Kind.VARIABLE_DEFINITION, + variable: this.parseVariable(), + type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()), + defaultValue: this.expectOptionalToken(TokenKind.EQUALS) + ? this.parseValueLiteral(true) + : undefined, + directives: this.parseDirectives(true), + loc: this.loc(start), + }; + } + + /** + * Variable : $ Name + */ + parseVariable(): VariableNode { + const start = this._lexer.token; + this.expectToken(TokenKind.DOLLAR); + return { + kind: Kind.VARIABLE, + name: this.parseName(), + loc: this.loc(start), + }; + } + + /** + * SelectionSet : { Selection+ } + */ + parseSelectionSet(): SelectionSetNode { + const start = this._lexer.token; + return { + kind: Kind.SELECTION_SET, + selections: this.many( + TokenKind.BRACE_L, + this.parseSelection, + TokenKind.BRACE_R, + ), + loc: this.loc(start), + }; + } + + /** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ + parseSelection(): SelectionNode { + return this.peek(TokenKind.SPREAD) + ? this.parseFragment() + : this.parseField(); + } + + /** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ + parseField(): FieldNode { + const start = this._lexer.token; + + const nameOrAlias = this.parseName(); + let alias; + let name; + if (this.expectOptionalToken(TokenKind.COLON)) { + alias = nameOrAlias; + name = this.parseName(); + } else { + name = nameOrAlias; + } + + return { + kind: Kind.FIELD, + alias, + name, + arguments: this.parseArguments(false), + directives: this.parseDirectives(false), + selectionSet: this.peek(TokenKind.BRACE_L) + ? this.parseSelectionSet() + : undefined, + loc: this.loc(start), + }; + } + + /** + * Arguments[Const] : ( Argument[?Const]+ ) + */ + parseArguments(isConst: boolean): Array<ArgumentNode> { + const item = isConst ? this.parseConstArgument : this.parseArgument; + return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R); + } + + /** + * Argument[Const] : Name : Value[?Const] + */ + parseArgument(): ArgumentNode { + const start = this._lexer.token; + const name = this.parseName(); + + this.expectToken(TokenKind.COLON); + return { + kind: Kind.ARGUMENT, + name, + value: this.parseValueLiteral(false), + loc: this.loc(start), + }; + } + + parseConstArgument(): ArgumentNode { + const start = this._lexer.token; + return { + kind: Kind.ARGUMENT, + name: this.parseName(), + value: (this.expectToken(TokenKind.COLON), this.parseValueLiteral(true)), + loc: this.loc(start), + }; + } + + // Implements the parsing rules in the Fragments section. + + /** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ + parseFragment(): FragmentSpreadNode | InlineFragmentNode { + const start = this._lexer.token; + this.expectToken(TokenKind.SPREAD); + + const hasTypeCondition = this.expectOptionalKeyword('on'); + if (!hasTypeCondition && this.peek(TokenKind.NAME)) { + return { + kind: Kind.FRAGMENT_SPREAD, + name: this.parseFragmentName(), + directives: this.parseDirectives(false), + loc: this.loc(start), + }; + } + return { + kind: Kind.INLINE_FRAGMENT, + typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start), + }; + } + + /** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ + parseFragmentDefinition(): FragmentDefinitionNode { + const start = this._lexer.token; + this.expectKeyword('fragment'); + // Experimental support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + if (this._options?.experimentalFragmentVariables === true) { + return { + kind: Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + variableDefinitions: this.parseVariableDefinitions(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start), + }; + } + return { + kind: Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start), + }; + } + + /** + * FragmentName : Name but not `on` + */ + parseFragmentName(): NameNode { + if (this._lexer.token.value === 'on') { + throw this.unexpected(); + } + return this.parseName(); + } + + // Implements the parsing rules in the Values section. + + /** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ + parseValueLiteral(isConst: boolean): ValueNode { + const token = this._lexer.token; + switch (token.kind) { + case TokenKind.BRACKET_L: + return this.parseList(isConst); + case TokenKind.BRACE_L: + return this.parseObject(isConst); + case TokenKind.INT: + this._lexer.advance(); + return { + kind: Kind.INT, + value: ((token.value: any): string), + loc: this.loc(token), + }; + case TokenKind.FLOAT: + this._lexer.advance(); + return { + kind: Kind.FLOAT, + value: ((token.value: any): string), + loc: this.loc(token), + }; + case TokenKind.STRING: + case TokenKind.BLOCK_STRING: + return this.parseStringLiteral(); + case TokenKind.NAME: + this._lexer.advance(); + switch (token.value) { + case 'true': + return { kind: Kind.BOOLEAN, value: true, loc: this.loc(token) }; + case 'false': + return { kind: Kind.BOOLEAN, value: false, loc: this.loc(token) }; + case 'null': + return { kind: Kind.NULL, loc: this.loc(token) }; + default: + return { + kind: Kind.ENUM, + value: ((token.value: any): string), + loc: this.loc(token), + }; + } + case TokenKind.DOLLAR: + if (!isConst) { + return this.parseVariable(); + } + break; + } + throw this.unexpected(); + } + + parseStringLiteral(): StringValueNode { + const token = this._lexer.token; + this._lexer.advance(); + return { + kind: Kind.STRING, + value: ((token.value: any): string), + block: token.kind === TokenKind.BLOCK_STRING, + loc: this.loc(token), + }; + } + + /** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ + parseList(isConst: boolean): ListValueNode { + const start = this._lexer.token; + const item = () => this.parseValueLiteral(isConst); + return { + kind: Kind.LIST, + values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R), + loc: this.loc(start), + }; + } + + /** + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + */ + parseObject(isConst: boolean): ObjectValueNode { + const start = this._lexer.token; + const item = () => this.parseObjectField(isConst); + return { + kind: Kind.OBJECT, + fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R), + loc: this.loc(start), + }; + } + + /** + * ObjectField[Const] : Name : Value[?Const] + */ + parseObjectField(isConst: boolean): ObjectFieldNode { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(TokenKind.COLON); + + return { + kind: Kind.OBJECT_FIELD, + name, + value: this.parseValueLiteral(isConst), + loc: this.loc(start), + }; + } + + // Implements the parsing rules in the Directives section. + + /** + * Directives[Const] : Directive[?Const]+ + */ + parseDirectives(isConst: boolean): Array<DirectiveNode> { + const directives = []; + while (this.peek(TokenKind.AT)) { + directives.push(this.parseDirective(isConst)); + } + return directives; + } + + /** + * Directive[Const] : @ Name Arguments[?Const]? + */ + parseDirective(isConst: boolean): DirectiveNode { + const start = this._lexer.token; + this.expectToken(TokenKind.AT); + return { + kind: Kind.DIRECTIVE, + name: this.parseName(), + arguments: this.parseArguments(isConst), + loc: this.loc(start), + }; + } + + // Implements the parsing rules in the Types section. + + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + parseTypeReference(): TypeNode { + const start = this._lexer.token; + let type; + if (this.expectOptionalToken(TokenKind.BRACKET_L)) { + type = this.parseTypeReference(); + this.expectToken(TokenKind.BRACKET_R); + type = { + kind: Kind.LIST_TYPE, + type, + loc: this.loc(start), + }; + } else { + type = this.parseNamedType(); + } + + if (this.expectOptionalToken(TokenKind.BANG)) { + return { + kind: Kind.NON_NULL_TYPE, + type, + loc: this.loc(start), + }; + } + return type; + } + + /** + * NamedType : Name + */ + parseNamedType(): NamedTypeNode { + const start = this._lexer.token; + return { + kind: Kind.NAMED_TYPE, + name: this.parseName(), + loc: this.loc(start), + }; + } + + // Implements the parsing rules in the Type Definition section. + + /** + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ + parseTypeSystemDefinition(): TypeSystemDefinitionNode { + // Many definitions begin with a description and require a lookahead. + const keywordToken = this.peekDescription() + ? this._lexer.lookahead() + : this._lexer.token; + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaDefinition(); + case 'scalar': + return this.parseScalarTypeDefinition(); + case 'type': + return this.parseObjectTypeDefinition(); + case 'interface': + return this.parseInterfaceTypeDefinition(); + case 'union': + return this.parseUnionTypeDefinition(); + case 'enum': + return this.parseEnumTypeDefinition(); + case 'input': + return this.parseInputObjectTypeDefinition(); + case 'directive': + return this.parseDirectiveDefinition(); + } + } + + throw this.unexpected(keywordToken); + } + + peekDescription(): boolean { + return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING); + } + + /** + * Description : StringValue + */ + parseDescription(): void | StringValueNode { + if (this.peekDescription()) { + return this.parseStringLiteral(); + } + } + + /** + * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } + */ + parseSchemaDefinition(): SchemaDefinitionNode { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('schema'); + const directives = this.parseDirectives(true); + const operationTypes = this.many( + TokenKind.BRACE_L, + this.parseOperationTypeDefinition, + TokenKind.BRACE_R, + ); + return { + kind: Kind.SCHEMA_DEFINITION, + description, + directives, + operationTypes, + loc: this.loc(start), + }; + } + + /** + * OperationTypeDefinition : OperationType : NamedType + */ + parseOperationTypeDefinition(): OperationTypeDefinitionNode { + const start = this._lexer.token; + const operation = this.parseOperationType(); + this.expectToken(TokenKind.COLON); + const type = this.parseNamedType(); + return { + kind: Kind.OPERATION_TYPE_DEFINITION, + operation, + type, + loc: this.loc(start), + }; + } + + /** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ + parseScalarTypeDefinition(): ScalarTypeDefinitionNode { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseDirectives(true); + return { + kind: Kind.SCALAR_TYPE_DEFINITION, + description, + name, + directives, + loc: this.loc(start), + }; + } + + /** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ + parseObjectTypeDefinition(): ObjectTypeDefinitionNode { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseDirectives(true); + const fields = this.parseFieldsDefinition(); + return { + kind: Kind.OBJECT_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + loc: this.loc(start), + }; + } + + /** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ + parseImplementsInterfaces(): Array<NamedTypeNode> { + if (!this.expectOptionalKeyword('implements')) { + return []; + } + + if (this._options?.allowLegacySDLImplementsInterfaces === true) { + const types = []; + // Optional leading ampersand + this.expectOptionalToken(TokenKind.AMP); + do { + types.push(this.parseNamedType()); + } while ( + this.expectOptionalToken(TokenKind.AMP) || + this.peek(TokenKind.NAME) + ); + return types; + } + + return this.delimitedMany(TokenKind.AMP, this.parseNamedType); + } + + /** + * FieldsDefinition : { FieldDefinition+ } + */ + parseFieldsDefinition(): Array<FieldDefinitionNode> { + // Legacy support for the SDL? + if ( + this._options?.allowLegacySDLEmptyFields === true && + this.peek(TokenKind.BRACE_L) && + this._lexer.lookahead().kind === TokenKind.BRACE_R + ) { + this._lexer.advance(); + this._lexer.advance(); + return []; + } + return this.optionalMany( + TokenKind.BRACE_L, + this.parseFieldDefinition, + TokenKind.BRACE_R, + ); + } + + /** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ + parseFieldDefinition(): FieldDefinitionNode { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + this.expectToken(TokenKind.COLON); + const type = this.parseTypeReference(); + const directives = this.parseDirectives(true); + return { + kind: Kind.FIELD_DEFINITION, + description, + name, + arguments: args, + type, + directives, + loc: this.loc(start), + }; + } + + /** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ + parseArgumentDefs(): Array<InputValueDefinitionNode> { + return this.optionalMany( + TokenKind.PAREN_L, + this.parseInputValueDef, + TokenKind.PAREN_R, + ); + } + + /** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ + parseInputValueDef(): InputValueDefinitionNode { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + this.expectToken(TokenKind.COLON); + const type = this.parseTypeReference(); + let defaultValue; + if (this.expectOptionalToken(TokenKind.EQUALS)) { + defaultValue = this.parseValueLiteral(true); + } + const directives = this.parseDirectives(true); + return { + kind: Kind.INPUT_VALUE_DEFINITION, + description, + name, + type, + defaultValue, + directives, + loc: this.loc(start), + }; + } + + /** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ + parseInterfaceTypeDefinition(): InterfaceTypeDefinitionNode { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseDirectives(true); + const fields = this.parseFieldsDefinition(); + return { + kind: Kind.INTERFACE_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + loc: this.loc(start), + }; + } + + /** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ + parseUnionTypeDefinition(): UnionTypeDefinitionNode { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseDirectives(true); + const types = this.parseUnionMemberTypes(); + return { + kind: Kind.UNION_TYPE_DEFINITION, + description, + name, + directives, + types, + loc: this.loc(start), + }; + } + + /** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ + parseUnionMemberTypes(): Array<NamedTypeNode> { + return this.expectOptionalToken(TokenKind.EQUALS) + ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType) + : []; + } + + /** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ + parseEnumTypeDefinition(): EnumTypeDefinitionNode { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseDirectives(true); + const values = this.parseEnumValuesDefinition(); + return { + kind: Kind.ENUM_TYPE_DEFINITION, + description, + name, + directives, + values, + loc: this.loc(start), + }; + } + + /** + * EnumValuesDefinition : { EnumValueDefinition+ } + */ + parseEnumValuesDefinition(): Array<EnumValueDefinitionNode> { + return this.optionalMany( + TokenKind.BRACE_L, + this.parseEnumValueDefinition, + TokenKind.BRACE_R, + ); + } + + /** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * EnumValue : Name + */ + parseEnumValueDefinition(): EnumValueDefinitionNode { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + const directives = this.parseDirectives(true); + return { + kind: Kind.ENUM_VALUE_DEFINITION, + description, + name, + directives, + loc: this.loc(start), + }; + } + + /** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ + parseInputObjectTypeDefinition(): InputObjectTypeDefinitionNode { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseDirectives(true); + const fields = this.parseInputFieldsDefinition(); + return { + kind: Kind.INPUT_OBJECT_TYPE_DEFINITION, + description, + name, + directives, + fields, + loc: this.loc(start), + }; + } + + /** + * InputFieldsDefinition : { InputValueDefinition+ } + */ + parseInputFieldsDefinition(): Array<InputValueDefinitionNode> { + return this.optionalMany( + TokenKind.BRACE_L, + this.parseInputValueDef, + TokenKind.BRACE_R, + ); + } + + /** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ + parseTypeSystemExtension(): TypeSystemExtensionNode { + const keywordToken = this._lexer.lookahead(); + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaExtension(); + case 'scalar': + return this.parseScalarTypeExtension(); + case 'type': + return this.parseObjectTypeExtension(); + case 'interface': + return this.parseInterfaceTypeExtension(); + case 'union': + return this.parseUnionTypeExtension(); + case 'enum': + return this.parseEnumTypeExtension(); + case 'input': + return this.parseInputObjectTypeExtension(); + } + } + + throw this.unexpected(keywordToken); + } + + /** + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + */ + parseSchemaExtension(): SchemaExtensionNode { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('schema'); + const directives = this.parseDirectives(true); + const operationTypes = this.optionalMany( + TokenKind.BRACE_L, + this.parseOperationTypeDefinition, + TokenKind.BRACE_R, + ); + if (directives.length === 0 && operationTypes.length === 0) { + throw this.unexpected(); + } + return { + kind: Kind.SCHEMA_EXTENSION, + directives, + operationTypes, + loc: this.loc(start), + }; + } + + /** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ + parseScalarTypeExtension(): ScalarTypeExtensionNode { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseDirectives(true); + if (directives.length === 0) { + throw this.unexpected(); + } + return { + kind: Kind.SCALAR_TYPE_EXTENSION, + name, + directives, + loc: this.loc(start), + }; + } + + /** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ + parseObjectTypeExtension(): ObjectTypeExtensionNode { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseDirectives(true); + const fields = this.parseFieldsDefinition(); + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw this.unexpected(); + } + return { + kind: Kind.OBJECT_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + loc: this.loc(start), + }; + } + + /** + * InterfaceTypeExtension : + * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend interface Name ImplementsInterfaces? Directives[Const] + * - extend interface Name ImplementsInterfaces + */ + parseInterfaceTypeExtension(): InterfaceTypeExtensionNode { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseDirectives(true); + const fields = this.parseFieldsDefinition(); + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw this.unexpected(); + } + return { + kind: Kind.INTERFACE_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + loc: this.loc(start), + }; + } + + /** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ + parseUnionTypeExtension(): UnionTypeExtensionNode { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseDirectives(true); + const types = this.parseUnionMemberTypes(); + if (directives.length === 0 && types.length === 0) { + throw this.unexpected(); + } + return { + kind: Kind.UNION_TYPE_EXTENSION, + name, + directives, + types, + loc: this.loc(start), + }; + } + + /** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ + parseEnumTypeExtension(): EnumTypeExtensionNode { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseDirectives(true); + const values = this.parseEnumValuesDefinition(); + if (directives.length === 0 && values.length === 0) { + throw this.unexpected(); + } + return { + kind: Kind.ENUM_TYPE_EXTENSION, + name, + directives, + values, + loc: this.loc(start), + }; + } + + /** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ + parseInputObjectTypeExtension(): InputObjectTypeExtensionNode { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseDirectives(true); + const fields = this.parseInputFieldsDefinition(); + if (directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + return { + kind: Kind.INPUT_OBJECT_TYPE_EXTENSION, + name, + directives, + fields, + loc: this.loc(start), + }; + } + + /** + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations + */ + parseDirectiveDefinition(): DirectiveDefinitionNode { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('directive'); + this.expectToken(TokenKind.AT); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + const repeatable = this.expectOptionalKeyword('repeatable'); + this.expectKeyword('on'); + const locations = this.parseDirectiveLocations(); + return { + kind: Kind.DIRECTIVE_DEFINITION, + description, + name, + arguments: args, + repeatable, + locations, + loc: this.loc(start), + }; + } + + /** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ + parseDirectiveLocations(): Array<NameNode> { + return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation); + } + + /* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ + parseDirectiveLocation(): NameNode { + const start = this._lexer.token; + const name = this.parseName(); + if (DirectiveLocation[name.value] !== undefined) { + return name; + } + throw this.unexpected(start); + } + + // Core parsing utility functions + + /** + * Returns a location object, used to identify the place in the source that created a given parsed object. + */ + loc(startToken: Token): Location | void { + if (this._options?.noLocation !== true) { + return new Location( + startToken, + this._lexer.lastToken, + this._lexer.source, + ); + } + } + + /** + * Determines if the next token is of a given kind + */ + peek(kind: TokenKindEnum): boolean { + return this._lexer.token.kind === kind; + } + + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and throw an error. + */ + expectToken(kind: TokenKindEnum): Token { + const token = this._lexer.token; + if (token.kind === kind) { + this._lexer.advance(); + return token; + } + + throw syntaxError( + this._lexer.source, + token.start, + `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`, + ); + } + + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and return undefined. + */ + expectOptionalToken(kind: TokenKindEnum): ?Token { + const token = this._lexer.token; + if (token.kind === kind) { + this._lexer.advance(); + return token; + } + return undefined; + } + + /** + * If the next token is a given keyword, advance the lexer. + * Otherwise, do not change the parser state and throw an error. + */ + expectKeyword(value: string) { + const token = this._lexer.token; + if (token.kind === TokenKind.NAME && token.value === value) { + this._lexer.advance(); + } else { + throw syntaxError( + this._lexer.source, + token.start, + `Expected "${value}", found ${getTokenDesc(token)}.`, + ); + } + } + + /** + * If the next token is a given keyword, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + */ + expectOptionalKeyword(value: string): boolean { + const token = this._lexer.token; + if (token.kind === TokenKind.NAME && token.value === value) { + this._lexer.advance(); + return true; + } + return false; + } + + /** + * Helper function for creating an error when an unexpected lexed token is encountered. + */ + unexpected(atToken?: ?Token): GraphQLError { + const token = atToken ?? this._lexer.token; + return syntaxError( + this._lexer.source, + token.start, + `Unexpected ${getTokenDesc(token)}.`, + ); + } + + /** + * Returns a possibly empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + any<T>( + openKind: TokenKindEnum, + parseFn: () => T, + closeKind: TokenKindEnum, + ): Array<T> { + this.expectToken(openKind); + const nodes = []; + while (!this.expectOptionalToken(closeKind)) { + nodes.push(parseFn.call(this)); + } + return nodes; + } + + /** + * Returns a list of parse nodes, determined by the parseFn. + * It can be empty only if open token is missing otherwise it will always return non-empty list + * that begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + optionalMany<T>( + openKind: TokenKindEnum, + parseFn: () => T, + closeKind: TokenKindEnum, + ): Array<T> { + if (this.expectOptionalToken(openKind)) { + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + return nodes; + } + return []; + } + + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + many<T>( + openKind: TokenKindEnum, + parseFn: () => T, + closeKind: TokenKindEnum, + ): Array<T> { + this.expectToken(openKind); + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + return nodes; + } + + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. + * Advances the parser to the next lex token after last item in the list. + */ + delimitedMany<T>(delimiterKind: TokenKindEnum, parseFn: () => T): Array<T> { + this.expectOptionalToken(delimiterKind); + + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (this.expectOptionalToken(delimiterKind)); + return nodes; + } +} + +/** + * A helper function to describe a token as a string for debugging. + */ +function getTokenDesc(token: Token): string { + const value = token.value; + return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : ''); +} + +/** + * A helper function to describe a token kind as a string for debugging. + */ +function getTokenKindDesc(kind: TokenKindEnum): string { + return isPunctuatorTokenKind(kind) ? `"${kind}"` : kind; +} diff --git a/school/node_modules/graphql/language/parser.mjs b/school/node_modules/graphql/language/parser.mjs new file mode 100644 index 0000000..3987f6c --- /dev/null +++ b/school/node_modules/graphql/language/parser.mjs @@ -0,0 +1,1547 @@ +import { syntaxError } from "../error/syntaxError.mjs"; +import { Kind } from "./kinds.mjs"; +import { Location } from "./ast.mjs"; +import { TokenKind } from "./tokenKind.mjs"; +import { Source, isSource } from "./source.mjs"; +import { DirectiveLocation } from "./directiveLocation.mjs"; +import { Lexer, isPunctuatorTokenKind } from "./lexer.mjs"; +/** + * Configuration options to control parser behavior + */ + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +export function parse(source, options) { + var parser = new Parser(source, options); + return parser.parseDocument(); +} +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ + +export function parseValue(source, options) { + var parser = new Parser(source, options); + parser.expectToken(TokenKind.SOF); + var value = parser.parseValueLiteral(false); + parser.expectToken(TokenKind.EOF); + return value; +} +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ + +export function parseType(source, options) { + var parser = new Parser(source, options); + parser.expectToken(TokenKind.SOF); + var type = parser.parseTypeReference(); + parser.expectToken(TokenKind.EOF); + return type; +} +/** + * This class is exported only to assist people in implementing their own parsers + * without duplicating too much code and should be used only as last resort for cases + * such as experimental syntax or if certain features could not be contributed upstream. + * + * It is still part of the internal API and is versioned, so any changes to it are never + * considered breaking changes. If you still need to support multiple versions of the + * library, please use the `versionInfo` variable for version detection. + * + * @internal + */ + +export var Parser = /*#__PURE__*/function () { + function Parser(source, options) { + var sourceObj = isSource(source) ? source : new Source(source); + this._lexer = new Lexer(sourceObj); + this._options = options; + } + /** + * Converts a name lex token into a name parse node. + */ + + + var _proto = Parser.prototype; + + _proto.parseName = function parseName() { + var token = this.expectToken(TokenKind.NAME); + return { + kind: Kind.NAME, + value: token.value, + loc: this.loc(token) + }; + } // Implements the parsing rules in the Document section. + + /** + * Document : Definition+ + */ + ; + + _proto.parseDocument = function parseDocument() { + var start = this._lexer.token; + return { + kind: Kind.DOCUMENT, + definitions: this.many(TokenKind.SOF, this.parseDefinition, TokenKind.EOF), + loc: this.loc(start) + }; + } + /** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + * + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + */ + ; + + _proto.parseDefinition = function parseDefinition() { + if (this.peek(TokenKind.NAME)) { + switch (this._lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + return this.parseOperationDefinition(); + + case 'fragment': + return this.parseFragmentDefinition(); + + case 'schema': + case 'scalar': + case 'type': + case 'interface': + case 'union': + case 'enum': + case 'input': + case 'directive': + return this.parseTypeSystemDefinition(); + + case 'extend': + return this.parseTypeSystemExtension(); + } + } else if (this.peek(TokenKind.BRACE_L)) { + return this.parseOperationDefinition(); + } else if (this.peekDescription()) { + return this.parseTypeSystemDefinition(); + } + + throw this.unexpected(); + } // Implements the parsing rules in the Operations section. + + /** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ + ; + + _proto.parseOperationDefinition = function parseOperationDefinition() { + var start = this._lexer.token; + + if (this.peek(TokenKind.BRACE_L)) { + return { + kind: Kind.OPERATION_DEFINITION, + operation: 'query', + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: this.parseSelectionSet(), + loc: this.loc(start) + }; + } + + var operation = this.parseOperationType(); + var name; + + if (this.peek(TokenKind.NAME)) { + name = this.parseName(); + } + + return { + kind: Kind.OPERATION_DEFINITION, + operation: operation, + name: name, + variableDefinitions: this.parseVariableDefinitions(), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start) + }; + } + /** + * OperationType : one of query mutation subscription + */ + ; + + _proto.parseOperationType = function parseOperationType() { + var operationToken = this.expectToken(TokenKind.NAME); + + switch (operationToken.value) { + case 'query': + return 'query'; + + case 'mutation': + return 'mutation'; + + case 'subscription': + return 'subscription'; + } + + throw this.unexpected(operationToken); + } + /** + * VariableDefinitions : ( VariableDefinition+ ) + */ + ; + + _proto.parseVariableDefinitions = function parseVariableDefinitions() { + return this.optionalMany(TokenKind.PAREN_L, this.parseVariableDefinition, TokenKind.PAREN_R); + } + /** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ + ; + + _proto.parseVariableDefinition = function parseVariableDefinition() { + var start = this._lexer.token; + return { + kind: Kind.VARIABLE_DEFINITION, + variable: this.parseVariable(), + type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()), + defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseValueLiteral(true) : undefined, + directives: this.parseDirectives(true), + loc: this.loc(start) + }; + } + /** + * Variable : $ Name + */ + ; + + _proto.parseVariable = function parseVariable() { + var start = this._lexer.token; + this.expectToken(TokenKind.DOLLAR); + return { + kind: Kind.VARIABLE, + name: this.parseName(), + loc: this.loc(start) + }; + } + /** + * SelectionSet : { Selection+ } + */ + ; + + _proto.parseSelectionSet = function parseSelectionSet() { + var start = this._lexer.token; + return { + kind: Kind.SELECTION_SET, + selections: this.many(TokenKind.BRACE_L, this.parseSelection, TokenKind.BRACE_R), + loc: this.loc(start) + }; + } + /** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ + ; + + _proto.parseSelection = function parseSelection() { + return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField(); + } + /** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ + ; + + _proto.parseField = function parseField() { + var start = this._lexer.token; + var nameOrAlias = this.parseName(); + var alias; + var name; + + if (this.expectOptionalToken(TokenKind.COLON)) { + alias = nameOrAlias; + name = this.parseName(); + } else { + name = nameOrAlias; + } + + return { + kind: Kind.FIELD, + alias: alias, + name: name, + arguments: this.parseArguments(false), + directives: this.parseDirectives(false), + selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined, + loc: this.loc(start) + }; + } + /** + * Arguments[Const] : ( Argument[?Const]+ ) + */ + ; + + _proto.parseArguments = function parseArguments(isConst) { + var item = isConst ? this.parseConstArgument : this.parseArgument; + return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R); + } + /** + * Argument[Const] : Name : Value[?Const] + */ + ; + + _proto.parseArgument = function parseArgument() { + var start = this._lexer.token; + var name = this.parseName(); + this.expectToken(TokenKind.COLON); + return { + kind: Kind.ARGUMENT, + name: name, + value: this.parseValueLiteral(false), + loc: this.loc(start) + }; + }; + + _proto.parseConstArgument = function parseConstArgument() { + var start = this._lexer.token; + return { + kind: Kind.ARGUMENT, + name: this.parseName(), + value: (this.expectToken(TokenKind.COLON), this.parseValueLiteral(true)), + loc: this.loc(start) + }; + } // Implements the parsing rules in the Fragments section. + + /** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ + ; + + _proto.parseFragment = function parseFragment() { + var start = this._lexer.token; + this.expectToken(TokenKind.SPREAD); + var hasTypeCondition = this.expectOptionalKeyword('on'); + + if (!hasTypeCondition && this.peek(TokenKind.NAME)) { + return { + kind: Kind.FRAGMENT_SPREAD, + name: this.parseFragmentName(), + directives: this.parseDirectives(false), + loc: this.loc(start) + }; + } + + return { + kind: Kind.INLINE_FRAGMENT, + typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start) + }; + } + /** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ + ; + + _proto.parseFragmentDefinition = function parseFragmentDefinition() { + var _this$_options; + + var start = this._lexer.token; + this.expectKeyword('fragment'); // Experimental support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + + if (((_this$_options = this._options) === null || _this$_options === void 0 ? void 0 : _this$_options.experimentalFragmentVariables) === true) { + return { + kind: Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + variableDefinitions: this.parseVariableDefinitions(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start) + }; + } + + return { + kind: Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + loc: this.loc(start) + }; + } + /** + * FragmentName : Name but not `on` + */ + ; + + _proto.parseFragmentName = function parseFragmentName() { + if (this._lexer.token.value === 'on') { + throw this.unexpected(); + } + + return this.parseName(); + } // Implements the parsing rules in the Values section. + + /** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ + ; + + _proto.parseValueLiteral = function parseValueLiteral(isConst) { + var token = this._lexer.token; + + switch (token.kind) { + case TokenKind.BRACKET_L: + return this.parseList(isConst); + + case TokenKind.BRACE_L: + return this.parseObject(isConst); + + case TokenKind.INT: + this._lexer.advance(); + + return { + kind: Kind.INT, + value: token.value, + loc: this.loc(token) + }; + + case TokenKind.FLOAT: + this._lexer.advance(); + + return { + kind: Kind.FLOAT, + value: token.value, + loc: this.loc(token) + }; + + case TokenKind.STRING: + case TokenKind.BLOCK_STRING: + return this.parseStringLiteral(); + + case TokenKind.NAME: + this._lexer.advance(); + + switch (token.value) { + case 'true': + return { + kind: Kind.BOOLEAN, + value: true, + loc: this.loc(token) + }; + + case 'false': + return { + kind: Kind.BOOLEAN, + value: false, + loc: this.loc(token) + }; + + case 'null': + return { + kind: Kind.NULL, + loc: this.loc(token) + }; + + default: + return { + kind: Kind.ENUM, + value: token.value, + loc: this.loc(token) + }; + } + + case TokenKind.DOLLAR: + if (!isConst) { + return this.parseVariable(); + } + + break; + } + + throw this.unexpected(); + }; + + _proto.parseStringLiteral = function parseStringLiteral() { + var token = this._lexer.token; + + this._lexer.advance(); + + return { + kind: Kind.STRING, + value: token.value, + block: token.kind === TokenKind.BLOCK_STRING, + loc: this.loc(token) + }; + } + /** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ + ; + + _proto.parseList = function parseList(isConst) { + var _this = this; + + var start = this._lexer.token; + + var item = function item() { + return _this.parseValueLiteral(isConst); + }; + + return { + kind: Kind.LIST, + values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R), + loc: this.loc(start) + }; + } + /** + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + */ + ; + + _proto.parseObject = function parseObject(isConst) { + var _this2 = this; + + var start = this._lexer.token; + + var item = function item() { + return _this2.parseObjectField(isConst); + }; + + return { + kind: Kind.OBJECT, + fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R), + loc: this.loc(start) + }; + } + /** + * ObjectField[Const] : Name : Value[?Const] + */ + ; + + _proto.parseObjectField = function parseObjectField(isConst) { + var start = this._lexer.token; + var name = this.parseName(); + this.expectToken(TokenKind.COLON); + return { + kind: Kind.OBJECT_FIELD, + name: name, + value: this.parseValueLiteral(isConst), + loc: this.loc(start) + }; + } // Implements the parsing rules in the Directives section. + + /** + * Directives[Const] : Directive[?Const]+ + */ + ; + + _proto.parseDirectives = function parseDirectives(isConst) { + var directives = []; + + while (this.peek(TokenKind.AT)) { + directives.push(this.parseDirective(isConst)); + } + + return directives; + } + /** + * Directive[Const] : @ Name Arguments[?Const]? + */ + ; + + _proto.parseDirective = function parseDirective(isConst) { + var start = this._lexer.token; + this.expectToken(TokenKind.AT); + return { + kind: Kind.DIRECTIVE, + name: this.parseName(), + arguments: this.parseArguments(isConst), + loc: this.loc(start) + }; + } // Implements the parsing rules in the Types section. + + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + ; + + _proto.parseTypeReference = function parseTypeReference() { + var start = this._lexer.token; + var type; + + if (this.expectOptionalToken(TokenKind.BRACKET_L)) { + type = this.parseTypeReference(); + this.expectToken(TokenKind.BRACKET_R); + type = { + kind: Kind.LIST_TYPE, + type: type, + loc: this.loc(start) + }; + } else { + type = this.parseNamedType(); + } + + if (this.expectOptionalToken(TokenKind.BANG)) { + return { + kind: Kind.NON_NULL_TYPE, + type: type, + loc: this.loc(start) + }; + } + + return type; + } + /** + * NamedType : Name + */ + ; + + _proto.parseNamedType = function parseNamedType() { + var start = this._lexer.token; + return { + kind: Kind.NAMED_TYPE, + name: this.parseName(), + loc: this.loc(start) + }; + } // Implements the parsing rules in the Type Definition section. + + /** + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ + ; + + _proto.parseTypeSystemDefinition = function parseTypeSystemDefinition() { + // Many definitions begin with a description and require a lookahead. + var keywordToken = this.peekDescription() ? this._lexer.lookahead() : this._lexer.token; + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaDefinition(); + + case 'scalar': + return this.parseScalarTypeDefinition(); + + case 'type': + return this.parseObjectTypeDefinition(); + + case 'interface': + return this.parseInterfaceTypeDefinition(); + + case 'union': + return this.parseUnionTypeDefinition(); + + case 'enum': + return this.parseEnumTypeDefinition(); + + case 'input': + return this.parseInputObjectTypeDefinition(); + + case 'directive': + return this.parseDirectiveDefinition(); + } + } + + throw this.unexpected(keywordToken); + }; + + _proto.peekDescription = function peekDescription() { + return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING); + } + /** + * Description : StringValue + */ + ; + + _proto.parseDescription = function parseDescription() { + if (this.peekDescription()) { + return this.parseStringLiteral(); + } + } + /** + * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } + */ + ; + + _proto.parseSchemaDefinition = function parseSchemaDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('schema'); + var directives = this.parseDirectives(true); + var operationTypes = this.many(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R); + return { + kind: Kind.SCHEMA_DEFINITION, + description: description, + directives: directives, + operationTypes: operationTypes, + loc: this.loc(start) + }; + } + /** + * OperationTypeDefinition : OperationType : NamedType + */ + ; + + _proto.parseOperationTypeDefinition = function parseOperationTypeDefinition() { + var start = this._lexer.token; + var operation = this.parseOperationType(); + this.expectToken(TokenKind.COLON); + var type = this.parseNamedType(); + return { + kind: Kind.OPERATION_TYPE_DEFINITION, + operation: operation, + type: type, + loc: this.loc(start) + }; + } + /** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ + ; + + _proto.parseScalarTypeDefinition = function parseScalarTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('scalar'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + return { + kind: Kind.SCALAR_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: this.loc(start) + }; + } + /** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ + ; + + _proto.parseObjectTypeDefinition = function parseObjectTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('type'); + var name = this.parseName(); + var interfaces = this.parseImplementsInterfaces(); + var directives = this.parseDirectives(true); + var fields = this.parseFieldsDefinition(); + return { + kind: Kind.OBJECT_TYPE_DEFINITION, + description: description, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ + ; + + _proto.parseImplementsInterfaces = function parseImplementsInterfaces() { + var _this$_options2; + + if (!this.expectOptionalKeyword('implements')) { + return []; + } + + if (((_this$_options2 = this._options) === null || _this$_options2 === void 0 ? void 0 : _this$_options2.allowLegacySDLImplementsInterfaces) === true) { + var types = []; // Optional leading ampersand + + this.expectOptionalToken(TokenKind.AMP); + + do { + types.push(this.parseNamedType()); + } while (this.expectOptionalToken(TokenKind.AMP) || this.peek(TokenKind.NAME)); + + return types; + } + + return this.delimitedMany(TokenKind.AMP, this.parseNamedType); + } + /** + * FieldsDefinition : { FieldDefinition+ } + */ + ; + + _proto.parseFieldsDefinition = function parseFieldsDefinition() { + var _this$_options3; + + // Legacy support for the SDL? + if (((_this$_options3 = this._options) === null || _this$_options3 === void 0 ? void 0 : _this$_options3.allowLegacySDLEmptyFields) === true && this.peek(TokenKind.BRACE_L) && this._lexer.lookahead().kind === TokenKind.BRACE_R) { + this._lexer.advance(); + + this._lexer.advance(); + + return []; + } + + return this.optionalMany(TokenKind.BRACE_L, this.parseFieldDefinition, TokenKind.BRACE_R); + } + /** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ + ; + + _proto.parseFieldDefinition = function parseFieldDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + var name = this.parseName(); + var args = this.parseArgumentDefs(); + this.expectToken(TokenKind.COLON); + var type = this.parseTypeReference(); + var directives = this.parseDirectives(true); + return { + kind: Kind.FIELD_DEFINITION, + description: description, + name: name, + arguments: args, + type: type, + directives: directives, + loc: this.loc(start) + }; + } + /** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ + ; + + _proto.parseArgumentDefs = function parseArgumentDefs() { + return this.optionalMany(TokenKind.PAREN_L, this.parseInputValueDef, TokenKind.PAREN_R); + } + /** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ + ; + + _proto.parseInputValueDef = function parseInputValueDef() { + var start = this._lexer.token; + var description = this.parseDescription(); + var name = this.parseName(); + this.expectToken(TokenKind.COLON); + var type = this.parseTypeReference(); + var defaultValue; + + if (this.expectOptionalToken(TokenKind.EQUALS)) { + defaultValue = this.parseValueLiteral(true); + } + + var directives = this.parseDirectives(true); + return { + kind: Kind.INPUT_VALUE_DEFINITION, + description: description, + name: name, + type: type, + defaultValue: defaultValue, + directives: directives, + loc: this.loc(start) + }; + } + /** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ + ; + + _proto.parseInterfaceTypeDefinition = function parseInterfaceTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('interface'); + var name = this.parseName(); + var interfaces = this.parseImplementsInterfaces(); + var directives = this.parseDirectives(true); + var fields = this.parseFieldsDefinition(); + return { + kind: Kind.INTERFACE_TYPE_DEFINITION, + description: description, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ + ; + + _proto.parseUnionTypeDefinition = function parseUnionTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('union'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var types = this.parseUnionMemberTypes(); + return { + kind: Kind.UNION_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + types: types, + loc: this.loc(start) + }; + } + /** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ + ; + + _proto.parseUnionMemberTypes = function parseUnionMemberTypes() { + return this.expectOptionalToken(TokenKind.EQUALS) ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType) : []; + } + /** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ + ; + + _proto.parseEnumTypeDefinition = function parseEnumTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('enum'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var values = this.parseEnumValuesDefinition(); + return { + kind: Kind.ENUM_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + values: values, + loc: this.loc(start) + }; + } + /** + * EnumValuesDefinition : { EnumValueDefinition+ } + */ + ; + + _proto.parseEnumValuesDefinition = function parseEnumValuesDefinition() { + return this.optionalMany(TokenKind.BRACE_L, this.parseEnumValueDefinition, TokenKind.BRACE_R); + } + /** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * EnumValue : Name + */ + ; + + _proto.parseEnumValueDefinition = function parseEnumValueDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + var name = this.parseName(); + var directives = this.parseDirectives(true); + return { + kind: Kind.ENUM_VALUE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: this.loc(start) + }; + } + /** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ + ; + + _proto.parseInputObjectTypeDefinition = function parseInputObjectTypeDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('input'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var fields = this.parseInputFieldsDefinition(); + return { + kind: Kind.INPUT_OBJECT_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * InputFieldsDefinition : { InputValueDefinition+ } + */ + ; + + _proto.parseInputFieldsDefinition = function parseInputFieldsDefinition() { + return this.optionalMany(TokenKind.BRACE_L, this.parseInputValueDef, TokenKind.BRACE_R); + } + /** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ + ; + + _proto.parseTypeSystemExtension = function parseTypeSystemExtension() { + var keywordToken = this._lexer.lookahead(); + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaExtension(); + + case 'scalar': + return this.parseScalarTypeExtension(); + + case 'type': + return this.parseObjectTypeExtension(); + + case 'interface': + return this.parseInterfaceTypeExtension(); + + case 'union': + return this.parseUnionTypeExtension(); + + case 'enum': + return this.parseEnumTypeExtension(); + + case 'input': + return this.parseInputObjectTypeExtension(); + } + } + + throw this.unexpected(keywordToken); + } + /** + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + */ + ; + + _proto.parseSchemaExtension = function parseSchemaExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('schema'); + var directives = this.parseDirectives(true); + var operationTypes = this.optionalMany(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R); + + if (directives.length === 0 && operationTypes.length === 0) { + throw this.unexpected(); + } + + return { + kind: Kind.SCHEMA_EXTENSION, + directives: directives, + operationTypes: operationTypes, + loc: this.loc(start) + }; + } + /** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ + ; + + _proto.parseScalarTypeExtension = function parseScalarTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('scalar'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + + if (directives.length === 0) { + throw this.unexpected(); + } + + return { + kind: Kind.SCALAR_TYPE_EXTENSION, + name: name, + directives: directives, + loc: this.loc(start) + }; + } + /** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ + ; + + _proto.parseObjectTypeExtension = function parseObjectTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('type'); + var name = this.parseName(); + var interfaces = this.parseImplementsInterfaces(); + var directives = this.parseDirectives(true); + var fields = this.parseFieldsDefinition(); + + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + + return { + kind: Kind.OBJECT_TYPE_EXTENSION, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * InterfaceTypeExtension : + * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend interface Name ImplementsInterfaces? Directives[Const] + * - extend interface Name ImplementsInterfaces + */ + ; + + _proto.parseInterfaceTypeExtension = function parseInterfaceTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('interface'); + var name = this.parseName(); + var interfaces = this.parseImplementsInterfaces(); + var directives = this.parseDirectives(true); + var fields = this.parseFieldsDefinition(); + + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + + return { + kind: Kind.INTERFACE_TYPE_EXTENSION, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ + ; + + _proto.parseUnionTypeExtension = function parseUnionTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('union'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var types = this.parseUnionMemberTypes(); + + if (directives.length === 0 && types.length === 0) { + throw this.unexpected(); + } + + return { + kind: Kind.UNION_TYPE_EXTENSION, + name: name, + directives: directives, + types: types, + loc: this.loc(start) + }; + } + /** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ + ; + + _proto.parseEnumTypeExtension = function parseEnumTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('enum'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var values = this.parseEnumValuesDefinition(); + + if (directives.length === 0 && values.length === 0) { + throw this.unexpected(); + } + + return { + kind: Kind.ENUM_TYPE_EXTENSION, + name: name, + directives: directives, + values: values, + loc: this.loc(start) + }; + } + /** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ + ; + + _proto.parseInputObjectTypeExtension = function parseInputObjectTypeExtension() { + var start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('input'); + var name = this.parseName(); + var directives = this.parseDirectives(true); + var fields = this.parseInputFieldsDefinition(); + + if (directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + + return { + kind: Kind.INPUT_OBJECT_TYPE_EXTENSION, + name: name, + directives: directives, + fields: fields, + loc: this.loc(start) + }; + } + /** + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations + */ + ; + + _proto.parseDirectiveDefinition = function parseDirectiveDefinition() { + var start = this._lexer.token; + var description = this.parseDescription(); + this.expectKeyword('directive'); + this.expectToken(TokenKind.AT); + var name = this.parseName(); + var args = this.parseArgumentDefs(); + var repeatable = this.expectOptionalKeyword('repeatable'); + this.expectKeyword('on'); + var locations = this.parseDirectiveLocations(); + return { + kind: Kind.DIRECTIVE_DEFINITION, + description: description, + name: name, + arguments: args, + repeatable: repeatable, + locations: locations, + loc: this.loc(start) + }; + } + /** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ + ; + + _proto.parseDirectiveLocations = function parseDirectiveLocations() { + return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation); + } + /* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ + ; + + _proto.parseDirectiveLocation = function parseDirectiveLocation() { + var start = this._lexer.token; + var name = this.parseName(); + + if (DirectiveLocation[name.value] !== undefined) { + return name; + } + + throw this.unexpected(start); + } // Core parsing utility functions + + /** + * Returns a location object, used to identify the place in the source that created a given parsed object. + */ + ; + + _proto.loc = function loc(startToken) { + var _this$_options4; + + if (((_this$_options4 = this._options) === null || _this$_options4 === void 0 ? void 0 : _this$_options4.noLocation) !== true) { + return new Location(startToken, this._lexer.lastToken, this._lexer.source); + } + } + /** + * Determines if the next token is of a given kind + */ + ; + + _proto.peek = function peek(kind) { + return this._lexer.token.kind === kind; + } + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and throw an error. + */ + ; + + _proto.expectToken = function expectToken(kind) { + var token = this._lexer.token; + + if (token.kind === kind) { + this._lexer.advance(); + + return token; + } + + throw syntaxError(this._lexer.source, token.start, "Expected ".concat(getTokenKindDesc(kind), ", found ").concat(getTokenDesc(token), ".")); + } + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and return undefined. + */ + ; + + _proto.expectOptionalToken = function expectOptionalToken(kind) { + var token = this._lexer.token; + + if (token.kind === kind) { + this._lexer.advance(); + + return token; + } + + return undefined; + } + /** + * If the next token is a given keyword, advance the lexer. + * Otherwise, do not change the parser state and throw an error. + */ + ; + + _proto.expectKeyword = function expectKeyword(value) { + var token = this._lexer.token; + + if (token.kind === TokenKind.NAME && token.value === value) { + this._lexer.advance(); + } else { + throw syntaxError(this._lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat(getTokenDesc(token), ".")); + } + } + /** + * If the next token is a given keyword, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + */ + ; + + _proto.expectOptionalKeyword = function expectOptionalKeyword(value) { + var token = this._lexer.token; + + if (token.kind === TokenKind.NAME && token.value === value) { + this._lexer.advance(); + + return true; + } + + return false; + } + /** + * Helper function for creating an error when an unexpected lexed token is encountered. + */ + ; + + _proto.unexpected = function unexpected(atToken) { + var token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token; + return syntaxError(this._lexer.source, token.start, "Unexpected ".concat(getTokenDesc(token), ".")); + } + /** + * Returns a possibly empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + ; + + _proto.any = function any(openKind, parseFn, closeKind) { + this.expectToken(openKind); + var nodes = []; + + while (!this.expectOptionalToken(closeKind)) { + nodes.push(parseFn.call(this)); + } + + return nodes; + } + /** + * Returns a list of parse nodes, determined by the parseFn. + * It can be empty only if open token is missing otherwise it will always return non-empty list + * that begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + ; + + _proto.optionalMany = function optionalMany(openKind, parseFn, closeKind) { + if (this.expectOptionalToken(openKind)) { + var nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + + return nodes; + } + + return []; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + ; + + _proto.many = function many(openKind, parseFn, closeKind) { + this.expectToken(openKind); + var nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + + return nodes; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. + * Advances the parser to the next lex token after last item in the list. + */ + ; + + _proto.delimitedMany = function delimitedMany(delimiterKind, parseFn) { + this.expectOptionalToken(delimiterKind); + var nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (this.expectOptionalToken(delimiterKind)); + + return nodes; + }; + + return Parser; +}(); +/** + * A helper function to describe a token as a string for debugging. + */ + +function getTokenDesc(token) { + var value = token.value; + return getTokenKindDesc(token.kind) + (value != null ? " \"".concat(value, "\"") : ''); +} +/** + * A helper function to describe a token kind as a string for debugging. + */ + + +function getTokenKindDesc(kind) { + return isPunctuatorTokenKind(kind) ? "\"".concat(kind, "\"") : kind; +} diff --git a/school/node_modules/graphql/language/predicates.d.ts b/school/node_modules/graphql/language/predicates.d.ts new file mode 100644 index 0000000..cdbe1f9 --- /dev/null +++ b/school/node_modules/graphql/language/predicates.d.ts @@ -0,0 +1,36 @@ +import { + ASTNode, + DefinitionNode, + ExecutableDefinitionNode, + SelectionNode, + ValueNode, + TypeNode, + TypeSystemDefinitionNode, + TypeDefinitionNode, + TypeSystemExtensionNode, + TypeExtensionNode, +} from './ast'; + +export function isDefinitionNode(node: ASTNode): node is DefinitionNode; + +export function isExecutableDefinitionNode( + node: ASTNode, +): node is ExecutableDefinitionNode; + +export function isSelectionNode(node: ASTNode): node is SelectionNode; + +export function isValueNode(node: ASTNode): node is ValueNode; + +export function isTypeNode(node: ASTNode): node is TypeNode; + +export function isTypeSystemDefinitionNode( + node: ASTNode, +): node is TypeSystemDefinitionNode; + +export function isTypeDefinitionNode(node: ASTNode): node is TypeDefinitionNode; + +export function isTypeSystemExtensionNode( + node: ASTNode, +): node is TypeSystemExtensionNode; + +export function isTypeExtensionNode(node: ASTNode): node is TypeExtensionNode; diff --git a/school/node_modules/graphql/language/predicates.js b/school/node_modules/graphql/language/predicates.js new file mode 100644 index 0000000..f75f9f4 --- /dev/null +++ b/school/node_modules/graphql/language/predicates.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isDefinitionNode = isDefinitionNode; +exports.isExecutableDefinitionNode = isExecutableDefinitionNode; +exports.isSelectionNode = isSelectionNode; +exports.isValueNode = isValueNode; +exports.isTypeNode = isTypeNode; +exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; +exports.isTypeDefinitionNode = isTypeDefinitionNode; +exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; +exports.isTypeExtensionNode = isTypeExtensionNode; + +var _kinds = require("./kinds.js"); + +function isDefinitionNode(node) { + return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node); +} + +function isExecutableDefinitionNode(node) { + return node.kind === _kinds.Kind.OPERATION_DEFINITION || node.kind === _kinds.Kind.FRAGMENT_DEFINITION; +} + +function isSelectionNode(node) { + return node.kind === _kinds.Kind.FIELD || node.kind === _kinds.Kind.FRAGMENT_SPREAD || node.kind === _kinds.Kind.INLINE_FRAGMENT; +} + +function isValueNode(node) { + return node.kind === _kinds.Kind.VARIABLE || node.kind === _kinds.Kind.INT || node.kind === _kinds.Kind.FLOAT || node.kind === _kinds.Kind.STRING || node.kind === _kinds.Kind.BOOLEAN || node.kind === _kinds.Kind.NULL || node.kind === _kinds.Kind.ENUM || node.kind === _kinds.Kind.LIST || node.kind === _kinds.Kind.OBJECT; +} + +function isTypeNode(node) { + return node.kind === _kinds.Kind.NAMED_TYPE || node.kind === _kinds.Kind.LIST_TYPE || node.kind === _kinds.Kind.NON_NULL_TYPE; +} + +function isTypeSystemDefinitionNode(node) { + return node.kind === _kinds.Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === _kinds.Kind.DIRECTIVE_DEFINITION; +} + +function isTypeDefinitionNode(node) { + return node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION; +} + +function isTypeSystemExtensionNode(node) { + return node.kind === _kinds.Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); +} + +function isTypeExtensionNode(node) { + return node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; +} diff --git a/school/node_modules/graphql/language/predicates.js.flow b/school/node_modules/graphql/language/predicates.js.flow new file mode 100644 index 0000000..5597dbb --- /dev/null +++ b/school/node_modules/graphql/language/predicates.js.flow @@ -0,0 +1,82 @@ +// @flow strict +import type { ASTNode } from './ast'; +import { Kind } from './kinds'; + +export function isDefinitionNode(node: ASTNode): boolean %checks { + return ( + isExecutableDefinitionNode(node) || + isTypeSystemDefinitionNode(node) || + isTypeSystemExtensionNode(node) + ); +} + +export function isExecutableDefinitionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.OPERATION_DEFINITION || + node.kind === Kind.FRAGMENT_DEFINITION + ); +} + +export function isSelectionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.FIELD || + node.kind === Kind.FRAGMENT_SPREAD || + node.kind === Kind.INLINE_FRAGMENT + ); +} + +export function isValueNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.VARIABLE || + node.kind === Kind.INT || + node.kind === Kind.FLOAT || + node.kind === Kind.STRING || + node.kind === Kind.BOOLEAN || + node.kind === Kind.NULL || + node.kind === Kind.ENUM || + node.kind === Kind.LIST || + node.kind === Kind.OBJECT + ); +} + +export function isTypeNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.NAMED_TYPE || + node.kind === Kind.LIST_TYPE || + node.kind === Kind.NON_NULL_TYPE + ); +} + +export function isTypeSystemDefinitionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.SCHEMA_DEFINITION || + isTypeDefinitionNode(node) || + node.kind === Kind.DIRECTIVE_DEFINITION + ); +} + +export function isTypeDefinitionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.SCALAR_TYPE_DEFINITION || + node.kind === Kind.OBJECT_TYPE_DEFINITION || + node.kind === Kind.INTERFACE_TYPE_DEFINITION || + node.kind === Kind.UNION_TYPE_DEFINITION || + node.kind === Kind.ENUM_TYPE_DEFINITION || + node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION + ); +} + +export function isTypeSystemExtensionNode(node: ASTNode): boolean %checks { + return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); +} + +export function isTypeExtensionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.SCALAR_TYPE_EXTENSION || + node.kind === Kind.OBJECT_TYPE_EXTENSION || + node.kind === Kind.INTERFACE_TYPE_EXTENSION || + node.kind === Kind.UNION_TYPE_EXTENSION || + node.kind === Kind.ENUM_TYPE_EXTENSION || + node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION + ); +} diff --git a/school/node_modules/graphql/language/predicates.mjs b/school/node_modules/graphql/language/predicates.mjs new file mode 100644 index 0000000..7a066f7 --- /dev/null +++ b/school/node_modules/graphql/language/predicates.mjs @@ -0,0 +1,28 @@ +import { Kind } from "./kinds.mjs"; +export function isDefinitionNode(node) { + return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node); +} +export function isExecutableDefinitionNode(node) { + return node.kind === Kind.OPERATION_DEFINITION || node.kind === Kind.FRAGMENT_DEFINITION; +} +export function isSelectionNode(node) { + return node.kind === Kind.FIELD || node.kind === Kind.FRAGMENT_SPREAD || node.kind === Kind.INLINE_FRAGMENT; +} +export function isValueNode(node) { + return node.kind === Kind.VARIABLE || node.kind === Kind.INT || node.kind === Kind.FLOAT || node.kind === Kind.STRING || node.kind === Kind.BOOLEAN || node.kind === Kind.NULL || node.kind === Kind.ENUM || node.kind === Kind.LIST || node.kind === Kind.OBJECT; +} +export function isTypeNode(node) { + return node.kind === Kind.NAMED_TYPE || node.kind === Kind.LIST_TYPE || node.kind === Kind.NON_NULL_TYPE; +} +export function isTypeSystemDefinitionNode(node) { + return node.kind === Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === Kind.DIRECTIVE_DEFINITION; +} +export function isTypeDefinitionNode(node) { + return node.kind === Kind.SCALAR_TYPE_DEFINITION || node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.INTERFACE_TYPE_DEFINITION || node.kind === Kind.UNION_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION; +} +export function isTypeSystemExtensionNode(node) { + return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); +} +export function isTypeExtensionNode(node) { + return node.kind === Kind.SCALAR_TYPE_EXTENSION || node.kind === Kind.OBJECT_TYPE_EXTENSION || node.kind === Kind.INTERFACE_TYPE_EXTENSION || node.kind === Kind.UNION_TYPE_EXTENSION || node.kind === Kind.ENUM_TYPE_EXTENSION || node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION; +} diff --git a/school/node_modules/graphql/language/printLocation.d.ts b/school/node_modules/graphql/language/printLocation.d.ts new file mode 100644 index 0000000..7d0c347 --- /dev/null +++ b/school/node_modules/graphql/language/printLocation.d.ts @@ -0,0 +1,16 @@ +import { Location } from './ast'; +import { Source } from './source'; +import { SourceLocation } from './location'; + +/** + * Render a helpful description of the location in the GraphQL Source document. + */ +export function printLocation(location: Location): string; + +/** + * Render a helpful description of the location in the GraphQL Source document. + */ +export function printSourceLocation( + source: Source, + sourceLocation: SourceLocation, +): string; diff --git a/school/node_modules/graphql/language/printLocation.js b/school/node_modules/graphql/language/printLocation.js new file mode 100644 index 0000000..86987ba --- /dev/null +++ b/school/node_modules/graphql/language/printLocation.js @@ -0,0 +1,75 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.printLocation = printLocation; +exports.printSourceLocation = printSourceLocation; + +var _location = require("./location.js"); + +/** + * Render a helpful description of the location in the GraphQL Source document. + */ +function printLocation(location) { + return printSourceLocation(location.source, (0, _location.getLocation)(location.source, location.start)); +} +/** + * Render a helpful description of the location in the GraphQL Source document. + */ + + +function printSourceLocation(source, sourceLocation) { + var firstLineColumnOffset = source.locationOffset.column - 1; + var body = whitespace(firstLineColumnOffset) + source.body; + var lineIndex = sourceLocation.line - 1; + var lineOffset = source.locationOffset.line - 1; + var lineNum = sourceLocation.line + lineOffset; + var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; + var columnNum = sourceLocation.column + columnOffset; + var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n"); + var lines = body.split(/\r\n|[\n\r]/g); + var locationLine = lines[lineIndex]; // Special case for minified documents + + if (locationLine.length > 120) { + var subLineIndex = Math.floor(columnNum / 80); + var subLineColumnNum = columnNum % 80; + var subLines = []; + + for (var i = 0; i < locationLine.length; i += 80) { + subLines.push(locationLine.slice(i, i + 80)); + } + + return locationStr + printPrefixedLines([["".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function (subLine) { + return ['', subLine]; + }), [[' ', whitespace(subLineColumnNum - 1) + '^'], ['', subLines[subLineIndex + 1]]])); + } + + return locationStr + printPrefixedLines([// Lines specified like this: ["prefix", "string"], + ["".concat(lineNum - 1), lines[lineIndex - 1]], ["".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1), lines[lineIndex + 1]]]); +} + +function printPrefixedLines(lines) { + var existingLines = lines.filter(function (_ref) { + var _ = _ref[0], + line = _ref[1]; + return line !== undefined; + }); + var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) { + var prefix = _ref2[0]; + return prefix.length; + })); + return existingLines.map(function (_ref3) { + var prefix = _ref3[0], + line = _ref3[1]; + return leftPad(padLen, prefix) + (line ? ' | ' + line : ' |'); + }).join('\n'); +} + +function whitespace(len) { + return Array(len + 1).join(' '); +} + +function leftPad(len, str) { + return whitespace(len - str.length) + str; +} diff --git a/school/node_modules/graphql/language/printLocation.js.flow b/school/node_modules/graphql/language/printLocation.js.flow new file mode 100644 index 0000000..db3bf91 --- /dev/null +++ b/school/node_modules/graphql/language/printLocation.js.flow @@ -0,0 +1,88 @@ +// @flow strict +import type { Source } from './source'; +import type { Location } from './ast'; +import type { SourceLocation } from './location'; +import { getLocation } from './location'; + +/** + * Render a helpful description of the location in the GraphQL Source document. + */ +export function printLocation(location: Location): string { + return printSourceLocation( + location.source, + getLocation(location.source, location.start), + ); +} + +/** + * Render a helpful description of the location in the GraphQL Source document. + */ +export function printSourceLocation( + source: Source, + sourceLocation: SourceLocation, +): string { + const firstLineColumnOffset = source.locationOffset.column - 1; + const body = whitespace(firstLineColumnOffset) + source.body; + + const lineIndex = sourceLocation.line - 1; + const lineOffset = source.locationOffset.line - 1; + const lineNum = sourceLocation.line + lineOffset; + + const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; + const columnNum = sourceLocation.column + columnOffset; + const locationStr = `${source.name}:${lineNum}:${columnNum}\n`; + + const lines = body.split(/\r\n|[\n\r]/g); + const locationLine = lines[lineIndex]; + + // Special case for minified documents + if (locationLine.length > 120) { + const subLineIndex = Math.floor(columnNum / 80); + const subLineColumnNum = columnNum % 80; + const subLines = []; + for (let i = 0; i < locationLine.length; i += 80) { + subLines.push(locationLine.slice(i, i + 80)); + } + + return ( + locationStr + + printPrefixedLines([ + [`${lineNum}`, subLines[0]], + ...subLines.slice(1, subLineIndex + 1).map((subLine) => ['', subLine]), + [' ', whitespace(subLineColumnNum - 1) + '^'], + ['', subLines[subLineIndex + 1]], + ]) + ); + } + + return ( + locationStr + + printPrefixedLines([ + // Lines specified like this: ["prefix", "string"], + [`${lineNum - 1}`, lines[lineIndex - 1]], + [`${lineNum}`, locationLine], + ['', whitespace(columnNum - 1) + '^'], + [`${lineNum + 1}`, lines[lineIndex + 1]], + ]) + ); +} + +function printPrefixedLines(lines: $ReadOnlyArray<[string, string]>): string { + const existingLines = lines.filter(([_, line]) => line !== undefined); + + const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length)); + return existingLines + .map( + ([prefix, line]) => + leftPad(padLen, prefix) + (line ? ' | ' + line : ' |'), + ) + .join('\n'); +} + +function whitespace(len: number): string { + return Array(len + 1).join(' '); +} + +function leftPad(len: number, str: string): string { + return whitespace(len - str.length) + str; +} diff --git a/school/node_modules/graphql/language/printLocation.mjs b/school/node_modules/graphql/language/printLocation.mjs new file mode 100644 index 0000000..c683f26 --- /dev/null +++ b/school/node_modules/graphql/language/printLocation.mjs @@ -0,0 +1,66 @@ +import { getLocation } from "./location.mjs"; +/** + * Render a helpful description of the location in the GraphQL Source document. + */ + +export function printLocation(location) { + return printSourceLocation(location.source, getLocation(location.source, location.start)); +} +/** + * Render a helpful description of the location in the GraphQL Source document. + */ + +export function printSourceLocation(source, sourceLocation) { + var firstLineColumnOffset = source.locationOffset.column - 1; + var body = whitespace(firstLineColumnOffset) + source.body; + var lineIndex = sourceLocation.line - 1; + var lineOffset = source.locationOffset.line - 1; + var lineNum = sourceLocation.line + lineOffset; + var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; + var columnNum = sourceLocation.column + columnOffset; + var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n"); + var lines = body.split(/\r\n|[\n\r]/g); + var locationLine = lines[lineIndex]; // Special case for minified documents + + if (locationLine.length > 120) { + var subLineIndex = Math.floor(columnNum / 80); + var subLineColumnNum = columnNum % 80; + var subLines = []; + + for (var i = 0; i < locationLine.length; i += 80) { + subLines.push(locationLine.slice(i, i + 80)); + } + + return locationStr + printPrefixedLines([["".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function (subLine) { + return ['', subLine]; + }), [[' ', whitespace(subLineColumnNum - 1) + '^'], ['', subLines[subLineIndex + 1]]])); + } + + return locationStr + printPrefixedLines([// Lines specified like this: ["prefix", "string"], + ["".concat(lineNum - 1), lines[lineIndex - 1]], ["".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1), lines[lineIndex + 1]]]); +} + +function printPrefixedLines(lines) { + var existingLines = lines.filter(function (_ref) { + var _ = _ref[0], + line = _ref[1]; + return line !== undefined; + }); + var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) { + var prefix = _ref2[0]; + return prefix.length; + })); + return existingLines.map(function (_ref3) { + var prefix = _ref3[0], + line = _ref3[1]; + return leftPad(padLen, prefix) + (line ? ' | ' + line : ' |'); + }).join('\n'); +} + +function whitespace(len) { + return Array(len + 1).join(' '); +} + +function leftPad(len, str) { + return whitespace(len - str.length) + str; +} diff --git a/school/node_modules/graphql/language/printer.d.ts b/school/node_modules/graphql/language/printer.d.ts new file mode 100644 index 0000000..9329b45 --- /dev/null +++ b/school/node_modules/graphql/language/printer.d.ts @@ -0,0 +1,7 @@ +import { ASTNode } from './ast'; + +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ +export function print(ast: ASTNode): string; diff --git a/school/node_modules/graphql/language/printer.js b/school/node_modules/graphql/language/printer.js new file mode 100644 index 0000000..b76814b --- /dev/null +++ b/school/node_modules/graphql/language/printer.js @@ -0,0 +1,322 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.print = print; + +var _visitor = require("./visitor.js"); + +var _blockString = require("./blockString.js"); + +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ +function print(ast) { + return (0, _visitor.visit)(ast, { + leave: printDocASTReducer + }); +} + +var MAX_LINE_LENGTH = 80; // TODO: provide better type coverage in future + +var printDocASTReducer = { + Name: function Name(node) { + return node.value; + }, + Variable: function Variable(node) { + return '$' + node.name; + }, + // Document + Document: function Document(node) { + return join(node.definitions, '\n\n') + '\n'; + }, + OperationDefinition: function OperationDefinition(node) { + var op = node.operation; + var name = node.name; + var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + var directives = join(node.directives, ' '); + var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' '); + }, + VariableDefinition: function VariableDefinition(_ref) { + var variable = _ref.variable, + type = _ref.type, + defaultValue = _ref.defaultValue, + directives = _ref.directives; + return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')); + }, + SelectionSet: function SelectionSet(_ref2) { + var selections = _ref2.selections; + return block(selections); + }, + Field: function Field(_ref3) { + var alias = _ref3.alias, + name = _ref3.name, + args = _ref3.arguments, + directives = _ref3.directives, + selectionSet = _ref3.selectionSet; + var prefix = wrap('', alias, ': ') + name; + var argsLine = prefix + wrap('(', join(args, ', '), ')'); + + if (argsLine.length > MAX_LINE_LENGTH) { + argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)'); + } + + return join([argsLine, join(directives, ' '), selectionSet], ' '); + }, + Argument: function Argument(_ref4) { + var name = _ref4.name, + value = _ref4.value; + return name + ': ' + value; + }, + // Fragments + FragmentSpread: function FragmentSpread(_ref5) { + var name = _ref5.name, + directives = _ref5.directives; + return '...' + name + wrap(' ', join(directives, ' ')); + }, + InlineFragment: function InlineFragment(_ref6) { + var typeCondition = _ref6.typeCondition, + directives = _ref6.directives, + selectionSet = _ref6.selectionSet; + return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' '); + }, + FragmentDefinition: function FragmentDefinition(_ref7) { + var name = _ref7.name, + typeCondition = _ref7.typeCondition, + variableDefinitions = _ref7.variableDefinitions, + directives = _ref7.directives, + selectionSet = _ref7.selectionSet; + return (// Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + "fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet + ); + }, + // Value + IntValue: function IntValue(_ref8) { + var value = _ref8.value; + return value; + }, + FloatValue: function FloatValue(_ref9) { + var value = _ref9.value; + return value; + }, + StringValue: function StringValue(_ref10, key) { + var value = _ref10.value, + isBlockString = _ref10.block; + return isBlockString ? (0, _blockString.printBlockString)(value, key === 'description' ? '' : ' ') : JSON.stringify(value); + }, + BooleanValue: function BooleanValue(_ref11) { + var value = _ref11.value; + return value ? 'true' : 'false'; + }, + NullValue: function NullValue() { + return 'null'; + }, + EnumValue: function EnumValue(_ref12) { + var value = _ref12.value; + return value; + }, + ListValue: function ListValue(_ref13) { + var values = _ref13.values; + return '[' + join(values, ', ') + ']'; + }, + ObjectValue: function ObjectValue(_ref14) { + var fields = _ref14.fields; + return '{' + join(fields, ', ') + '}'; + }, + ObjectField: function ObjectField(_ref15) { + var name = _ref15.name, + value = _ref15.value; + return name + ': ' + value; + }, + // Directive + Directive: function Directive(_ref16) { + var name = _ref16.name, + args = _ref16.arguments; + return '@' + name + wrap('(', join(args, ', '), ')'); + }, + // Type + NamedType: function NamedType(_ref17) { + var name = _ref17.name; + return name; + }, + ListType: function ListType(_ref18) { + var type = _ref18.type; + return '[' + type + ']'; + }, + NonNullType: function NonNullType(_ref19) { + var type = _ref19.type; + return type + '!'; + }, + // Type System Definitions + SchemaDefinition: addDescription(function (_ref20) { + var directives = _ref20.directives, + operationTypes = _ref20.operationTypes; + return join(['schema', join(directives, ' '), block(operationTypes)], ' '); + }), + OperationTypeDefinition: function OperationTypeDefinition(_ref21) { + var operation = _ref21.operation, + type = _ref21.type; + return operation + ': ' + type; + }, + ScalarTypeDefinition: addDescription(function (_ref22) { + var name = _ref22.name, + directives = _ref22.directives; + return join(['scalar', name, join(directives, ' ')], ' '); + }), + ObjectTypeDefinition: addDescription(function (_ref23) { + var name = _ref23.name, + interfaces = _ref23.interfaces, + directives = _ref23.directives, + fields = _ref23.fields; + return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }), + FieldDefinition: addDescription(function (_ref24) { + var name = _ref24.name, + args = _ref24.arguments, + type = _ref24.type, + directives = _ref24.directives; + return name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' ')); + }), + InputValueDefinition: addDescription(function (_ref25) { + var name = _ref25.name, + type = _ref25.type, + defaultValue = _ref25.defaultValue, + directives = _ref25.directives; + return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' '); + }), + InterfaceTypeDefinition: addDescription(function (_ref26) { + var name = _ref26.name, + interfaces = _ref26.interfaces, + directives = _ref26.directives, + fields = _ref26.fields; + return join(['interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }), + UnionTypeDefinition: addDescription(function (_ref27) { + var name = _ref27.name, + directives = _ref27.directives, + types = _ref27.types; + return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }), + EnumTypeDefinition: addDescription(function (_ref28) { + var name = _ref28.name, + directives = _ref28.directives, + values = _ref28.values; + return join(['enum', name, join(directives, ' '), block(values)], ' '); + }), + EnumValueDefinition: addDescription(function (_ref29) { + var name = _ref29.name, + directives = _ref29.directives; + return join([name, join(directives, ' ')], ' '); + }), + InputObjectTypeDefinition: addDescription(function (_ref30) { + var name = _ref30.name, + directives = _ref30.directives, + fields = _ref30.fields; + return join(['input', name, join(directives, ' '), block(fields)], ' '); + }), + DirectiveDefinition: addDescription(function (_ref31) { + var name = _ref31.name, + args = _ref31.arguments, + repeatable = _ref31.repeatable, + locations = _ref31.locations; + return 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' on ' + join(locations, ' | '); + }), + SchemaExtension: function SchemaExtension(_ref32) { + var directives = _ref32.directives, + operationTypes = _ref32.operationTypes; + return join(['extend schema', join(directives, ' '), block(operationTypes)], ' '); + }, + ScalarTypeExtension: function ScalarTypeExtension(_ref33) { + var name = _ref33.name, + directives = _ref33.directives; + return join(['extend scalar', name, join(directives, ' ')], ' '); + }, + ObjectTypeExtension: function ObjectTypeExtension(_ref34) { + var name = _ref34.name, + interfaces = _ref34.interfaces, + directives = _ref34.directives, + fields = _ref34.fields; + return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }, + InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) { + var name = _ref35.name, + interfaces = _ref35.interfaces, + directives = _ref35.directives, + fields = _ref35.fields; + return join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }, + UnionTypeExtension: function UnionTypeExtension(_ref36) { + var name = _ref36.name, + directives = _ref36.directives, + types = _ref36.types; + return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }, + EnumTypeExtension: function EnumTypeExtension(_ref37) { + var name = _ref37.name, + directives = _ref37.directives, + values = _ref37.values; + return join(['extend enum', name, join(directives, ' '), block(values)], ' '); + }, + InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) { + var name = _ref38.name, + directives = _ref38.directives, + fields = _ref38.fields; + return join(['extend input', name, join(directives, ' '), block(fields)], ' '); + } +}; + +function addDescription(cb) { + return function (node) { + return join([node.description, cb(node)], '\n'); + }; +} +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ + + +function join(maybeArray) { + var _maybeArray$filter$jo; + + var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(function (x) { + return x; + }).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : ''; +} +/** + * Given array, print each item on its own line, wrapped in an + * indented "{ }" block. + */ + + +function block(array) { + return wrap('{\n', indent(join(array, '\n')), '\n}'); +} +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. + */ + + +function wrap(start, maybeString) { + var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + return maybeString != null && maybeString !== '' ? start + maybeString + end : ''; +} + +function indent(str) { + return wrap(' ', str.replace(/\n/g, '\n ')); +} + +function isMultiline(str) { + return str.indexOf('\n') !== -1; +} + +function hasMultilineItems(maybeArray) { + return maybeArray != null && maybeArray.some(isMultiline); +} diff --git a/school/node_modules/graphql/language/printer.js.flow b/school/node_modules/graphql/language/printer.js.flow new file mode 100644 index 0000000..efaff6c --- /dev/null +++ b/school/node_modules/graphql/language/printer.js.flow @@ -0,0 +1,292 @@ +// @flow strict +import type { ASTNode } from './ast'; + +import { visit } from './visitor'; +import { printBlockString } from './blockString'; + +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ +export function print(ast: ASTNode): string { + return visit(ast, { leave: printDocASTReducer }); +} + +const MAX_LINE_LENGTH = 80; + +// TODO: provide better type coverage in future +const printDocASTReducer: any = { + Name: (node) => node.value, + Variable: (node) => '$' + node.name, + + // Document + + Document: (node) => join(node.definitions, '\n\n') + '\n', + + OperationDefinition(node) { + const op = node.operation; + const name = node.name; + const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + const directives = join(node.directives, ' '); + const selectionSet = node.selectionSet; + // Anonymous queries with no directives or variable definitions can use + // the query short form. + return !name && !directives && !varDefs && op === 'query' + ? selectionSet + : join([op, join([name, varDefs]), directives, selectionSet], ' '); + }, + + VariableDefinition: ({ variable, type, defaultValue, directives }) => + variable + + ': ' + + type + + wrap(' = ', defaultValue) + + wrap(' ', join(directives, ' ')), + SelectionSet: ({ selections }) => block(selections), + + Field: ({ alias, name, arguments: args, directives, selectionSet }) => { + const prefix = wrap('', alias, ': ') + name; + let argsLine = prefix + wrap('(', join(args, ', '), ')'); + + if (argsLine.length > MAX_LINE_LENGTH) { + argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)'); + } + + return join([argsLine, join(directives, ' '), selectionSet], ' '); + }, + + Argument: ({ name, value }) => name + ': ' + value, + + // Fragments + + FragmentSpread: ({ name, directives }) => + '...' + name + wrap(' ', join(directives, ' ')), + + InlineFragment: ({ typeCondition, directives, selectionSet }) => + join( + ['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], + ' ', + ), + + FragmentDefinition: ({ + name, + typeCondition, + variableDefinitions, + directives, + selectionSet, + }) => + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` + + `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` + + selectionSet, + + // Value + + IntValue: ({ value }) => value, + FloatValue: ({ value }) => value, + StringValue: ({ value, block: isBlockString }, key) => + isBlockString + ? printBlockString(value, key === 'description' ? '' : ' ') + : JSON.stringify(value), + BooleanValue: ({ value }) => (value ? 'true' : 'false'), + NullValue: () => 'null', + EnumValue: ({ value }) => value, + ListValue: ({ values }) => '[' + join(values, ', ') + ']', + ObjectValue: ({ fields }) => '{' + join(fields, ', ') + '}', + ObjectField: ({ name, value }) => name + ': ' + value, + + // Directive + + Directive: ({ name, arguments: args }) => + '@' + name + wrap('(', join(args, ', '), ')'), + + // Type + + NamedType: ({ name }) => name, + ListType: ({ type }) => '[' + type + ']', + NonNullType: ({ type }) => type + '!', + + // Type System Definitions + + SchemaDefinition: addDescription(({ directives, operationTypes }) => + join(['schema', join(directives, ' '), block(operationTypes)], ' '), + ), + + OperationTypeDefinition: ({ operation, type }) => operation + ': ' + type, + + ScalarTypeDefinition: addDescription(({ name, directives }) => + join(['scalar', name, join(directives, ' ')], ' '), + ), + + ObjectTypeDefinition: addDescription( + ({ name, interfaces, directives, fields }) => + join( + [ + 'type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + ), + + FieldDefinition: addDescription( + ({ name, arguments: args, type, directives }) => + name + + (hasMultilineItems(args) + ? wrap('(\n', indent(join(args, '\n')), '\n)') + : wrap('(', join(args, ', '), ')')) + + ': ' + + type + + wrap(' ', join(directives, ' ')), + ), + + InputValueDefinition: addDescription( + ({ name, type, defaultValue, directives }) => + join( + [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], + ' ', + ), + ), + + InterfaceTypeDefinition: addDescription( + ({ name, interfaces, directives, fields }) => + join( + [ + 'interface', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + ), + + UnionTypeDefinition: addDescription(({ name, directives, types }) => + join( + [ + 'union', + name, + join(directives, ' '), + types && types.length !== 0 ? '= ' + join(types, ' | ') : '', + ], + ' ', + ), + ), + + EnumTypeDefinition: addDescription(({ name, directives, values }) => + join(['enum', name, join(directives, ' '), block(values)], ' '), + ), + + EnumValueDefinition: addDescription(({ name, directives }) => + join([name, join(directives, ' ')], ' '), + ), + + InputObjectTypeDefinition: addDescription(({ name, directives, fields }) => + join(['input', name, join(directives, ' '), block(fields)], ' '), + ), + + DirectiveDefinition: addDescription( + ({ name, arguments: args, repeatable, locations }) => + 'directive @' + + name + + (hasMultilineItems(args) + ? wrap('(\n', indent(join(args, '\n')), '\n)') + : wrap('(', join(args, ', '), ')')) + + (repeatable ? ' repeatable' : '') + + ' on ' + + join(locations, ' | '), + ), + + SchemaExtension: ({ directives, operationTypes }) => + join(['extend schema', join(directives, ' '), block(operationTypes)], ' '), + + ScalarTypeExtension: ({ name, directives }) => + join(['extend scalar', name, join(directives, ' ')], ' '), + + ObjectTypeExtension: ({ name, interfaces, directives, fields }) => + join( + [ + 'extend type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + + InterfaceTypeExtension: ({ name, interfaces, directives, fields }) => + join( + [ + 'extend interface', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + + UnionTypeExtension: ({ name, directives, types }) => + join( + [ + 'extend union', + name, + join(directives, ' '), + types && types.length !== 0 ? '= ' + join(types, ' | ') : '', + ], + ' ', + ), + + EnumTypeExtension: ({ name, directives, values }) => + join(['extend enum', name, join(directives, ' '), block(values)], ' '), + + InputObjectTypeExtension: ({ name, directives, fields }) => + join(['extend input', name, join(directives, ' '), block(fields)], ' '), +}; + +function addDescription(cb) { + return (node) => join([node.description, cb(node)], '\n'); +} + +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ +function join(maybeArray: ?Array<string>, separator = ''): string { + return maybeArray?.filter((x) => x).join(separator) ?? ''; +} + +/** + * Given array, print each item on its own line, wrapped in an + * indented "{ }" block. + */ +function block(array: ?Array<string>): string { + return wrap('{\n', indent(join(array, '\n')), '\n}'); +} + +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. + */ +function wrap(start: string, maybeString: ?string, end: string = ''): string { + return maybeString != null && maybeString !== '' + ? start + maybeString + end + : ''; +} + +function indent(str: string): string { + return wrap(' ', str.replace(/\n/g, '\n ')); +} + +function isMultiline(str: string): boolean { + return str.indexOf('\n') !== -1; +} + +function hasMultilineItems(maybeArray: ?Array<string>): boolean { + return maybeArray != null && maybeArray.some(isMultiline); +} diff --git a/school/node_modules/graphql/language/printer.mjs b/school/node_modules/graphql/language/printer.mjs new file mode 100644 index 0000000..2435311 --- /dev/null +++ b/school/node_modules/graphql/language/printer.mjs @@ -0,0 +1,313 @@ +import { visit } from "./visitor.mjs"; +import { printBlockString } from "./blockString.mjs"; +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ + +export function print(ast) { + return visit(ast, { + leave: printDocASTReducer + }); +} +var MAX_LINE_LENGTH = 80; // TODO: provide better type coverage in future + +var printDocASTReducer = { + Name: function Name(node) { + return node.value; + }, + Variable: function Variable(node) { + return '$' + node.name; + }, + // Document + Document: function Document(node) { + return join(node.definitions, '\n\n') + '\n'; + }, + OperationDefinition: function OperationDefinition(node) { + var op = node.operation; + var name = node.name; + var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + var directives = join(node.directives, ' '); + var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' '); + }, + VariableDefinition: function VariableDefinition(_ref) { + var variable = _ref.variable, + type = _ref.type, + defaultValue = _ref.defaultValue, + directives = _ref.directives; + return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')); + }, + SelectionSet: function SelectionSet(_ref2) { + var selections = _ref2.selections; + return block(selections); + }, + Field: function Field(_ref3) { + var alias = _ref3.alias, + name = _ref3.name, + args = _ref3.arguments, + directives = _ref3.directives, + selectionSet = _ref3.selectionSet; + var prefix = wrap('', alias, ': ') + name; + var argsLine = prefix + wrap('(', join(args, ', '), ')'); + + if (argsLine.length > MAX_LINE_LENGTH) { + argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)'); + } + + return join([argsLine, join(directives, ' '), selectionSet], ' '); + }, + Argument: function Argument(_ref4) { + var name = _ref4.name, + value = _ref4.value; + return name + ': ' + value; + }, + // Fragments + FragmentSpread: function FragmentSpread(_ref5) { + var name = _ref5.name, + directives = _ref5.directives; + return '...' + name + wrap(' ', join(directives, ' ')); + }, + InlineFragment: function InlineFragment(_ref6) { + var typeCondition = _ref6.typeCondition, + directives = _ref6.directives, + selectionSet = _ref6.selectionSet; + return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' '); + }, + FragmentDefinition: function FragmentDefinition(_ref7) { + var name = _ref7.name, + typeCondition = _ref7.typeCondition, + variableDefinitions = _ref7.variableDefinitions, + directives = _ref7.directives, + selectionSet = _ref7.selectionSet; + return (// Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + "fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet + ); + }, + // Value + IntValue: function IntValue(_ref8) { + var value = _ref8.value; + return value; + }, + FloatValue: function FloatValue(_ref9) { + var value = _ref9.value; + return value; + }, + StringValue: function StringValue(_ref10, key) { + var value = _ref10.value, + isBlockString = _ref10.block; + return isBlockString ? printBlockString(value, key === 'description' ? '' : ' ') : JSON.stringify(value); + }, + BooleanValue: function BooleanValue(_ref11) { + var value = _ref11.value; + return value ? 'true' : 'false'; + }, + NullValue: function NullValue() { + return 'null'; + }, + EnumValue: function EnumValue(_ref12) { + var value = _ref12.value; + return value; + }, + ListValue: function ListValue(_ref13) { + var values = _ref13.values; + return '[' + join(values, ', ') + ']'; + }, + ObjectValue: function ObjectValue(_ref14) { + var fields = _ref14.fields; + return '{' + join(fields, ', ') + '}'; + }, + ObjectField: function ObjectField(_ref15) { + var name = _ref15.name, + value = _ref15.value; + return name + ': ' + value; + }, + // Directive + Directive: function Directive(_ref16) { + var name = _ref16.name, + args = _ref16.arguments; + return '@' + name + wrap('(', join(args, ', '), ')'); + }, + // Type + NamedType: function NamedType(_ref17) { + var name = _ref17.name; + return name; + }, + ListType: function ListType(_ref18) { + var type = _ref18.type; + return '[' + type + ']'; + }, + NonNullType: function NonNullType(_ref19) { + var type = _ref19.type; + return type + '!'; + }, + // Type System Definitions + SchemaDefinition: addDescription(function (_ref20) { + var directives = _ref20.directives, + operationTypes = _ref20.operationTypes; + return join(['schema', join(directives, ' '), block(operationTypes)], ' '); + }), + OperationTypeDefinition: function OperationTypeDefinition(_ref21) { + var operation = _ref21.operation, + type = _ref21.type; + return operation + ': ' + type; + }, + ScalarTypeDefinition: addDescription(function (_ref22) { + var name = _ref22.name, + directives = _ref22.directives; + return join(['scalar', name, join(directives, ' ')], ' '); + }), + ObjectTypeDefinition: addDescription(function (_ref23) { + var name = _ref23.name, + interfaces = _ref23.interfaces, + directives = _ref23.directives, + fields = _ref23.fields; + return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }), + FieldDefinition: addDescription(function (_ref24) { + var name = _ref24.name, + args = _ref24.arguments, + type = _ref24.type, + directives = _ref24.directives; + return name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' ')); + }), + InputValueDefinition: addDescription(function (_ref25) { + var name = _ref25.name, + type = _ref25.type, + defaultValue = _ref25.defaultValue, + directives = _ref25.directives; + return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' '); + }), + InterfaceTypeDefinition: addDescription(function (_ref26) { + var name = _ref26.name, + interfaces = _ref26.interfaces, + directives = _ref26.directives, + fields = _ref26.fields; + return join(['interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }), + UnionTypeDefinition: addDescription(function (_ref27) { + var name = _ref27.name, + directives = _ref27.directives, + types = _ref27.types; + return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }), + EnumTypeDefinition: addDescription(function (_ref28) { + var name = _ref28.name, + directives = _ref28.directives, + values = _ref28.values; + return join(['enum', name, join(directives, ' '), block(values)], ' '); + }), + EnumValueDefinition: addDescription(function (_ref29) { + var name = _ref29.name, + directives = _ref29.directives; + return join([name, join(directives, ' ')], ' '); + }), + InputObjectTypeDefinition: addDescription(function (_ref30) { + var name = _ref30.name, + directives = _ref30.directives, + fields = _ref30.fields; + return join(['input', name, join(directives, ' '), block(fields)], ' '); + }), + DirectiveDefinition: addDescription(function (_ref31) { + var name = _ref31.name, + args = _ref31.arguments, + repeatable = _ref31.repeatable, + locations = _ref31.locations; + return 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' on ' + join(locations, ' | '); + }), + SchemaExtension: function SchemaExtension(_ref32) { + var directives = _ref32.directives, + operationTypes = _ref32.operationTypes; + return join(['extend schema', join(directives, ' '), block(operationTypes)], ' '); + }, + ScalarTypeExtension: function ScalarTypeExtension(_ref33) { + var name = _ref33.name, + directives = _ref33.directives; + return join(['extend scalar', name, join(directives, ' ')], ' '); + }, + ObjectTypeExtension: function ObjectTypeExtension(_ref34) { + var name = _ref34.name, + interfaces = _ref34.interfaces, + directives = _ref34.directives, + fields = _ref34.fields; + return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }, + InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) { + var name = _ref35.name, + interfaces = _ref35.interfaces, + directives = _ref35.directives, + fields = _ref35.fields; + return join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }, + UnionTypeExtension: function UnionTypeExtension(_ref36) { + var name = _ref36.name, + directives = _ref36.directives, + types = _ref36.types; + return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }, + EnumTypeExtension: function EnumTypeExtension(_ref37) { + var name = _ref37.name, + directives = _ref37.directives, + values = _ref37.values; + return join(['extend enum', name, join(directives, ' '), block(values)], ' '); + }, + InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) { + var name = _ref38.name, + directives = _ref38.directives, + fields = _ref38.fields; + return join(['extend input', name, join(directives, ' '), block(fields)], ' '); + } +}; + +function addDescription(cb) { + return function (node) { + return join([node.description, cb(node)], '\n'); + }; +} +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ + + +function join(maybeArray) { + var _maybeArray$filter$jo; + + var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(function (x) { + return x; + }).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : ''; +} +/** + * Given array, print each item on its own line, wrapped in an + * indented "{ }" block. + */ + + +function block(array) { + return wrap('{\n', indent(join(array, '\n')), '\n}'); +} +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. + */ + + +function wrap(start, maybeString) { + var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + return maybeString != null && maybeString !== '' ? start + maybeString + end : ''; +} + +function indent(str) { + return wrap(' ', str.replace(/\n/g, '\n ')); +} + +function isMultiline(str) { + return str.indexOf('\n') !== -1; +} + +function hasMultilineItems(maybeArray) { + return maybeArray != null && maybeArray.some(isMultiline); +} diff --git a/school/node_modules/graphql/language/source.d.ts b/school/node_modules/graphql/language/source.d.ts new file mode 100644 index 0000000..a7df7cb --- /dev/null +++ b/school/node_modules/graphql/language/source.d.ts @@ -0,0 +1,25 @@ +interface Location { + line: number; + column: number; +} + +/** + * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are + * optional, but they are useful for clients who store GraphQL documents in source files. + * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might + * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. + * The `line` and `column` properties in `locationOffset` are 1-indexed. + */ +export class Source { + body: string; + name: string; + locationOffset: Location; + constructor(body: string, name?: string, locationOffset?: Location); +} + +/** + * Test if the given value is a Source object. + * + * @internal + */ +export function isSource(source: any): source is Source; diff --git a/school/node_modules/graphql/language/source.js b/school/node_modules/graphql/language/source.js new file mode 100644 index 0000000..7b19503 --- /dev/null +++ b/school/node_modules/graphql/language/source.js @@ -0,0 +1,67 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isSource = isSource; +exports.Source = void 0; + +var _symbols = require("../polyfills/symbols.js"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _devAssert = _interopRequireDefault(require("../jsutils/devAssert.js")); + +var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +/** + * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are + * optional, but they are useful for clients who store GraphQL documents in source files. + * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might + * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. + * The `line` and `column` properties in `locationOffset` are 1-indexed. + */ +var Source = /*#__PURE__*/function () { + function Source(body) { + var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GraphQL request'; + var locationOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + line: 1, + column: 1 + }; + typeof body === 'string' || (0, _devAssert.default)(0, "Body must be a string. Received: ".concat((0, _inspect.default)(body), ".")); + this.body = body; + this.name = name; + this.locationOffset = locationOffset; + this.locationOffset.line > 0 || (0, _devAssert.default)(0, 'line in locationOffset is 1-indexed and must be positive.'); + this.locationOffset.column > 0 || (0, _devAssert.default)(0, 'column in locationOffset is 1-indexed and must be positive.'); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + + + _createClass(Source, [{ + key: _symbols.SYMBOL_TO_STRING_TAG, + get: function get() { + return 'Source'; + } + }]); + + return Source; +}(); +/** + * Test if the given value is a Source object. + * + * @internal + */ + + +exports.Source = Source; + +// eslint-disable-next-line no-redeclare +function isSource(source) { + return (0, _instanceOf.default)(source, Source); +} diff --git a/school/node_modules/graphql/language/source.js.flow b/school/node_modules/graphql/language/source.js.flow new file mode 100644 index 0000000..270c85b --- /dev/null +++ b/school/node_modules/graphql/language/source.js.flow @@ -0,0 +1,64 @@ +// @flow strict +import { SYMBOL_TO_STRING_TAG } from '../polyfills/symbols'; + +import inspect from '../jsutils/inspect'; +import devAssert from '../jsutils/devAssert'; +import instanceOf from '../jsutils/instanceOf'; + +type Location = {| + line: number, + column: number, +|}; + +/** + * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are + * optional, but they are useful for clients who store GraphQL documents in source files. + * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might + * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. + * The `line` and `column` properties in `locationOffset` are 1-indexed. + */ +export class Source { + body: string; + name: string; + locationOffset: Location; + + constructor( + body: string, + name: string = 'GraphQL request', + locationOffset: Location = { line: 1, column: 1 }, + ) { + devAssert( + typeof body === 'string', + `Body must be a string. Received: ${inspect(body)}.`, + ); + + this.body = body; + this.name = name; + this.locationOffset = locationOffset; + devAssert( + this.locationOffset.line > 0, + 'line in locationOffset is 1-indexed and must be positive.', + ); + devAssert( + this.locationOffset.column > 0, + 'column in locationOffset is 1-indexed and must be positive.', + ); + } + + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + get [SYMBOL_TO_STRING_TAG]() { + return 'Source'; + } +} + +/** + * Test if the given value is a Source object. + * + * @internal + */ +declare function isSource(source: mixed): boolean %checks(source instanceof + Source); +// eslint-disable-next-line no-redeclare +export function isSource(source) { + return instanceOf(source, Source); +} diff --git a/school/node_modules/graphql/language/source.mjs b/school/node_modules/graphql/language/source.mjs new file mode 100644 index 0000000..e358f61 --- /dev/null +++ b/school/node_modules/graphql/language/source.mjs @@ -0,0 +1,51 @@ +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +import { SYMBOL_TO_STRING_TAG } from "../polyfills/symbols.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import devAssert from "../jsutils/devAssert.mjs"; +import instanceOf from "../jsutils/instanceOf.mjs"; + +/** + * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are + * optional, but they are useful for clients who store GraphQL documents in source files. + * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might + * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. + * The `line` and `column` properties in `locationOffset` are 1-indexed. + */ +export var Source = /*#__PURE__*/function () { + function Source(body) { + var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GraphQL request'; + var locationOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + line: 1, + column: 1 + }; + typeof body === 'string' || devAssert(0, "Body must be a string. Received: ".concat(inspect(body), ".")); + this.body = body; + this.name = name; + this.locationOffset = locationOffset; + this.locationOffset.line > 0 || devAssert(0, 'line in locationOffset is 1-indexed and must be positive.'); + this.locationOffset.column > 0 || devAssert(0, 'column in locationOffset is 1-indexed and must be positive.'); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + + + _createClass(Source, [{ + key: SYMBOL_TO_STRING_TAG, + get: function get() { + return 'Source'; + } + }]); + + return Source; +}(); +/** + * Test if the given value is a Source object. + * + * @internal + */ + +// eslint-disable-next-line no-redeclare +export function isSource(source) { + return instanceOf(source, Source); +} diff --git a/school/node_modules/graphql/language/tokenKind.d.ts b/school/node_modules/graphql/language/tokenKind.d.ts new file mode 100644 index 0000000..fa27e23 --- /dev/null +++ b/school/node_modules/graphql/language/tokenKind.d.ts @@ -0,0 +1,33 @@ +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +export const TokenKind: { + SOF: '<SOF>'; + EOF: '<EOF>'; + BANG: '!'; + DOLLAR: '$'; + AMP: '&'; + PAREN_L: '('; + PAREN_R: ')'; + SPREAD: '...'; + COLON: ':'; + EQUALS: '='; + AT: '@'; + BRACKET_L: '['; + BRACKET_R: ']'; + BRACE_L: '{'; + PIPE: '|'; + BRACE_R: '}'; + NAME: 'Name'; + INT: 'Int'; + FLOAT: 'Float'; + STRING: 'String'; + BLOCK_STRING: 'BlockString'; + COMMENT: 'Comment'; +}; + +/** + * The enum type representing the token kinds values. + */ +export type TokenKindEnum = typeof TokenKind[keyof typeof TokenKind]; diff --git a/school/node_modules/graphql/language/tokenKind.js b/school/node_modules/graphql/language/tokenKind.js new file mode 100644 index 0000000..3d5532d --- /dev/null +++ b/school/node_modules/graphql/language/tokenKind.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TokenKind = void 0; + +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +var TokenKind = Object.freeze({ + SOF: '<SOF>', + EOF: '<EOF>', + BANG: '!', + DOLLAR: '$', + AMP: '&', + PAREN_L: '(', + PAREN_R: ')', + SPREAD: '...', + COLON: ':', + EQUALS: '=', + AT: '@', + BRACKET_L: '[', + BRACKET_R: ']', + BRACE_L: '{', + PIPE: '|', + BRACE_R: '}', + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment' +}); +/** + * The enum type representing the token kinds values. + */ + +exports.TokenKind = TokenKind; diff --git a/school/node_modules/graphql/language/tokenKind.js.flow b/school/node_modules/graphql/language/tokenKind.js.flow new file mode 100644 index 0000000..70b3cfb --- /dev/null +++ b/school/node_modules/graphql/language/tokenKind.js.flow @@ -0,0 +1,34 @@ +// @flow strict +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +export const TokenKind = Object.freeze({ + SOF: '<SOF>', + EOF: '<EOF>', + BANG: '!', + DOLLAR: '$', + AMP: '&', + PAREN_L: '(', + PAREN_R: ')', + SPREAD: '...', + COLON: ':', + EQUALS: '=', + AT: '@', + BRACKET_L: '[', + BRACKET_R: ']', + BRACE_L: '{', + PIPE: '|', + BRACE_R: '}', + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment', +}); + +/** + * The enum type representing the token kinds values. + */ +export type TokenKindEnum = $Values<typeof TokenKind>; diff --git a/school/node_modules/graphql/language/tokenKind.mjs b/school/node_modules/graphql/language/tokenKind.mjs new file mode 100644 index 0000000..f100b99 --- /dev/null +++ b/school/node_modules/graphql/language/tokenKind.mjs @@ -0,0 +1,31 @@ +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +export var TokenKind = Object.freeze({ + SOF: '<SOF>', + EOF: '<EOF>', + BANG: '!', + DOLLAR: '$', + AMP: '&', + PAREN_L: '(', + PAREN_R: ')', + SPREAD: '...', + COLON: ':', + EQUALS: '=', + AT: '@', + BRACKET_L: '[', + BRACKET_R: ']', + BRACE_L: '{', + PIPE: '|', + BRACE_R: '}', + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment' +}); +/** + * The enum type representing the token kinds values. + */ diff --git a/school/node_modules/graphql/language/visitor.d.ts b/school/node_modules/graphql/language/visitor.d.ts new file mode 100644 index 0000000..ca0a81f --- /dev/null +++ b/school/node_modules/graphql/language/visitor.d.ts @@ -0,0 +1,272 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { ASTNode, ASTKindToNode } from './ast'; + +/** + * A visitor is provided to visit, it contains the collection of + * relevant functions to be called during the visitor's traversal. + */ +export type ASTVisitor = Visitor<ASTKindToNode>; +export type Visitor<KindToNode, Nodes = KindToNode[keyof KindToNode]> = + | EnterLeaveVisitor<KindToNode, Nodes> + | ShapeMapVisitor<KindToNode, Nodes>; + +interface EnterLeave<T> { + readonly enter?: T; + readonly leave?: T; +} + +type EnterLeaveVisitor<KindToNode, Nodes> = EnterLeave< + VisitFn<Nodes> | { [K in keyof KindToNode]?: VisitFn<Nodes, KindToNode[K]> } +>; + +type ShapeMapVisitor<KindToNode, Nodes> = { + [K in keyof KindToNode]?: + | VisitFn<Nodes, KindToNode[K]> + | EnterLeave<VisitFn<Nodes, KindToNode[K]>>; +}; + +/** + * A visitor is comprised of visit functions, which are called on each node + * during the visitor's traversal. + */ +export type VisitFn<TAnyNode, TVisitedNode = TAnyNode> = ( + /** The current node being visiting. */ + node: TVisitedNode, + /** The index or key to this node from the parent node or Array. */ + key: string | number | undefined, + /** The parent immediately above this node, which may be an Array. */ + parent: TAnyNode | ReadonlyArray<TAnyNode> | undefined, + /** The key path to get to this node from the root node. */ + path: ReadonlyArray<string | number>, + /** + * All nodes and Arrays visited before reaching parent of this node. + * These correspond to array indices in `path`. + * Note: ancestors includes arrays which contain the parent of visited node. + */ + ancestors: ReadonlyArray<TAnyNode | ReadonlyArray<TAnyNode>>, +) => any; + +/** + * A KeyMap describes each the traversable properties of each kind of node. + * + * @deprecated Please using ASTVisitorKeyMap instead + */ +export type VisitorKeyMap<T> = { [P in keyof T]: ReadonlyArray<keyof T[P]> }; + +/** + * A KeyMap describes each the traversable properties of each kind of node. + */ +export type ASTVisitorKeyMap = { + [P in keyof ASTKindToNode]?: ReadonlyArray<keyof ASTKindToNode[P]>; +}; + +// TODO: Should be `[]`, but that requires TypeScript@3 +type EmptyTuple = Array<never>; + +export const QueryDocumentKeys: { + Name: EmptyTuple; + + Document: ['definitions']; + // Prettier forces trailing commas, but TS pre 3.2 doesn't allow them. + // prettier-ignore + OperationDefinition: [ + 'name', + 'variableDefinitions', + 'directives', + 'selectionSet' + ]; + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives']; + Variable: ['name']; + SelectionSet: ['selections']; + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet']; + Argument: ['name', 'value']; + + FragmentSpread: ['name', 'directives']; + InlineFragment: ['typeCondition', 'directives', 'selectionSet']; + // prettier-ignore + FragmentDefinition: [ + 'name', + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + 'variableDefinitions', + 'typeCondition', + 'directives', + 'selectionSet' + ]; + + IntValue: EmptyTuple; + FloatValue: EmptyTuple; + StringValue: EmptyTuple; + BooleanValue: EmptyTuple; + NullValue: EmptyTuple; + EnumValue: EmptyTuple; + ListValue: ['values']; + ObjectValue: ['fields']; + ObjectField: ['name', 'value']; + + Directive: ['name', 'arguments']; + + NamedType: ['name']; + ListType: ['type']; + NonNullType: ['type']; + + SchemaDefinition: ['description', 'directives', 'operationTypes']; + OperationTypeDefinition: ['type']; + + ScalarTypeDefinition: ['description', 'name', 'directives']; + // prettier-ignore + ObjectTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields' + ]; + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives']; + // prettier-ignore + InputValueDefinition: [ + 'description', + 'name', + 'type', + 'defaultValue', + 'directives' + ]; + // prettier-ignore + InterfaceTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields' + ]; + UnionTypeDefinition: ['description', 'name', 'directives', 'types']; + EnumTypeDefinition: ['description', 'name', 'directives', 'values']; + EnumValueDefinition: ['description', 'name', 'directives']; + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields']; + + DirectiveDefinition: ['description', 'name', 'arguments', 'locations']; + + SchemaExtension: ['directives', 'operationTypes']; + + ScalarTypeExtension: ['name', 'directives']; + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields']; + InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields']; + UnionTypeExtension: ['name', 'directives', 'types']; + EnumTypeExtension: ['name', 'directives', 'values']; + InputObjectTypeExtension: ['name', 'directives', 'fields']; +}; + +export const BREAK: any; + +/** + * visit() will walk through an AST using a depth-first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to four permutations of the + * visitor API: + * + * 1) Named visitors triggered when entering a node of a specific kind. + * + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * + * 2) Named visitors that trigger upon entering and leaving a node of + * a specific kind. + * + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * + * 4) Parallel visitors for entering and leaving nodes of a specific kind. + * + * visit(ast, { + * enter: { + * Kind(node) { + * // enter the "Kind" node + * } + * }, + * leave: { + * Kind(node) { + * // leave the "Kind" node + * } + * } + * }) + */ +export function visit( + root: ASTNode, + visitor: Visitor<ASTKindToNode>, + visitorKeys?: VisitorKeyMap<ASTKindToNode>, // default: QueryDocumentKeys +): any; + +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ +export function visitInParallel( + visitors: ReadonlyArray<Visitor<ASTKindToNode>>, +): Visitor<ASTKindToNode>; + +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + */ +export function getVisitFn( + visitor: Visitor<any>, + kind: string, + isLeaving: boolean, +): Maybe<VisitFn<any>>; diff --git a/school/node_modules/graphql/language/visitor.js b/school/node_modules/graphql/language/visitor.js new file mode 100644 index 0000000..af31e83 --- /dev/null +++ b/school/node_modules/graphql/language/visitor.js @@ -0,0 +1,397 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.visit = visit; +exports.visitInParallel = visitInParallel; +exports.getVisitFn = getVisitFn; +exports.BREAK = exports.QueryDocumentKeys = void 0; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _ast = require("./ast.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var QueryDocumentKeys = { + Name: [], + Document: ['definitions'], + OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + Directive: ['name', 'arguments'], + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + SchemaDefinition: ['description', 'directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], + InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + SchemaExtension: ['directives', 'operationTypes'], + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'] +}; +exports.QueryDocumentKeys = QueryDocumentKeys; +var BREAK = Object.freeze({}); +/** + * visit() will walk through an AST using a depth-first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to four permutations of the + * visitor API: + * + * 1) Named visitors triggered when entering a node of a specific kind. + * + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * + * 2) Named visitors that trigger upon entering and leaving a node of + * a specific kind. + * + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * + * 4) Parallel visitors for entering and leaving nodes of a specific kind. + * + * visit(ast, { + * enter: { + * Kind(node) { + * // enter the "Kind" node + * } + * }, + * leave: { + * Kind(node) { + * // leave the "Kind" node + * } + * } + * }) + */ + +exports.BREAK = BREAK; + +function visit(root, visitor) { + var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys; + + /* eslint-disable no-undef-init */ + var stack = undefined; + var inArray = Array.isArray(root); + var keys = [root]; + var index = -1; + var edits = []; + var node = undefined; + var key = undefined; + var parent = undefined; + var path = []; + var ancestors = []; + var newRoot = root; + /* eslint-enable no-undef-init */ + + do { + index++; + var isLeaving = index === keys.length; + var isEdited = isLeaving && edits.length !== 0; + + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + + if (isEdited) { + if (inArray) { + node = node.slice(); + } else { + var clone = {}; + + for (var _i2 = 0, _Object$keys2 = Object.keys(node); _i2 < _Object$keys2.length; _i2++) { + var k = _Object$keys2[_i2]; + clone[k] = node[k]; + } + + node = clone; + } + + var editOffset = 0; + + for (var ii = 0; ii < edits.length; ii++) { + var editKey = edits[ii][0]; + var editValue = edits[ii][1]; + + if (inArray) { + editKey -= editOffset; + } + + if (inArray && editValue === null) { + node.splice(editKey, 1); + editOffset++; + } else { + node[editKey] = editValue; + } + } + } + + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else { + key = parent ? inArray ? index : keys[index] : undefined; + node = parent ? parent[key] : newRoot; + + if (node === null || node === undefined) { + continue; + } + + if (parent) { + path.push(key); + } + } + + var result = void 0; + + if (!Array.isArray(node)) { + if (!(0, _ast.isNode)(node)) { + throw new Error("Invalid AST Node: ".concat((0, _inspect.default)(node), ".")); + } + + var visitFn = getVisitFn(visitor, node.kind, isLeaving); + + if (visitFn) { + result = visitFn.call(visitor, node, key, parent, path, ancestors); + + if (result === BREAK) { + break; + } + + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + + if (!isLeaving) { + if ((0, _ast.isNode)(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + } + + if (result === undefined && isEdited) { + edits.push([key, node]); + } + + if (isLeaving) { + path.pop(); + } else { + var _visitorKeys$node$kin; + + stack = { + inArray: inArray, + index: index, + keys: keys, + edits: edits, + prev: stack + }; + inArray = Array.isArray(node); + keys = inArray ? node : (_visitorKeys$node$kin = visitorKeys[node.kind]) !== null && _visitorKeys$node$kin !== void 0 ? _visitorKeys$node$kin : []; + index = -1; + edits = []; + + if (parent) { + ancestors.push(parent); + } + + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + newRoot = edits[edits.length - 1][1]; + } + + return newRoot; +} +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ + + +function visitInParallel(visitors) { + var skipping = new Array(visitors.length); + return { + enter: function enter(node) { + for (var i = 0; i < visitors.length; i++) { + if (skipping[i] == null) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + } + }, + leave: function leave(node) { + for (var i = 0; i < visitors.length; i++) { + if (skipping[i] == null) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + true); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + } + }; +} +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + */ + + +function getVisitFn(visitor, kind, isLeaving) { + var kindVisitor = visitor[kind]; + + if (kindVisitor) { + if (!isLeaving && typeof kindVisitor === 'function') { + // { Kind() {} } + return kindVisitor; + } + + var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter; + + if (typeof kindSpecificVisitor === 'function') { + // { Kind: { enter() {}, leave() {} } } + return kindSpecificVisitor; + } + } else { + var specificVisitor = isLeaving ? visitor.leave : visitor.enter; + + if (specificVisitor) { + if (typeof specificVisitor === 'function') { + // { enter() {}, leave() {} } + return specificVisitor; + } + + var specificKindVisitor = specificVisitor[kind]; + + if (typeof specificKindVisitor === 'function') { + // { enter: { Kind() {} }, leave: { Kind() {} } } + return specificKindVisitor; + } + } + } +} diff --git a/school/node_modules/graphql/language/visitor.js.flow b/school/node_modules/graphql/language/visitor.js.flow new file mode 100644 index 0000000..b53d476 --- /dev/null +++ b/school/node_modules/graphql/language/visitor.js.flow @@ -0,0 +1,437 @@ +// @flow strict +import inspect from '../jsutils/inspect'; + +import type { ASTNode, ASTKindToNode } from './ast'; +import { isNode } from './ast'; + +/** + * A visitor is provided to visit, it contains the collection of + * relevant functions to be called during the visitor's traversal. + */ +export type ASTVisitor = Visitor<ASTKindToNode>; +export type Visitor<KindToNode, Nodes = $Values<KindToNode>> = + | EnterLeave< + | VisitFn<Nodes> + | ShapeMap<KindToNode, <Node>(Node) => VisitFn<Nodes, Node>>, + > + | ShapeMap< + KindToNode, + <Node>(Node) => VisitFn<Nodes, Node> | EnterLeave<VisitFn<Nodes, Node>>, + >; +type EnterLeave<T> = {| +enter?: T, +leave?: T |}; +type ShapeMap<O, F> = $Shape<$ObjMap<O, F>>; + +/** + * A visitor is comprised of visit functions, which are called on each node + * during the visitor's traversal. + */ +export type VisitFn<TAnyNode, TVisitedNode: TAnyNode = TAnyNode> = ( + // The current node being visiting. + node: TVisitedNode, + // The index or key to this node from the parent node or Array. + key: string | number | void, + // The parent immediately above this node, which may be an Array. + parent: TAnyNode | $ReadOnlyArray<TAnyNode> | void, + // The key path to get to this node from the root node. + path: $ReadOnlyArray<string | number>, + // All nodes and Arrays visited before reaching parent of this node. + // These correspond to array indices in `path`. + // Note: ancestors includes arrays which contain the parent of visited node. + ancestors: $ReadOnlyArray<TAnyNode | $ReadOnlyArray<TAnyNode>>, +) => any; + +/** + * A KeyMap describes each the traversable properties of each kind of node. + */ +export type VisitorKeyMap<KindToNode> = $ObjMap< + KindToNode, + <T>(T) => $ReadOnlyArray<$Keys<T>>, +>; + +export const QueryDocumentKeys: VisitorKeyMap<ASTKindToNode> = { + Name: [], + + Document: ['definitions'], + OperationDefinition: [ + 'name', + 'variableDefinitions', + 'directives', + 'selectionSet', + ], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: [ + 'name', + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + 'variableDefinitions', + 'typeCondition', + 'directives', + 'selectionSet', + ], + + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + + Directive: ['name', 'arguments'], + + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + + SchemaDefinition: ['description', 'directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields', + ], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: [ + 'description', + 'name', + 'type', + 'defaultValue', + 'directives', + ], + InterfaceTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields', + ], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + + SchemaExtension: ['directives', 'operationTypes'], + + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'], +}; + +export const BREAK: { ... } = Object.freeze({}); + +/** + * visit() will walk through an AST using a depth-first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to four permutations of the + * visitor API: + * + * 1) Named visitors triggered when entering a node of a specific kind. + * + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * + * 2) Named visitors that trigger upon entering and leaving a node of + * a specific kind. + * + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * + * 4) Parallel visitors for entering and leaving nodes of a specific kind. + * + * visit(ast, { + * enter: { + * Kind(node) { + * // enter the "Kind" node + * } + * }, + * leave: { + * Kind(node) { + * // leave the "Kind" node + * } + * } + * }) + */ +export function visit( + root: ASTNode, + visitor: Visitor<ASTKindToNode>, + visitorKeys: VisitorKeyMap<ASTKindToNode> = QueryDocumentKeys, +): any { + /* eslint-disable no-undef-init */ + let stack: any = undefined; + let inArray = Array.isArray(root); + let keys: any = [root]; + let index = -1; + let edits = []; + let node: any = undefined; + let key: any = undefined; + let parent: any = undefined; + const path: any = []; + const ancestors = []; + let newRoot = root; + /* eslint-enable no-undef-init */ + + do { + index++; + const isLeaving = index === keys.length; + const isEdited = isLeaving && edits.length !== 0; + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + if (isEdited) { + if (inArray) { + node = node.slice(); + } else { + const clone = {}; + for (const k of Object.keys(node)) { + clone[k] = node[k]; + } + node = clone; + } + let editOffset = 0; + for (let ii = 0; ii < edits.length; ii++) { + let editKey: any = edits[ii][0]; + const editValue = edits[ii][1]; + if (inArray) { + editKey -= editOffset; + } + if (inArray && editValue === null) { + node.splice(editKey, 1); + editOffset++; + } else { + node[editKey] = editValue; + } + } + } + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else { + key = parent ? (inArray ? index : keys[index]) : undefined; + node = parent ? parent[key] : newRoot; + if (node === null || node === undefined) { + continue; + } + if (parent) { + path.push(key); + } + } + + let result; + if (!Array.isArray(node)) { + if (!isNode(node)) { + throw new Error(`Invalid AST Node: ${inspect(node)}.`); + } + const visitFn = getVisitFn(visitor, node.kind, isLeaving); + if (visitFn) { + result = visitFn.call(visitor, node, key, parent, path, ancestors); + + if (result === BREAK) { + break; + } + + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + if (!isLeaving) { + if (isNode(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + } + + if (result === undefined && isEdited) { + edits.push([key, node]); + } + + if (isLeaving) { + path.pop(); + } else { + stack = { inArray, index, keys, edits, prev: stack }; + inArray = Array.isArray(node); + keys = inArray ? node : visitorKeys[node.kind] ?? []; + index = -1; + edits = []; + if (parent) { + ancestors.push(parent); + } + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + newRoot = edits[edits.length - 1][1]; + } + + return newRoot; +} + +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ +export function visitInParallel( + visitors: $ReadOnlyArray<Visitor<ASTKindToNode>>, +): Visitor<ASTKindToNode> { + const skipping = new Array(visitors.length); + + return { + enter(node) { + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] == null) { + const fn = getVisitFn(visitors[i], node.kind, /* isLeaving */ false); + if (fn) { + const result = fn.apply(visitors[i], arguments); + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + } + }, + leave(node) { + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] == null) { + const fn = getVisitFn(visitors[i], node.kind, /* isLeaving */ true); + if (fn) { + const result = fn.apply(visitors[i], arguments); + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + }, + }; +} + +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + */ +export function getVisitFn( + visitor: Visitor<any>, + kind: string, + isLeaving: boolean, +): ?VisitFn<any> { + const kindVisitor = visitor[kind]; + if (kindVisitor) { + if (!isLeaving && typeof kindVisitor === 'function') { + // { Kind() {} } + return kindVisitor; + } + const kindSpecificVisitor = isLeaving + ? kindVisitor.leave + : kindVisitor.enter; + if (typeof kindSpecificVisitor === 'function') { + // { Kind: { enter() {}, leave() {} } } + return kindSpecificVisitor; + } + } else { + const specificVisitor = isLeaving ? visitor.leave : visitor.enter; + if (specificVisitor) { + if (typeof specificVisitor === 'function') { + // { enter() {}, leave() {} } + return specificVisitor; + } + const specificKindVisitor = specificVisitor[kind]; + if (typeof specificKindVisitor === 'function') { + // { enter: { Kind() {} }, leave: { Kind() {} } } + return specificKindVisitor; + } + } + } +} diff --git a/school/node_modules/graphql/language/visitor.mjs b/school/node_modules/graphql/language/visitor.mjs new file mode 100644 index 0000000..776e0cc --- /dev/null +++ b/school/node_modules/graphql/language/visitor.mjs @@ -0,0 +1,383 @@ +import inspect from "../jsutils/inspect.mjs"; +import { isNode } from "./ast.mjs"; +/** + * A visitor is provided to visit, it contains the collection of + * relevant functions to be called during the visitor's traversal. + */ + +export var QueryDocumentKeys = { + Name: [], + Document: ['definitions'], + OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + Directive: ['name', 'arguments'], + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + SchemaDefinition: ['description', 'directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], + InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + SchemaExtension: ['directives', 'operationTypes'], + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'] +}; +export var BREAK = Object.freeze({}); +/** + * visit() will walk through an AST using a depth-first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to four permutations of the + * visitor API: + * + * 1) Named visitors triggered when entering a node of a specific kind. + * + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * + * 2) Named visitors that trigger upon entering and leaving a node of + * a specific kind. + * + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * + * 4) Parallel visitors for entering and leaving nodes of a specific kind. + * + * visit(ast, { + * enter: { + * Kind(node) { + * // enter the "Kind" node + * } + * }, + * leave: { + * Kind(node) { + * // leave the "Kind" node + * } + * } + * }) + */ + +export function visit(root, visitor) { + var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys; + + /* eslint-disable no-undef-init */ + var stack = undefined; + var inArray = Array.isArray(root); + var keys = [root]; + var index = -1; + var edits = []; + var node = undefined; + var key = undefined; + var parent = undefined; + var path = []; + var ancestors = []; + var newRoot = root; + /* eslint-enable no-undef-init */ + + do { + index++; + var isLeaving = index === keys.length; + var isEdited = isLeaving && edits.length !== 0; + + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + + if (isEdited) { + if (inArray) { + node = node.slice(); + } else { + var clone = {}; + + for (var _i2 = 0, _Object$keys2 = Object.keys(node); _i2 < _Object$keys2.length; _i2++) { + var k = _Object$keys2[_i2]; + clone[k] = node[k]; + } + + node = clone; + } + + var editOffset = 0; + + for (var ii = 0; ii < edits.length; ii++) { + var editKey = edits[ii][0]; + var editValue = edits[ii][1]; + + if (inArray) { + editKey -= editOffset; + } + + if (inArray && editValue === null) { + node.splice(editKey, 1); + editOffset++; + } else { + node[editKey] = editValue; + } + } + } + + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else { + key = parent ? inArray ? index : keys[index] : undefined; + node = parent ? parent[key] : newRoot; + + if (node === null || node === undefined) { + continue; + } + + if (parent) { + path.push(key); + } + } + + var result = void 0; + + if (!Array.isArray(node)) { + if (!isNode(node)) { + throw new Error("Invalid AST Node: ".concat(inspect(node), ".")); + } + + var visitFn = getVisitFn(visitor, node.kind, isLeaving); + + if (visitFn) { + result = visitFn.call(visitor, node, key, parent, path, ancestors); + + if (result === BREAK) { + break; + } + + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + + if (!isLeaving) { + if (isNode(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + } + + if (result === undefined && isEdited) { + edits.push([key, node]); + } + + if (isLeaving) { + path.pop(); + } else { + var _visitorKeys$node$kin; + + stack = { + inArray: inArray, + index: index, + keys: keys, + edits: edits, + prev: stack + }; + inArray = Array.isArray(node); + keys = inArray ? node : (_visitorKeys$node$kin = visitorKeys[node.kind]) !== null && _visitorKeys$node$kin !== void 0 ? _visitorKeys$node$kin : []; + index = -1; + edits = []; + + if (parent) { + ancestors.push(parent); + } + + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + newRoot = edits[edits.length - 1][1]; + } + + return newRoot; +} +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ + +export function visitInParallel(visitors) { + var skipping = new Array(visitors.length); + return { + enter: function enter(node) { + for (var i = 0; i < visitors.length; i++) { + if (skipping[i] == null) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + } + }, + leave: function leave(node) { + for (var i = 0; i < visitors.length; i++) { + if (skipping[i] == null) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + true); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + } + }; +} +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + */ + +export function getVisitFn(visitor, kind, isLeaving) { + var kindVisitor = visitor[kind]; + + if (kindVisitor) { + if (!isLeaving && typeof kindVisitor === 'function') { + // { Kind() {} } + return kindVisitor; + } + + var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter; + + if (typeof kindSpecificVisitor === 'function') { + // { Kind: { enter() {}, leave() {} } } + return kindSpecificVisitor; + } + } else { + var specificVisitor = isLeaving ? visitor.leave : visitor.enter; + + if (specificVisitor) { + if (typeof specificVisitor === 'function') { + // { enter() {}, leave() {} } + return specificVisitor; + } + + var specificKindVisitor = specificVisitor[kind]; + + if (typeof specificKindVisitor === 'function') { + // { enter: { Kind() {} }, leave: { Kind() {} } } + return specificKindVisitor; + } + } + } +} diff --git a/school/node_modules/graphql/package.json b/school/node_modules/graphql/package.json new file mode 100644 index 0000000..d813820 --- /dev/null +++ b/school/node_modules/graphql/package.json @@ -0,0 +1,28 @@ +{ + "name": "graphql", + "version": "15.8.0", + "description": "A Query Language and Runtime which can target any service.", + "license": "MIT", + "main": "index", + "module": "index.mjs", + "types": "index.d.ts", + "sideEffects": false, + "homepage": "https://github.com/graphql/graphql-js", + "bugs": { + "url": "https://github.com/graphql/graphql-js/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/graphql/graphql-js.git" + }, + "keywords": [ + "graphql", + "graphql-js" + ], + "engines": { + "node": ">= 10.x" + }, + "publishConfig": { + "tag": "15.x.x" + } +}
\ No newline at end of file diff --git a/school/node_modules/graphql/polyfills/arrayFrom.js b/school/node_modules/graphql/polyfills/arrayFrom.js new file mode 100644 index 0000000..0f2eab2 --- /dev/null +++ b/school/node_modules/graphql/polyfills/arrayFrom.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _symbols = require("./symbols.js"); + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] +var arrayFrom = Array.from || function (obj, mapFn, thisArg) { + if (obj == null) { + throw new TypeError('Array.from requires an array-like object - not null or undefined'); + } // Is Iterable? + + + var iteratorMethod = obj[_symbols.SYMBOL_ITERATOR]; + + if (typeof iteratorMethod === 'function') { + var iterator = iteratorMethod.call(obj); + var result = []; + var step; + + for (var i = 0; !(step = iterator.next()).done; ++i) { + result.push(mapFn.call(thisArg, step.value, i)); // Infinite Iterators could cause forEach to run forever. + // After a very large number of iterations, produce an error. + // istanbul ignore if (Too big to actually test) + + if (i > 9999999) { + throw new TypeError('Near-infinite iteration.'); + } + } + + return result; + } // Is Array like? + + + var length = obj.length; + + if (typeof length === 'number' && length >= 0 && length % 1 === 0) { + var _result = []; + + for (var _i = 0; _i < length; ++_i) { + if (Object.prototype.hasOwnProperty.call(obj, _i)) { + _result.push(mapFn.call(thisArg, obj[_i], _i)); + } + } + + return _result; + } + + return []; +}; + +var _default = arrayFrom; +exports.default = _default; diff --git a/school/node_modules/graphql/polyfills/arrayFrom.js.flow b/school/node_modules/graphql/polyfills/arrayFrom.js.flow new file mode 100644 index 0000000..73093b7 --- /dev/null +++ b/school/node_modules/graphql/polyfills/arrayFrom.js.flow @@ -0,0 +1,58 @@ +// @flow strict +import { SYMBOL_ITERATOR } from './symbols'; + +declare function arrayFrom<T>(arrayLike: Iterable<T>): Array<T>; +// eslint-disable-next-line no-redeclare +declare function arrayFrom<T: mixed>( + arrayLike: mixed, + mapFn?: (elem: mixed, index: number) => T, + thisArg?: mixed, +): Array<T>; + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] +const arrayFrom = + Array.from || + function (obj, mapFn, thisArg) { + if (obj == null) { + throw new TypeError( + 'Array.from requires an array-like object - not null or undefined', + ); + } + + // Is Iterable? + const iteratorMethod = obj[SYMBOL_ITERATOR]; + if (typeof iteratorMethod === 'function') { + const iterator = iteratorMethod.call(obj); + const result = []; + let step; + + for (let i = 0; !(step = iterator.next()).done; ++i) { + result.push(mapFn.call(thisArg, step.value, i)); + // Infinite Iterators could cause forEach to run forever. + // After a very large number of iterations, produce an error. + // istanbul ignore if (Too big to actually test) + if (i > 9999999) { + throw new TypeError('Near-infinite iteration.'); + } + } + return result; + } + + // Is Array like? + const length = obj.length; + if (typeof length === 'number' && length >= 0 && length % 1 === 0) { + const result = []; + + for (let i = 0; i < length; ++i) { + if (Object.prototype.hasOwnProperty.call(obj, i)) { + result.push(mapFn.call(thisArg, obj[i], i)); + } + } + return result; + } + + return []; + }; + +export default arrayFrom; diff --git a/school/node_modules/graphql/polyfills/arrayFrom.mjs b/school/node_modules/graphql/polyfills/arrayFrom.mjs new file mode 100644 index 0000000..1ea59f0 --- /dev/null +++ b/school/node_modules/graphql/polyfills/arrayFrom.mjs @@ -0,0 +1,49 @@ +import { SYMBOL_ITERATOR } from "./symbols.mjs"; + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] +var arrayFrom = Array.from || function (obj, mapFn, thisArg) { + if (obj == null) { + throw new TypeError('Array.from requires an array-like object - not null or undefined'); + } // Is Iterable? + + + var iteratorMethod = obj[SYMBOL_ITERATOR]; + + if (typeof iteratorMethod === 'function') { + var iterator = iteratorMethod.call(obj); + var result = []; + var step; + + for (var i = 0; !(step = iterator.next()).done; ++i) { + result.push(mapFn.call(thisArg, step.value, i)); // Infinite Iterators could cause forEach to run forever. + // After a very large number of iterations, produce an error. + // istanbul ignore if (Too big to actually test) + + if (i > 9999999) { + throw new TypeError('Near-infinite iteration.'); + } + } + + return result; + } // Is Array like? + + + var length = obj.length; + + if (typeof length === 'number' && length >= 0 && length % 1 === 0) { + var _result = []; + + for (var _i = 0; _i < length; ++_i) { + if (Object.prototype.hasOwnProperty.call(obj, _i)) { + _result.push(mapFn.call(thisArg, obj[_i], _i)); + } + } + + return _result; + } + + return []; +}; + +export default arrayFrom; diff --git a/school/node_modules/graphql/polyfills/find.js b/school/node_modules/graphql/polyfills/find.js new file mode 100644 index 0000000..fb14137 --- /dev/null +++ b/school/node_modules/graphql/polyfills/find.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] +var find = Array.prototype.find ? function (list, predicate) { + return Array.prototype.find.call(list, predicate); +} : function (list, predicate) { + for (var _i2 = 0; _i2 < list.length; _i2++) { + var value = list[_i2]; + + if (predicate(value)) { + return value; + } + } +}; +var _default = find; +exports.default = _default; diff --git a/school/node_modules/graphql/polyfills/find.js.flow b/school/node_modules/graphql/polyfills/find.js.flow new file mode 100644 index 0000000..4ed151c --- /dev/null +++ b/school/node_modules/graphql/polyfills/find.js.flow @@ -0,0 +1,20 @@ +// @flow strict +declare function find<T>( + list: $ReadOnlyArray<T>, + predicate: (item: T) => boolean, +): T | void; + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] +const find = Array.prototype.find + ? function (list, predicate) { + return Array.prototype.find.call(list, predicate); + } + : function (list, predicate) { + for (const value of list) { + if (predicate(value)) { + return value; + } + } + }; +export default find; diff --git a/school/node_modules/graphql/polyfills/find.mjs b/school/node_modules/graphql/polyfills/find.mjs new file mode 100644 index 0000000..ed3e6f3 --- /dev/null +++ b/school/node_modules/graphql/polyfills/find.mjs @@ -0,0 +1,14 @@ +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] +var find = Array.prototype.find ? function (list, predicate) { + return Array.prototype.find.call(list, predicate); +} : function (list, predicate) { + for (var _i2 = 0; _i2 < list.length; _i2++) { + var value = list[_i2]; + + if (predicate(value)) { + return value; + } + } +}; +export default find; diff --git a/school/node_modules/graphql/polyfills/isFinite.js b/school/node_modules/graphql/polyfills/isFinite.js new file mode 100644 index 0000000..9c0e559 --- /dev/null +++ b/school/node_modules/graphql/polyfills/isFinite.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +var isFinitePolyfill = Number.isFinite || function (value) { + return typeof value === 'number' && isFinite(value); +}; + +var _default = isFinitePolyfill; +exports.default = _default; diff --git a/school/node_modules/graphql/polyfills/isFinite.js.flow b/school/node_modules/graphql/polyfills/isFinite.js.flow new file mode 100644 index 0000000..5dd0229 --- /dev/null +++ b/school/node_modules/graphql/polyfills/isFinite.js.flow @@ -0,0 +1,13 @@ +// @flow strict +declare function isFinitePolyfill( + value: mixed, +): boolean %checks(typeof value === 'number'); + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +const isFinitePolyfill = + Number.isFinite || + function (value) { + return typeof value === 'number' && isFinite(value); + }; +export default isFinitePolyfill; diff --git a/school/node_modules/graphql/polyfills/isFinite.mjs b/school/node_modules/graphql/polyfills/isFinite.mjs new file mode 100644 index 0000000..7c1aea6 --- /dev/null +++ b/school/node_modules/graphql/polyfills/isFinite.mjs @@ -0,0 +1,7 @@ +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +var isFinitePolyfill = Number.isFinite || function (value) { + return typeof value === 'number' && isFinite(value); +}; + +export default isFinitePolyfill; diff --git a/school/node_modules/graphql/polyfills/isInteger.js b/school/node_modules/graphql/polyfills/isInteger.js new file mode 100644 index 0000000..9b25361 --- /dev/null +++ b/school/node_modules/graphql/polyfills/isInteger.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +var isInteger = Number.isInteger || function (value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; +}; + +var _default = isInteger; +exports.default = _default; diff --git a/school/node_modules/graphql/polyfills/isInteger.js.flow b/school/node_modules/graphql/polyfills/isInteger.js.flow new file mode 100644 index 0000000..757da92 --- /dev/null +++ b/school/node_modules/graphql/polyfills/isInteger.js.flow @@ -0,0 +1,16 @@ +// @flow strict +declare function isInteger(value: mixed): boolean %checks(typeof value === + 'number'); + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +const isInteger = + Number.isInteger || + function (value) { + return ( + typeof value === 'number' && + isFinite(value) && + Math.floor(value) === value + ); + }; +export default isInteger; diff --git a/school/node_modules/graphql/polyfills/isInteger.mjs b/school/node_modules/graphql/polyfills/isInteger.mjs new file mode 100644 index 0000000..3396f16 --- /dev/null +++ b/school/node_modules/graphql/polyfills/isInteger.mjs @@ -0,0 +1,7 @@ +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +var isInteger = Number.isInteger || function (value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; +}; + +export default isInteger; diff --git a/school/node_modules/graphql/polyfills/objectEntries.js b/school/node_modules/graphql/polyfills/objectEntries.js new file mode 100644 index 0000000..749d4ef --- /dev/null +++ b/school/node_modules/graphql/polyfills/objectEntries.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +var objectEntries = Object.entries || function (obj) { + return Object.keys(obj).map(function (key) { + return [key, obj[key]]; + }); +}; + +var _default = objectEntries; +exports.default = _default; diff --git a/school/node_modules/graphql/polyfills/objectEntries.js.flow b/school/node_modules/graphql/polyfills/objectEntries.js.flow new file mode 100644 index 0000000..d30e3c1 --- /dev/null +++ b/school/node_modules/graphql/polyfills/objectEntries.js.flow @@ -0,0 +1,11 @@ +// @flow strict +import type { ObjMap } from '../jsutils/ObjMap'; + +declare function objectEntries<T>(obj: ObjMap<T>): Array<[string, T]>; + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +const objectEntries = + Object.entries || ((obj) => Object.keys(obj).map((key) => [key, obj[key]])); + +export default objectEntries; diff --git a/school/node_modules/graphql/polyfills/objectEntries.mjs b/school/node_modules/graphql/polyfills/objectEntries.mjs new file mode 100644 index 0000000..72d0c60 --- /dev/null +++ b/school/node_modules/graphql/polyfills/objectEntries.mjs @@ -0,0 +1,9 @@ +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +var objectEntries = Object.entries || function (obj) { + return Object.keys(obj).map(function (key) { + return [key, obj[key]]; + }); +}; + +export default objectEntries; diff --git a/school/node_modules/graphql/polyfills/objectValues.js b/school/node_modules/graphql/polyfills/objectValues.js new file mode 100644 index 0000000..ab14e65 --- /dev/null +++ b/school/node_modules/graphql/polyfills/objectValues.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +var objectValues = Object.values || function (obj) { + return Object.keys(obj).map(function (key) { + return obj[key]; + }); +}; + +var _default = objectValues; +exports.default = _default; diff --git a/school/node_modules/graphql/polyfills/objectValues.js.flow b/school/node_modules/graphql/polyfills/objectValues.js.flow new file mode 100644 index 0000000..343419a --- /dev/null +++ b/school/node_modules/graphql/polyfills/objectValues.js.flow @@ -0,0 +1,10 @@ +// @flow strict +import type { ObjMap } from '../jsutils/ObjMap'; + +declare function objectValues<T>(obj: ObjMap<T>): Array<T>; + +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +const objectValues = + Object.values || ((obj) => Object.keys(obj).map((key) => obj[key])); +export default objectValues; diff --git a/school/node_modules/graphql/polyfills/objectValues.mjs b/school/node_modules/graphql/polyfills/objectValues.mjs new file mode 100644 index 0000000..afbde06 --- /dev/null +++ b/school/node_modules/graphql/polyfills/objectValues.mjs @@ -0,0 +1,9 @@ +/* eslint-disable no-redeclare */ +// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441 +var objectValues = Object.values || function (obj) { + return Object.keys(obj).map(function (key) { + return obj[key]; + }); +}; + +export default objectValues; diff --git a/school/node_modules/graphql/polyfills/symbols.js b/school/node_modules/graphql/polyfills/symbols.js new file mode 100644 index 0000000..3d4ba2e --- /dev/null +++ b/school/node_modules/graphql/polyfills/symbols.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SYMBOL_TO_STRING_TAG = exports.SYMBOL_ASYNC_ITERATOR = exports.SYMBOL_ITERATOR = void 0; +// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator +// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') +var SYMBOL_ITERATOR = typeof Symbol === 'function' && Symbol.iterator != null ? Symbol.iterator : '@@iterator'; // In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator +// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') + +exports.SYMBOL_ITERATOR = SYMBOL_ITERATOR; +var SYMBOL_ASYNC_ITERATOR = typeof Symbol === 'function' && Symbol.asyncIterator != null ? Symbol.asyncIterator : '@@asyncIterator'; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') + +exports.SYMBOL_ASYNC_ITERATOR = SYMBOL_ASYNC_ITERATOR; +var SYMBOL_TO_STRING_TAG = typeof Symbol === 'function' && Symbol.toStringTag != null ? Symbol.toStringTag : '@@toStringTag'; +exports.SYMBOL_TO_STRING_TAG = SYMBOL_TO_STRING_TAG; diff --git a/school/node_modules/graphql/polyfills/symbols.js.flow b/school/node_modules/graphql/polyfills/symbols.js.flow new file mode 100644 index 0000000..66a1b2c --- /dev/null +++ b/school/node_modules/graphql/polyfills/symbols.js.flow @@ -0,0 +1,20 @@ +// @flow strict +// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator +// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') +export const SYMBOL_ITERATOR: string = + typeof Symbol === 'function' && Symbol.iterator != null + ? Symbol.iterator + : '@@iterator'; + +// In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator +// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') +export const SYMBOL_ASYNC_ITERATOR: string = + typeof Symbol === 'function' && Symbol.asyncIterator != null + ? Symbol.asyncIterator + : '@@asyncIterator'; + +// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') +export const SYMBOL_TO_STRING_TAG: string = + typeof Symbol === 'function' && Symbol.toStringTag != null + ? Symbol.toStringTag + : '@@toStringTag'; diff --git a/school/node_modules/graphql/polyfills/symbols.mjs b/school/node_modules/graphql/polyfills/symbols.mjs new file mode 100644 index 0000000..b338851 --- /dev/null +++ b/school/node_modules/graphql/polyfills/symbols.mjs @@ -0,0 +1,8 @@ +// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator +// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') +export var SYMBOL_ITERATOR = typeof Symbol === 'function' && Symbol.iterator != null ? Symbol.iterator : '@@iterator'; // In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator +// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') + +export var SYMBOL_ASYNC_ITERATOR = typeof Symbol === 'function' && Symbol.asyncIterator != null ? Symbol.asyncIterator : '@@asyncIterator'; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') + +export var SYMBOL_TO_STRING_TAG = typeof Symbol === 'function' && Symbol.toStringTag != null ? Symbol.toStringTag : '@@toStringTag'; diff --git a/school/node_modules/graphql/subscription/index.d.ts b/school/node_modules/graphql/subscription/index.d.ts new file mode 100644 index 0000000..ba8835f --- /dev/null +++ b/school/node_modules/graphql/subscription/index.d.ts @@ -0,0 +1,5 @@ +export { + subscribe, + createSourceEventStream, + SubscriptionArgs, +} from './subscribe'; diff --git a/school/node_modules/graphql/subscription/index.js b/school/node_modules/graphql/subscription/index.js new file mode 100644 index 0000000..845d944 --- /dev/null +++ b/school/node_modules/graphql/subscription/index.js @@ -0,0 +1,19 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "subscribe", { + enumerable: true, + get: function get() { + return _subscribe.subscribe; + } +}); +Object.defineProperty(exports, "createSourceEventStream", { + enumerable: true, + get: function get() { + return _subscribe.createSourceEventStream; + } +}); + +var _subscribe = require("./subscribe.js"); diff --git a/school/node_modules/graphql/subscription/index.js.flow b/school/node_modules/graphql/subscription/index.js.flow new file mode 100644 index 0000000..9f37bfd --- /dev/null +++ b/school/node_modules/graphql/subscription/index.js.flow @@ -0,0 +1,3 @@ +// @flow strict +export { subscribe, createSourceEventStream } from './subscribe'; +export type { SubscriptionArgs } from './subscribe'; diff --git a/school/node_modules/graphql/subscription/index.mjs b/school/node_modules/graphql/subscription/index.mjs new file mode 100644 index 0000000..8983f84 --- /dev/null +++ b/school/node_modules/graphql/subscription/index.mjs @@ -0,0 +1 @@ +export { subscribe, createSourceEventStream } from "./subscribe.mjs"; diff --git a/school/node_modules/graphql/subscription/mapAsyncIterator.d.ts b/school/node_modules/graphql/subscription/mapAsyncIterator.d.ts new file mode 100644 index 0000000..22e8a34 --- /dev/null +++ b/school/node_modules/graphql/subscription/mapAsyncIterator.d.ts @@ -0,0 +1,11 @@ +import { PromiseOrValue } from '../jsutils/PromiseOrValue'; + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +export default function mapAsyncIterator<T, U>( + iterable: AsyncIterable<T>, + callback: (arg: T) => PromiseOrValue<U>, + rejectCallback?: (arg: any) => PromiseOrValue<U>, +): any; // TS_SPECIFIC: AsyncGenerator requires typescript@3.6 diff --git a/school/node_modules/graphql/subscription/mapAsyncIterator.js b/school/node_modules/graphql/subscription/mapAsyncIterator.js new file mode 100644 index 0000000..4fd37cd --- /dev/null +++ b/school/node_modules/graphql/subscription/mapAsyncIterator.js @@ -0,0 +1,86 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapAsyncIterator; + +var _symbols = require("../polyfills/symbols.js"); + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +function mapAsyncIterator(iterable, callback, rejectCallback) { + // $FlowFixMe[prop-missing] + var iteratorMethod = iterable[_symbols.SYMBOL_ASYNC_ITERATOR]; + var iterator = iteratorMethod.call(iterable); + var $return; + var abruptClose; + + if (typeof iterator.return === 'function') { + $return = iterator.return; + + abruptClose = function abruptClose(error) { + var rethrow = function rethrow() { + return Promise.reject(error); + }; + + return $return.call(iterator).then(rethrow, rethrow); + }; + } + + function mapResult(result) { + return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose); + } + + var mapReject; + + if (rejectCallback) { + // Capture rejectCallback to ensure it cannot be null. + var reject = rejectCallback; + + mapReject = function mapReject(error) { + return asyncMapValue(error, reject).then(iteratorResult, abruptClose); + }; + } + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + + + return _defineProperty({ + next: function next() { + return iterator.next().then(mapResult, mapReject); + }, + return: function _return() { + return $return ? $return.call(iterator).then(mapResult, mapReject) : Promise.resolve({ + value: undefined, + done: true + }); + }, + throw: function _throw(error) { + if (typeof iterator.throw === 'function') { + return iterator.throw(error).then(mapResult, mapReject); + } + + return Promise.reject(error).catch(abruptClose); + } + }, _symbols.SYMBOL_ASYNC_ITERATOR, function () { + return this; + }); +} + +function asyncMapValue(value, callback) { + return new Promise(function (resolve) { + return resolve(callback(value)); + }); +} + +function iteratorResult(value) { + return { + value: value, + done: false + }; +} diff --git a/school/node_modules/graphql/subscription/mapAsyncIterator.js.flow b/school/node_modules/graphql/subscription/mapAsyncIterator.js.flow new file mode 100644 index 0000000..8b1d1d8 --- /dev/null +++ b/school/node_modules/graphql/subscription/mapAsyncIterator.js.flow @@ -0,0 +1,74 @@ +// @flow strict +import { SYMBOL_ASYNC_ITERATOR } from '../polyfills/symbols'; + +import type { PromiseOrValue } from '../jsutils/PromiseOrValue'; + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +export default function mapAsyncIterator<T, U>( + iterable: AsyncIterable<T> | AsyncGenerator<T, void, void>, + callback: (T) => PromiseOrValue<U>, + rejectCallback?: (any) => PromiseOrValue<U>, +): AsyncGenerator<U, void, void> { + // $FlowFixMe[prop-missing] + const iteratorMethod = iterable[SYMBOL_ASYNC_ITERATOR]; + const iterator: any = iteratorMethod.call(iterable); + let $return: any; + let abruptClose; + if (typeof iterator.return === 'function') { + $return = iterator.return; + abruptClose = (error: mixed) => { + const rethrow = () => Promise.reject(error); + return $return.call(iterator).then(rethrow, rethrow); + }; + } + + function mapResult(result: IteratorResult<T, void>) { + return result.done + ? result + : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose); + } + + let mapReject; + if (rejectCallback) { + // Capture rejectCallback to ensure it cannot be null. + const reject = rejectCallback; + mapReject = (error: mixed) => + asyncMapValue(error, reject).then(iteratorResult, abruptClose); + } + + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + return ({ + next(): Promise<IteratorResult<U, void>> { + return iterator.next().then(mapResult, mapReject); + }, + return() { + return $return + ? $return.call(iterator).then(mapResult, mapReject) + : Promise.resolve({ value: undefined, done: true }); + }, + throw(error?: mixed): Promise<IteratorResult<U, void>> { + if (typeof iterator.throw === 'function') { + return iterator.throw(error).then(mapResult, mapReject); + } + return Promise.reject(error).catch(abruptClose); + }, + [SYMBOL_ASYNC_ITERATOR]() { + return this; + }, + }: $FlowFixMe); +} + +function asyncMapValue<T, U>( + value: T, + callback: (T) => PromiseOrValue<U>, +): Promise<U> { + return new Promise((resolve) => resolve(callback(value))); +} + +function iteratorResult<T>(value: T): IteratorResult<T, void> { + return { value, done: false }; +} diff --git a/school/node_modules/graphql/subscription/mapAsyncIterator.mjs b/school/node_modules/graphql/subscription/mapAsyncIterator.mjs new file mode 100644 index 0000000..ffe23e0 --- /dev/null +++ b/school/node_modules/graphql/subscription/mapAsyncIterator.mjs @@ -0,0 +1,79 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +import { SYMBOL_ASYNC_ITERATOR } from "../polyfills/symbols.mjs"; + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +export default function mapAsyncIterator(iterable, callback, rejectCallback) { + // $FlowFixMe[prop-missing] + var iteratorMethod = iterable[SYMBOL_ASYNC_ITERATOR]; + var iterator = iteratorMethod.call(iterable); + var $return; + var abruptClose; + + if (typeof iterator.return === 'function') { + $return = iterator.return; + + abruptClose = function abruptClose(error) { + var rethrow = function rethrow() { + return Promise.reject(error); + }; + + return $return.call(iterator).then(rethrow, rethrow); + }; + } + + function mapResult(result) { + return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose); + } + + var mapReject; + + if (rejectCallback) { + // Capture rejectCallback to ensure it cannot be null. + var reject = rejectCallback; + + mapReject = function mapReject(error) { + return asyncMapValue(error, reject).then(iteratorResult, abruptClose); + }; + } + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + + + return _defineProperty({ + next: function next() { + return iterator.next().then(mapResult, mapReject); + }, + return: function _return() { + return $return ? $return.call(iterator).then(mapResult, mapReject) : Promise.resolve({ + value: undefined, + done: true + }); + }, + throw: function _throw(error) { + if (typeof iterator.throw === 'function') { + return iterator.throw(error).then(mapResult, mapReject); + } + + return Promise.reject(error).catch(abruptClose); + } + }, SYMBOL_ASYNC_ITERATOR, function () { + return this; + }); +} + +function asyncMapValue(value, callback) { + return new Promise(function (resolve) { + return resolve(callback(value)); + }); +} + +function iteratorResult(value) { + return { + value: value, + done: false + }; +} diff --git a/school/node_modules/graphql/subscription/subscribe.d.ts b/school/node_modules/graphql/subscription/subscribe.d.ts new file mode 100644 index 0000000..3ed750a --- /dev/null +++ b/school/node_modules/graphql/subscription/subscribe.d.ts @@ -0,0 +1,80 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { DocumentNode } from '../language/ast'; +import { ExecutionResult } from '../execution/execute'; +import { GraphQLSchema } from '../type/schema'; +import { GraphQLFieldResolver } from '../type/definition'; + +export interface SubscriptionArgs { + schema: GraphQLSchema; + document: DocumentNode; + rootValue?: any; + contextValue?: any; + variableValues?: Maybe<Record<string, any>>; + operationName?: Maybe<string>; + fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>; + subscribeFieldResolver?: Maybe<GraphQLFieldResolver<any, any>>; +} + +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise which resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (client error). The promise will be rejected if a + * server error occurs. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Accepts either an object with named arguments, or individual arguments. + */ +export function subscribe( + args: SubscriptionArgs, +): Promise<AsyncIterableIterator<ExecutionResult> | ExecutionResult>; + +export function subscribe( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: any, + contextValue?: any, + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe<string>, + fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>, + subscribeFieldResolver?: Maybe<GraphQLFieldResolver<any, any>>, +): Promise<AsyncIterableIterator<ExecutionResult> | ExecutionResult>; + +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise<AsyncIterable>. + * + * If the client-provided invalid arguments, the source stream could not be + * created, or the resolver did not return an AsyncIterable, this function will + * will throw an error, which should be caught and handled by the caller. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ +export function createSourceEventStream( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: any, + contextValue?: any, + variableValues?: { [key: string]: any }, + operationName?: Maybe<string>, + fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>, +): Promise<AsyncIterable<any> | ExecutionResult>; diff --git a/school/node_modules/graphql/subscription/subscribe.js b/school/node_modules/graphql/subscription/subscribe.js new file mode 100644 index 0000000..9f8225d --- /dev/null +++ b/school/node_modules/graphql/subscription/subscribe.js @@ -0,0 +1,192 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.subscribe = subscribe; +exports.createSourceEventStream = createSourceEventStream; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _isAsyncIterable = _interopRequireDefault(require("../jsutils/isAsyncIterable.js")); + +var _Path = require("../jsutils/Path.js"); + +var _GraphQLError = require("../error/GraphQLError.js"); + +var _locatedError = require("../error/locatedError.js"); + +var _values = require("../execution/values.js"); + +var _execute = require("../execution/execute.js"); + +var _getOperationRootType = require("../utilities/getOperationRootType.js"); + +var _mapAsyncIterator = _interopRequireDefault(require("./mapAsyncIterator.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? subscribeImpl(argsOrSchema) : subscribeImpl({ + schema: argsOrSchema, + document: document, + rootValue: rootValue, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver, + subscribeFieldResolver: subscribeFieldResolver + }); +} +/** + * This function checks if the error is a GraphQLError. If it is, report it as + * an ExecutionResult, containing only errors and no data. Otherwise treat the + * error as a system-class error and re-throw it. + */ + + +function reportGraphQLError(error) { + if (error instanceof _GraphQLError.GraphQLError) { + return { + errors: [error] + }; + } + + throw error; +} + +function subscribeImpl(args) { + var schema = args.schema, + document = args.document, + rootValue = args.rootValue, + contextValue = args.contextValue, + variableValues = args.variableValues, + operationName = args.operationName, + fieldResolver = args.fieldResolver, + subscribeFieldResolver = args.subscribeFieldResolver; + var sourcePromise = createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver); // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. + + var mapSourceToResponse = function mapSourceToResponse(payload) { + return (0, _execute.execute)({ + schema: schema, + document: document, + rootValue: payload, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver + }); + }; // Resolve the Source Stream, then map every source value to a + // ExecutionResult value as described above. + + + return sourcePromise.then(function (resultOrStream) { + return (// Note: Flow can't refine isAsyncIterable, so explicit casts are used. + (0, _isAsyncIterable.default)(resultOrStream) ? (0, _mapAsyncIterator.default)(resultOrStream, mapSourceToResponse, reportGraphQLError) : resultOrStream + ); + }); +} +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise which resolves to either an AsyncIterable (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to the AsyncIterable for the + * event stream returned by the resolver. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ + + +function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + (0, _execute.assertValidExecutionArguments)(schema, document, variableValues); + return new Promise(function (resolve) { + // If a valid context cannot be created due to incorrect arguments, + // this will throw an error. + var exeContext = (0, _execute.buildExecutionContext)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); + resolve( // Return early errors if execution context failed. + Array.isArray(exeContext) ? { + errors: exeContext + } : executeSubscription(exeContext)); + }).catch(reportGraphQLError); +} + +function executeSubscription(exeContext) { + var schema = exeContext.schema, + operation = exeContext.operation, + variableValues = exeContext.variableValues, + rootValue = exeContext.rootValue; + var type = (0, _getOperationRootType.getOperationRootType)(schema, operation); + var fields = (0, _execute.collectFields)(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null)); + var responseNames = Object.keys(fields); + var responseName = responseNames[0]; + var fieldNodes = fields[responseName]; + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = (0, _execute.getFieldDef)(schema, type, fieldName); + + if (!fieldDef) { + throw new _GraphQLError.GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes); + } + + var path = (0, _Path.addPath)(undefined, responseName, type.name); + var info = (0, _execute.buildResolveInfo)(exeContext, fieldDef, fieldNodes, type, path); // Coerce to Promise for easier error handling and consistent return type. + + return new Promise(function (resolveResult) { + var _fieldDef$subscribe; + + // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. + // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + var args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + var contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + + var resolveFn = (_fieldDef$subscribe = fieldDef.subscribe) !== null && _fieldDef$subscribe !== void 0 ? _fieldDef$subscribe : exeContext.fieldResolver; + resolveResult(resolveFn(rootValue, args, contextValue, info)); + }).then(function (eventStream) { + if (eventStream instanceof Error) { + throw (0, _locatedError.locatedError)(eventStream, fieldNodes, (0, _Path.pathToArray)(path)); + } // Assert field returned an event stream, otherwise yield an error. + + + if (!(0, _isAsyncIterable.default)(eventStream)) { + throw new Error('Subscription field must return Async Iterable. ' + "Received: ".concat((0, _inspect.default)(eventStream), ".")); + } + + return eventStream; + }, function (error) { + throw (0, _locatedError.locatedError)(error, fieldNodes, (0, _Path.pathToArray)(path)); + }); +} diff --git a/school/node_modules/graphql/subscription/subscribe.js.flow b/school/node_modules/graphql/subscription/subscribe.js.flow new file mode 100644 index 0000000..7d21367 --- /dev/null +++ b/school/node_modules/graphql/subscription/subscribe.js.flow @@ -0,0 +1,298 @@ +// @flow strict +import inspect from '../jsutils/inspect'; +import isAsyncIterable from '../jsutils/isAsyncIterable'; +import { addPath, pathToArray } from '../jsutils/Path'; + +import { GraphQLError } from '../error/GraphQLError'; +import { locatedError } from '../error/locatedError'; + +import type { DocumentNode } from '../language/ast'; + +import type { ExecutionResult, ExecutionContext } from '../execution/execute'; +import { getArgumentValues } from '../execution/values'; +import { + assertValidExecutionArguments, + buildExecutionContext, + buildResolveInfo, + collectFields, + execute, + getFieldDef, +} from '../execution/execute'; + +import type { GraphQLSchema } from '../type/schema'; +import type { GraphQLFieldResolver } from '../type/definition'; + +import { getOperationRootType } from '../utilities/getOperationRootType'; + +import mapAsyncIterator from './mapAsyncIterator'; + +export type SubscriptionArgs = {| + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ +[variable: string]: mixed, ... }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver<any, any>, + subscribeFieldResolver?: ?GraphQLFieldResolver<any, any>, +|}; + +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise which resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Accepts either an object with named arguments, or individual arguments. + */ +declare function subscribe( + SubscriptionArgs, + ..._: [] +): Promise<AsyncGenerator<ExecutionResult, void, void> | ExecutionResult>; +/* eslint-disable no-redeclare */ +declare function subscribe( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ +[variable: string]: mixed, ... }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver<any, any>, + subscribeFieldResolver?: ?GraphQLFieldResolver<any, any>, +): Promise<AsyncIterator<ExecutionResult> | ExecutionResult>; +export function subscribe( + argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + subscribeFieldResolver, +) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 + ? subscribeImpl(argsOrSchema) + : subscribeImpl({ + schema: argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + subscribeFieldResolver, + }); +} + +/** + * This function checks if the error is a GraphQLError. If it is, report it as + * an ExecutionResult, containing only errors and no data. Otherwise treat the + * error as a system-class error and re-throw it. + */ +function reportGraphQLError(error: mixed): ExecutionResult { + if (error instanceof GraphQLError) { + return { errors: [error] }; + } + throw error; +} + +function subscribeImpl( + args: SubscriptionArgs, +): Promise<AsyncGenerator<ExecutionResult, void, void> | ExecutionResult> { + const { + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + subscribeFieldResolver, + } = args; + + const sourcePromise = createSourceEventStream( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + subscribeFieldResolver, + ); + + // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. + const mapSourceToResponse = (payload) => + execute({ + schema, + document, + rootValue: payload, + contextValue, + variableValues, + operationName, + fieldResolver, + }); + + // Resolve the Source Stream, then map every source value to a + // ExecutionResult value as described above. + return sourcePromise.then((resultOrStream) => + // Note: Flow can't refine isAsyncIterable, so explicit casts are used. + isAsyncIterable(resultOrStream) + ? mapAsyncIterator( + resultOrStream, + mapSourceToResponse, + reportGraphQLError, + ) + : ((resultOrStream: any): ExecutionResult), + ); +} + +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise which resolves to either an AsyncIterable (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to the AsyncIterable for the + * event stream returned by the resolver. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ +export function createSourceEventStream( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ +[variable: string]: mixed, ... }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver<any, any>, +): Promise<AsyncIterable<mixed> | ExecutionResult> { + // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + assertValidExecutionArguments(schema, document, variableValues); + + return new Promise((resolve) => { + // If a valid context cannot be created due to incorrect arguments, + // this will throw an error. + const exeContext = buildExecutionContext( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ); + + resolve( + // Return early errors if execution context failed. + Array.isArray(exeContext) + ? { errors: exeContext } + : executeSubscription(exeContext), + ); + }).catch(reportGraphQLError); +} + +function executeSubscription( + exeContext: ExecutionContext, +): Promise<AsyncIterable<mixed>> { + const { schema, operation, variableValues, rootValue } = exeContext; + const type = getOperationRootType(schema, operation); + const fields = collectFields( + exeContext, + type, + operation.selectionSet, + Object.create(null), + Object.create(null), + ); + const responseNames = Object.keys(fields); + const responseName = responseNames[0]; + const fieldNodes = fields[responseName]; + const fieldNode = fieldNodes[0]; + const fieldName = fieldNode.name.value; + const fieldDef = getFieldDef(schema, type, fieldName); + + if (!fieldDef) { + throw new GraphQLError( + `The subscription field "${fieldName}" is not defined.`, + fieldNodes, + ); + } + + const path = addPath(undefined, responseName, type.name); + const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, type, path); + + // Coerce to Promise for easier error handling and consistent return type. + return new Promise((resolveResult) => { + // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. + // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. + + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + const args = getArgumentValues(fieldDef, fieldNodes[0], variableValues); + + // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + const contextValue = exeContext.contextValue; + + // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + const resolveFn = fieldDef.subscribe ?? exeContext.fieldResolver; + resolveResult(resolveFn(rootValue, args, contextValue, info)); + }).then( + (eventStream) => { + if (eventStream instanceof Error) { + throw locatedError(eventStream, fieldNodes, pathToArray(path)); + } + + // Assert field returned an event stream, otherwise yield an error. + if (!isAsyncIterable(eventStream)) { + throw new Error( + 'Subscription field must return Async Iterable. ' + + `Received: ${inspect(eventStream)}.`, + ); + } + return eventStream; + }, + (error) => { + throw locatedError(error, fieldNodes, pathToArray(path)); + }, + ); +} diff --git a/school/node_modules/graphql/subscription/subscribe.mjs b/school/node_modules/graphql/subscription/subscribe.mjs new file mode 100644 index 0000000..a35acf9 --- /dev/null +++ b/school/node_modules/graphql/subscription/subscribe.mjs @@ -0,0 +1,172 @@ +import inspect from "../jsutils/inspect.mjs"; +import isAsyncIterable from "../jsutils/isAsyncIterable.mjs"; +import { addPath, pathToArray } from "../jsutils/Path.mjs"; +import { GraphQLError } from "../error/GraphQLError.mjs"; +import { locatedError } from "../error/locatedError.mjs"; +import { getArgumentValues } from "../execution/values.mjs"; +import { assertValidExecutionArguments, buildExecutionContext, buildResolveInfo, collectFields, execute, getFieldDef } from "../execution/execute.mjs"; +import { getOperationRootType } from "../utilities/getOperationRootType.mjs"; +import mapAsyncIterator from "./mapAsyncIterator.mjs"; +export function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? subscribeImpl(argsOrSchema) : subscribeImpl({ + schema: argsOrSchema, + document: document, + rootValue: rootValue, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver, + subscribeFieldResolver: subscribeFieldResolver + }); +} +/** + * This function checks if the error is a GraphQLError. If it is, report it as + * an ExecutionResult, containing only errors and no data. Otherwise treat the + * error as a system-class error and re-throw it. + */ + +function reportGraphQLError(error) { + if (error instanceof GraphQLError) { + return { + errors: [error] + }; + } + + throw error; +} + +function subscribeImpl(args) { + var schema = args.schema, + document = args.document, + rootValue = args.rootValue, + contextValue = args.contextValue, + variableValues = args.variableValues, + operationName = args.operationName, + fieldResolver = args.fieldResolver, + subscribeFieldResolver = args.subscribeFieldResolver; + var sourcePromise = createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver); // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. + + var mapSourceToResponse = function mapSourceToResponse(payload) { + return execute({ + schema: schema, + document: document, + rootValue: payload, + contextValue: contextValue, + variableValues: variableValues, + operationName: operationName, + fieldResolver: fieldResolver + }); + }; // Resolve the Source Stream, then map every source value to a + // ExecutionResult value as described above. + + + return sourcePromise.then(function (resultOrStream) { + return (// Note: Flow can't refine isAsyncIterable, so explicit casts are used. + isAsyncIterable(resultOrStream) ? mapAsyncIterator(resultOrStream, mapSourceToResponse, reportGraphQLError) : resultOrStream + ); + }); +} +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise which resolves to either an AsyncIterable (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to the AsyncIterable for the + * event stream returned by the resolver. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ + + +export function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + assertValidExecutionArguments(schema, document, variableValues); + return new Promise(function (resolve) { + // If a valid context cannot be created due to incorrect arguments, + // this will throw an error. + var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); + resolve( // Return early errors if execution context failed. + Array.isArray(exeContext) ? { + errors: exeContext + } : executeSubscription(exeContext)); + }).catch(reportGraphQLError); +} + +function executeSubscription(exeContext) { + var schema = exeContext.schema, + operation = exeContext.operation, + variableValues = exeContext.variableValues, + rootValue = exeContext.rootValue; + var type = getOperationRootType(schema, operation); + var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null)); + var responseNames = Object.keys(fields); + var responseName = responseNames[0]; + var fieldNodes = fields[responseName]; + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = getFieldDef(schema, type, fieldName); + + if (!fieldDef) { + throw new GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes); + } + + var path = addPath(undefined, responseName, type.name); + var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, type, path); // Coerce to Promise for easier error handling and consistent return type. + + return new Promise(function (resolveResult) { + var _fieldDef$subscribe; + + // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. + // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + var args = getArgumentValues(fieldDef, fieldNodes[0], variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + var contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + + var resolveFn = (_fieldDef$subscribe = fieldDef.subscribe) !== null && _fieldDef$subscribe !== void 0 ? _fieldDef$subscribe : exeContext.fieldResolver; + resolveResult(resolveFn(rootValue, args, contextValue, info)); + }).then(function (eventStream) { + if (eventStream instanceof Error) { + throw locatedError(eventStream, fieldNodes, pathToArray(path)); + } // Assert field returned an event stream, otherwise yield an error. + + + if (!isAsyncIterable(eventStream)) { + throw new Error('Subscription field must return Async Iterable. ' + "Received: ".concat(inspect(eventStream), ".")); + } + + return eventStream; + }, function (error) { + throw locatedError(error, fieldNodes, pathToArray(path)); + }); +} diff --git a/school/node_modules/graphql/type/definition.d.ts b/school/node_modules/graphql/type/definition.d.ts new file mode 100644 index 0000000..b304d22 --- /dev/null +++ b/school/node_modules/graphql/type/definition.d.ts @@ -0,0 +1,955 @@ +// FIXME +/* eslint-disable import/no-cycle */ + +import { Maybe } from '../jsutils/Maybe'; + +import { PromiseOrValue } from '../jsutils/PromiseOrValue'; +import { Path } from '../jsutils/Path'; + +import { + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + OperationDefinitionNode, + FieldNode, + FragmentDefinitionNode, + ValueNode, + ScalarTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from '../language/ast'; + +import { GraphQLSchema } from './schema'; + +/** + * These are all of the possible kinds of types. + */ +export type GraphQLType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList<any> + | GraphQLNonNull<any>; + +export function isType(type: any): type is GraphQLType; + +export function assertType(type: any): GraphQLType; + +export function isScalarType(type: any): type is GraphQLScalarType; + +export function assertScalarType(type: any): GraphQLScalarType; + +export function isObjectType(type: any): type is GraphQLObjectType; + +export function assertObjectType(type: any): GraphQLObjectType; + +export function isInterfaceType(type: any): type is GraphQLInterfaceType; + +export function assertInterfaceType(type: any): GraphQLInterfaceType; + +export function isUnionType(type: any): type is GraphQLUnionType; + +export function assertUnionType(type: any): GraphQLUnionType; + +export function isEnumType(type: any): type is GraphQLEnumType; + +export function assertEnumType(type: any): GraphQLEnumType; + +export function isInputObjectType(type: any): type is GraphQLInputObjectType; + +export function assertInputObjectType(type: any): GraphQLInputObjectType; + +export function isListType(type: any): type is GraphQLList<any>; + +export function assertListType(type: any): GraphQLList<any>; + +export function isNonNullType(type: any): type is GraphQLNonNull<any>; + +export function assertNonNullType(type: any): GraphQLNonNull<any>; + +/** + * These types may be used as input types for arguments and directives. + */ +// TS_SPECIFIC: TS does not allow recursive type definitions, hence the `any`s +export type GraphQLInputType = + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList<any> + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList<any> + >; + +export function isInputType(type: any): type is GraphQLInputType; + +export function assertInputType(type: any): GraphQLInputType; + +/** + * These types may be used as output types as the result of fields. + */ +// TS_SPECIFIC: TS does not allow recursive type definitions, hence the `any`s +export type GraphQLOutputType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList<any> + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList<any> + >; + +export function isOutputType(type: any): type is GraphQLOutputType; + +export function assertOutputType(type: any): GraphQLOutputType; + +/** + * These types may describe types which may be leaf values. + */ +export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; + +export function isLeafType(type: any): type is GraphQLLeafType; + +export function assertLeafType(type: any): GraphQLLeafType; + +/** + * These types may describe the parent context of a selection set. + */ +export type GraphQLCompositeType = + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType; + +export function isCompositeType(type: any): type is GraphQLCompositeType; + +export function assertCompositeType(type: any): GraphQLCompositeType; + +/** + * These types may describe the parent context of a selection set. + */ +export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; + +export function isAbstractType(type: any): type is GraphQLAbstractType; + +export function assertAbstractType(type: any): GraphQLAbstractType; + +/** + * List Modifier + * + * A list is a kind of type marker, a wrapping type which points to another + * type. Lists are often created within the context of defining the fields + * of an object type. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(Person) }, + * children: { type: new GraphQLList(Person) }, + * }) + * }) + * + */ +interface GraphQLList<T extends GraphQLType> { + readonly ofType: T; + toString: () => string; + toJSON: () => string; + inspect: () => string; +} + +interface _GraphQLList<T extends GraphQLType> { + (type: T): GraphQLList<T>; + new (type: T): GraphQLList<T>; +} + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const GraphQLList: _GraphQLList<GraphQLType>; + +/** + * Non-Null Modifier + * + * A non-null is a kind of type marker, a wrapping type which points to another + * type. Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ +interface GraphQLNonNull<T extends GraphQLNullableType> { + readonly ofType: T; + toString: () => string; + toJSON: () => string; + inspect: () => string; +} + +interface _GraphQLNonNull<T extends GraphQLNullableType> { + (type: T): GraphQLNonNull<T>; + new (type: T): GraphQLNonNull<T>; +} + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const GraphQLNonNull: _GraphQLNonNull<GraphQLNullableType>; + +export type GraphQLWrappingType = GraphQLList<any> | GraphQLNonNull<any>; + +export function isWrappingType(type: any): type is GraphQLWrappingType; + +export function assertWrappingType(type: any): GraphQLWrappingType; + +/** + * These types can all accept null as a value. + */ +export type GraphQLNullableType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList<any>; + +export function isNullableType(type: any): type is GraphQLNullableType; + +export function assertNullableType(type: any): GraphQLNullableType; + +export function getNullableType(type: undefined): undefined; +export function getNullableType<T extends GraphQLNullableType>(type: T): T; +export function getNullableType<T extends GraphQLNullableType>( + // FIXME Disabled because of https://github.com/yaacovCR/graphql-tools-fork/issues/40#issuecomment-586671219 + // eslint-disable-next-line @typescript-eslint/unified-signatures + type: GraphQLNonNull<T>, +): T; + +/** + * These named types do not include modifiers like List or NonNull. + */ +export type GraphQLNamedType = GraphQLNamedInputType | GraphQLNamedOutputType; + +export type GraphQLNamedInputType = + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType; + +export type GraphQLNamedOutputType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType; + +export function isNamedType(type: any): type is GraphQLNamedType; + +export function assertNamedType(type: any): GraphQLNamedType; + +export function getNamedType(type: undefined): undefined; +export function getNamedType(type: GraphQLInputType): GraphQLNamedInputType; +export function getNamedType(type: GraphQLOutputType): GraphQLNamedOutputType; +export function getNamedType(type: GraphQLType): GraphQLNamedType; + +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ +export type Thunk<T> = (() => T) | T; + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLScalarTypeExtensions { + [attributeName: string]: any; +} + +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * return value % 2 === 1 ? value : null; + * } + * }); + * + */ +export class GraphQLScalarType { + name: string; + description: Maybe<string>; + specifiedByUrl: Maybe<string>; + serialize: GraphQLScalarSerializer<any>; + parseValue: GraphQLScalarValueParser<any>; + parseLiteral: GraphQLScalarLiteralParser<any>; + extensions: Maybe<Readonly<GraphQLScalarTypeExtensions>>; + astNode: Maybe<ScalarTypeDefinitionNode>; + extensionASTNodes: Maybe<ReadonlyArray<ScalarTypeExtensionNode>>; + + constructor(config: Readonly<GraphQLScalarTypeConfig<any, any>>); + + toConfig(): GraphQLScalarTypeConfig<any, any> & { + specifiedByUrl: Maybe<string>; + serialize: GraphQLScalarSerializer<any>; + parseValue: GraphQLScalarValueParser<any>; + parseLiteral: GraphQLScalarLiteralParser<any>; + extensions: Maybe<Readonly<GraphQLScalarTypeExtensions>>; + extensionASTNodes: ReadonlyArray<ScalarTypeExtensionNode>; + }; + + toString(): string; + toJSON(): string; + inspect(): string; +} + +export type GraphQLScalarSerializer<TExternal> = ( + value: any, +) => Maybe<TExternal>; +export type GraphQLScalarValueParser<TInternal> = ( + value: any, +) => Maybe<TInternal>; +export type GraphQLScalarLiteralParser<TInternal> = ( + valueNode: ValueNode, + variables: Maybe<{ [key: string]: any }>, +) => Maybe<TInternal>; + +export interface GraphQLScalarTypeConfig<TInternal, TExternal> { + name: string; + description?: Maybe<string>; + specifiedByUrl?: Maybe<string>; + // Serializes an internal value to include in a response. + serialize?: GraphQLScalarSerializer<TExternal>; + // Parses an externally provided value to use as an input. + parseValue?: GraphQLScalarValueParser<TInternal>; + // Parses an externally provided literal value to use as an input. + parseLiteral?: GraphQLScalarLiteralParser<TInternal>; + extensions?: Maybe<Readonly<GraphQLScalarTypeExtensions>>; + astNode?: Maybe<ScalarTypeDefinitionNode>; + extensionASTNodes?: Maybe<ReadonlyArray<ScalarTypeExtensionNode>>; +} + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + * + * We've provided these template arguments because this is an open type and + * you may find them useful. + */ +export interface GraphQLObjectTypeExtensions<_TSource = any, _TContext = any> { + [attributeName: string]: any; +} + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * + */ +export class GraphQLObjectType<TSource = any, TContext = any> { + name: string; + description: Maybe<string>; + isTypeOf: Maybe<GraphQLIsTypeOfFn<TSource, TContext>>; + extensions: Maybe<Readonly<GraphQLObjectTypeExtensions<TSource, TContext>>>; + astNode: Maybe<ObjectTypeDefinitionNode>; + extensionASTNodes: Maybe<ReadonlyArray<ObjectTypeExtensionNode>>; + + constructor(config: Readonly<GraphQLObjectTypeConfig<TSource, TContext>>); + + getFields(): GraphQLFieldMap<any, TContext>; + getInterfaces(): Array<GraphQLInterfaceType>; + + toConfig(): GraphQLObjectTypeConfig<any, any> & { + interfaces: Array<GraphQLInterfaceType>; + fields: GraphQLFieldConfigMap<any, any>; + extensions: Maybe<Readonly<GraphQLObjectTypeExtensions<TSource, TContext>>>; + extensionASTNodes: ReadonlyArray<ObjectTypeExtensionNode>; + }; + + toString(): string; + toJSON(): string; + inspect(): string; +} + +export function argsToArgsConfig( + args: ReadonlyArray<GraphQLArgument>, +): GraphQLFieldConfigArgumentMap; + +export interface GraphQLObjectTypeConfig<TSource, TContext> { + name: string; + description?: Maybe<string>; + interfaces?: Thunk<Maybe<Array<GraphQLInterfaceType>>>; + fields: Thunk<GraphQLFieldConfigMap<TSource, TContext>>; + isTypeOf?: Maybe<GraphQLIsTypeOfFn<TSource, TContext>>; + extensions?: Maybe<Readonly<GraphQLObjectTypeExtensions<TSource, TContext>>>; + astNode?: Maybe<ObjectTypeDefinitionNode>; + extensionASTNodes?: Maybe<ReadonlyArray<ObjectTypeExtensionNode>>; +} + +export type GraphQLTypeResolver<TSource, TContext> = ( + value: TSource, + context: TContext, + info: GraphQLResolveInfo, + abstractType: GraphQLAbstractType, +) => PromiseOrValue<Maybe<GraphQLObjectType<TSource, TContext> | string>>; + +export type GraphQLIsTypeOfFn<TSource, TContext> = ( + source: TSource, + context: TContext, + info: GraphQLResolveInfo, +) => PromiseOrValue<boolean>; + +export type GraphQLFieldResolver< + TSource, + TContext, + TArgs = { [argName: string]: any } +> = ( + source: TSource, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo, +) => any; + +export interface GraphQLResolveInfo { + readonly fieldName: string; + readonly fieldNodes: ReadonlyArray<FieldNode>; + readonly returnType: GraphQLOutputType; + readonly parentType: GraphQLObjectType; + readonly path: Path; + readonly schema: GraphQLSchema; + readonly fragments: { [key: string]: FragmentDefinitionNode }; + readonly rootValue: any; + readonly operation: OperationDefinitionNode; + readonly variableValues: { [variableName: string]: any }; +} + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + * + * We've provided these template arguments because this is an open type and + * you may find them useful. + */ +export interface GraphQLFieldExtensions< + _TSource, + _TContext, + _TArgs = { [argName: string]: any } +> { + [attributeName: string]: any; +} + +export interface GraphQLFieldConfig< + TSource, + TContext, + TArgs = { [argName: string]: any } +> { + description?: Maybe<string>; + type: GraphQLOutputType; + args?: GraphQLFieldConfigArgumentMap; + resolve?: GraphQLFieldResolver<TSource, TContext, TArgs>; + subscribe?: GraphQLFieldResolver<TSource, TContext, TArgs>; + deprecationReason?: Maybe<string>; + extensions?: Maybe< + Readonly<GraphQLFieldExtensions<TSource, TContext, TArgs>> + >; + astNode?: Maybe<FieldDefinitionNode>; +} + +export interface GraphQLFieldConfigArgumentMap { + [key: string]: GraphQLArgumentConfig; +} + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLArgumentExtensions { + [attributeName: string]: any; +} + +export interface GraphQLArgumentConfig { + description?: Maybe<string>; + type: GraphQLInputType; + defaultValue?: any; + deprecationReason?: Maybe<string>; + extensions?: Maybe<Readonly<GraphQLArgumentExtensions>>; + astNode?: Maybe<InputValueDefinitionNode>; +} + +export interface GraphQLFieldConfigMap<TSource, TContext> { + [key: string]: GraphQLFieldConfig<TSource, TContext>; +} + +export interface GraphQLField< + TSource, + TContext, + TArgs = { [key: string]: any } +> { + name: string; + description: Maybe<string>; + type: GraphQLOutputType; + args: Array<GraphQLArgument>; + resolve?: GraphQLFieldResolver<TSource, TContext, TArgs>; + subscribe?: GraphQLFieldResolver<TSource, TContext, TArgs>; + deprecationReason: Maybe<string>; + extensions: Maybe<Readonly<GraphQLFieldExtensions<TSource, TContext, TArgs>>>; + astNode?: Maybe<FieldDefinitionNode>; + + // @deprecated and will be removed in v16 + isDeprecated: boolean; +} + +export interface GraphQLArgument { + name: string; + description: Maybe<string>; + type: GraphQLInputType; + defaultValue: any; + deprecationReason: Maybe<string>; + extensions: Maybe<Readonly<GraphQLArgumentExtensions>>; + astNode: Maybe<InputValueDefinitionNode>; +} + +export function isRequiredArgument(arg: GraphQLArgument): boolean; + +export interface GraphQLFieldMap<TSource, TContext> { + [key: string]: GraphQLField<TSource, TContext>; +} + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLInterfaceTypeExtensions { + [attributeName: string]: any; +} + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * + */ +export class GraphQLInterfaceType { + name: string; + description: Maybe<string>; + resolveType: Maybe<GraphQLTypeResolver<any, any>>; + extensions: Maybe<Readonly<GraphQLInterfaceTypeExtensions>>; + astNode?: Maybe<InterfaceTypeDefinitionNode>; + extensionASTNodes: Maybe<ReadonlyArray<InterfaceTypeExtensionNode>>; + + constructor(config: Readonly<GraphQLInterfaceTypeConfig<any, any>>); + getFields(): GraphQLFieldMap<any, any>; + getInterfaces(): Array<GraphQLInterfaceType>; + + toConfig(): GraphQLInterfaceTypeConfig<any, any> & { + interfaces: Array<GraphQLInterfaceType>; + fields: GraphQLFieldConfigMap<any, any>; + extensions: Maybe<Readonly<GraphQLInterfaceTypeExtensions>>; + extensionASTNodes: ReadonlyArray<InterfaceTypeExtensionNode>; + }; + + toString(): string; + toJSON(): string; + inspect(): string; +} + +export interface GraphQLInterfaceTypeConfig<TSource, TContext> { + name: string; + description?: Maybe<string>; + interfaces?: Thunk<Maybe<Array<GraphQLInterfaceType>>>; + fields: Thunk<GraphQLFieldConfigMap<TSource, TContext>>; + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: Maybe<GraphQLTypeResolver<TSource, TContext>>; + extensions?: Maybe<Readonly<GraphQLInterfaceTypeExtensions>>; + astNode?: Maybe<InterfaceTypeDefinitionNode>; + extensionASTNodes?: Maybe<ReadonlyArray<InterfaceTypeExtensionNode>>; +} + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLUnionTypeExtensions { + [attributeName: string]: any; +} + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * + */ +export class GraphQLUnionType { + name: string; + description: Maybe<string>; + resolveType: Maybe<GraphQLTypeResolver<any, any>>; + extensions: Maybe<Readonly<GraphQLUnionTypeExtensions>>; + astNode: Maybe<UnionTypeDefinitionNode>; + extensionASTNodes: Maybe<ReadonlyArray<UnionTypeExtensionNode>>; + + constructor(config: Readonly<GraphQLUnionTypeConfig<any, any>>); + getTypes(): Array<GraphQLObjectType>; + + toConfig(): GraphQLUnionTypeConfig<any, any> & { + types: Array<GraphQLObjectType>; + extensions: Maybe<Readonly<GraphQLUnionTypeExtensions>>; + extensionASTNodes: ReadonlyArray<UnionTypeExtensionNode>; + }; + + toString(): string; + toJSON(): string; + inspect(): string; +} + +export interface GraphQLUnionTypeConfig<TSource, TContext> { + name: string; + description?: Maybe<string>; + types: Thunk<Array<GraphQLObjectType>>; + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: Maybe<GraphQLTypeResolver<TSource, TContext>>; + extensions?: Maybe<Readonly<GraphQLUnionTypeExtensions>>; + astNode?: Maybe<UnionTypeDefinitionNode>; + extensionASTNodes?: Maybe<ReadonlyArray<UnionTypeExtensionNode>>; +} + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLEnumTypeExtensions { + [attributeName: string]: any; +} + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +export class GraphQLEnumType { + name: string; + description: Maybe<string>; + extensions: Maybe<Readonly<GraphQLEnumTypeExtensions>>; + astNode: Maybe<EnumTypeDefinitionNode>; + extensionASTNodes: Maybe<ReadonlyArray<EnumTypeExtensionNode>>; + + constructor(config: Readonly<GraphQLEnumTypeConfig>); + getValues(): Array<GraphQLEnumValue>; + getValue(name: string): Maybe<GraphQLEnumValue>; + serialize(value: any): Maybe<string>; + parseValue(value: any): Maybe<any>; + parseLiteral( + valueNode: ValueNode, + _variables: Maybe<{ [key: string]: any }>, + ): Maybe<any>; + + toConfig(): GraphQLEnumTypeConfig & { + extensions: Maybe<Readonly<GraphQLEnumTypeExtensions>>; + extensionASTNodes: ReadonlyArray<EnumTypeExtensionNode>; + }; + + toString(): string; + toJSON(): string; + inspect(): string; +} + +export interface GraphQLEnumTypeConfig { + name: string; + description?: Maybe<string>; + values: GraphQLEnumValueConfigMap; + extensions?: Maybe<Readonly<GraphQLEnumTypeExtensions>>; + astNode?: Maybe<EnumTypeDefinitionNode>; + extensionASTNodes?: Maybe<ReadonlyArray<EnumTypeExtensionNode>>; +} + +export interface GraphQLEnumValueConfigMap { + [key: string]: GraphQLEnumValueConfig; +} + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLEnumValueExtensions { + [attributeName: string]: any; +} + +export interface GraphQLEnumValueConfig { + description?: Maybe<string>; + value?: any; + deprecationReason?: Maybe<string>; + extensions?: Maybe<Readonly<GraphQLEnumValueExtensions>>; + astNode?: Maybe<EnumValueDefinitionNode>; +} + +export interface GraphQLEnumValue { + name: string; + description: Maybe<string>; + value: any; + deprecationReason: Maybe<string>; + extensions: Maybe<Readonly<GraphQLEnumValueExtensions>>; + astNode?: Maybe<EnumValueDefinitionNode>; + + // @deprecated and will be removed in v16 + isDeprecated: boolean; +} + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLInputObjectTypeExtensions { + [attributeName: string]: any; +} + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +export class GraphQLInputObjectType { + name: string; + description: Maybe<string>; + extensions: Maybe<Readonly<GraphQLInputObjectTypeExtensions>>; + astNode: Maybe<InputObjectTypeDefinitionNode>; + extensionASTNodes: Maybe<ReadonlyArray<InputObjectTypeExtensionNode>>; + + constructor(config: Readonly<GraphQLInputObjectTypeConfig>); + getFields(): GraphQLInputFieldMap; + + toConfig(): GraphQLInputObjectTypeConfig & { + fields: GraphQLInputFieldConfigMap; + extensions: Maybe<Readonly<GraphQLInputObjectTypeExtensions>>; + extensionASTNodes: ReadonlyArray<InputObjectTypeExtensionNode>; + }; + + toString(): string; + toJSON(): string; + inspect(): string; +} + +export interface GraphQLInputObjectTypeConfig { + name: string; + description?: Maybe<string>; + fields: Thunk<GraphQLInputFieldConfigMap>; + extensions?: Maybe<Readonly<GraphQLInputObjectTypeExtensions>>; + astNode?: Maybe<InputObjectTypeDefinitionNode>; + extensionASTNodes?: Maybe<ReadonlyArray<InputObjectTypeExtensionNode>>; +} + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLInputFieldExtensions { + [attributeName: string]: any; +} + +export interface GraphQLInputFieldConfig { + description?: Maybe<string>; + type: GraphQLInputType; + defaultValue?: any; + deprecationReason?: Maybe<string>; + extensions?: Maybe<Readonly<GraphQLInputFieldExtensions>>; + astNode?: Maybe<InputValueDefinitionNode>; +} + +export interface GraphQLInputFieldConfigMap { + [key: string]: GraphQLInputFieldConfig; +} + +export interface GraphQLInputField { + name: string; + description?: Maybe<string>; + type: GraphQLInputType; + defaultValue?: any; + deprecationReason: Maybe<string>; + extensions: Maybe<Readonly<GraphQLInputFieldExtensions>>; + astNode?: Maybe<InputValueDefinitionNode>; +} + +export function isRequiredInputField(field: GraphQLInputField): boolean; + +export interface GraphQLInputFieldMap { + [key: string]: GraphQLInputField; +} diff --git a/school/node_modules/graphql/type/definition.js b/school/node_modules/graphql/type/definition.js new file mode 100644 index 0000000..6d53cb7 --- /dev/null +++ b/school/node_modules/graphql/type/definition.js @@ -0,0 +1,1226 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isType = isType; +exports.assertType = assertType; +exports.isScalarType = isScalarType; +exports.assertScalarType = assertScalarType; +exports.isObjectType = isObjectType; +exports.assertObjectType = assertObjectType; +exports.isInterfaceType = isInterfaceType; +exports.assertInterfaceType = assertInterfaceType; +exports.isUnionType = isUnionType; +exports.assertUnionType = assertUnionType; +exports.isEnumType = isEnumType; +exports.assertEnumType = assertEnumType; +exports.isInputObjectType = isInputObjectType; +exports.assertInputObjectType = assertInputObjectType; +exports.isListType = isListType; +exports.assertListType = assertListType; +exports.isNonNullType = isNonNullType; +exports.assertNonNullType = assertNonNullType; +exports.isInputType = isInputType; +exports.assertInputType = assertInputType; +exports.isOutputType = isOutputType; +exports.assertOutputType = assertOutputType; +exports.isLeafType = isLeafType; +exports.assertLeafType = assertLeafType; +exports.isCompositeType = isCompositeType; +exports.assertCompositeType = assertCompositeType; +exports.isAbstractType = isAbstractType; +exports.assertAbstractType = assertAbstractType; +exports.GraphQLList = GraphQLList; +exports.GraphQLNonNull = GraphQLNonNull; +exports.isWrappingType = isWrappingType; +exports.assertWrappingType = assertWrappingType; +exports.isNullableType = isNullableType; +exports.assertNullableType = assertNullableType; +exports.getNullableType = getNullableType; +exports.isNamedType = isNamedType; +exports.assertNamedType = assertNamedType; +exports.getNamedType = getNamedType; +exports.argsToArgsConfig = argsToArgsConfig; +exports.isRequiredArgument = isRequiredArgument; +exports.isRequiredInputField = isRequiredInputField; +exports.GraphQLInputObjectType = exports.GraphQLEnumType = exports.GraphQLUnionType = exports.GraphQLInterfaceType = exports.GraphQLObjectType = exports.GraphQLScalarType = void 0; + +var _objectEntries = _interopRequireDefault(require("../polyfills/objectEntries.js")); + +var _symbols = require("../polyfills/symbols.js"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap.js")); + +var _mapValue = _interopRequireDefault(require("../jsutils/mapValue.js")); + +var _toObjMap = _interopRequireDefault(require("../jsutils/toObjMap.js")); + +var _devAssert = _interopRequireDefault(require("../jsutils/devAssert.js")); + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap.js")); + +var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf.js")); + +var _didYouMean = _interopRequireDefault(require("../jsutils/didYouMean.js")); + +var _isObjectLike = _interopRequireDefault(require("../jsutils/isObjectLike.js")); + +var _identityFunc = _interopRequireDefault(require("../jsutils/identityFunc.js")); + +var _defineInspect = _interopRequireDefault(require("../jsutils/defineInspect.js")); + +var _suggestionList = _interopRequireDefault(require("../jsutils/suggestionList.js")); + +var _GraphQLError = require("../error/GraphQLError.js"); + +var _kinds = require("../language/kinds.js"); + +var _printer = require("../language/printer.js"); + +var _valueFromASTUntyped = require("../utilities/valueFromASTUntyped.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function isType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type); +} + +function assertType(type) { + if (!isType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL type.")); + } + + return type; +} +/** + * There are predicates for each kind of GraphQL type. + */ + + +// eslint-disable-next-line no-redeclare +function isScalarType(type) { + return (0, _instanceOf.default)(type, GraphQLScalarType); +} + +function assertScalarType(type) { + if (!isScalarType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Scalar type.")); + } + + return type; +} + +// eslint-disable-next-line no-redeclare +function isObjectType(type) { + return (0, _instanceOf.default)(type, GraphQLObjectType); +} + +function assertObjectType(type) { + if (!isObjectType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Object type.")); + } + + return type; +} + +// eslint-disable-next-line no-redeclare +function isInterfaceType(type) { + return (0, _instanceOf.default)(type, GraphQLInterfaceType); +} + +function assertInterfaceType(type) { + if (!isInterfaceType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Interface type.")); + } + + return type; +} + +// eslint-disable-next-line no-redeclare +function isUnionType(type) { + return (0, _instanceOf.default)(type, GraphQLUnionType); +} + +function assertUnionType(type) { + if (!isUnionType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Union type.")); + } + + return type; +} + +// eslint-disable-next-line no-redeclare +function isEnumType(type) { + return (0, _instanceOf.default)(type, GraphQLEnumType); +} + +function assertEnumType(type) { + if (!isEnumType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Enum type.")); + } + + return type; +} + +// eslint-disable-next-line no-redeclare +function isInputObjectType(type) { + return (0, _instanceOf.default)(type, GraphQLInputObjectType); +} + +function assertInputObjectType(type) { + if (!isInputObjectType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Input Object type.")); + } + + return type; +} + +// eslint-disable-next-line no-redeclare +function isListType(type) { + return (0, _instanceOf.default)(type, GraphQLList); +} + +function assertListType(type) { + if (!isListType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL List type.")); + } + + return type; +} + +// eslint-disable-next-line no-redeclare +function isNonNullType(type) { + return (0, _instanceOf.default)(type, GraphQLNonNull); +} + +function assertNonNullType(type) { + if (!isNonNullType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Non-Null type.")); + } + + return type; +} +/** + * These types may be used as input types for arguments and directives. + */ + + +function isInputType(type) { + return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType); +} + +function assertInputType(type) { + if (!isInputType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL input type.")); + } + + return type; +} +/** + * These types may be used as output types as the result of fields. + */ + + +function isOutputType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType); +} + +function assertOutputType(type) { + if (!isOutputType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL output type.")); + } + + return type; +} +/** + * These types may describe types which may be leaf values. + */ + + +function isLeafType(type) { + return isScalarType(type) || isEnumType(type); +} + +function assertLeafType(type) { + if (!isLeafType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL leaf type.")); + } + + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + + +function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} + +function assertCompositeType(type) { + if (!isCompositeType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL composite type.")); + } + + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + + +function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); +} + +function assertAbstractType(type) { + if (!isAbstractType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL abstract type.")); + } + + return type; +} +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(PersonType) }, + * children: { type: new GraphQLList(PersonType) }, + * }) + * }) + * + */ +// FIXME: workaround to fix issue with Babel parser + +/* :: +declare class GraphQLList<+T: GraphQLType> { + +ofType: T; + static <T>(ofType: T): GraphQLList<T>; + // Note: constructors cannot be used for covariant types. Drop the "new". + constructor(ofType: GraphQLType): void; +} +*/ + + +function GraphQLList(ofType) { + // istanbul ignore else (to be removed in v16.0.0) + if (this instanceof GraphQLList) { + this.ofType = assertType(ofType); + } else { + return new GraphQLList(ofType); + } +} // Need to cast through any to alter the prototype. + + +GraphQLList.prototype.toString = function toString() { + return '[' + String(this.ofType) + ']'; +}; + +GraphQLList.prototype.toJSON = function toJSON() { + return this.toString(); +}; + +Object.defineProperty(GraphQLList.prototype, _symbols.SYMBOL_TO_STRING_TAG, { + get: function get() { + return 'GraphQLList'; + } +}); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +(0, _defineInspect.default)(GraphQLList); +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ +// FIXME: workaround to fix issue with Babel parser + +/* :: +declare class GraphQLNonNull<+T: GraphQLNullableType> { + +ofType: T; + static <T>(ofType: T): GraphQLNonNull<T>; + // Note: constructors cannot be used for covariant types. Drop the "new". + constructor(ofType: GraphQLType): void; +} +*/ + +function GraphQLNonNull(ofType) { + // istanbul ignore else (to be removed in v16.0.0) + if (this instanceof GraphQLNonNull) { + this.ofType = assertNullableType(ofType); + } else { + return new GraphQLNonNull(ofType); + } +} // Need to cast through any to alter the prototype. + + +GraphQLNonNull.prototype.toString = function toString() { + return String(this.ofType) + '!'; +}; + +GraphQLNonNull.prototype.toJSON = function toJSON() { + return this.toString(); +}; + +Object.defineProperty(GraphQLNonNull.prototype, _symbols.SYMBOL_TO_STRING_TAG, { + get: function get() { + return 'GraphQLNonNull'; + } +}); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +(0, _defineInspect.default)(GraphQLNonNull); +/** + * These types wrap and modify other types + */ + +function isWrappingType(type) { + return isListType(type) || isNonNullType(type); +} + +function assertWrappingType(type) { + if (!isWrappingType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL wrapping type.")); + } + + return type; +} +/** + * These types can all accept null as a value. + */ + + +function isNullableType(type) { + return isType(type) && !isNonNullType(type); +} + +function assertNullableType(type) { + if (!isNullableType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL nullable type.")); + } + + return type; +} +/* eslint-disable no-redeclare */ + + +function getNullableType(type) { + /* eslint-enable no-redeclare */ + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} +/** + * These named types do not include modifiers like List or NonNull. + */ + + +function isNamedType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type); +} + +function assertNamedType(type) { + if (!isNamedType(type)) { + throw new Error("Expected ".concat((0, _inspect.default)(type), " to be a GraphQL named type.")); + } + + return type; +} +/* eslint-disable no-redeclare */ + + +function getNamedType(type) { + /* eslint-enable no-redeclare */ + if (type) { + var unwrappedType = type; + + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + + return unwrappedType; + } +} +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ + + +function resolveThunk(thunk) { + // $FlowFixMe[incompatible-use] + return typeof thunk === 'function' ? thunk() : thunk; +} + +function undefineIfEmpty(arr) { + return arr && arr.length > 0 ? arr : undefined; +} +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function does not return a value (i.e. it returns + * `undefined`) then an error will be raised and a `null` value will be returned + * in the response. If the serialize function returns `null`, then no error will + * be included in the response. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (value % 2 === 1) { + * return value; + * } + * } + * }); + * + */ + + +var GraphQLScalarType = /*#__PURE__*/function () { + function GraphQLScalarType(config) { + var _config$parseValue, _config$serialize, _config$parseLiteral; + + var parseValue = (_config$parseValue = config.parseValue) !== null && _config$parseValue !== void 0 ? _config$parseValue : _identityFunc.default; + this.name = config.name; + this.description = config.description; + this.specifiedByUrl = config.specifiedByUrl; + this.serialize = (_config$serialize = config.serialize) !== null && _config$serialize !== void 0 ? _config$serialize : _identityFunc.default; + this.parseValue = parseValue; + this.parseLiteral = (_config$parseLiteral = config.parseLiteral) !== null && _config$parseLiteral !== void 0 ? _config$parseLiteral : function (node, variables) { + return parseValue((0, _valueFromASTUntyped.valueFromASTUntyped)(node, variables)); + }; + this.extensions = config.extensions && (0, _toObjMap.default)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + typeof config.name === 'string' || (0, _devAssert.default)(0, 'Must provide name.'); + config.specifiedByUrl == null || typeof config.specifiedByUrl === 'string' || (0, _devAssert.default)(0, "".concat(this.name, " must provide \"specifiedByUrl\" as a string, ") + "but got: ".concat((0, _inspect.default)(config.specifiedByUrl), ".")); + config.serialize == null || typeof config.serialize === 'function' || (0, _devAssert.default)(0, "".concat(this.name, " must provide \"serialize\" function. If this custom Scalar is also used as an input type, ensure \"parseValue\" and \"parseLiteral\" functions are also provided.")); + + if (config.parseLiteral) { + typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function' || (0, _devAssert.default)(0, "".concat(this.name, " must provide both \"parseValue\" and \"parseLiteral\" functions.")); + } + } + + var _proto = GraphQLScalarType.prototype; + + _proto.toConfig = function toConfig() { + var _this$extensionASTNod; + + return { + name: this.name, + description: this.description, + specifiedByUrl: this.specifiedByUrl, + serialize: this.serialize, + parseValue: this.parseValue, + parseLiteral: this.parseLiteral, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod = this.extensionASTNodes) !== null && _this$extensionASTNod !== void 0 ? _this$extensionASTNod : [] + }; + }; + + _proto.toString = function toString() { + return this.name; + }; + + _proto.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLScalarType, [{ + key: _symbols.SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLScalarType'; + } + }]); + + return GraphQLScalarType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + + +exports.GraphQLScalarType = GraphQLScalarType; +(0, _defineInspect.default)(GraphQLScalarType); + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * + */ +var GraphQLObjectType = /*#__PURE__*/function () { + function GraphQLObjectType(config) { + this.name = config.name; + this.description = config.description; + this.isTypeOf = config.isTypeOf; + this.extensions = config.extensions && (0, _toObjMap.default)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + typeof config.name === 'string' || (0, _devAssert.default)(0, 'Must provide name.'); + config.isTypeOf == null || typeof config.isTypeOf === 'function' || (0, _devAssert.default)(0, "".concat(this.name, " must provide \"isTypeOf\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.isTypeOf), ".")); + } + + var _proto2 = GraphQLObjectType.prototype; + + _proto2.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto2.getInterfaces = function getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + }; + + _proto2.toConfig = function toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + isTypeOf: this.isTypeOf, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes || [] + }; + }; + + _proto2.toString = function toString() { + return this.name; + }; + + _proto2.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLObjectType, [{ + key: _symbols.SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLObjectType'; + } + }]); + + return GraphQLObjectType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + + +exports.GraphQLObjectType = GraphQLObjectType; +(0, _defineInspect.default)(GraphQLObjectType); + +function defineInterfaces(config) { + var _resolveThunk; + + var interfaces = (_resolveThunk = resolveThunk(config.interfaces)) !== null && _resolveThunk !== void 0 ? _resolveThunk : []; + Array.isArray(interfaces) || (0, _devAssert.default)(0, "".concat(config.name, " interfaces must be an Array or a function which returns an Array.")); + return interfaces; +} + +function defineFieldMap(config) { + var fieldMap = resolveThunk(config.fields); + isPlainObj(fieldMap) || (0, _devAssert.default)(0, "".concat(config.name, " fields must be an object with field names as keys or a function which returns such an object.")); + return (0, _mapValue.default)(fieldMap, function (fieldConfig, fieldName) { + var _fieldConfig$args; + + isPlainObj(fieldConfig) || (0, _devAssert.default)(0, "".concat(config.name, ".").concat(fieldName, " field config must be an object.")); + !('isDeprecated' in fieldConfig) || (0, _devAssert.default)(0, "".concat(config.name, ".").concat(fieldName, " should provide \"deprecationReason\" instead of \"isDeprecated\".")); + fieldConfig.resolve == null || typeof fieldConfig.resolve === 'function' || (0, _devAssert.default)(0, "".concat(config.name, ".").concat(fieldName, " field resolver must be a function if ") + "provided, but got: ".concat((0, _inspect.default)(fieldConfig.resolve), ".")); + var argsConfig = (_fieldConfig$args = fieldConfig.args) !== null && _fieldConfig$args !== void 0 ? _fieldConfig$args : {}; + isPlainObj(argsConfig) || (0, _devAssert.default)(0, "".concat(config.name, ".").concat(fieldName, " args must be an object with argument names as keys.")); + var args = (0, _objectEntries.default)(argsConfig).map(function (_ref) { + var argName = _ref[0], + argConfig = _ref[1]; + return { + name: argName, + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: argConfig.extensions && (0, _toObjMap.default)(argConfig.extensions), + astNode: argConfig.astNode + }; + }); + return { + name: fieldName, + description: fieldConfig.description, + type: fieldConfig.type, + args: args, + resolve: fieldConfig.resolve, + subscribe: fieldConfig.subscribe, + isDeprecated: fieldConfig.deprecationReason != null, + deprecationReason: fieldConfig.deprecationReason, + extensions: fieldConfig.extensions && (0, _toObjMap.default)(fieldConfig.extensions), + astNode: fieldConfig.astNode + }; + }); +} + +function isPlainObj(obj) { + return (0, _isObjectLike.default)(obj) && !Array.isArray(obj); +} + +function fieldsToFieldsConfig(fields) { + return (0, _mapValue.default)(fields, function (field) { + return { + description: field.description, + type: field.type, + args: argsToArgsConfig(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode + }; + }); +} +/** + * @internal + */ + + +function argsToArgsConfig(args) { + return (0, _keyValMap.default)(args, function (arg) { + return arg.name; + }, function (arg) { + return { + description: arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + deprecationReason: arg.deprecationReason, + extensions: arg.extensions, + astNode: arg.astNode + }; + }); +} + +function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * + */ +var GraphQLInterfaceType = /*#__PURE__*/function () { + function GraphQLInterfaceType(config) { + this.name = config.name; + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = config.extensions && (0, _toObjMap.default)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + typeof config.name === 'string' || (0, _devAssert.default)(0, 'Must provide name.'); + config.resolveType == null || typeof config.resolveType === 'function' || (0, _devAssert.default)(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.resolveType), ".")); + } + + var _proto3 = GraphQLInterfaceType.prototype; + + _proto3.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto3.getInterfaces = function getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + }; + + _proto3.toConfig = function toConfig() { + var _this$extensionASTNod2; + + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod2 = this.extensionASTNodes) !== null && _this$extensionASTNod2 !== void 0 ? _this$extensionASTNod2 : [] + }; + }; + + _proto3.toString = function toString() { + return this.name; + }; + + _proto3.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLInterfaceType, [{ + key: _symbols.SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLInterfaceType'; + } + }]); + + return GraphQLInterfaceType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + + +exports.GraphQLInterfaceType = GraphQLInterfaceType; +(0, _defineInspect.default)(GraphQLInterfaceType); + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * + */ +var GraphQLUnionType = /*#__PURE__*/function () { + function GraphQLUnionType(config) { + this.name = config.name; + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = config.extensions && (0, _toObjMap.default)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + this._types = defineTypes.bind(undefined, config); + typeof config.name === 'string' || (0, _devAssert.default)(0, 'Must provide name.'); + config.resolveType == null || typeof config.resolveType === 'function' || (0, _devAssert.default)(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.resolveType), ".")); + } + + var _proto4 = GraphQLUnionType.prototype; + + _proto4.getTypes = function getTypes() { + if (typeof this._types === 'function') { + this._types = this._types(); + } + + return this._types; + }; + + _proto4.toConfig = function toConfig() { + var _this$extensionASTNod3; + + return { + name: this.name, + description: this.description, + types: this.getTypes(), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod3 = this.extensionASTNodes) !== null && _this$extensionASTNod3 !== void 0 ? _this$extensionASTNod3 : [] + }; + }; + + _proto4.toString = function toString() { + return this.name; + }; + + _proto4.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLUnionType, [{ + key: _symbols.SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLUnionType'; + } + }]); + + return GraphQLUnionType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + + +exports.GraphQLUnionType = GraphQLUnionType; +(0, _defineInspect.default)(GraphQLUnionType); + +function defineTypes(config) { + var types = resolveThunk(config.types); + Array.isArray(types) || (0, _devAssert.default)(0, "Must provide Array of types or a function which returns such an array for Union ".concat(config.name, ".")); + return types; +} + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +var GraphQLEnumType +/* <T> */ += /*#__PURE__*/function () { + function GraphQLEnumType(config) { + this.name = config.name; + this.description = config.description; + this.extensions = config.extensions && (0, _toObjMap.default)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + this._values = defineEnumValues(this.name, config.values); + this._valueLookup = new Map(this._values.map(function (enumValue) { + return [enumValue.value, enumValue]; + })); + this._nameLookup = (0, _keyMap.default)(this._values, function (value) { + return value.name; + }); + typeof config.name === 'string' || (0, _devAssert.default)(0, 'Must provide name.'); + } + + var _proto5 = GraphQLEnumType.prototype; + + _proto5.getValues = function getValues() { + return this._values; + }; + + _proto5.getValue = function getValue(name) { + return this._nameLookup[name]; + }; + + _proto5.serialize = function serialize(outputValue) { + var enumValue = this._valueLookup.get(outputValue); + + if (enumValue === undefined) { + throw new _GraphQLError.GraphQLError("Enum \"".concat(this.name, "\" cannot represent value: ").concat((0, _inspect.default)(outputValue))); + } + + return enumValue.name; + }; + + _proto5.parseValue = function parseValue(inputValue) + /* T */ + { + if (typeof inputValue !== 'string') { + var valueStr = (0, _inspect.default)(inputValue); + throw new _GraphQLError.GraphQLError("Enum \"".concat(this.name, "\" cannot represent non-string value: ").concat(valueStr, ".") + didYouMeanEnumValue(this, valueStr)); + } + + var enumValue = this.getValue(inputValue); + + if (enumValue == null) { + throw new _GraphQLError.GraphQLError("Value \"".concat(inputValue, "\" does not exist in \"").concat(this.name, "\" enum.") + didYouMeanEnumValue(this, inputValue)); + } + + return enumValue.value; + }; + + _proto5.parseLiteral = function parseLiteral(valueNode, _variables) + /* T */ + { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind !== _kinds.Kind.ENUM) { + var valueStr = (0, _printer.print)(valueNode); + throw new _GraphQLError.GraphQLError("Enum \"".concat(this.name, "\" cannot represent non-enum value: ").concat(valueStr, ".") + didYouMeanEnumValue(this, valueStr), valueNode); + } + + var enumValue = this.getValue(valueNode.value); + + if (enumValue == null) { + var _valueStr = (0, _printer.print)(valueNode); + + throw new _GraphQLError.GraphQLError("Value \"".concat(_valueStr, "\" does not exist in \"").concat(this.name, "\" enum.") + didYouMeanEnumValue(this, _valueStr), valueNode); + } + + return enumValue.value; + }; + + _proto5.toConfig = function toConfig() { + var _this$extensionASTNod4; + + var values = (0, _keyValMap.default)(this.getValues(), function (value) { + return value.name; + }, function (value) { + return { + description: value.description, + value: value.value, + deprecationReason: value.deprecationReason, + extensions: value.extensions, + astNode: value.astNode + }; + }); + return { + name: this.name, + description: this.description, + values: values, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod4 = this.extensionASTNodes) !== null && _this$extensionASTNod4 !== void 0 ? _this$extensionASTNod4 : [] + }; + }; + + _proto5.toString = function toString() { + return this.name; + }; + + _proto5.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLEnumType, [{ + key: _symbols.SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLEnumType'; + } + }]); + + return GraphQLEnumType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + + +exports.GraphQLEnumType = GraphQLEnumType; +(0, _defineInspect.default)(GraphQLEnumType); + +function didYouMeanEnumValue(enumType, unknownValueStr) { + var allNames = enumType.getValues().map(function (value) { + return value.name; + }); + var suggestedValues = (0, _suggestionList.default)(unknownValueStr, allNames); + return (0, _didYouMean.default)('the enum value', suggestedValues); +} + +function defineEnumValues(typeName, valueMap) { + isPlainObj(valueMap) || (0, _devAssert.default)(0, "".concat(typeName, " values must be an object with value names as keys.")); + return (0, _objectEntries.default)(valueMap).map(function (_ref2) { + var valueName = _ref2[0], + valueConfig = _ref2[1]; + isPlainObj(valueConfig) || (0, _devAssert.default)(0, "".concat(typeName, ".").concat(valueName, " must refer to an object with a \"value\" key ") + "representing an internal value but got: ".concat((0, _inspect.default)(valueConfig), ".")); + !('isDeprecated' in valueConfig) || (0, _devAssert.default)(0, "".concat(typeName, ".").concat(valueName, " should provide \"deprecationReason\" instead of \"isDeprecated\".")); + return { + name: valueName, + description: valueConfig.description, + value: valueConfig.value !== undefined ? valueConfig.value : valueName, + isDeprecated: valueConfig.deprecationReason != null, + deprecationReason: valueConfig.deprecationReason, + extensions: valueConfig.extensions && (0, _toObjMap.default)(valueConfig.extensions), + astNode: valueConfig.astNode + }; + }); +} + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +var GraphQLInputObjectType = /*#__PURE__*/function () { + function GraphQLInputObjectType(config) { + this.name = config.name; + this.description = config.description; + this.extensions = config.extensions && (0, _toObjMap.default)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + this._fields = defineInputFieldMap.bind(undefined, config); + typeof config.name === 'string' || (0, _devAssert.default)(0, 'Must provide name.'); + } + + var _proto6 = GraphQLInputObjectType.prototype; + + _proto6.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto6.toConfig = function toConfig() { + var _this$extensionASTNod5; + + var fields = (0, _mapValue.default)(this.getFields(), function (field) { + return { + description: field.description, + type: field.type, + defaultValue: field.defaultValue, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode + }; + }); + return { + name: this.name, + description: this.description, + fields: fields, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod5 = this.extensionASTNodes) !== null && _this$extensionASTNod5 !== void 0 ? _this$extensionASTNod5 : [] + }; + }; + + _proto6.toString = function toString() { + return this.name; + }; + + _proto6.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLInputObjectType, [{ + key: _symbols.SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLInputObjectType'; + } + }]); + + return GraphQLInputObjectType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + + +exports.GraphQLInputObjectType = GraphQLInputObjectType; +(0, _defineInspect.default)(GraphQLInputObjectType); + +function defineInputFieldMap(config) { + var fieldMap = resolveThunk(config.fields); + isPlainObj(fieldMap) || (0, _devAssert.default)(0, "".concat(config.name, " fields must be an object with field names as keys or a function which returns such an object.")); + return (0, _mapValue.default)(fieldMap, function (fieldConfig, fieldName) { + !('resolve' in fieldConfig) || (0, _devAssert.default)(0, "".concat(config.name, ".").concat(fieldName, " field has a resolve property, but Input Types cannot define resolvers.")); + return { + name: fieldName, + description: fieldConfig.description, + type: fieldConfig.type, + defaultValue: fieldConfig.defaultValue, + deprecationReason: fieldConfig.deprecationReason, + extensions: fieldConfig.extensions && (0, _toObjMap.default)(fieldConfig.extensions), + astNode: fieldConfig.astNode + }; + }); +} + +function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; +} diff --git a/school/node_modules/graphql/type/definition.js.flow b/school/node_modules/graphql/type/definition.js.flow new file mode 100644 index 0000000..1f71d9c --- /dev/null +++ b/school/node_modules/graphql/type/definition.js.flow @@ -0,0 +1,1659 @@ +// @flow strict +import objectEntries from '../polyfills/objectEntries'; +import { SYMBOL_TO_STRING_TAG } from '../polyfills/symbols'; + +import type { Path } from '../jsutils/Path'; +import type { PromiseOrValue } from '../jsutils/PromiseOrValue'; +import type { + ObjMap, + ReadOnlyObjMap, + ReadOnlyObjMapLike, +} from '../jsutils/ObjMap'; +import inspect from '../jsutils/inspect'; +import keyMap from '../jsutils/keyMap'; +import mapValue from '../jsutils/mapValue'; +import toObjMap from '../jsutils/toObjMap'; +import devAssert from '../jsutils/devAssert'; +import keyValMap from '../jsutils/keyValMap'; +import instanceOf from '../jsutils/instanceOf'; +import didYouMean from '../jsutils/didYouMean'; +import isObjectLike from '../jsutils/isObjectLike'; +import identityFunc from '../jsutils/identityFunc'; +import defineInspect from '../jsutils/defineInspect'; +import suggestionList from '../jsutils/suggestionList'; + +import { GraphQLError } from '../error/GraphQLError'; + +import { Kind } from '../language/kinds'; +import { print } from '../language/printer'; +import type { + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, + OperationDefinitionNode, + FieldNode, + FragmentDefinitionNode, + ValueNode, +} from '../language/ast'; + +import { valueFromASTUntyped } from '../utilities/valueFromASTUntyped'; + +import type { GraphQLSchema } from './schema'; + +// Predicates & Assertions + +/** + * These are all of the possible kinds of types. + */ +export type GraphQLType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList<any> + | GraphQLNonNull<any>; + +export function isType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) || + isListType(type) || + isNonNullType(type) + ); +} + +export function assertType(type: mixed): GraphQLType { + if (!isType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL type.`); + } + return type; +} + +/** + * There are predicates for each kind of GraphQL type. + */ + +declare function isScalarType(type: mixed): boolean %checks(type instanceof + GraphQLScalarType); +// eslint-disable-next-line no-redeclare +export function isScalarType(type) { + return instanceOf(type, GraphQLScalarType); +} + +export function assertScalarType(type: mixed): GraphQLScalarType { + if (!isScalarType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL Scalar type.`); + } + return type; +} + +declare function isObjectType(type: mixed): boolean %checks(type instanceof + GraphQLObjectType); +// eslint-disable-next-line no-redeclare +export function isObjectType(type) { + return instanceOf(type, GraphQLObjectType); +} + +export function assertObjectType(type: mixed): GraphQLObjectType { + if (!isObjectType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL Object type.`); + } + return type; +} + +declare function isInterfaceType(type: mixed): boolean %checks(type instanceof + GraphQLInterfaceType); +// eslint-disable-next-line no-redeclare +export function isInterfaceType(type) { + return instanceOf(type, GraphQLInterfaceType); +} + +export function assertInterfaceType(type: mixed): GraphQLInterfaceType { + if (!isInterfaceType(type)) { + throw new Error( + `Expected ${inspect(type)} to be a GraphQL Interface type.`, + ); + } + return type; +} + +declare function isUnionType(type: mixed): boolean %checks(type instanceof + GraphQLUnionType); +// eslint-disable-next-line no-redeclare +export function isUnionType(type) { + return instanceOf(type, GraphQLUnionType); +} + +export function assertUnionType(type: mixed): GraphQLUnionType { + if (!isUnionType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL Union type.`); + } + return type; +} + +declare function isEnumType(type: mixed): boolean %checks(type instanceof + GraphQLEnumType); +// eslint-disable-next-line no-redeclare +export function isEnumType(type) { + return instanceOf(type, GraphQLEnumType); +} + +export function assertEnumType(type: mixed): GraphQLEnumType { + if (!isEnumType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL Enum type.`); + } + return type; +} + +declare function isInputObjectType(type: mixed): boolean %checks(type instanceof + GraphQLInputObjectType); +// eslint-disable-next-line no-redeclare +export function isInputObjectType(type) { + return instanceOf(type, GraphQLInputObjectType); +} + +export function assertInputObjectType(type: mixed): GraphQLInputObjectType { + if (!isInputObjectType(type)) { + throw new Error( + `Expected ${inspect(type)} to be a GraphQL Input Object type.`, + ); + } + return type; +} + +declare function isListType(type: mixed): boolean %checks(type instanceof + GraphQLList); +// eslint-disable-next-line no-redeclare +export function isListType(type) { + return instanceOf(type, GraphQLList); +} + +export function assertListType(type: mixed): GraphQLList<any> { + if (!isListType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL List type.`); + } + return type; +} + +declare function isNonNullType(type: mixed): boolean %checks(type instanceof + GraphQLNonNull); +// eslint-disable-next-line no-redeclare +export function isNonNullType(type) { + return instanceOf(type, GraphQLNonNull); +} + +export function assertNonNullType(type: mixed): GraphQLNonNull<any> { + if (!isNonNullType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL Non-Null type.`); + } + return type; +} + +/** + * These types may be used as input types for arguments and directives. + */ +export type GraphQLInputType = + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList<GraphQLInputType> + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList<GraphQLInputType>, + >; + +export function isInputType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isEnumType(type) || + isInputObjectType(type) || + (isWrappingType(type) && isInputType(type.ofType)) + ); +} + +export function assertInputType(type: mixed): GraphQLInputType { + if (!isInputType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL input type.`); + } + return type; +} + +/** + * These types may be used as output types as the result of fields. + */ +export type GraphQLOutputType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList<GraphQLOutputType> + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList<GraphQLOutputType>, + >; + +export function isOutputType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + (isWrappingType(type) && isOutputType(type.ofType)) + ); +} + +export function assertOutputType(type: mixed): GraphQLOutputType { + if (!isOutputType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL output type.`); + } + return type; +} + +/** + * These types may describe types which may be leaf values. + */ +export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; + +export function isLeafType(type: mixed): boolean %checks { + return isScalarType(type) || isEnumType(type); +} + +export function assertLeafType(type: mixed): GraphQLLeafType { + if (!isLeafType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL leaf type.`); + } + return type; +} + +/** + * These types may describe the parent context of a selection set. + */ +export type GraphQLCompositeType = + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType; + +export function isCompositeType(type: mixed): boolean %checks { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} + +export function assertCompositeType(type: mixed): GraphQLCompositeType { + if (!isCompositeType(type)) { + throw new Error( + `Expected ${inspect(type)} to be a GraphQL composite type.`, + ); + } + return type; +} + +/** + * These types may describe the parent context of a selection set. + */ +export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; + +export function isAbstractType(type: mixed): boolean %checks { + return isInterfaceType(type) || isUnionType(type); +} + +export function assertAbstractType(type: mixed): GraphQLAbstractType { + if (!isAbstractType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL abstract type.`); + } + return type; +} + +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(PersonType) }, + * children: { type: new GraphQLList(PersonType) }, + * }) + * }) + * + */ +// FIXME: workaround to fix issue with Babel parser +/* :: +declare class GraphQLList<+T: GraphQLType> { + +ofType: T; + static <T>(ofType: T): GraphQLList<T>; + // Note: constructors cannot be used for covariant types. Drop the "new". + constructor(ofType: GraphQLType): void; +} +*/ + +export function GraphQLList(ofType) { + // istanbul ignore else (to be removed in v16.0.0) + if (this instanceof GraphQLList) { + this.ofType = assertType(ofType); + } else { + return new GraphQLList(ofType); + } +} + +// Need to cast through any to alter the prototype. +(GraphQLList.prototype: any).toString = function toString() { + return '[' + String(this.ofType) + ']'; +}; + +(GraphQLList.prototype: any).toJSON = function toJSON() { + return this.toString(); +}; + +Object.defineProperty(GraphQLList.prototype, SYMBOL_TO_STRING_TAG, { + get() { + return 'GraphQLList'; + }, +}); + +// Print a simplified form when appearing in `inspect` and `util.inspect`. +defineInspect(GraphQLList); + +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ +// FIXME: workaround to fix issue with Babel parser +/* :: +declare class GraphQLNonNull<+T: GraphQLNullableType> { + +ofType: T; + static <T>(ofType: T): GraphQLNonNull<T>; + // Note: constructors cannot be used for covariant types. Drop the "new". + constructor(ofType: GraphQLType): void; +} +*/ + +export function GraphQLNonNull(ofType) { + // istanbul ignore else (to be removed in v16.0.0) + if (this instanceof GraphQLNonNull) { + this.ofType = assertNullableType(ofType); + } else { + return new GraphQLNonNull(ofType); + } +} + +// Need to cast through any to alter the prototype. +(GraphQLNonNull.prototype: any).toString = function toString() { + return String(this.ofType) + '!'; +}; + +(GraphQLNonNull.prototype: any).toJSON = function toJSON() { + return this.toString(); +}; + +Object.defineProperty(GraphQLNonNull.prototype, SYMBOL_TO_STRING_TAG, { + get() { + return 'GraphQLNonNull'; + }, +}); + +// Print a simplified form when appearing in `inspect` and `util.inspect`. +defineInspect(GraphQLNonNull); + +/** + * These types wrap and modify other types + */ + +export type GraphQLWrappingType = GraphQLList<any> | GraphQLNonNull<any>; + +export function isWrappingType(type: mixed): boolean %checks { + return isListType(type) || isNonNullType(type); +} + +export function assertWrappingType(type: mixed): GraphQLWrappingType { + if (!isWrappingType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL wrapping type.`); + } + return type; +} + +/** + * These types can all accept null as a value. + */ +export type GraphQLNullableType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList<any>; + +export function isNullableType(type: mixed): boolean %checks { + return isType(type) && !isNonNullType(type); +} + +export function assertNullableType(type: mixed): GraphQLNullableType { + if (!isNullableType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL nullable type.`); + } + return type; +} + +/* eslint-disable no-redeclare */ +declare function getNullableType(type: void | null): void; +declare function getNullableType<T: GraphQLNullableType>(type: T): T; +declare function getNullableType<T>(type: GraphQLNonNull<T>): T; +export function getNullableType(type) { + /* eslint-enable no-redeclare */ + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} + +/** + * These named types do not include modifiers like List or NonNull. + */ +export type GraphQLNamedType = GraphQLNamedInputType | GraphQLNamedOutputType; + +export type GraphQLNamedInputType = + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType; + +export type GraphQLNamedOutputType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType; + +export function isNamedType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) + ); +} + +export function assertNamedType(type: mixed): GraphQLNamedType { + if (!isNamedType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL named type.`); + } + return type; +} + +/* eslint-disable no-redeclare */ +declare function getNamedType(type: void | null): void; +declare function getNamedType(type: GraphQLInputType): GraphQLNamedInputType; +declare function getNamedType(type: GraphQLOutputType): GraphQLNamedOutputType; +declare function getNamedType(type: GraphQLType): GraphQLNamedType; +export function getNamedType(type) { + /* eslint-enable no-redeclare */ + if (type) { + let unwrappedType = type; + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + return unwrappedType; + } +} + +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ +export type Thunk<+T> = (() => T) | T; + +function resolveThunk<+T>(thunk: Thunk<T>): T { + // $FlowFixMe[incompatible-use] + return typeof thunk === 'function' ? thunk() : thunk; +} + +function undefineIfEmpty<T>(arr: ?$ReadOnlyArray<T>): ?$ReadOnlyArray<T> { + return arr && arr.length > 0 ? arr : undefined; +} + +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function does not return a value (i.e. it returns + * `undefined`) then an error will be raised and a `null` value will be returned + * in the response. If the serialize function returns `null`, then no error will + * be included in the response. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (value % 2 === 1) { + * return value; + * } + * } + * }); + * + */ +export class GraphQLScalarType { + name: string; + description: ?string; + specifiedByUrl: ?string; + serialize: GraphQLScalarSerializer<mixed>; + parseValue: GraphQLScalarValueParser<mixed>; + parseLiteral: GraphQLScalarLiteralParser<mixed>; + extensions: ?ReadOnlyObjMap<mixed>; + astNode: ?ScalarTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray<ScalarTypeExtensionNode>; + + constructor(config: $ReadOnly<GraphQLScalarTypeConfig<mixed, mixed>>) { + const parseValue = config.parseValue ?? identityFunc; + this.name = config.name; + this.description = config.description; + this.specifiedByUrl = config.specifiedByUrl; + this.serialize = config.serialize ?? identityFunc; + this.parseValue = parseValue; + this.parseLiteral = + config.parseLiteral ?? + ((node, variables) => parseValue(valueFromASTUntyped(node, variables))); + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + + devAssert(typeof config.name === 'string', 'Must provide name.'); + + devAssert( + config.specifiedByUrl == null || + typeof config.specifiedByUrl === 'string', + `${this.name} must provide "specifiedByUrl" as a string, ` + + `but got: ${inspect(config.specifiedByUrl)}.`, + ); + + devAssert( + config.serialize == null || typeof config.serialize === 'function', + `${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`, + ); + + if (config.parseLiteral) { + devAssert( + typeof config.parseValue === 'function' && + typeof config.parseLiteral === 'function', + `${this.name} must provide both "parseValue" and "parseLiteral" functions.`, + ); + } + } + + toConfig(): GraphQLScalarTypeNormalizedConfig { + return { + name: this.name, + description: this.description, + specifiedByUrl: this.specifiedByUrl, + serialize: this.serialize, + parseValue: this.parseValue, + parseLiteral: this.parseLiteral, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes ?? [], + }; + } + + toString(): string { + return this.name; + } + + toJSON(): string { + return this.toString(); + } + + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + get [SYMBOL_TO_STRING_TAG]() { + return 'GraphQLScalarType'; + } +} + +// Print a simplified form when appearing in `inspect` and `util.inspect`. +defineInspect(GraphQLScalarType); + +export type GraphQLScalarSerializer<TExternal> = ( + outputValue: mixed, +) => ?TExternal; + +export type GraphQLScalarValueParser<TInternal> = ( + inputValue: mixed, +) => ?TInternal; + +export type GraphQLScalarLiteralParser<TInternal> = ( + valueNode: ValueNode, + variables: ?ObjMap<mixed>, +) => ?TInternal; + +export type GraphQLScalarTypeConfig<TInternal, TExternal> = {| + name: string, + description?: ?string, + specifiedByUrl?: ?string, + // Serializes an internal value to include in a response. + serialize?: GraphQLScalarSerializer<TExternal>, + // Parses an externally provided value to use as an input. + parseValue?: GraphQLScalarValueParser<TInternal>, + // Parses an externally provided literal value to use as an input. + parseLiteral?: GraphQLScalarLiteralParser<TInternal>, + extensions?: ?ReadOnlyObjMapLike<mixed>, + astNode?: ?ScalarTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray<ScalarTypeExtensionNode>, +|}; + +type GraphQLScalarTypeNormalizedConfig = {| + ...GraphQLScalarTypeConfig<mixed, mixed>, + serialize: GraphQLScalarSerializer<mixed>, + parseValue: GraphQLScalarValueParser<mixed>, + parseLiteral: GraphQLScalarLiteralParser<mixed>, + extensions: ?ReadOnlyObjMap<mixed>, + extensionASTNodes: $ReadOnlyArray<ScalarTypeExtensionNode>, +|}; + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * + */ +export class GraphQLObjectType { + name: string; + description: ?string; + isTypeOf: ?GraphQLIsTypeOfFn<any, any>; + extensions: ?ReadOnlyObjMap<mixed>; + astNode: ?ObjectTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray<ObjectTypeExtensionNode>; + + _fields: Thunk<GraphQLFieldMap<any, any>>; + _interfaces: Thunk<Array<GraphQLInterfaceType>>; + + constructor(config: $ReadOnly<GraphQLObjectTypeConfig<any, any>>) { + this.name = config.name; + this.description = config.description; + this.isTypeOf = config.isTypeOf; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + devAssert(typeof config.name === 'string', 'Must provide name.'); + devAssert( + config.isTypeOf == null || typeof config.isTypeOf === 'function', + `${this.name} must provide "isTypeOf" as a function, ` + + `but got: ${inspect(config.isTypeOf)}.`, + ); + } + + getFields(): GraphQLFieldMap<any, any> { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + + getInterfaces(): Array<GraphQLInterfaceType> { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + + toConfig(): GraphQLObjectTypeNormalizedConfig { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + isTypeOf: this.isTypeOf, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes || [], + }; + } + + toString(): string { + return this.name; + } + + toJSON(): string { + return this.toString(); + } + + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + get [SYMBOL_TO_STRING_TAG]() { + return 'GraphQLObjectType'; + } +} + +// Print a simplified form when appearing in `inspect` and `util.inspect`. +defineInspect(GraphQLObjectType); + +function defineInterfaces( + config: $ReadOnly< + | GraphQLObjectTypeConfig<mixed, mixed> + | GraphQLInterfaceTypeConfig<mixed, mixed>, + >, +): Array<GraphQLInterfaceType> { + const interfaces = resolveThunk(config.interfaces) ?? []; + devAssert( + Array.isArray(interfaces), + `${config.name} interfaces must be an Array or a function which returns an Array.`, + ); + return interfaces; +} + +function defineFieldMap<TSource, TContext>( + config: $ReadOnly< + | GraphQLObjectTypeConfig<TSource, TContext> + | GraphQLInterfaceTypeConfig<TSource, TContext>, + >, +): GraphQLFieldMap<TSource, TContext> { + const fieldMap = resolveThunk(config.fields); + devAssert( + isPlainObj(fieldMap), + `${config.name} fields must be an object with field names as keys or a function which returns such an object.`, + ); + + return mapValue(fieldMap, (fieldConfig, fieldName) => { + devAssert( + isPlainObj(fieldConfig), + `${config.name}.${fieldName} field config must be an object.`, + ); + devAssert( + !('isDeprecated' in fieldConfig), + `${config.name}.${fieldName} should provide "deprecationReason" instead of "isDeprecated".`, + ); + devAssert( + fieldConfig.resolve == null || typeof fieldConfig.resolve === 'function', + `${config.name}.${fieldName} field resolver must be a function if ` + + `provided, but got: ${inspect(fieldConfig.resolve)}.`, + ); + + const argsConfig = fieldConfig.args ?? {}; + devAssert( + isPlainObj(argsConfig), + `${config.name}.${fieldName} args must be an object with argument names as keys.`, + ); + + const args = objectEntries(argsConfig).map(([argName, argConfig]) => ({ + name: argName, + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: argConfig.extensions && toObjMap(argConfig.extensions), + astNode: argConfig.astNode, + })); + + return { + name: fieldName, + description: fieldConfig.description, + type: fieldConfig.type, + args, + resolve: fieldConfig.resolve, + subscribe: fieldConfig.subscribe, + isDeprecated: fieldConfig.deprecationReason != null, + deprecationReason: fieldConfig.deprecationReason, + extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions), + astNode: fieldConfig.astNode, + }; + }); +} + +function isPlainObj(obj: mixed): boolean { + return isObjectLike(obj) && !Array.isArray(obj); +} + +function fieldsToFieldsConfig( + fields: GraphQLFieldMap<mixed, mixed>, +): GraphQLFieldConfigMap<mixed, mixed> { + return mapValue(fields, (field) => ({ + description: field.description, + type: field.type, + args: argsToArgsConfig(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode, + })); +} + +/** + * @internal + */ +export function argsToArgsConfig( + args: $ReadOnlyArray<GraphQLArgument>, +): GraphQLFieldConfigArgumentMap { + return keyValMap( + args, + (arg) => arg.name, + (arg) => ({ + description: arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + deprecationReason: arg.deprecationReason, + extensions: arg.extensions, + astNode: arg.astNode, + }), + ); +} + +export type GraphQLObjectTypeConfig<TSource, TContext> = {| + name: string, + description?: ?string, + interfaces?: Thunk<?Array<GraphQLInterfaceType>>, + fields: Thunk<GraphQLFieldConfigMap<TSource, TContext>>, + isTypeOf?: ?GraphQLIsTypeOfFn<TSource, TContext>, + extensions?: ?ReadOnlyObjMapLike<mixed>, + astNode?: ?ObjectTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray<ObjectTypeExtensionNode>, +|}; + +type GraphQLObjectTypeNormalizedConfig = {| + ...GraphQLObjectTypeConfig<any, any>, + interfaces: Array<GraphQLInterfaceType>, + fields: GraphQLFieldConfigMap<any, any>, + extensions: ?ReadOnlyObjMap<mixed>, + extensionASTNodes: $ReadOnlyArray<ObjectTypeExtensionNode>, +|}; + +/** + * Note: returning GraphQLObjectType is deprecated and will be removed in v16.0.0 + */ +export type GraphQLTypeResolver<TSource, TContext> = ( + value: TSource, + context: TContext, + info: GraphQLResolveInfo, + abstractType: GraphQLAbstractType, +) => PromiseOrValue<?GraphQLObjectType | string>; + +export type GraphQLIsTypeOfFn<TSource, TContext> = ( + source: TSource, + context: TContext, + info: GraphQLResolveInfo, +) => PromiseOrValue<boolean>; + +export type GraphQLFieldResolver< + TSource, + TContext, + TArgs = { [argument: string]: any, ... }, +> = ( + source: TSource, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo, +) => mixed; + +export type GraphQLResolveInfo = {| + +fieldName: string, + +fieldNodes: $ReadOnlyArray<FieldNode>, + +returnType: GraphQLOutputType, + +parentType: GraphQLObjectType, + +path: Path, + +schema: GraphQLSchema, + +fragments: ObjMap<FragmentDefinitionNode>, + +rootValue: mixed, + +operation: OperationDefinitionNode, + +variableValues: { [variable: string]: mixed, ... }, +|}; + +export type GraphQLFieldConfig< + TSource, + TContext, + TArgs = { [argument: string]: any, ... }, +> = {| + description?: ?string, + type: GraphQLOutputType, + args?: GraphQLFieldConfigArgumentMap, + resolve?: GraphQLFieldResolver<TSource, TContext, TArgs>, + subscribe?: GraphQLFieldResolver<TSource, TContext, TArgs>, + deprecationReason?: ?string, + extensions?: ?ReadOnlyObjMapLike<mixed>, + astNode?: ?FieldDefinitionNode, +|}; + +export type GraphQLFieldConfigArgumentMap = ObjMap<GraphQLArgumentConfig>; + +export type GraphQLArgumentConfig = {| + description?: ?string, + type: GraphQLInputType, + defaultValue?: mixed, + extensions?: ?ReadOnlyObjMapLike<mixed>, + deprecationReason?: ?string, + astNode?: ?InputValueDefinitionNode, +|}; + +export type GraphQLFieldConfigMap<TSource, TContext> = ObjMap< + GraphQLFieldConfig<TSource, TContext>, +>; + +export type GraphQLField< + TSource, + TContext, + TArgs = { [argument: string]: any, ... }, +> = {| + name: string, + description: ?string, + type: GraphQLOutputType, + args: Array<GraphQLArgument>, + resolve?: GraphQLFieldResolver<TSource, TContext, TArgs>, + subscribe?: GraphQLFieldResolver<TSource, TContext, TArgs>, + deprecationReason: ?string, + extensions: ?ReadOnlyObjMap<mixed>, + astNode: ?FieldDefinitionNode, + + // @deprecated and will be removed in v16 + isDeprecated: boolean, +|}; + +export type GraphQLArgument = {| + name: string, + description: ?string, + type: GraphQLInputType, + defaultValue: mixed, + deprecationReason: ?string, + extensions: ?ReadOnlyObjMap<mixed>, + astNode: ?InputValueDefinitionNode, +|}; + +export function isRequiredArgument(arg: GraphQLArgument): boolean %checks { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} + +export type GraphQLFieldMap<TSource, TContext> = ObjMap< + GraphQLField<TSource, TContext>, +>; + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * + */ +export class GraphQLInterfaceType { + name: string; + description: ?string; + resolveType: ?GraphQLTypeResolver<any, any>; + extensions: ?ReadOnlyObjMap<mixed>; + astNode: ?InterfaceTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray<InterfaceTypeExtensionNode>; + + _fields: Thunk<GraphQLFieldMap<any, any>>; + _interfaces: Thunk<Array<GraphQLInterfaceType>>; + + constructor(config: $ReadOnly<GraphQLInterfaceTypeConfig<any, any>>) { + this.name = config.name; + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + devAssert(typeof config.name === 'string', 'Must provide name.'); + devAssert( + config.resolveType == null || typeof config.resolveType === 'function', + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${inspect(config.resolveType)}.`, + ); + } + + getFields(): GraphQLFieldMap<any, any> { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + + getInterfaces(): Array<GraphQLInterfaceType> { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + + toConfig(): GraphQLInterfaceTypeNormalizedConfig { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes ?? [], + }; + } + + toString(): string { + return this.name; + } + + toJSON(): string { + return this.toString(); + } + + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + get [SYMBOL_TO_STRING_TAG]() { + return 'GraphQLInterfaceType'; + } +} + +// Print a simplified form when appearing in `inspect` and `util.inspect`. +defineInspect(GraphQLInterfaceType); + +export type GraphQLInterfaceTypeConfig<TSource, TContext> = {| + name: string, + description?: ?string, + interfaces?: Thunk<?Array<GraphQLInterfaceType>>, + fields: Thunk<GraphQLFieldConfigMap<TSource, TContext>>, + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: ?GraphQLTypeResolver<TSource, TContext>, + extensions?: ?ReadOnlyObjMapLike<mixed>, + astNode?: ?InterfaceTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray<InterfaceTypeExtensionNode>, +|}; + +export type GraphQLInterfaceTypeNormalizedConfig = {| + ...GraphQLInterfaceTypeConfig<any, any>, + interfaces: Array<GraphQLInterfaceType>, + fields: GraphQLFieldConfigMap<any, any>, + extensions: ?ReadOnlyObjMap<mixed>, + extensionASTNodes: $ReadOnlyArray<InterfaceTypeExtensionNode>, +|}; + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * + */ +export class GraphQLUnionType { + name: string; + description: ?string; + resolveType: ?GraphQLTypeResolver<any, any>; + extensions: ?ReadOnlyObjMap<mixed>; + astNode: ?UnionTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray<UnionTypeExtensionNode>; + + _types: Thunk<Array<GraphQLObjectType>>; + + constructor(config: $ReadOnly<GraphQLUnionTypeConfig<any, any>>) { + this.name = config.name; + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + + this._types = defineTypes.bind(undefined, config); + devAssert(typeof config.name === 'string', 'Must provide name.'); + devAssert( + config.resolveType == null || typeof config.resolveType === 'function', + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${inspect(config.resolveType)}.`, + ); + } + + getTypes(): Array<GraphQLObjectType> { + if (typeof this._types === 'function') { + this._types = this._types(); + } + return this._types; + } + + toConfig(): GraphQLUnionTypeNormalizedConfig { + return { + name: this.name, + description: this.description, + types: this.getTypes(), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes ?? [], + }; + } + + toString(): string { + return this.name; + } + + toJSON(): string { + return this.toString(); + } + + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + get [SYMBOL_TO_STRING_TAG]() { + return 'GraphQLUnionType'; + } +} + +// Print a simplified form when appearing in `inspect` and `util.inspect`. +defineInspect(GraphQLUnionType); + +function defineTypes( + config: $ReadOnly<GraphQLUnionTypeConfig<mixed, mixed>>, +): Array<GraphQLObjectType> { + const types = resolveThunk(config.types); + devAssert( + Array.isArray(types), + `Must provide Array of types or a function which returns such an array for Union ${config.name}.`, + ); + return types; +} + +export type GraphQLUnionTypeConfig<TSource, TContext> = {| + name: string, + description?: ?string, + types: Thunk<Array<GraphQLObjectType>>, + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: ?GraphQLTypeResolver<TSource, TContext>, + extensions?: ?ReadOnlyObjMapLike<mixed>, + astNode?: ?UnionTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray<UnionTypeExtensionNode>, +|}; + +type GraphQLUnionTypeNormalizedConfig = {| + ...GraphQLUnionTypeConfig<any, any>, + types: Array<GraphQLObjectType>, + extensions: ?ReadOnlyObjMap<mixed>, + extensionASTNodes: $ReadOnlyArray<UnionTypeExtensionNode>, +|}; + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +export class GraphQLEnumType /* <T> */ { + name: string; + description: ?string; + extensions: ?ReadOnlyObjMap<mixed>; + astNode: ?EnumTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray<EnumTypeExtensionNode>; + + _values: Array<GraphQLEnumValue /* <T> */>; + _valueLookup: Map<any /* T */, GraphQLEnumValue>; + _nameLookup: ObjMap<GraphQLEnumValue>; + + constructor(config: $ReadOnly<GraphQLEnumTypeConfig /* <T> */>) { + this.name = config.name; + this.description = config.description; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + + this._values = defineEnumValues(this.name, config.values); + this._valueLookup = new Map( + this._values.map((enumValue) => [enumValue.value, enumValue]), + ); + this._nameLookup = keyMap(this._values, (value) => value.name); + + devAssert(typeof config.name === 'string', 'Must provide name.'); + } + + getValues(): Array<GraphQLEnumValue /* <T> */> { + return this._values; + } + + getValue(name: string): ?GraphQLEnumValue { + return this._nameLookup[name]; + } + + serialize(outputValue: mixed /* T */): ?string { + const enumValue = this._valueLookup.get(outputValue); + if (enumValue === undefined) { + throw new GraphQLError( + `Enum "${this.name}" cannot represent value: ${inspect(outputValue)}`, + ); + } + return enumValue.name; + } + + parseValue(inputValue: mixed): ?any /* T */ { + if (typeof inputValue !== 'string') { + const valueStr = inspect(inputValue); + throw new GraphQLError( + `Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + + didYouMeanEnumValue(this, valueStr), + ); + } + + const enumValue = this.getValue(inputValue); + if (enumValue == null) { + throw new GraphQLError( + `Value "${inputValue}" does not exist in "${this.name}" enum.` + + didYouMeanEnumValue(this, inputValue), + ); + } + return enumValue.value; + } + + parseLiteral(valueNode: ValueNode, _variables: ?ObjMap<mixed>): ?any /* T */ { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind !== Kind.ENUM) { + const valueStr = print(valueNode); + throw new GraphQLError( + `Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + + didYouMeanEnumValue(this, valueStr), + valueNode, + ); + } + + const enumValue = this.getValue(valueNode.value); + if (enumValue == null) { + const valueStr = print(valueNode); + throw new GraphQLError( + `Value "${valueStr}" does not exist in "${this.name}" enum.` + + didYouMeanEnumValue(this, valueStr), + valueNode, + ); + } + return enumValue.value; + } + + toConfig(): GraphQLEnumTypeNormalizedConfig { + const values = keyValMap( + this.getValues(), + (value) => value.name, + (value) => ({ + description: value.description, + value: value.value, + deprecationReason: value.deprecationReason, + extensions: value.extensions, + astNode: value.astNode, + }), + ); + + return { + name: this.name, + description: this.description, + values, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes ?? [], + }; + } + + toString(): string { + return this.name; + } + + toJSON(): string { + return this.toString(); + } + + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + get [SYMBOL_TO_STRING_TAG]() { + return 'GraphQLEnumType'; + } +} + +// Print a simplified form when appearing in `inspect` and `util.inspect`. +defineInspect(GraphQLEnumType); + +function didYouMeanEnumValue( + enumType: GraphQLEnumType, + unknownValueStr: string, +): string { + const allNames = enumType.getValues().map((value) => value.name); + const suggestedValues = suggestionList(unknownValueStr, allNames); + + return didYouMean('the enum value', suggestedValues); +} + +function defineEnumValues( + typeName: string, + valueMap: GraphQLEnumValueConfigMap /* <T> */, +): Array<GraphQLEnumValue /* <T> */> { + devAssert( + isPlainObj(valueMap), + `${typeName} values must be an object with value names as keys.`, + ); + return objectEntries(valueMap).map(([valueName, valueConfig]) => { + devAssert( + isPlainObj(valueConfig), + `${typeName}.${valueName} must refer to an object with a "value" key ` + + `representing an internal value but got: ${inspect(valueConfig)}.`, + ); + devAssert( + !('isDeprecated' in valueConfig), + `${typeName}.${valueName} should provide "deprecationReason" instead of "isDeprecated".`, + ); + return { + name: valueName, + description: valueConfig.description, + value: valueConfig.value !== undefined ? valueConfig.value : valueName, + isDeprecated: valueConfig.deprecationReason != null, + deprecationReason: valueConfig.deprecationReason, + extensions: valueConfig.extensions && toObjMap(valueConfig.extensions), + astNode: valueConfig.astNode, + }; + }); +} + +export type GraphQLEnumTypeConfig /* <T> */ = {| + name: string, + description?: ?string, + values: GraphQLEnumValueConfigMap /* <T> */, + extensions?: ?ReadOnlyObjMapLike<mixed>, + astNode?: ?EnumTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray<EnumTypeExtensionNode>, +|}; + +type GraphQLEnumTypeNormalizedConfig = {| + ...GraphQLEnumTypeConfig, + extensions: ?ReadOnlyObjMap<mixed>, + extensionASTNodes: $ReadOnlyArray<EnumTypeExtensionNode>, +|}; + +export type GraphQLEnumValueConfigMap /* <T> */ = ObjMap<GraphQLEnumValueConfig /* <T> */>; + +export type GraphQLEnumValueConfig /* <T> */ = {| + description?: ?string, + value?: any /* T */, + deprecationReason?: ?string, + extensions?: ?ReadOnlyObjMapLike<mixed>, + astNode?: ?EnumValueDefinitionNode, +|}; + +export type GraphQLEnumValue /* <T> */ = {| + name: string, + description: ?string, + value: any /* T */, + deprecationReason: ?string, + extensions: ?ReadOnlyObjMap<mixed>, + astNode: ?EnumValueDefinitionNode, + + // @deprecated and will be removed in v16 + isDeprecated: boolean, +|}; + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +export class GraphQLInputObjectType { + name: string; + description: ?string; + extensions: ?ReadOnlyObjMap<mixed>; + astNode: ?InputObjectTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray<InputObjectTypeExtensionNode>; + + _fields: Thunk<GraphQLInputFieldMap>; + + constructor(config: $ReadOnly<GraphQLInputObjectTypeConfig>) { + this.name = config.name; + this.description = config.description; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + + this._fields = defineInputFieldMap.bind(undefined, config); + devAssert(typeof config.name === 'string', 'Must provide name.'); + } + + getFields(): GraphQLInputFieldMap { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + + toConfig(): GraphQLInputObjectTypeNormalizedConfig { + const fields = mapValue(this.getFields(), (field) => ({ + description: field.description, + type: field.type, + defaultValue: field.defaultValue, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode, + })); + + return { + name: this.name, + description: this.description, + fields, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes ?? [], + }; + } + + toString(): string { + return this.name; + } + + toJSON(): string { + return this.toString(); + } + + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + get [SYMBOL_TO_STRING_TAG]() { + return 'GraphQLInputObjectType'; + } +} + +// Print a simplified form when appearing in `inspect` and `util.inspect`. +defineInspect(GraphQLInputObjectType); + +function defineInputFieldMap( + config: $ReadOnly<GraphQLInputObjectTypeConfig>, +): GraphQLInputFieldMap { + const fieldMap = resolveThunk(config.fields); + devAssert( + isPlainObj(fieldMap), + `${config.name} fields must be an object with field names as keys or a function which returns such an object.`, + ); + return mapValue(fieldMap, (fieldConfig, fieldName) => { + devAssert( + !('resolve' in fieldConfig), + `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`, + ); + + return { + name: fieldName, + description: fieldConfig.description, + type: fieldConfig.type, + defaultValue: fieldConfig.defaultValue, + deprecationReason: fieldConfig.deprecationReason, + extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions), + astNode: fieldConfig.astNode, + }; + }); +} + +export type GraphQLInputObjectTypeConfig = {| + name: string, + description?: ?string, + fields: Thunk<GraphQLInputFieldConfigMap>, + extensions?: ?ReadOnlyObjMapLike<mixed>, + astNode?: ?InputObjectTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray<InputObjectTypeExtensionNode>, +|}; + +type GraphQLInputObjectTypeNormalizedConfig = {| + ...GraphQLInputObjectTypeConfig, + fields: GraphQLInputFieldConfigMap, + extensions: ?ReadOnlyObjMap<mixed>, + extensionASTNodes: $ReadOnlyArray<InputObjectTypeExtensionNode>, +|}; + +export type GraphQLInputFieldConfig = {| + description?: ?string, + type: GraphQLInputType, + defaultValue?: mixed, + deprecationReason?: ?string, + extensions?: ?ReadOnlyObjMapLike<mixed>, + astNode?: ?InputValueDefinitionNode, +|}; + +export type GraphQLInputFieldConfigMap = ObjMap<GraphQLInputFieldConfig>; + +export type GraphQLInputField = {| + name: string, + description: ?string, + type: GraphQLInputType, + defaultValue: mixed, + deprecationReason: ?string, + extensions: ?ReadOnlyObjMap<mixed>, + astNode: ?InputValueDefinitionNode, +|}; + +export function isRequiredInputField( + field: GraphQLInputField, +): boolean %checks { + return isNonNullType(field.type) && field.defaultValue === undefined; +} + +export type GraphQLInputFieldMap = ObjMap<GraphQLInputField>; diff --git a/school/node_modules/graphql/type/definition.mjs b/school/node_modules/graphql/type/definition.mjs new file mode 100644 index 0000000..70c27be --- /dev/null +++ b/school/node_modules/graphql/type/definition.mjs @@ -0,0 +1,1107 @@ +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +import objectEntries from "../polyfills/objectEntries.mjs"; +import { SYMBOL_TO_STRING_TAG } from "../polyfills/symbols.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import keyMap from "../jsutils/keyMap.mjs"; +import mapValue from "../jsutils/mapValue.mjs"; +import toObjMap from "../jsutils/toObjMap.mjs"; +import devAssert from "../jsutils/devAssert.mjs"; +import keyValMap from "../jsutils/keyValMap.mjs"; +import instanceOf from "../jsutils/instanceOf.mjs"; +import didYouMean from "../jsutils/didYouMean.mjs"; +import isObjectLike from "../jsutils/isObjectLike.mjs"; +import identityFunc from "../jsutils/identityFunc.mjs"; +import defineInspect from "../jsutils/defineInspect.mjs"; +import suggestionList from "../jsutils/suggestionList.mjs"; +import { GraphQLError } from "../error/GraphQLError.mjs"; +import { Kind } from "../language/kinds.mjs"; +import { print } from "../language/printer.mjs"; +import { valueFromASTUntyped } from "../utilities/valueFromASTUntyped.mjs"; +export function isType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type); +} +export function assertType(type) { + if (!isType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL type.")); + } + + return type; +} +/** + * There are predicates for each kind of GraphQL type. + */ + +// eslint-disable-next-line no-redeclare +export function isScalarType(type) { + return instanceOf(type, GraphQLScalarType); +} +export function assertScalarType(type) { + if (!isScalarType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Scalar type.")); + } + + return type; +} +// eslint-disable-next-line no-redeclare +export function isObjectType(type) { + return instanceOf(type, GraphQLObjectType); +} +export function assertObjectType(type) { + if (!isObjectType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Object type.")); + } + + return type; +} +// eslint-disable-next-line no-redeclare +export function isInterfaceType(type) { + return instanceOf(type, GraphQLInterfaceType); +} +export function assertInterfaceType(type) { + if (!isInterfaceType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Interface type.")); + } + + return type; +} +// eslint-disable-next-line no-redeclare +export function isUnionType(type) { + return instanceOf(type, GraphQLUnionType); +} +export function assertUnionType(type) { + if (!isUnionType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Union type.")); + } + + return type; +} +// eslint-disable-next-line no-redeclare +export function isEnumType(type) { + return instanceOf(type, GraphQLEnumType); +} +export function assertEnumType(type) { + if (!isEnumType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Enum type.")); + } + + return type; +} +// eslint-disable-next-line no-redeclare +export function isInputObjectType(type) { + return instanceOf(type, GraphQLInputObjectType); +} +export function assertInputObjectType(type) { + if (!isInputObjectType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Input Object type.")); + } + + return type; +} +// eslint-disable-next-line no-redeclare +export function isListType(type) { + return instanceOf(type, GraphQLList); +} +export function assertListType(type) { + if (!isListType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL List type.")); + } + + return type; +} +// eslint-disable-next-line no-redeclare +export function isNonNullType(type) { + return instanceOf(type, GraphQLNonNull); +} +export function assertNonNullType(type) { + if (!isNonNullType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Non-Null type.")); + } + + return type; +} +/** + * These types may be used as input types for arguments and directives. + */ + +export function isInputType(type) { + return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType); +} +export function assertInputType(type) { + if (!isInputType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL input type.")); + } + + return type; +} +/** + * These types may be used as output types as the result of fields. + */ + +export function isOutputType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType); +} +export function assertOutputType(type) { + if (!isOutputType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL output type.")); + } + + return type; +} +/** + * These types may describe types which may be leaf values. + */ + +export function isLeafType(type) { + return isScalarType(type) || isEnumType(type); +} +export function assertLeafType(type) { + if (!isLeafType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL leaf type.")); + } + + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + +export function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} +export function assertCompositeType(type) { + if (!isCompositeType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL composite type.")); + } + + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + +export function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); +} +export function assertAbstractType(type) { + if (!isAbstractType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL abstract type.")); + } + + return type; +} +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(PersonType) }, + * children: { type: new GraphQLList(PersonType) }, + * }) + * }) + * + */ +// FIXME: workaround to fix issue with Babel parser + +/* :: +declare class GraphQLList<+T: GraphQLType> { + +ofType: T; + static <T>(ofType: T): GraphQLList<T>; + // Note: constructors cannot be used for covariant types. Drop the "new". + constructor(ofType: GraphQLType): void; +} +*/ + +export function GraphQLList(ofType) { + // istanbul ignore else (to be removed in v16.0.0) + if (this instanceof GraphQLList) { + this.ofType = assertType(ofType); + } else { + return new GraphQLList(ofType); + } +} // Need to cast through any to alter the prototype. + +GraphQLList.prototype.toString = function toString() { + return '[' + String(this.ofType) + ']'; +}; + +GraphQLList.prototype.toJSON = function toJSON() { + return this.toString(); +}; + +Object.defineProperty(GraphQLList.prototype, SYMBOL_TO_STRING_TAG, { + get: function get() { + return 'GraphQLList'; + } +}); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +defineInspect(GraphQLList); +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ +// FIXME: workaround to fix issue with Babel parser + +/* :: +declare class GraphQLNonNull<+T: GraphQLNullableType> { + +ofType: T; + static <T>(ofType: T): GraphQLNonNull<T>; + // Note: constructors cannot be used for covariant types. Drop the "new". + constructor(ofType: GraphQLType): void; +} +*/ + +export function GraphQLNonNull(ofType) { + // istanbul ignore else (to be removed in v16.0.0) + if (this instanceof GraphQLNonNull) { + this.ofType = assertNullableType(ofType); + } else { + return new GraphQLNonNull(ofType); + } +} // Need to cast through any to alter the prototype. + +GraphQLNonNull.prototype.toString = function toString() { + return String(this.ofType) + '!'; +}; + +GraphQLNonNull.prototype.toJSON = function toJSON() { + return this.toString(); +}; + +Object.defineProperty(GraphQLNonNull.prototype, SYMBOL_TO_STRING_TAG, { + get: function get() { + return 'GraphQLNonNull'; + } +}); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +defineInspect(GraphQLNonNull); +/** + * These types wrap and modify other types + */ + +export function isWrappingType(type) { + return isListType(type) || isNonNullType(type); +} +export function assertWrappingType(type) { + if (!isWrappingType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL wrapping type.")); + } + + return type; +} +/** + * These types can all accept null as a value. + */ + +export function isNullableType(type) { + return isType(type) && !isNonNullType(type); +} +export function assertNullableType(type) { + if (!isNullableType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL nullable type.")); + } + + return type; +} +/* eslint-disable no-redeclare */ + +export function getNullableType(type) { + /* eslint-enable no-redeclare */ + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} +/** + * These named types do not include modifiers like List or NonNull. + */ + +export function isNamedType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type); +} +export function assertNamedType(type) { + if (!isNamedType(type)) { + throw new Error("Expected ".concat(inspect(type), " to be a GraphQL named type.")); + } + + return type; +} +/* eslint-disable no-redeclare */ + +export function getNamedType(type) { + /* eslint-enable no-redeclare */ + if (type) { + var unwrappedType = type; + + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + + return unwrappedType; + } +} +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ + +function resolveThunk(thunk) { + // $FlowFixMe[incompatible-use] + return typeof thunk === 'function' ? thunk() : thunk; +} + +function undefineIfEmpty(arr) { + return arr && arr.length > 0 ? arr : undefined; +} +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function does not return a value (i.e. it returns + * `undefined`) then an error will be raised and a `null` value will be returned + * in the response. If the serialize function returns `null`, then no error will + * be included in the response. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (value % 2 === 1) { + * return value; + * } + * } + * }); + * + */ + + +export var GraphQLScalarType = /*#__PURE__*/function () { + function GraphQLScalarType(config) { + var _config$parseValue, _config$serialize, _config$parseLiteral; + + var parseValue = (_config$parseValue = config.parseValue) !== null && _config$parseValue !== void 0 ? _config$parseValue : identityFunc; + this.name = config.name; + this.description = config.description; + this.specifiedByUrl = config.specifiedByUrl; + this.serialize = (_config$serialize = config.serialize) !== null && _config$serialize !== void 0 ? _config$serialize : identityFunc; + this.parseValue = parseValue; + this.parseLiteral = (_config$parseLiteral = config.parseLiteral) !== null && _config$parseLiteral !== void 0 ? _config$parseLiteral : function (node, variables) { + return parseValue(valueFromASTUntyped(node, variables)); + }; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + typeof config.name === 'string' || devAssert(0, 'Must provide name.'); + config.specifiedByUrl == null || typeof config.specifiedByUrl === 'string' || devAssert(0, "".concat(this.name, " must provide \"specifiedByUrl\" as a string, ") + "but got: ".concat(inspect(config.specifiedByUrl), ".")); + config.serialize == null || typeof config.serialize === 'function' || devAssert(0, "".concat(this.name, " must provide \"serialize\" function. If this custom Scalar is also used as an input type, ensure \"parseValue\" and \"parseLiteral\" functions are also provided.")); + + if (config.parseLiteral) { + typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function' || devAssert(0, "".concat(this.name, " must provide both \"parseValue\" and \"parseLiteral\" functions.")); + } + } + + var _proto = GraphQLScalarType.prototype; + + _proto.toConfig = function toConfig() { + var _this$extensionASTNod; + + return { + name: this.name, + description: this.description, + specifiedByUrl: this.specifiedByUrl, + serialize: this.serialize, + parseValue: this.parseValue, + parseLiteral: this.parseLiteral, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod = this.extensionASTNodes) !== null && _this$extensionASTNod !== void 0 ? _this$extensionASTNod : [] + }; + }; + + _proto.toString = function toString() { + return this.name; + }; + + _proto.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLScalarType, [{ + key: SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLScalarType'; + } + }]); + + return GraphQLScalarType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +defineInspect(GraphQLScalarType); + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * + */ +export var GraphQLObjectType = /*#__PURE__*/function () { + function GraphQLObjectType(config) { + this.name = config.name; + this.description = config.description; + this.isTypeOf = config.isTypeOf; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + typeof config.name === 'string' || devAssert(0, 'Must provide name.'); + config.isTypeOf == null || typeof config.isTypeOf === 'function' || devAssert(0, "".concat(this.name, " must provide \"isTypeOf\" as a function, ") + "but got: ".concat(inspect(config.isTypeOf), ".")); + } + + var _proto2 = GraphQLObjectType.prototype; + + _proto2.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto2.getInterfaces = function getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + }; + + _proto2.toConfig = function toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + isTypeOf: this.isTypeOf, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes || [] + }; + }; + + _proto2.toString = function toString() { + return this.name; + }; + + _proto2.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLObjectType, [{ + key: SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLObjectType'; + } + }]); + + return GraphQLObjectType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +defineInspect(GraphQLObjectType); + +function defineInterfaces(config) { + var _resolveThunk; + + var interfaces = (_resolveThunk = resolveThunk(config.interfaces)) !== null && _resolveThunk !== void 0 ? _resolveThunk : []; + Array.isArray(interfaces) || devAssert(0, "".concat(config.name, " interfaces must be an Array or a function which returns an Array.")); + return interfaces; +} + +function defineFieldMap(config) { + var fieldMap = resolveThunk(config.fields); + isPlainObj(fieldMap) || devAssert(0, "".concat(config.name, " fields must be an object with field names as keys or a function which returns such an object.")); + return mapValue(fieldMap, function (fieldConfig, fieldName) { + var _fieldConfig$args; + + isPlainObj(fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " field config must be an object.")); + !('isDeprecated' in fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " should provide \"deprecationReason\" instead of \"isDeprecated\".")); + fieldConfig.resolve == null || typeof fieldConfig.resolve === 'function' || devAssert(0, "".concat(config.name, ".").concat(fieldName, " field resolver must be a function if ") + "provided, but got: ".concat(inspect(fieldConfig.resolve), ".")); + var argsConfig = (_fieldConfig$args = fieldConfig.args) !== null && _fieldConfig$args !== void 0 ? _fieldConfig$args : {}; + isPlainObj(argsConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " args must be an object with argument names as keys.")); + var args = objectEntries(argsConfig).map(function (_ref) { + var argName = _ref[0], + argConfig = _ref[1]; + return { + name: argName, + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: argConfig.extensions && toObjMap(argConfig.extensions), + astNode: argConfig.astNode + }; + }); + return { + name: fieldName, + description: fieldConfig.description, + type: fieldConfig.type, + args: args, + resolve: fieldConfig.resolve, + subscribe: fieldConfig.subscribe, + isDeprecated: fieldConfig.deprecationReason != null, + deprecationReason: fieldConfig.deprecationReason, + extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions), + astNode: fieldConfig.astNode + }; + }); +} + +function isPlainObj(obj) { + return isObjectLike(obj) && !Array.isArray(obj); +} + +function fieldsToFieldsConfig(fields) { + return mapValue(fields, function (field) { + return { + description: field.description, + type: field.type, + args: argsToArgsConfig(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode + }; + }); +} +/** + * @internal + */ + + +export function argsToArgsConfig(args) { + return keyValMap(args, function (arg) { + return arg.name; + }, function (arg) { + return { + description: arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + deprecationReason: arg.deprecationReason, + extensions: arg.extensions, + astNode: arg.astNode + }; + }); +} +export function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * + */ +export var GraphQLInterfaceType = /*#__PURE__*/function () { + function GraphQLInterfaceType(config) { + this.name = config.name; + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + typeof config.name === 'string' || devAssert(0, 'Must provide name.'); + config.resolveType == null || typeof config.resolveType === 'function' || devAssert(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), ".")); + } + + var _proto3 = GraphQLInterfaceType.prototype; + + _proto3.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto3.getInterfaces = function getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + }; + + _proto3.toConfig = function toConfig() { + var _this$extensionASTNod2; + + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod2 = this.extensionASTNodes) !== null && _this$extensionASTNod2 !== void 0 ? _this$extensionASTNod2 : [] + }; + }; + + _proto3.toString = function toString() { + return this.name; + }; + + _proto3.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLInterfaceType, [{ + key: SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLInterfaceType'; + } + }]); + + return GraphQLInterfaceType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +defineInspect(GraphQLInterfaceType); + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * + */ +export var GraphQLUnionType = /*#__PURE__*/function () { + function GraphQLUnionType(config) { + this.name = config.name; + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + this._types = defineTypes.bind(undefined, config); + typeof config.name === 'string' || devAssert(0, 'Must provide name.'); + config.resolveType == null || typeof config.resolveType === 'function' || devAssert(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), ".")); + } + + var _proto4 = GraphQLUnionType.prototype; + + _proto4.getTypes = function getTypes() { + if (typeof this._types === 'function') { + this._types = this._types(); + } + + return this._types; + }; + + _proto4.toConfig = function toConfig() { + var _this$extensionASTNod3; + + return { + name: this.name, + description: this.description, + types: this.getTypes(), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod3 = this.extensionASTNodes) !== null && _this$extensionASTNod3 !== void 0 ? _this$extensionASTNod3 : [] + }; + }; + + _proto4.toString = function toString() { + return this.name; + }; + + _proto4.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLUnionType, [{ + key: SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLUnionType'; + } + }]); + + return GraphQLUnionType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +defineInspect(GraphQLUnionType); + +function defineTypes(config) { + var types = resolveThunk(config.types); + Array.isArray(types) || devAssert(0, "Must provide Array of types or a function which returns such an array for Union ".concat(config.name, ".")); + return types; +} + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +export var GraphQLEnumType +/* <T> */ += /*#__PURE__*/function () { + function GraphQLEnumType(config) { + this.name = config.name; + this.description = config.description; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + this._values = defineEnumValues(this.name, config.values); + this._valueLookup = new Map(this._values.map(function (enumValue) { + return [enumValue.value, enumValue]; + })); + this._nameLookup = keyMap(this._values, function (value) { + return value.name; + }); + typeof config.name === 'string' || devAssert(0, 'Must provide name.'); + } + + var _proto5 = GraphQLEnumType.prototype; + + _proto5.getValues = function getValues() { + return this._values; + }; + + _proto5.getValue = function getValue(name) { + return this._nameLookup[name]; + }; + + _proto5.serialize = function serialize(outputValue) { + var enumValue = this._valueLookup.get(outputValue); + + if (enumValue === undefined) { + throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent value: ").concat(inspect(outputValue))); + } + + return enumValue.name; + }; + + _proto5.parseValue = function parseValue(inputValue) + /* T */ + { + if (typeof inputValue !== 'string') { + var valueStr = inspect(inputValue); + throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent non-string value: ").concat(valueStr, ".") + didYouMeanEnumValue(this, valueStr)); + } + + var enumValue = this.getValue(inputValue); + + if (enumValue == null) { + throw new GraphQLError("Value \"".concat(inputValue, "\" does not exist in \"").concat(this.name, "\" enum.") + didYouMeanEnumValue(this, inputValue)); + } + + return enumValue.value; + }; + + _proto5.parseLiteral = function parseLiteral(valueNode, _variables) + /* T */ + { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind !== Kind.ENUM) { + var valueStr = print(valueNode); + throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent non-enum value: ").concat(valueStr, ".") + didYouMeanEnumValue(this, valueStr), valueNode); + } + + var enumValue = this.getValue(valueNode.value); + + if (enumValue == null) { + var _valueStr = print(valueNode); + + throw new GraphQLError("Value \"".concat(_valueStr, "\" does not exist in \"").concat(this.name, "\" enum.") + didYouMeanEnumValue(this, _valueStr), valueNode); + } + + return enumValue.value; + }; + + _proto5.toConfig = function toConfig() { + var _this$extensionASTNod4; + + var values = keyValMap(this.getValues(), function (value) { + return value.name; + }, function (value) { + return { + description: value.description, + value: value.value, + deprecationReason: value.deprecationReason, + extensions: value.extensions, + astNode: value.astNode + }; + }); + return { + name: this.name, + description: this.description, + values: values, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod4 = this.extensionASTNodes) !== null && _this$extensionASTNod4 !== void 0 ? _this$extensionASTNod4 : [] + }; + }; + + _proto5.toString = function toString() { + return this.name; + }; + + _proto5.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLEnumType, [{ + key: SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLEnumType'; + } + }]); + + return GraphQLEnumType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +defineInspect(GraphQLEnumType); + +function didYouMeanEnumValue(enumType, unknownValueStr) { + var allNames = enumType.getValues().map(function (value) { + return value.name; + }); + var suggestedValues = suggestionList(unknownValueStr, allNames); + return didYouMean('the enum value', suggestedValues); +} + +function defineEnumValues(typeName, valueMap) { + isPlainObj(valueMap) || devAssert(0, "".concat(typeName, " values must be an object with value names as keys.")); + return objectEntries(valueMap).map(function (_ref2) { + var valueName = _ref2[0], + valueConfig = _ref2[1]; + isPlainObj(valueConfig) || devAssert(0, "".concat(typeName, ".").concat(valueName, " must refer to an object with a \"value\" key ") + "representing an internal value but got: ".concat(inspect(valueConfig), ".")); + !('isDeprecated' in valueConfig) || devAssert(0, "".concat(typeName, ".").concat(valueName, " should provide \"deprecationReason\" instead of \"isDeprecated\".")); + return { + name: valueName, + description: valueConfig.description, + value: valueConfig.value !== undefined ? valueConfig.value : valueName, + isDeprecated: valueConfig.deprecationReason != null, + deprecationReason: valueConfig.deprecationReason, + extensions: valueConfig.extensions && toObjMap(valueConfig.extensions), + astNode: valueConfig.astNode + }; + }); +} + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +export var GraphQLInputObjectType = /*#__PURE__*/function () { + function GraphQLInputObjectType(config) { + this.name = config.name; + this.description = config.description; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes); + this._fields = defineInputFieldMap.bind(undefined, config); + typeof config.name === 'string' || devAssert(0, 'Must provide name.'); + } + + var _proto6 = GraphQLInputObjectType.prototype; + + _proto6.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto6.toConfig = function toConfig() { + var _this$extensionASTNod5; + + var fields = mapValue(this.getFields(), function (field) { + return { + description: field.description, + type: field.type, + defaultValue: field.defaultValue, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode + }; + }); + return { + name: this.name, + description: this.description, + fields: fields, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod5 = this.extensionASTNodes) !== null && _this$extensionASTNod5 !== void 0 ? _this$extensionASTNod5 : [] + }; + }; + + _proto6.toString = function toString() { + return this.name; + }; + + _proto6.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLInputObjectType, [{ + key: SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLInputObjectType'; + } + }]); + + return GraphQLInputObjectType; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +defineInspect(GraphQLInputObjectType); + +function defineInputFieldMap(config) { + var fieldMap = resolveThunk(config.fields); + isPlainObj(fieldMap) || devAssert(0, "".concat(config.name, " fields must be an object with field names as keys or a function which returns such an object.")); + return mapValue(fieldMap, function (fieldConfig, fieldName) { + !('resolve' in fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " field has a resolve property, but Input Types cannot define resolvers.")); + return { + name: fieldName, + description: fieldConfig.description, + type: fieldConfig.type, + defaultValue: fieldConfig.defaultValue, + deprecationReason: fieldConfig.deprecationReason, + extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions), + astNode: fieldConfig.astNode + }; + }); +} + +export function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; +} diff --git a/school/node_modules/graphql/type/directives.d.ts b/school/node_modules/graphql/type/directives.d.ts new file mode 100644 index 0000000..2c6de77 --- /dev/null +++ b/school/node_modules/graphql/type/directives.d.ts @@ -0,0 +1,96 @@ +// FIXME +/* eslint-disable import/no-cycle */ + +import { Maybe } from '../jsutils/Maybe'; + +import { DirectiveDefinitionNode } from '../language/ast'; +import { DirectiveLocationEnum } from '../language/directiveLocation'; + +import { GraphQLFieldConfigArgumentMap, GraphQLArgument } from './definition'; + +/** + * Test if the given value is a GraphQL directive. + */ +export function isDirective(directive: any): directive is GraphQLDirective; +export function assertDirective(directive: any): GraphQLDirective; + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLDirectiveExtensions { + [attributeName: string]: any; +} + +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ +export class GraphQLDirective { + name: string; + description: Maybe<string>; + locations: Array<DirectiveLocationEnum>; + isRepeatable: boolean; + args: Array<GraphQLArgument>; + extensions: Maybe<Readonly<GraphQLDirectiveExtensions>>; + astNode: Maybe<DirectiveDefinitionNode>; + + constructor(config: Readonly<GraphQLDirectiveConfig>); + + toConfig(): GraphQLDirectiveConfig & { + args: GraphQLFieldConfigArgumentMap; + isRepeatable: boolean; + extensions: Maybe<Readonly<GraphQLDirectiveExtensions>>; + }; + + toString(): string; + toJSON(): string; + inspect(): string; +} + +export interface GraphQLDirectiveConfig { + name: string; + description?: Maybe<string>; + locations: Array<DirectiveLocationEnum>; + args?: Maybe<GraphQLFieldConfigArgumentMap>; + isRepeatable?: Maybe<boolean>; + extensions?: Maybe<Readonly<GraphQLDirectiveExtensions>>; + astNode?: Maybe<DirectiveDefinitionNode>; +} + +/** + * Used to conditionally include fields or fragments. + */ +export const GraphQLIncludeDirective: GraphQLDirective; + +/** + * Used to conditionally skip (exclude) fields or fragments. + */ +export const GraphQLSkipDirective: GraphQLDirective; + +/** + * Used to provide a URL for specifying the behavior of custom scalar definitions. + */ +export const GraphQLSpecifiedByDirective: GraphQLDirective; + +/** + * Constant string used for default reason for a deprecation. + */ +export const DEFAULT_DEPRECATION_REASON: 'No longer supported'; + +/** + * Used to declare element of a GraphQL schema as deprecated. + */ +export const GraphQLDeprecatedDirective: GraphQLDirective; + +/** + * The full list of specified directives. + */ +export const specifiedDirectives: ReadonlyArray<GraphQLDirective>; + +export function isSpecifiedDirective(directive: GraphQLDirective): boolean; diff --git a/school/node_modules/graphql/type/directives.js b/school/node_modules/graphql/type/directives.js new file mode 100644 index 0000000..58ee0ab --- /dev/null +++ b/school/node_modules/graphql/type/directives.js @@ -0,0 +1,205 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isDirective = isDirective; +exports.assertDirective = assertDirective; +exports.isSpecifiedDirective = isSpecifiedDirective; +exports.specifiedDirectives = exports.GraphQLSpecifiedByDirective = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = void 0; + +var _objectEntries = _interopRequireDefault(require("../polyfills/objectEntries.js")); + +var _symbols = require("../polyfills/symbols.js"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _toObjMap = _interopRequireDefault(require("../jsutils/toObjMap.js")); + +var _devAssert = _interopRequireDefault(require("../jsutils/devAssert.js")); + +var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf.js")); + +var _isObjectLike = _interopRequireDefault(require("../jsutils/isObjectLike.js")); + +var _defineInspect = _interopRequireDefault(require("../jsutils/defineInspect.js")); + +var _directiveLocation = require("../language/directiveLocation.js"); + +var _scalars = require("./scalars.js"); + +var _definition = require("./definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +// eslint-disable-next-line no-redeclare +function isDirective(directive) { + return (0, _instanceOf.default)(directive, GraphQLDirective); +} + +function assertDirective(directive) { + if (!isDirective(directive)) { + throw new Error("Expected ".concat((0, _inspect.default)(directive), " to be a GraphQL directive.")); + } + + return directive; +} +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ + + +var GraphQLDirective = /*#__PURE__*/function () { + function GraphQLDirective(config) { + var _config$isRepeatable, _config$args; + + this.name = config.name; + this.description = config.description; + this.locations = config.locations; + this.isRepeatable = (_config$isRepeatable = config.isRepeatable) !== null && _config$isRepeatable !== void 0 ? _config$isRepeatable : false; + this.extensions = config.extensions && (0, _toObjMap.default)(config.extensions); + this.astNode = config.astNode; + config.name || (0, _devAssert.default)(0, 'Directive must be named.'); + Array.isArray(config.locations) || (0, _devAssert.default)(0, "@".concat(config.name, " locations must be an Array.")); + var args = (_config$args = config.args) !== null && _config$args !== void 0 ? _config$args : {}; + (0, _isObjectLike.default)(args) && !Array.isArray(args) || (0, _devAssert.default)(0, "@".concat(config.name, " args must be an object with argument names as keys.")); + this.args = (0, _objectEntries.default)(args).map(function (_ref) { + var argName = _ref[0], + argConfig = _ref[1]; + return { + name: argName, + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: argConfig.extensions && (0, _toObjMap.default)(argConfig.extensions), + astNode: argConfig.astNode + }; + }); + } + + var _proto = GraphQLDirective.prototype; + + _proto.toConfig = function toConfig() { + return { + name: this.name, + description: this.description, + locations: this.locations, + args: (0, _definition.argsToArgsConfig)(this.args), + isRepeatable: this.isRepeatable, + extensions: this.extensions, + astNode: this.astNode + }; + }; + + _proto.toString = function toString() { + return '@' + this.name; + }; + + _proto.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLDirective, [{ + key: _symbols.SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLDirective'; + } + }]); + + return GraphQLDirective; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + + +exports.GraphQLDirective = GraphQLDirective; +(0, _defineInspect.default)(GraphQLDirective); + +/** + * Used to conditionally include fields or fragments. + */ +var GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: 'Directs the executor to include this field or fragment only when the `if` argument is true.', + locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Included when true.' + } + } +}); +/** + * Used to conditionally skip (exclude) fields or fragments. + */ + +exports.GraphQLIncludeDirective = GraphQLIncludeDirective; +var GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: 'Directs the executor to skip this field or fragment when the `if` argument is true.', + locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Skipped when true.' + } + } +}); +/** + * Constant string used for default reason for a deprecation. + */ + +exports.GraphQLSkipDirective = GraphQLSkipDirective; +var DEFAULT_DEPRECATION_REASON = 'No longer supported'; +/** + * Used to declare element of a GraphQL schema as deprecated. + */ + +exports.DEFAULT_DEPRECATION_REASON = DEFAULT_DEPRECATION_REASON; +var GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [_directiveLocation.DirectiveLocation.FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ENUM_VALUE], + args: { + reason: { + type: _scalars.GraphQLString, + description: 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON + } + } +}); +/** + * Used to provide a URL for specifying the behaviour of custom scalar definitions. + */ + +exports.GraphQLDeprecatedDirective = GraphQLDeprecatedDirective; +var GraphQLSpecifiedByDirective = new GraphQLDirective({ + name: 'specifiedBy', + description: 'Exposes a URL that specifies the behaviour of this scalar.', + locations: [_directiveLocation.DirectiveLocation.SCALAR], + args: { + url: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: 'The URL that specifies the behaviour of this scalar.' + } + } +}); +/** + * The full list of specified directives. + */ + +exports.GraphQLSpecifiedByDirective = GraphQLSpecifiedByDirective; +var specifiedDirectives = Object.freeze([GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, GraphQLSpecifiedByDirective]); +exports.specifiedDirectives = specifiedDirectives; + +function isSpecifiedDirective(directive) { + return specifiedDirectives.some(function (_ref2) { + var name = _ref2.name; + return name === directive.name; + }); +} diff --git a/school/node_modules/graphql/type/directives.js.flow b/school/node_modules/graphql/type/directives.js.flow new file mode 100644 index 0000000..5eed2b9 --- /dev/null +++ b/school/node_modules/graphql/type/directives.js.flow @@ -0,0 +1,230 @@ +// @flow strict +import objectEntries from '../polyfills/objectEntries'; +import { SYMBOL_TO_STRING_TAG } from '../polyfills/symbols'; + +import type { ReadOnlyObjMap, ReadOnlyObjMapLike } from '../jsutils/ObjMap'; +import inspect from '../jsutils/inspect'; +import toObjMap from '../jsutils/toObjMap'; +import devAssert from '../jsutils/devAssert'; +import instanceOf from '../jsutils/instanceOf'; +import isObjectLike from '../jsutils/isObjectLike'; +import defineInspect from '../jsutils/defineInspect'; + +import type { DirectiveDefinitionNode } from '../language/ast'; +import type { DirectiveLocationEnum } from '../language/directiveLocation'; +import { DirectiveLocation } from '../language/directiveLocation'; + +import type { + GraphQLArgument, + GraphQLFieldConfigArgumentMap, +} from './definition'; +import { GraphQLString, GraphQLBoolean } from './scalars'; +import { argsToArgsConfig, GraphQLNonNull } from './definition'; + +/** + * Test if the given value is a GraphQL directive. + */ +declare function isDirective( + directive: mixed, +): boolean %checks(directive instanceof GraphQLDirective); +// eslint-disable-next-line no-redeclare +export function isDirective(directive) { + return instanceOf(directive, GraphQLDirective); +} + +export function assertDirective(directive: mixed): GraphQLDirective { + if (!isDirective(directive)) { + throw new Error( + `Expected ${inspect(directive)} to be a GraphQL directive.`, + ); + } + return directive; +} + +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ +export class GraphQLDirective { + name: string; + description: ?string; + locations: Array<DirectiveLocationEnum>; + args: Array<GraphQLArgument>; + isRepeatable: boolean; + extensions: ?ReadOnlyObjMap<mixed>; + astNode: ?DirectiveDefinitionNode; + + constructor(config: $ReadOnly<GraphQLDirectiveConfig>) { + this.name = config.name; + this.description = config.description; + this.locations = config.locations; + this.isRepeatable = config.isRepeatable ?? false; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + + devAssert(config.name, 'Directive must be named.'); + devAssert( + Array.isArray(config.locations), + `@${config.name} locations must be an Array.`, + ); + + const args = config.args ?? {}; + devAssert( + isObjectLike(args) && !Array.isArray(args), + `@${config.name} args must be an object with argument names as keys.`, + ); + + this.args = objectEntries(args).map(([argName, argConfig]) => ({ + name: argName, + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: argConfig.extensions && toObjMap(argConfig.extensions), + astNode: argConfig.astNode, + })); + } + + toConfig(): GraphQLDirectiveNormalizedConfig { + return { + name: this.name, + description: this.description, + locations: this.locations, + args: argsToArgsConfig(this.args), + isRepeatable: this.isRepeatable, + extensions: this.extensions, + astNode: this.astNode, + }; + } + + toString(): string { + return '@' + this.name; + } + + toJSON(): string { + return this.toString(); + } + + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + get [SYMBOL_TO_STRING_TAG]() { + return 'GraphQLDirective'; + } +} + +// Print a simplified form when appearing in `inspect` and `util.inspect`. +defineInspect(GraphQLDirective); + +export type GraphQLDirectiveConfig = {| + name: string, + description?: ?string, + locations: Array<DirectiveLocationEnum>, + args?: ?GraphQLFieldConfigArgumentMap, + isRepeatable?: ?boolean, + extensions?: ?ReadOnlyObjMapLike<mixed>, + astNode?: ?DirectiveDefinitionNode, +|}; + +type GraphQLDirectiveNormalizedConfig = {| + ...GraphQLDirectiveConfig, + args: GraphQLFieldConfigArgumentMap, + isRepeatable: boolean, + extensions: ?ReadOnlyObjMap<mixed>, +|}; + +/** + * Used to conditionally include fields or fragments. + */ +export const GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: + 'Directs the executor to include this field or fragment only when the `if` argument is true.', + locations: [ + DirectiveLocation.FIELD, + DirectiveLocation.FRAGMENT_SPREAD, + DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: new GraphQLNonNull(GraphQLBoolean), + description: 'Included when true.', + }, + }, +}); + +/** + * Used to conditionally skip (exclude) fields or fragments. + */ +export const GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: + 'Directs the executor to skip this field or fragment when the `if` argument is true.', + locations: [ + DirectiveLocation.FIELD, + DirectiveLocation.FRAGMENT_SPREAD, + DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: new GraphQLNonNull(GraphQLBoolean), + description: 'Skipped when true.', + }, + }, +}); + +/** + * Constant string used for default reason for a deprecation. + */ +export const DEFAULT_DEPRECATION_REASON = 'No longer supported'; + +/** + * Used to declare element of a GraphQL schema as deprecated. + */ +export const GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [ + DirectiveLocation.FIELD_DEFINITION, + DirectiveLocation.ARGUMENT_DEFINITION, + DirectiveLocation.INPUT_FIELD_DEFINITION, + DirectiveLocation.ENUM_VALUE, + ], + args: { + reason: { + type: GraphQLString, + description: + 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON, + }, + }, +}); + +/** + * Used to provide a URL for specifying the behaviour of custom scalar definitions. + */ +export const GraphQLSpecifiedByDirective = new GraphQLDirective({ + name: 'specifiedBy', + description: 'Exposes a URL that specifies the behaviour of this scalar.', + locations: [DirectiveLocation.SCALAR], + args: { + url: { + type: new GraphQLNonNull(GraphQLString), + description: 'The URL that specifies the behaviour of this scalar.', + }, + }, +}); + +/** + * The full list of specified directives. + */ +export const specifiedDirectives = Object.freeze([ + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, +]); + +export function isSpecifiedDirective( + directive: GraphQLDirective, +): boolean %checks { + return specifiedDirectives.some(({ name }) => name === directive.name); +} diff --git a/school/node_modules/graphql/type/directives.mjs b/school/node_modules/graphql/type/directives.mjs new file mode 100644 index 0000000..6b17658 --- /dev/null +++ b/school/node_modules/graphql/type/directives.mjs @@ -0,0 +1,175 @@ +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +import objectEntries from "../polyfills/objectEntries.mjs"; +import { SYMBOL_TO_STRING_TAG } from "../polyfills/symbols.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import toObjMap from "../jsutils/toObjMap.mjs"; +import devAssert from "../jsutils/devAssert.mjs"; +import instanceOf from "../jsutils/instanceOf.mjs"; +import isObjectLike from "../jsutils/isObjectLike.mjs"; +import defineInspect from "../jsutils/defineInspect.mjs"; +import { DirectiveLocation } from "../language/directiveLocation.mjs"; +import { GraphQLString, GraphQLBoolean } from "./scalars.mjs"; +import { argsToArgsConfig, GraphQLNonNull } from "./definition.mjs"; +/** + * Test if the given value is a GraphQL directive. + */ + +// eslint-disable-next-line no-redeclare +export function isDirective(directive) { + return instanceOf(directive, GraphQLDirective); +} +export function assertDirective(directive) { + if (!isDirective(directive)) { + throw new Error("Expected ".concat(inspect(directive), " to be a GraphQL directive.")); + } + + return directive; +} +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ + +export var GraphQLDirective = /*#__PURE__*/function () { + function GraphQLDirective(config) { + var _config$isRepeatable, _config$args; + + this.name = config.name; + this.description = config.description; + this.locations = config.locations; + this.isRepeatable = (_config$isRepeatable = config.isRepeatable) !== null && _config$isRepeatable !== void 0 ? _config$isRepeatable : false; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + config.name || devAssert(0, 'Directive must be named.'); + Array.isArray(config.locations) || devAssert(0, "@".concat(config.name, " locations must be an Array.")); + var args = (_config$args = config.args) !== null && _config$args !== void 0 ? _config$args : {}; + isObjectLike(args) && !Array.isArray(args) || devAssert(0, "@".concat(config.name, " args must be an object with argument names as keys.")); + this.args = objectEntries(args).map(function (_ref) { + var argName = _ref[0], + argConfig = _ref[1]; + return { + name: argName, + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: argConfig.extensions && toObjMap(argConfig.extensions), + astNode: argConfig.astNode + }; + }); + } + + var _proto = GraphQLDirective.prototype; + + _proto.toConfig = function toConfig() { + return { + name: this.name, + description: this.description, + locations: this.locations, + args: argsToArgsConfig(this.args), + isRepeatable: this.isRepeatable, + extensions: this.extensions, + astNode: this.astNode + }; + }; + + _proto.toString = function toString() { + return '@' + this.name; + }; + + _proto.toJSON = function toJSON() { + return this.toString(); + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLDirective, [{ + key: SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLDirective'; + } + }]); + + return GraphQLDirective; +}(); // Print a simplified form when appearing in `inspect` and `util.inspect`. + +defineInspect(GraphQLDirective); + +/** + * Used to conditionally include fields or fragments. + */ +export var GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: 'Directs the executor to include this field or fragment only when the `if` argument is true.', + locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: new GraphQLNonNull(GraphQLBoolean), + description: 'Included when true.' + } + } +}); +/** + * Used to conditionally skip (exclude) fields or fragments. + */ + +export var GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: 'Directs the executor to skip this field or fragment when the `if` argument is true.', + locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: new GraphQLNonNull(GraphQLBoolean), + description: 'Skipped when true.' + } + } +}); +/** + * Constant string used for default reason for a deprecation. + */ + +export var DEFAULT_DEPRECATION_REASON = 'No longer supported'; +/** + * Used to declare element of a GraphQL schema as deprecated. + */ + +export var GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.ARGUMENT_DEFINITION, DirectiveLocation.INPUT_FIELD_DEFINITION, DirectiveLocation.ENUM_VALUE], + args: { + reason: { + type: GraphQLString, + description: 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON + } + } +}); +/** + * Used to provide a URL for specifying the behaviour of custom scalar definitions. + */ + +export var GraphQLSpecifiedByDirective = new GraphQLDirective({ + name: 'specifiedBy', + description: 'Exposes a URL that specifies the behaviour of this scalar.', + locations: [DirectiveLocation.SCALAR], + args: { + url: { + type: new GraphQLNonNull(GraphQLString), + description: 'The URL that specifies the behaviour of this scalar.' + } + } +}); +/** + * The full list of specified directives. + */ + +export var specifiedDirectives = Object.freeze([GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, GraphQLSpecifiedByDirective]); +export function isSpecifiedDirective(directive) { + return specifiedDirectives.some(function (_ref2) { + var name = _ref2.name; + return name === directive.name; + }); +} diff --git a/school/node_modules/graphql/type/index.d.ts b/school/node_modules/graphql/type/index.d.ts new file mode 100644 index 0000000..3635319 --- /dev/null +++ b/school/node_modules/graphql/type/index.d.ts @@ -0,0 +1,170 @@ +export { Path as ResponsePath } from '../jsutils/Path'; + +export { + // Predicate + isSchema, + // Assertion + assertSchema, + // GraphQL Schema definition + GraphQLSchema, + GraphQLSchemaConfig, + GraphQLSchemaExtensions, +} from './schema'; + +export { + // Predicates + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, + // Assertions + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, + // Un-modifiers + getNullableType, + getNamedType, + // Definitions + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + // Type Wrappers + GraphQLList, + GraphQLNonNull, + // type + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + Thunk, + GraphQLNamedInputType, + GraphQLNamedOutputType, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLArgumentExtensions, + GraphQLEnumTypeConfig, + GraphQLEnumTypeExtensions, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueConfigMap, + GraphQLEnumValueExtensions, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldExtensions, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldConfigMap, + GraphQLInputFieldExtensions, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInputObjectTypeExtensions, + GraphQLInterfaceTypeConfig, + GraphQLInterfaceTypeExtensions, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLObjectTypeExtensions, + GraphQLResolveInfo, + GraphQLScalarTypeConfig, + GraphQLScalarTypeExtensions, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLUnionTypeExtensions, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from './definition'; + +export { + // Predicate + isDirective, + // Assertion + assertDirective, + // Directives Definition + GraphQLDirective, + // Built-in Directives defined by the Spec + isSpecifiedDirective, + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, + // type + GraphQLDirectiveConfig, + GraphQLDirectiveExtensions, +} from './directives'; + +// Common built-in scalar instances. +export { + isSpecifiedScalarType, + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, +} from './scalars'; + +export { + // "Enum" of Type Kinds + TypeKind, + // GraphQL Types for introspection. + isIntrospectionType, + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from './introspection'; + +export { validateSchema, assertValidSchema } from './validate'; diff --git a/school/node_modules/graphql/type/index.js b/school/node_modules/graphql/type/index.js new file mode 100644 index 0000000..e245def --- /dev/null +++ b/school/node_modules/graphql/type/index.js @@ -0,0 +1,509 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isSchema", { + enumerable: true, + get: function get() { + return _schema.isSchema; + } +}); +Object.defineProperty(exports, "assertSchema", { + enumerable: true, + get: function get() { + return _schema.assertSchema; + } +}); +Object.defineProperty(exports, "GraphQLSchema", { + enumerable: true, + get: function get() { + return _schema.GraphQLSchema; + } +}); +Object.defineProperty(exports, "isType", { + enumerable: true, + get: function get() { + return _definition.isType; + } +}); +Object.defineProperty(exports, "isScalarType", { + enumerable: true, + get: function get() { + return _definition.isScalarType; + } +}); +Object.defineProperty(exports, "isObjectType", { + enumerable: true, + get: function get() { + return _definition.isObjectType; + } +}); +Object.defineProperty(exports, "isInterfaceType", { + enumerable: true, + get: function get() { + return _definition.isInterfaceType; + } +}); +Object.defineProperty(exports, "isUnionType", { + enumerable: true, + get: function get() { + return _definition.isUnionType; + } +}); +Object.defineProperty(exports, "isEnumType", { + enumerable: true, + get: function get() { + return _definition.isEnumType; + } +}); +Object.defineProperty(exports, "isInputObjectType", { + enumerable: true, + get: function get() { + return _definition.isInputObjectType; + } +}); +Object.defineProperty(exports, "isListType", { + enumerable: true, + get: function get() { + return _definition.isListType; + } +}); +Object.defineProperty(exports, "isNonNullType", { + enumerable: true, + get: function get() { + return _definition.isNonNullType; + } +}); +Object.defineProperty(exports, "isInputType", { + enumerable: true, + get: function get() { + return _definition.isInputType; + } +}); +Object.defineProperty(exports, "isOutputType", { + enumerable: true, + get: function get() { + return _definition.isOutputType; + } +}); +Object.defineProperty(exports, "isLeafType", { + enumerable: true, + get: function get() { + return _definition.isLeafType; + } +}); +Object.defineProperty(exports, "isCompositeType", { + enumerable: true, + get: function get() { + return _definition.isCompositeType; + } +}); +Object.defineProperty(exports, "isAbstractType", { + enumerable: true, + get: function get() { + return _definition.isAbstractType; + } +}); +Object.defineProperty(exports, "isWrappingType", { + enumerable: true, + get: function get() { + return _definition.isWrappingType; + } +}); +Object.defineProperty(exports, "isNullableType", { + enumerable: true, + get: function get() { + return _definition.isNullableType; + } +}); +Object.defineProperty(exports, "isNamedType", { + enumerable: true, + get: function get() { + return _definition.isNamedType; + } +}); +Object.defineProperty(exports, "isRequiredArgument", { + enumerable: true, + get: function get() { + return _definition.isRequiredArgument; + } +}); +Object.defineProperty(exports, "isRequiredInputField", { + enumerable: true, + get: function get() { + return _definition.isRequiredInputField; + } +}); +Object.defineProperty(exports, "assertType", { + enumerable: true, + get: function get() { + return _definition.assertType; + } +}); +Object.defineProperty(exports, "assertScalarType", { + enumerable: true, + get: function get() { + return _definition.assertScalarType; + } +}); +Object.defineProperty(exports, "assertObjectType", { + enumerable: true, + get: function get() { + return _definition.assertObjectType; + } +}); +Object.defineProperty(exports, "assertInterfaceType", { + enumerable: true, + get: function get() { + return _definition.assertInterfaceType; + } +}); +Object.defineProperty(exports, "assertUnionType", { + enumerable: true, + get: function get() { + return _definition.assertUnionType; + } +}); +Object.defineProperty(exports, "assertEnumType", { + enumerable: true, + get: function get() { + return _definition.assertEnumType; + } +}); +Object.defineProperty(exports, "assertInputObjectType", { + enumerable: true, + get: function get() { + return _definition.assertInputObjectType; + } +}); +Object.defineProperty(exports, "assertListType", { + enumerable: true, + get: function get() { + return _definition.assertListType; + } +}); +Object.defineProperty(exports, "assertNonNullType", { + enumerable: true, + get: function get() { + return _definition.assertNonNullType; + } +}); +Object.defineProperty(exports, "assertInputType", { + enumerable: true, + get: function get() { + return _definition.assertInputType; + } +}); +Object.defineProperty(exports, "assertOutputType", { + enumerable: true, + get: function get() { + return _definition.assertOutputType; + } +}); +Object.defineProperty(exports, "assertLeafType", { + enumerable: true, + get: function get() { + return _definition.assertLeafType; + } +}); +Object.defineProperty(exports, "assertCompositeType", { + enumerable: true, + get: function get() { + return _definition.assertCompositeType; + } +}); +Object.defineProperty(exports, "assertAbstractType", { + enumerable: true, + get: function get() { + return _definition.assertAbstractType; + } +}); +Object.defineProperty(exports, "assertWrappingType", { + enumerable: true, + get: function get() { + return _definition.assertWrappingType; + } +}); +Object.defineProperty(exports, "assertNullableType", { + enumerable: true, + get: function get() { + return _definition.assertNullableType; + } +}); +Object.defineProperty(exports, "assertNamedType", { + enumerable: true, + get: function get() { + return _definition.assertNamedType; + } +}); +Object.defineProperty(exports, "getNullableType", { + enumerable: true, + get: function get() { + return _definition.getNullableType; + } +}); +Object.defineProperty(exports, "getNamedType", { + enumerable: true, + get: function get() { + return _definition.getNamedType; + } +}); +Object.defineProperty(exports, "GraphQLScalarType", { + enumerable: true, + get: function get() { + return _definition.GraphQLScalarType; + } +}); +Object.defineProperty(exports, "GraphQLObjectType", { + enumerable: true, + get: function get() { + return _definition.GraphQLObjectType; + } +}); +Object.defineProperty(exports, "GraphQLInterfaceType", { + enumerable: true, + get: function get() { + return _definition.GraphQLInterfaceType; + } +}); +Object.defineProperty(exports, "GraphQLUnionType", { + enumerable: true, + get: function get() { + return _definition.GraphQLUnionType; + } +}); +Object.defineProperty(exports, "GraphQLEnumType", { + enumerable: true, + get: function get() { + return _definition.GraphQLEnumType; + } +}); +Object.defineProperty(exports, "GraphQLInputObjectType", { + enumerable: true, + get: function get() { + return _definition.GraphQLInputObjectType; + } +}); +Object.defineProperty(exports, "GraphQLList", { + enumerable: true, + get: function get() { + return _definition.GraphQLList; + } +}); +Object.defineProperty(exports, "GraphQLNonNull", { + enumerable: true, + get: function get() { + return _definition.GraphQLNonNull; + } +}); +Object.defineProperty(exports, "isDirective", { + enumerable: true, + get: function get() { + return _directives.isDirective; + } +}); +Object.defineProperty(exports, "assertDirective", { + enumerable: true, + get: function get() { + return _directives.assertDirective; + } +}); +Object.defineProperty(exports, "GraphQLDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLDirective; + } +}); +Object.defineProperty(exports, "isSpecifiedDirective", { + enumerable: true, + get: function get() { + return _directives.isSpecifiedDirective; + } +}); +Object.defineProperty(exports, "specifiedDirectives", { + enumerable: true, + get: function get() { + return _directives.specifiedDirectives; + } +}); +Object.defineProperty(exports, "GraphQLIncludeDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLIncludeDirective; + } +}); +Object.defineProperty(exports, "GraphQLSkipDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLSkipDirective; + } +}); +Object.defineProperty(exports, "GraphQLDeprecatedDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLDeprecatedDirective; + } +}); +Object.defineProperty(exports, "GraphQLSpecifiedByDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLSpecifiedByDirective; + } +}); +Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", { + enumerable: true, + get: function get() { + return _directives.DEFAULT_DEPRECATION_REASON; + } +}); +Object.defineProperty(exports, "isSpecifiedScalarType", { + enumerable: true, + get: function get() { + return _scalars.isSpecifiedScalarType; + } +}); +Object.defineProperty(exports, "specifiedScalarTypes", { + enumerable: true, + get: function get() { + return _scalars.specifiedScalarTypes; + } +}); +Object.defineProperty(exports, "GraphQLInt", { + enumerable: true, + get: function get() { + return _scalars.GraphQLInt; + } +}); +Object.defineProperty(exports, "GraphQLFloat", { + enumerable: true, + get: function get() { + return _scalars.GraphQLFloat; + } +}); +Object.defineProperty(exports, "GraphQLString", { + enumerable: true, + get: function get() { + return _scalars.GraphQLString; + } +}); +Object.defineProperty(exports, "GraphQLBoolean", { + enumerable: true, + get: function get() { + return _scalars.GraphQLBoolean; + } +}); +Object.defineProperty(exports, "GraphQLID", { + enumerable: true, + get: function get() { + return _scalars.GraphQLID; + } +}); +Object.defineProperty(exports, "isIntrospectionType", { + enumerable: true, + get: function get() { + return _introspection.isIntrospectionType; + } +}); +Object.defineProperty(exports, "introspectionTypes", { + enumerable: true, + get: function get() { + return _introspection.introspectionTypes; + } +}); +Object.defineProperty(exports, "__Schema", { + enumerable: true, + get: function get() { + return _introspection.__Schema; + } +}); +Object.defineProperty(exports, "__Directive", { + enumerable: true, + get: function get() { + return _introspection.__Directive; + } +}); +Object.defineProperty(exports, "__DirectiveLocation", { + enumerable: true, + get: function get() { + return _introspection.__DirectiveLocation; + } +}); +Object.defineProperty(exports, "__Type", { + enumerable: true, + get: function get() { + return _introspection.__Type; + } +}); +Object.defineProperty(exports, "__Field", { + enumerable: true, + get: function get() { + return _introspection.__Field; + } +}); +Object.defineProperty(exports, "__InputValue", { + enumerable: true, + get: function get() { + return _introspection.__InputValue; + } +}); +Object.defineProperty(exports, "__EnumValue", { + enumerable: true, + get: function get() { + return _introspection.__EnumValue; + } +}); +Object.defineProperty(exports, "__TypeKind", { + enumerable: true, + get: function get() { + return _introspection.__TypeKind; + } +}); +Object.defineProperty(exports, "TypeKind", { + enumerable: true, + get: function get() { + return _introspection.TypeKind; + } +}); +Object.defineProperty(exports, "SchemaMetaFieldDef", { + enumerable: true, + get: function get() { + return _introspection.SchemaMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeMetaFieldDef", { + enumerable: true, + get: function get() { + return _introspection.TypeMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeNameMetaFieldDef", { + enumerable: true, + get: function get() { + return _introspection.TypeNameMetaFieldDef; + } +}); +Object.defineProperty(exports, "validateSchema", { + enumerable: true, + get: function get() { + return _validate.validateSchema; + } +}); +Object.defineProperty(exports, "assertValidSchema", { + enumerable: true, + get: function get() { + return _validate.assertValidSchema; + } +}); + +var _schema = require("./schema.js"); + +var _definition = require("./definition.js"); + +var _directives = require("./directives.js"); + +var _scalars = require("./scalars.js"); + +var _introspection = require("./introspection.js"); + +var _validate = require("./validate.js"); diff --git a/school/node_modules/graphql/type/index.js.flow b/school/node_modules/graphql/type/index.js.flow new file mode 100644 index 0000000..af0fef2 --- /dev/null +++ b/school/node_modules/graphql/type/index.js.flow @@ -0,0 +1,165 @@ +// @flow strict +export type { Path as ResponsePath } from '../jsutils/Path'; + +export { + // Predicate + isSchema, + // Assertion + assertSchema, + // GraphQL Schema definition + GraphQLSchema, +} from './schema'; +export type { GraphQLSchemaConfig } from './schema'; + +export { + // Predicates + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, + // Assertions + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, + // Un-modifiers + getNullableType, + getNamedType, + // Definitions + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + // Type Wrappers + GraphQLList, + GraphQLNonNull, +} from './definition'; + +export { + // Predicate + isDirective, + // Assertion + assertDirective, + // Directives Definition + GraphQLDirective, + // Built-in Directives defined by the Spec + isSpecifiedDirective, + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, +} from './directives'; + +export type { GraphQLDirectiveConfig } from './directives'; + +// Common built-in scalar instances. +export { + // Predicate + isSpecifiedScalarType, + // Standard GraphQL Scalars + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, +} from './scalars'; + +export { + // Predicate + isIntrospectionType, + // GraphQL Types for introspection. + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + // "Enum" of Type Kinds + TypeKind, + // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from './introspection'; + +export type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + Thunk, + GraphQLNamedInputType, + GraphQLNamedOutputType, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLEnumTypeConfig, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueConfigMap, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldConfigMap, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInterfaceTypeConfig, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLResolveInfo, + GraphQLScalarTypeConfig, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from './definition'; + +// Validate GraphQL schema. +export { validateSchema, assertValidSchema } from './validate'; diff --git a/school/node_modules/graphql/type/index.mjs b/school/node_modules/graphql/type/index.mjs new file mode 100644 index 0000000..48e61ba --- /dev/null +++ b/school/node_modules/graphql/type/index.mjs @@ -0,0 +1,27 @@ +export { // Predicate +isSchema // Assertion +, assertSchema // GraphQL Schema definition +, GraphQLSchema } from "./schema.mjs"; +export { // Predicates +isType, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isListType, isNonNullType, isInputType, isOutputType, isLeafType, isCompositeType, isAbstractType, isWrappingType, isNullableType, isNamedType, isRequiredArgument, isRequiredInputField // Assertions +, assertType, assertScalarType, assertObjectType, assertInterfaceType, assertUnionType, assertEnumType, assertInputObjectType, assertListType, assertNonNullType, assertInputType, assertOutputType, assertLeafType, assertCompositeType, assertAbstractType, assertWrappingType, assertNullableType, assertNamedType // Un-modifiers +, getNullableType, getNamedType // Definitions +, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType // Type Wrappers +, GraphQLList, GraphQLNonNull } from "./definition.mjs"; +export { // Predicate +isDirective // Assertion +, assertDirective // Directives Definition +, GraphQLDirective // Built-in Directives defined by the Spec +, isSpecifiedDirective, specifiedDirectives, GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, GraphQLSpecifiedByDirective // Constant Deprecation Reason +, DEFAULT_DEPRECATION_REASON } from "./directives.mjs"; +// Common built-in scalar instances. +export { // Predicate +isSpecifiedScalarType // Standard GraphQL Scalars +, specifiedScalarTypes, GraphQLInt, GraphQLFloat, GraphQLString, GraphQLBoolean, GraphQLID } from "./scalars.mjs"; +export { // Predicate +isIntrospectionType // GraphQL Types for introspection. +, introspectionTypes, __Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind // "Enum" of Type Kinds +, TypeKind // Meta-field definitions. +, SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from "./introspection.mjs"; +// Validate GraphQL schema. +export { validateSchema, assertValidSchema } from "./validate.mjs"; diff --git a/school/node_modules/graphql/type/introspection.d.ts b/school/node_modules/graphql/type/introspection.d.ts new file mode 100644 index 0000000..34cefa7 --- /dev/null +++ b/school/node_modules/graphql/type/introspection.d.ts @@ -0,0 +1,40 @@ +import { + GraphQLObjectType, + GraphQLField, + GraphQLEnumType, + GraphQLNamedType, +} from './definition'; + +export const __Schema: GraphQLObjectType; +export const __Directive: GraphQLObjectType; +export const __DirectiveLocation: GraphQLEnumType; +export const __Type: GraphQLObjectType; +export const __Field: GraphQLObjectType; +export const __InputValue: GraphQLObjectType; +export const __EnumValue: GraphQLObjectType; + +export const TypeKind: { + SCALAR: 'SCALAR'; + OBJECT: 'OBJECT'; + INTERFACE: 'INTERFACE'; + UNION: 'UNION'; + ENUM: 'ENUM'; + INPUT_OBJECT: 'INPUT_OBJECT'; + LIST: 'LIST'; + NON_NULL: 'NON_NULL'; +}; + +export const __TypeKind: GraphQLEnumType; + +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +export const SchemaMetaFieldDef: GraphQLField<any, any>; +export const TypeMetaFieldDef: GraphQLField<any, any>; +export const TypeNameMetaFieldDef: GraphQLField<any, any>; + +export const introspectionTypes: ReadonlyArray<GraphQLNamedType>; + +export function isIntrospectionType(type: GraphQLNamedType): boolean; diff --git a/school/node_modules/graphql/type/introspection.js b/school/node_modules/graphql/type/introspection.js new file mode 100644 index 0000000..751b982 --- /dev/null +++ b/school/node_modules/graphql/type/introspection.js @@ -0,0 +1,624 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIntrospectionType = isIntrospectionType; +exports.introspectionTypes = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.SchemaMetaFieldDef = exports.__TypeKind = exports.TypeKind = exports.__EnumValue = exports.__InputValue = exports.__Field = exports.__Type = exports.__DirectiveLocation = exports.__Directive = exports.__Schema = void 0; + +var _objectValues = _interopRequireDefault(require("../polyfills/objectValues.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _printer = require("../language/printer.js"); + +var _directiveLocation = require("../language/directiveLocation.js"); + +var _astFromValue = require("../utilities/astFromValue.js"); + +var _scalars = require("./scalars.js"); + +var _definition = require("./definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var __Schema = new _definition.GraphQLObjectType({ + name: '__Schema', + description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.', + fields: function fields() { + return { + description: { + type: _scalars.GraphQLString, + resolve: function resolve(schema) { + return schema.description; + } + }, + types: { + description: 'A list of all types supported by this server.', + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type))), + resolve: function resolve(schema) { + return (0, _objectValues.default)(schema.getTypeMap()); + } + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: new _definition.GraphQLNonNull(__Type), + resolve: function resolve(schema) { + return schema.getQueryType(); + } + }, + mutationType: { + description: 'If this server supports mutation, the type that mutation operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getMutationType(); + } + }, + subscriptionType: { + description: 'If this server support subscription, the type that subscription operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getSubscriptionType(); + } + }, + directives: { + description: 'A list of all directives supported by this server.', + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Directive))), + resolve: function resolve(schema) { + return schema.getDirectives(); + } + } + }; + } +}); + +exports.__Schema = __Schema; + +var __Directive = new _definition.GraphQLObjectType({ + name: '__Directive', + description: "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.", + fields: function fields() { + return { + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: function resolve(directive) { + return directive.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(directive) { + return directive.description; + } + }, + isRepeatable: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: function resolve(directive) { + return directive.isRepeatable; + } + }, + locations: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__DirectiveLocation))), + resolve: function resolve(directive) { + return directive.locations; + } + }, + args: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(field, _ref) { + var includeDeprecated = _ref.includeDeprecated; + return includeDeprecated ? field.args : field.args.filter(function (arg) { + return arg.deprecationReason == null; + }); + } + } + }; + } +}); + +exports.__Directive = __Directive; + +var __DirectiveLocation = new _definition.GraphQLEnumType({ + name: '__DirectiveLocation', + description: 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: _directiveLocation.DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.' + }, + MUTATION: { + value: _directiveLocation.DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.' + }, + SUBSCRIPTION: { + value: _directiveLocation.DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.' + }, + FIELD: { + value: _directiveLocation.DirectiveLocation.FIELD, + description: 'Location adjacent to a field.' + }, + FRAGMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.' + }, + FRAGMENT_SPREAD: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.' + }, + INLINE_FRAGMENT: { + value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.' + }, + VARIABLE_DEFINITION: { + value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.' + }, + SCHEMA: { + value: _directiveLocation.DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.' + }, + SCALAR: { + value: _directiveLocation.DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.' + }, + OBJECT: { + value: _directiveLocation.DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.' + }, + FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.' + }, + ARGUMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.' + }, + INTERFACE: { + value: _directiveLocation.DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.' + }, + UNION: { + value: _directiveLocation.DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.' + }, + ENUM: { + value: _directiveLocation.DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.' + }, + ENUM_VALUE: { + value: _directiveLocation.DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.' + }, + INPUT_OBJECT: { + value: _directiveLocation.DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.' + }, + INPUT_FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.' + } + } +}); + +exports.__DirectiveLocation = __DirectiveLocation; + +var __Type = new _definition.GraphQLObjectType({ + name: '__Type', + description: 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByUrl`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.', + fields: function fields() { + return { + kind: { + type: new _definition.GraphQLNonNull(__TypeKind), + resolve: function resolve(type) { + if ((0, _definition.isScalarType)(type)) { + return TypeKind.SCALAR; + } + + if ((0, _definition.isObjectType)(type)) { + return TypeKind.OBJECT; + } + + if ((0, _definition.isInterfaceType)(type)) { + return TypeKind.INTERFACE; + } + + if ((0, _definition.isUnionType)(type)) { + return TypeKind.UNION; + } + + if ((0, _definition.isEnumType)(type)) { + return TypeKind.ENUM; + } + + if ((0, _definition.isInputObjectType)(type)) { + return TypeKind.INPUT_OBJECT; + } + + if ((0, _definition.isListType)(type)) { + return TypeKind.LIST; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if ((0, _definition.isNonNullType)(type)) { + return TypeKind.NON_NULL; + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || (0, _invariant.default)(0, "Unexpected type: \"".concat((0, _inspect.default)(type), "\".")); + } + }, + name: { + type: _scalars.GraphQLString, + resolve: function resolve(type) { + return type.name !== undefined ? type.name : undefined; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(type) { + return type.description !== undefined ? type.description : undefined; + } + }, + specifiedByUrl: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.specifiedByUrl !== undefined ? obj.specifiedByUrl : undefined; + } + }, + fields: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Field)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref2) { + var includeDeprecated = _ref2.includeDeprecated; + + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + var fields = (0, _objectValues.default)(type.getFields()); + return includeDeprecated ? fields : fields.filter(function (field) { + return field.deprecationReason == null; + }); + } + } + }, + interfaces: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + resolve: function resolve(type) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + return type.getInterfaces(); + } + } + }, + possibleTypes: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + resolve: function resolve(type, _args, _context, _ref3) { + var schema = _ref3.schema; + + if ((0, _definition.isAbstractType)(type)) { + return schema.getPossibleTypes(type); + } + } + }, + enumValues: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__EnumValue)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref4) { + var includeDeprecated = _ref4.includeDeprecated; + + if ((0, _definition.isEnumType)(type)) { + var values = type.getValues(); + return includeDeprecated ? values : values.filter(function (field) { + return field.deprecationReason == null; + }); + } + } + }, + inputFields: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref5) { + var includeDeprecated = _ref5.includeDeprecated; + + if ((0, _definition.isInputObjectType)(type)) { + var values = (0, _objectValues.default)(type.getFields()); + return includeDeprecated ? values : values.filter(function (field) { + return field.deprecationReason == null; + }); + } + } + }, + ofType: { + type: __Type, + resolve: function resolve(type) { + return type.ofType !== undefined ? type.ofType : undefined; + } + } + }; + } +}); + +exports.__Type = __Type; + +var __Field = new _definition.GraphQLObjectType({ + name: '__Field', + description: 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.', + fields: function fields() { + return { + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: function resolve(field) { + return field.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(field) { + return field.description; + } + }, + args: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(field, _ref6) { + var includeDeprecated = _ref6.includeDeprecated; + return includeDeprecated ? field.args : field.args.filter(function (arg) { + return arg.deprecationReason == null; + }); + } + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: function resolve(field) { + return field.type; + } + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: function resolve(field) { + return field.deprecationReason != null; + } + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: function resolve(field) { + return field.deprecationReason; + } + } + }; + } +}); + +exports.__Field = __Field; + +var __InputValue = new _definition.GraphQLObjectType({ + name: '__InputValue', + description: 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.', + fields: function fields() { + return { + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: function resolve(inputValue) { + return inputValue.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(inputValue) { + return inputValue.description; + } + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: function resolve(inputValue) { + return inputValue.type; + } + }, + defaultValue: { + type: _scalars.GraphQLString, + description: 'A GraphQL-formatted string representing the default value for this input value.', + resolve: function resolve(inputValue) { + var type = inputValue.type, + defaultValue = inputValue.defaultValue; + var valueAST = (0, _astFromValue.astFromValue)(defaultValue, type); + return valueAST ? (0, _printer.print)(valueAST) : null; + } + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: function resolve(field) { + return field.deprecationReason != null; + } + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.deprecationReason; + } + } + }; + } +}); + +exports.__InputValue = __InputValue; + +var __EnumValue = new _definition.GraphQLObjectType({ + name: '__EnumValue', + description: 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.', + fields: function fields() { + return { + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: function resolve(enumValue) { + return enumValue.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(enumValue) { + return enumValue.description; + } + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: function resolve(enumValue) { + return enumValue.deprecationReason != null; + } + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: function resolve(enumValue) { + return enumValue.deprecationReason; + } + } + }; + } +}); + +exports.__EnumValue = __EnumValue; +var TypeKind = Object.freeze({ + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + INPUT_OBJECT: 'INPUT_OBJECT', + LIST: 'LIST', + NON_NULL: 'NON_NULL' +}); +exports.TypeKind = TypeKind; + +var __TypeKind = new _definition.GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.' + }, + OBJECT: { + value: TypeKind.OBJECT, + description: 'Indicates this type is an object. `fields` and `interfaces` are valid fields.' + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.' + }, + UNION: { + value: TypeKind.UNION, + description: 'Indicates this type is a union. `possibleTypes` is a valid field.' + }, + ENUM: { + value: TypeKind.ENUM, + description: 'Indicates this type is an enum. `enumValues` is a valid field.' + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: 'Indicates this type is an input object. `inputFields` is a valid field.' + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.' + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: 'Indicates this type is a non-null. `ofType` is a valid field.' + } + } +}); +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + + +exports.__TypeKind = __TypeKind; +var SchemaMetaFieldDef = { + name: '__schema', + type: new _definition.GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: function resolve(_source, _args, _context, _ref7) { + var schema = _ref7.schema; + return schema; + }, + isDeprecated: false, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined +}; +exports.SchemaMetaFieldDef = SchemaMetaFieldDef; +var TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [{ + name: 'name', + description: undefined, + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + defaultValue: undefined, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined + }], + resolve: function resolve(_source, _ref8, _context, _ref9) { + var name = _ref8.name; + var schema = _ref9.schema; + return schema.getType(name); + }, + isDeprecated: false, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined +}; +exports.TypeMetaFieldDef = TypeMetaFieldDef; +var TypeNameMetaFieldDef = { + name: '__typename', + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: function resolve(_source, _args, _context, _ref10) { + var parentType = _ref10.parentType; + return parentType.name; + }, + isDeprecated: false, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined +}; +exports.TypeNameMetaFieldDef = TypeNameMetaFieldDef; +var introspectionTypes = Object.freeze([__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]); +exports.introspectionTypes = introspectionTypes; + +function isIntrospectionType(type) { + return introspectionTypes.some(function (_ref11) { + var name = _ref11.name; + return type.name === name; + }); +} diff --git a/school/node_modules/graphql/type/introspection.js.flow b/school/node_modules/graphql/type/introspection.js.flow new file mode 100644 index 0000000..e6eb628 --- /dev/null +++ b/school/node_modules/graphql/type/introspection.js.flow @@ -0,0 +1,560 @@ +// @flow strict +import objectValues from '../polyfills/objectValues'; + +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; + +import { print } from '../language/printer'; +import { DirectiveLocation } from '../language/directiveLocation'; +import { astFromValue } from '../utilities/astFromValue'; + +import type { GraphQLSchema } from './schema'; +import type { GraphQLDirective } from './directives'; +import type { + GraphQLType, + GraphQLNamedType, + GraphQLInputField, + GraphQLEnumValue, + GraphQLField, + GraphQLFieldConfigMap, +} from './definition'; +import { GraphQLString, GraphQLBoolean } from './scalars'; +import { + GraphQLList, + GraphQLNonNull, + GraphQLObjectType, + GraphQLEnumType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isAbstractType, +} from './definition'; + +export const __Schema = new GraphQLObjectType({ + name: '__Schema', + description: + 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.', + fields: () => + ({ + description: { + type: GraphQLString, + resolve: (schema) => schema.description, + }, + types: { + description: 'A list of all types supported by this server.', + type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(__Type))), + resolve(schema) { + return objectValues(schema.getTypeMap()); + }, + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: new GraphQLNonNull(__Type), + resolve: (schema) => schema.getQueryType(), + }, + mutationType: { + description: + 'If this server supports mutation, the type that mutation operations will be rooted at.', + type: __Type, + resolve: (schema) => schema.getMutationType(), + }, + subscriptionType: { + description: + 'If this server support subscription, the type that subscription operations will be rooted at.', + type: __Type, + resolve: (schema) => schema.getSubscriptionType(), + }, + directives: { + description: 'A list of all directives supported by this server.', + type: new GraphQLNonNull( + new GraphQLList(new GraphQLNonNull(__Directive)), + ), + resolve: (schema) => schema.getDirectives(), + }, + }: GraphQLFieldConfigMap<GraphQLSchema, mixed>), +}); + +export const __Directive = new GraphQLObjectType({ + name: '__Directive', + description: + "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.", + fields: () => + ({ + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: (directive) => directive.name, + }, + description: { + type: GraphQLString, + resolve: (directive) => directive.description, + }, + isRepeatable: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: (directive) => directive.isRepeatable, + }, + locations: { + type: new GraphQLNonNull( + new GraphQLList(new GraphQLNonNull(__DirectiveLocation)), + ), + resolve: (directive) => directive.locations, + }, + args: { + type: new GraphQLNonNull( + new GraphQLList(new GraphQLNonNull(__InputValue)), + ), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false, + }, + }, + resolve(field, { includeDeprecated }) { + return includeDeprecated + ? field.args + : field.args.filter((arg) => arg.deprecationReason == null); + }, + }, + }: GraphQLFieldConfigMap<GraphQLDirective, mixed>), +}); + +export const __DirectiveLocation = new GraphQLEnumType({ + name: '__DirectiveLocation', + description: + 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.', + }, + MUTATION: { + value: DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.', + }, + SUBSCRIPTION: { + value: DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.', + }, + FIELD: { + value: DirectiveLocation.FIELD, + description: 'Location adjacent to a field.', + }, + FRAGMENT_DEFINITION: { + value: DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.', + }, + FRAGMENT_SPREAD: { + value: DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.', + }, + INLINE_FRAGMENT: { + value: DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.', + }, + VARIABLE_DEFINITION: { + value: DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.', + }, + SCHEMA: { + value: DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.', + }, + SCALAR: { + value: DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.', + }, + OBJECT: { + value: DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.', + }, + FIELD_DEFINITION: { + value: DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.', + }, + ARGUMENT_DEFINITION: { + value: DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.', + }, + INTERFACE: { + value: DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.', + }, + UNION: { + value: DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.', + }, + ENUM: { + value: DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.', + }, + ENUM_VALUE: { + value: DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.', + }, + INPUT_OBJECT: { + value: DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.', + }, + INPUT_FIELD_DEFINITION: { + value: DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.', + }, + }, +}); + +export const __Type = new GraphQLObjectType({ + name: '__Type', + description: + 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByUrl`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.', + fields: () => + ({ + kind: { + type: new GraphQLNonNull(__TypeKind), + resolve(type) { + if (isScalarType(type)) { + return TypeKind.SCALAR; + } + if (isObjectType(type)) { + return TypeKind.OBJECT; + } + if (isInterfaceType(type)) { + return TypeKind.INTERFACE; + } + if (isUnionType(type)) { + return TypeKind.UNION; + } + if (isEnumType(type)) { + return TypeKind.ENUM; + } + if (isInputObjectType(type)) { + return TypeKind.INPUT_OBJECT; + } + if (isListType(type)) { + return TypeKind.LIST; + } + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + if (isNonNullType(type)) { + return TypeKind.NON_NULL; + } + + // istanbul ignore next (Not reachable. All possible types have been considered) + invariant(false, `Unexpected type: "${inspect((type: empty))}".`); + }, + }, + name: { + type: GraphQLString, + resolve: (type) => (type.name !== undefined ? type.name : undefined), + }, + description: { + type: GraphQLString, + resolve: (type) => + type.description !== undefined ? type.description : undefined, + }, + specifiedByUrl: { + type: GraphQLString, + resolve: (obj) => + obj.specifiedByUrl !== undefined ? obj.specifiedByUrl : undefined, + }, + fields: { + type: new GraphQLList(new GraphQLNonNull(__Field)), + args: { + includeDeprecated: { type: GraphQLBoolean, defaultValue: false }, + }, + resolve(type, { includeDeprecated }) { + if (isObjectType(type) || isInterfaceType(type)) { + const fields = objectValues(type.getFields()); + return includeDeprecated + ? fields + : fields.filter((field) => field.deprecationReason == null); + } + }, + }, + interfaces: { + type: new GraphQLList(new GraphQLNonNull(__Type)), + resolve(type) { + if (isObjectType(type) || isInterfaceType(type)) { + return type.getInterfaces(); + } + }, + }, + possibleTypes: { + type: new GraphQLList(new GraphQLNonNull(__Type)), + resolve(type, _args, _context, { schema }) { + if (isAbstractType(type)) { + return schema.getPossibleTypes(type); + } + }, + }, + enumValues: { + type: new GraphQLList(new GraphQLNonNull(__EnumValue)), + args: { + includeDeprecated: { type: GraphQLBoolean, defaultValue: false }, + }, + resolve(type, { includeDeprecated }) { + if (isEnumType(type)) { + const values = type.getValues(); + return includeDeprecated + ? values + : values.filter((field) => field.deprecationReason == null); + } + }, + }, + inputFields: { + type: new GraphQLList(new GraphQLNonNull(__InputValue)), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false, + }, + }, + resolve(type, { includeDeprecated }) { + if (isInputObjectType(type)) { + const values = objectValues(type.getFields()); + return includeDeprecated + ? values + : values.filter((field) => field.deprecationReason == null); + } + }, + }, + ofType: { + type: __Type, + resolve: (type) => + type.ofType !== undefined ? type.ofType : undefined, + }, + }: GraphQLFieldConfigMap<GraphQLType, mixed>), +}); + +export const __Field = new GraphQLObjectType({ + name: '__Field', + description: + 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.', + fields: () => + ({ + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: (field) => field.name, + }, + description: { + type: GraphQLString, + resolve: (field) => field.description, + }, + args: { + type: new GraphQLNonNull( + new GraphQLList(new GraphQLNonNull(__InputValue)), + ), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false, + }, + }, + resolve(field, { includeDeprecated }) { + return includeDeprecated + ? field.args + : field.args.filter((arg) => arg.deprecationReason == null); + }, + }, + type: { + type: new GraphQLNonNull(__Type), + resolve: (field) => field.type, + }, + isDeprecated: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: (field) => field.deprecationReason != null, + }, + deprecationReason: { + type: GraphQLString, + resolve: (field) => field.deprecationReason, + }, + }: GraphQLFieldConfigMap<GraphQLField<mixed, mixed>, mixed>), +}); + +export const __InputValue = new GraphQLObjectType({ + name: '__InputValue', + description: + 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.', + fields: () => + ({ + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: (inputValue) => inputValue.name, + }, + description: { + type: GraphQLString, + resolve: (inputValue) => inputValue.description, + }, + type: { + type: new GraphQLNonNull(__Type), + resolve: (inputValue) => inputValue.type, + }, + defaultValue: { + type: GraphQLString, + description: + 'A GraphQL-formatted string representing the default value for this input value.', + resolve(inputValue) { + const { type, defaultValue } = inputValue; + const valueAST = astFromValue(defaultValue, type); + return valueAST ? print(valueAST) : null; + }, + }, + isDeprecated: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: (field) => field.deprecationReason != null, + }, + deprecationReason: { + type: GraphQLString, + resolve: (obj) => obj.deprecationReason, + }, + }: GraphQLFieldConfigMap<GraphQLInputField, mixed>), +}); + +export const __EnumValue = new GraphQLObjectType({ + name: '__EnumValue', + description: + 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.', + fields: () => + ({ + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: (enumValue) => enumValue.name, + }, + description: { + type: GraphQLString, + resolve: (enumValue) => enumValue.description, + }, + isDeprecated: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: (enumValue) => enumValue.deprecationReason != null, + }, + deprecationReason: { + type: GraphQLString, + resolve: (enumValue) => enumValue.deprecationReason, + }, + }: GraphQLFieldConfigMap<GraphQLEnumValue, mixed>), +}); + +export const TypeKind = Object.freeze({ + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + INPUT_OBJECT: 'INPUT_OBJECT', + LIST: 'LIST', + NON_NULL: 'NON_NULL', +}); + +export const __TypeKind = new GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.', + }, + OBJECT: { + value: TypeKind.OBJECT, + description: + 'Indicates this type is an object. `fields` and `interfaces` are valid fields.', + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: + 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.', + }, + UNION: { + value: TypeKind.UNION, + description: + 'Indicates this type is a union. `possibleTypes` is a valid field.', + }, + ENUM: { + value: TypeKind.ENUM, + description: + 'Indicates this type is an enum. `enumValues` is a valid field.', + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: + 'Indicates this type is an input object. `inputFields` is a valid field.', + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.', + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: + 'Indicates this type is a non-null. `ofType` is a valid field.', + }, + }, +}); + +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +export const SchemaMetaFieldDef: GraphQLField<mixed, mixed> = { + name: '__schema', + type: new GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: (_source, _args, _context, { schema }) => schema, + isDeprecated: false, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined, +}; + +export const TypeMetaFieldDef: GraphQLField<mixed, mixed> = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [ + { + name: 'name', + description: undefined, + type: new GraphQLNonNull(GraphQLString), + defaultValue: undefined, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined, + }, + ], + resolve: (_source, { name }, _context, { schema }) => schema.getType(name), + isDeprecated: false, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined, +}; + +export const TypeNameMetaFieldDef: GraphQLField<mixed, mixed> = { + name: '__typename', + type: new GraphQLNonNull(GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: (_source, _args, _context, { parentType }) => parentType.name, + isDeprecated: false, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined, +}; + +export const introspectionTypes = Object.freeze([ + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, +]); + +export function isIntrospectionType(type: GraphQLNamedType): boolean %checks { + return introspectionTypes.some(({ name }) => type.name === name); +} diff --git a/school/node_modules/graphql/type/introspection.mjs b/school/node_modules/graphql/type/introspection.mjs new file mode 100644 index 0000000..2448a59 --- /dev/null +++ b/school/node_modules/graphql/type/introspection.mjs @@ -0,0 +1,577 @@ +import objectValues from "../polyfills/objectValues.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import invariant from "../jsutils/invariant.mjs"; +import { print } from "../language/printer.mjs"; +import { DirectiveLocation } from "../language/directiveLocation.mjs"; +import { astFromValue } from "../utilities/astFromValue.mjs"; +import { GraphQLString, GraphQLBoolean } from "./scalars.mjs"; +import { GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLEnumType, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isListType, isNonNullType, isAbstractType } from "./definition.mjs"; +export var __Schema = new GraphQLObjectType({ + name: '__Schema', + description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.', + fields: function fields() { + return { + description: { + type: GraphQLString, + resolve: function resolve(schema) { + return schema.description; + } + }, + types: { + description: 'A list of all types supported by this server.', + type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(__Type))), + resolve: function resolve(schema) { + return objectValues(schema.getTypeMap()); + } + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: new GraphQLNonNull(__Type), + resolve: function resolve(schema) { + return schema.getQueryType(); + } + }, + mutationType: { + description: 'If this server supports mutation, the type that mutation operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getMutationType(); + } + }, + subscriptionType: { + description: 'If this server support subscription, the type that subscription operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getSubscriptionType(); + } + }, + directives: { + description: 'A list of all directives supported by this server.', + type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(__Directive))), + resolve: function resolve(schema) { + return schema.getDirectives(); + } + } + }; + } +}); +export var __Directive = new GraphQLObjectType({ + name: '__Directive', + description: "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.", + fields: function fields() { + return { + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: function resolve(directive) { + return directive.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(directive) { + return directive.description; + } + }, + isRepeatable: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: function resolve(directive) { + return directive.isRepeatable; + } + }, + locations: { + type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(__DirectiveLocation))), + resolve: function resolve(directive) { + return directive.locations; + } + }, + args: { + type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(__InputValue))), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(field, _ref) { + var includeDeprecated = _ref.includeDeprecated; + return includeDeprecated ? field.args : field.args.filter(function (arg) { + return arg.deprecationReason == null; + }); + } + } + }; + } +}); +export var __DirectiveLocation = new GraphQLEnumType({ + name: '__DirectiveLocation', + description: 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.' + }, + MUTATION: { + value: DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.' + }, + SUBSCRIPTION: { + value: DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.' + }, + FIELD: { + value: DirectiveLocation.FIELD, + description: 'Location adjacent to a field.' + }, + FRAGMENT_DEFINITION: { + value: DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.' + }, + FRAGMENT_SPREAD: { + value: DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.' + }, + INLINE_FRAGMENT: { + value: DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.' + }, + VARIABLE_DEFINITION: { + value: DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.' + }, + SCHEMA: { + value: DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.' + }, + SCALAR: { + value: DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.' + }, + OBJECT: { + value: DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.' + }, + FIELD_DEFINITION: { + value: DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.' + }, + ARGUMENT_DEFINITION: { + value: DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.' + }, + INTERFACE: { + value: DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.' + }, + UNION: { + value: DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.' + }, + ENUM: { + value: DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.' + }, + ENUM_VALUE: { + value: DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.' + }, + INPUT_OBJECT: { + value: DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.' + }, + INPUT_FIELD_DEFINITION: { + value: DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.' + } + } +}); +export var __Type = new GraphQLObjectType({ + name: '__Type', + description: 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByUrl`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.', + fields: function fields() { + return { + kind: { + type: new GraphQLNonNull(__TypeKind), + resolve: function resolve(type) { + if (isScalarType(type)) { + return TypeKind.SCALAR; + } + + if (isObjectType(type)) { + return TypeKind.OBJECT; + } + + if (isInterfaceType(type)) { + return TypeKind.INTERFACE; + } + + if (isUnionType(type)) { + return TypeKind.UNION; + } + + if (isEnumType(type)) { + return TypeKind.ENUM; + } + + if (isInputObjectType(type)) { + return TypeKind.INPUT_OBJECT; + } + + if (isListType(type)) { + return TypeKind.LIST; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if (isNonNullType(type)) { + return TypeKind.NON_NULL; + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || invariant(0, "Unexpected type: \"".concat(inspect(type), "\".")); + } + }, + name: { + type: GraphQLString, + resolve: function resolve(type) { + return type.name !== undefined ? type.name : undefined; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(type) { + return type.description !== undefined ? type.description : undefined; + } + }, + specifiedByUrl: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.specifiedByUrl !== undefined ? obj.specifiedByUrl : undefined; + } + }, + fields: { + type: new GraphQLList(new GraphQLNonNull(__Field)), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref2) { + var includeDeprecated = _ref2.includeDeprecated; + + if (isObjectType(type) || isInterfaceType(type)) { + var fields = objectValues(type.getFields()); + return includeDeprecated ? fields : fields.filter(function (field) { + return field.deprecationReason == null; + }); + } + } + }, + interfaces: { + type: new GraphQLList(new GraphQLNonNull(__Type)), + resolve: function resolve(type) { + if (isObjectType(type) || isInterfaceType(type)) { + return type.getInterfaces(); + } + } + }, + possibleTypes: { + type: new GraphQLList(new GraphQLNonNull(__Type)), + resolve: function resolve(type, _args, _context, _ref3) { + var schema = _ref3.schema; + + if (isAbstractType(type)) { + return schema.getPossibleTypes(type); + } + } + }, + enumValues: { + type: new GraphQLList(new GraphQLNonNull(__EnumValue)), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref4) { + var includeDeprecated = _ref4.includeDeprecated; + + if (isEnumType(type)) { + var values = type.getValues(); + return includeDeprecated ? values : values.filter(function (field) { + return field.deprecationReason == null; + }); + } + } + }, + inputFields: { + type: new GraphQLList(new GraphQLNonNull(__InputValue)), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref5) { + var includeDeprecated = _ref5.includeDeprecated; + + if (isInputObjectType(type)) { + var values = objectValues(type.getFields()); + return includeDeprecated ? values : values.filter(function (field) { + return field.deprecationReason == null; + }); + } + } + }, + ofType: { + type: __Type, + resolve: function resolve(type) { + return type.ofType !== undefined ? type.ofType : undefined; + } + } + }; + } +}); +export var __Field = new GraphQLObjectType({ + name: '__Field', + description: 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.', + fields: function fields() { + return { + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: function resolve(field) { + return field.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(field) { + return field.description; + } + }, + args: { + type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(__InputValue))), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(field, _ref6) { + var includeDeprecated = _ref6.includeDeprecated; + return includeDeprecated ? field.args : field.args.filter(function (arg) { + return arg.deprecationReason == null; + }); + } + }, + type: { + type: new GraphQLNonNull(__Type), + resolve: function resolve(field) { + return field.type; + } + }, + isDeprecated: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: function resolve(field) { + return field.deprecationReason != null; + } + }, + deprecationReason: { + type: GraphQLString, + resolve: function resolve(field) { + return field.deprecationReason; + } + } + }; + } +}); +export var __InputValue = new GraphQLObjectType({ + name: '__InputValue', + description: 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.', + fields: function fields() { + return { + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: function resolve(inputValue) { + return inputValue.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(inputValue) { + return inputValue.description; + } + }, + type: { + type: new GraphQLNonNull(__Type), + resolve: function resolve(inputValue) { + return inputValue.type; + } + }, + defaultValue: { + type: GraphQLString, + description: 'A GraphQL-formatted string representing the default value for this input value.', + resolve: function resolve(inputValue) { + var type = inputValue.type, + defaultValue = inputValue.defaultValue; + var valueAST = astFromValue(defaultValue, type); + return valueAST ? print(valueAST) : null; + } + }, + isDeprecated: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: function resolve(field) { + return field.deprecationReason != null; + } + }, + deprecationReason: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.deprecationReason; + } + } + }; + } +}); +export var __EnumValue = new GraphQLObjectType({ + name: '__EnumValue', + description: 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.', + fields: function fields() { + return { + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: function resolve(enumValue) { + return enumValue.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(enumValue) { + return enumValue.description; + } + }, + isDeprecated: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: function resolve(enumValue) { + return enumValue.deprecationReason != null; + } + }, + deprecationReason: { + type: GraphQLString, + resolve: function resolve(enumValue) { + return enumValue.deprecationReason; + } + } + }; + } +}); +export var TypeKind = Object.freeze({ + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + INPUT_OBJECT: 'INPUT_OBJECT', + LIST: 'LIST', + NON_NULL: 'NON_NULL' +}); +export var __TypeKind = new GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.' + }, + OBJECT: { + value: TypeKind.OBJECT, + description: 'Indicates this type is an object. `fields` and `interfaces` are valid fields.' + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.' + }, + UNION: { + value: TypeKind.UNION, + description: 'Indicates this type is a union. `possibleTypes` is a valid field.' + }, + ENUM: { + value: TypeKind.ENUM, + description: 'Indicates this type is an enum. `enumValues` is a valid field.' + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: 'Indicates this type is an input object. `inputFields` is a valid field.' + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.' + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: 'Indicates this type is a non-null. `ofType` is a valid field.' + } + } +}); +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +export var SchemaMetaFieldDef = { + name: '__schema', + type: new GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: function resolve(_source, _args, _context, _ref7) { + var schema = _ref7.schema; + return schema; + }, + isDeprecated: false, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined +}; +export var TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [{ + name: 'name', + description: undefined, + type: new GraphQLNonNull(GraphQLString), + defaultValue: undefined, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined + }], + resolve: function resolve(_source, _ref8, _context, _ref9) { + var name = _ref8.name; + var schema = _ref9.schema; + return schema.getType(name); + }, + isDeprecated: false, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined +}; +export var TypeNameMetaFieldDef = { + name: '__typename', + type: new GraphQLNonNull(GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: function resolve(_source, _args, _context, _ref10) { + var parentType = _ref10.parentType; + return parentType.name; + }, + isDeprecated: false, + deprecationReason: undefined, + extensions: undefined, + astNode: undefined +}; +export var introspectionTypes = Object.freeze([__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]); +export function isIntrospectionType(type) { + return introspectionTypes.some(function (_ref11) { + var name = _ref11.name; + return type.name === name; + }); +} diff --git a/school/node_modules/graphql/type/scalars.d.ts b/school/node_modules/graphql/type/scalars.d.ts new file mode 100644 index 0000000..71593d1 --- /dev/null +++ b/school/node_modules/graphql/type/scalars.d.ts @@ -0,0 +1,11 @@ +import { GraphQLScalarType, GraphQLNamedType } from './definition'; + +export const GraphQLInt: GraphQLScalarType; +export const GraphQLFloat: GraphQLScalarType; +export const GraphQLString: GraphQLScalarType; +export const GraphQLBoolean: GraphQLScalarType; +export const GraphQLID: GraphQLScalarType; + +export const specifiedScalarTypes: ReadonlyArray<GraphQLScalarType>; + +export function isSpecifiedScalarType(type: GraphQLNamedType): boolean; diff --git a/school/node_modules/graphql/type/scalars.js b/school/node_modules/graphql/type/scalars.js new file mode 100644 index 0000000..ca1f35b --- /dev/null +++ b/school/node_modules/graphql/type/scalars.js @@ -0,0 +1,284 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isSpecifiedScalarType = isSpecifiedScalarType; +exports.specifiedScalarTypes = exports.GraphQLID = exports.GraphQLBoolean = exports.GraphQLString = exports.GraphQLFloat = exports.GraphQLInt = void 0; + +var _isFinite = _interopRequireDefault(require("../polyfills/isFinite.js")); + +var _isInteger = _interopRequireDefault(require("../polyfills/isInteger.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _isObjectLike = _interopRequireDefault(require("../jsutils/isObjectLike.js")); + +var _kinds = require("../language/kinds.js"); + +var _printer = require("../language/printer.js"); + +var _GraphQLError = require("../error/GraphQLError.js"); + +var _definition = require("./definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// As per the GraphQL Spec, Integers are only treated as valid when a valid +// 32-bit signed integer, providing the broadest support across platforms. +// +// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because +// they are internally represented as IEEE 754 doubles. +var MAX_INT = 2147483647; +var MIN_INT = -2147483648; + +function serializeInt(outputValue) { + var coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + var num = coercedValue; + + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (!(0, _isInteger.default)(num)) { + throw new _GraphQLError.GraphQLError("Int cannot represent non-integer value: ".concat((0, _inspect.default)(coercedValue))); + } + + if (num > MAX_INT || num < MIN_INT) { + throw new _GraphQLError.GraphQLError('Int cannot represent non 32-bit signed integer value: ' + (0, _inspect.default)(coercedValue)); + } + + return num; +} + +function coerceInt(inputValue) { + if (!(0, _isInteger.default)(inputValue)) { + throw new _GraphQLError.GraphQLError("Int cannot represent non-integer value: ".concat((0, _inspect.default)(inputValue))); + } + + if (inputValue > MAX_INT || inputValue < MIN_INT) { + throw new _GraphQLError.GraphQLError("Int cannot represent non 32-bit signed integer value: ".concat(inputValue)); + } + + return inputValue; +} + +var GraphQLInt = new _definition.GraphQLScalarType({ + name: 'Int', + description: 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.', + serialize: serializeInt, + parseValue: coerceInt, + parseLiteral: function parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError("Int cannot represent non-integer value: ".concat((0, _printer.print)(valueNode)), valueNode); + } + + var num = parseInt(valueNode.value, 10); + + if (num > MAX_INT || num < MIN_INT) { + throw new _GraphQLError.GraphQLError("Int cannot represent non 32-bit signed integer value: ".concat(valueNode.value), valueNode); + } + + return num; + } +}); +exports.GraphQLInt = GraphQLInt; + +function serializeFloat(outputValue) { + var coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + var num = coercedValue; + + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (!(0, _isFinite.default)(num)) { + throw new _GraphQLError.GraphQLError("Float cannot represent non numeric value: ".concat((0, _inspect.default)(coercedValue))); + } + + return num; +} + +function coerceFloat(inputValue) { + if (!(0, _isFinite.default)(inputValue)) { + throw new _GraphQLError.GraphQLError("Float cannot represent non numeric value: ".concat((0, _inspect.default)(inputValue))); + } + + return inputValue; +} + +var GraphQLFloat = new _definition.GraphQLScalarType({ + name: 'Float', + description: 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).', + serialize: serializeFloat, + parseValue: coerceFloat, + parseLiteral: function parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.FLOAT && valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError("Float cannot represent non numeric value: ".concat((0, _printer.print)(valueNode)), valueNode); + } + + return parseFloat(valueNode.value); + } +}); // Support serializing objects with custom valueOf() or toJSON() functions - +// a common way to represent a complex value which can be represented as +// a string (ex: MongoDB id objects). + +exports.GraphQLFloat = GraphQLFloat; + +function serializeObject(outputValue) { + if ((0, _isObjectLike.default)(outputValue)) { + if (typeof outputValue.valueOf === 'function') { + var valueOfResult = outputValue.valueOf(); + + if (!(0, _isObjectLike.default)(valueOfResult)) { + return valueOfResult; + } + } + + if (typeof outputValue.toJSON === 'function') { + // $FlowFixMe[incompatible-use] + return outputValue.toJSON(); + } + } + + return outputValue; +} + +function serializeString(outputValue) { + var coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof coercedValue === 'string') { + return coercedValue; + } + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 'true' : 'false'; + } + + if ((0, _isFinite.default)(coercedValue)) { + return coercedValue.toString(); + } + + throw new _GraphQLError.GraphQLError("String cannot represent value: ".concat((0, _inspect.default)(outputValue))); +} + +function coerceString(inputValue) { + if (typeof inputValue !== 'string') { + throw new _GraphQLError.GraphQLError("String cannot represent a non string value: ".concat((0, _inspect.default)(inputValue))); + } + + return inputValue; +} + +var GraphQLString = new _definition.GraphQLScalarType({ + name: 'String', + description: 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.', + serialize: serializeString, + parseValue: coerceString, + parseLiteral: function parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.STRING) { + throw new _GraphQLError.GraphQLError("String cannot represent a non string value: ".concat((0, _printer.print)(valueNode)), valueNode); + } + + return valueNode.value; + } +}); +exports.GraphQLString = GraphQLString; + +function serializeBoolean(outputValue) { + var coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue; + } + + if ((0, _isFinite.default)(coercedValue)) { + return coercedValue !== 0; + } + + throw new _GraphQLError.GraphQLError("Boolean cannot represent a non boolean value: ".concat((0, _inspect.default)(coercedValue))); +} + +function coerceBoolean(inputValue) { + if (typeof inputValue !== 'boolean') { + throw new _GraphQLError.GraphQLError("Boolean cannot represent a non boolean value: ".concat((0, _inspect.default)(inputValue))); + } + + return inputValue; +} + +var GraphQLBoolean = new _definition.GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize: serializeBoolean, + parseValue: coerceBoolean, + parseLiteral: function parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.BOOLEAN) { + throw new _GraphQLError.GraphQLError("Boolean cannot represent a non boolean value: ".concat((0, _printer.print)(valueNode)), valueNode); + } + + return valueNode.value; + } +}); +exports.GraphQLBoolean = GraphQLBoolean; + +function serializeID(outputValue) { + var coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'string') { + return coercedValue; + } + + if ((0, _isInteger.default)(coercedValue)) { + return String(coercedValue); + } + + throw new _GraphQLError.GraphQLError("ID cannot represent value: ".concat((0, _inspect.default)(outputValue))); +} + +function coerceID(inputValue) { + if (typeof inputValue === 'string') { + return inputValue; + } + + if ((0, _isInteger.default)(inputValue)) { + return inputValue.toString(); + } + + throw new _GraphQLError.GraphQLError("ID cannot represent value: ".concat((0, _inspect.default)(inputValue))); +} + +var GraphQLID = new _definition.GraphQLScalarType({ + name: 'ID', + description: 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.', + serialize: serializeID, + parseValue: coerceID, + parseLiteral: function parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.STRING && valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError('ID cannot represent a non-string and non-integer value: ' + (0, _printer.print)(valueNode), valueNode); + } + + return valueNode.value; + } +}); +exports.GraphQLID = GraphQLID; +var specifiedScalarTypes = Object.freeze([GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]); +exports.specifiedScalarTypes = specifiedScalarTypes; + +function isSpecifiedScalarType(type) { + return specifiedScalarTypes.some(function (_ref) { + var name = _ref.name; + return type.name === name; + }); +} diff --git a/school/node_modules/graphql/type/scalars.js.flow b/school/node_modules/graphql/type/scalars.js.flow new file mode 100644 index 0000000..b72b579 --- /dev/null +++ b/school/node_modules/graphql/type/scalars.js.flow @@ -0,0 +1,287 @@ +// @flow strict +import isFinite from '../polyfills/isFinite'; +import isInteger from '../polyfills/isInteger'; + +import inspect from '../jsutils/inspect'; +import isObjectLike from '../jsutils/isObjectLike'; + +import { Kind } from '../language/kinds'; +import { print } from '../language/printer'; + +import { GraphQLError } from '../error/GraphQLError'; + +import type { GraphQLNamedType } from './definition'; +import { GraphQLScalarType } from './definition'; + +// As per the GraphQL Spec, Integers are only treated as valid when a valid +// 32-bit signed integer, providing the broadest support across platforms. +// +// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because +// they are internally represented as IEEE 754 doubles. +const MAX_INT = 2147483647; +const MIN_INT = -2147483648; + +function serializeInt(outputValue: mixed): number { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + let num = coercedValue; + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (!isInteger(num)) { + throw new GraphQLError( + `Int cannot represent non-integer value: ${inspect(coercedValue)}`, + ); + } + if (num > MAX_INT || num < MIN_INT) { + throw new GraphQLError( + 'Int cannot represent non 32-bit signed integer value: ' + + inspect(coercedValue), + ); + } + return num; +} + +function coerceInt(inputValue: mixed): number { + if (!isInteger(inputValue)) { + throw new GraphQLError( + `Int cannot represent non-integer value: ${inspect(inputValue)}`, + ); + } + if (inputValue > MAX_INT || inputValue < MIN_INT) { + throw new GraphQLError( + `Int cannot represent non 32-bit signed integer value: ${inputValue}`, + ); + } + return inputValue; +} + +export const GraphQLInt = new GraphQLScalarType({ + name: 'Int', + description: + 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.', + serialize: serializeInt, + parseValue: coerceInt, + parseLiteral(valueNode) { + if (valueNode.kind !== Kind.INT) { + throw new GraphQLError( + `Int cannot represent non-integer value: ${print(valueNode)}`, + valueNode, + ); + } + const num = parseInt(valueNode.value, 10); + if (num > MAX_INT || num < MIN_INT) { + throw new GraphQLError( + `Int cannot represent non 32-bit signed integer value: ${valueNode.value}`, + valueNode, + ); + } + return num; + }, +}); + +function serializeFloat(outputValue: mixed): number { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + let num = coercedValue; + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (!isFinite(num)) { + throw new GraphQLError( + `Float cannot represent non numeric value: ${inspect(coercedValue)}`, + ); + } + return num; +} + +function coerceFloat(inputValue: mixed): number { + if (!isFinite(inputValue)) { + throw new GraphQLError( + `Float cannot represent non numeric value: ${inspect(inputValue)}`, + ); + } + return inputValue; +} + +export const GraphQLFloat = new GraphQLScalarType({ + name: 'Float', + description: + 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).', + serialize: serializeFloat, + parseValue: coerceFloat, + parseLiteral(valueNode) { + if (valueNode.kind !== Kind.FLOAT && valueNode.kind !== Kind.INT) { + throw new GraphQLError( + `Float cannot represent non numeric value: ${print(valueNode)}`, + valueNode, + ); + } + return parseFloat(valueNode.value); + }, +}); + +// Support serializing objects with custom valueOf() or toJSON() functions - +// a common way to represent a complex value which can be represented as +// a string (ex: MongoDB id objects). +function serializeObject(outputValue: mixed): mixed { + if (isObjectLike(outputValue)) { + if (typeof outputValue.valueOf === 'function') { + const valueOfResult = outputValue.valueOf(); + if (!isObjectLike(valueOfResult)) { + return valueOfResult; + } + } + if (typeof outputValue.toJSON === 'function') { + // $FlowFixMe[incompatible-use] + return outputValue.toJSON(); + } + } + return outputValue; +} + +function serializeString(outputValue: mixed): string { + const coercedValue = serializeObject(outputValue); + + // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + if (typeof coercedValue === 'string') { + return coercedValue; + } + if (typeof coercedValue === 'boolean') { + return coercedValue ? 'true' : 'false'; + } + if (isFinite(coercedValue)) { + return coercedValue.toString(); + } + throw new GraphQLError( + `String cannot represent value: ${inspect(outputValue)}`, + ); +} + +function coerceString(inputValue: mixed): string { + if (typeof inputValue !== 'string') { + throw new GraphQLError( + `String cannot represent a non string value: ${inspect(inputValue)}`, + ); + } + return inputValue; +} + +export const GraphQLString = new GraphQLScalarType({ + name: 'String', + description: + 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.', + serialize: serializeString, + parseValue: coerceString, + parseLiteral(valueNode) { + if (valueNode.kind !== Kind.STRING) { + throw new GraphQLError( + `String cannot represent a non string value: ${print(valueNode)}`, + valueNode, + ); + } + return valueNode.value; + }, +}); + +function serializeBoolean(outputValue: mixed): boolean { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue; + } + if (isFinite(coercedValue)) { + return coercedValue !== 0; + } + throw new GraphQLError( + `Boolean cannot represent a non boolean value: ${inspect(coercedValue)}`, + ); +} + +function coerceBoolean(inputValue: mixed): boolean { + if (typeof inputValue !== 'boolean') { + throw new GraphQLError( + `Boolean cannot represent a non boolean value: ${inspect(inputValue)}`, + ); + } + return inputValue; +} + +export const GraphQLBoolean = new GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize: serializeBoolean, + parseValue: coerceBoolean, + parseLiteral(valueNode) { + if (valueNode.kind !== Kind.BOOLEAN) { + throw new GraphQLError( + `Boolean cannot represent a non boolean value: ${print(valueNode)}`, + valueNode, + ); + } + return valueNode.value; + }, +}); + +function serializeID(outputValue: mixed): string { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'string') { + return coercedValue; + } + if (isInteger(coercedValue)) { + return String(coercedValue); + } + throw new GraphQLError(`ID cannot represent value: ${inspect(outputValue)}`); +} + +function coerceID(inputValue: mixed): string { + if (typeof inputValue === 'string') { + return inputValue; + } + if (isInteger(inputValue)) { + return inputValue.toString(); + } + throw new GraphQLError(`ID cannot represent value: ${inspect(inputValue)}`); +} + +export const GraphQLID = new GraphQLScalarType({ + name: 'ID', + description: + 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.', + serialize: serializeID, + parseValue: coerceID, + parseLiteral(valueNode) { + if (valueNode.kind !== Kind.STRING && valueNode.kind !== Kind.INT) { + throw new GraphQLError( + 'ID cannot represent a non-string and non-integer value: ' + + print(valueNode), + valueNode, + ); + } + return valueNode.value; + }, +}); + +export const specifiedScalarTypes = Object.freeze([ + GraphQLString, + GraphQLInt, + GraphQLFloat, + GraphQLBoolean, + GraphQLID, +]); + +export function isSpecifiedScalarType(type: GraphQLNamedType): boolean %checks { + return specifiedScalarTypes.some(({ name }) => type.name === name); +} diff --git a/school/node_modules/graphql/type/scalars.mjs b/school/node_modules/graphql/type/scalars.mjs new file mode 100644 index 0000000..e6f76a0 --- /dev/null +++ b/school/node_modules/graphql/type/scalars.mjs @@ -0,0 +1,258 @@ +import isFinite from "../polyfills/isFinite.mjs"; +import isInteger from "../polyfills/isInteger.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import isObjectLike from "../jsutils/isObjectLike.mjs"; +import { Kind } from "../language/kinds.mjs"; +import { print } from "../language/printer.mjs"; +import { GraphQLError } from "../error/GraphQLError.mjs"; +import { GraphQLScalarType } from "./definition.mjs"; // As per the GraphQL Spec, Integers are only treated as valid when a valid +// 32-bit signed integer, providing the broadest support across platforms. +// +// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because +// they are internally represented as IEEE 754 doubles. + +var MAX_INT = 2147483647; +var MIN_INT = -2147483648; + +function serializeInt(outputValue) { + var coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + var num = coercedValue; + + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (!isInteger(num)) { + throw new GraphQLError("Int cannot represent non-integer value: ".concat(inspect(coercedValue))); + } + + if (num > MAX_INT || num < MIN_INT) { + throw new GraphQLError('Int cannot represent non 32-bit signed integer value: ' + inspect(coercedValue)); + } + + return num; +} + +function coerceInt(inputValue) { + if (!isInteger(inputValue)) { + throw new GraphQLError("Int cannot represent non-integer value: ".concat(inspect(inputValue))); + } + + if (inputValue > MAX_INT || inputValue < MIN_INT) { + throw new GraphQLError("Int cannot represent non 32-bit signed integer value: ".concat(inputValue)); + } + + return inputValue; +} + +export var GraphQLInt = new GraphQLScalarType({ + name: 'Int', + description: 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.', + serialize: serializeInt, + parseValue: coerceInt, + parseLiteral: function parseLiteral(valueNode) { + if (valueNode.kind !== Kind.INT) { + throw new GraphQLError("Int cannot represent non-integer value: ".concat(print(valueNode)), valueNode); + } + + var num = parseInt(valueNode.value, 10); + + if (num > MAX_INT || num < MIN_INT) { + throw new GraphQLError("Int cannot represent non 32-bit signed integer value: ".concat(valueNode.value), valueNode); + } + + return num; + } +}); + +function serializeFloat(outputValue) { + var coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + var num = coercedValue; + + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (!isFinite(num)) { + throw new GraphQLError("Float cannot represent non numeric value: ".concat(inspect(coercedValue))); + } + + return num; +} + +function coerceFloat(inputValue) { + if (!isFinite(inputValue)) { + throw new GraphQLError("Float cannot represent non numeric value: ".concat(inspect(inputValue))); + } + + return inputValue; +} + +export var GraphQLFloat = new GraphQLScalarType({ + name: 'Float', + description: 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).', + serialize: serializeFloat, + parseValue: coerceFloat, + parseLiteral: function parseLiteral(valueNode) { + if (valueNode.kind !== Kind.FLOAT && valueNode.kind !== Kind.INT) { + throw new GraphQLError("Float cannot represent non numeric value: ".concat(print(valueNode)), valueNode); + } + + return parseFloat(valueNode.value); + } +}); // Support serializing objects with custom valueOf() or toJSON() functions - +// a common way to represent a complex value which can be represented as +// a string (ex: MongoDB id objects). + +function serializeObject(outputValue) { + if (isObjectLike(outputValue)) { + if (typeof outputValue.valueOf === 'function') { + var valueOfResult = outputValue.valueOf(); + + if (!isObjectLike(valueOfResult)) { + return valueOfResult; + } + } + + if (typeof outputValue.toJSON === 'function') { + // $FlowFixMe[incompatible-use] + return outputValue.toJSON(); + } + } + + return outputValue; +} + +function serializeString(outputValue) { + var coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof coercedValue === 'string') { + return coercedValue; + } + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 'true' : 'false'; + } + + if (isFinite(coercedValue)) { + return coercedValue.toString(); + } + + throw new GraphQLError("String cannot represent value: ".concat(inspect(outputValue))); +} + +function coerceString(inputValue) { + if (typeof inputValue !== 'string') { + throw new GraphQLError("String cannot represent a non string value: ".concat(inspect(inputValue))); + } + + return inputValue; +} + +export var GraphQLString = new GraphQLScalarType({ + name: 'String', + description: 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.', + serialize: serializeString, + parseValue: coerceString, + parseLiteral: function parseLiteral(valueNode) { + if (valueNode.kind !== Kind.STRING) { + throw new GraphQLError("String cannot represent a non string value: ".concat(print(valueNode)), valueNode); + } + + return valueNode.value; + } +}); + +function serializeBoolean(outputValue) { + var coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue; + } + + if (isFinite(coercedValue)) { + return coercedValue !== 0; + } + + throw new GraphQLError("Boolean cannot represent a non boolean value: ".concat(inspect(coercedValue))); +} + +function coerceBoolean(inputValue) { + if (typeof inputValue !== 'boolean') { + throw new GraphQLError("Boolean cannot represent a non boolean value: ".concat(inspect(inputValue))); + } + + return inputValue; +} + +export var GraphQLBoolean = new GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize: serializeBoolean, + parseValue: coerceBoolean, + parseLiteral: function parseLiteral(valueNode) { + if (valueNode.kind !== Kind.BOOLEAN) { + throw new GraphQLError("Boolean cannot represent a non boolean value: ".concat(print(valueNode)), valueNode); + } + + return valueNode.value; + } +}); + +function serializeID(outputValue) { + var coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'string') { + return coercedValue; + } + + if (isInteger(coercedValue)) { + return String(coercedValue); + } + + throw new GraphQLError("ID cannot represent value: ".concat(inspect(outputValue))); +} + +function coerceID(inputValue) { + if (typeof inputValue === 'string') { + return inputValue; + } + + if (isInteger(inputValue)) { + return inputValue.toString(); + } + + throw new GraphQLError("ID cannot represent value: ".concat(inspect(inputValue))); +} + +export var GraphQLID = new GraphQLScalarType({ + name: 'ID', + description: 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.', + serialize: serializeID, + parseValue: coerceID, + parseLiteral: function parseLiteral(valueNode) { + if (valueNode.kind !== Kind.STRING && valueNode.kind !== Kind.INT) { + throw new GraphQLError('ID cannot represent a non-string and non-integer value: ' + print(valueNode), valueNode); + } + + return valueNode.value; + } +}); +export var specifiedScalarTypes = Object.freeze([GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]); +export function isSpecifiedScalarType(type) { + return specifiedScalarTypes.some(function (_ref) { + var name = _ref.name; + return type.name === name; + }); +} diff --git a/school/node_modules/graphql/type/schema.d.ts b/school/node_modules/graphql/type/schema.d.ts new file mode 100644 index 0000000..4f759f9 --- /dev/null +++ b/school/node_modules/graphql/type/schema.d.ts @@ -0,0 +1,147 @@ +// FIXME +/* eslint-disable import/no-cycle */ + +import { Maybe } from '../jsutils/Maybe'; + +import { SchemaDefinitionNode, SchemaExtensionNode } from '../language/ast'; + +import { GraphQLDirective } from './directives'; +import { + GraphQLNamedType, + GraphQLAbstractType, + GraphQLObjectType, + GraphQLInterfaceType, +} from './definition'; + +/** + * Test if the given value is a GraphQL schema. + */ +export function isSchema(schema: any): schema is GraphQLSchema; +export function assertSchema(schema: any): GraphQLSchema; + +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLSchemaExtensions { + [attributeName: string]: any; +} + +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. @include and + * @skip) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * + */ +export class GraphQLSchema { + description: Maybe<string>; + extensions: Maybe<Readonly<GraphQLSchemaExtensions>>; + astNode: Maybe<SchemaDefinitionNode>; + extensionASTNodes: Maybe<ReadonlyArray<SchemaExtensionNode>>; + + constructor(config: Readonly<GraphQLSchemaConfig>); + getQueryType(): Maybe<GraphQLObjectType>; + getMutationType(): Maybe<GraphQLObjectType>; + getSubscriptionType(): Maybe<GraphQLObjectType>; + getTypeMap(): TypeMap; + getType(name: string): Maybe<GraphQLNamedType>; + + getPossibleTypes( + abstractType: GraphQLAbstractType, + ): ReadonlyArray<GraphQLObjectType>; + + getImplementations( + interfaceType: GraphQLInterfaceType, + ): InterfaceImplementations; + + // @deprecated: use isSubType instead - will be removed in v16. + isPossibleType( + abstractType: GraphQLAbstractType, + possibleType: GraphQLObjectType, + ): boolean; + + isSubType( + abstractType: GraphQLAbstractType, + maybeSubType: GraphQLNamedType, + ): boolean; + + getDirectives(): ReadonlyArray<GraphQLDirective>; + getDirective(name: string): Maybe<GraphQLDirective>; + + toConfig(): GraphQLSchemaConfig & { + types: Array<GraphQLNamedType>; + directives: Array<GraphQLDirective>; + extensions: Maybe<Readonly<GraphQLSchemaExtensions>>; + extensionASTNodes: ReadonlyArray<SchemaExtensionNode>; + assumeValid: boolean; + }; +} + +interface TypeMap { + [key: string]: GraphQLNamedType; +} + +interface InterfaceImplementations { + objects: ReadonlyArray<GraphQLObjectType>; + interfaces: ReadonlyArray<GraphQLInterfaceType>; +} + +export interface GraphQLSchemaValidationOptions { + /** + * When building a schema from a GraphQL service's introspection result, it + * might be safe to assume the schema is valid. Set to true to assume the + * produced schema is valid. + * + * Default: false + */ + assumeValid?: boolean; +} + +export interface GraphQLSchemaConfig extends GraphQLSchemaValidationOptions { + description?: Maybe<string>; + query?: Maybe<GraphQLObjectType>; + mutation?: Maybe<GraphQLObjectType>; + subscription?: Maybe<GraphQLObjectType>; + types?: Maybe<Array<GraphQLNamedType>>; + directives?: Maybe<Array<GraphQLDirective>>; + extensions?: Maybe<Readonly<GraphQLSchemaExtensions>>; + astNode?: Maybe<SchemaDefinitionNode>; + extensionASTNodes?: Maybe<ReadonlyArray<SchemaExtensionNode>>; +} + +/** + * @internal + */ +export interface GraphQLSchemaNormalizedConfig extends GraphQLSchemaConfig { + description: Maybe<string>; + types: Array<GraphQLNamedType>; + directives: Array<GraphQLDirective>; + extensions: Maybe<Readonly<GraphQLSchemaExtensions>>; + extensionASTNodes: Maybe<ReadonlyArray<SchemaExtensionNode>>; + assumeValid: boolean; +} diff --git a/school/node_modules/graphql/type/schema.js b/school/node_modules/graphql/type/schema.js new file mode 100644 index 0000000..9eef4d0 --- /dev/null +++ b/school/node_modules/graphql/type/schema.js @@ -0,0 +1,384 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isSchema = isSchema; +exports.assertSchema = assertSchema; +exports.GraphQLSchema = void 0; + +var _find = _interopRequireDefault(require("../polyfills/find.js")); + +var _arrayFrom3 = _interopRequireDefault(require("../polyfills/arrayFrom.js")); + +var _objectValues5 = _interopRequireDefault(require("../polyfills/objectValues.js")); + +var _symbols = require("../polyfills/symbols.js"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _toObjMap = _interopRequireDefault(require("../jsutils/toObjMap.js")); + +var _devAssert = _interopRequireDefault(require("../jsutils/devAssert.js")); + +var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf.js")); + +var _isObjectLike = _interopRequireDefault(require("../jsutils/isObjectLike.js")); + +var _introspection = require("./introspection.js"); + +var _directives = require("./directives.js"); + +var _definition = require("./definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +// eslint-disable-next-line no-redeclare +function isSchema(schema) { + return (0, _instanceOf.default)(schema, GraphQLSchema); +} + +function assertSchema(schema) { + if (!isSchema(schema)) { + throw new Error("Expected ".concat((0, _inspect.default)(schema), " to be a GraphQL schema.")); + } + + return schema; +} +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * + * Note: When the schema is constructed, by default only the types that are + * reachable by traversing the root types are included, other types must be + * explicitly referenced. + * + * Example: + * + * const characterInterface = new GraphQLInterfaceType({ + * name: 'Character', + * ... + * }); + * + * const humanType = new GraphQLObjectType({ + * name: 'Human', + * interfaces: [characterInterface], + * ... + * }); + * + * const droidType = new GraphQLObjectType({ + * name: 'Droid', + * interfaces: [characterInterface], + * ... + * }); + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * hero: { type: characterInterface, ... }, + * } + * }), + * ... + * // Since this schema references only the `Character` interface it's + * // necessary to explicitly list the types that implement it if + * // you want them to be included in the final schema. + * types: [humanType, droidType], + * }) + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. @include and + * @skip) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * + */ + + +var GraphQLSchema = /*#__PURE__*/function () { + // Used as a cache for validateSchema(). + function GraphQLSchema(config) { + var _config$directives; + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors. + + (0, _isObjectLike.default)(config) || (0, _devAssert.default)(0, 'Must provide configuration object.'); + !config.types || Array.isArray(config.types) || (0, _devAssert.default)(0, "\"types\" must be Array if provided but got: ".concat((0, _inspect.default)(config.types), ".")); + !config.directives || Array.isArray(config.directives) || (0, _devAssert.default)(0, '"directives" must be Array if provided but got: ' + "".concat((0, _inspect.default)(config.directives), ".")); + this.description = config.description; + this.extensions = config.extensions && (0, _toObjMap.default)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = (_config$directives = config.directives) !== null && _config$directives !== void 0 ? _config$directives : _directives.specifiedDirectives; // To preserve order of user-provided types, we add first to add them to + // the set of "collected" types, so `collectReferencedTypes` ignore them. + + var allReferencedTypes = new Set(config.types); + + if (config.types != null) { + for (var _i2 = 0, _config$types2 = config.types; _i2 < _config$types2.length; _i2++) { + var type = _config$types2[_i2]; + // When we ready to process this type, we remove it from "collected" types + // and then add it together with all dependent types in the correct position. + allReferencedTypes.delete(type); + collectReferencedTypes(type, allReferencedTypes); + } + } + + if (this._queryType != null) { + collectReferencedTypes(this._queryType, allReferencedTypes); + } + + if (this._mutationType != null) { + collectReferencedTypes(this._mutationType, allReferencedTypes); + } + + if (this._subscriptionType != null) { + collectReferencedTypes(this._subscriptionType, allReferencedTypes); + } + + for (var _i4 = 0, _this$_directives2 = this._directives; _i4 < _this$_directives2.length; _i4++) { + var directive = _this$_directives2[_i4]; + + // Directives are not validated until validateSchema() is called. + if ((0, _directives.isDirective)(directive)) { + for (var _i6 = 0, _directive$args2 = directive.args; _i6 < _directive$args2.length; _i6++) { + var arg = _directive$args2[_i6]; + collectReferencedTypes(arg.type, allReferencedTypes); + } + } + } + + collectReferencedTypes(_introspection.__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema. + + this._typeMap = Object.create(null); + this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name. + + this._implementationsMap = Object.create(null); + + for (var _i8 = 0, _arrayFrom2 = (0, _arrayFrom3.default)(allReferencedTypes); _i8 < _arrayFrom2.length; _i8++) { + var namedType = _arrayFrom2[_i8]; + + if (namedType == null) { + continue; + } + + var typeName = namedType.name; + typeName || (0, _devAssert.default)(0, 'One of the provided types for building the Schema is missing a name.'); + + if (this._typeMap[typeName] !== undefined) { + throw new Error("Schema must contain uniquely named types but contains multiple types named \"".concat(typeName, "\".")); + } + + this._typeMap[typeName] = namedType; + + if ((0, _definition.isInterfaceType)(namedType)) { + // Store implementations by interface. + for (var _i10 = 0, _namedType$getInterfa2 = namedType.getInterfaces(); _i10 < _namedType$getInterfa2.length; _i10++) { + var iface = _namedType$getInterfa2[_i10]; + + if ((0, _definition.isInterfaceType)(iface)) { + var implementations = this._implementationsMap[iface.name]; + + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [] + }; + } + + implementations.interfaces.push(namedType); + } + } + } else if ((0, _definition.isObjectType)(namedType)) { + // Store implementations by objects. + for (var _i12 = 0, _namedType$getInterfa4 = namedType.getInterfaces(); _i12 < _namedType$getInterfa4.length; _i12++) { + var _iface = _namedType$getInterfa4[_i12]; + + if ((0, _definition.isInterfaceType)(_iface)) { + var _implementations = this._implementationsMap[_iface.name]; + + if (_implementations === undefined) { + _implementations = this._implementationsMap[_iface.name] = { + objects: [], + interfaces: [] + }; + } + + _implementations.objects.push(namedType); + } + } + } + } + } + + var _proto = GraphQLSchema.prototype; + + _proto.getQueryType = function getQueryType() { + return this._queryType; + }; + + _proto.getMutationType = function getMutationType() { + return this._mutationType; + }; + + _proto.getSubscriptionType = function getSubscriptionType() { + return this._subscriptionType; + }; + + _proto.getTypeMap = function getTypeMap() { + return this._typeMap; + }; + + _proto.getType = function getType(name) { + return this.getTypeMap()[name]; + }; + + _proto.getPossibleTypes = function getPossibleTypes(abstractType) { + return (0, _definition.isUnionType)(abstractType) ? abstractType.getTypes() : this.getImplementations(abstractType).objects; + }; + + _proto.getImplementations = function getImplementations(interfaceType) { + var implementations = this._implementationsMap[interfaceType.name]; + return implementations !== null && implementations !== void 0 ? implementations : { + objects: [], + interfaces: [] + }; + } // @deprecated: use isSubType instead - will be removed in v16. + ; + + _proto.isPossibleType = function isPossibleType(abstractType, possibleType) { + return this.isSubType(abstractType, possibleType); + }; + + _proto.isSubType = function isSubType(abstractType, maybeSubType) { + var map = this._subTypeMap[abstractType.name]; + + if (map === undefined) { + map = Object.create(null); + + if ((0, _definition.isUnionType)(abstractType)) { + for (var _i14 = 0, _abstractType$getType2 = abstractType.getTypes(); _i14 < _abstractType$getType2.length; _i14++) { + var type = _abstractType$getType2[_i14]; + map[type.name] = true; + } + } else { + var implementations = this.getImplementations(abstractType); + + for (var _i16 = 0, _implementations$obje2 = implementations.objects; _i16 < _implementations$obje2.length; _i16++) { + var _type = _implementations$obje2[_i16]; + map[_type.name] = true; + } + + for (var _i18 = 0, _implementations$inte2 = implementations.interfaces; _i18 < _implementations$inte2.length; _i18++) { + var _type2 = _implementations$inte2[_i18]; + map[_type2.name] = true; + } + } + + this._subTypeMap[abstractType.name] = map; + } + + return map[maybeSubType.name] !== undefined; + }; + + _proto.getDirectives = function getDirectives() { + return this._directives; + }; + + _proto.getDirective = function getDirective(name) { + return (0, _find.default)(this.getDirectives(), function (directive) { + return directive.name === name; + }); + }; + + _proto.toConfig = function toConfig() { + var _this$extensionASTNod; + + return { + description: this.description, + query: this.getQueryType(), + mutation: this.getMutationType(), + subscription: this.getSubscriptionType(), + types: (0, _objectValues5.default)(this.getTypeMap()), + directives: this.getDirectives().slice(), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod = this.extensionASTNodes) !== null && _this$extensionASTNod !== void 0 ? _this$extensionASTNod : [], + assumeValid: this.__validationErrors !== undefined + }; + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLSchema, [{ + key: _symbols.SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLSchema'; + } + }]); + + return GraphQLSchema; +}(); + +exports.GraphQLSchema = GraphQLSchema; + +function collectReferencedTypes(type, typeSet) { + var namedType = (0, _definition.getNamedType)(type); + + if (!typeSet.has(namedType)) { + typeSet.add(namedType); + + if ((0, _definition.isUnionType)(namedType)) { + for (var _i20 = 0, _namedType$getTypes2 = namedType.getTypes(); _i20 < _namedType$getTypes2.length; _i20++) { + var memberType = _namedType$getTypes2[_i20]; + collectReferencedTypes(memberType, typeSet); + } + } else if ((0, _definition.isObjectType)(namedType) || (0, _definition.isInterfaceType)(namedType)) { + for (var _i22 = 0, _namedType$getInterfa6 = namedType.getInterfaces(); _i22 < _namedType$getInterfa6.length; _i22++) { + var interfaceType = _namedType$getInterfa6[_i22]; + collectReferencedTypes(interfaceType, typeSet); + } + + for (var _i24 = 0, _objectValues2 = (0, _objectValues5.default)(namedType.getFields()); _i24 < _objectValues2.length; _i24++) { + var field = _objectValues2[_i24]; + collectReferencedTypes(field.type, typeSet); + + for (var _i26 = 0, _field$args2 = field.args; _i26 < _field$args2.length; _i26++) { + var arg = _field$args2[_i26]; + collectReferencedTypes(arg.type, typeSet); + } + } + } else if ((0, _definition.isInputObjectType)(namedType)) { + for (var _i28 = 0, _objectValues4 = (0, _objectValues5.default)(namedType.getFields()); _i28 < _objectValues4.length; _i28++) { + var _field = _objectValues4[_i28]; + collectReferencedTypes(_field.type, typeSet); + } + } + } + + return typeSet; +} diff --git a/school/node_modules/graphql/type/schema.js.flow b/school/node_modules/graphql/type/schema.js.flow new file mode 100644 index 0000000..bc51b70 --- /dev/null +++ b/school/node_modules/graphql/type/schema.js.flow @@ -0,0 +1,435 @@ +// @flow strict +import find from '../polyfills/find'; +import arrayFrom from '../polyfills/arrayFrom'; +import objectValues from '../polyfills/objectValues'; +import { SYMBOL_TO_STRING_TAG } from '../polyfills/symbols'; + +import type { + ObjMap, + ReadOnlyObjMap, + ReadOnlyObjMapLike, +} from '../jsutils/ObjMap'; +import inspect from '../jsutils/inspect'; +import toObjMap from '../jsutils/toObjMap'; +import devAssert from '../jsutils/devAssert'; +import instanceOf from '../jsutils/instanceOf'; +import isObjectLike from '../jsutils/isObjectLike'; + +import type { GraphQLError } from '../error/GraphQLError'; + +import type { + SchemaDefinitionNode, + SchemaExtensionNode, +} from '../language/ast'; + +import type { + GraphQLType, + GraphQLNamedType, + GraphQLAbstractType, + GraphQLObjectType, + GraphQLInterfaceType, +} from './definition'; +import { __Schema } from './introspection'; +import { + GraphQLDirective, + isDirective, + specifiedDirectives, +} from './directives'; +import { + isObjectType, + isInterfaceType, + isUnionType, + isInputObjectType, + getNamedType, +} from './definition'; + +/** + * Test if the given value is a GraphQL schema. + */ +declare function isSchema(schema: mixed): boolean %checks(schema instanceof + GraphQLSchema); +// eslint-disable-next-line no-redeclare +export function isSchema(schema) { + return instanceOf(schema, GraphQLSchema); +} + +export function assertSchema(schema: mixed): GraphQLSchema { + if (!isSchema(schema)) { + throw new Error(`Expected ${inspect(schema)} to be a GraphQL schema.`); + } + return schema; +} + +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * + * Note: When the schema is constructed, by default only the types that are + * reachable by traversing the root types are included, other types must be + * explicitly referenced. + * + * Example: + * + * const characterInterface = new GraphQLInterfaceType({ + * name: 'Character', + * ... + * }); + * + * const humanType = new GraphQLObjectType({ + * name: 'Human', + * interfaces: [characterInterface], + * ... + * }); + * + * const droidType = new GraphQLObjectType({ + * name: 'Droid', + * interfaces: [characterInterface], + * ... + * }); + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * hero: { type: characterInterface, ... }, + * } + * }), + * ... + * // Since this schema references only the `Character` interface it's + * // necessary to explicitly list the types that implement it if + * // you want them to be included in the final schema. + * types: [humanType, droidType], + * }) + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. @include and + * @skip) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * + */ +export class GraphQLSchema { + description: ?string; + extensions: ?ReadOnlyObjMap<mixed>; + astNode: ?SchemaDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray<SchemaExtensionNode>; + + _queryType: ?GraphQLObjectType; + _mutationType: ?GraphQLObjectType; + _subscriptionType: ?GraphQLObjectType; + _directives: $ReadOnlyArray<GraphQLDirective>; + _typeMap: TypeMap; + _subTypeMap: ObjMap<ObjMap<boolean>>; + _implementationsMap: ObjMap<{| + objects: Array<GraphQLObjectType>, + interfaces: Array<GraphQLInterfaceType>, + |}>; + + // Used as a cache for validateSchema(). + __validationErrors: ?$ReadOnlyArray<GraphQLError>; + + constructor(config: $ReadOnly<GraphQLSchemaConfig>) { + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + this.__validationErrors = config.assumeValid === true ? [] : undefined; + + // Check for common mistakes during construction to produce early errors. + devAssert(isObjectLike(config), 'Must provide configuration object.'); + devAssert( + !config.types || Array.isArray(config.types), + `"types" must be Array if provided but got: ${inspect(config.types)}.`, + ); + devAssert( + !config.directives || Array.isArray(config.directives), + '"directives" must be Array if provided but got: ' + + `${inspect(config.directives)}.`, + ); + + this.description = config.description; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; + // Provide specified directives (e.g. @include and @skip) by default. + this._directives = config.directives ?? specifiedDirectives; + + // To preserve order of user-provided types, we add first to add them to + // the set of "collected" types, so `collectReferencedTypes` ignore them. + const allReferencedTypes: Set<GraphQLNamedType> = new Set(config.types); + if (config.types != null) { + for (const type of config.types) { + // When we ready to process this type, we remove it from "collected" types + // and then add it together with all dependent types in the correct position. + allReferencedTypes.delete(type); + collectReferencedTypes(type, allReferencedTypes); + } + } + + if (this._queryType != null) { + collectReferencedTypes(this._queryType, allReferencedTypes); + } + if (this._mutationType != null) { + collectReferencedTypes(this._mutationType, allReferencedTypes); + } + if (this._subscriptionType != null) { + collectReferencedTypes(this._subscriptionType, allReferencedTypes); + } + + for (const directive of this._directives) { + // Directives are not validated until validateSchema() is called. + if (isDirective(directive)) { + for (const arg of directive.args) { + collectReferencedTypes(arg.type, allReferencedTypes); + } + } + } + collectReferencedTypes(__Schema, allReferencedTypes); + + // Storing the resulting map for reference by the schema. + this._typeMap = Object.create(null); + this._subTypeMap = Object.create(null); + // Keep track of all implementations by interface name. + this._implementationsMap = Object.create(null); + + for (const namedType of arrayFrom(allReferencedTypes)) { + if (namedType == null) { + continue; + } + + const typeName = namedType.name; + devAssert( + typeName, + 'One of the provided types for building the Schema is missing a name.', + ); + if (this._typeMap[typeName] !== undefined) { + throw new Error( + `Schema must contain uniquely named types but contains multiple types named "${typeName}".`, + ); + } + this._typeMap[typeName] = namedType; + + if (isInterfaceType(namedType)) { + // Store implementations by interface. + for (const iface of namedType.getInterfaces()) { + if (isInterfaceType(iface)) { + let implementations = this._implementationsMap[iface.name]; + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [], + }; + } + + implementations.interfaces.push(namedType); + } + } + } else if (isObjectType(namedType)) { + // Store implementations by objects. + for (const iface of namedType.getInterfaces()) { + if (isInterfaceType(iface)) { + let implementations = this._implementationsMap[iface.name]; + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [], + }; + } + + implementations.objects.push(namedType); + } + } + } + } + } + + getQueryType(): ?GraphQLObjectType { + return this._queryType; + } + + getMutationType(): ?GraphQLObjectType { + return this._mutationType; + } + + getSubscriptionType(): ?GraphQLObjectType { + return this._subscriptionType; + } + + getTypeMap(): TypeMap { + return this._typeMap; + } + + getType(name: string): ?GraphQLNamedType { + return this.getTypeMap()[name]; + } + + getPossibleTypes( + abstractType: GraphQLAbstractType, + ): $ReadOnlyArray<GraphQLObjectType> { + return isUnionType(abstractType) + ? abstractType.getTypes() + : this.getImplementations(abstractType).objects; + } + + getImplementations( + interfaceType: GraphQLInterfaceType, + ): {| + objects: /* $ReadOnly */ Array<GraphQLObjectType>, + interfaces: /* $ReadOnly */ Array<GraphQLInterfaceType>, + |} { + const implementations = this._implementationsMap[interfaceType.name]; + return implementations ?? { objects: [], interfaces: [] }; + } + + // @deprecated: use isSubType instead - will be removed in v16. + isPossibleType( + abstractType: GraphQLAbstractType, + possibleType: GraphQLObjectType, + ): boolean { + return this.isSubType(abstractType, possibleType); + } + + isSubType( + abstractType: GraphQLAbstractType, + maybeSubType: GraphQLObjectType | GraphQLInterfaceType, + ): boolean { + let map = this._subTypeMap[abstractType.name]; + if (map === undefined) { + map = Object.create(null); + + if (isUnionType(abstractType)) { + for (const type of abstractType.getTypes()) { + map[type.name] = true; + } + } else { + const implementations = this.getImplementations(abstractType); + for (const type of implementations.objects) { + map[type.name] = true; + } + for (const type of implementations.interfaces) { + map[type.name] = true; + } + } + + this._subTypeMap[abstractType.name] = map; + } + return map[maybeSubType.name] !== undefined; + } + + getDirectives(): $ReadOnlyArray<GraphQLDirective> { + return this._directives; + } + + getDirective(name: string): ?GraphQLDirective { + return find(this.getDirectives(), (directive) => directive.name === name); + } + + toConfig(): GraphQLSchemaNormalizedConfig { + return { + description: this.description, + query: this.getQueryType(), + mutation: this.getMutationType(), + subscription: this.getSubscriptionType(), + types: objectValues(this.getTypeMap()), + directives: this.getDirectives().slice(), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes ?? [], + assumeValid: this.__validationErrors !== undefined, + }; + } + + // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + get [SYMBOL_TO_STRING_TAG]() { + return 'GraphQLSchema'; + } +} + +type TypeMap = ObjMap<GraphQLNamedType>; + +export type GraphQLSchemaValidationOptions = {| + /** + * When building a schema from a GraphQL service's introspection result, it + * might be safe to assume the schema is valid. Set to true to assume the + * produced schema is valid. + * + * Default: false + */ + assumeValid?: boolean, +|}; + +export type GraphQLSchemaConfig = {| + description?: ?string, + query?: ?GraphQLObjectType, + mutation?: ?GraphQLObjectType, + subscription?: ?GraphQLObjectType, + types?: ?Array<GraphQLNamedType>, + directives?: ?Array<GraphQLDirective>, + extensions?: ?ReadOnlyObjMapLike<mixed>, + astNode?: ?SchemaDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray<SchemaExtensionNode>, + ...GraphQLSchemaValidationOptions, +|}; + +/** + * @internal + */ +export type GraphQLSchemaNormalizedConfig = {| + ...GraphQLSchemaConfig, + description: ?string, + types: Array<GraphQLNamedType>, + directives: Array<GraphQLDirective>, + extensions: ?ReadOnlyObjMap<mixed>, + extensionASTNodes: $ReadOnlyArray<SchemaExtensionNode>, + assumeValid: boolean, +|}; + +function collectReferencedTypes( + type: GraphQLType, + typeSet: Set<GraphQLNamedType>, +): Set<GraphQLNamedType> { + const namedType = getNamedType(type); + + if (!typeSet.has(namedType)) { + typeSet.add(namedType); + if (isUnionType(namedType)) { + for (const memberType of namedType.getTypes()) { + collectReferencedTypes(memberType, typeSet); + } + } else if (isObjectType(namedType) || isInterfaceType(namedType)) { + for (const interfaceType of namedType.getInterfaces()) { + collectReferencedTypes(interfaceType, typeSet); + } + + for (const field of objectValues(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + for (const arg of field.args) { + collectReferencedTypes(arg.type, typeSet); + } + } + } else if (isInputObjectType(namedType)) { + for (const field of objectValues(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + } + } + } + + return typeSet; +} diff --git a/school/node_modules/graphql/type/schema.mjs b/school/node_modules/graphql/type/schema.mjs new file mode 100644 index 0000000..0163455 --- /dev/null +++ b/school/node_modules/graphql/type/schema.mjs @@ -0,0 +1,361 @@ +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +import find from "../polyfills/find.mjs"; +import arrayFrom from "../polyfills/arrayFrom.mjs"; +import objectValues from "../polyfills/objectValues.mjs"; +import { SYMBOL_TO_STRING_TAG } from "../polyfills/symbols.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import toObjMap from "../jsutils/toObjMap.mjs"; +import devAssert from "../jsutils/devAssert.mjs"; +import instanceOf from "../jsutils/instanceOf.mjs"; +import isObjectLike from "../jsutils/isObjectLike.mjs"; +import { __Schema } from "./introspection.mjs"; +import { GraphQLDirective, isDirective, specifiedDirectives } from "./directives.mjs"; +import { isObjectType, isInterfaceType, isUnionType, isInputObjectType, getNamedType } from "./definition.mjs"; +/** + * Test if the given value is a GraphQL schema. + */ + +// eslint-disable-next-line no-redeclare +export function isSchema(schema) { + return instanceOf(schema, GraphQLSchema); +} +export function assertSchema(schema) { + if (!isSchema(schema)) { + throw new Error("Expected ".concat(inspect(schema), " to be a GraphQL schema.")); + } + + return schema; +} +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * + * Note: When the schema is constructed, by default only the types that are + * reachable by traversing the root types are included, other types must be + * explicitly referenced. + * + * Example: + * + * const characterInterface = new GraphQLInterfaceType({ + * name: 'Character', + * ... + * }); + * + * const humanType = new GraphQLObjectType({ + * name: 'Human', + * interfaces: [characterInterface], + * ... + * }); + * + * const droidType = new GraphQLObjectType({ + * name: 'Droid', + * interfaces: [characterInterface], + * ... + * }); + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * hero: { type: characterInterface, ... }, + * } + * }), + * ... + * // Since this schema references only the `Character` interface it's + * // necessary to explicitly list the types that implement it if + * // you want them to be included in the final schema. + * types: [humanType, droidType], + * }) + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. @include and + * @skip) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * + */ + +export var GraphQLSchema = /*#__PURE__*/function () { + // Used as a cache for validateSchema(). + function GraphQLSchema(config) { + var _config$directives; + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors. + + isObjectLike(config) || devAssert(0, 'Must provide configuration object.'); + !config.types || Array.isArray(config.types) || devAssert(0, "\"types\" must be Array if provided but got: ".concat(inspect(config.types), ".")); + !config.directives || Array.isArray(config.directives) || devAssert(0, '"directives" must be Array if provided but got: ' + "".concat(inspect(config.directives), ".")); + this.description = config.description; + this.extensions = config.extensions && toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = (_config$directives = config.directives) !== null && _config$directives !== void 0 ? _config$directives : specifiedDirectives; // To preserve order of user-provided types, we add first to add them to + // the set of "collected" types, so `collectReferencedTypes` ignore them. + + var allReferencedTypes = new Set(config.types); + + if (config.types != null) { + for (var _i2 = 0, _config$types2 = config.types; _i2 < _config$types2.length; _i2++) { + var type = _config$types2[_i2]; + // When we ready to process this type, we remove it from "collected" types + // and then add it together with all dependent types in the correct position. + allReferencedTypes.delete(type); + collectReferencedTypes(type, allReferencedTypes); + } + } + + if (this._queryType != null) { + collectReferencedTypes(this._queryType, allReferencedTypes); + } + + if (this._mutationType != null) { + collectReferencedTypes(this._mutationType, allReferencedTypes); + } + + if (this._subscriptionType != null) { + collectReferencedTypes(this._subscriptionType, allReferencedTypes); + } + + for (var _i4 = 0, _this$_directives2 = this._directives; _i4 < _this$_directives2.length; _i4++) { + var directive = _this$_directives2[_i4]; + + // Directives are not validated until validateSchema() is called. + if (isDirective(directive)) { + for (var _i6 = 0, _directive$args2 = directive.args; _i6 < _directive$args2.length; _i6++) { + var arg = _directive$args2[_i6]; + collectReferencedTypes(arg.type, allReferencedTypes); + } + } + } + + collectReferencedTypes(__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema. + + this._typeMap = Object.create(null); + this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name. + + this._implementationsMap = Object.create(null); + + for (var _i8 = 0, _arrayFrom2 = arrayFrom(allReferencedTypes); _i8 < _arrayFrom2.length; _i8++) { + var namedType = _arrayFrom2[_i8]; + + if (namedType == null) { + continue; + } + + var typeName = namedType.name; + typeName || devAssert(0, 'One of the provided types for building the Schema is missing a name.'); + + if (this._typeMap[typeName] !== undefined) { + throw new Error("Schema must contain uniquely named types but contains multiple types named \"".concat(typeName, "\".")); + } + + this._typeMap[typeName] = namedType; + + if (isInterfaceType(namedType)) { + // Store implementations by interface. + for (var _i10 = 0, _namedType$getInterfa2 = namedType.getInterfaces(); _i10 < _namedType$getInterfa2.length; _i10++) { + var iface = _namedType$getInterfa2[_i10]; + + if (isInterfaceType(iface)) { + var implementations = this._implementationsMap[iface.name]; + + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [] + }; + } + + implementations.interfaces.push(namedType); + } + } + } else if (isObjectType(namedType)) { + // Store implementations by objects. + for (var _i12 = 0, _namedType$getInterfa4 = namedType.getInterfaces(); _i12 < _namedType$getInterfa4.length; _i12++) { + var _iface = _namedType$getInterfa4[_i12]; + + if (isInterfaceType(_iface)) { + var _implementations = this._implementationsMap[_iface.name]; + + if (_implementations === undefined) { + _implementations = this._implementationsMap[_iface.name] = { + objects: [], + interfaces: [] + }; + } + + _implementations.objects.push(namedType); + } + } + } + } + } + + var _proto = GraphQLSchema.prototype; + + _proto.getQueryType = function getQueryType() { + return this._queryType; + }; + + _proto.getMutationType = function getMutationType() { + return this._mutationType; + }; + + _proto.getSubscriptionType = function getSubscriptionType() { + return this._subscriptionType; + }; + + _proto.getTypeMap = function getTypeMap() { + return this._typeMap; + }; + + _proto.getType = function getType(name) { + return this.getTypeMap()[name]; + }; + + _proto.getPossibleTypes = function getPossibleTypes(abstractType) { + return isUnionType(abstractType) ? abstractType.getTypes() : this.getImplementations(abstractType).objects; + }; + + _proto.getImplementations = function getImplementations(interfaceType) { + var implementations = this._implementationsMap[interfaceType.name]; + return implementations !== null && implementations !== void 0 ? implementations : { + objects: [], + interfaces: [] + }; + } // @deprecated: use isSubType instead - will be removed in v16. + ; + + _proto.isPossibleType = function isPossibleType(abstractType, possibleType) { + return this.isSubType(abstractType, possibleType); + }; + + _proto.isSubType = function isSubType(abstractType, maybeSubType) { + var map = this._subTypeMap[abstractType.name]; + + if (map === undefined) { + map = Object.create(null); + + if (isUnionType(abstractType)) { + for (var _i14 = 0, _abstractType$getType2 = abstractType.getTypes(); _i14 < _abstractType$getType2.length; _i14++) { + var type = _abstractType$getType2[_i14]; + map[type.name] = true; + } + } else { + var implementations = this.getImplementations(abstractType); + + for (var _i16 = 0, _implementations$obje2 = implementations.objects; _i16 < _implementations$obje2.length; _i16++) { + var _type = _implementations$obje2[_i16]; + map[_type.name] = true; + } + + for (var _i18 = 0, _implementations$inte2 = implementations.interfaces; _i18 < _implementations$inte2.length; _i18++) { + var _type2 = _implementations$inte2[_i18]; + map[_type2.name] = true; + } + } + + this._subTypeMap[abstractType.name] = map; + } + + return map[maybeSubType.name] !== undefined; + }; + + _proto.getDirectives = function getDirectives() { + return this._directives; + }; + + _proto.getDirective = function getDirective(name) { + return find(this.getDirectives(), function (directive) { + return directive.name === name; + }); + }; + + _proto.toConfig = function toConfig() { + var _this$extensionASTNod; + + return { + description: this.description, + query: this.getQueryType(), + mutation: this.getMutationType(), + subscription: this.getSubscriptionType(), + types: objectValues(this.getTypeMap()), + directives: this.getDirectives().slice(), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: (_this$extensionASTNod = this.extensionASTNodes) !== null && _this$extensionASTNod !== void 0 ? _this$extensionASTNod : [], + assumeValid: this.__validationErrors !== undefined + }; + } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet + ; + + _createClass(GraphQLSchema, [{ + key: SYMBOL_TO_STRING_TAG, + get: function get() { + return 'GraphQLSchema'; + } + }]); + + return GraphQLSchema; +}(); + +function collectReferencedTypes(type, typeSet) { + var namedType = getNamedType(type); + + if (!typeSet.has(namedType)) { + typeSet.add(namedType); + + if (isUnionType(namedType)) { + for (var _i20 = 0, _namedType$getTypes2 = namedType.getTypes(); _i20 < _namedType$getTypes2.length; _i20++) { + var memberType = _namedType$getTypes2[_i20]; + collectReferencedTypes(memberType, typeSet); + } + } else if (isObjectType(namedType) || isInterfaceType(namedType)) { + for (var _i22 = 0, _namedType$getInterfa6 = namedType.getInterfaces(); _i22 < _namedType$getInterfa6.length; _i22++) { + var interfaceType = _namedType$getInterfa6[_i22]; + collectReferencedTypes(interfaceType, typeSet); + } + + for (var _i24 = 0, _objectValues2 = objectValues(namedType.getFields()); _i24 < _objectValues2.length; _i24++) { + var field = _objectValues2[_i24]; + collectReferencedTypes(field.type, typeSet); + + for (var _i26 = 0, _field$args2 = field.args; _i26 < _field$args2.length; _i26++) { + var arg = _field$args2[_i26]; + collectReferencedTypes(arg.type, typeSet); + } + } + } else if (isInputObjectType(namedType)) { + for (var _i28 = 0, _objectValues4 = objectValues(namedType.getFields()); _i28 < _objectValues4.length; _i28++) { + var _field = _objectValues4[_i28]; + collectReferencedTypes(_field.type, typeSet); + } + } + } + + return typeSet; +} diff --git a/school/node_modules/graphql/type/validate.d.ts b/school/node_modules/graphql/type/validate.d.ts new file mode 100644 index 0000000..98400a2 --- /dev/null +++ b/school/node_modules/graphql/type/validate.d.ts @@ -0,0 +1,20 @@ +import { GraphQLError } from '../error/GraphQLError'; + +import { GraphQLSchema } from './schema'; + +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ +export function validateSchema( + schema: GraphQLSchema, +): ReadonlyArray<GraphQLError>; + +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ +export function assertValidSchema(schema: GraphQLSchema): void; diff --git a/school/node_modules/graphql/type/validate.js b/school/node_modules/graphql/type/validate.js new file mode 100644 index 0000000..a233668 --- /dev/null +++ b/school/node_modules/graphql/type/validate.js @@ -0,0 +1,549 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validateSchema = validateSchema; +exports.assertValidSchema = assertValidSchema; + +var _find = _interopRequireDefault(require("../polyfills/find.js")); + +var _objectValues5 = _interopRequireDefault(require("../polyfills/objectValues.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _GraphQLError = require("../error/GraphQLError.js"); + +var _locatedError = require("../error/locatedError.js"); + +var _assertValidName = require("../utilities/assertValidName.js"); + +var _typeComparators = require("../utilities/typeComparators.js"); + +var _schema = require("./schema.js"); + +var _introspection = require("./introspection.js"); + +var _directives = require("./directives.js"); + +var _definition = require("./definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ +function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + + var context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + var errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ + + +function assertValidSchema(schema) { + var errors = validateSchema(schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} + +var SchemaValidationContext = /*#__PURE__*/function () { + function SchemaValidationContext(schema) { + this._errors = []; + this.schema = schema; + } + + var _proto = SchemaValidationContext.prototype; + + _proto.reportError = function reportError(message, nodes) { + var _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; + + this.addError(new _GraphQLError.GraphQLError(message, _nodes)); + }; + + _proto.addError = function addError(error) { + this._errors.push(error); + }; + + _proto.getErrors = function getErrors() { + return this._errors; + }; + + return SchemaValidationContext; +}(); + +function validateRootTypes(context) { + var schema = context.schema; + var queryType = schema.getQueryType(); + + if (!queryType) { + context.reportError('Query root type must be provided.', schema.astNode); + } else if (!(0, _definition.isObjectType)(queryType)) { + var _getOperationTypeNode; + + context.reportError("Query root type must be Object type, it cannot be ".concat((0, _inspect.default)(queryType), "."), (_getOperationTypeNode = getOperationTypeNode(schema, 'query')) !== null && _getOperationTypeNode !== void 0 ? _getOperationTypeNode : queryType.astNode); + } + + var mutationType = schema.getMutationType(); + + if (mutationType && !(0, _definition.isObjectType)(mutationType)) { + var _getOperationTypeNode2; + + context.reportError('Mutation root type must be Object type if provided, it cannot be ' + "".concat((0, _inspect.default)(mutationType), "."), (_getOperationTypeNode2 = getOperationTypeNode(schema, 'mutation')) !== null && _getOperationTypeNode2 !== void 0 ? _getOperationTypeNode2 : mutationType.astNode); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) { + var _getOperationTypeNode3; + + context.reportError('Subscription root type must be Object type if provided, it cannot be ' + "".concat((0, _inspect.default)(subscriptionType), "."), (_getOperationTypeNode3 = getOperationTypeNode(schema, 'subscription')) !== null && _getOperationTypeNode3 !== void 0 ? _getOperationTypeNode3 : subscriptionType.astNode); + } +} + +function getOperationTypeNode(schema, operation) { + var operationNodes = getAllSubNodes(schema, function (node) { + return node.operationTypes; + }); + + for (var _i2 = 0; _i2 < operationNodes.length; _i2++) { + var node = operationNodes[_i2]; + + if (node.operation === operation) { + return node.type; + } + } + + return undefined; +} + +function validateDirectives(context) { + for (var _i4 = 0, _context$schema$getDi2 = context.schema.getDirectives(); _i4 < _context$schema$getDi2.length; _i4++) { + var directive = _context$schema$getDi2[_i4]; + + // Ensure all directives are in fact GraphQL directives. + if (!(0, _directives.isDirective)(directive)) { + context.reportError("Expected directive but got: ".concat((0, _inspect.default)(directive), "."), directive === null || directive === void 0 ? void 0 : directive.astNode); + continue; + } // Ensure they are named correctly. + + + validateName(context, directive); // TODO: Ensure proper locations. + // Ensure the arguments are valid. + + for (var _i6 = 0, _directive$args2 = directive.args; _i6 < _directive$args2.length; _i6++) { + var arg = _directive$args2[_i6]; + // Ensure they are named correctly. + validateName(context, arg); // Ensure the type is an input type. + + if (!(0, _definition.isInputType)(arg.type)) { + context.reportError("The type of @".concat(directive.name, "(").concat(arg.name, ":) must be Input Type ") + "but got: ".concat((0, _inspect.default)(arg.type), "."), arg.astNode); + } + + if ((0, _definition.isRequiredArgument)(arg) && arg.deprecationReason != null) { + var _arg$astNode; + + context.reportError("Required argument @".concat(directive.name, "(").concat(arg.name, ":) cannot be deprecated."), [getDeprecatedDirectiveNode(arg.astNode), // istanbul ignore next (TODO need to write coverage tests) + (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 ? void 0 : _arg$astNode.type]); + } + } + } +} + +function validateName(context, node) { + // Ensure names are valid, however introspection types opt out. + var error = (0, _assertValidName.isValidNameError)(node.name); + + if (error) { + context.addError((0, _locatedError.locatedError)(error, node.astNode)); + } +} + +function validateTypes(context) { + var validateInputObjectCircularRefs = createInputObjectCircularRefsValidator(context); + var typeMap = context.schema.getTypeMap(); + + for (var _i8 = 0, _objectValues2 = (0, _objectValues5.default)(typeMap); _i8 < _objectValues2.length; _i8++) { + var type = _objectValues2[_i8]; + + // Ensure all provided types are in fact GraphQL type. + if (!(0, _definition.isNamedType)(type)) { + context.reportError("Expected GraphQL named type but got: ".concat((0, _inspect.default)(type), "."), type.astNode); + continue; + } // Ensure it is named correctly (excluding introspection types). + + + if (!(0, _introspection.isIntrospectionType)(type)) { + validateName(context, type); + } + + if ((0, _definition.isObjectType)(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isInterfaceType)(type)) { + // Ensure fields are valid. + validateFields(context, type); // Ensure interfaces implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isUnionType)(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if ((0, _definition.isEnumType)(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if ((0, _definition.isInputObjectType)(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references + + validateInputObjectCircularRefs(type); + } + } +} + +function validateFields(context, type) { + var fields = (0, _objectValues5.default)(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError("Type ".concat(type.name, " must define one or more fields."), getAllNodes(type)); + } + + for (var _i10 = 0; _i10 < fields.length; _i10++) { + var field = fields[_i10]; + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an output type + + if (!(0, _definition.isOutputType)(field.type)) { + var _field$astNode; + + context.reportError("The type of ".concat(type.name, ".").concat(field.name, " must be Output Type ") + "but got: ".concat((0, _inspect.default)(field.type), "."), (_field$astNode = field.astNode) === null || _field$astNode === void 0 ? void 0 : _field$astNode.type); + } // Ensure the arguments are valid + + + for (var _i12 = 0, _field$args2 = field.args; _i12 < _field$args2.length; _i12++) { + var arg = _field$args2[_i12]; + var argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(arg.type)) { + var _arg$astNode2; + + context.reportError("The type of ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) must be Input ") + "Type but got: ".concat((0, _inspect.default)(arg.type), "."), (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0 ? void 0 : _arg$astNode2.type); + } + + if ((0, _definition.isRequiredArgument)(arg) && arg.deprecationReason != null) { + var _arg$astNode3; + + context.reportError("Required argument ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) cannot be deprecated."), [getDeprecatedDirectiveNode(arg.astNode), // istanbul ignore next (TODO need to write coverage tests) + (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0 ? void 0 : _arg$astNode3.type]); + } + } + } +} + +function validateInterfaces(context, type) { + var ifaceTypeNames = Object.create(null); + + for (var _i14 = 0, _type$getInterfaces2 = type.getInterfaces(); _i14 < _type$getInterfaces2.length; _i14++) { + var iface = _type$getInterfaces2[_i14]; + + if (!(0, _definition.isInterfaceType)(iface)) { + context.reportError("Type ".concat((0, _inspect.default)(type), " must only implement Interface types, ") + "it cannot implement ".concat((0, _inspect.default)(iface), "."), getAllImplementsInterfaceNodes(type, iface)); + continue; + } + + if (type === iface) { + context.reportError("Type ".concat(type.name, " cannot implement itself because it would create a circular reference."), getAllImplementsInterfaceNodes(type, iface)); + continue; + } + + if (ifaceTypeNames[iface.name]) { + context.reportError("Type ".concat(type.name, " can only implement ").concat(iface.name, " once."), getAllImplementsInterfaceNodes(type, iface)); + continue; + } + + ifaceTypeNames[iface.name] = true; + validateTypeImplementsAncestors(context, type, iface); + validateTypeImplementsInterface(context, type, iface); + } +} + +function validateTypeImplementsInterface(context, type, iface) { + var typeFieldMap = type.getFields(); // Assert each interface field is implemented. + + for (var _i16 = 0, _objectValues4 = (0, _objectValues5.default)(iface.getFields()); _i16 < _objectValues4.length; _i16++) { + var ifaceField = _objectValues4[_i16]; + var fieldName = ifaceField.name; + var typeField = typeFieldMap[fieldName]; // Assert interface field exists on type. + + if (!typeField) { + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expected but ").concat(type.name, " does not provide it."), [ifaceField.astNode].concat(getAllNodes(type))); + continue; + } // Assert interface field type is satisfied by type field type, by being + // a valid subtype. (covariant) + + + if (!(0, _typeComparators.isTypeSubTypeOf)(context.schema, typeField.type, ifaceField.type)) { + var _ifaceField$astNode, _typeField$astNode; + + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expects type ") + "".concat((0, _inspect.default)(ifaceField.type), " but ").concat(type.name, ".").concat(fieldName, " ") + "is type ".concat((0, _inspect.default)(typeField.type), "."), [// istanbul ignore next (TODO need to write coverage tests) + (_ifaceField$astNode = ifaceField.astNode) === null || _ifaceField$astNode === void 0 ? void 0 : _ifaceField$astNode.type, // istanbul ignore next (TODO need to write coverage tests) + (_typeField$astNode = typeField.astNode) === null || _typeField$astNode === void 0 ? void 0 : _typeField$astNode.type]); + } // Assert each interface field arg is implemented. + + + var _loop = function _loop(_i18, _ifaceField$args2) { + var ifaceArg = _ifaceField$args2[_i18]; + var argName = ifaceArg.name; + var typeArg = (0, _find.default)(typeField.args, function (arg) { + return arg.name === argName; + }); // Assert interface field arg exists on object field. + + if (!typeArg) { + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) expected but ").concat(type.name, ".").concat(fieldName, " does not provide it."), [ifaceArg.astNode, typeField.astNode]); + return "continue"; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + + if (!(0, _typeComparators.isEqualType)(ifaceArg.type, typeArg.type)) { + var _ifaceArg$astNode, _typeArg$astNode; + + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expects type ".concat((0, _inspect.default)(ifaceArg.type), " but ") + "".concat(type.name, ".").concat(fieldName, "(").concat(argName, ":) is type ") + "".concat((0, _inspect.default)(typeArg.type), "."), [// istanbul ignore next (TODO need to write coverage tests) + (_ifaceArg$astNode = ifaceArg.astNode) === null || _ifaceArg$astNode === void 0 ? void 0 : _ifaceArg$astNode.type, // istanbul ignore next (TODO need to write coverage tests) + (_typeArg$astNode = typeArg.astNode) === null || _typeArg$astNode === void 0 ? void 0 : _typeArg$astNode.type]); + } // TODO: validate default values? + + }; + + for (var _i18 = 0, _ifaceField$args2 = ifaceField.args; _i18 < _ifaceField$args2.length; _i18++) { + var _ret = _loop(_i18, _ifaceField$args2); + + if (_ret === "continue") continue; + } // Assert additional arguments must not be required. + + + var _loop2 = function _loop2(_i20, _typeField$args2) { + var typeArg = _typeField$args2[_i20]; + var argName = typeArg.name; + var ifaceArg = (0, _find.default)(ifaceField.args, function (arg) { + return arg.name === argName; + }); + + if (!ifaceArg && (0, _definition.isRequiredArgument)(typeArg)) { + context.reportError("Object field ".concat(type.name, ".").concat(fieldName, " includes required argument ").concat(argName, " that is missing from the Interface field ").concat(iface.name, ".").concat(fieldName, "."), [typeArg.astNode, ifaceField.astNode]); + } + }; + + for (var _i20 = 0, _typeField$args2 = typeField.args; _i20 < _typeField$args2.length; _i20++) { + _loop2(_i20, _typeField$args2); + } + } +} + +function validateTypeImplementsAncestors(context, type, iface) { + var ifaceInterfaces = type.getInterfaces(); + + for (var _i22 = 0, _iface$getInterfaces2 = iface.getInterfaces(); _i22 < _iface$getInterfaces2.length; _i22++) { + var transitive = _iface$getInterfaces2[_i22]; + + if (ifaceInterfaces.indexOf(transitive) === -1) { + context.reportError(transitive === type ? "Type ".concat(type.name, " cannot implement ").concat(iface.name, " because it would create a circular reference.") : "Type ".concat(type.name, " must implement ").concat(transitive.name, " because it is implemented by ").concat(iface.name, "."), [].concat(getAllImplementsInterfaceNodes(iface, transitive), getAllImplementsInterfaceNodes(type, iface))); + } + } +} + +function validateUnionMembers(context, union) { + var memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError("Union type ".concat(union.name, " must define one or more member types."), getAllNodes(union)); + } + + var includedTypeNames = Object.create(null); + + for (var _i24 = 0; _i24 < memberTypes.length; _i24++) { + var memberType = memberTypes[_i24]; + + if (includedTypeNames[memberType.name]) { + context.reportError("Union type ".concat(union.name, " can only include type ").concat(memberType.name, " once."), getUnionMemberTypeNodes(union, memberType.name)); + continue; + } + + includedTypeNames[memberType.name] = true; + + if (!(0, _definition.isObjectType)(memberType)) { + context.reportError("Union type ".concat(union.name, " can only include Object types, ") + "it cannot include ".concat((0, _inspect.default)(memberType), "."), getUnionMemberTypeNodes(union, String(memberType))); + } + } +} + +function validateEnumValues(context, enumType) { + var enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError("Enum type ".concat(enumType.name, " must define one or more values."), getAllNodes(enumType)); + } + + for (var _i26 = 0; _i26 < enumValues.length; _i26++) { + var enumValue = enumValues[_i26]; + var valueName = enumValue.name; // Ensure valid name. + + validateName(context, enumValue); + + if (valueName === 'true' || valueName === 'false' || valueName === 'null') { + context.reportError("Enum type ".concat(enumType.name, " cannot include value: ").concat(valueName, "."), enumValue.astNode); + } + } +} + +function validateInputFields(context, inputObj) { + var fields = (0, _objectValues5.default)(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError("Input Object type ".concat(inputObj.name, " must define one or more fields."), getAllNodes(inputObj)); + } // Ensure the arguments are valid + + + for (var _i28 = 0; _i28 < fields.length; _i28++) { + var field = fields[_i28]; + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(field.type)) { + var _field$astNode2; + + context.reportError("The type of ".concat(inputObj.name, ".").concat(field.name, " must be Input Type ") + "but got: ".concat((0, _inspect.default)(field.type), "."), (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 ? void 0 : _field$astNode2.type); + } + + if ((0, _definition.isRequiredInputField)(field) && field.deprecationReason != null) { + var _field$astNode3; + + context.reportError("Required input field ".concat(inputObj.name, ".").concat(field.name, " cannot be deprecated."), [getDeprecatedDirectiveNode(field.astNode), // istanbul ignore next (TODO need to write coverage tests) + (_field$astNode3 = field.astNode) === null || _field$astNode3 === void 0 ? void 0 : _field$astNode3.type]); + } + } +} + +function createInputObjectCircularRefsValidator(context) { + // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. + // Tracks already visited types to maintain O(N) and to ensure that cycles + // are not redundantly reported. + var visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors + + var fieldPath = []; // Position in the type path + + var fieldPathIndexByTypeName = Object.create(null); + return detectCycleRecursive; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(inputObj) { + if (visitedTypes[inputObj.name]) { + return; + } + + visitedTypes[inputObj.name] = true; + fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; + var fields = (0, _objectValues5.default)(inputObj.getFields()); + + for (var _i30 = 0; _i30 < fields.length; _i30++) { + var field = fields[_i30]; + + if ((0, _definition.isNonNullType)(field.type) && (0, _definition.isInputObjectType)(field.type.ofType)) { + var fieldType = field.type.ofType; + var cycleIndex = fieldPathIndexByTypeName[fieldType.name]; + fieldPath.push(field); + + if (cycleIndex === undefined) { + detectCycleRecursive(fieldType); + } else { + var cyclePath = fieldPath.slice(cycleIndex); + var pathStr = cyclePath.map(function (fieldObj) { + return fieldObj.name; + }).join('.'); + context.reportError("Cannot reference Input Object \"".concat(fieldType.name, "\" within itself through a series of non-null fields: \"").concat(pathStr, "\"."), cyclePath.map(function (fieldObj) { + return fieldObj.astNode; + })); + } + + fieldPath.pop(); + } + } + + fieldPathIndexByTypeName[inputObj.name] = undefined; + } +} + +function getAllNodes(object) { + var astNode = object.astNode, + extensionASTNodes = object.extensionASTNodes; + return astNode ? extensionASTNodes ? [astNode].concat(extensionASTNodes) : [astNode] : extensionASTNodes !== null && extensionASTNodes !== void 0 ? extensionASTNodes : []; +} + +function getAllSubNodes(object, getter) { + var subNodes = []; + + for (var _i32 = 0, _getAllNodes2 = getAllNodes(object); _i32 < _getAllNodes2.length; _i32++) { + var _getter; + + var node = _getAllNodes2[_i32]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + subNodes = subNodes.concat((_getter = getter(node)) !== null && _getter !== void 0 ? _getter : []); + } + + return subNodes; +} + +function getAllImplementsInterfaceNodes(type, iface) { + return getAllSubNodes(type, function (typeNode) { + return typeNode.interfaces; + }).filter(function (ifaceNode) { + return ifaceNode.name.value === iface.name; + }); +} + +function getUnionMemberTypeNodes(union, typeName) { + return getAllSubNodes(union, function (unionNode) { + return unionNode.types; + }).filter(function (typeNode) { + return typeNode.name.value === typeName; + }); +} + +function getDeprecatedDirectiveNode(definitionNode) { + var _definitionNode$direc; + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + return definitionNode === null || definitionNode === void 0 ? void 0 : (_definitionNode$direc = definitionNode.directives) === null || _definitionNode$direc === void 0 ? void 0 : _definitionNode$direc.find(function (node) { + return node.name.value === _directives.GraphQLDeprecatedDirective.name; + }); +} diff --git a/school/node_modules/graphql/type/validate.js.flow b/school/node_modules/graphql/type/validate.js.flow new file mode 100644 index 0000000..f870b20 --- /dev/null +++ b/school/node_modules/graphql/type/validate.js.flow @@ -0,0 +1,670 @@ +// @flow strict +import find from '../polyfills/find'; +import objectValues from '../polyfills/objectValues'; + +import inspect from '../jsutils/inspect'; + +import { GraphQLError } from '../error/GraphQLError'; +import { locatedError } from '../error/locatedError'; + +import type { + ASTNode, + NamedTypeNode, + DirectiveNode, + OperationTypeNode, +} from '../language/ast'; + +import { isValidNameError } from '../utilities/assertValidName'; +import { isEqualType, isTypeSubTypeOf } from '../utilities/typeComparators'; + +import type { GraphQLSchema } from './schema'; +import type { + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, +} from './definition'; +import { assertSchema } from './schema'; +import { isIntrospectionType } from './introspection'; +import { isDirective, GraphQLDeprecatedDirective } from './directives'; +import { + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isNamedType, + isNonNullType, + isInputType, + isOutputType, + isRequiredArgument, + isRequiredInputField, +} from './definition'; + +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ +export function validateSchema( + schema: GraphQLSchema, +): $ReadOnlyArray<GraphQLError> { + // First check to ensure the provided value is in fact a GraphQLSchema. + assertSchema(schema); + + // If this Schema has already been validated, return the previous results. + if (schema.__validationErrors) { + return schema.__validationErrors; + } + + // Validate the schema, producing a list of errors. + const context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); + + // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + const errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} + +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ +export function assertValidSchema(schema: GraphQLSchema): void { + const errors = validateSchema(schema); + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); + } +} + +class SchemaValidationContext { + +_errors: Array<GraphQLError>; + +schema: GraphQLSchema; + + constructor(schema) { + this._errors = []; + this.schema = schema; + } + + reportError( + message: string, + nodes?: $ReadOnlyArray<?ASTNode> | ?ASTNode, + ): void { + const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; + this.addError(new GraphQLError(message, _nodes)); + } + + addError(error: GraphQLError): void { + this._errors.push(error); + } + + getErrors(): $ReadOnlyArray<GraphQLError> { + return this._errors; + } +} + +function validateRootTypes(context: SchemaValidationContext): void { + const schema = context.schema; + const queryType = schema.getQueryType(); + if (!queryType) { + context.reportError('Query root type must be provided.', schema.astNode); + } else if (!isObjectType(queryType)) { + context.reportError( + `Query root type must be Object type, it cannot be ${inspect( + queryType, + )}.`, + getOperationTypeNode(schema, 'query') ?? queryType.astNode, + ); + } + + const mutationType = schema.getMutationType(); + if (mutationType && !isObjectType(mutationType)) { + context.reportError( + 'Mutation root type must be Object type if provided, it cannot be ' + + `${inspect(mutationType)}.`, + getOperationTypeNode(schema, 'mutation') ?? mutationType.astNode, + ); + } + + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType && !isObjectType(subscriptionType)) { + context.reportError( + 'Subscription root type must be Object type if provided, it cannot be ' + + `${inspect(subscriptionType)}.`, + getOperationTypeNode(schema, 'subscription') ?? subscriptionType.astNode, + ); + } +} + +function getOperationTypeNode( + schema: GraphQLSchema, + operation: OperationTypeNode, +): ?ASTNode { + const operationNodes = getAllSubNodes(schema, (node) => node.operationTypes); + for (const node of operationNodes) { + if (node.operation === operation) { + return node.type; + } + } + return undefined; +} + +function validateDirectives(context: SchemaValidationContext): void { + for (const directive of context.schema.getDirectives()) { + // Ensure all directives are in fact GraphQL directives. + if (!isDirective(directive)) { + context.reportError( + `Expected directive but got: ${inspect(directive)}.`, + directive?.astNode, + ); + continue; + } + + // Ensure they are named correctly. + validateName(context, directive); + + // TODO: Ensure proper locations. + + // Ensure the arguments are valid. + for (const arg of directive.args) { + // Ensure they are named correctly. + validateName(context, arg); + + // Ensure the type is an input type. + if (!isInputType(arg.type)) { + context.reportError( + `The type of @${directive.name}(${arg.name}:) must be Input Type ` + + `but got: ${inspect(arg.type)}.`, + arg.astNode, + ); + } + + if (isRequiredArgument(arg) && arg.deprecationReason != null) { + context.reportError( + `Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(arg.astNode), + // istanbul ignore next (TODO need to write coverage tests) + arg.astNode?.type, + ], + ); + } + } + } +} + +function validateName( + context: SchemaValidationContext, + node: { +name: string, +astNode: ?ASTNode, ... }, +): void { + // Ensure names are valid, however introspection types opt out. + const error = isValidNameError(node.name); + if (error) { + context.addError(locatedError(error, node.astNode)); + } +} + +function validateTypes(context: SchemaValidationContext): void { + const validateInputObjectCircularRefs = createInputObjectCircularRefsValidator( + context, + ); + const typeMap = context.schema.getTypeMap(); + for (const type of objectValues(typeMap)) { + // Ensure all provided types are in fact GraphQL type. + if (!isNamedType(type)) { + context.reportError( + `Expected GraphQL named type but got: ${inspect(type)}.`, + type.astNode, + ); + continue; + } + + // Ensure it is named correctly (excluding introspection types). + if (!isIntrospectionType(type)) { + validateName(context, type); + } + + if (isObjectType(type)) { + // Ensure fields are valid + validateFields(context, type); + + // Ensure objects implement the interfaces they claim to. + validateInterfaces(context, type); + } else if (isInterfaceType(type)) { + // Ensure fields are valid. + validateFields(context, type); + + // Ensure interfaces implement the interfaces they claim to. + validateInterfaces(context, type); + } else if (isUnionType(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if (isEnumType(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if (isInputObjectType(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); + + // Ensure Input Objects do not contain non-nullable circular references + validateInputObjectCircularRefs(type); + } + } +} + +function validateFields( + context: SchemaValidationContext, + type: GraphQLObjectType | GraphQLInterfaceType, +): void { + const fields = objectValues(type.getFields()); + + // Objects and Interfaces both must define one or more fields. + if (fields.length === 0) { + context.reportError( + `Type ${type.name} must define one or more fields.`, + getAllNodes(type), + ); + } + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); + + // Ensure the type is an output type + if (!isOutputType(field.type)) { + context.reportError( + `The type of ${type.name}.${field.name} must be Output Type ` + + `but got: ${inspect(field.type)}.`, + field.astNode?.type, + ); + } + + // Ensure the arguments are valid + for (const arg of field.args) { + const argName = arg.name; + + // Ensure they are named correctly. + validateName(context, arg); + + // Ensure the type is an input type + if (!isInputType(arg.type)) { + context.reportError( + `The type of ${type.name}.${field.name}(${argName}:) must be Input ` + + `Type but got: ${inspect(arg.type)}.`, + arg.astNode?.type, + ); + } + + if (isRequiredArgument(arg) && arg.deprecationReason != null) { + context.reportError( + `Required argument ${type.name}.${field.name}(${argName}:) cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(arg.astNode), + // istanbul ignore next (TODO need to write coverage tests) + arg.astNode?.type, + ], + ); + } + } + } +} + +function validateInterfaces( + context: SchemaValidationContext, + type: GraphQLObjectType | GraphQLInterfaceType, +): void { + const ifaceTypeNames = Object.create(null); + for (const iface of type.getInterfaces()) { + if (!isInterfaceType(iface)) { + context.reportError( + `Type ${inspect(type)} must only implement Interface types, ` + + `it cannot implement ${inspect(iface)}.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + if (type === iface) { + context.reportError( + `Type ${type.name} cannot implement itself because it would create a circular reference.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + if (ifaceTypeNames[iface.name]) { + context.reportError( + `Type ${type.name} can only implement ${iface.name} once.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + ifaceTypeNames[iface.name] = true; + + validateTypeImplementsAncestors(context, type, iface); + validateTypeImplementsInterface(context, type, iface); + } +} + +function validateTypeImplementsInterface( + context: SchemaValidationContext, + type: GraphQLObjectType | GraphQLInterfaceType, + iface: GraphQLInterfaceType, +): void { + const typeFieldMap = type.getFields(); + + // Assert each interface field is implemented. + for (const ifaceField of objectValues(iface.getFields())) { + const fieldName = ifaceField.name; + const typeField = typeFieldMap[fieldName]; + + // Assert interface field exists on type. + if (!typeField) { + context.reportError( + `Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`, + [ifaceField.astNode, ...getAllNodes(type)], + ); + continue; + } + + // Assert interface field type is satisfied by type field type, by being + // a valid subtype. (covariant) + if (!isTypeSubTypeOf(context.schema, typeField.type, ifaceField.type)) { + context.reportError( + `Interface field ${iface.name}.${fieldName} expects type ` + + `${inspect(ifaceField.type)} but ${type.name}.${fieldName} ` + + `is type ${inspect(typeField.type)}.`, + [ + // istanbul ignore next (TODO need to write coverage tests) + ifaceField.astNode?.type, + // istanbul ignore next (TODO need to write coverage tests) + typeField.astNode?.type, + ], + ); + } + + // Assert each interface field arg is implemented. + for (const ifaceArg of ifaceField.args) { + const argName = ifaceArg.name; + const typeArg = find(typeField.args, (arg) => arg.name === argName); + + // Assert interface field arg exists on object field. + if (!typeArg) { + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`, + [ifaceArg.astNode, typeField.astNode], + ); + continue; + } + + // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + if (!isEqualType(ifaceArg.type, typeArg.type)) { + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + + `expects type ${inspect(ifaceArg.type)} but ` + + `${type.name}.${fieldName}(${argName}:) is type ` + + `${inspect(typeArg.type)}.`, + [ + // istanbul ignore next (TODO need to write coverage tests) + ifaceArg.astNode?.type, + // istanbul ignore next (TODO need to write coverage tests) + typeArg.astNode?.type, + ], + ); + } + + // TODO: validate default values? + } + + // Assert additional arguments must not be required. + for (const typeArg of typeField.args) { + const argName = typeArg.name; + const ifaceArg = find(ifaceField.args, (arg) => arg.name === argName); + if (!ifaceArg && isRequiredArgument(typeArg)) { + context.reportError( + `Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`, + [typeArg.astNode, ifaceField.astNode], + ); + } + } + } +} + +function validateTypeImplementsAncestors( + context: SchemaValidationContext, + type: GraphQLObjectType | GraphQLInterfaceType, + iface: GraphQLInterfaceType, +): void { + const ifaceInterfaces = type.getInterfaces(); + for (const transitive of iface.getInterfaces()) { + if (ifaceInterfaces.indexOf(transitive) === -1) { + context.reportError( + transitive === type + ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.` + : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`, + [ + ...getAllImplementsInterfaceNodes(iface, transitive), + ...getAllImplementsInterfaceNodes(type, iface), + ], + ); + } + } +} + +function validateUnionMembers( + context: SchemaValidationContext, + union: GraphQLUnionType, +): void { + const memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError( + `Union type ${union.name} must define one or more member types.`, + getAllNodes(union), + ); + } + + const includedTypeNames = Object.create(null); + for (const memberType of memberTypes) { + if (includedTypeNames[memberType.name]) { + context.reportError( + `Union type ${union.name} can only include type ${memberType.name} once.`, + getUnionMemberTypeNodes(union, memberType.name), + ); + continue; + } + includedTypeNames[memberType.name] = true; + if (!isObjectType(memberType)) { + context.reportError( + `Union type ${union.name} can only include Object types, ` + + `it cannot include ${inspect(memberType)}.`, + getUnionMemberTypeNodes(union, String(memberType)), + ); + } + } +} + +function validateEnumValues( + context: SchemaValidationContext, + enumType: GraphQLEnumType, +): void { + const enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError( + `Enum type ${enumType.name} must define one or more values.`, + getAllNodes(enumType), + ); + } + + for (const enumValue of enumValues) { + const valueName = enumValue.name; + + // Ensure valid name. + validateName(context, enumValue); + if (valueName === 'true' || valueName === 'false' || valueName === 'null') { + context.reportError( + `Enum type ${enumType.name} cannot include value: ${valueName}.`, + enumValue.astNode, + ); + } + } +} + +function validateInputFields( + context: SchemaValidationContext, + inputObj: GraphQLInputObjectType, +): void { + const fields = objectValues(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError( + `Input Object type ${inputObj.name} must define one or more fields.`, + getAllNodes(inputObj), + ); + } + + // Ensure the arguments are valid + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); + + // Ensure the type is an input type + if (!isInputType(field.type)) { + context.reportError( + `The type of ${inputObj.name}.${field.name} must be Input Type ` + + `but got: ${inspect(field.type)}.`, + field.astNode?.type, + ); + } + + if (isRequiredInputField(field) && field.deprecationReason != null) { + context.reportError( + `Required input field ${inputObj.name}.${field.name} cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(field.astNode), + // istanbul ignore next (TODO need to write coverage tests) + field.astNode?.type, + ], + ); + } + } +} + +function createInputObjectCircularRefsValidator( + context: SchemaValidationContext, +): (GraphQLInputObjectType) => void { + // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. + // Tracks already visited types to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedTypes = Object.create(null); + + // Array of types nodes used to produce meaningful errors + const fieldPath = []; + + // Position in the type path + const fieldPathIndexByTypeName = Object.create(null); + + return detectCycleRecursive; + + // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + function detectCycleRecursive(inputObj: GraphQLInputObjectType): void { + if (visitedTypes[inputObj.name]) { + return; + } + + visitedTypes[inputObj.name] = true; + fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; + + const fields = objectValues(inputObj.getFields()); + for (const field of fields) { + if (isNonNullType(field.type) && isInputObjectType(field.type.ofType)) { + const fieldType = field.type.ofType; + const cycleIndex = fieldPathIndexByTypeName[fieldType.name]; + + fieldPath.push(field); + if (cycleIndex === undefined) { + detectCycleRecursive(fieldType); + } else { + const cyclePath = fieldPath.slice(cycleIndex); + const pathStr = cyclePath.map((fieldObj) => fieldObj.name).join('.'); + context.reportError( + `Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`, + cyclePath.map((fieldObj) => fieldObj.astNode), + ); + } + fieldPath.pop(); + } + } + + fieldPathIndexByTypeName[inputObj.name] = undefined; + } +} + +type SDLDefinedObject<T, K> = { + +astNode: ?T, + +extensionASTNodes?: ?$ReadOnlyArray<K>, + ... +}; + +function getAllNodes<T: ASTNode, K: ASTNode>( + object: SDLDefinedObject<T, K>, +): $ReadOnlyArray<T | K> { + const { astNode, extensionASTNodes } = object; + return astNode + ? extensionASTNodes + ? [astNode].concat(extensionASTNodes) + : [astNode] + : extensionASTNodes ?? []; +} + +function getAllSubNodes<T: ASTNode, K: ASTNode, L: ASTNode>( + object: SDLDefinedObject<T, K>, + getter: (T | K) => ?(L | $ReadOnlyArray<L>), +): $ReadOnlyArray<L> { + let subNodes = []; + for (const node of getAllNodes(object)) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + subNodes = subNodes.concat(getter(node) ?? []); + } + return subNodes; +} + +function getAllImplementsInterfaceNodes( + type: GraphQLObjectType | GraphQLInterfaceType, + iface: GraphQLInterfaceType, +): $ReadOnlyArray<NamedTypeNode> { + return getAllSubNodes(type, (typeNode) => typeNode.interfaces).filter( + (ifaceNode) => ifaceNode.name.value === iface.name, + ); +} + +function getUnionMemberTypeNodes( + union: GraphQLUnionType, + typeName: string, +): ?$ReadOnlyArray<NamedTypeNode> { + return getAllSubNodes(union, (unionNode) => unionNode.types).filter( + (typeNode) => typeNode.name.value === typeName, + ); +} + +function getDeprecatedDirectiveNode( + definitionNode: ?{ +directives?: $ReadOnlyArray<DirectiveNode>, ... }, +): ?DirectiveNode { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + return definitionNode?.directives?.find( + (node) => node.name.value === GraphQLDeprecatedDirective.name, + ); +} diff --git a/school/node_modules/graphql/type/validate.mjs b/school/node_modules/graphql/type/validate.mjs new file mode 100644 index 0000000..ce9f7b0 --- /dev/null +++ b/school/node_modules/graphql/type/validate.mjs @@ -0,0 +1,528 @@ +import find from "../polyfills/find.mjs"; +import objectValues from "../polyfills/objectValues.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import { GraphQLError } from "../error/GraphQLError.mjs"; +import { locatedError } from "../error/locatedError.mjs"; +import { isValidNameError } from "../utilities/assertValidName.mjs"; +import { isEqualType, isTypeSubTypeOf } from "../utilities/typeComparators.mjs"; +import { assertSchema } from "./schema.mjs"; +import { isIntrospectionType } from "./introspection.mjs"; +import { isDirective, GraphQLDeprecatedDirective } from "./directives.mjs"; +import { isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isNamedType, isNonNullType, isInputType, isOutputType, isRequiredArgument, isRequiredInputField } from "./definition.mjs"; +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ + +export function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + assertSchema(schema); // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + + var context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + var errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ + +export function assertValidSchema(schema) { + var errors = validateSchema(schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} + +var SchemaValidationContext = /*#__PURE__*/function () { + function SchemaValidationContext(schema) { + this._errors = []; + this.schema = schema; + } + + var _proto = SchemaValidationContext.prototype; + + _proto.reportError = function reportError(message, nodes) { + var _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; + + this.addError(new GraphQLError(message, _nodes)); + }; + + _proto.addError = function addError(error) { + this._errors.push(error); + }; + + _proto.getErrors = function getErrors() { + return this._errors; + }; + + return SchemaValidationContext; +}(); + +function validateRootTypes(context) { + var schema = context.schema; + var queryType = schema.getQueryType(); + + if (!queryType) { + context.reportError('Query root type must be provided.', schema.astNode); + } else if (!isObjectType(queryType)) { + var _getOperationTypeNode; + + context.reportError("Query root type must be Object type, it cannot be ".concat(inspect(queryType), "."), (_getOperationTypeNode = getOperationTypeNode(schema, 'query')) !== null && _getOperationTypeNode !== void 0 ? _getOperationTypeNode : queryType.astNode); + } + + var mutationType = schema.getMutationType(); + + if (mutationType && !isObjectType(mutationType)) { + var _getOperationTypeNode2; + + context.reportError('Mutation root type must be Object type if provided, it cannot be ' + "".concat(inspect(mutationType), "."), (_getOperationTypeNode2 = getOperationTypeNode(schema, 'mutation')) !== null && _getOperationTypeNode2 !== void 0 ? _getOperationTypeNode2 : mutationType.astNode); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && !isObjectType(subscriptionType)) { + var _getOperationTypeNode3; + + context.reportError('Subscription root type must be Object type if provided, it cannot be ' + "".concat(inspect(subscriptionType), "."), (_getOperationTypeNode3 = getOperationTypeNode(schema, 'subscription')) !== null && _getOperationTypeNode3 !== void 0 ? _getOperationTypeNode3 : subscriptionType.astNode); + } +} + +function getOperationTypeNode(schema, operation) { + var operationNodes = getAllSubNodes(schema, function (node) { + return node.operationTypes; + }); + + for (var _i2 = 0; _i2 < operationNodes.length; _i2++) { + var node = operationNodes[_i2]; + + if (node.operation === operation) { + return node.type; + } + } + + return undefined; +} + +function validateDirectives(context) { + for (var _i4 = 0, _context$schema$getDi2 = context.schema.getDirectives(); _i4 < _context$schema$getDi2.length; _i4++) { + var directive = _context$schema$getDi2[_i4]; + + // Ensure all directives are in fact GraphQL directives. + if (!isDirective(directive)) { + context.reportError("Expected directive but got: ".concat(inspect(directive), "."), directive === null || directive === void 0 ? void 0 : directive.astNode); + continue; + } // Ensure they are named correctly. + + + validateName(context, directive); // TODO: Ensure proper locations. + // Ensure the arguments are valid. + + for (var _i6 = 0, _directive$args2 = directive.args; _i6 < _directive$args2.length; _i6++) { + var arg = _directive$args2[_i6]; + // Ensure they are named correctly. + validateName(context, arg); // Ensure the type is an input type. + + if (!isInputType(arg.type)) { + context.reportError("The type of @".concat(directive.name, "(").concat(arg.name, ":) must be Input Type ") + "but got: ".concat(inspect(arg.type), "."), arg.astNode); + } + + if (isRequiredArgument(arg) && arg.deprecationReason != null) { + var _arg$astNode; + + context.reportError("Required argument @".concat(directive.name, "(").concat(arg.name, ":) cannot be deprecated."), [getDeprecatedDirectiveNode(arg.astNode), // istanbul ignore next (TODO need to write coverage tests) + (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 ? void 0 : _arg$astNode.type]); + } + } + } +} + +function validateName(context, node) { + // Ensure names are valid, however introspection types opt out. + var error = isValidNameError(node.name); + + if (error) { + context.addError(locatedError(error, node.astNode)); + } +} + +function validateTypes(context) { + var validateInputObjectCircularRefs = createInputObjectCircularRefsValidator(context); + var typeMap = context.schema.getTypeMap(); + + for (var _i8 = 0, _objectValues2 = objectValues(typeMap); _i8 < _objectValues2.length; _i8++) { + var type = _objectValues2[_i8]; + + // Ensure all provided types are in fact GraphQL type. + if (!isNamedType(type)) { + context.reportError("Expected GraphQL named type but got: ".concat(inspect(type), "."), type.astNode); + continue; + } // Ensure it is named correctly (excluding introspection types). + + + if (!isIntrospectionType(type)) { + validateName(context, type); + } + + if (isObjectType(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if (isInterfaceType(type)) { + // Ensure fields are valid. + validateFields(context, type); // Ensure interfaces implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if (isUnionType(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if (isEnumType(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if (isInputObjectType(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references + + validateInputObjectCircularRefs(type); + } + } +} + +function validateFields(context, type) { + var fields = objectValues(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError("Type ".concat(type.name, " must define one or more fields."), getAllNodes(type)); + } + + for (var _i10 = 0; _i10 < fields.length; _i10++) { + var field = fields[_i10]; + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an output type + + if (!isOutputType(field.type)) { + var _field$astNode; + + context.reportError("The type of ".concat(type.name, ".").concat(field.name, " must be Output Type ") + "but got: ".concat(inspect(field.type), "."), (_field$astNode = field.astNode) === null || _field$astNode === void 0 ? void 0 : _field$astNode.type); + } // Ensure the arguments are valid + + + for (var _i12 = 0, _field$args2 = field.args; _i12 < _field$args2.length; _i12++) { + var arg = _field$args2[_i12]; + var argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure the type is an input type + + if (!isInputType(arg.type)) { + var _arg$astNode2; + + context.reportError("The type of ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) must be Input ") + "Type but got: ".concat(inspect(arg.type), "."), (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0 ? void 0 : _arg$astNode2.type); + } + + if (isRequiredArgument(arg) && arg.deprecationReason != null) { + var _arg$astNode3; + + context.reportError("Required argument ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) cannot be deprecated."), [getDeprecatedDirectiveNode(arg.astNode), // istanbul ignore next (TODO need to write coverage tests) + (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0 ? void 0 : _arg$astNode3.type]); + } + } + } +} + +function validateInterfaces(context, type) { + var ifaceTypeNames = Object.create(null); + + for (var _i14 = 0, _type$getInterfaces2 = type.getInterfaces(); _i14 < _type$getInterfaces2.length; _i14++) { + var iface = _type$getInterfaces2[_i14]; + + if (!isInterfaceType(iface)) { + context.reportError("Type ".concat(inspect(type), " must only implement Interface types, ") + "it cannot implement ".concat(inspect(iface), "."), getAllImplementsInterfaceNodes(type, iface)); + continue; + } + + if (type === iface) { + context.reportError("Type ".concat(type.name, " cannot implement itself because it would create a circular reference."), getAllImplementsInterfaceNodes(type, iface)); + continue; + } + + if (ifaceTypeNames[iface.name]) { + context.reportError("Type ".concat(type.name, " can only implement ").concat(iface.name, " once."), getAllImplementsInterfaceNodes(type, iface)); + continue; + } + + ifaceTypeNames[iface.name] = true; + validateTypeImplementsAncestors(context, type, iface); + validateTypeImplementsInterface(context, type, iface); + } +} + +function validateTypeImplementsInterface(context, type, iface) { + var typeFieldMap = type.getFields(); // Assert each interface field is implemented. + + for (var _i16 = 0, _objectValues4 = objectValues(iface.getFields()); _i16 < _objectValues4.length; _i16++) { + var ifaceField = _objectValues4[_i16]; + var fieldName = ifaceField.name; + var typeField = typeFieldMap[fieldName]; // Assert interface field exists on type. + + if (!typeField) { + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expected but ").concat(type.name, " does not provide it."), [ifaceField.astNode].concat(getAllNodes(type))); + continue; + } // Assert interface field type is satisfied by type field type, by being + // a valid subtype. (covariant) + + + if (!isTypeSubTypeOf(context.schema, typeField.type, ifaceField.type)) { + var _ifaceField$astNode, _typeField$astNode; + + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expects type ") + "".concat(inspect(ifaceField.type), " but ").concat(type.name, ".").concat(fieldName, " ") + "is type ".concat(inspect(typeField.type), "."), [// istanbul ignore next (TODO need to write coverage tests) + (_ifaceField$astNode = ifaceField.astNode) === null || _ifaceField$astNode === void 0 ? void 0 : _ifaceField$astNode.type, // istanbul ignore next (TODO need to write coverage tests) + (_typeField$astNode = typeField.astNode) === null || _typeField$astNode === void 0 ? void 0 : _typeField$astNode.type]); + } // Assert each interface field arg is implemented. + + + var _loop = function _loop(_i18, _ifaceField$args2) { + var ifaceArg = _ifaceField$args2[_i18]; + var argName = ifaceArg.name; + var typeArg = find(typeField.args, function (arg) { + return arg.name === argName; + }); // Assert interface field arg exists on object field. + + if (!typeArg) { + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) expected but ").concat(type.name, ".").concat(fieldName, " does not provide it."), [ifaceArg.astNode, typeField.astNode]); + return "continue"; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + + if (!isEqualType(ifaceArg.type, typeArg.type)) { + var _ifaceArg$astNode, _typeArg$astNode; + + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expects type ".concat(inspect(ifaceArg.type), " but ") + "".concat(type.name, ".").concat(fieldName, "(").concat(argName, ":) is type ") + "".concat(inspect(typeArg.type), "."), [// istanbul ignore next (TODO need to write coverage tests) + (_ifaceArg$astNode = ifaceArg.astNode) === null || _ifaceArg$astNode === void 0 ? void 0 : _ifaceArg$astNode.type, // istanbul ignore next (TODO need to write coverage tests) + (_typeArg$astNode = typeArg.astNode) === null || _typeArg$astNode === void 0 ? void 0 : _typeArg$astNode.type]); + } // TODO: validate default values? + + }; + + for (var _i18 = 0, _ifaceField$args2 = ifaceField.args; _i18 < _ifaceField$args2.length; _i18++) { + var _ret = _loop(_i18, _ifaceField$args2); + + if (_ret === "continue") continue; + } // Assert additional arguments must not be required. + + + var _loop2 = function _loop2(_i20, _typeField$args2) { + var typeArg = _typeField$args2[_i20]; + var argName = typeArg.name; + var ifaceArg = find(ifaceField.args, function (arg) { + return arg.name === argName; + }); + + if (!ifaceArg && isRequiredArgument(typeArg)) { + context.reportError("Object field ".concat(type.name, ".").concat(fieldName, " includes required argument ").concat(argName, " that is missing from the Interface field ").concat(iface.name, ".").concat(fieldName, "."), [typeArg.astNode, ifaceField.astNode]); + } + }; + + for (var _i20 = 0, _typeField$args2 = typeField.args; _i20 < _typeField$args2.length; _i20++) { + _loop2(_i20, _typeField$args2); + } + } +} + +function validateTypeImplementsAncestors(context, type, iface) { + var ifaceInterfaces = type.getInterfaces(); + + for (var _i22 = 0, _iface$getInterfaces2 = iface.getInterfaces(); _i22 < _iface$getInterfaces2.length; _i22++) { + var transitive = _iface$getInterfaces2[_i22]; + + if (ifaceInterfaces.indexOf(transitive) === -1) { + context.reportError(transitive === type ? "Type ".concat(type.name, " cannot implement ").concat(iface.name, " because it would create a circular reference.") : "Type ".concat(type.name, " must implement ").concat(transitive.name, " because it is implemented by ").concat(iface.name, "."), [].concat(getAllImplementsInterfaceNodes(iface, transitive), getAllImplementsInterfaceNodes(type, iface))); + } + } +} + +function validateUnionMembers(context, union) { + var memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError("Union type ".concat(union.name, " must define one or more member types."), getAllNodes(union)); + } + + var includedTypeNames = Object.create(null); + + for (var _i24 = 0; _i24 < memberTypes.length; _i24++) { + var memberType = memberTypes[_i24]; + + if (includedTypeNames[memberType.name]) { + context.reportError("Union type ".concat(union.name, " can only include type ").concat(memberType.name, " once."), getUnionMemberTypeNodes(union, memberType.name)); + continue; + } + + includedTypeNames[memberType.name] = true; + + if (!isObjectType(memberType)) { + context.reportError("Union type ".concat(union.name, " can only include Object types, ") + "it cannot include ".concat(inspect(memberType), "."), getUnionMemberTypeNodes(union, String(memberType))); + } + } +} + +function validateEnumValues(context, enumType) { + var enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError("Enum type ".concat(enumType.name, " must define one or more values."), getAllNodes(enumType)); + } + + for (var _i26 = 0; _i26 < enumValues.length; _i26++) { + var enumValue = enumValues[_i26]; + var valueName = enumValue.name; // Ensure valid name. + + validateName(context, enumValue); + + if (valueName === 'true' || valueName === 'false' || valueName === 'null') { + context.reportError("Enum type ".concat(enumType.name, " cannot include value: ").concat(valueName, "."), enumValue.astNode); + } + } +} + +function validateInputFields(context, inputObj) { + var fields = objectValues(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError("Input Object type ".concat(inputObj.name, " must define one or more fields."), getAllNodes(inputObj)); + } // Ensure the arguments are valid + + + for (var _i28 = 0; _i28 < fields.length; _i28++) { + var field = fields[_i28]; + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an input type + + if (!isInputType(field.type)) { + var _field$astNode2; + + context.reportError("The type of ".concat(inputObj.name, ".").concat(field.name, " must be Input Type ") + "but got: ".concat(inspect(field.type), "."), (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 ? void 0 : _field$astNode2.type); + } + + if (isRequiredInputField(field) && field.deprecationReason != null) { + var _field$astNode3; + + context.reportError("Required input field ".concat(inputObj.name, ".").concat(field.name, " cannot be deprecated."), [getDeprecatedDirectiveNode(field.astNode), // istanbul ignore next (TODO need to write coverage tests) + (_field$astNode3 = field.astNode) === null || _field$astNode3 === void 0 ? void 0 : _field$astNode3.type]); + } + } +} + +function createInputObjectCircularRefsValidator(context) { + // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. + // Tracks already visited types to maintain O(N) and to ensure that cycles + // are not redundantly reported. + var visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors + + var fieldPath = []; // Position in the type path + + var fieldPathIndexByTypeName = Object.create(null); + return detectCycleRecursive; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(inputObj) { + if (visitedTypes[inputObj.name]) { + return; + } + + visitedTypes[inputObj.name] = true; + fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; + var fields = objectValues(inputObj.getFields()); + + for (var _i30 = 0; _i30 < fields.length; _i30++) { + var field = fields[_i30]; + + if (isNonNullType(field.type) && isInputObjectType(field.type.ofType)) { + var fieldType = field.type.ofType; + var cycleIndex = fieldPathIndexByTypeName[fieldType.name]; + fieldPath.push(field); + + if (cycleIndex === undefined) { + detectCycleRecursive(fieldType); + } else { + var cyclePath = fieldPath.slice(cycleIndex); + var pathStr = cyclePath.map(function (fieldObj) { + return fieldObj.name; + }).join('.'); + context.reportError("Cannot reference Input Object \"".concat(fieldType.name, "\" within itself through a series of non-null fields: \"").concat(pathStr, "\"."), cyclePath.map(function (fieldObj) { + return fieldObj.astNode; + })); + } + + fieldPath.pop(); + } + } + + fieldPathIndexByTypeName[inputObj.name] = undefined; + } +} + +function getAllNodes(object) { + var astNode = object.astNode, + extensionASTNodes = object.extensionASTNodes; + return astNode ? extensionASTNodes ? [astNode].concat(extensionASTNodes) : [astNode] : extensionASTNodes !== null && extensionASTNodes !== void 0 ? extensionASTNodes : []; +} + +function getAllSubNodes(object, getter) { + var subNodes = []; + + for (var _i32 = 0, _getAllNodes2 = getAllNodes(object); _i32 < _getAllNodes2.length; _i32++) { + var _getter; + + var node = _getAllNodes2[_i32]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + subNodes = subNodes.concat((_getter = getter(node)) !== null && _getter !== void 0 ? _getter : []); + } + + return subNodes; +} + +function getAllImplementsInterfaceNodes(type, iface) { + return getAllSubNodes(type, function (typeNode) { + return typeNode.interfaces; + }).filter(function (ifaceNode) { + return ifaceNode.name.value === iface.name; + }); +} + +function getUnionMemberTypeNodes(union, typeName) { + return getAllSubNodes(union, function (unionNode) { + return unionNode.types; + }).filter(function (typeNode) { + return typeNode.name.value === typeName; + }); +} + +function getDeprecatedDirectiveNode(definitionNode) { + var _definitionNode$direc; + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + return definitionNode === null || definitionNode === void 0 ? void 0 : (_definitionNode$direc = definitionNode.directives) === null || _definitionNode$direc === void 0 ? void 0 : _definitionNode$direc.find(function (node) { + return node.name.value === GraphQLDeprecatedDirective.name; + }); +} diff --git a/school/node_modules/graphql/utilities/TypeInfo.d.ts b/school/node_modules/graphql/utilities/TypeInfo.d.ts new file mode 100644 index 0000000..499fb02 --- /dev/null +++ b/school/node_modules/graphql/utilities/TypeInfo.d.ts @@ -0,0 +1,60 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { Visitor } from '../language/visitor'; +import { ASTNode, ASTKindToNode, FieldNode } from '../language/ast'; +import { GraphQLSchema } from '../type/schema'; +import { GraphQLDirective } from '../type/directives'; +import { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, + GraphQLArgument, + GraphQLEnumValue, +} from '../type/definition'; + +/** + * 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: GraphQLSchema, + // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant code bases. You should never need to use it. + // It may disappear in the future. + getFieldDefFn?: getFieldDef, + // Initial type may be provided in rare cases to facilitate traversals + // beginning somewhere other than documents. + initialType?: GraphQLType, + ); + + getType(): Maybe<GraphQLOutputType>; + getParentType(): Maybe<GraphQLCompositeType>; + getInputType(): Maybe<GraphQLInputType>; + getParentInputType(): Maybe<GraphQLInputType>; + getFieldDef(): GraphQLField<any, Maybe<any>>; + getDefaultValue(): Maybe<any>; + getDirective(): Maybe<GraphQLDirective>; + getArgument(): Maybe<GraphQLArgument>; + getEnumValue(): Maybe<GraphQLEnumValue>; + enter(node: ASTNode): any; + leave(node: ASTNode): any; +} + +type getFieldDef = ( + schema: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode, +) => Maybe<GraphQLField<any, any>>; + +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ +export function visitWithTypeInfo( + typeInfo: TypeInfo, + visitor: Visitor<ASTKindToNode>, +): Visitor<ASTKindToNode>; diff --git a/school/node_modules/graphql/utilities/TypeInfo.js b/school/node_modules/graphql/utilities/TypeInfo.js new file mode 100644 index 0000000..ccffc74 --- /dev/null +++ b/school/node_modules/graphql/utilities/TypeInfo.js @@ -0,0 +1,397 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.visitWithTypeInfo = visitWithTypeInfo; +exports.TypeInfo = void 0; + +var _find = _interopRequireDefault(require("../polyfills/find.js")); + +var _kinds = require("../language/kinds.js"); + +var _ast = require("../language/ast.js"); + +var _visitor = require("../language/visitor.js"); + +var _definition = require("../type/definition.js"); + +var _introspection = require("../type/introspection.js"); + +var _typeFromAST = require("./typeFromAST.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * 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)`. + */ +var TypeInfo = /*#__PURE__*/function () { + function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant code bases. You should never need to use it. + // It may disappear in the future. + getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals + // beginning somewhere other than documents. + initialType) { + 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); + } + } + } + + var _proto = TypeInfo.prototype; + + _proto.getType = function getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + }; + + _proto.getParentType = function getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + }; + + _proto.getInputType = function getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + }; + + _proto.getParentInputType = function getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + }; + + _proto.getFieldDef = function getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + }; + + _proto.getDefaultValue = function getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + }; + + _proto.getDirective = function getDirective() { + return this._directive; + }; + + _proto.getArgument = function getArgument() { + return this._argument; + }; + + _proto.getEnumValue = function getEnumValue() { + return this._enumValue; + }; + + _proto.enter = function enter(node) { + var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" 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: + { + var namedType = (0, _definition.getNamedType)(this.getType()); + + this._parentTypeStack.push((0, _definition.isCompositeType)(namedType) ? namedType : undefined); + + break; + } + + case _kinds.Kind.FIELD: + { + var parentType = this.getParentType(); + var fieldDef; + var 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: + { + var type; + + switch (node.operation) { + case 'query': + type = schema.getQueryType(); + break; + + case 'mutation': + type = schema.getMutationType(); + break; + + case 'subscription': + type = schema.getSubscriptionType(); + break; + } + + this._typeStack.push((0, _definition.isObjectType)(type) ? type : undefined); + + break; + } + + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + { + var typeConditionAST = node.typeCondition; + var 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: + { + var inputType = (0, _typeFromAST.typeFromAST)(schema, node.type); + + this._inputTypeStack.push((0, _definition.isInputType)(inputType) ? inputType : undefined); + + break; + } + + case _kinds.Kind.ARGUMENT: + { + var _this$getDirective; + + var argDef; + var argType; + var fieldOrDirective = (_this$getDirective = this.getDirective()) !== null && _this$getDirective !== void 0 ? _this$getDirective : this.getFieldDef(); + + if (fieldOrDirective) { + argDef = (0, _find.default)(fieldOrDirective.args, function (arg) { + return 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: + { + var listType = (0, _definition.getNullableType)(this.getInputType()); + var 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: + { + var objectType = (0, _definition.getNamedType)(this.getInputType()); + var inputFieldType; + var 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: + { + var enumType = (0, _definition.getNamedType)(this.getInputType()); + var enumValue; + + if ((0, _definition.isEnumType)(enumType)) { + enumValue = enumType.getValue(node.value); + } + + this._enumValue = enumValue; + break; + } + } + }; + + _proto.leave = function 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; + } + }; + + return 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. + */ + + +exports.TypeInfo = TypeInfo; + +function getFieldDef(schema, parentType, fieldNode) { + var 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: function enter(node) { + typeInfo.enter(node); + var fn = (0, _visitor.getVisitFn)(visitor, node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitor, arguments); + + if (result !== undefined) { + typeInfo.leave(node); + + if ((0, _ast.isNode)(result)) { + typeInfo.enter(result); + } + } + + return result; + } + }, + leave: function leave(node) { + var fn = (0, _visitor.getVisitFn)(visitor, node.kind, + /* isLeaving */ + true); + var result; + + if (fn) { + result = fn.apply(visitor, arguments); + } + + typeInfo.leave(node); + return result; + } + }; +} diff --git a/school/node_modules/graphql/utilities/TypeInfo.js.flow b/school/node_modules/graphql/utilities/TypeInfo.js.flow new file mode 100644 index 0000000..aac8c78 --- /dev/null +++ b/school/node_modules/graphql/utilities/TypeInfo.js.flow @@ -0,0 +1,359 @@ +// @flow strict +import find from '../polyfills/find'; + +import type { Visitor } from '../language/visitor'; +import type { ASTNode, ASTKindToNode, FieldNode } from '../language/ast'; +import { Kind } from '../language/kinds'; +import { isNode } from '../language/ast'; +import { getVisitFn } from '../language/visitor'; + +import type { GraphQLSchema } from '../type/schema'; +import type { GraphQLDirective } from '../type/directives'; +import type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, + GraphQLArgument, + GraphQLInputField, + GraphQLEnumValue, +} from '../type/definition'; +import { + isObjectType, + isInterfaceType, + isEnumType, + isInputObjectType, + isListType, + isCompositeType, + isInputType, + isOutputType, + getNullableType, + getNamedType, +} from '../type/definition'; +import { + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from '../type/introspection'; + +import { typeFromAST } from './typeFromAST'; + +/** + * 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 { + _schema: GraphQLSchema; + _typeStack: Array<?GraphQLOutputType>; + _parentTypeStack: Array<?GraphQLCompositeType>; + _inputTypeStack: Array<?GraphQLInputType>; + _fieldDefStack: Array<?GraphQLField<mixed, mixed>>; + _defaultValueStack: Array<?mixed>; + _directive: ?GraphQLDirective; + _argument: ?GraphQLArgument; + _enumValue: ?GraphQLEnumValue; + _getFieldDef: typeof getFieldDef; + + constructor( + schema: GraphQLSchema, + // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant code bases. You should never need to use it. + // It may disappear in the future. + getFieldDefFn?: typeof getFieldDef, + // Initial type may be provided in rare cases to facilitate traversals + // beginning somewhere other than documents. + initialType?: GraphQLType, + ) { + 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 ?? getFieldDef; + if (initialType) { + if (isInputType(initialType)) { + this._inputTypeStack.push(initialType); + } + if (isCompositeType(initialType)) { + this._parentTypeStack.push(initialType); + } + if (isOutputType(initialType)) { + this._typeStack.push(initialType); + } + } + } + + getType(): ?GraphQLOutputType { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + } + + getParentType(): ?GraphQLCompositeType { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + } + + getInputType(): ?GraphQLInputType { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + } + + getParentInputType(): ?GraphQLInputType { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + } + + getFieldDef(): ?GraphQLField<mixed, mixed> { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + } + + getDefaultValue(): ?mixed { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + } + + getDirective(): ?GraphQLDirective { + return this._directive; + } + + getArgument(): ?GraphQLArgument { + return this._argument; + } + + getEnumValue(): ?GraphQLEnumValue { + return this._enumValue; + } + + enter(node: ASTNode) { + const schema = this._schema; + // Note: many of the types below are explicitly typed as "mixed" 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: mixed = getNamedType(this.getType()); + this._parentTypeStack.push( + isCompositeType(namedType) ? namedType : undefined, + ); + break; + } + case Kind.FIELD: { + const parentType = this.getParentType(); + let fieldDef; + let fieldType: mixed; + 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: { + let type: mixed; + switch (node.operation) { + case 'query': + type = schema.getQueryType(); + break; + case 'mutation': + type = schema.getMutationType(); + break; + case 'subscription': + type = schema.getSubscriptionType(); + break; + } + this._typeStack.push(isObjectType(type) ? type : undefined); + break; + } + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: { + const typeConditionAST = node.typeCondition; + const outputType: mixed = typeConditionAST + ? typeFromAST(schema, typeConditionAST) + : getNamedType(this.getType()); + this._typeStack.push(isOutputType(outputType) ? outputType : undefined); + break; + } + case Kind.VARIABLE_DEFINITION: { + const inputType: mixed = typeFromAST(schema, node.type); + this._inputTypeStack.push( + isInputType(inputType) ? inputType : undefined, + ); + break; + } + case Kind.ARGUMENT: { + let argDef; + let argType: mixed; + const fieldOrDirective = this.getDirective() ?? this.getFieldDef(); + if (fieldOrDirective) { + argDef = find( + fieldOrDirective.args, + (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: mixed = getNullableType(this.getInputType()); + const itemType: mixed = 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: mixed = getNamedType(this.getInputType()); + let inputFieldType: GraphQLInputType | void; + let inputField: GraphQLInputField | void; + 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: mixed = getNamedType(this.getInputType()); + let enumValue; + if (isEnumType(enumType)) { + enumValue = enumType.getValue(node.value); + } + this._enumValue = enumValue; + break; + } + } + } + + leave(node: ASTNode) { + 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; + } + } +} + +/** + * 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: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode, +): ?GraphQLField<mixed, mixed> { + 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: TypeInfo, + visitor: Visitor<ASTKindToNode>, +): Visitor<ASTKindToNode> { + return { + enter(node) { + typeInfo.enter(node); + const fn = getVisitFn(visitor, node.kind, /* isLeaving */ false); + if (fn) { + const result = fn.apply(visitor, arguments); + if (result !== undefined) { + typeInfo.leave(node); + if (isNode(result)) { + typeInfo.enter(result); + } + } + return result; + } + }, + leave(node) { + const fn = getVisitFn(visitor, node.kind, /* isLeaving */ true); + let result; + if (fn) { + result = fn.apply(visitor, arguments); + } + typeInfo.leave(node); + return result; + }, + }; +} diff --git a/school/node_modules/graphql/utilities/TypeInfo.mjs b/school/node_modules/graphql/utilities/TypeInfo.mjs new file mode 100644 index 0000000..00e988f --- /dev/null +++ b/school/node_modules/graphql/utilities/TypeInfo.mjs @@ -0,0 +1,378 @@ +import find from "../polyfills/find.mjs"; +import { Kind } from "../language/kinds.mjs"; +import { isNode } from "../language/ast.mjs"; +import { getVisitFn } from "../language/visitor.mjs"; +import { isObjectType, isInterfaceType, isEnumType, isInputObjectType, isListType, isCompositeType, isInputType, isOutputType, getNullableType, getNamedType } 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 var TypeInfo = /*#__PURE__*/function () { + function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant code bases. You should never need to use it. + // It may disappear in the future. + getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals + // beginning somewhere other than documents. + initialType) { + 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); + } + } + } + + var _proto = TypeInfo.prototype; + + _proto.getType = function getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + }; + + _proto.getParentType = function getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + }; + + _proto.getInputType = function getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + }; + + _proto.getParentInputType = function getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + }; + + _proto.getFieldDef = function getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + }; + + _proto.getDefaultValue = function getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + }; + + _proto.getDirective = function getDirective() { + return this._directive; + }; + + _proto.getArgument = function getArgument() { + return this._argument; + }; + + _proto.getEnumValue = function getEnumValue() { + return this._enumValue; + }; + + _proto.enter = function enter(node) { + var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" 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: + { + var namedType = getNamedType(this.getType()); + + this._parentTypeStack.push(isCompositeType(namedType) ? namedType : undefined); + + break; + } + + case Kind.FIELD: + { + var parentType = this.getParentType(); + var fieldDef; + var 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: + { + var type; + + switch (node.operation) { + case 'query': + type = schema.getQueryType(); + break; + + case 'mutation': + type = schema.getMutationType(); + break; + + case 'subscription': + type = schema.getSubscriptionType(); + break; + } + + this._typeStack.push(isObjectType(type) ? type : undefined); + + break; + } + + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + { + var typeConditionAST = node.typeCondition; + var outputType = typeConditionAST ? typeFromAST(schema, typeConditionAST) : getNamedType(this.getType()); + + this._typeStack.push(isOutputType(outputType) ? outputType : undefined); + + break; + } + + case Kind.VARIABLE_DEFINITION: + { + var inputType = typeFromAST(schema, node.type); + + this._inputTypeStack.push(isInputType(inputType) ? inputType : undefined); + + break; + } + + case Kind.ARGUMENT: + { + var _this$getDirective; + + var argDef; + var argType; + var fieldOrDirective = (_this$getDirective = this.getDirective()) !== null && _this$getDirective !== void 0 ? _this$getDirective : this.getFieldDef(); + + if (fieldOrDirective) { + argDef = find(fieldOrDirective.args, function (arg) { + return 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: + { + var listType = getNullableType(this.getInputType()); + var 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: + { + var objectType = getNamedType(this.getInputType()); + var inputFieldType; + var 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: + { + var enumType = getNamedType(this.getInputType()); + var enumValue; + + if (isEnumType(enumType)) { + enumValue = enumType.getValue(node.value); + } + + this._enumValue = enumValue; + break; + } + } + }; + + _proto.leave = function 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; + } + }; + + return 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) { + var 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: function enter(node) { + typeInfo.enter(node); + var fn = getVisitFn(visitor, node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitor, arguments); + + if (result !== undefined) { + typeInfo.leave(node); + + if (isNode(result)) { + typeInfo.enter(result); + } + } + + return result; + } + }, + leave: function leave(node) { + var fn = getVisitFn(visitor, node.kind, + /* isLeaving */ + true); + var result; + + if (fn) { + result = fn.apply(visitor, arguments); + } + + typeInfo.leave(node); + return result; + } + }; +} diff --git a/school/node_modules/graphql/utilities/assertValidName.d.ts b/school/node_modules/graphql/utilities/assertValidName.d.ts new file mode 100644 index 0000000..5a1011e --- /dev/null +++ b/school/node_modules/graphql/utilities/assertValidName.d.ts @@ -0,0 +1,11 @@ +import { GraphQLError } from '../error/GraphQLError'; + +/** + * Upholds the spec rules about naming. + */ +export function assertValidName(name: string): string; + +/** + * Returns an Error if a name is invalid. + */ +export function isValidNameError(name: string): GraphQLError | undefined; diff --git a/school/node_modules/graphql/utilities/assertValidName.js b/school/node_modules/graphql/utilities/assertValidName.js new file mode 100644 index 0000000..5affb00 --- /dev/null +++ b/school/node_modules/graphql/utilities/assertValidName.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assertValidName = assertValidName; +exports.isValidNameError = isValidNameError; + +var _devAssert = _interopRequireDefault(require("../jsutils/devAssert.js")); + +var _GraphQLError = require("../error/GraphQLError.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * Upholds the spec rules about naming. + */ + +function assertValidName(name) { + var error = isValidNameError(name); + + if (error) { + throw error; + } + + return name; +} +/** + * Returns an Error if a name is invalid. + */ + + +function isValidNameError(name) { + typeof name === 'string' || (0, _devAssert.default)(0, 'Expected name to be a string.'); + + if (name.length > 1 && name[0] === '_' && name[1] === '_') { + return new _GraphQLError.GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by GraphQL introspection.")); + } + + if (!NAME_RX.test(name)) { + return new _GraphQLError.GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not.")); + } +} diff --git a/school/node_modules/graphql/utilities/assertValidName.js.flow b/school/node_modules/graphql/utilities/assertValidName.js.flow new file mode 100644 index 0000000..2e2493a --- /dev/null +++ b/school/node_modules/graphql/utilities/assertValidName.js.flow @@ -0,0 +1,34 @@ +// @flow strict +import devAssert from '../jsutils/devAssert'; + +import { GraphQLError } from '../error/GraphQLError'; + +const NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * Upholds the spec rules about naming. + */ +export function assertValidName(name: string): string { + const error = isValidNameError(name); + if (error) { + throw error; + } + return name; +} + +/** + * Returns an Error if a name is invalid. + */ +export function isValidNameError(name: string): GraphQLError | void { + devAssert(typeof name === 'string', 'Expected name to be a string.'); + if (name.length > 1 && name[0] === '_' && name[1] === '_') { + return new GraphQLError( + `Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`, + ); + } + if (!NAME_RX.test(name)) { + return new GraphQLError( + `Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "${name}" does not.`, + ); + } +} diff --git a/school/node_modules/graphql/utilities/assertValidName.mjs b/school/node_modules/graphql/utilities/assertValidName.mjs new file mode 100644 index 0000000..d504d22 --- /dev/null +++ b/school/node_modules/graphql/utilities/assertValidName.mjs @@ -0,0 +1,31 @@ +import devAssert from "../jsutils/devAssert.mjs"; +import { GraphQLError } from "../error/GraphQLError.mjs"; +var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * Upholds the spec rules about naming. + */ + +export function assertValidName(name) { + var error = isValidNameError(name); + + if (error) { + throw error; + } + + return name; +} +/** + * Returns an Error if a name is invalid. + */ + +export function isValidNameError(name) { + typeof name === 'string' || devAssert(0, 'Expected name to be a string.'); + + if (name.length > 1 && name[0] === '_' && name[1] === '_') { + return new GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by GraphQL introspection.")); + } + + if (!NAME_RX.test(name)) { + return new GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not.")); + } +} diff --git a/school/node_modules/graphql/utilities/astFromValue.d.ts b/school/node_modules/graphql/utilities/astFromValue.d.ts new file mode 100644 index 0000000..19f0a8f --- /dev/null +++ b/school/node_modules/graphql/utilities/astFromValue.d.ts @@ -0,0 +1,26 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { ValueNode } from '../language/ast'; +import { GraphQLInputType } from '../type/definition'; + +/** + * Produces a GraphQL Value AST given a JavaScript value. + * + * 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 | + * | Mixed | Enum Value | + * | null | NullValue | + * + */ +export function astFromValue( + value: any, + type: GraphQLInputType, +): Maybe<ValueNode>; diff --git a/school/node_modules/graphql/utilities/astFromValue.js b/school/node_modules/graphql/utilities/astFromValue.js new file mode 100644 index 0000000..6872309 --- /dev/null +++ b/school/node_modules/graphql/utilities/astFromValue.js @@ -0,0 +1,196 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.astFromValue = astFromValue; + +var _isFinite = _interopRequireDefault(require("../polyfills/isFinite.js")); + +var _objectValues3 = _interopRequireDefault(require("../polyfills/objectValues.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _isObjectLike = _interopRequireDefault(require("../jsutils/isObjectLike.js")); + +var _safeArrayFrom = _interopRequireDefault(require("../jsutils/safeArrayFrom.js")); + +var _kinds = require("../language/kinds.js"); + +var _scalars = require("../type/scalars.js"); + +var _definition = require("../type/definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * 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 | + * | Mixed | Enum Value | + * | null | NullValue | + * + */ +function astFromValue(value, type) { + if ((0, _definition.isNonNullType)(type)) { + var 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)) { + var itemType = type.ofType; + var items = (0, _safeArrayFrom.default)(value); + + if (items != null) { + var valuesNodes = []; + + for (var _i2 = 0; _i2 < items.length; _i2++) { + var item = items[_i2]; + var 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.default)(value)) { + return null; + } + + var fieldNodes = []; + + for (var _i4 = 0, _objectValues2 = (0, _objectValues3.default)(type.getFields()); _i4 < _objectValues2.length; _i4++) { + var field = _objectValues2[_i4]; + var 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 + }; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + 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. + var 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' && (0, _isFinite.default)(serialized)) { + var 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: ".concat((0, _inspect.default)(serialized), ".")); + } // istanbul ignore next (Not reachable. All possible input types have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected input type: ' + (0, _inspect.default)(type)); +} +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ + + +var integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; diff --git a/school/node_modules/graphql/utilities/astFromValue.js.flow b/school/node_modules/graphql/utilities/astFromValue.js.flow new file mode 100644 index 0000000..d7528ee --- /dev/null +++ b/school/node_modules/graphql/utilities/astFromValue.js.flow @@ -0,0 +1,154 @@ +// @flow strict +import isFinite from '../polyfills/isFinite'; +import objectValues from '../polyfills/objectValues'; + +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import isObjectLike from '../jsutils/isObjectLike'; +import safeArrayFrom from '../jsutils/safeArrayFrom'; + +import type { ValueNode } from '../language/ast'; +import { Kind } from '../language/kinds'; + +import type { GraphQLInputType } from '../type/definition'; +import { GraphQLID } from '../type/scalars'; +import { + isLeafType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, +} 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 | + * | Mixed | Enum Value | + * | null | NullValue | + * + */ +export function astFromValue(value: mixed, type: GraphQLInputType): ?ValueNode { + if (isNonNullType(type)) { + const astValue = astFromValue(value, type.ofType); + if (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; + + const items = safeArrayFrom(value); + if (items != null) { + const valuesNodes = []; + for (const item of items) { + 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 objectValues(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 }; + } + + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + 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' && 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)}.`); + } + + // istanbul ignore next (Not reachable. All possible input types have been considered) + invariant(false, 'Unexpected input type: ' + inspect((type: empty))); +} + +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ +const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; diff --git a/school/node_modules/graphql/utilities/astFromValue.mjs b/school/node_modules/graphql/utilities/astFromValue.mjs new file mode 100644 index 0000000..b35fb6c --- /dev/null +++ b/school/node_modules/graphql/utilities/astFromValue.mjs @@ -0,0 +1,178 @@ +import isFinite from "../polyfills/isFinite.mjs"; +import objectValues from "../polyfills/objectValues.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import invariant from "../jsutils/invariant.mjs"; +import isObjectLike from "../jsutils/isObjectLike.mjs"; +import safeArrayFrom from "../jsutils/safeArrayFrom.mjs"; +import { Kind } from "../language/kinds.mjs"; +import { GraphQLID } from "../type/scalars.mjs"; +import { isLeafType, isEnumType, isInputObjectType, isListType, isNonNullType } from "../type/definition.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 | + * | Mixed | Enum Value | + * | null | NullValue | + * + */ + +export function astFromValue(value, type) { + if (isNonNullType(type)) { + var 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)) { + var itemType = type.ofType; + var items = safeArrayFrom(value); + + if (items != null) { + var valuesNodes = []; + + for (var _i2 = 0; _i2 < items.length; _i2++) { + var item = items[_i2]; + var 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; + } + + var fieldNodes = []; + + for (var _i4 = 0, _objectValues2 = objectValues(type.getFields()); _i4 < _objectValues2.length; _i4++) { + var field = _objectValues2[_i4]; + var 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 + }; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if (isLeafType(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + var 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' && isFinite(serialized)) { + var 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: ".concat(inspect(serialized), ".")); + } // istanbul ignore next (Not reachable. All possible input types have been considered) + + + false || invariant(0, 'Unexpected input type: ' + inspect(type)); +} +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ + +var integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; diff --git a/school/node_modules/graphql/utilities/buildASTSchema.d.ts b/school/node_modules/graphql/utilities/buildASTSchema.d.ts new file mode 100644 index 0000000..e051436 --- /dev/null +++ b/school/node_modules/graphql/utilities/buildASTSchema.d.ts @@ -0,0 +1,53 @@ +import { DocumentNode } from '../language/ast'; +import { Source } from '../language/source'; +import { GraphQLSchema, GraphQLSchemaValidationOptions } from '../type/schema'; +import { ParseOptions } from '../language/parser'; + +export interface BuildSchemaOptions extends GraphQLSchemaValidationOptions { + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean; + + /** + * 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 + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function buildASTSchema( + documentAST: DocumentNode, + options?: BuildSchemaOptions, +): GraphQLSchema; + +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ +export function buildSchema( + source: string | Source, + options?: BuildSchemaOptions & ParseOptions, +): GraphQLSchema; diff --git a/school/node_modules/graphql/utilities/buildASTSchema.js b/school/node_modules/graphql/utilities/buildASTSchema.js new file mode 100644 index 0000000..859e869 --- /dev/null +++ b/school/node_modules/graphql/utilities/buildASTSchema.js @@ -0,0 +1,117 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildASTSchema = buildASTSchema; +exports.buildSchema = buildSchema; + +var _devAssert = _interopRequireDefault(require("../jsutils/devAssert.js")); + +var _kinds = require("../language/kinds.js"); + +var _parser = require("../language/parser.js"); + +var _validate = require("../validation/validate.js"); + +var _schema = require("../type/schema.js"); + +var _directives = require("../type/directives.js"); + +var _extendSchema = require("./extendSchema.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * 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 + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +function buildASTSchema(documentAST, options) { + documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT || (0, _devAssert.default)(0, '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); + } + + var emptySchemaConfig = { + description: undefined, + types: [], + directives: [], + extensions: undefined, + extensionASTNodes: [], + assumeValid: false + }; + var config = (0, _extendSchema.extendSchemaImpl)(emptySchemaConfig, documentAST, options); + + if (config.astNode == null) { + for (var _i2 = 0, _config$types2 = config.types; _i2 < _config$types2.length; _i2++) { + var type = _config$types2[_i2]; + + 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': + config.query = type; + break; + + case 'Mutation': + config.mutation = type; + break; + + case 'Subscription': + config.subscription = type; + break; + } + } + } + + var directives = config.directives; // If specified directives were not explicitly declared, add them. + + var _loop = function _loop(_i4) { + var stdDirective = _directives.specifiedDirectives[_i4]; + + if (directives.every(function (directive) { + return directive.name !== stdDirective.name; + })) { + directives.push(stdDirective); + } + }; + + for (var _i4 = 0; _i4 < _directives.specifiedDirectives.length; _i4++) { + _loop(_i4); + } + + return new _schema.GraphQLSchema(config); +} +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + + +function buildSchema(source, options) { + var document = (0, _parser.parse)(source, { + noLocation: options === null || options === void 0 ? void 0 : options.noLocation, + allowLegacySDLEmptyFields: options === null || options === void 0 ? void 0 : options.allowLegacySDLEmptyFields, + allowLegacySDLImplementsInterfaces: options === null || options === void 0 ? void 0 : options.allowLegacySDLImplementsInterfaces, + experimentalFragmentVariables: options === null || options === void 0 ? void 0 : options.experimentalFragmentVariables + }); + return buildASTSchema(document, { + commentDescriptions: options === null || options === void 0 ? void 0 : options.commentDescriptions, + assumeValidSDL: options === null || options === void 0 ? void 0 : options.assumeValidSDL, + assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid + }); +} diff --git a/school/node_modules/graphql/utilities/buildASTSchema.js.flow b/school/node_modules/graphql/utilities/buildASTSchema.js.flow new file mode 100644 index 0000000..a271c8c --- /dev/null +++ b/school/node_modules/graphql/utilities/buildASTSchema.js.flow @@ -0,0 +1,129 @@ +// @flow strict +import devAssert from '../jsutils/devAssert'; + +import type { Source } from '../language/source'; +import type { DocumentNode } from '../language/ast'; +import type { ParseOptions } from '../language/parser'; +import { Kind } from '../language/kinds'; +import { parse } from '../language/parser'; + +import { assertValidSDL } from '../validation/validate'; + +import type { GraphQLSchemaValidationOptions } from '../type/schema'; +import { GraphQLSchema } from '../type/schema'; +import { specifiedDirectives } from '../type/directives'; + +import { extendSchemaImpl } from './extendSchema'; + +export type BuildSchemaOptions = {| + ...GraphQLSchemaValidationOptions, + + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean, + + /** + * 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 + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function buildASTSchema( + documentAST: DocumentNode, + options?: BuildSchemaOptions, +): GraphQLSchema { + devAssert( + documentAST != null && documentAST.kind === Kind.DOCUMENT, + 'Must provide valid Document AST.', + ); + + if (options?.assumeValid !== true && options?.assumeValidSDL !== true) { + assertValidSDL(documentAST); + } + + const emptySchemaConfig = { + description: undefined, + types: [], + directives: [], + extensions: undefined, + 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': + config.query = (type: any); + break; + case 'Mutation': + config.mutation = (type: any); + break; + case 'Subscription': + config.subscription = (type: any); + break; + } + } + } + + const { directives } = config; + // If specified directives were not explicitly declared, add them. + for (const stdDirective of specifiedDirectives) { + if (directives.every((directive) => directive.name !== stdDirective.name)) { + directives.push(stdDirective); + } + } + + return new GraphQLSchema(config); +} + +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ +export function buildSchema( + source: string | Source, + options?: {| ...BuildSchemaOptions, ...ParseOptions |}, +): GraphQLSchema { + const document = parse(source, { + noLocation: options?.noLocation, + allowLegacySDLEmptyFields: options?.allowLegacySDLEmptyFields, + allowLegacySDLImplementsInterfaces: + options?.allowLegacySDLImplementsInterfaces, + experimentalFragmentVariables: options?.experimentalFragmentVariables, + }); + + return buildASTSchema(document, { + commentDescriptions: options?.commentDescriptions, + assumeValidSDL: options?.assumeValidSDL, + assumeValid: options?.assumeValid, + }); +} diff --git a/school/node_modules/graphql/utilities/buildASTSchema.mjs b/school/node_modules/graphql/utilities/buildASTSchema.mjs new file mode 100644 index 0000000..8c4d4b1 --- /dev/null +++ b/school/node_modules/graphql/utilities/buildASTSchema.mjs @@ -0,0 +1,100 @@ +import devAssert from "../jsutils/devAssert.mjs"; +import { Kind } from "../language/kinds.mjs"; +import { parse } from "../language/parser.mjs"; +import { assertValidSDL } from "../validation/validate.mjs"; +import { GraphQLSchema } from "../type/schema.mjs"; +import { specifiedDirectives } from "../type/directives.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 + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function buildASTSchema(documentAST, options) { + documentAST != null && documentAST.kind === Kind.DOCUMENT || devAssert(0, '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); + } + + var emptySchemaConfig = { + description: undefined, + types: [], + directives: [], + extensions: undefined, + extensionASTNodes: [], + assumeValid: false + }; + var config = extendSchemaImpl(emptySchemaConfig, documentAST, options); + + if (config.astNode == null) { + for (var _i2 = 0, _config$types2 = config.types; _i2 < _config$types2.length; _i2++) { + var type = _config$types2[_i2]; + + 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': + config.query = type; + break; + + case 'Mutation': + config.mutation = type; + break; + + case 'Subscription': + config.subscription = type; + break; + } + } + } + + var directives = config.directives; // If specified directives were not explicitly declared, add them. + + var _loop = function _loop(_i4) { + var stdDirective = specifiedDirectives[_i4]; + + if (directives.every(function (directive) { + return directive.name !== stdDirective.name; + })) { + directives.push(stdDirective); + } + }; + + for (var _i4 = 0; _i4 < specifiedDirectives.length; _i4++) { + _loop(_i4); + } + + return new GraphQLSchema(config); +} +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + +export function buildSchema(source, options) { + var document = parse(source, { + noLocation: options === null || options === void 0 ? void 0 : options.noLocation, + allowLegacySDLEmptyFields: options === null || options === void 0 ? void 0 : options.allowLegacySDLEmptyFields, + allowLegacySDLImplementsInterfaces: options === null || options === void 0 ? void 0 : options.allowLegacySDLImplementsInterfaces, + experimentalFragmentVariables: options === null || options === void 0 ? void 0 : options.experimentalFragmentVariables + }); + return buildASTSchema(document, { + commentDescriptions: options === null || options === void 0 ? void 0 : options.commentDescriptions, + assumeValidSDL: options === null || options === void 0 ? void 0 : options.assumeValidSDL, + assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid + }); +} diff --git a/school/node_modules/graphql/utilities/buildClientSchema.d.ts b/school/node_modules/graphql/utilities/buildClientSchema.d.ts new file mode 100644 index 0000000..a541cd3 --- /dev/null +++ b/school/node_modules/graphql/utilities/buildClientSchema.d.ts @@ -0,0 +1,20 @@ +import { GraphQLSchema, GraphQLSchemaValidationOptions } from '../type/schema'; + +import { 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 function buildClientSchema( + introspection: IntrospectionQuery, + options?: GraphQLSchemaValidationOptions, +): GraphQLSchema; diff --git a/school/node_modules/graphql/utilities/buildClientSchema.js b/school/node_modules/graphql/utilities/buildClientSchema.js new file mode 100644 index 0000000..979f6d0 --- /dev/null +++ b/school/node_modules/graphql/utilities/buildClientSchema.js @@ -0,0 +1,335 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildClientSchema = buildClientSchema; + +var _objectValues = _interopRequireDefault(require("../polyfills/objectValues.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _devAssert = _interopRequireDefault(require("../jsutils/devAssert.js")); + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap.js")); + +var _isObjectLike = _interopRequireDefault(require("../jsutils/isObjectLike.js")); + +var _parser = require("../language/parser.js"); + +var _schema = require("../type/schema.js"); + +var _directives = require("../type/directives.js"); + +var _scalars = require("../type/scalars.js"); + +var _introspection = require("../type/introspection.js"); + +var _definition = require("../type/definition.js"); + +var _valueFromAST = require("./valueFromAST.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * 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.default)(introspection) && (0, _isObjectLike.default)(introspection.__schema) || (0, _devAssert.default)(0, "Invalid or incomplete introspection result. Ensure that you are passing \"data\" property of introspection response and no \"errors\" was returned alongside: ".concat((0, _inspect.default)(introspection), ".")); // Get the schema from the introspection result. + + var schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. + + var typeMap = (0, _keyValMap.default)(schemaIntrospection.types, function (typeIntrospection) { + return typeIntrospection.name; + }, function (typeIntrospection) { + return buildType(typeIntrospection); + }); // Include standard types only if they are used. + + for (var _i2 = 0, _ref2 = [].concat(_scalars.specifiedScalarTypes, _introspection.introspectionTypes); _i2 < _ref2.length; _i2++) { + var stdType = _ref2[_i2]; + + if (typeMap[stdType.name]) { + typeMap[stdType.name] = stdType; + } + } // Get the root Query, Mutation, and Subscription types. + + + var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null; + var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null; + var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + var 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: (0, _objectValues.default)(typeMap), + directives: 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) { + var 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) { + var nullableRef = typeRef.ofType; + + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + var nullableType = getType(nullableRef); + return new _definition.GraphQLNonNull((0, _definition.assertNullableType)(nullableType)); + } + + return getNamedType(typeRef); + } + + function getNamedType(typeRef) { + var typeName = typeRef.name; + + if (!typeName) { + throw new Error("Unknown type reference: ".concat((0, _inspect.default)(typeRef), ".")); + } + + var type = typeMap[typeName]; + + if (!type) { + throw new Error("Invalid or incomplete schema, unknown type: ".concat(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) { + if (type != null && type.name != null && type.kind != null) { + 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); + } + } + + var typeStr = (0, _inspect.default)(type); + throw new Error("Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ".concat(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) { + var implementingIntrospectionStr = (0, _inspect.default)(implementingIntrospection); + throw new Error("Introspection result missing interfaces: ".concat(implementingIntrospectionStr, ".")); + } + + return implementingIntrospection.interfaces.map(getInterfaceType); + } + + function buildObjectDef(objectIntrospection) { + return new _definition.GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: function interfaces() { + return buildImplementationsList(objectIntrospection); + }, + fields: function fields() { + return buildFieldDefMap(objectIntrospection); + } + }); + } + + function buildInterfaceDef(interfaceIntrospection) { + return new _definition.GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + interfaces: function interfaces() { + return buildImplementationsList(interfaceIntrospection); + }, + fields: function fields() { + return buildFieldDefMap(interfaceIntrospection); + } + }); + } + + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + var unionIntrospectionStr = (0, _inspect.default)(unionIntrospection); + throw new Error("Introspection result missing possibleTypes: ".concat(unionIntrospectionStr, ".")); + } + + return new _definition.GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: function types() { + return unionIntrospection.possibleTypes.map(getObjectType); + } + }); + } + + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + var enumIntrospectionStr = (0, _inspect.default)(enumIntrospection); + throw new Error("Introspection result missing enumValues: ".concat(enumIntrospectionStr, ".")); + } + + return new _definition.GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: (0, _keyValMap.default)(enumIntrospection.enumValues, function (valueIntrospection) { + return valueIntrospection.name; + }, function (valueIntrospection) { + return { + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason + }; + }) + }); + } + + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + var inputObjectIntrospectionStr = (0, _inspect.default)(inputObjectIntrospection); + throw new Error("Introspection result missing inputFields: ".concat(inputObjectIntrospectionStr, ".")); + } + + return new _definition.GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: function fields() { + return buildInputValueDefMap(inputObjectIntrospection.inputFields); + } + }); + } + + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error("Introspection result missing fields: ".concat((0, _inspect.default)(typeIntrospection), ".")); + } + + return (0, _keyValMap.default)(typeIntrospection.fields, function (fieldIntrospection) { + return fieldIntrospection.name; + }, buildField); + } + + function buildField(fieldIntrospection) { + var type = getType(fieldIntrospection.type); + + if (!(0, _definition.isOutputType)(type)) { + var typeStr = (0, _inspect.default)(type); + throw new Error("Introspection must provide output type for fields, but received: ".concat(typeStr, ".")); + } + + if (!fieldIntrospection.args) { + var fieldIntrospectionStr = (0, _inspect.default)(fieldIntrospection); + throw new Error("Introspection result missing field args: ".concat(fieldIntrospectionStr, ".")); + } + + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type: type, + args: buildInputValueDefMap(fieldIntrospection.args) + }; + } + + function buildInputValueDefMap(inputValueIntrospections) { + return (0, _keyValMap.default)(inputValueIntrospections, function (inputValue) { + return inputValue.name; + }, buildInputValue); + } + + function buildInputValue(inputValueIntrospection) { + var type = getType(inputValueIntrospection.type); + + if (!(0, _definition.isInputType)(type)) { + var typeStr = (0, _inspect.default)(type); + throw new Error("Introspection must provide input type for arguments, but received: ".concat(typeStr, ".")); + } + + var defaultValue = inputValueIntrospection.defaultValue != null ? (0, _valueFromAST.valueFromAST)((0, _parser.parseValue)(inputValueIntrospection.defaultValue), type) : undefined; + return { + description: inputValueIntrospection.description, + type: type, + defaultValue: defaultValue, + deprecationReason: inputValueIntrospection.deprecationReason + }; + } + + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + var directiveIntrospectionStr = (0, _inspect.default)(directiveIntrospection); + throw new Error("Introspection result missing directive args: ".concat(directiveIntrospectionStr, ".")); + } + + if (!directiveIntrospection.locations) { + var _directiveIntrospectionStr = (0, _inspect.default)(directiveIntrospection); + + throw new Error("Introspection result missing directive locations: ".concat(_directiveIntrospectionStr, ".")); + } + + return new _directives.GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + isRepeatable: directiveIntrospection.isRepeatable, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args) + }); + } +} diff --git a/school/node_modules/graphql/utilities/buildClientSchema.js.flow b/school/node_modules/graphql/utilities/buildClientSchema.js.flow new file mode 100644 index 0000000..6123954 --- /dev/null +++ b/school/node_modules/graphql/utilities/buildClientSchema.js.flow @@ -0,0 +1,408 @@ +// @flow strict +import objectValues from '../polyfills/objectValues'; + +import inspect from '../jsutils/inspect'; +import devAssert from '../jsutils/devAssert'; +import keyValMap from '../jsutils/keyValMap'; +import isObjectLike from '../jsutils/isObjectLike'; + +import { parseValue } from '../language/parser'; + +import type { GraphQLSchemaValidationOptions } from '../type/schema'; +import type { + GraphQLType, + GraphQLNamedType, + GraphQLFieldConfig, + GraphQLFieldConfigMap, +} from '../type/definition'; +import { GraphQLSchema } from '../type/schema'; +import { GraphQLDirective } from '../type/directives'; +import { specifiedScalarTypes } from '../type/scalars'; +import { introspectionTypes, TypeKind } from '../type/introspection'; +import { + isInputType, + isOutputType, + GraphQLList, + GraphQLNonNull, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + assertNullableType, + assertObjectType, + assertInterfaceType, +} from '../type/definition'; + +import type { + IntrospectionQuery, + IntrospectionDirective, + IntrospectionField, + IntrospectionInputValue, + IntrospectionType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionNamedTypeRef, +} from './getIntrospectionQuery'; +import { valueFromAST } from './valueFromAST'; + +/** + * 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: IntrospectionQuery, + options?: GraphQLSchemaValidationOptions, +): GraphQLSchema { + devAssert( + isObjectLike(introspection) && isObjectLike(introspection.__schema), + `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: objectValues(typeMap), + directives, + assumeValid: options?.assumeValid, + }); + + // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + function getType(typeRef: IntrospectionTypeRef): GraphQLType { + 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: IntrospectionNamedTypeRef<>, + ): GraphQLNamedType { + 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: IntrospectionNamedTypeRef<IntrospectionObjectType>, + ): GraphQLObjectType { + return assertObjectType(getNamedType(typeRef)); + } + + function getInterfaceType( + typeRef: IntrospectionNamedTypeRef<IntrospectionInterfaceType>, + ): GraphQLInterfaceType { + return assertInterfaceType(getNamedType(typeRef)); + } + + // Given a type's introspection result, construct the correct + // GraphQLType instance. + function buildType(type: IntrospectionType): GraphQLNamedType { + if (type != null && type.name != null && type.kind != null) { + 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: IntrospectionScalarType, + ): GraphQLScalarType { + return new GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + specifiedByUrl: scalarIntrospection.specifiedByUrl, + }); + } + + function buildImplementationsList( + implementingIntrospection: + | IntrospectionObjectType + | IntrospectionInterfaceType, + ): Array<GraphQLInterfaceType> { + // 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: IntrospectionObjectType, + ): GraphQLObjectType { + return new GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: () => buildImplementationsList(objectIntrospection), + fields: () => buildFieldDefMap(objectIntrospection), + }); + } + + function buildInterfaceDef( + interfaceIntrospection: IntrospectionInterfaceType, + ): GraphQLInterfaceType { + return new GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + interfaces: () => buildImplementationsList(interfaceIntrospection), + fields: () => buildFieldDefMap(interfaceIntrospection), + }); + } + + function buildUnionDef( + unionIntrospection: IntrospectionUnionType, + ): GraphQLUnionType { + 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: IntrospectionEnumType, + ): GraphQLEnumType { + 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: IntrospectionInputObjectType, + ): GraphQLInputObjectType { + 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: IntrospectionObjectType | IntrospectionInterfaceType, + ): GraphQLFieldConfigMap<mixed, mixed> { + if (!typeIntrospection.fields) { + throw new Error( + `Introspection result missing fields: ${inspect(typeIntrospection)}.`, + ); + } + + return keyValMap( + typeIntrospection.fields, + (fieldIntrospection) => fieldIntrospection.name, + buildField, + ); + } + + function buildField( + fieldIntrospection: IntrospectionField, + ): GraphQLFieldConfig<mixed, mixed> { + 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: $ReadOnlyArray<IntrospectionInputValue>, + ) { + return keyValMap( + inputValueIntrospections, + (inputValue) => inputValue.name, + buildInputValue, + ); + } + + function buildInputValue(inputValueIntrospection: IntrospectionInputValue) { + 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: IntrospectionDirective, + ): GraphQLDirective { + 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), + }); + } +} diff --git a/school/node_modules/graphql/utilities/buildClientSchema.mjs b/school/node_modules/graphql/utilities/buildClientSchema.mjs new file mode 100644 index 0000000..8651a3d --- /dev/null +++ b/school/node_modules/graphql/utilities/buildClientSchema.mjs @@ -0,0 +1,315 @@ +import objectValues from "../polyfills/objectValues.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import devAssert from "../jsutils/devAssert.mjs"; +import keyValMap from "../jsutils/keyValMap.mjs"; +import isObjectLike from "../jsutils/isObjectLike.mjs"; +import { parseValue } from "../language/parser.mjs"; +import { GraphQLSchema } from "../type/schema.mjs"; +import { GraphQLDirective } from "../type/directives.mjs"; +import { specifiedScalarTypes } from "../type/scalars.mjs"; +import { introspectionTypes, TypeKind } from "../type/introspection.mjs"; +import { isInputType, isOutputType, GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, assertNullableType, assertObjectType, assertInterfaceType } from "../type/definition.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(0, "Invalid or incomplete introspection result. Ensure that you are passing \"data\" property of introspection response and no \"errors\" was returned alongside: ".concat(inspect(introspection), ".")); // Get the schema from the introspection result. + + var schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. + + var typeMap = keyValMap(schemaIntrospection.types, function (typeIntrospection) { + return typeIntrospection.name; + }, function (typeIntrospection) { + return buildType(typeIntrospection); + }); // Include standard types only if they are used. + + for (var _i2 = 0, _ref2 = [].concat(specifiedScalarTypes, introspectionTypes); _i2 < _ref2.length; _i2++) { + var stdType = _ref2[_i2]; + + if (typeMap[stdType.name]) { + typeMap[stdType.name] = stdType; + } + } // Get the root Query, Mutation, and Subscription types. + + + var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null; + var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null; + var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + var 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: objectValues(typeMap), + directives: 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) { + var 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) { + var nullableRef = typeRef.ofType; + + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + var nullableType = getType(nullableRef); + return new GraphQLNonNull(assertNullableType(nullableType)); + } + + return getNamedType(typeRef); + } + + function getNamedType(typeRef) { + var typeName = typeRef.name; + + if (!typeName) { + throw new Error("Unknown type reference: ".concat(inspect(typeRef), ".")); + } + + var type = typeMap[typeName]; + + if (!type) { + throw new Error("Invalid or incomplete schema, unknown type: ".concat(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) { + if (type != null && type.name != null && type.kind != null) { + 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); + } + } + + var 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: ".concat(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) { + var implementingIntrospectionStr = inspect(implementingIntrospection); + throw new Error("Introspection result missing interfaces: ".concat(implementingIntrospectionStr, ".")); + } + + return implementingIntrospection.interfaces.map(getInterfaceType); + } + + function buildObjectDef(objectIntrospection) { + return new GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: function interfaces() { + return buildImplementationsList(objectIntrospection); + }, + fields: function fields() { + return buildFieldDefMap(objectIntrospection); + } + }); + } + + function buildInterfaceDef(interfaceIntrospection) { + return new GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + interfaces: function interfaces() { + return buildImplementationsList(interfaceIntrospection); + }, + fields: function fields() { + return buildFieldDefMap(interfaceIntrospection); + } + }); + } + + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + var unionIntrospectionStr = inspect(unionIntrospection); + throw new Error("Introspection result missing possibleTypes: ".concat(unionIntrospectionStr, ".")); + } + + return new GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: function types() { + return unionIntrospection.possibleTypes.map(getObjectType); + } + }); + } + + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + var enumIntrospectionStr = inspect(enumIntrospection); + throw new Error("Introspection result missing enumValues: ".concat(enumIntrospectionStr, ".")); + } + + return new GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: keyValMap(enumIntrospection.enumValues, function (valueIntrospection) { + return valueIntrospection.name; + }, function (valueIntrospection) { + return { + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason + }; + }) + }); + } + + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + var inputObjectIntrospectionStr = inspect(inputObjectIntrospection); + throw new Error("Introspection result missing inputFields: ".concat(inputObjectIntrospectionStr, ".")); + } + + return new GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: function fields() { + return buildInputValueDefMap(inputObjectIntrospection.inputFields); + } + }); + } + + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error("Introspection result missing fields: ".concat(inspect(typeIntrospection), ".")); + } + + return keyValMap(typeIntrospection.fields, function (fieldIntrospection) { + return fieldIntrospection.name; + }, buildField); + } + + function buildField(fieldIntrospection) { + var type = getType(fieldIntrospection.type); + + if (!isOutputType(type)) { + var typeStr = inspect(type); + throw new Error("Introspection must provide output type for fields, but received: ".concat(typeStr, ".")); + } + + if (!fieldIntrospection.args) { + var fieldIntrospectionStr = inspect(fieldIntrospection); + throw new Error("Introspection result missing field args: ".concat(fieldIntrospectionStr, ".")); + } + + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type: type, + args: buildInputValueDefMap(fieldIntrospection.args) + }; + } + + function buildInputValueDefMap(inputValueIntrospections) { + return keyValMap(inputValueIntrospections, function (inputValue) { + return inputValue.name; + }, buildInputValue); + } + + function buildInputValue(inputValueIntrospection) { + var type = getType(inputValueIntrospection.type); + + if (!isInputType(type)) { + var typeStr = inspect(type); + throw new Error("Introspection must provide input type for arguments, but received: ".concat(typeStr, ".")); + } + + var defaultValue = inputValueIntrospection.defaultValue != null ? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type) : undefined; + return { + description: inputValueIntrospection.description, + type: type, + defaultValue: defaultValue, + deprecationReason: inputValueIntrospection.deprecationReason + }; + } + + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + var directiveIntrospectionStr = inspect(directiveIntrospection); + throw new Error("Introspection result missing directive args: ".concat(directiveIntrospectionStr, ".")); + } + + if (!directiveIntrospection.locations) { + var _directiveIntrospectionStr = inspect(directiveIntrospection); + + throw new Error("Introspection result missing directive locations: ".concat(_directiveIntrospectionStr, ".")); + } + + return new GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + isRepeatable: directiveIntrospection.isRepeatable, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args) + }); + } +} diff --git a/school/node_modules/graphql/utilities/coerceInputValue.d.ts b/school/node_modules/graphql/utilities/coerceInputValue.d.ts new file mode 100644 index 0000000..45c70a5 --- /dev/null +++ b/school/node_modules/graphql/utilities/coerceInputValue.d.ts @@ -0,0 +1,17 @@ +import { GraphQLInputType } from '../type/definition'; +import { GraphQLError } from '../error/GraphQLError'; + +type OnErrorCB = ( + path: ReadonlyArray<string | number>, + invalidValue: any, + error: GraphQLError, +) => void; + +/** + * Coerces a JavaScript value given a GraphQL Input Type. + */ +export function coerceInputValue( + inputValue: any, + type: GraphQLInputType, + onError?: OnErrorCB, +): any; diff --git a/school/node_modules/graphql/utilities/coerceInputValue.js b/school/node_modules/graphql/utilities/coerceInputValue.js new file mode 100644 index 0000000..aa2381a --- /dev/null +++ b/school/node_modules/graphql/utilities/coerceInputValue.js @@ -0,0 +1,148 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.coerceInputValue = coerceInputValue; + +var _objectValues3 = _interopRequireDefault(require("../polyfills/objectValues.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _didYouMean = _interopRequireDefault(require("../jsutils/didYouMean.js")); + +var _isObjectLike = _interopRequireDefault(require("../jsutils/isObjectLike.js")); + +var _safeArrayFrom = _interopRequireDefault(require("../jsutils/safeArrayFrom.js")); + +var _suggestionList = _interopRequireDefault(require("../jsutils/suggestionList.js")); + +var _printPathArray = _interopRequireDefault(require("../jsutils/printPathArray.js")); + +var _Path = require("../jsutils/Path.js"); + +var _GraphQLError = require("../error/GraphQLError.js"); + +var _definition = require("../type/definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Coerces a JavaScript value given a GraphQL Input Type. + */ +function coerceInputValue(inputValue, type) { + var onError = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultOnError; + return coerceInputValueImpl(inputValue, type, onError); +} + +function defaultOnError(path, invalidValue, error) { + var errorPrefix = 'Invalid value ' + (0, _inspect.default)(invalidValue); + + if (path.length > 0) { + errorPrefix += " at \"value".concat((0, _printPathArray.default)(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 \"".concat((0, _inspect.default)(type), "\" not to be null."))); + return; + } + + if (inputValue == null) { + // Explicitly return the value null. + return null; + } + + if ((0, _definition.isListType)(type)) { + var itemType = type.ofType; + var coercedList = (0, _safeArrayFrom.default)(inputValue, function (itemValue, index) { + var itemPath = (0, _Path.addPath)(path, index, undefined); + return coerceInputValueImpl(itemValue, itemType, onError, itemPath); + }); + + if (coercedList != null) { + return coercedList; + } // 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.default)(inputValue)) { + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError("Expected type \"".concat(type.name, "\" to be an object."))); + return; + } + + var coercedValue = {}; + var fieldDefs = type.getFields(); + + for (var _i2 = 0, _objectValues2 = (0, _objectValues3.default)(fieldDefs); _i2 < _objectValues2.length; _i2++) { + var field = _objectValues2[_i2]; + var fieldValue = inputValue[field.name]; + + if (fieldValue === undefined) { + if (field.defaultValue !== undefined) { + coercedValue[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + var typeStr = (0, _inspect.default)(field.type); + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError("Field \"".concat(field.name, "\" of required type \"").concat(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 (var _i4 = 0, _Object$keys2 = Object.keys(inputValue); _i4 < _Object$keys2.length; _i4++) { + var fieldName = _Object$keys2[_i4]; + + if (!fieldDefs[fieldName]) { + var suggestions = (0, _suggestionList.default)(fieldName, Object.keys(type.getFields())); + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError("Field \"".concat(fieldName, "\" is not defined by type \"").concat(type.name, "\".") + (0, _didYouMean.default)(suggestions))); + } + } + + return coercedValue; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if ((0, _definition.isLeafType)(type)) { + var 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 \"".concat(type.name, "\". ") + error.message, undefined, undefined, undefined, undefined, error)); + } + + return; + } + + if (parseResult === undefined) { + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError("Expected type \"".concat(type.name, "\"."))); + } + + return parseResult; + } // istanbul ignore next (Not reachable. All possible input types have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected input type: ' + (0, _inspect.default)(type)); +} diff --git a/school/node_modules/graphql/utilities/coerceInputValue.js.flow b/school/node_modules/graphql/utilities/coerceInputValue.js.flow new file mode 100644 index 0000000..a42fa06 --- /dev/null +++ b/school/node_modules/graphql/utilities/coerceInputValue.js.flow @@ -0,0 +1,195 @@ +// @flow strict +import objectValues from '../polyfills/objectValues'; + +import type { Path } from '../jsutils/Path'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import didYouMean from '../jsutils/didYouMean'; +import isObjectLike from '../jsutils/isObjectLike'; +import safeArrayFrom from '../jsutils/safeArrayFrom'; +import suggestionList from '../jsutils/suggestionList'; +import printPathArray from '../jsutils/printPathArray'; +import { addPath, pathToArray } from '../jsutils/Path'; + +import { GraphQLError } from '../error/GraphQLError'; + +import type { GraphQLInputType } from '../type/definition'; +import { + isLeafType, + isInputObjectType, + isListType, + isNonNullType, +} from '../type/definition'; + +type OnErrorCB = ( + path: $ReadOnlyArray<string | number>, + invalidValue: mixed, + error: GraphQLError, +) => void; + +/** + * Coerces a JavaScript value given a GraphQL Input Type. + */ +export function coerceInputValue( + inputValue: mixed, + type: GraphQLInputType, + onError: OnErrorCB = defaultOnError, +): mixed { + return coerceInputValueImpl(inputValue, type, onError); +} + +function defaultOnError( + path: $ReadOnlyArray<string | number>, + invalidValue: mixed, + error: GraphQLError, +): void { + 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: mixed, + type: GraphQLInputType, + onError: OnErrorCB, + path: Path | void, +): mixed { + 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; + + const coercedList = safeArrayFrom(inputValue, (itemValue, index) => { + const itemPath = addPath(path, index, undefined); + return coerceInputValueImpl(itemValue, itemType, onError, itemPath); + }); + + if (coercedList != null) { + return coercedList; + } + + // 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 objectValues(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; + } + + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + 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, + undefined, + undefined, + undefined, + undefined, + error, + ), + ); + } + return; + } + if (parseResult === undefined) { + onError( + pathToArray(path), + inputValue, + new GraphQLError(`Expected type "${type.name}".`), + ); + } + return parseResult; + } + + // istanbul ignore next (Not reachable. All possible input types have been considered) + invariant(false, 'Unexpected input type: ' + inspect((type: empty))); +} diff --git a/school/node_modules/graphql/utilities/coerceInputValue.mjs b/school/node_modules/graphql/utilities/coerceInputValue.mjs new file mode 100644 index 0000000..dbca94c --- /dev/null +++ b/school/node_modules/graphql/utilities/coerceInputValue.mjs @@ -0,0 +1,129 @@ +import objectValues from "../polyfills/objectValues.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import invariant from "../jsutils/invariant.mjs"; +import didYouMean from "../jsutils/didYouMean.mjs"; +import isObjectLike from "../jsutils/isObjectLike.mjs"; +import safeArrayFrom from "../jsutils/safeArrayFrom.mjs"; +import suggestionList from "../jsutils/suggestionList.mjs"; +import printPathArray from "../jsutils/printPathArray.mjs"; +import { addPath, pathToArray } from "../jsutils/Path.mjs"; +import { GraphQLError } from "../error/GraphQLError.mjs"; +import { isLeafType, isInputObjectType, isListType, isNonNullType } from "../type/definition.mjs"; + +/** + * Coerces a JavaScript value given a GraphQL Input Type. + */ +export function coerceInputValue(inputValue, type) { + var onError = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultOnError; + return coerceInputValueImpl(inputValue, type, onError); +} + +function defaultOnError(path, invalidValue, error) { + var errorPrefix = 'Invalid value ' + inspect(invalidValue); + + if (path.length > 0) { + errorPrefix += " at \"value".concat(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 \"".concat(inspect(type), "\" not to be null."))); + return; + } + + if (inputValue == null) { + // Explicitly return the value null. + return null; + } + + if (isListType(type)) { + var itemType = type.ofType; + var coercedList = safeArrayFrom(inputValue, function (itemValue, index) { + var itemPath = addPath(path, index, undefined); + return coerceInputValueImpl(itemValue, itemType, onError, itemPath); + }); + + if (coercedList != null) { + return coercedList; + } // 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 \"".concat(type.name, "\" to be an object."))); + return; + } + + var coercedValue = {}; + var fieldDefs = type.getFields(); + + for (var _i2 = 0, _objectValues2 = objectValues(fieldDefs); _i2 < _objectValues2.length; _i2++) { + var field = _objectValues2[_i2]; + var fieldValue = inputValue[field.name]; + + if (fieldValue === undefined) { + if (field.defaultValue !== undefined) { + coercedValue[field.name] = field.defaultValue; + } else if (isNonNullType(field.type)) { + var typeStr = inspect(field.type); + onError(pathToArray(path), inputValue, new GraphQLError("Field \"".concat(field.name, "\" of required type \"").concat(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 (var _i4 = 0, _Object$keys2 = Object.keys(inputValue); _i4 < _Object$keys2.length; _i4++) { + var fieldName = _Object$keys2[_i4]; + + if (!fieldDefs[fieldName]) { + var suggestions = suggestionList(fieldName, Object.keys(type.getFields())); + onError(pathToArray(path), inputValue, new GraphQLError("Field \"".concat(fieldName, "\" is not defined by type \"").concat(type.name, "\".") + didYouMean(suggestions))); + } + } + + return coercedValue; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if (isLeafType(type)) { + var 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 \"".concat(type.name, "\". ") + error.message, undefined, undefined, undefined, undefined, error)); + } + + return; + } + + if (parseResult === undefined) { + onError(pathToArray(path), inputValue, new GraphQLError("Expected type \"".concat(type.name, "\"."))); + } + + return parseResult; + } // istanbul ignore next (Not reachable. All possible input types have been considered) + + + false || invariant(0, 'Unexpected input type: ' + inspect(type)); +} diff --git a/school/node_modules/graphql/utilities/concatAST.d.ts b/school/node_modules/graphql/utilities/concatAST.d.ts new file mode 100644 index 0000000..03d441e --- /dev/null +++ b/school/node_modules/graphql/utilities/concatAST.d.ts @@ -0,0 +1,8 @@ +import { 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 function concatAST(asts: ReadonlyArray<DocumentNode>): DocumentNode; diff --git a/school/node_modules/graphql/utilities/concatAST.js b/school/node_modules/graphql/utilities/concatAST.js new file mode 100644 index 0000000..9c3ac48 --- /dev/null +++ b/school/node_modules/graphql/utilities/concatAST.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.concatAST = concatAST; + +/** + * 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) { + var definitions = []; + + for (var _i2 = 0; _i2 < documents.length; _i2++) { + var doc = documents[_i2]; + definitions = definitions.concat(doc.definitions); + } + + return { + kind: 'Document', + definitions: definitions + }; +} diff --git a/school/node_modules/graphql/utilities/concatAST.js.flow b/school/node_modules/graphql/utilities/concatAST.js.flow new file mode 100644 index 0000000..0e0bb5f --- /dev/null +++ b/school/node_modules/graphql/utilities/concatAST.js.flow @@ -0,0 +1,17 @@ +// @flow strict +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 function concatAST( + documents: $ReadOnlyArray<DocumentNode>, +): DocumentNode { + let definitions = []; + for (const doc of documents) { + definitions = definitions.concat(doc.definitions); + } + return { kind: 'Document', definitions }; +} diff --git a/school/node_modules/graphql/utilities/concatAST.mjs b/school/node_modules/graphql/utilities/concatAST.mjs new file mode 100644 index 0000000..4e9e9ee --- /dev/null +++ b/school/node_modules/graphql/utilities/concatAST.mjs @@ -0,0 +1,18 @@ +/** + * 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) { + var definitions = []; + + for (var _i2 = 0; _i2 < documents.length; _i2++) { + var doc = documents[_i2]; + definitions = definitions.concat(doc.definitions); + } + + return { + kind: 'Document', + definitions: definitions + }; +} diff --git a/school/node_modules/graphql/utilities/extendSchema.d.ts b/school/node_modules/graphql/utilities/extendSchema.d.ts new file mode 100644 index 0000000..6795e01 --- /dev/null +++ b/school/node_modules/graphql/utilities/extendSchema.d.ts @@ -0,0 +1,75 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { Location, DocumentNode, StringValueNode } from '../language/ast'; +import { + GraphQLSchemaValidationOptions, + GraphQLSchema, + GraphQLSchemaNormalizedConfig, +} from '../type/schema'; + +interface Options extends GraphQLSchemaValidationOptions { + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean; + + /** + * 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. + * + * Accepts options as a third argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function extendSchema( + schema: GraphQLSchema, + documentAST: DocumentNode, + options?: Options, +): GraphQLSchema; + +/** + * @internal + */ +export function extendSchemaImpl( + schemaConfig: GraphQLSchemaNormalizedConfig, + documentAST: DocumentNode, + options?: Options, +): GraphQLSchemaNormalizedConfig; + +/** + * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function getDescription( + node: { readonly description?: StringValueNode; readonly loc?: Location }, + options?: Maybe<{ commentDescriptions?: boolean }>, +): string | undefined; diff --git a/school/node_modules/graphql/utilities/extendSchema.js b/school/node_modules/graphql/utilities/extendSchema.js new file mode 100644 index 0000000..0b0201d --- /dev/null +++ b/school/node_modules/graphql/utilities/extendSchema.js @@ -0,0 +1,719 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.extendSchema = extendSchema; +exports.extendSchemaImpl = extendSchemaImpl; +exports.getDescription = getDescription; + +var _objectValues = _interopRequireDefault(require("../polyfills/objectValues.js")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _mapValue = _interopRequireDefault(require("../jsutils/mapValue.js")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _devAssert = _interopRequireDefault(require("../jsutils/devAssert.js")); + +var _kinds = require("../language/kinds.js"); + +var _tokenKind = require("../language/tokenKind.js"); + +var _blockString = require("../language/blockString.js"); + +var _predicates = require("../language/predicates.js"); + +var _validate = require("../validation/validate.js"); + +var _values = require("../execution/values.js"); + +var _schema = require("../type/schema.js"); + +var _scalars = require("../type/scalars.js"); + +var _introspection = require("../type/introspection.js"); + +var _directives = require("../type/directives.js"); + +var _definition = require("../type/definition.js"); + +var _valueFromAST = require("./valueFromAST.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * 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. + * + * Accepts options as a third argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +function extendSchema(schema, documentAST, options) { + (0, _schema.assertSchema)(schema); + documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT || (0, _devAssert.default)(0, '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); + } + + var schemaConfig = schema.toConfig(); + var 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. + var typeDefs = []; + var 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". + + var directiveDefs = []; + var schemaDef; // Schema extensions are collected which may add additional operation types. + + var schemaExtensions = []; + + for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) { + var def = _documentAST$definiti2[_i2]; + + 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)) { + var extendedTypeName = def.name.value; + var 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; + } + + var typeMap = Object.create(null); + + for (var _i4 = 0, _schemaConfig$types2 = schemaConfig.types; _i4 < _schemaConfig$types2.length; _i4++) { + var existingType = _schemaConfig$types2[_i4]; + typeMap[existingType.name] = extendNamedType(existingType); + } + + for (var _i6 = 0; _i6 < typeDefs.length; _i6++) { + var _stdTypeMap$name; + + var typeNode = typeDefs[_i6]; + var name = typeNode.name.value; + typeMap[name] = (_stdTypeMap$name = stdTypeMap[name]) !== null && _stdTypeMap$name !== void 0 ? _stdTypeMap$name : buildType(typeNode); + } + + var operationTypes = _objectSpread(_objectSpread({ + // Get the extended root operation types. + query: schemaConfig.query && replaceNamedType(schemaConfig.query), + mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation), + subscription: schemaConfig.subscription && replaceNamedType(schemaConfig.subscription) + }, schemaDef && getOperationTypes([schemaDef])), getOperationTypes(schemaExtensions)); // Then produce and return a Schema config with these types. + + + return _objectSpread(_objectSpread({ + 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: (0, _objectValues.default)(typeMap), + directives: [].concat(schemaConfig.directives.map(replaceDirective), directiveDefs.map(buildDirective)), + extensions: undefined, + 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)) { + // $FlowFixMe[incompatible-return] + return new _definition.GraphQLList(replaceType(type.ofType)); + } + + if ((0, _definition.isNonNullType)(type)) { + // $FlowFixMe[incompatible-return] + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } + + 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) { + var config = directive.toConfig(); + return new _directives.GraphQLDirective(_objectSpread(_objectSpread({}, config), {}, { + args: (0, _mapValue.default)(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); + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if ((0, _definition.isInputObjectType)(type)) { + return extendInputObjectType(type); + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected type: ' + (0, _inspect.default)(type)); + } + + function extendInputObjectType(type) { + var _typeExtensionsMap$co; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co !== void 0 ? _typeExtensionsMap$co : []; + return new _definition.GraphQLInputObjectType(_objectSpread(_objectSpread({}, config), {}, { + fields: function fields() { + return _objectSpread(_objectSpread({}, (0, _mapValue.default)(config.fields, function (field) { + return _objectSpread(_objectSpread({}, field), {}, { + type: replaceType(field.type) + }); + })), buildInputFieldMap(extensions)); + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendEnumType(type) { + var _typeExtensionsMap$ty; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && _typeExtensionsMap$ty !== void 0 ? _typeExtensionsMap$ty : []; + return new _definition.GraphQLEnumType(_objectSpread(_objectSpread({}, config), {}, { + values: _objectSpread(_objectSpread({}, config.values), buildEnumValueMap(extensions)), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendScalarType(type) { + var _typeExtensionsMap$co2; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co2 !== void 0 ? _typeExtensionsMap$co2 : []; + var specifiedByUrl = config.specifiedByUrl; + + for (var _i8 = 0; _i8 < extensions.length; _i8++) { + var _getSpecifiedByUrl; + + var extensionNode = extensions[_i8]; + specifiedByUrl = (_getSpecifiedByUrl = getSpecifiedByUrl(extensionNode)) !== null && _getSpecifiedByUrl !== void 0 ? _getSpecifiedByUrl : specifiedByUrl; + } + + return new _definition.GraphQLScalarType(_objectSpread(_objectSpread({}, config), {}, { + specifiedByUrl: specifiedByUrl, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendObjectType(type) { + var _typeExtensionsMap$co3; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co3 !== void 0 ? _typeExtensionsMap$co3 : []; + return new _definition.GraphQLObjectType(_objectSpread(_objectSpread({}, config), {}, { + interfaces: function interfaces() { + return [].concat(type.getInterfaces().map(replaceNamedType), buildInterfaces(extensions)); + }, + fields: function fields() { + return _objectSpread(_objectSpread({}, (0, _mapValue.default)(config.fields, extendField)), buildFieldMap(extensions)); + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendInterfaceType(type) { + var _typeExtensionsMap$co4; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co4 !== void 0 ? _typeExtensionsMap$co4 : []; + return new _definition.GraphQLInterfaceType(_objectSpread(_objectSpread({}, config), {}, { + interfaces: function interfaces() { + return [].concat(type.getInterfaces().map(replaceNamedType), buildInterfaces(extensions)); + }, + fields: function fields() { + return _objectSpread(_objectSpread({}, (0, _mapValue.default)(config.fields, extendField)), buildFieldMap(extensions)); + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendUnionType(type) { + var _typeExtensionsMap$co5; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co5 !== void 0 ? _typeExtensionsMap$co5 : []; + return new _definition.GraphQLUnionType(_objectSpread(_objectSpread({}, config), {}, { + types: function types() { + return [].concat(type.getTypes().map(replaceNamedType), buildUnionTypes(extensions)); + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendField(field) { + return _objectSpread(_objectSpread({}, field), {}, { + type: replaceType(field.type), + // $FlowFixMe[incompatible-call] + args: (0, _mapValue.default)(field.args, extendArg) + }); + } + + function extendArg(arg) { + return _objectSpread(_objectSpread({}, arg), {}, { + type: replaceType(arg.type) + }); + } + + function getOperationTypes(nodes) { + var opTypes = {}; + + for (var _i10 = 0; _i10 < nodes.length; _i10++) { + var _node$operationTypes; + + var node = nodes[_i10]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; + + for (var _i12 = 0; _i12 < operationTypesNodes.length; _i12++) { + var operationType = operationTypesNodes[_i12]; + opTypes[operationType.operation] = getNamedType(operationType.type); + } + } // 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. + + + return opTypes; + } + + function getNamedType(node) { + var _stdTypeMap$name2; + + var name = node.name.value; + var type = (_stdTypeMap$name2 = stdTypeMap[name]) !== null && _stdTypeMap$name2 !== void 0 ? _stdTypeMap$name2 : typeMap[name]; + + if (type === undefined) { + throw new Error("Unknown type: \"".concat(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 locations = node.locations.map(function (_ref) { + var value = _ref.value; + return value; + }); + return new _directives.GraphQLDirective({ + name: node.name.value, + description: getDescription(node, options), + locations: locations, + isRepeatable: node.repeatable, + args: buildArgumentMap(node.arguments), + astNode: node + }); + } + + function buildFieldMap(nodes) { + var fieldConfigMap = Object.create(null); + + for (var _i14 = 0; _i14 < nodes.length; _i14++) { + var _node$fields; + + var node = nodes[_i14]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var nodeFields = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; + + for (var _i16 = 0; _i16 < nodeFields.length; _i16++) { + var field = nodeFields[_i16]; + 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: getDescription(field, options), + args: buildArgumentMap(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + } + } + + return fieldConfigMap; + } + + function buildArgumentMap(args) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var argsNodes = args !== null && args !== void 0 ? args : []; + var argConfigMap = Object.create(null); + + for (var _i18 = 0; _i18 < argsNodes.length; _i18++) { + var arg = argsNodes[_i18]; + // 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. + var type = getWrappedType(arg.type); + argConfigMap[arg.name.value] = { + type: type, + description: getDescription(arg, options), + defaultValue: (0, _valueFromAST.valueFromAST)(arg.defaultValue, type), + deprecationReason: getDeprecationReason(arg), + astNode: arg + }; + } + + return argConfigMap; + } + + function buildInputFieldMap(nodes) { + var inputFieldMap = Object.create(null); + + for (var _i20 = 0; _i20 < nodes.length; _i20++) { + var _node$fields2; + + var node = nodes[_i20]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var fieldsNodes = (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 ? _node$fields2 : []; + + for (var _i22 = 0; _i22 < fieldsNodes.length; _i22++) { + var field = fieldsNodes[_i22]; + // 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. + var type = getWrappedType(field.type); + inputFieldMap[field.name.value] = { + type: type, + description: getDescription(field, options), + defaultValue: (0, _valueFromAST.valueFromAST)(field.defaultValue, type), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + } + } + + return inputFieldMap; + } + + function buildEnumValueMap(nodes) { + var enumValueMap = Object.create(null); + + for (var _i24 = 0; _i24 < nodes.length; _i24++) { + var _node$values; + + var node = nodes[_i24]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var valuesNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; + + for (var _i26 = 0; _i26 < valuesNodes.length; _i26++) { + var value = valuesNodes[_i26]; + enumValueMap[value.name.value] = { + description: getDescription(value, options), + deprecationReason: getDeprecationReason(value), + astNode: value + }; + } + } + + return enumValueMap; + } + + function buildInterfaces(nodes) { + var interfaces = []; + + for (var _i28 = 0; _i28 < nodes.length; _i28++) { + var _node$interfaces; + + var node = nodes[_i28]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var interfacesNodes = (_node$interfaces = node.interfaces) !== null && _node$interfaces !== void 0 ? _node$interfaces : []; + + for (var _i30 = 0; _i30 < interfacesNodes.length; _i30++) { + var type = interfacesNodes[_i30]; + // 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. + interfaces.push(getNamedType(type)); + } + } + + return interfaces; + } + + function buildUnionTypes(nodes) { + var types = []; + + for (var _i32 = 0; _i32 < nodes.length; _i32++) { + var _node$types; + + var node = nodes[_i32]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var typeNodes = (_node$types = node.types) !== null && _node$types !== void 0 ? _node$types : []; + + for (var _i34 = 0; _i34 < typeNodes.length; _i34++) { + var type = typeNodes[_i34]; + // 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. + types.push(getNamedType(type)); + } + } + + return types; + } + + function buildType(astNode) { + var _typeExtensionsMap$na; + + var name = astNode.name.value; + var description = getDescription(astNode, options); + var extensionNodes = (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && _typeExtensionsMap$na !== void 0 ? _typeExtensionsMap$na : []; + + switch (astNode.kind) { + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + { + var extensionASTNodes = extensionNodes; + var allNodes = [astNode].concat(extensionASTNodes); + return new _definition.GraphQLObjectType({ + name: name, + description: description, + interfaces: function interfaces() { + return buildInterfaces(allNodes); + }, + fields: function fields() { + return buildFieldMap(allNodes); + }, + astNode: astNode, + extensionASTNodes: extensionASTNodes + }); + } + + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + { + var _extensionASTNodes = extensionNodes; + + var _allNodes = [astNode].concat(_extensionASTNodes); + + return new _definition.GraphQLInterfaceType({ + name: name, + description: description, + interfaces: function interfaces() { + return buildInterfaces(_allNodes); + }, + fields: function fields() { + return buildFieldMap(_allNodes); + }, + astNode: astNode, + extensionASTNodes: _extensionASTNodes + }); + } + + case _kinds.Kind.ENUM_TYPE_DEFINITION: + { + var _extensionASTNodes2 = extensionNodes; + + var _allNodes2 = [astNode].concat(_extensionASTNodes2); + + return new _definition.GraphQLEnumType({ + name: name, + description: description, + values: buildEnumValueMap(_allNodes2), + astNode: astNode, + extensionASTNodes: _extensionASTNodes2 + }); + } + + case _kinds.Kind.UNION_TYPE_DEFINITION: + { + var _extensionASTNodes3 = extensionNodes; + + var _allNodes3 = [astNode].concat(_extensionASTNodes3); + + return new _definition.GraphQLUnionType({ + name: name, + description: description, + types: function types() { + return buildUnionTypes(_allNodes3); + }, + astNode: astNode, + extensionASTNodes: _extensionASTNodes3 + }); + } + + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + { + var _extensionASTNodes4 = extensionNodes; + return new _definition.GraphQLScalarType({ + name: name, + description: description, + specifiedByUrl: getSpecifiedByUrl(astNode), + astNode: astNode, + extensionASTNodes: _extensionASTNodes4 + }); + } + + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + { + var _extensionASTNodes5 = extensionNodes; + + var _allNodes4 = [astNode].concat(_extensionASTNodes5); + + return new _definition.GraphQLInputObjectType({ + name: name, + description: description, + fields: function fields() { + return buildInputFieldMap(_allNodes4); + }, + astNode: astNode, + extensionASTNodes: _extensionASTNodes5 + }); + } + } // istanbul ignore next (Not reachable. All possible type definition nodes have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected type definition node: ' + (0, _inspect.default)(astNode)); + } +} + +var stdTypeMap = (0, _keyMap.default)(_scalars.specifiedScalarTypes.concat(_introspection.introspectionTypes), function (type) { + return type.name; +}); +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ + +function getDeprecationReason(node) { + var deprecated = (0, _values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective, node); + return deprecated === null || deprecated === void 0 ? void 0 : deprecated.reason; +} +/** + * Given a scalar node, returns the string value for the specifiedByUrl. + */ + + +function getSpecifiedByUrl(node) { + var specifiedBy = (0, _values.getDirectiveValues)(_directives.GraphQLSpecifiedByDirective, node); + return specifiedBy === null || specifiedBy === void 0 ? void 0 : specifiedBy.url; +} +/** + * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ + + +function getDescription(node, options) { + if (node.description) { + return node.description.value; + } + + if ((options === null || options === void 0 ? void 0 : options.commentDescriptions) === true) { + var rawValue = getLeadingCommentBlock(node); + + if (rawValue !== undefined) { + return (0, _blockString.dedentBlockStringValue)('\n' + rawValue); + } + } +} + +function getLeadingCommentBlock(node) { + var loc = node.loc; + + if (!loc) { + return; + } + + var comments = []; + var token = loc.startToken.prev; + + while (token != null && token.kind === _tokenKind.TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) { + var value = String(token.value); + comments.push(value); + token = token.prev; + } + + return comments.length > 0 ? comments.reverse().join('\n') : undefined; +} diff --git a/school/node_modules/graphql/utilities/extendSchema.js.flow b/school/node_modules/graphql/utilities/extendSchema.js.flow new file mode 100644 index 0000000..2d5a229 --- /dev/null +++ b/school/node_modules/graphql/utilities/extendSchema.js.flow @@ -0,0 +1,782 @@ +// @flow strict +import objectValues from '../polyfills/objectValues'; + +import keyMap from '../jsutils/keyMap'; +import inspect from '../jsutils/inspect'; +import mapValue from '../jsutils/mapValue'; +import invariant from '../jsutils/invariant'; +import devAssert from '../jsutils/devAssert'; + +import type { DirectiveLocationEnum } from '../language/directiveLocation'; +import type { + Location, + DocumentNode, + StringValueNode, + TypeNode, + NamedTypeNode, + SchemaDefinitionNode, + SchemaExtensionNode, + TypeDefinitionNode, + InterfaceTypeDefinitionNode, + InterfaceTypeExtensionNode, + ObjectTypeDefinitionNode, + ObjectTypeExtensionNode, + UnionTypeDefinitionNode, + UnionTypeExtensionNode, + FieldDefinitionNode, + InputObjectTypeDefinitionNode, + InputObjectTypeExtensionNode, + InputValueDefinitionNode, + EnumTypeDefinitionNode, + EnumTypeExtensionNode, + EnumValueDefinitionNode, + DirectiveDefinitionNode, + ScalarTypeDefinitionNode, + ScalarTypeExtensionNode, +} from '../language/ast'; +import { Kind } from '../language/kinds'; +import { TokenKind } from '../language/tokenKind'; +import { dedentBlockStringValue } from '../language/blockString'; +import { + isTypeDefinitionNode, + isTypeExtensionNode, +} from '../language/predicates'; + +import { assertValidSDLExtension } from '../validation/validate'; + +import { getDirectiveValues } from '../execution/values'; + +import type { + GraphQLSchemaValidationOptions, + GraphQLSchemaNormalizedConfig, +} from '../type/schema'; +import type { + GraphQLType, + GraphQLNamedType, + GraphQLFieldConfig, + GraphQLFieldConfigMap, + GraphQLArgumentConfig, + GraphQLFieldConfigArgumentMap, + GraphQLEnumValueConfigMap, + GraphQLInputFieldConfigMap, +} from '../type/definition'; +import { assertSchema, GraphQLSchema } from '../type/schema'; +import { specifiedScalarTypes, isSpecifiedScalarType } from '../type/scalars'; +import { introspectionTypes, isIntrospectionType } from '../type/introspection'; +import { + GraphQLDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, +} from '../type/directives'; +import { + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isListType, + isNonNullType, + isEnumType, + isInputObjectType, + GraphQLList, + GraphQLNonNull, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, +} from '../type/definition'; + +import { valueFromAST } from './valueFromAST'; + +type Options = {| + ...GraphQLSchemaValidationOptions, + + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean, + + /** + * 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. + * + * Accepts options as a third argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function extendSchema( + schema: GraphQLSchema, + documentAST: DocumentNode, + options?: Options, +): GraphQLSchema { + assertSchema(schema); + + devAssert( + documentAST != null && documentAST.kind === Kind.DOCUMENT, + 'Must provide valid Document AST.', + ); + + if (options?.assumeValid !== true && 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: GraphQLSchemaNormalizedConfig, + documentAST: DocumentNode, + options?: Options, +): GraphQLSchemaNormalizedConfig { + // Collect the type definitions and extensions found in the document. + const typeDefs: Array<TypeDefinitionNode> = []; + 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: Array<DirectiveDefinitionNode> = []; + + let schemaDef: ?SchemaDefinitionNode; + // Schema extensions are collected which may add additional operation types. + const schemaExtensions: Array<SchemaExtensionNode> = []; + + 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) { + const name = typeNode.name.value; + typeMap[name] = 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?.description?.value, + ...operationTypes, + types: objectValues(typeMap), + directives: [ + ...schemaConfig.directives.map(replaceDirective), + ...directiveDefs.map(buildDirective), + ], + extensions: undefined, + astNode: schemaDef ?? schemaConfig.astNode, + extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions), + assumeValid: 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<T: GraphQLType>(type: T): T { + if (isListType(type)) { + // $FlowFixMe[incompatible-return] + return new GraphQLList(replaceType(type.ofType)); + } + if (isNonNullType(type)) { + // $FlowFixMe[incompatible-return] + return new GraphQLNonNull(replaceType(type.ofType)); + } + return replaceNamedType(type); + } + + function replaceNamedType<T: GraphQLNamedType>(type: T): T { + // 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]: any): T); + } + + function replaceDirective(directive: GraphQLDirective): GraphQLDirective { + const config = directive.toConfig(); + return new GraphQLDirective({ + ...config, + args: mapValue(config.args, extendArg), + }); + } + + function extendNamedType(type: GraphQLNamedType): GraphQLNamedType { + 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); + } + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + if (isInputObjectType(type)) { + return extendInputObjectType(type); + } + + // istanbul ignore next (Not reachable. All possible types have been considered) + invariant(false, 'Unexpected type: ' + inspect((type: empty))); + } + + function extendInputObjectType( + type: GraphQLInputObjectType, + ): GraphQLInputObjectType { + const config = type.toConfig(); + const extensions = typeExtensionsMap[config.name] ?? []; + + return new GraphQLInputObjectType({ + ...config, + fields: () => ({ + ...mapValue(config.fields, (field) => ({ + ...field, + type: replaceType(field.type), + })), + ...buildInputFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendEnumType(type: GraphQLEnumType): GraphQLEnumType { + const config = type.toConfig(); + const extensions = typeExtensionsMap[type.name] ?? []; + + return new GraphQLEnumType({ + ...config, + values: { + ...config.values, + ...buildEnumValueMap(extensions), + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendScalarType(type: GraphQLScalarType): GraphQLScalarType { + const config = type.toConfig(); + const extensions = typeExtensionsMap[config.name] ?? []; + + let specifiedByUrl = config.specifiedByUrl; + for (const extensionNode of extensions) { + specifiedByUrl = getSpecifiedByUrl(extensionNode) ?? specifiedByUrl; + } + + return new GraphQLScalarType({ + ...config, + specifiedByUrl, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendObjectType(type: GraphQLObjectType): GraphQLObjectType { + const config = type.toConfig(); + const extensions = typeExtensionsMap[config.name] ?? []; + + 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: GraphQLInterfaceType, + ): GraphQLInterfaceType { + const config = type.toConfig(); + const extensions = typeExtensionsMap[config.name] ?? []; + + 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: GraphQLUnionType): GraphQLUnionType { + const config = type.toConfig(); + const extensions = typeExtensionsMap[config.name] ?? []; + + return new GraphQLUnionType({ + ...config, + types: () => [ + ...type.getTypes().map(replaceNamedType), + ...buildUnionTypes(extensions), + ], + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendField( + field: GraphQLFieldConfig<mixed, mixed>, + ): GraphQLFieldConfig<mixed, mixed> { + return { + ...field, + type: replaceType(field.type), + // $FlowFixMe[incompatible-call] + args: mapValue(field.args, extendArg), + }; + } + + function extendArg(arg: GraphQLArgumentConfig) { + return { + ...arg, + type: replaceType(arg.type), + }; + } + + function getOperationTypes( + nodes: $ReadOnlyArray<SchemaDefinitionNode | SchemaExtensionNode>, + ): {| + query: ?GraphQLObjectType, + mutation: ?GraphQLObjectType, + subscription: ?GraphQLObjectType, + |} { + const opTypes = {}; + for (const node of nodes) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const operationTypesNodes = node.operationTypes ?? []; + + for (const operationType of operationTypesNodes) { + opTypes[operationType.operation] = getNamedType(operationType.type); + } + } + + // 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. + return (opTypes: any); + } + + function getNamedType(node: NamedTypeNode): GraphQLNamedType { + const name = node.name.value; + const type = stdTypeMap[name] ?? typeMap[name]; + + if (type === undefined) { + throw new Error(`Unknown type: "${name}".`); + } + return type; + } + + function getWrappedType(node: TypeNode): GraphQLType { + 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: DirectiveDefinitionNode): GraphQLDirective { + const locations = node.locations.map( + ({ value }) => ((value: any): DirectiveLocationEnum), + ); + + return new GraphQLDirective({ + name: node.name.value, + description: getDescription(node, options), + locations, + isRepeatable: node.repeatable, + args: buildArgumentMap(node.arguments), + astNode: node, + }); + } + + function buildFieldMap( + nodes: $ReadOnlyArray< + | InterfaceTypeDefinitionNode + | InterfaceTypeExtensionNode + | ObjectTypeDefinitionNode + | ObjectTypeExtensionNode, + >, + ): GraphQLFieldConfigMap<mixed, mixed> { + const fieldConfigMap = Object.create(null); + for (const node of nodes) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const nodeFields = node.fields ?? []; + + for (const field of nodeFields) { + 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): any), + description: getDescription(field, options), + args: buildArgumentMap(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + } + return fieldConfigMap; + } + + function buildArgumentMap( + args: ?$ReadOnlyArray<InputValueDefinitionNode>, + ): GraphQLFieldConfigArgumentMap { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const argsNodes = args ?? []; + + const argConfigMap = Object.create(null); + for (const arg of argsNodes) { + // 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: any = getWrappedType(arg.type); + + argConfigMap[arg.name.value] = { + type, + description: getDescription(arg, options), + defaultValue: valueFromAST(arg.defaultValue, type), + deprecationReason: getDeprecationReason(arg), + astNode: arg, + }; + } + return argConfigMap; + } + + function buildInputFieldMap( + nodes: $ReadOnlyArray< + InputObjectTypeDefinitionNode | InputObjectTypeExtensionNode, + >, + ): GraphQLInputFieldConfigMap { + const inputFieldMap = Object.create(null); + for (const node of nodes) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const fieldsNodes = node.fields ?? []; + + for (const field of fieldsNodes) { + // 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: any = getWrappedType(field.type); + + inputFieldMap[field.name.value] = { + type, + description: getDescription(field, options), + defaultValue: valueFromAST(field.defaultValue, type), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + } + return inputFieldMap; + } + + function buildEnumValueMap( + nodes: $ReadOnlyArray<EnumTypeDefinitionNode | EnumTypeExtensionNode>, + ): GraphQLEnumValueConfigMap { + const enumValueMap = Object.create(null); + for (const node of nodes) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const valuesNodes = node.values ?? []; + + for (const value of valuesNodes) { + enumValueMap[value.name.value] = { + description: getDescription(value, options), + deprecationReason: getDeprecationReason(value), + astNode: value, + }; + } + } + return enumValueMap; + } + + function buildInterfaces( + nodes: $ReadOnlyArray< + | InterfaceTypeDefinitionNode + | InterfaceTypeExtensionNode + | ObjectTypeDefinitionNode + | ObjectTypeExtensionNode, + >, + ): Array<GraphQLInterfaceType> { + const interfaces = []; + for (const node of nodes) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const interfacesNodes = node.interfaces ?? []; + + for (const type of interfacesNodes) { + // 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. + interfaces.push((getNamedType(type): any)); + } + } + return interfaces; + } + + function buildUnionTypes( + nodes: $ReadOnlyArray<UnionTypeDefinitionNode | UnionTypeExtensionNode>, + ): Array<GraphQLObjectType> { + const types = []; + for (const node of nodes) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const typeNodes = node.types ?? []; + + for (const type of typeNodes) { + // 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. + types.push((getNamedType(type): any)); + } + } + return types; + } + + function buildType(astNode: TypeDefinitionNode): GraphQLNamedType { + const name = astNode.name.value; + const description = getDescription(astNode, options); + const extensionNodes = typeExtensionsMap[name] ?? []; + + switch (astNode.kind) { + case Kind.OBJECT_TYPE_DEFINITION: { + const extensionASTNodes = (extensionNodes: any); + const allNodes = [astNode, ...extensionASTNodes]; + + return new GraphQLObjectType({ + name, + description, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } + case Kind.INTERFACE_TYPE_DEFINITION: { + const extensionASTNodes = (extensionNodes: any); + const allNodes = [astNode, ...extensionASTNodes]; + + return new GraphQLInterfaceType({ + name, + description, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } + case Kind.ENUM_TYPE_DEFINITION: { + const extensionASTNodes = (extensionNodes: any); + const allNodes = [astNode, ...extensionASTNodes]; + + return new GraphQLEnumType({ + name, + description, + values: buildEnumValueMap(allNodes), + astNode, + extensionASTNodes, + }); + } + case Kind.UNION_TYPE_DEFINITION: { + const extensionASTNodes = (extensionNodes: any); + const allNodes = [astNode, ...extensionASTNodes]; + + return new GraphQLUnionType({ + name, + description, + types: () => buildUnionTypes(allNodes), + astNode, + extensionASTNodes, + }); + } + case Kind.SCALAR_TYPE_DEFINITION: { + const extensionASTNodes = (extensionNodes: any); + + return new GraphQLScalarType({ + name, + description, + specifiedByUrl: getSpecifiedByUrl(astNode), + astNode, + extensionASTNodes, + }); + } + case Kind.INPUT_OBJECT_TYPE_DEFINITION: { + const extensionASTNodes = (extensionNodes: any); + const allNodes = [astNode, ...extensionASTNodes]; + + return new GraphQLInputObjectType({ + name, + description, + fields: () => buildInputFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } + } + + // istanbul ignore next (Not reachable. All possible type definition nodes have been considered) + invariant( + false, + 'Unexpected type definition node: ' + inspect((astNode: empty)), + ); + } +} + +const stdTypeMap = keyMap( + specifiedScalarTypes.concat(introspectionTypes), + (type) => type.name, +); + +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ +function getDeprecationReason( + node: + | EnumValueDefinitionNode + | FieldDefinitionNode + | InputValueDefinitionNode, +): ?string { + const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node); + return (deprecated?.reason: any); +} + +/** + * Given a scalar node, returns the string value for the specifiedByUrl. + */ +function getSpecifiedByUrl( + node: ScalarTypeDefinitionNode | ScalarTypeExtensionNode, +): ?string { + const specifiedBy = getDirectiveValues(GraphQLSpecifiedByDirective, node); + return (specifiedBy?.url: any); +} + +/** + * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function getDescription( + node: { +description?: StringValueNode, +loc?: Location, ... }, + options: ?{ commentDescriptions?: boolean, ... }, +): void | string { + if (node.description) { + return node.description.value; + } + if (options?.commentDescriptions === true) { + const rawValue = getLeadingCommentBlock(node); + if (rawValue !== undefined) { + return dedentBlockStringValue('\n' + rawValue); + } + } +} + +function getLeadingCommentBlock(node): void | string { + const loc = node.loc; + if (!loc) { + return; + } + const comments = []; + let token = loc.startToken.prev; + while ( + token != null && + token.kind === TokenKind.COMMENT && + token.next && + token.prev && + token.line + 1 === token.next.line && + token.line !== token.prev.line + ) { + const value = String(token.value); + comments.push(value); + token = token.prev; + } + return comments.length > 0 ? comments.reverse().join('\n') : undefined; +} diff --git a/school/node_modules/graphql/utilities/extendSchema.mjs b/school/node_modules/graphql/utilities/extendSchema.mjs new file mode 100644 index 0000000..b6ee4c9 --- /dev/null +++ b/school/node_modules/graphql/utilities/extendSchema.mjs @@ -0,0 +1,689 @@ +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +import objectValues from "../polyfills/objectValues.mjs"; +import keyMap from "../jsutils/keyMap.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import mapValue from "../jsutils/mapValue.mjs"; +import invariant from "../jsutils/invariant.mjs"; +import devAssert from "../jsutils/devAssert.mjs"; +import { Kind } from "../language/kinds.mjs"; +import { TokenKind } from "../language/tokenKind.mjs"; +import { dedentBlockStringValue } from "../language/blockString.mjs"; +import { isTypeDefinitionNode, isTypeExtensionNode } from "../language/predicates.mjs"; +import { assertValidSDLExtension } from "../validation/validate.mjs"; +import { getDirectiveValues } from "../execution/values.mjs"; +import { assertSchema, GraphQLSchema } from "../type/schema.mjs"; +import { specifiedScalarTypes, isSpecifiedScalarType } from "../type/scalars.mjs"; +import { introspectionTypes, isIntrospectionType } from "../type/introspection.mjs"; +import { GraphQLDirective, GraphQLDeprecatedDirective, GraphQLSpecifiedByDirective } from "../type/directives.mjs"; +import { isScalarType, isObjectType, isInterfaceType, isUnionType, isListType, isNonNullType, isEnumType, isInputObjectType, GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType } from "../type/definition.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. + * + * Accepts options as a third argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function extendSchema(schema, documentAST, options) { + assertSchema(schema); + documentAST != null && documentAST.kind === Kind.DOCUMENT || devAssert(0, '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); + } + + var schemaConfig = schema.toConfig(); + var 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. + var typeDefs = []; + var 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". + + var directiveDefs = []; + var schemaDef; // Schema extensions are collected which may add additional operation types. + + var schemaExtensions = []; + + for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) { + var def = _documentAST$definiti2[_i2]; + + 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)) { + var extendedTypeName = def.name.value; + var 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; + } + + var typeMap = Object.create(null); + + for (var _i4 = 0, _schemaConfig$types2 = schemaConfig.types; _i4 < _schemaConfig$types2.length; _i4++) { + var existingType = _schemaConfig$types2[_i4]; + typeMap[existingType.name] = extendNamedType(existingType); + } + + for (var _i6 = 0; _i6 < typeDefs.length; _i6++) { + var _stdTypeMap$name; + + var typeNode = typeDefs[_i6]; + var name = typeNode.name.value; + typeMap[name] = (_stdTypeMap$name = stdTypeMap[name]) !== null && _stdTypeMap$name !== void 0 ? _stdTypeMap$name : buildType(typeNode); + } + + var operationTypes = _objectSpread(_objectSpread({ + // Get the extended root operation types. + query: schemaConfig.query && replaceNamedType(schemaConfig.query), + mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation), + subscription: schemaConfig.subscription && replaceNamedType(schemaConfig.subscription) + }, schemaDef && getOperationTypes([schemaDef])), getOperationTypes(schemaExtensions)); // Then produce and return a Schema config with these types. + + + return _objectSpread(_objectSpread({ + 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: objectValues(typeMap), + directives: [].concat(schemaConfig.directives.map(replaceDirective), directiveDefs.map(buildDirective)), + extensions: undefined, + 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)) { + // $FlowFixMe[incompatible-return] + return new GraphQLList(replaceType(type.ofType)); + } + + if (isNonNullType(type)) { + // $FlowFixMe[incompatible-return] + return new GraphQLNonNull(replaceType(type.ofType)); + } + + 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) { + var config = directive.toConfig(); + return new GraphQLDirective(_objectSpread(_objectSpread({}, 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); + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if (isInputObjectType(type)) { + return extendInputObjectType(type); + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || invariant(0, 'Unexpected type: ' + inspect(type)); + } + + function extendInputObjectType(type) { + var _typeExtensionsMap$co; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co !== void 0 ? _typeExtensionsMap$co : []; + return new GraphQLInputObjectType(_objectSpread(_objectSpread({}, config), {}, { + fields: function fields() { + return _objectSpread(_objectSpread({}, mapValue(config.fields, function (field) { + return _objectSpread(_objectSpread({}, field), {}, { + type: replaceType(field.type) + }); + })), buildInputFieldMap(extensions)); + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendEnumType(type) { + var _typeExtensionsMap$ty; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && _typeExtensionsMap$ty !== void 0 ? _typeExtensionsMap$ty : []; + return new GraphQLEnumType(_objectSpread(_objectSpread({}, config), {}, { + values: _objectSpread(_objectSpread({}, config.values), buildEnumValueMap(extensions)), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendScalarType(type) { + var _typeExtensionsMap$co2; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co2 !== void 0 ? _typeExtensionsMap$co2 : []; + var specifiedByUrl = config.specifiedByUrl; + + for (var _i8 = 0; _i8 < extensions.length; _i8++) { + var _getSpecifiedByUrl; + + var extensionNode = extensions[_i8]; + specifiedByUrl = (_getSpecifiedByUrl = getSpecifiedByUrl(extensionNode)) !== null && _getSpecifiedByUrl !== void 0 ? _getSpecifiedByUrl : specifiedByUrl; + } + + return new GraphQLScalarType(_objectSpread(_objectSpread({}, config), {}, { + specifiedByUrl: specifiedByUrl, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendObjectType(type) { + var _typeExtensionsMap$co3; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co3 !== void 0 ? _typeExtensionsMap$co3 : []; + return new GraphQLObjectType(_objectSpread(_objectSpread({}, config), {}, { + interfaces: function interfaces() { + return [].concat(type.getInterfaces().map(replaceNamedType), buildInterfaces(extensions)); + }, + fields: function fields() { + return _objectSpread(_objectSpread({}, mapValue(config.fields, extendField)), buildFieldMap(extensions)); + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendInterfaceType(type) { + var _typeExtensionsMap$co4; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co4 !== void 0 ? _typeExtensionsMap$co4 : []; + return new GraphQLInterfaceType(_objectSpread(_objectSpread({}, config), {}, { + interfaces: function interfaces() { + return [].concat(type.getInterfaces().map(replaceNamedType), buildInterfaces(extensions)); + }, + fields: function fields() { + return _objectSpread(_objectSpread({}, mapValue(config.fields, extendField)), buildFieldMap(extensions)); + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendUnionType(type) { + var _typeExtensionsMap$co5; + + var config = type.toConfig(); + var extensions = (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co5 !== void 0 ? _typeExtensionsMap$co5 : []; + return new GraphQLUnionType(_objectSpread(_objectSpread({}, config), {}, { + types: function types() { + return [].concat(type.getTypes().map(replaceNamedType), buildUnionTypes(extensions)); + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + })); + } + + function extendField(field) { + return _objectSpread(_objectSpread({}, field), {}, { + type: replaceType(field.type), + // $FlowFixMe[incompatible-call] + args: mapValue(field.args, extendArg) + }); + } + + function extendArg(arg) { + return _objectSpread(_objectSpread({}, arg), {}, { + type: replaceType(arg.type) + }); + } + + function getOperationTypes(nodes) { + var opTypes = {}; + + for (var _i10 = 0; _i10 < nodes.length; _i10++) { + var _node$operationTypes; + + var node = nodes[_i10]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; + + for (var _i12 = 0; _i12 < operationTypesNodes.length; _i12++) { + var operationType = operationTypesNodes[_i12]; + opTypes[operationType.operation] = getNamedType(operationType.type); + } + } // 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. + + + return opTypes; + } + + function getNamedType(node) { + var _stdTypeMap$name2; + + var name = node.name.value; + var type = (_stdTypeMap$name2 = stdTypeMap[name]) !== null && _stdTypeMap$name2 !== void 0 ? _stdTypeMap$name2 : typeMap[name]; + + if (type === undefined) { + throw new Error("Unknown type: \"".concat(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 locations = node.locations.map(function (_ref) { + var value = _ref.value; + return value; + }); + return new GraphQLDirective({ + name: node.name.value, + description: getDescription(node, options), + locations: locations, + isRepeatable: node.repeatable, + args: buildArgumentMap(node.arguments), + astNode: node + }); + } + + function buildFieldMap(nodes) { + var fieldConfigMap = Object.create(null); + + for (var _i14 = 0; _i14 < nodes.length; _i14++) { + var _node$fields; + + var node = nodes[_i14]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var nodeFields = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; + + for (var _i16 = 0; _i16 < nodeFields.length; _i16++) { + var field = nodeFields[_i16]; + 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: getDescription(field, options), + args: buildArgumentMap(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + } + } + + return fieldConfigMap; + } + + function buildArgumentMap(args) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var argsNodes = args !== null && args !== void 0 ? args : []; + var argConfigMap = Object.create(null); + + for (var _i18 = 0; _i18 < argsNodes.length; _i18++) { + var arg = argsNodes[_i18]; + // 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. + var type = getWrappedType(arg.type); + argConfigMap[arg.name.value] = { + type: type, + description: getDescription(arg, options), + defaultValue: valueFromAST(arg.defaultValue, type), + deprecationReason: getDeprecationReason(arg), + astNode: arg + }; + } + + return argConfigMap; + } + + function buildInputFieldMap(nodes) { + var inputFieldMap = Object.create(null); + + for (var _i20 = 0; _i20 < nodes.length; _i20++) { + var _node$fields2; + + var node = nodes[_i20]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var fieldsNodes = (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 ? _node$fields2 : []; + + for (var _i22 = 0; _i22 < fieldsNodes.length; _i22++) { + var field = fieldsNodes[_i22]; + // 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. + var type = getWrappedType(field.type); + inputFieldMap[field.name.value] = { + type: type, + description: getDescription(field, options), + defaultValue: valueFromAST(field.defaultValue, type), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + } + } + + return inputFieldMap; + } + + function buildEnumValueMap(nodes) { + var enumValueMap = Object.create(null); + + for (var _i24 = 0; _i24 < nodes.length; _i24++) { + var _node$values; + + var node = nodes[_i24]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var valuesNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; + + for (var _i26 = 0; _i26 < valuesNodes.length; _i26++) { + var value = valuesNodes[_i26]; + enumValueMap[value.name.value] = { + description: getDescription(value, options), + deprecationReason: getDeprecationReason(value), + astNode: value + }; + } + } + + return enumValueMap; + } + + function buildInterfaces(nodes) { + var interfaces = []; + + for (var _i28 = 0; _i28 < nodes.length; _i28++) { + var _node$interfaces; + + var node = nodes[_i28]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var interfacesNodes = (_node$interfaces = node.interfaces) !== null && _node$interfaces !== void 0 ? _node$interfaces : []; + + for (var _i30 = 0; _i30 < interfacesNodes.length; _i30++) { + var type = interfacesNodes[_i30]; + // 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. + interfaces.push(getNamedType(type)); + } + } + + return interfaces; + } + + function buildUnionTypes(nodes) { + var types = []; + + for (var _i32 = 0; _i32 < nodes.length; _i32++) { + var _node$types; + + var node = nodes[_i32]; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var typeNodes = (_node$types = node.types) !== null && _node$types !== void 0 ? _node$types : []; + + for (var _i34 = 0; _i34 < typeNodes.length; _i34++) { + var type = typeNodes[_i34]; + // 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. + types.push(getNamedType(type)); + } + } + + return types; + } + + function buildType(astNode) { + var _typeExtensionsMap$na; + + var name = astNode.name.value; + var description = getDescription(astNode, options); + var extensionNodes = (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && _typeExtensionsMap$na !== void 0 ? _typeExtensionsMap$na : []; + + switch (astNode.kind) { + case Kind.OBJECT_TYPE_DEFINITION: + { + var extensionASTNodes = extensionNodes; + var allNodes = [astNode].concat(extensionASTNodes); + return new GraphQLObjectType({ + name: name, + description: description, + interfaces: function interfaces() { + return buildInterfaces(allNodes); + }, + fields: function fields() { + return buildFieldMap(allNodes); + }, + astNode: astNode, + extensionASTNodes: extensionASTNodes + }); + } + + case Kind.INTERFACE_TYPE_DEFINITION: + { + var _extensionASTNodes = extensionNodes; + + var _allNodes = [astNode].concat(_extensionASTNodes); + + return new GraphQLInterfaceType({ + name: name, + description: description, + interfaces: function interfaces() { + return buildInterfaces(_allNodes); + }, + fields: function fields() { + return buildFieldMap(_allNodes); + }, + astNode: astNode, + extensionASTNodes: _extensionASTNodes + }); + } + + case Kind.ENUM_TYPE_DEFINITION: + { + var _extensionASTNodes2 = extensionNodes; + + var _allNodes2 = [astNode].concat(_extensionASTNodes2); + + return new GraphQLEnumType({ + name: name, + description: description, + values: buildEnumValueMap(_allNodes2), + astNode: astNode, + extensionASTNodes: _extensionASTNodes2 + }); + } + + case Kind.UNION_TYPE_DEFINITION: + { + var _extensionASTNodes3 = extensionNodes; + + var _allNodes3 = [astNode].concat(_extensionASTNodes3); + + return new GraphQLUnionType({ + name: name, + description: description, + types: function types() { + return buildUnionTypes(_allNodes3); + }, + astNode: astNode, + extensionASTNodes: _extensionASTNodes3 + }); + } + + case Kind.SCALAR_TYPE_DEFINITION: + { + var _extensionASTNodes4 = extensionNodes; + return new GraphQLScalarType({ + name: name, + description: description, + specifiedByUrl: getSpecifiedByUrl(astNode), + astNode: astNode, + extensionASTNodes: _extensionASTNodes4 + }); + } + + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + { + var _extensionASTNodes5 = extensionNodes; + + var _allNodes4 = [astNode].concat(_extensionASTNodes5); + + return new GraphQLInputObjectType({ + name: name, + description: description, + fields: function fields() { + return buildInputFieldMap(_allNodes4); + }, + astNode: astNode, + extensionASTNodes: _extensionASTNodes5 + }); + } + } // istanbul ignore next (Not reachable. All possible type definition nodes have been considered) + + + false || invariant(0, 'Unexpected type definition node: ' + inspect(astNode)); + } +} +var stdTypeMap = keyMap(specifiedScalarTypes.concat(introspectionTypes), function (type) { + return type.name; +}); +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ + +function getDeprecationReason(node) { + var deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node); + return deprecated === null || deprecated === void 0 ? void 0 : deprecated.reason; +} +/** + * Given a scalar node, returns the string value for the specifiedByUrl. + */ + + +function getSpecifiedByUrl(node) { + var specifiedBy = getDirectiveValues(GraphQLSpecifiedByDirective, node); + return specifiedBy === null || specifiedBy === void 0 ? void 0 : specifiedBy.url; +} +/** + * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ + + +export function getDescription(node, options) { + if (node.description) { + return node.description.value; + } + + if ((options === null || options === void 0 ? void 0 : options.commentDescriptions) === true) { + var rawValue = getLeadingCommentBlock(node); + + if (rawValue !== undefined) { + return dedentBlockStringValue('\n' + rawValue); + } + } +} + +function getLeadingCommentBlock(node) { + var loc = node.loc; + + if (!loc) { + return; + } + + var comments = []; + var token = loc.startToken.prev; + + while (token != null && token.kind === TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) { + var value = String(token.value); + comments.push(value); + token = token.prev; + } + + return comments.length > 0 ? comments.reverse().join('\n') : undefined; +} diff --git a/school/node_modules/graphql/utilities/findBreakingChanges.d.ts b/school/node_modules/graphql/utilities/findBreakingChanges.d.ts new file mode 100644 index 0000000..df35805 --- /dev/null +++ b/school/node_modules/graphql/utilities/findBreakingChanges.d.ts @@ -0,0 +1,57 @@ +import { GraphQLSchema } from '../type/schema'; + +export const 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 const 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 interface BreakingChange { + type: keyof typeof BreakingChangeType; + description: string; +} + +export interface DangerousChange { + type: keyof typeof 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 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 function findDangerousChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array<DangerousChange>; diff --git a/school/node_modules/graphql/utilities/findBreakingChanges.js b/school/node_modules/graphql/utilities/findBreakingChanges.js new file mode 100644 index 0000000..699c88f --- /dev/null +++ b/school/node_modules/graphql/utilities/findBreakingChanges.js @@ -0,0 +1,522 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findBreakingChanges = findBreakingChanges; +exports.findDangerousChanges = findDangerousChanges; +exports.DangerousChangeType = exports.BreakingChangeType = void 0; + +var _objectValues = _interopRequireDefault(require("../polyfills/objectValues.js")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _naturalCompare = _interopRequireDefault(require("../jsutils/naturalCompare.js")); + +var _printer = require("../language/printer.js"); + +var _visitor = require("../language/visitor.js"); + +var _scalars = require("../type/scalars.js"); + +var _definition = require("../type/definition.js"); + +var _astFromValue = require("./astFromValue.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var BreakingChangeType = Object.freeze({ + 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' +}); +exports.BreakingChangeType = BreakingChangeType; +var DangerousChangeType = Object.freeze({ + 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' +}); +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) { + var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) { + return change.type in BreakingChangeType; + }); + return breakingChanges; +} +/** + * 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) { + var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) { + return change.type in DangerousChangeType; + }); + return dangerousChanges; +} + +function findSchemaChanges(oldSchema, newSchema) { + return [].concat(findTypeChanges(oldSchema, newSchema), findDirectiveChanges(oldSchema, newSchema)); +} + +function findDirectiveChanges(oldSchema, newSchema) { + var schemaChanges = []; + var directivesDiff = diff(oldSchema.getDirectives(), newSchema.getDirectives()); + + for (var _i2 = 0, _directivesDiff$remov2 = directivesDiff.removed; _i2 < _directivesDiff$remov2.length; _i2++) { + var oldDirective = _directivesDiff$remov2[_i2]; + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: "".concat(oldDirective.name, " was removed.") + }); + } + + for (var _i4 = 0, _directivesDiff$persi2 = directivesDiff.persisted; _i4 < _directivesDiff$persi2.length; _i4++) { + var _ref2 = _directivesDiff$persi2[_i4]; + var _oldDirective = _ref2[0]; + var newDirective = _ref2[1]; + var argsDiff = diff(_oldDirective.args, newDirective.args); + + for (var _i6 = 0, _argsDiff$added2 = argsDiff.added; _i6 < _argsDiff$added2.length; _i6++) { + var newArg = _argsDiff$added2[_i6]; + + if ((0, _definition.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: "A required arg ".concat(newArg.name, " on directive ").concat(_oldDirective.name, " was added.") + }); + } + } + + for (var _i8 = 0, _argsDiff$removed2 = argsDiff.removed; _i8 < _argsDiff$removed2.length; _i8++) { + var oldArg = _argsDiff$removed2[_i8]; + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: "".concat(oldArg.name, " was removed from ").concat(_oldDirective.name, ".") + }); + } + + if (_oldDirective.isRepeatable && !newDirective.isRepeatable) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, + description: "Repeatable flag was removed from ".concat(_oldDirective.name, ".") + }); + } + + for (var _i10 = 0, _oldDirective$locatio2 = _oldDirective.locations; _i10 < _oldDirective$locatio2.length; _i10++) { + var location = _oldDirective$locatio2[_i10]; + + if (newDirective.locations.indexOf(location) === -1) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: "".concat(location, " was removed from ").concat(_oldDirective.name, ".") + }); + } + } + } + + return schemaChanges; +} + +function findTypeChanges(oldSchema, newSchema) { + var schemaChanges = []; + var typesDiff = diff((0, _objectValues.default)(oldSchema.getTypeMap()), (0, _objectValues.default)(newSchema.getTypeMap())); + + for (var _i12 = 0, _typesDiff$removed2 = typesDiff.removed; _i12 < _typesDiff$removed2.length; _i12++) { + var oldType = _typesDiff$removed2[_i12]; + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: (0, _scalars.isSpecifiedScalarType)(oldType) ? "Standard scalar ".concat(oldType.name, " was removed because it is not referenced anymore.") : "".concat(oldType.name, " was removed.") + }); + } + + for (var _i14 = 0, _typesDiff$persisted2 = typesDiff.persisted; _i14 < _typesDiff$persisted2.length; _i14++) { + var _ref4 = _typesDiff$persisted2[_i14]; + var _oldType = _ref4[0]; + var newType = _ref4[1]; + + if ((0, _definition.isEnumType)(_oldType) && (0, _definition.isEnumType)(newType)) { + schemaChanges.push.apply(schemaChanges, findEnumTypeChanges(_oldType, newType)); + } else if ((0, _definition.isUnionType)(_oldType) && (0, _definition.isUnionType)(newType)) { + schemaChanges.push.apply(schemaChanges, findUnionTypeChanges(_oldType, newType)); + } else if ((0, _definition.isInputObjectType)(_oldType) && (0, _definition.isInputObjectType)(newType)) { + schemaChanges.push.apply(schemaChanges, findInputObjectTypeChanges(_oldType, newType)); + } else if ((0, _definition.isObjectType)(_oldType) && (0, _definition.isObjectType)(newType)) { + schemaChanges.push.apply(schemaChanges, findFieldChanges(_oldType, newType).concat(findImplementedInterfacesChanges(_oldType, newType))); + } else if ((0, _definition.isInterfaceType)(_oldType) && (0, _definition.isInterfaceType)(newType)) { + schemaChanges.push.apply(schemaChanges, findFieldChanges(_oldType, newType).concat(findImplementedInterfacesChanges(_oldType, newType))); + } else if (_oldType.constructor !== newType.constructor) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: "".concat(_oldType.name, " changed from ") + "".concat(typeKindName(_oldType), " to ").concat(typeKindName(newType), ".") + }); + } + } + + return schemaChanges; +} + +function findInputObjectTypeChanges(oldType, newType) { + var schemaChanges = []; + var fieldsDiff = diff((0, _objectValues.default)(oldType.getFields()), (0, _objectValues.default)(newType.getFields())); + + for (var _i16 = 0, _fieldsDiff$added2 = fieldsDiff.added; _i16 < _fieldsDiff$added2.length; _i16++) { + var newField = _fieldsDiff$added2[_i16]; + + if ((0, _definition.isRequiredInputField)(newField)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: "A required field ".concat(newField.name, " on input type ").concat(oldType.name, " was added.") + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: "An optional field ".concat(newField.name, " on input type ").concat(oldType.name, " was added.") + }); + } + } + + for (var _i18 = 0, _fieldsDiff$removed2 = fieldsDiff.removed; _i18 < _fieldsDiff$removed2.length; _i18++) { + var oldField = _fieldsDiff$removed2[_i18]; + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(oldType.name, ".").concat(oldField.name, " was removed.") + }); + } + + for (var _i20 = 0, _fieldsDiff$persisted2 = fieldsDiff.persisted; _i20 < _fieldsDiff$persisted2.length; _i20++) { + var _ref6 = _fieldsDiff$persisted2[_i20]; + var _oldField = _ref6[0]; + var _newField = _ref6[1]; + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(_oldField.type, _newField.type); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(oldType.name, ".").concat(_oldField.name, " changed type from ") + "".concat(String(_oldField.type), " to ").concat(String(_newField.type), ".") + }); + } + } + + return schemaChanges; +} + +function findUnionTypeChanges(oldType, newType) { + var schemaChanges = []; + var possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes()); + + for (var _i22 = 0, _possibleTypesDiff$ad2 = possibleTypesDiff.added; _i22 < _possibleTypesDiff$ad2.length; _i22++) { + var newPossibleType = _possibleTypesDiff$ad2[_i22]; + schemaChanges.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: "".concat(newPossibleType.name, " was added to union type ").concat(oldType.name, ".") + }); + } + + for (var _i24 = 0, _possibleTypesDiff$re2 = possibleTypesDiff.removed; _i24 < _possibleTypesDiff$re2.length; _i24++) { + var oldPossibleType = _possibleTypesDiff$re2[_i24]; + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: "".concat(oldPossibleType.name, " was removed from union type ").concat(oldType.name, ".") + }); + } + + return schemaChanges; +} + +function findEnumTypeChanges(oldType, newType) { + var schemaChanges = []; + var valuesDiff = diff(oldType.getValues(), newType.getValues()); + + for (var _i26 = 0, _valuesDiff$added2 = valuesDiff.added; _i26 < _valuesDiff$added2.length; _i26++) { + var newValue = _valuesDiff$added2[_i26]; + schemaChanges.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: "".concat(newValue.name, " was added to enum type ").concat(oldType.name, ".") + }); + } + + for (var _i28 = 0, _valuesDiff$removed2 = valuesDiff.removed; _i28 < _valuesDiff$removed2.length; _i28++) { + var oldValue = _valuesDiff$removed2[_i28]; + schemaChanges.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: "".concat(oldValue.name, " was removed from enum type ").concat(oldType.name, ".") + }); + } + + return schemaChanges; +} + +function findImplementedInterfacesChanges(oldType, newType) { + var schemaChanges = []; + var interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces()); + + for (var _i30 = 0, _interfacesDiff$added2 = interfacesDiff.added; _i30 < _interfacesDiff$added2.length; _i30++) { + var newInterface = _interfacesDiff$added2[_i30]; + schemaChanges.push({ + type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, + description: "".concat(newInterface.name, " added to interfaces implemented by ").concat(oldType.name, ".") + }); + } + + for (var _i32 = 0, _interfacesDiff$remov2 = interfacesDiff.removed; _i32 < _interfacesDiff$remov2.length; _i32++) { + var oldInterface = _interfacesDiff$remov2[_i32]; + schemaChanges.push({ + type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, + description: "".concat(oldType.name, " no longer implements interface ").concat(oldInterface.name, ".") + }); + } + + return schemaChanges; +} + +function findFieldChanges(oldType, newType) { + var schemaChanges = []; + var fieldsDiff = diff((0, _objectValues.default)(oldType.getFields()), (0, _objectValues.default)(newType.getFields())); + + for (var _i34 = 0, _fieldsDiff$removed4 = fieldsDiff.removed; _i34 < _fieldsDiff$removed4.length; _i34++) { + var oldField = _fieldsDiff$removed4[_i34]; + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(oldType.name, ".").concat(oldField.name, " was removed.") + }); + } + + for (var _i36 = 0, _fieldsDiff$persisted4 = fieldsDiff.persisted; _i36 < _fieldsDiff$persisted4.length; _i36++) { + var _ref8 = _fieldsDiff$persisted4[_i36]; + var _oldField2 = _ref8[0]; + var newField = _ref8[1]; + schemaChanges.push.apply(schemaChanges, findArgChanges(oldType, _oldField2, newField)); + var isSafe = isChangeSafeForObjectOrInterfaceField(_oldField2.type, newField.type); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(oldType.name, ".").concat(_oldField2.name, " changed type from ") + "".concat(String(_oldField2.type), " to ").concat(String(newField.type), ".") + }); + } + } + + return schemaChanges; +} + +function findArgChanges(oldType, oldField, newField) { + var schemaChanges = []; + var argsDiff = diff(oldField.args, newField.args); + + for (var _i38 = 0, _argsDiff$removed4 = argsDiff.removed; _i38 < _argsDiff$removed4.length; _i38++) { + var oldArg = _argsDiff$removed4[_i38]; + schemaChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(oldArg.name, " was removed.") + }); + } + + for (var _i40 = 0, _argsDiff$persisted2 = argsDiff.persisted; _i40 < _argsDiff$persisted2.length; _i40++) { + var _ref10 = _argsDiff$persisted2[_i40]; + var _oldArg = _ref10[0]; + var newArg = _ref10[1]; + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(_oldArg.type, newArg.type); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_oldArg.name, " has changed type from ") + "".concat(String(_oldArg.type), " to ").concat(String(newArg.type), ".") + }); + } else if (_oldArg.defaultValue !== undefined) { + if (newArg.defaultValue === undefined) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_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. + var oldValueStr = stringifyValue(_oldArg.defaultValue, _oldArg.type); + var newValueStr = stringifyValue(newArg.defaultValue, newArg.type); + + if (oldValueStr !== newValueStr) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_oldArg.name, " has changed defaultValue from ").concat(oldValueStr, " to ").concat(newValueStr, ".") + }); + } + } + } + } + + for (var _i42 = 0, _argsDiff$added4 = argsDiff.added; _i42 < _argsDiff$added4.length; _i42++) { + var _newArg = _argsDiff$added4[_i42]; + + if ((0, _definition.isRequiredArgument)(_newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: "A required arg ".concat(_newArg.name, " on ").concat(oldType.name, ".").concat(oldField.name, " was added.") + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: "An optional arg ".concat(_newArg.name, " on ").concat(oldType.name, ".").concat(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'; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if ((0, _definition.isInputObjectType)(type)) { + return 'an Input type'; + } // istanbul ignore next (Not reachable. All possible named types have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected type: ' + (0, _inspect.default)(type)); +} + +function stringifyValue(value, type) { + var ast = (0, _astFromValue.astFromValue)(value, type); + ast != null || (0, _invariant.default)(0); + var sortedAST = (0, _visitor.visit)(ast, { + ObjectValue: function ObjectValue(objectNode) { + // Make a copy since sort mutates array + var fields = [].concat(objectNode.fields); + fields.sort(function (fieldA, fieldB) { + return (0, _naturalCompare.default)(fieldA.name.value, fieldB.name.value); + }); + return _objectSpread(_objectSpread({}, objectNode), {}, { + fields: fields + }); + } + }); + return (0, _printer.print)(sortedAST); +} + +function diff(oldArray, newArray) { + var added = []; + var removed = []; + var persisted = []; + var oldMap = (0, _keyMap.default)(oldArray, function (_ref11) { + var name = _ref11.name; + return name; + }); + var newMap = (0, _keyMap.default)(newArray, function (_ref12) { + var name = _ref12.name; + return name; + }); + + for (var _i44 = 0; _i44 < oldArray.length; _i44++) { + var oldItem = oldArray[_i44]; + var newItem = newMap[oldItem.name]; + + if (newItem === undefined) { + removed.push(oldItem); + } else { + persisted.push([oldItem, newItem]); + } + } + + for (var _i46 = 0; _i46 < newArray.length; _i46++) { + var _newItem = newArray[_i46]; + + if (oldMap[_newItem.name] === undefined) { + added.push(_newItem); + } + } + + return { + added: added, + persisted: persisted, + removed: removed + }; +} diff --git a/school/node_modules/graphql/utilities/findBreakingChanges.js.flow b/school/node_modules/graphql/utilities/findBreakingChanges.js.flow new file mode 100644 index 0000000..673b2e8 --- /dev/null +++ b/school/node_modules/graphql/utilities/findBreakingChanges.js.flow @@ -0,0 +1,590 @@ +// @flow strict +import objectValues from '../polyfills/objectValues'; + +import keyMap from '../jsutils/keyMap'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import naturalCompare from '../jsutils/naturalCompare'; + +import { print } from '../language/printer'; +import { visit } from '../language/visitor'; + +import type { GraphQLSchema } from '../type/schema'; +import type { + GraphQLField, + GraphQLType, + GraphQLInputType, + GraphQLNamedType, + GraphQLEnumType, + GraphQLUnionType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLInputObjectType, +} from '../type/definition'; +import { isSpecifiedScalarType } from '../type/scalars'; +import { + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isNonNullType, + isListType, + isNamedType, + isRequiredArgument, + isRequiredInputField, +} from '../type/definition'; + +import { astFromValue } from './astFromValue'; + +export const BreakingChangeType = Object.freeze({ + 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 const DangerousChangeType = Object.freeze({ + 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 type BreakingChange = {| + type: $Keys<typeof BreakingChangeType>, + description: string, +|}; + +export type DangerousChange = {| + type: $Keys<typeof 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 function findBreakingChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array<BreakingChange> { + const breakingChanges = findSchemaChanges(oldSchema, newSchema).filter( + (change) => change.type in BreakingChangeType, + ); + return ((breakingChanges: any): 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 function findDangerousChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array<DangerousChange> { + const dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter( + (change) => change.type in DangerousChangeType, + ); + return ((dangerousChanges: any): Array<DangerousChange>); +} + +function findSchemaChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array<BreakingChange | DangerousChange> { + return [ + ...findTypeChanges(oldSchema, newSchema), + ...findDirectiveChanges(oldSchema, newSchema), + ]; +} + +function findDirectiveChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array<BreakingChange | DangerousChange> { + 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.indexOf(location) === -1) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: `${location} was removed from ${oldDirective.name}.`, + }); + } + } + } + + return schemaChanges; +} + +function findTypeChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array<BreakingChange | DangerousChange> { + const schemaChanges = []; + + const typesDiff = diff( + objectValues(oldSchema.getTypeMap()), + objectValues(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: GraphQLInputObjectType, + newType: GraphQLInputObjectType, +): Array<BreakingChange | DangerousChange> { + const schemaChanges = []; + const fieldsDiff = diff( + objectValues(oldType.getFields()), + objectValues(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: GraphQLUnionType, + newType: GraphQLUnionType, +): Array<BreakingChange | DangerousChange> { + 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: GraphQLEnumType, + newType: GraphQLEnumType, +): Array<BreakingChange | DangerousChange> { + 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: GraphQLObjectType | GraphQLInterfaceType, + newType: GraphQLObjectType | GraphQLInterfaceType, +): Array<BreakingChange | DangerousChange> { + 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: GraphQLObjectType | GraphQLInterfaceType, + newType: GraphQLObjectType | GraphQLInterfaceType, +): Array<BreakingChange | DangerousChange> { + const schemaChanges = []; + const fieldsDiff = diff( + objectValues(oldType.getFields()), + objectValues(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: GraphQLObjectType | GraphQLInterfaceType, + oldField: GraphQLField<mixed, mixed>, + newField: GraphQLField<mixed, mixed>, +): Array<BreakingChange | DangerousChange> { + 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: GraphQLType, + newType: GraphQLType, +): boolean { + 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: GraphQLType, + newType: GraphQLType, +): boolean { + 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: GraphQLNamedType): string { + 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'; + } + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + if (isInputObjectType(type)) { + return 'an Input type'; + } + + // istanbul ignore next (Not reachable. All possible named types have been considered) + invariant(false, 'Unexpected type: ' + inspect((type: empty))); +} + +function stringifyValue(value: mixed, type: GraphQLInputType): string { + const ast = astFromValue(value, type); + invariant(ast != null); + + const sortedAST = visit(ast, { + ObjectValue(objectNode) { + // Make a copy since sort mutates array + const fields = [...objectNode.fields]; + + fields.sort((fieldA, fieldB) => + naturalCompare(fieldA.name.value, fieldB.name.value), + ); + return { ...objectNode, fields }; + }, + }); + + return print(sortedAST); +} + +function diff<T: { name: string, ... }>( + oldArray: $ReadOnlyArray<T>, + newArray: $ReadOnlyArray<T>, +): {| + added: Array<T>, + removed: Array<T>, + persisted: Array<[T, T]>, +|} { + 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 }; +} diff --git a/school/node_modules/graphql/utilities/findBreakingChanges.mjs b/school/node_modules/graphql/utilities/findBreakingChanges.mjs new file mode 100644 index 0000000..52e5804 --- /dev/null +++ b/school/node_modules/graphql/utilities/findBreakingChanges.mjs @@ -0,0 +1,498 @@ +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +import objectValues from "../polyfills/objectValues.mjs"; +import keyMap from "../jsutils/keyMap.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import invariant from "../jsutils/invariant.mjs"; +import naturalCompare from "../jsutils/naturalCompare.mjs"; +import { print } from "../language/printer.mjs"; +import { visit } from "../language/visitor.mjs"; +import { isSpecifiedScalarType } from "../type/scalars.mjs"; +import { isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isNonNullType, isListType, isNamedType, isRequiredArgument, isRequiredInputField } from "../type/definition.mjs"; +import { astFromValue } from "./astFromValue.mjs"; +export var BreakingChangeType = Object.freeze({ + 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 var DangerousChangeType = Object.freeze({ + 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' +}); + +/** + * 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) { + var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) { + return change.type in BreakingChangeType; + }); + return breakingChanges; +} +/** + * 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) { + var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) { + return change.type in DangerousChangeType; + }); + return dangerousChanges; +} + +function findSchemaChanges(oldSchema, newSchema) { + return [].concat(findTypeChanges(oldSchema, newSchema), findDirectiveChanges(oldSchema, newSchema)); +} + +function findDirectiveChanges(oldSchema, newSchema) { + var schemaChanges = []; + var directivesDiff = diff(oldSchema.getDirectives(), newSchema.getDirectives()); + + for (var _i2 = 0, _directivesDiff$remov2 = directivesDiff.removed; _i2 < _directivesDiff$remov2.length; _i2++) { + var oldDirective = _directivesDiff$remov2[_i2]; + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: "".concat(oldDirective.name, " was removed.") + }); + } + + for (var _i4 = 0, _directivesDiff$persi2 = directivesDiff.persisted; _i4 < _directivesDiff$persi2.length; _i4++) { + var _ref2 = _directivesDiff$persi2[_i4]; + var _oldDirective = _ref2[0]; + var newDirective = _ref2[1]; + var argsDiff = diff(_oldDirective.args, newDirective.args); + + for (var _i6 = 0, _argsDiff$added2 = argsDiff.added; _i6 < _argsDiff$added2.length; _i6++) { + var newArg = _argsDiff$added2[_i6]; + + if (isRequiredArgument(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: "A required arg ".concat(newArg.name, " on directive ").concat(_oldDirective.name, " was added.") + }); + } + } + + for (var _i8 = 0, _argsDiff$removed2 = argsDiff.removed; _i8 < _argsDiff$removed2.length; _i8++) { + var oldArg = _argsDiff$removed2[_i8]; + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: "".concat(oldArg.name, " was removed from ").concat(_oldDirective.name, ".") + }); + } + + if (_oldDirective.isRepeatable && !newDirective.isRepeatable) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, + description: "Repeatable flag was removed from ".concat(_oldDirective.name, ".") + }); + } + + for (var _i10 = 0, _oldDirective$locatio2 = _oldDirective.locations; _i10 < _oldDirective$locatio2.length; _i10++) { + var location = _oldDirective$locatio2[_i10]; + + if (newDirective.locations.indexOf(location) === -1) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: "".concat(location, " was removed from ").concat(_oldDirective.name, ".") + }); + } + } + } + + return schemaChanges; +} + +function findTypeChanges(oldSchema, newSchema) { + var schemaChanges = []; + var typesDiff = diff(objectValues(oldSchema.getTypeMap()), objectValues(newSchema.getTypeMap())); + + for (var _i12 = 0, _typesDiff$removed2 = typesDiff.removed; _i12 < _typesDiff$removed2.length; _i12++) { + var oldType = _typesDiff$removed2[_i12]; + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: isSpecifiedScalarType(oldType) ? "Standard scalar ".concat(oldType.name, " was removed because it is not referenced anymore.") : "".concat(oldType.name, " was removed.") + }); + } + + for (var _i14 = 0, _typesDiff$persisted2 = typesDiff.persisted; _i14 < _typesDiff$persisted2.length; _i14++) { + var _ref4 = _typesDiff$persisted2[_i14]; + var _oldType = _ref4[0]; + var newType = _ref4[1]; + + if (isEnumType(_oldType) && isEnumType(newType)) { + schemaChanges.push.apply(schemaChanges, findEnumTypeChanges(_oldType, newType)); + } else if (isUnionType(_oldType) && isUnionType(newType)) { + schemaChanges.push.apply(schemaChanges, findUnionTypeChanges(_oldType, newType)); + } else if (isInputObjectType(_oldType) && isInputObjectType(newType)) { + schemaChanges.push.apply(schemaChanges, findInputObjectTypeChanges(_oldType, newType)); + } else if (isObjectType(_oldType) && isObjectType(newType)) { + schemaChanges.push.apply(schemaChanges, findFieldChanges(_oldType, newType).concat(findImplementedInterfacesChanges(_oldType, newType))); + } else if (isInterfaceType(_oldType) && isInterfaceType(newType)) { + schemaChanges.push.apply(schemaChanges, findFieldChanges(_oldType, newType).concat(findImplementedInterfacesChanges(_oldType, newType))); + } else if (_oldType.constructor !== newType.constructor) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: "".concat(_oldType.name, " changed from ") + "".concat(typeKindName(_oldType), " to ").concat(typeKindName(newType), ".") + }); + } + } + + return schemaChanges; +} + +function findInputObjectTypeChanges(oldType, newType) { + var schemaChanges = []; + var fieldsDiff = diff(objectValues(oldType.getFields()), objectValues(newType.getFields())); + + for (var _i16 = 0, _fieldsDiff$added2 = fieldsDiff.added; _i16 < _fieldsDiff$added2.length; _i16++) { + var newField = _fieldsDiff$added2[_i16]; + + if (isRequiredInputField(newField)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: "A required field ".concat(newField.name, " on input type ").concat(oldType.name, " was added.") + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: "An optional field ".concat(newField.name, " on input type ").concat(oldType.name, " was added.") + }); + } + } + + for (var _i18 = 0, _fieldsDiff$removed2 = fieldsDiff.removed; _i18 < _fieldsDiff$removed2.length; _i18++) { + var oldField = _fieldsDiff$removed2[_i18]; + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(oldType.name, ".").concat(oldField.name, " was removed.") + }); + } + + for (var _i20 = 0, _fieldsDiff$persisted2 = fieldsDiff.persisted; _i20 < _fieldsDiff$persisted2.length; _i20++) { + var _ref6 = _fieldsDiff$persisted2[_i20]; + var _oldField = _ref6[0]; + var _newField = _ref6[1]; + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(_oldField.type, _newField.type); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(oldType.name, ".").concat(_oldField.name, " changed type from ") + "".concat(String(_oldField.type), " to ").concat(String(_newField.type), ".") + }); + } + } + + return schemaChanges; +} + +function findUnionTypeChanges(oldType, newType) { + var schemaChanges = []; + var possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes()); + + for (var _i22 = 0, _possibleTypesDiff$ad2 = possibleTypesDiff.added; _i22 < _possibleTypesDiff$ad2.length; _i22++) { + var newPossibleType = _possibleTypesDiff$ad2[_i22]; + schemaChanges.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: "".concat(newPossibleType.name, " was added to union type ").concat(oldType.name, ".") + }); + } + + for (var _i24 = 0, _possibleTypesDiff$re2 = possibleTypesDiff.removed; _i24 < _possibleTypesDiff$re2.length; _i24++) { + var oldPossibleType = _possibleTypesDiff$re2[_i24]; + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: "".concat(oldPossibleType.name, " was removed from union type ").concat(oldType.name, ".") + }); + } + + return schemaChanges; +} + +function findEnumTypeChanges(oldType, newType) { + var schemaChanges = []; + var valuesDiff = diff(oldType.getValues(), newType.getValues()); + + for (var _i26 = 0, _valuesDiff$added2 = valuesDiff.added; _i26 < _valuesDiff$added2.length; _i26++) { + var newValue = _valuesDiff$added2[_i26]; + schemaChanges.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: "".concat(newValue.name, " was added to enum type ").concat(oldType.name, ".") + }); + } + + for (var _i28 = 0, _valuesDiff$removed2 = valuesDiff.removed; _i28 < _valuesDiff$removed2.length; _i28++) { + var oldValue = _valuesDiff$removed2[_i28]; + schemaChanges.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: "".concat(oldValue.name, " was removed from enum type ").concat(oldType.name, ".") + }); + } + + return schemaChanges; +} + +function findImplementedInterfacesChanges(oldType, newType) { + var schemaChanges = []; + var interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces()); + + for (var _i30 = 0, _interfacesDiff$added2 = interfacesDiff.added; _i30 < _interfacesDiff$added2.length; _i30++) { + var newInterface = _interfacesDiff$added2[_i30]; + schemaChanges.push({ + type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, + description: "".concat(newInterface.name, " added to interfaces implemented by ").concat(oldType.name, ".") + }); + } + + for (var _i32 = 0, _interfacesDiff$remov2 = interfacesDiff.removed; _i32 < _interfacesDiff$remov2.length; _i32++) { + var oldInterface = _interfacesDiff$remov2[_i32]; + schemaChanges.push({ + type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, + description: "".concat(oldType.name, " no longer implements interface ").concat(oldInterface.name, ".") + }); + } + + return schemaChanges; +} + +function findFieldChanges(oldType, newType) { + var schemaChanges = []; + var fieldsDiff = diff(objectValues(oldType.getFields()), objectValues(newType.getFields())); + + for (var _i34 = 0, _fieldsDiff$removed4 = fieldsDiff.removed; _i34 < _fieldsDiff$removed4.length; _i34++) { + var oldField = _fieldsDiff$removed4[_i34]; + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(oldType.name, ".").concat(oldField.name, " was removed.") + }); + } + + for (var _i36 = 0, _fieldsDiff$persisted4 = fieldsDiff.persisted; _i36 < _fieldsDiff$persisted4.length; _i36++) { + var _ref8 = _fieldsDiff$persisted4[_i36]; + var _oldField2 = _ref8[0]; + var newField = _ref8[1]; + schemaChanges.push.apply(schemaChanges, findArgChanges(oldType, _oldField2, newField)); + var isSafe = isChangeSafeForObjectOrInterfaceField(_oldField2.type, newField.type); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(oldType.name, ".").concat(_oldField2.name, " changed type from ") + "".concat(String(_oldField2.type), " to ").concat(String(newField.type), ".") + }); + } + } + + return schemaChanges; +} + +function findArgChanges(oldType, oldField, newField) { + var schemaChanges = []; + var argsDiff = diff(oldField.args, newField.args); + + for (var _i38 = 0, _argsDiff$removed4 = argsDiff.removed; _i38 < _argsDiff$removed4.length; _i38++) { + var oldArg = _argsDiff$removed4[_i38]; + schemaChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(oldArg.name, " was removed.") + }); + } + + for (var _i40 = 0, _argsDiff$persisted2 = argsDiff.persisted; _i40 < _argsDiff$persisted2.length; _i40++) { + var _ref10 = _argsDiff$persisted2[_i40]; + var _oldArg = _ref10[0]; + var newArg = _ref10[1]; + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(_oldArg.type, newArg.type); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_oldArg.name, " has changed type from ") + "".concat(String(_oldArg.type), " to ").concat(String(newArg.type), ".") + }); + } else if (_oldArg.defaultValue !== undefined) { + if (newArg.defaultValue === undefined) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_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. + var oldValueStr = stringifyValue(_oldArg.defaultValue, _oldArg.type); + var newValueStr = stringifyValue(newArg.defaultValue, newArg.type); + + if (oldValueStr !== newValueStr) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_oldArg.name, " has changed defaultValue from ").concat(oldValueStr, " to ").concat(newValueStr, ".") + }); + } + } + } + } + + for (var _i42 = 0, _argsDiff$added4 = argsDiff.added; _i42 < _argsDiff$added4.length; _i42++) { + var _newArg = _argsDiff$added4[_i42]; + + if (isRequiredArgument(_newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: "A required arg ".concat(_newArg.name, " on ").concat(oldType.name, ".").concat(oldField.name, " was added.") + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: "An optional arg ".concat(_newArg.name, " on ").concat(oldType.name, ".").concat(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'; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if (isInputObjectType(type)) { + return 'an Input type'; + } // istanbul ignore next (Not reachable. All possible named types have been considered) + + + false || invariant(0, 'Unexpected type: ' + inspect(type)); +} + +function stringifyValue(value, type) { + var ast = astFromValue(value, type); + ast != null || invariant(0); + var sortedAST = visit(ast, { + ObjectValue: function ObjectValue(objectNode) { + // Make a copy since sort mutates array + var fields = [].concat(objectNode.fields); + fields.sort(function (fieldA, fieldB) { + return naturalCompare(fieldA.name.value, fieldB.name.value); + }); + return _objectSpread(_objectSpread({}, objectNode), {}, { + fields: fields + }); + } + }); + return print(sortedAST); +} + +function diff(oldArray, newArray) { + var added = []; + var removed = []; + var persisted = []; + var oldMap = keyMap(oldArray, function (_ref11) { + var name = _ref11.name; + return name; + }); + var newMap = keyMap(newArray, function (_ref12) { + var name = _ref12.name; + return name; + }); + + for (var _i44 = 0; _i44 < oldArray.length; _i44++) { + var oldItem = oldArray[_i44]; + var newItem = newMap[oldItem.name]; + + if (newItem === undefined) { + removed.push(oldItem); + } else { + persisted.push([oldItem, newItem]); + } + } + + for (var _i46 = 0; _i46 < newArray.length; _i46++) { + var _newItem = newArray[_i46]; + + if (oldMap[_newItem.name] === undefined) { + added.push(_newItem); + } + } + + return { + added: added, + persisted: persisted, + removed: removed + }; +} diff --git a/school/node_modules/graphql/utilities/findDeprecatedUsages.d.ts b/school/node_modules/graphql/utilities/findDeprecatedUsages.d.ts new file mode 100644 index 0000000..bbdf943 --- /dev/null +++ b/school/node_modules/graphql/utilities/findDeprecatedUsages.d.ts @@ -0,0 +1,21 @@ +import { GraphQLError } from '../error/GraphQLError'; +import { DocumentNode } from '../language/ast'; +import { GraphQLSchema } from '../type/schema'; + +/** + * A validation rule which reports deprecated usages. + * + * Returns a list of GraphQLError instances describing each deprecated use. + * + * @deprecated Please use `validate` with `NoDeprecatedCustomRule` instead: + * + * ``` + * import { validate, NoDeprecatedCustomRule } from 'graphql' + * + * const errors = validate(schema, document, [NoDeprecatedCustomRule]) + * ``` + */ +export function findDeprecatedUsages( + schema: GraphQLSchema, + ast: DocumentNode, +): ReadonlyArray<GraphQLError>; diff --git a/school/node_modules/graphql/utilities/findDeprecatedUsages.js b/school/node_modules/graphql/utilities/findDeprecatedUsages.js new file mode 100644 index 0000000..e27b03e --- /dev/null +++ b/school/node_modules/graphql/utilities/findDeprecatedUsages.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findDeprecatedUsages = findDeprecatedUsages; + +var _validate = require("../validation/validate.js"); + +var _NoDeprecatedCustomRule = require("../validation/rules/custom/NoDeprecatedCustomRule.js"); + +/** + * A validation rule which reports deprecated usages. + * + * Returns a list of GraphQLError instances describing each deprecated use. + * + * @deprecated Please use `validate` with `NoDeprecatedCustomRule` instead: + * + * ``` + * import { validate, NoDeprecatedCustomRule } from 'graphql' + * + * const errors = validate(schema, document, [NoDeprecatedCustomRule]) + * ``` + */ +function findDeprecatedUsages(schema, ast) { + return (0, _validate.validate)(schema, ast, [_NoDeprecatedCustomRule.NoDeprecatedCustomRule]); +} diff --git a/school/node_modules/graphql/utilities/findDeprecatedUsages.js.flow b/school/node_modules/graphql/utilities/findDeprecatedUsages.js.flow new file mode 100644 index 0000000..5db22f0 --- /dev/null +++ b/school/node_modules/graphql/utilities/findDeprecatedUsages.js.flow @@ -0,0 +1,29 @@ +// @flow strict +import type { GraphQLError } from '../error/GraphQLError'; + +import type { DocumentNode } from '../language/ast'; + +import type { GraphQLSchema } from '../type/schema'; + +import { validate } from '../validation/validate'; +import { NoDeprecatedCustomRule } from '../validation/rules/custom/NoDeprecatedCustomRule'; + +/** + * A validation rule which reports deprecated usages. + * + * Returns a list of GraphQLError instances describing each deprecated use. + * + * @deprecated Please use `validate` with `NoDeprecatedCustomRule` instead: + * + * ``` + * import { validate, NoDeprecatedCustomRule } from 'graphql' + * + * const errors = validate(schema, document, [NoDeprecatedCustomRule]) + * ``` + */ +export function findDeprecatedUsages( + schema: GraphQLSchema, + ast: DocumentNode, +): $ReadOnlyArray<GraphQLError> { + return validate(schema, ast, [NoDeprecatedCustomRule]); +} diff --git a/school/node_modules/graphql/utilities/findDeprecatedUsages.mjs b/school/node_modules/graphql/utilities/findDeprecatedUsages.mjs new file mode 100644 index 0000000..7a85004 --- /dev/null +++ b/school/node_modules/graphql/utilities/findDeprecatedUsages.mjs @@ -0,0 +1,19 @@ +import { validate } from "../validation/validate.mjs"; +import { NoDeprecatedCustomRule } from "../validation/rules/custom/NoDeprecatedCustomRule.mjs"; +/** + * A validation rule which reports deprecated usages. + * + * Returns a list of GraphQLError instances describing each deprecated use. + * + * @deprecated Please use `validate` with `NoDeprecatedCustomRule` instead: + * + * ``` + * import { validate, NoDeprecatedCustomRule } from 'graphql' + * + * const errors = validate(schema, document, [NoDeprecatedCustomRule]) + * ``` + */ + +export function findDeprecatedUsages(schema, ast) { + return validate(schema, ast, [NoDeprecatedCustomRule]); +} diff --git a/school/node_modules/graphql/utilities/getIntrospectionQuery.d.ts b/school/node_modules/graphql/utilities/getIntrospectionQuery.d.ts new file mode 100644 index 0000000..6e5fad1 --- /dev/null +++ b/school/node_modules/graphql/utilities/getIntrospectionQuery.d.ts @@ -0,0 +1,193 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { DirectiveLocationEnum } 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; +} + +export function getIntrospectionQuery(options?: IntrospectionOptions): string; + +export interface IntrospectionQuery { + readonly __schema: IntrospectionSchema; +} + +export interface IntrospectionSchema { + readonly queryType: IntrospectionNamedTypeRef<IntrospectionObjectType>; + readonly mutationType: Maybe< + IntrospectionNamedTypeRef<IntrospectionObjectType> + >; + readonly subscriptionType: Maybe< + IntrospectionNamedTypeRef<IntrospectionObjectType> + >; + readonly types: ReadonlyArray<IntrospectionType>; + readonly directives: ReadonlyArray<IntrospectionDirective>; +} + +export type IntrospectionType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType + | IntrospectionInputObjectType; + +export type IntrospectionOutputType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType; + +export 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 type IntrospectionTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef<any> + | IntrospectionNonNullTypeRef< + IntrospectionNamedTypeRef | IntrospectionListTypeRef<any> + >; + +export type IntrospectionOutputTypeRef = + | IntrospectionNamedTypeRef<IntrospectionOutputType> + | IntrospectionListTypeRef<any> + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef<IntrospectionOutputType> + | IntrospectionListTypeRef<any> + >; + +export type IntrospectionInputTypeRef = + | IntrospectionNamedTypeRef<IntrospectionInputType> + | IntrospectionListTypeRef<any> + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef<IntrospectionInputType> + | IntrospectionListTypeRef<any> + >; + +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<DirectiveLocationEnum>; + readonly args: ReadonlyArray<IntrospectionInputValue>; +} diff --git a/school/node_modules/graphql/utilities/getIntrospectionQuery.js b/school/node_modules/graphql/utilities/getIntrospectionQuery.js new file mode 100644 index 0000000..aac7994 --- /dev/null +++ b/school/node_modules/graphql/utilities/getIntrospectionQuery.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getIntrospectionQuery = getIntrospectionQuery; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function getIntrospectionQuery(options) { + var optionsWithDefault = _objectSpread({ + descriptions: true, + specifiedByUrl: false, + directiveIsRepeatable: false, + schemaDescription: false, + inputValueDeprecation: false + }, options); + + var descriptions = optionsWithDefault.descriptions ? 'description' : ''; + var specifiedByUrl = optionsWithDefault.specifiedByUrl ? 'specifiedByUrl' : ''; + var directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable ? 'isRepeatable' : ''; + var schemaDescription = optionsWithDefault.schemaDescription ? descriptions : ''; + + function inputDeprecation(str) { + return optionsWithDefault.inputValueDeprecation ? str : ''; + } + + return "\n query IntrospectionQuery {\n __schema {\n ".concat(schemaDescription, "\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ").concat(descriptions, "\n ").concat(directiveIsRepeatable, "\n locations\n args").concat(inputDeprecation('(includeDeprecated: true)'), " {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions, "\n ").concat(specifiedByUrl, "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions, "\n args").concat(inputDeprecation('(includeDeprecated: true)'), " {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields").concat(inputDeprecation('(includeDeprecated: true)'), " {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions, "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions, "\n type { ...TypeRef }\n defaultValue\n ").concat(inputDeprecation('isDeprecated'), "\n ").concat(inputDeprecation('deprecationReason'), "\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n "); +} diff --git a/school/node_modules/graphql/utilities/getIntrospectionQuery.js.flow b/school/node_modules/graphql/utilities/getIntrospectionQuery.js.flow new file mode 100644 index 0000000..db72ed4 --- /dev/null +++ b/school/node_modules/graphql/utilities/getIntrospectionQuery.js.flow @@ -0,0 +1,312 @@ +// @flow strict +import type { DirectiveLocationEnum } from '../language/directiveLocation'; + +export type 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` field 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, +|}; + +export function getIntrospectionQuery(options?: IntrospectionOptions): string { + 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 + } + } + } + } + } + } + } + } + `; +} + +export type IntrospectionQuery = {| + +__schema: IntrospectionSchema, +|}; + +export type IntrospectionSchema = {| + +description?: ?string, + +queryType: IntrospectionNamedTypeRef<IntrospectionObjectType>, + +mutationType: ?IntrospectionNamedTypeRef<IntrospectionObjectType>, + +subscriptionType: ?IntrospectionNamedTypeRef<IntrospectionObjectType>, + +types: $ReadOnlyArray<IntrospectionType>, + +directives: $ReadOnlyArray<IntrospectionDirective>, +|}; + +export type IntrospectionType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType + | IntrospectionInputObjectType; + +export type IntrospectionOutputType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType; + +export type IntrospectionInputType = + | IntrospectionScalarType + | IntrospectionEnumType + | IntrospectionInputObjectType; + +export type IntrospectionScalarType = {| + +kind: 'SCALAR', + +name: string, + +description?: ?string, + +specifiedByUrl?: ?string, +|}; + +export type IntrospectionObjectType = {| + +kind: 'OBJECT', + +name: string, + +description?: ?string, + +fields: $ReadOnlyArray<IntrospectionField>, + +interfaces: $ReadOnlyArray< + IntrospectionNamedTypeRef<IntrospectionInterfaceType>, + >, +|}; + +export type IntrospectionInterfaceType = {| + +kind: 'INTERFACE', + +name: string, + +description?: ?string, + +fields: $ReadOnlyArray<IntrospectionField>, + +interfaces: $ReadOnlyArray< + IntrospectionNamedTypeRef<IntrospectionInterfaceType>, + >, + +possibleTypes: $ReadOnlyArray< + IntrospectionNamedTypeRef<IntrospectionObjectType>, + >, +|}; + +export type IntrospectionUnionType = {| + +kind: 'UNION', + +name: string, + +description?: ?string, + +possibleTypes: $ReadOnlyArray< + IntrospectionNamedTypeRef<IntrospectionObjectType>, + >, +|}; + +export type IntrospectionEnumType = {| + +kind: 'ENUM', + +name: string, + +description?: ?string, + +enumValues: $ReadOnlyArray<IntrospectionEnumValue>, +|}; + +export type IntrospectionInputObjectType = {| + +kind: 'INPUT_OBJECT', + +name: string, + +description?: ?string, + +inputFields: $ReadOnlyArray<IntrospectionInputValue>, +|}; + +export type IntrospectionListTypeRef< + T: IntrospectionTypeRef = IntrospectionTypeRef, +> = {| + +kind: 'LIST', + +ofType: T, +|}; + +export type IntrospectionNonNullTypeRef< + T: IntrospectionTypeRef = IntrospectionTypeRef, +> = {| + +kind: 'NON_NULL', + +ofType: T, +|}; + +export type IntrospectionTypeRef = + | IntrospectionNamedTypeRef<> + | IntrospectionListTypeRef<> + | IntrospectionNonNullTypeRef< + IntrospectionNamedTypeRef<> | IntrospectionListTypeRef<>, + >; + +export type IntrospectionOutputTypeRef = + | IntrospectionNamedTypeRef<IntrospectionOutputType> + | IntrospectionListTypeRef<IntrospectionOutputTypeRef> + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef<IntrospectionOutputType> + | IntrospectionListTypeRef<IntrospectionOutputTypeRef>, + >; + +export type IntrospectionInputTypeRef = + | IntrospectionNamedTypeRef<IntrospectionInputType> + | IntrospectionListTypeRef<IntrospectionInputTypeRef> + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef<IntrospectionInputType> + | IntrospectionListTypeRef<IntrospectionInputTypeRef>, + >; + +export type IntrospectionNamedTypeRef< + T: IntrospectionType = IntrospectionType, +> = {| + +kind: $PropertyType<T, 'kind'>, + +name: string, +|}; + +export type IntrospectionField = {| + +name: string, + +description?: ?string, + +args: $ReadOnlyArray<IntrospectionInputValue>, + +type: IntrospectionOutputTypeRef, + +isDeprecated: boolean, + +deprecationReason: ?string, +|}; + +export type IntrospectionInputValue = {| + +name: string, + +description?: ?string, + +type: IntrospectionInputTypeRef, + +defaultValue: ?string, + +isDeprecated?: boolean, + +deprecationReason?: ?string, +|}; + +export type IntrospectionEnumValue = {| + +name: string, + +description?: ?string, + +isDeprecated: boolean, + +deprecationReason: ?string, +|}; + +export type IntrospectionDirective = {| + +name: string, + +description?: ?string, + +isRepeatable?: boolean, + +locations: $ReadOnlyArray<DirectiveLocationEnum>, + +args: $ReadOnlyArray<IntrospectionInputValue>, +|}; diff --git a/school/node_modules/graphql/utilities/getIntrospectionQuery.mjs b/school/node_modules/graphql/utilities/getIntrospectionQuery.mjs new file mode 100644 index 0000000..3951060 --- /dev/null +++ b/school/node_modules/graphql/utilities/getIntrospectionQuery.mjs @@ -0,0 +1,26 @@ +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +export function getIntrospectionQuery(options) { + var optionsWithDefault = _objectSpread({ + descriptions: true, + specifiedByUrl: false, + directiveIsRepeatable: false, + schemaDescription: false, + inputValueDeprecation: false + }, options); + + var descriptions = optionsWithDefault.descriptions ? 'description' : ''; + var specifiedByUrl = optionsWithDefault.specifiedByUrl ? 'specifiedByUrl' : ''; + var directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable ? 'isRepeatable' : ''; + var schemaDescription = optionsWithDefault.schemaDescription ? descriptions : ''; + + function inputDeprecation(str) { + return optionsWithDefault.inputValueDeprecation ? str : ''; + } + + return "\n query IntrospectionQuery {\n __schema {\n ".concat(schemaDescription, "\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ").concat(descriptions, "\n ").concat(directiveIsRepeatable, "\n locations\n args").concat(inputDeprecation('(includeDeprecated: true)'), " {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions, "\n ").concat(specifiedByUrl, "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions, "\n args").concat(inputDeprecation('(includeDeprecated: true)'), " {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields").concat(inputDeprecation('(includeDeprecated: true)'), " {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions, "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions, "\n type { ...TypeRef }\n defaultValue\n ").concat(inputDeprecation('isDeprecated'), "\n ").concat(inputDeprecation('deprecationReason'), "\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n "); +} diff --git a/school/node_modules/graphql/utilities/getOperationAST.d.ts b/school/node_modules/graphql/utilities/getOperationAST.d.ts new file mode 100644 index 0000000..d17a9b4 --- /dev/null +++ b/school/node_modules/graphql/utilities/getOperationAST.d.ts @@ -0,0 +1,13 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { 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 function getOperationAST( + documentAST: DocumentNode, + operationName?: Maybe<string>, +): Maybe<OperationDefinitionNode>; diff --git a/school/node_modules/graphql/utilities/getOperationAST.js b/school/node_modules/graphql/utilities/getOperationAST.js new file mode 100644 index 0000000..976879c --- /dev/null +++ b/school/node_modules/graphql/utilities/getOperationAST.js @@ -0,0 +1,40 @@ +"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) { + var operation = null; + + for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) { + var definition = _documentAST$definiti2[_i2]; + + 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; +} diff --git a/school/node_modules/graphql/utilities/getOperationAST.js.flow b/school/node_modules/graphql/utilities/getOperationAST.js.flow new file mode 100644 index 0000000..eaee0b0 --- /dev/null +++ b/school/node_modules/graphql/utilities/getOperationAST.js.flow @@ -0,0 +1,31 @@ +// @flow strict +import type { DocumentNode, OperationDefinitionNode } from '../language/ast'; +import { Kind } from '../language/kinds'; + +/** + * 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: DocumentNode, + operationName?: ?string, +): ?OperationDefinitionNode { + let operation = null; + for (const definition of documentAST.definitions) { + if (definition.kind === Kind.OPERATION_DEFINITION) { + 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?.value === operationName) { + return definition; + } + } + } + return operation; +} diff --git a/school/node_modules/graphql/utilities/getOperationAST.mjs b/school/node_modules/graphql/utilities/getOperationAST.mjs new file mode 100644 index 0000000..ce72191 --- /dev/null +++ b/school/node_modules/graphql/utilities/getOperationAST.mjs @@ -0,0 +1,33 @@ +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) { + var operation = null; + + for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) { + var definition = _documentAST$definiti2[_i2]; + + 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; +} diff --git a/school/node_modules/graphql/utilities/getOperationRootType.d.ts b/school/node_modules/graphql/utilities/getOperationRootType.d.ts new file mode 100644 index 0000000..5adc59c --- /dev/null +++ b/school/node_modules/graphql/utilities/getOperationRootType.d.ts @@ -0,0 +1,14 @@ +import { + OperationDefinitionNode, + OperationTypeDefinitionNode, +} from '../language/ast'; +import { GraphQLSchema } from '../type/schema'; +import { GraphQLObjectType } from '../type/definition'; + +/** + * Extracts the root type of the operation from the schema. + */ +export function getOperationRootType( + schema: GraphQLSchema, + operation: OperationDefinitionNode | OperationTypeDefinitionNode, +): GraphQLObjectType; diff --git a/school/node_modules/graphql/utilities/getOperationRootType.js b/school/node_modules/graphql/utilities/getOperationRootType.js new file mode 100644 index 0000000..f179fc3 --- /dev/null +++ b/school/node_modules/graphql/utilities/getOperationRootType.js @@ -0,0 +1,45 @@ +"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. + */ +function getOperationRootType(schema, operation) { + if (operation.operation === 'query') { + var queryType = schema.getQueryType(); + + if (!queryType) { + throw new _GraphQLError.GraphQLError('Schema does not define the required query root type.', operation); + } + + return queryType; + } + + if (operation.operation === 'mutation') { + var mutationType = schema.getMutationType(); + + if (!mutationType) { + throw new _GraphQLError.GraphQLError('Schema is not configured for mutations.', operation); + } + + return mutationType; + } + + if (operation.operation === 'subscription') { + var subscriptionType = schema.getSubscriptionType(); + + if (!subscriptionType) { + throw new _GraphQLError.GraphQLError('Schema is not configured for subscriptions.', operation); + } + + return subscriptionType; + } + + throw new _GraphQLError.GraphQLError('Can only have query, mutation and subscription operations.', operation); +} diff --git a/school/node_modules/graphql/utilities/getOperationRootType.js.flow b/school/node_modules/graphql/utilities/getOperationRootType.js.flow new file mode 100644 index 0000000..5358be4 --- /dev/null +++ b/school/node_modules/graphql/utilities/getOperationRootType.js.flow @@ -0,0 +1,56 @@ +// @flow strict +import { GraphQLError } from '../error/GraphQLError'; + +import type { + OperationDefinitionNode, + OperationTypeDefinitionNode, +} from '../language/ast'; + +import type { GraphQLSchema } from '../type/schema'; +import type { GraphQLObjectType } from '../type/definition'; + +/** + * Extracts the root type of the operation from the schema. + */ +export function getOperationRootType( + schema: GraphQLSchema, + operation: OperationDefinitionNode | OperationTypeDefinitionNode, +): GraphQLObjectType { + if (operation.operation === 'query') { + const queryType = schema.getQueryType(); + if (!queryType) { + throw new GraphQLError( + 'Schema does not define the required query root type.', + operation, + ); + } + return queryType; + } + + if (operation.operation === 'mutation') { + const mutationType = schema.getMutationType(); + if (!mutationType) { + throw new GraphQLError( + 'Schema is not configured for mutations.', + operation, + ); + } + return mutationType; + } + + if (operation.operation === 'subscription') { + const subscriptionType = schema.getSubscriptionType(); + if (!subscriptionType) { + throw new GraphQLError( + 'Schema is not configured for subscriptions.', + operation, + ); + } + return subscriptionType; + } + + throw new GraphQLError( + 'Can only have query, mutation and subscription operations.', + operation, + ); +} diff --git a/school/node_modules/graphql/utilities/getOperationRootType.mjs b/school/node_modules/graphql/utilities/getOperationRootType.mjs new file mode 100644 index 0000000..e0b75d7 --- /dev/null +++ b/school/node_modules/graphql/utilities/getOperationRootType.mjs @@ -0,0 +1,38 @@ +import { GraphQLError } from "../error/GraphQLError.mjs"; + +/** + * Extracts the root type of the operation from the schema. + */ +export function getOperationRootType(schema, operation) { + if (operation.operation === 'query') { + var queryType = schema.getQueryType(); + + if (!queryType) { + throw new GraphQLError('Schema does not define the required query root type.', operation); + } + + return queryType; + } + + if (operation.operation === 'mutation') { + var mutationType = schema.getMutationType(); + + if (!mutationType) { + throw new GraphQLError('Schema is not configured for mutations.', operation); + } + + return mutationType; + } + + if (operation.operation === 'subscription') { + var subscriptionType = schema.getSubscriptionType(); + + if (!subscriptionType) { + throw new GraphQLError('Schema is not configured for subscriptions.', operation); + } + + return subscriptionType; + } + + throw new GraphQLError('Can only have query, mutation and subscription operations.', operation); +} diff --git a/school/node_modules/graphql/utilities/index.d.ts b/school/node_modules/graphql/utilities/index.d.ts new file mode 100644 index 0000000..a8019f9 --- /dev/null +++ b/school/node_modules/graphql/utilities/index.d.ts @@ -0,0 +1,119 @@ +export { + // Produce the GraphQL query recommended for a full schema introspection. + // Accepts optional IntrospectionOptions. + getIntrospectionQuery, + IntrospectionOptions, + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionInputType, + IntrospectionOutputType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionInputTypeRef, + IntrospectionOutputTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, +} from './getIntrospectionQuery'; + +// Gets the target Operation from a Document +export { getOperationAST } from './getOperationAST'; + +// Gets the Type for the target Operation AST. +export { getOperationRootType } from './getOperationRootType'; + +// Convert a GraphQLSchema to an IntrospectionQuery +export { introspectionFromSchema } from './introspectionFromSchema'; + +// Build a GraphQLSchema from an introspection result. +export { buildClientSchema } from './buildClientSchema'; + +// Build a GraphQLSchema from GraphQL Schema language. +export { + buildASTSchema, + buildSchema, + BuildSchemaOptions, +} from './buildASTSchema'; + +// Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. +export { + extendSchema, + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16 + getDescription, +} from './extendSchema'; + +// Sort a GraphQLSchema. +export { lexicographicSortSchema } from './lexicographicSortSchema'; + +// Print a GraphQLSchema to GraphQL Schema language. +export { + printSchema, + printType, + printIntrospectionSchema, +} from './printSchema'; + +// Create a GraphQLType from a GraphQL language AST. +export { typeFromAST } from './typeFromAST'; + +// Create a JavaScript value from a GraphQL language AST with a type. +export { valueFromAST } from './valueFromAST'; + +// Create a JavaScript value from a GraphQL language AST without a type. +export { valueFromASTUntyped } from './valueFromASTUntyped'; + +// Create a GraphQL language AST from a JavaScript value. +export { astFromValue } from './astFromValue'; + +// A helper to use within recursive-descent visitors which need to be aware of +// the GraphQL type system. +export { TypeInfo, visitWithTypeInfo } from './TypeInfo'; + +// Coerces a JavaScript value to a GraphQL type, or produces errors. +export { coerceInputValue } from './coerceInputValue'; + +// Concatenates multiple AST together. +export { concatAST } from './concatAST'; + +// Separates an AST into an AST per Operation. +export { separateOperations } from './separateOperations'; + +// Strips characters that are not significant to the validity or execution +// of a GraphQL document. +export { stripIgnoredCharacters } from './stripIgnoredCharacters'; + +// Comparators for types +export { + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, +} from './typeComparators'; + +// Asserts that a string is a valid GraphQL name +export { assertValidName, isValidNameError } from './assertValidName'; + +// Compares two GraphQLSchemas and detects breaking changes. +export { + BreakingChangeType, + DangerousChangeType, + findBreakingChanges, + findDangerousChanges, + BreakingChange, + DangerousChange, +} from './findBreakingChanges'; + +// Wrapper type that contains DocumentNode and types that can be deduced from it. +export { TypedQueryDocumentNode } from './typedQueryDocumentNode'; + +// @deprecated: Report all deprecated usage within a GraphQL document. +export { findDeprecatedUsages } from './findDeprecatedUsages'; diff --git a/school/node_modules/graphql/utilities/index.js b/school/node_modules/graphql/utilities/index.js new file mode 100644 index 0000000..086e5f3 --- /dev/null +++ b/school/node_modules/graphql/utilities/index.js @@ -0,0 +1,247 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getIntrospectionQuery", { + enumerable: true, + get: function get() { + return _getIntrospectionQuery.getIntrospectionQuery; + } +}); +Object.defineProperty(exports, "getOperationAST", { + enumerable: true, + get: function get() { + return _getOperationAST.getOperationAST; + } +}); +Object.defineProperty(exports, "getOperationRootType", { + enumerable: true, + get: function get() { + return _getOperationRootType.getOperationRootType; + } +}); +Object.defineProperty(exports, "introspectionFromSchema", { + enumerable: true, + get: function get() { + return _introspectionFromSchema.introspectionFromSchema; + } +}); +Object.defineProperty(exports, "buildClientSchema", { + enumerable: true, + get: function get() { + return _buildClientSchema.buildClientSchema; + } +}); +Object.defineProperty(exports, "buildASTSchema", { + enumerable: true, + get: function get() { + return _buildASTSchema.buildASTSchema; + } +}); +Object.defineProperty(exports, "buildSchema", { + enumerable: true, + get: function get() { + return _buildASTSchema.buildSchema; + } +}); +Object.defineProperty(exports, "extendSchema", { + enumerable: true, + get: function get() { + return _extendSchema.extendSchema; + } +}); +Object.defineProperty(exports, "getDescription", { + enumerable: true, + get: function get() { + return _extendSchema.getDescription; + } +}); +Object.defineProperty(exports, "lexicographicSortSchema", { + enumerable: true, + get: function get() { + return _lexicographicSortSchema.lexicographicSortSchema; + } +}); +Object.defineProperty(exports, "printSchema", { + enumerable: true, + get: function get() { + return _printSchema.printSchema; + } +}); +Object.defineProperty(exports, "printType", { + enumerable: true, + get: function get() { + return _printSchema.printType; + } +}); +Object.defineProperty(exports, "printIntrospectionSchema", { + enumerable: true, + get: function get() { + return _printSchema.printIntrospectionSchema; + } +}); +Object.defineProperty(exports, "typeFromAST", { + enumerable: true, + get: function get() { + return _typeFromAST.typeFromAST; + } +}); +Object.defineProperty(exports, "valueFromAST", { + enumerable: true, + get: function get() { + return _valueFromAST.valueFromAST; + } +}); +Object.defineProperty(exports, "valueFromASTUntyped", { + enumerable: true, + get: function get() { + return _valueFromASTUntyped.valueFromASTUntyped; + } +}); +Object.defineProperty(exports, "astFromValue", { + enumerable: true, + get: function get() { + return _astFromValue.astFromValue; + } +}); +Object.defineProperty(exports, "TypeInfo", { + enumerable: true, + get: function get() { + return _TypeInfo.TypeInfo; + } +}); +Object.defineProperty(exports, "visitWithTypeInfo", { + enumerable: true, + get: function get() { + return _TypeInfo.visitWithTypeInfo; + } +}); +Object.defineProperty(exports, "coerceInputValue", { + enumerable: true, + get: function get() { + return _coerceInputValue.coerceInputValue; + } +}); +Object.defineProperty(exports, "concatAST", { + enumerable: true, + get: function get() { + return _concatAST.concatAST; + } +}); +Object.defineProperty(exports, "separateOperations", { + enumerable: true, + get: function get() { + return _separateOperations.separateOperations; + } +}); +Object.defineProperty(exports, "stripIgnoredCharacters", { + enumerable: true, + get: function get() { + return _stripIgnoredCharacters.stripIgnoredCharacters; + } +}); +Object.defineProperty(exports, "isEqualType", { + enumerable: true, + get: function get() { + return _typeComparators.isEqualType; + } +}); +Object.defineProperty(exports, "isTypeSubTypeOf", { + enumerable: true, + get: function get() { + return _typeComparators.isTypeSubTypeOf; + } +}); +Object.defineProperty(exports, "doTypesOverlap", { + enumerable: true, + get: function get() { + return _typeComparators.doTypesOverlap; + } +}); +Object.defineProperty(exports, "assertValidName", { + enumerable: true, + get: function get() { + return _assertValidName.assertValidName; + } +}); +Object.defineProperty(exports, "isValidNameError", { + enumerable: true, + get: function get() { + return _assertValidName.isValidNameError; + } +}); +Object.defineProperty(exports, "BreakingChangeType", { + enumerable: true, + get: function get() { + return _findBreakingChanges.BreakingChangeType; + } +}); +Object.defineProperty(exports, "DangerousChangeType", { + enumerable: true, + get: function get() { + return _findBreakingChanges.DangerousChangeType; + } +}); +Object.defineProperty(exports, "findBreakingChanges", { + enumerable: true, + get: function get() { + return _findBreakingChanges.findBreakingChanges; + } +}); +Object.defineProperty(exports, "findDangerousChanges", { + enumerable: true, + get: function get() { + return _findBreakingChanges.findDangerousChanges; + } +}); +Object.defineProperty(exports, "findDeprecatedUsages", { + enumerable: true, + get: function get() { + return _findDeprecatedUsages.findDeprecatedUsages; + } +}); + +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"); + +var _findDeprecatedUsages = require("./findDeprecatedUsages.js"); diff --git a/school/node_modules/graphql/utilities/index.js.flow b/school/node_modules/graphql/utilities/index.js.flow new file mode 100644 index 0000000..96564b7 --- /dev/null +++ b/school/node_modules/graphql/utilities/index.js.flow @@ -0,0 +1,114 @@ +// @flow strict +// Produce the GraphQL query recommended for a full schema introspection. +// Accepts optional IntrospectionOptions. +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'; + +// Gets the target Operation from a Document. +export { getOperationAST } from './getOperationAST'; + +// Gets the Type for the target Operation AST. +export { getOperationRootType } from './getOperationRootType'; + +// Convert a GraphQLSchema to an IntrospectionQuery. +export { introspectionFromSchema } from './introspectionFromSchema'; + +// Build a GraphQLSchema from an introspection result. +export { buildClientSchema } from './buildClientSchema'; + +// Build a GraphQLSchema from GraphQL Schema language. +export { buildASTSchema, buildSchema } from './buildASTSchema'; +export type { BuildSchemaOptions } from './buildASTSchema'; + +// Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. +export { + extendSchema, + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16. + getDescription, +} from './extendSchema'; + +// Sort a GraphQLSchema. +export { lexicographicSortSchema } from './lexicographicSortSchema'; + +// Print a GraphQLSchema to GraphQL Schema language. +export { + printSchema, + printType, + printIntrospectionSchema, +} from './printSchema'; + +// Create a GraphQLType from a GraphQL language AST. +export { typeFromAST } from './typeFromAST'; + +// Create a JavaScript value from a GraphQL language AST with a type. +export { valueFromAST } from './valueFromAST'; + +// Create a JavaScript value from a GraphQL language AST without a type. +export { valueFromASTUntyped } from './valueFromASTUntyped'; + +// Create a GraphQL language AST from a JavaScript value. +export { astFromValue } from './astFromValue'; + +// A helper to use within recursive-descent visitors which need to be aware of +// the GraphQL type system. +export { TypeInfo, visitWithTypeInfo } from './TypeInfo'; + +// Coerces a JavaScript value to a GraphQL type, or produces errors. +export { coerceInputValue } from './coerceInputValue'; + +// Concatenates multiple AST together. +export { concatAST } from './concatAST'; + +// Separates an AST into an AST per Operation. +export { separateOperations } from './separateOperations'; + +// Strips characters that are not significant to the validity or execution +// of a GraphQL document. +export { stripIgnoredCharacters } from './stripIgnoredCharacters'; + +// Comparators for types +export { + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, +} from './typeComparators'; + +// Asserts that a string is a valid GraphQL name +export { assertValidName, isValidNameError } from './assertValidName'; + +// Compares two GraphQLSchemas and detects breaking changes. +export { + BreakingChangeType, + DangerousChangeType, + findBreakingChanges, + findDangerousChanges, +} from './findBreakingChanges'; +export type { BreakingChange, DangerousChange } from './findBreakingChanges'; + +// @deprecated: Report all deprecated usage within a GraphQL document. +export { findDeprecatedUsages } from './findDeprecatedUsages'; diff --git a/school/node_modules/graphql/utilities/index.mjs b/school/node_modules/graphql/utilities/index.mjs new file mode 100644 index 0000000..68868fe --- /dev/null +++ b/school/node_modules/graphql/utilities/index.mjs @@ -0,0 +1,49 @@ +// Produce the GraphQL query recommended for a full schema introspection. +// Accepts optional IntrospectionOptions. +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 // @deprecated: Get the description from a schema AST node and supports legacy +// syntax for specifying descriptions - will be removed in v16. +, getDescription } 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"; +// @deprecated: Report all deprecated usage within a GraphQL document. +export { findDeprecatedUsages } from "./findDeprecatedUsages.mjs"; diff --git a/school/node_modules/graphql/utilities/introspectionFromSchema.d.ts b/school/node_modules/graphql/utilities/introspectionFromSchema.d.ts new file mode 100644 index 0000000..ed9abf1 --- /dev/null +++ b/school/node_modules/graphql/utilities/introspectionFromSchema.d.ts @@ -0,0 +1,20 @@ +import { GraphQLSchema } from '../type/schema'; + +import { + IntrospectionQuery, + IntrospectionOptions, +} 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 function introspectionFromSchema( + schema: GraphQLSchema, + options?: IntrospectionOptions, +): IntrospectionQuery; diff --git a/school/node_modules/graphql/utilities/introspectionFromSchema.js b/school/node_modules/graphql/utilities/introspectionFromSchema.js new file mode 100644 index 0000000..3a1780e --- /dev/null +++ b/school/node_modules/graphql/utilities/introspectionFromSchema.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.introspectionFromSchema = introspectionFromSchema; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _parser = require("../language/parser.js"); + +var _execute = require("../execution/execute.js"); + +var _getIntrospectionQuery = require("./getIntrospectionQuery.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * 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) { + var optionsWithDefaults = _objectSpread({ + specifiedByUrl: true, + directiveIsRepeatable: true, + schemaDescription: true, + inputValueDeprecation: true + }, options); + + var document = (0, _parser.parse)((0, _getIntrospectionQuery.getIntrospectionQuery)(optionsWithDefaults)); + var result = (0, _execute.executeSync)({ + schema: schema, + document: document + }); + !result.errors && result.data || (0, _invariant.default)(0); + return result.data; +} diff --git a/school/node_modules/graphql/utilities/introspectionFromSchema.js.flow b/school/node_modules/graphql/utilities/introspectionFromSchema.js.flow new file mode 100644 index 0000000..0a73fe0 --- /dev/null +++ b/school/node_modules/graphql/utilities/introspectionFromSchema.js.flow @@ -0,0 +1,41 @@ +// @flow strict +import invariant from '../jsutils/invariant'; + +import { parse } from '../language/parser'; + +import type { GraphQLSchema } from '../type/schema'; + +import { executeSync } from '../execution/execute'; + +import type { + IntrospectionQuery, + IntrospectionOptions, +} from './getIntrospectionQuery'; +import { getIntrospectionQuery } 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 function introspectionFromSchema( + schema: GraphQLSchema, + options?: IntrospectionOptions, +): IntrospectionQuery { + const optionsWithDefaults = { + specifiedByUrl: true, + directiveIsRepeatable: true, + schemaDescription: true, + inputValueDeprecation: true, + ...options, + }; + + const document = parse(getIntrospectionQuery(optionsWithDefaults)); + const result = executeSync({ schema, document }); + invariant(!result.errors && result.data); + return (result.data: any); +} diff --git a/school/node_modules/graphql/utilities/introspectionFromSchema.mjs b/school/node_modules/graphql/utilities/introspectionFromSchema.mjs new file mode 100644 index 0000000..ad387eb --- /dev/null +++ b/school/node_modules/graphql/utilities/introspectionFromSchema.mjs @@ -0,0 +1,36 @@ +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +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) { + var optionsWithDefaults = _objectSpread({ + specifiedByUrl: true, + directiveIsRepeatable: true, + schemaDescription: true, + inputValueDeprecation: true + }, options); + + var document = parse(getIntrospectionQuery(optionsWithDefaults)); + var result = executeSync({ + schema: schema, + document: document + }); + !result.errors && result.data || invariant(0); + return result.data; +} diff --git a/school/node_modules/graphql/utilities/lexicographicSortSchema.d.ts b/school/node_modules/graphql/utilities/lexicographicSortSchema.d.ts new file mode 100644 index 0000000..7dfde70 --- /dev/null +++ b/school/node_modules/graphql/utilities/lexicographicSortSchema.d.ts @@ -0,0 +1,8 @@ +import { GraphQLSchema } from '../type/schema'; + +/** + * Sort GraphQLSchema. + * + * This function returns a sorted copy of the given GraphQLSchema. + */ +export function lexicographicSortSchema(schema: GraphQLSchema): GraphQLSchema; diff --git a/school/node_modules/graphql/utilities/lexicographicSortSchema.js b/school/node_modules/graphql/utilities/lexicographicSortSchema.js new file mode 100644 index 0000000..174bca4 --- /dev/null +++ b/school/node_modules/graphql/utilities/lexicographicSortSchema.js @@ -0,0 +1,202 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.lexicographicSortSchema = lexicographicSortSchema; + +var _objectValues = _interopRequireDefault(require("../polyfills/objectValues.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap.js")); + +var _naturalCompare = _interopRequireDefault(require("../jsutils/naturalCompare.js")); + +var _schema = require("../type/schema.js"); + +var _directives = require("../type/directives.js"); + +var _introspection = require("../type/introspection.js"); + +var _definition = require("../type/definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Sort GraphQLSchema. + * + * This function returns a sorted copy of the given GraphQLSchema. + */ +function lexicographicSortSchema(schema) { + var schemaConfig = schema.toConfig(); + var typeMap = (0, _keyValMap.default)(sortByName(schemaConfig.types), function (type) { + return type.name; + }, sortNamedType); + return new _schema.GraphQLSchema(_objectSpread(_objectSpread({}, schemaConfig), {}, { + types: (0, _objectValues.default)(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)) { + // $FlowFixMe[incompatible-return] + return new _definition.GraphQLList(replaceType(type.ofType)); + } else if ((0, _definition.isNonNullType)(type)) { + // $FlowFixMe[incompatible-return] + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } + + return replaceNamedType(type); + } + + function replaceNamedType(type) { + return typeMap[type.name]; + } + + function replaceMaybeType(maybeType) { + return maybeType && replaceNamedType(maybeType); + } + + function sortDirective(directive) { + var config = directive.toConfig(); + return new _directives.GraphQLDirective(_objectSpread(_objectSpread({}, config), {}, { + locations: sortBy(config.locations, function (x) { + return x; + }), + args: sortArgs(config.args) + })); + } + + function sortArgs(args) { + return sortObjMap(args, function (arg) { + return _objectSpread(_objectSpread({}, arg), {}, { + type: replaceType(arg.type) + }); + }); + } + + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return _objectSpread(_objectSpread({}, field), {}, { + type: replaceType(field.type), + args: sortArgs(field.args) + }); + }); + } + + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return _objectSpread(_objectSpread({}, field), {}, { + type: replaceType(field.type) + }); + }); + } + + function sortTypes(arr) { + return sortByName(arr).map(replaceNamedType); + } + + function sortNamedType(type) { + if ((0, _definition.isScalarType)(type) || (0, _introspection.isIntrospectionType)(type)) { + return type; + } + + if ((0, _definition.isObjectType)(type)) { + var config = type.toConfig(); + return new _definition.GraphQLObjectType(_objectSpread(_objectSpread({}, config), {}, { + interfaces: function interfaces() { + return sortTypes(config.interfaces); + }, + fields: function fields() { + return sortFields(config.fields); + } + })); + } + + if ((0, _definition.isInterfaceType)(type)) { + var _config = type.toConfig(); + + return new _definition.GraphQLInterfaceType(_objectSpread(_objectSpread({}, _config), {}, { + interfaces: function interfaces() { + return sortTypes(_config.interfaces); + }, + fields: function fields() { + return sortFields(_config.fields); + } + })); + } + + if ((0, _definition.isUnionType)(type)) { + var _config2 = type.toConfig(); + + return new _definition.GraphQLUnionType(_objectSpread(_objectSpread({}, _config2), {}, { + types: function types() { + return sortTypes(_config2.types); + } + })); + } + + if ((0, _definition.isEnumType)(type)) { + var _config3 = type.toConfig(); + + return new _definition.GraphQLEnumType(_objectSpread(_objectSpread({}, _config3), {}, { + values: sortObjMap(_config3.values) + })); + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if ((0, _definition.isInputObjectType)(type)) { + var _config4 = type.toConfig(); + + return new _definition.GraphQLInputObjectType(_objectSpread(_objectSpread({}, _config4), {}, { + fields: function fields() { + return sortInputFields(_config4.fields); + } + })); + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected type: ' + (0, _inspect.default)(type)); + } +} + +function sortObjMap(map, sortValueFn) { + var sortedMap = Object.create(null); + var sortedKeys = sortBy(Object.keys(map), function (x) { + return x; + }); + + for (var _i2 = 0; _i2 < sortedKeys.length; _i2++) { + var key = sortedKeys[_i2]; + var value = map[key]; + sortedMap[key] = sortValueFn ? sortValueFn(value) : value; + } + + return sortedMap; +} + +function sortByName(array) { + return sortBy(array, function (obj) { + return obj.name; + }); +} + +function sortBy(array, mapToKey) { + return array.slice().sort(function (obj1, obj2) { + var key1 = mapToKey(obj1); + var key2 = mapToKey(obj2); + return (0, _naturalCompare.default)(key1, key2); + }); +} diff --git a/school/node_modules/graphql/utilities/lexicographicSortSchema.js.flow b/school/node_modules/graphql/utilities/lexicographicSortSchema.js.flow new file mode 100644 index 0000000..a6f2505 --- /dev/null +++ b/school/node_modules/graphql/utilities/lexicographicSortSchema.js.flow @@ -0,0 +1,187 @@ +// @flow strict +import objectValues from '../polyfills/objectValues'; + +import type { ObjMap } from '../jsutils/ObjMap'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyValMap from '../jsutils/keyValMap'; +import naturalCompare from '../jsutils/naturalCompare'; + +import type { + GraphQLType, + GraphQLNamedType, + GraphQLFieldConfigMap, + GraphQLFieldConfigArgumentMap, + GraphQLInputFieldConfigMap, +} from '../type/definition'; +import { GraphQLSchema } from '../type/schema'; +import { GraphQLDirective } from '../type/directives'; +import { isIntrospectionType } from '../type/introspection'; +import { + GraphQLList, + GraphQLNonNull, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + isListType, + isNonNullType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, +} from '../type/definition'; + +/** + * Sort GraphQLSchema. + * + * This function returns a sorted copy of the given GraphQLSchema. + */ +export function lexicographicSortSchema(schema: GraphQLSchema): GraphQLSchema { + const schemaConfig = schema.toConfig(); + const typeMap = keyValMap( + sortByName(schemaConfig.types), + (type) => type.name, + sortNamedType, + ); + + return new GraphQLSchema({ + ...schemaConfig, + types: objectValues(typeMap), + directives: sortByName(schemaConfig.directives).map(sortDirective), + query: replaceMaybeType(schemaConfig.query), + mutation: replaceMaybeType(schemaConfig.mutation), + subscription: replaceMaybeType(schemaConfig.subscription), + }); + + function replaceType<T: GraphQLType>(type: T): T { + if (isListType(type)) { + // $FlowFixMe[incompatible-return] + return new GraphQLList(replaceType(type.ofType)); + } else if (isNonNullType(type)) { + // $FlowFixMe[incompatible-return] + return new GraphQLNonNull(replaceType(type.ofType)); + } + return replaceNamedType(type); + } + + function replaceNamedType<T: GraphQLNamedType>(type: T): T { + return ((typeMap[type.name]: any): T); + } + + function replaceMaybeType<T: ?GraphQLNamedType>(maybeType: T): T { + return maybeType && replaceNamedType(maybeType); + } + + function sortDirective(directive: GraphQLDirective) { + const config = directive.toConfig(); + return new GraphQLDirective({ + ...config, + locations: sortBy(config.locations, (x) => x), + args: sortArgs(config.args), + }); + } + + function sortArgs(args: GraphQLFieldConfigArgumentMap) { + return sortObjMap(args, (arg) => ({ + ...arg, + type: replaceType(arg.type), + })); + } + + function sortFields(fieldsMap: GraphQLFieldConfigMap<mixed, mixed>) { + return sortObjMap(fieldsMap, (field) => ({ + ...field, + type: replaceType(field.type), + args: sortArgs(field.args), + })); + } + + function sortInputFields(fieldsMap: GraphQLInputFieldConfigMap) { + return sortObjMap(fieldsMap, (field) => ({ + ...field, + type: replaceType(field.type), + })); + } + + function sortTypes<T: GraphQLNamedType>(arr: $ReadOnlyArray<T>): Array<T> { + return sortByName(arr).map(replaceNamedType); + } + + function sortNamedType(type: GraphQLNamedType): GraphQLNamedType { + 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), + }); + } + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + if (isInputObjectType(type)) { + const config = type.toConfig(); + return new GraphQLInputObjectType({ + ...config, + fields: () => sortInputFields(config.fields), + }); + } + + // istanbul ignore next (Not reachable. All possible types have been considered) + invariant(false, 'Unexpected type: ' + inspect((type: empty))); + } +} + +function sortObjMap<T, R>(map: ObjMap<T>, sortValueFn?: (T) => R): ObjMap<R> { + const sortedMap = Object.create(null); + const sortedKeys = sortBy(Object.keys(map), (x) => x); + for (const key of sortedKeys) { + const value = map[key]; + sortedMap[key] = sortValueFn ? sortValueFn(value) : value; + } + return sortedMap; +} + +function sortByName<T: { +name: string, ... }>( + array: $ReadOnlyArray<T>, +): Array<T> { + return sortBy(array, (obj) => obj.name); +} + +function sortBy<T>( + array: $ReadOnlyArray<T>, + mapToKey: (T) => string, +): Array<T> { + return array.slice().sort((obj1, obj2) => { + const key1 = mapToKey(obj1); + const key2 = mapToKey(obj2); + return naturalCompare(key1, key2); + }); +} diff --git a/school/node_modules/graphql/utilities/lexicographicSortSchema.mjs b/school/node_modules/graphql/utilities/lexicographicSortSchema.mjs new file mode 100644 index 0000000..cc9643f --- /dev/null +++ b/school/node_modules/graphql/utilities/lexicographicSortSchema.mjs @@ -0,0 +1,185 @@ +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +import objectValues from "../polyfills/objectValues.mjs"; +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 { GraphQLSchema } from "../type/schema.mjs"; +import { GraphQLDirective } from "../type/directives.mjs"; +import { isIntrospectionType } from "../type/introspection.mjs"; +import { GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, isListType, isNonNullType, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType } from "../type/definition.mjs"; +/** + * Sort GraphQLSchema. + * + * This function returns a sorted copy of the given GraphQLSchema. + */ + +export function lexicographicSortSchema(schema) { + var schemaConfig = schema.toConfig(); + var typeMap = keyValMap(sortByName(schemaConfig.types), function (type) { + return type.name; + }, sortNamedType); + return new GraphQLSchema(_objectSpread(_objectSpread({}, schemaConfig), {}, { + types: objectValues(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)) { + // $FlowFixMe[incompatible-return] + return new GraphQLList(replaceType(type.ofType)); + } else if (isNonNullType(type)) { + // $FlowFixMe[incompatible-return] + return new GraphQLNonNull(replaceType(type.ofType)); + } + + return replaceNamedType(type); + } + + function replaceNamedType(type) { + return typeMap[type.name]; + } + + function replaceMaybeType(maybeType) { + return maybeType && replaceNamedType(maybeType); + } + + function sortDirective(directive) { + var config = directive.toConfig(); + return new GraphQLDirective(_objectSpread(_objectSpread({}, config), {}, { + locations: sortBy(config.locations, function (x) { + return x; + }), + args: sortArgs(config.args) + })); + } + + function sortArgs(args) { + return sortObjMap(args, function (arg) { + return _objectSpread(_objectSpread({}, arg), {}, { + type: replaceType(arg.type) + }); + }); + } + + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return _objectSpread(_objectSpread({}, field), {}, { + type: replaceType(field.type), + args: sortArgs(field.args) + }); + }); + } + + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return _objectSpread(_objectSpread({}, field), {}, { + type: replaceType(field.type) + }); + }); + } + + function sortTypes(arr) { + return sortByName(arr).map(replaceNamedType); + } + + function sortNamedType(type) { + if (isScalarType(type) || isIntrospectionType(type)) { + return type; + } + + if (isObjectType(type)) { + var config = type.toConfig(); + return new GraphQLObjectType(_objectSpread(_objectSpread({}, config), {}, { + interfaces: function interfaces() { + return sortTypes(config.interfaces); + }, + fields: function fields() { + return sortFields(config.fields); + } + })); + } + + if (isInterfaceType(type)) { + var _config = type.toConfig(); + + return new GraphQLInterfaceType(_objectSpread(_objectSpread({}, _config), {}, { + interfaces: function interfaces() { + return sortTypes(_config.interfaces); + }, + fields: function fields() { + return sortFields(_config.fields); + } + })); + } + + if (isUnionType(type)) { + var _config2 = type.toConfig(); + + return new GraphQLUnionType(_objectSpread(_objectSpread({}, _config2), {}, { + types: function types() { + return sortTypes(_config2.types); + } + })); + } + + if (isEnumType(type)) { + var _config3 = type.toConfig(); + + return new GraphQLEnumType(_objectSpread(_objectSpread({}, _config3), {}, { + values: sortObjMap(_config3.values) + })); + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if (isInputObjectType(type)) { + var _config4 = type.toConfig(); + + return new GraphQLInputObjectType(_objectSpread(_objectSpread({}, _config4), {}, { + fields: function fields() { + return sortInputFields(_config4.fields); + } + })); + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || invariant(0, 'Unexpected type: ' + inspect(type)); + } +} + +function sortObjMap(map, sortValueFn) { + var sortedMap = Object.create(null); + var sortedKeys = sortBy(Object.keys(map), function (x) { + return x; + }); + + for (var _i2 = 0; _i2 < sortedKeys.length; _i2++) { + var key = sortedKeys[_i2]; + var value = map[key]; + sortedMap[key] = sortValueFn ? sortValueFn(value) : value; + } + + return sortedMap; +} + +function sortByName(array) { + return sortBy(array, function (obj) { + return obj.name; + }); +} + +function sortBy(array, mapToKey) { + return array.slice().sort(function (obj1, obj2) { + var key1 = mapToKey(obj1); + var key2 = mapToKey(obj2); + return naturalCompare(key1, key2); + }); +} diff --git a/school/node_modules/graphql/utilities/printSchema.d.ts b/school/node_modules/graphql/utilities/printSchema.d.ts new file mode 100644 index 0000000..1417ee5 --- /dev/null +++ b/school/node_modules/graphql/utilities/printSchema.d.ts @@ -0,0 +1,30 @@ +import { GraphQLSchema } from '../type/schema'; +import { GraphQLNamedType } from '../type/definition'; + +export interface Options { + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean; +} + +/** + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function printSchema(schema: GraphQLSchema, options?: Options): string; + +export function printIntrospectionSchema( + schema: GraphQLSchema, + options?: Options, +): string; + +export function printType(type: GraphQLNamedType, options?: Options): string; diff --git a/school/node_modules/graphql/utilities/printSchema.js b/school/node_modules/graphql/utilities/printSchema.js new file mode 100644 index 0000000..3d6d618 --- /dev/null +++ b/school/node_modules/graphql/utilities/printSchema.js @@ -0,0 +1,289 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.printSchema = printSchema; +exports.printIntrospectionSchema = printIntrospectionSchema; +exports.printType = printType; + +var _objectValues = _interopRequireDefault(require("../polyfills/objectValues.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _printer = require("../language/printer.js"); + +var _blockString = require("../language/blockString.js"); + +var _introspection = require("../type/introspection.js"); + +var _scalars = require("../type/scalars.js"); + +var _directives = require("../type/directives.js"); + +var _definition = require("../type/definition.js"); + +var _astFromValue = require("./astFromValue.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +function printSchema(schema, options) { + return printFilteredSchema(schema, function (n) { + return !(0, _directives.isSpecifiedDirective)(n); + }, isDefinedType, options); +} + +function printIntrospectionSchema(schema, options) { + return printFilteredSchema(schema, _directives.isSpecifiedDirective, _introspection.isIntrospectionType, options); +} + +function isDefinedType(type) { + return !(0, _scalars.isSpecifiedScalarType)(type) && !(0, _introspection.isIntrospectionType)(type); +} + +function printFilteredSchema(schema, directiveFilter, typeFilter, options) { + var directives = schema.getDirectives().filter(directiveFilter); + var types = (0, _objectValues.default)(schema.getTypeMap()).filter(typeFilter); + return [printSchemaDefinition(schema)].concat(directives.map(function (directive) { + return printDirective(directive, options); + }), types.map(function (type) { + return printType(type, options); + })).filter(Boolean).join('\n\n') + '\n'; +} + +function printSchemaDefinition(schema) { + if (schema.description == null && isSchemaOfCommonNames(schema)) { + return; + } + + var operationTypes = []; + var queryType = schema.getQueryType(); + + if (queryType) { + operationTypes.push(" query: ".concat(queryType.name)); + } + + var mutationType = schema.getMutationType(); + + if (mutationType) { + operationTypes.push(" mutation: ".concat(mutationType.name)); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType) { + operationTypes.push(" subscription: ".concat(subscriptionType.name)); + } + + return printDescription({}, schema) + "schema {\n".concat(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: + * + * schema { + * query: Query + * mutation: Mutation + * } + * + * When using this naming convention, the schema description can be omitted. + */ + + +function isSchemaOfCommonNames(schema) { + var queryType = schema.getQueryType(); + + if (queryType && queryType.name !== 'Query') { + return false; + } + + var mutationType = schema.getMutationType(); + + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + + return true; +} + +function printType(type, options) { + if ((0, _definition.isScalarType)(type)) { + return printScalar(type, options); + } + + if ((0, _definition.isObjectType)(type)) { + return printObject(type, options); + } + + if ((0, _definition.isInterfaceType)(type)) { + return printInterface(type, options); + } + + if ((0, _definition.isUnionType)(type)) { + return printUnion(type, options); + } + + if ((0, _definition.isEnumType)(type)) { + return printEnum(type, options); + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if ((0, _definition.isInputObjectType)(type)) { + return printInputObject(type, options); + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected type: ' + (0, _inspect.default)(type)); +} + +function printScalar(type, options) { + return printDescription(options, type) + "scalar ".concat(type.name) + printSpecifiedByUrl(type); +} + +function printImplementedInterfaces(type) { + var interfaces = type.getInterfaces(); + return interfaces.length ? ' implements ' + interfaces.map(function (i) { + return i.name; + }).join(' & ') : ''; +} + +function printObject(type, options) { + return printDescription(options, type) + "type ".concat(type.name) + printImplementedInterfaces(type) + printFields(options, type); +} + +function printInterface(type, options) { + return printDescription(options, type) + "interface ".concat(type.name) + printImplementedInterfaces(type) + printFields(options, type); +} + +function printUnion(type, options) { + var types = type.getTypes(); + var possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; + return printDescription(options, type) + 'union ' + type.name + possibleTypes; +} + +function printEnum(type, options) { + var values = type.getValues().map(function (value, i) { + return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value.deprecationReason); + }); + return printDescription(options, type) + "enum ".concat(type.name) + printBlock(values); +} + +function printInputObject(type, options) { + var fields = (0, _objectValues.default)(type.getFields()).map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f); + }); + return printDescription(options, type) + "input ".concat(type.name) + printBlock(fields); +} + +function printFields(options, type) { + var fields = (0, _objectValues.default)(type.getFields()).map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, 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(options, args) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + + if (args.length === 0) { + return ''; + } // If every arg does not have a description, print them on one line. + + + if (args.every(function (arg) { + return !arg.description; + })) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + + return '(\n' + args.map(function (arg, i) { + return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg); + }).join('\n') + '\n' + indentation + ')'; +} + +function printInputValue(arg) { + var defaultAST = (0, _astFromValue.astFromValue)(arg.defaultValue, arg.type); + var argDecl = arg.name + ': ' + String(arg.type); + + if (defaultAST) { + argDecl += " = ".concat((0, _printer.print)(defaultAST)); + } + + return argDecl + printDeprecated(arg.deprecationReason); +} + +function printDirective(directive, options) { + return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + (directive.isRepeatable ? ' repeatable' : '') + ' on ' + directive.locations.join(' | '); +} + +function printDeprecated(reason) { + if (reason == null) { + return ''; + } + + var reasonAST = (0, _astFromValue.astFromValue)(reason, _scalars.GraphQLString); + + if (reasonAST && reason !== _directives.DEFAULT_DEPRECATION_REASON) { + return ' @deprecated(reason: ' + (0, _printer.print)(reasonAST) + ')'; + } + + return ' @deprecated'; +} + +function printSpecifiedByUrl(scalar) { + if (scalar.specifiedByUrl == null) { + return ''; + } + + var url = scalar.specifiedByUrl; + var urlAST = (0, _astFromValue.astFromValue)(url, _scalars.GraphQLString); + urlAST || (0, _invariant.default)(0, 'Unexpected null value returned from `astFromValue` for specifiedByUrl'); + return ' @specifiedBy(url: ' + (0, _printer.print)(urlAST) + ')'; +} + +function printDescription(options, def) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + var description = def.description; + + if (description == null) { + return ''; + } + + if ((options === null || options === void 0 ? void 0 : options.commentDescriptions) === true) { + return printDescriptionWithComments(description, indentation, firstInBlock); + } + + var preferMultipleLines = description.length > 70; + var blockString = (0, _blockString.printBlockString)(description, '', preferMultipleLines); + var prefix = indentation && !firstInBlock ? '\n' + indentation : indentation; + return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; +} + +function printDescriptionWithComments(description, indentation, firstInBlock) { + var prefix = indentation && !firstInBlock ? '\n' : ''; + var comment = description.split('\n').map(function (line) { + return indentation + (line !== '' ? '# ' + line : '#'); + }).join('\n'); + return prefix + comment + '\n'; +} diff --git a/school/node_modules/graphql/utilities/printSchema.js.flow b/school/node_modules/graphql/utilities/printSchema.js.flow new file mode 100644 index 0000000..a240a3e --- /dev/null +++ b/school/node_modules/graphql/utilities/printSchema.js.flow @@ -0,0 +1,382 @@ +// @flow strict +import objectValues from '../polyfills/objectValues'; + +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; + +import { print } from '../language/printer'; +import { printBlockString } from '../language/blockString'; + +import type { GraphQLSchema } from '../type/schema'; +import type { GraphQLDirective } from '../type/directives'; +import type { + GraphQLNamedType, + GraphQLArgument, + GraphQLInputField, + GraphQLScalarType, + GraphQLEnumType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLInputObjectType, +} from '../type/definition'; +import { isIntrospectionType } from '../type/introspection'; +import { GraphQLString, isSpecifiedScalarType } from '../type/scalars'; +import { + DEFAULT_DEPRECATION_REASON, + isSpecifiedDirective, +} from '../type/directives'; +import { + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, +} from '../type/definition'; + +import { astFromValue } from './astFromValue'; + +type Options = {| + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean, +|}; + +/** + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function printSchema(schema: GraphQLSchema, options?: Options): string { + return printFilteredSchema( + schema, + (n) => !isSpecifiedDirective(n), + isDefinedType, + options, + ); +} + +export function printIntrospectionSchema( + schema: GraphQLSchema, + options?: Options, +): string { + return printFilteredSchema( + schema, + isSpecifiedDirective, + isIntrospectionType, + options, + ); +} + +function isDefinedType(type: GraphQLNamedType): boolean { + return !isSpecifiedScalarType(type) && !isIntrospectionType(type); +} + +function printFilteredSchema( + schema: GraphQLSchema, + directiveFilter: (type: GraphQLDirective) => boolean, + typeFilter: (type: GraphQLNamedType) => boolean, + options, +): string { + const directives = schema.getDirectives().filter(directiveFilter); + const types = objectValues(schema.getTypeMap()).filter(typeFilter); + + return ( + [printSchemaDefinition(schema)] + .concat( + directives.map((directive) => printDirective(directive, options)), + types.map((type) => printType(type, options)), + ) + .filter(Boolean) + .join('\n\n') + '\n' + ); +} + +function printSchemaDefinition(schema: GraphQLSchema): ?string { + 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: + * + * schema { + * query: Query + * mutation: Mutation + * } + * + * When using this naming convention, the schema description can be omitted. + */ +function isSchemaOfCommonNames(schema: GraphQLSchema): boolean { + 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: GraphQLNamedType, options?: Options): string { + if (isScalarType(type)) { + return printScalar(type, options); + } + if (isObjectType(type)) { + return printObject(type, options); + } + if (isInterfaceType(type)) { + return printInterface(type, options); + } + if (isUnionType(type)) { + return printUnion(type, options); + } + if (isEnumType(type)) { + return printEnum(type, options); + } + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + if (isInputObjectType(type)) { + return printInputObject(type, options); + } + + // istanbul ignore next (Not reachable. All possible types have been considered) + invariant(false, 'Unexpected type: ' + inspect((type: empty))); +} + +function printScalar(type: GraphQLScalarType, options): string { + return ( + printDescription(options, type) + + `scalar ${type.name}` + + printSpecifiedByUrl(type) + ); +} + +function printImplementedInterfaces( + type: GraphQLObjectType | GraphQLInterfaceType, +): string { + const interfaces = type.getInterfaces(); + return interfaces.length + ? ' implements ' + interfaces.map((i) => i.name).join(' & ') + : ''; +} + +function printObject(type: GraphQLObjectType, options): string { + return ( + printDescription(options, type) + + `type ${type.name}` + + printImplementedInterfaces(type) + + printFields(options, type) + ); +} + +function printInterface(type: GraphQLInterfaceType, options): string { + return ( + printDescription(options, type) + + `interface ${type.name}` + + printImplementedInterfaces(type) + + printFields(options, type) + ); +} + +function printUnion(type: GraphQLUnionType, options): string { + const types = type.getTypes(); + const possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; + return printDescription(options, type) + 'union ' + type.name + possibleTypes; +} + +function printEnum(type: GraphQLEnumType, options): string { + const values = type + .getValues() + .map( + (value, i) => + printDescription(options, value, ' ', !i) + + ' ' + + value.name + + printDeprecated(value.deprecationReason), + ); + + return ( + printDescription(options, type) + `enum ${type.name}` + printBlock(values) + ); +} + +function printInputObject(type: GraphQLInputObjectType, options): string { + const fields = objectValues(type.getFields()).map( + (f, i) => + printDescription(options, f, ' ', !i) + ' ' + printInputValue(f), + ); + return ( + printDescription(options, type) + `input ${type.name}` + printBlock(fields) + ); +} + +function printFields( + options, + type: GraphQLObjectType | GraphQLInterfaceType, +): string { + const fields = objectValues(type.getFields()).map( + (f, i) => + printDescription(options, f, ' ', !i) + + ' ' + + f.name + + printArgs(options, f.args, ' ') + + ': ' + + String(f.type) + + printDeprecated(f.deprecationReason), + ); + return printBlock(fields); +} + +function printBlock(items: $ReadOnlyArray<string>): string { + return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : ''; +} + +function printArgs( + options, + args: Array<GraphQLArgument>, + indentation: string = '', +): string { + 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(options, arg, ' ' + indentation, !i) + + ' ' + + indentation + + printInputValue(arg), + ) + .join('\n') + + '\n' + + indentation + + ')' + ); +} + +function printInputValue(arg: GraphQLInputField): string { + 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: GraphQLDirective, options): string { + return ( + printDescription(options, directive) + + 'directive @' + + directive.name + + printArgs(options, directive.args) + + (directive.isRepeatable ? ' repeatable' : '') + + ' on ' + + directive.locations.join(' | ') + ); +} + +function printDeprecated(reason: ?string): string { + if (reason == null) { + return ''; + } + const reasonAST = astFromValue(reason, GraphQLString); + if (reasonAST && reason !== DEFAULT_DEPRECATION_REASON) { + return ' @deprecated(reason: ' + print(reasonAST) + ')'; + } + return ' @deprecated'; +} + +function printSpecifiedByUrl(scalar: GraphQLScalarType): string { + if (scalar.specifiedByUrl == null) { + return ''; + } + const url = scalar.specifiedByUrl; + const urlAST = astFromValue(url, GraphQLString); + invariant( + urlAST, + 'Unexpected null value returned from `astFromValue` for specifiedByUrl', + ); + return ' @specifiedBy(url: ' + print(urlAST) + ')'; +} + +function printDescription( + options, + def: { +description: ?string, ... }, + indentation: string = '', + firstInBlock: boolean = true, +): string { + const { description } = def; + if (description == null) { + return ''; + } + + if (options?.commentDescriptions === true) { + return printDescriptionWithComments(description, indentation, firstInBlock); + } + + const preferMultipleLines = description.length > 70; + const blockString = printBlockString(description, '', preferMultipleLines); + const prefix = + indentation && !firstInBlock ? '\n' + indentation : indentation; + + return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; +} + +function printDescriptionWithComments(description, indentation, firstInBlock) { + const prefix = indentation && !firstInBlock ? '\n' : ''; + const comment = description + .split('\n') + .map((line) => indentation + (line !== '' ? '# ' + line : '#')) + .join('\n'); + + return prefix + comment + '\n'; +} diff --git a/school/node_modules/graphql/utilities/printSchema.mjs b/school/node_modules/graphql/utilities/printSchema.mjs new file mode 100644 index 0000000..a34cec4 --- /dev/null +++ b/school/node_modules/graphql/utilities/printSchema.mjs @@ -0,0 +1,268 @@ +import objectValues from "../polyfills/objectValues.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import invariant from "../jsutils/invariant.mjs"; +import { print } from "../language/printer.mjs"; +import { printBlockString } from "../language/blockString.mjs"; +import { isIntrospectionType } from "../type/introspection.mjs"; +import { GraphQLString, isSpecifiedScalarType } from "../type/scalars.mjs"; +import { DEFAULT_DEPRECATION_REASON, isSpecifiedDirective } from "../type/directives.mjs"; +import { isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType } from "../type/definition.mjs"; +import { astFromValue } from "./astFromValue.mjs"; + +/** + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function printSchema(schema, options) { + return printFilteredSchema(schema, function (n) { + return !isSpecifiedDirective(n); + }, isDefinedType, options); +} +export function printIntrospectionSchema(schema, options) { + return printFilteredSchema(schema, isSpecifiedDirective, isIntrospectionType, options); +} + +function isDefinedType(type) { + return !isSpecifiedScalarType(type) && !isIntrospectionType(type); +} + +function printFilteredSchema(schema, directiveFilter, typeFilter, options) { + var directives = schema.getDirectives().filter(directiveFilter); + var types = objectValues(schema.getTypeMap()).filter(typeFilter); + return [printSchemaDefinition(schema)].concat(directives.map(function (directive) { + return printDirective(directive, options); + }), types.map(function (type) { + return printType(type, options); + })).filter(Boolean).join('\n\n') + '\n'; +} + +function printSchemaDefinition(schema) { + if (schema.description == null && isSchemaOfCommonNames(schema)) { + return; + } + + var operationTypes = []; + var queryType = schema.getQueryType(); + + if (queryType) { + operationTypes.push(" query: ".concat(queryType.name)); + } + + var mutationType = schema.getMutationType(); + + if (mutationType) { + operationTypes.push(" mutation: ".concat(mutationType.name)); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType) { + operationTypes.push(" subscription: ".concat(subscriptionType.name)); + } + + return printDescription({}, schema) + "schema {\n".concat(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: + * + * schema { + * query: Query + * mutation: Mutation + * } + * + * When using this naming convention, the schema description can be omitted. + */ + + +function isSchemaOfCommonNames(schema) { + var queryType = schema.getQueryType(); + + if (queryType && queryType.name !== 'Query') { + return false; + } + + var mutationType = schema.getMutationType(); + + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + + return true; +} + +export function printType(type, options) { + if (isScalarType(type)) { + return printScalar(type, options); + } + + if (isObjectType(type)) { + return printObject(type, options); + } + + if (isInterfaceType(type)) { + return printInterface(type, options); + } + + if (isUnionType(type)) { + return printUnion(type, options); + } + + if (isEnumType(type)) { + return printEnum(type, options); + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if (isInputObjectType(type)) { + return printInputObject(type, options); + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || invariant(0, 'Unexpected type: ' + inspect(type)); +} + +function printScalar(type, options) { + return printDescription(options, type) + "scalar ".concat(type.name) + printSpecifiedByUrl(type); +} + +function printImplementedInterfaces(type) { + var interfaces = type.getInterfaces(); + return interfaces.length ? ' implements ' + interfaces.map(function (i) { + return i.name; + }).join(' & ') : ''; +} + +function printObject(type, options) { + return printDescription(options, type) + "type ".concat(type.name) + printImplementedInterfaces(type) + printFields(options, type); +} + +function printInterface(type, options) { + return printDescription(options, type) + "interface ".concat(type.name) + printImplementedInterfaces(type) + printFields(options, type); +} + +function printUnion(type, options) { + var types = type.getTypes(); + var possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; + return printDescription(options, type) + 'union ' + type.name + possibleTypes; +} + +function printEnum(type, options) { + var values = type.getValues().map(function (value, i) { + return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value.deprecationReason); + }); + return printDescription(options, type) + "enum ".concat(type.name) + printBlock(values); +} + +function printInputObject(type, options) { + var fields = objectValues(type.getFields()).map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f); + }); + return printDescription(options, type) + "input ".concat(type.name) + printBlock(fields); +} + +function printFields(options, type) { + var fields = objectValues(type.getFields()).map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, 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(options, args) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + + if (args.length === 0) { + return ''; + } // If every arg does not have a description, print them on one line. + + + if (args.every(function (arg) { + return !arg.description; + })) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + + return '(\n' + args.map(function (arg, i) { + return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg); + }).join('\n') + '\n' + indentation + ')'; +} + +function printInputValue(arg) { + var defaultAST = astFromValue(arg.defaultValue, arg.type); + var argDecl = arg.name + ': ' + String(arg.type); + + if (defaultAST) { + argDecl += " = ".concat(print(defaultAST)); + } + + return argDecl + printDeprecated(arg.deprecationReason); +} + +function printDirective(directive, options) { + return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + (directive.isRepeatable ? ' repeatable' : '') + ' on ' + directive.locations.join(' | '); +} + +function printDeprecated(reason) { + if (reason == null) { + return ''; + } + + var reasonAST = astFromValue(reason, GraphQLString); + + if (reasonAST && reason !== DEFAULT_DEPRECATION_REASON) { + return ' @deprecated(reason: ' + print(reasonAST) + ')'; + } + + return ' @deprecated'; +} + +function printSpecifiedByUrl(scalar) { + if (scalar.specifiedByUrl == null) { + return ''; + } + + var url = scalar.specifiedByUrl; + var urlAST = astFromValue(url, GraphQLString); + urlAST || invariant(0, 'Unexpected null value returned from `astFromValue` for specifiedByUrl'); + return ' @specifiedBy(url: ' + print(urlAST) + ')'; +} + +function printDescription(options, def) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + var description = def.description; + + if (description == null) { + return ''; + } + + if ((options === null || options === void 0 ? void 0 : options.commentDescriptions) === true) { + return printDescriptionWithComments(description, indentation, firstInBlock); + } + + var preferMultipleLines = description.length > 70; + var blockString = printBlockString(description, '', preferMultipleLines); + var prefix = indentation && !firstInBlock ? '\n' + indentation : indentation; + return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; +} + +function printDescriptionWithComments(description, indentation, firstInBlock) { + var prefix = indentation && !firstInBlock ? '\n' : ''; + var comment = description.split('\n').map(function (line) { + return indentation + (line !== '' ? '# ' + line : '#'); + }).join('\n'); + return prefix + comment + '\n'; +} diff --git a/school/node_modules/graphql/utilities/separateOperations.d.ts b/school/node_modules/graphql/utilities/separateOperations.d.ts new file mode 100644 index 0000000..28654fd --- /dev/null +++ b/school/node_modules/graphql/utilities/separateOperations.d.ts @@ -0,0 +1,11 @@ +import { 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 function separateOperations( + documentAST: DocumentNode, +): { [key: string]: DocumentNode }; diff --git a/school/node_modules/graphql/utilities/separateOperations.js b/school/node_modules/graphql/utilities/separateOperations.js new file mode 100644 index 0000000..de00bd7 --- /dev/null +++ b/school/node_modules/graphql/utilities/separateOperations.js @@ -0,0 +1,92 @@ +"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) { + var operations = []; + var depGraph = Object.create(null); // Populate metadata and build a dependency graph. + + for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) { + var definitionNode = _documentAST$definiti2[_i2]; + + 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; + } + } // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + + var separatedDocumentASTs = Object.create(null); + + var _loop = function _loop(_i4) { + var operation = operations[_i4]; + var dependencies = new Set(); + + for (var _i6 = 0, _collectDependencies2 = collectDependencies(operation.selectionSet); _i6 < _collectDependencies2.length; _i6++) { + var fragmentName = _collectDependencies2[_i6]; + collectTransitiveDependencies(dependencies, depGraph, fragmentName); + } // Provides the empty string for anonymous operations. + + + var 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(function (node) { + return node === operation || node.kind === _kinds.Kind.FRAGMENT_DEFINITION && dependencies.has(node.name.value); + }) + }; + }; + + for (var _i4 = 0; _i4 < operations.length; _i4++) { + _loop(_i4); + } + + 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); + var immediateDeps = depGraph[fromName]; + + if (immediateDeps !== undefined) { + for (var _i8 = 0; _i8 < immediateDeps.length; _i8++) { + var toName = immediateDeps[_i8]; + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } +} + +function collectDependencies(selectionSet) { + var dependencies = []; + (0, _visitor.visit)(selectionSet, { + FragmentSpread: function FragmentSpread(node) { + dependencies.push(node.name.value); + } + }); + return dependencies; +} diff --git a/school/node_modules/graphql/utilities/separateOperations.js.flow b/school/node_modules/graphql/utilities/separateOperations.js.flow new file mode 100644 index 0000000..320053e --- /dev/null +++ b/school/node_modules/graphql/utilities/separateOperations.js.flow @@ -0,0 +1,97 @@ +// @flow strict +import type { ObjMap } from '../jsutils/ObjMap'; + +import type { + DocumentNode, + OperationDefinitionNode, + SelectionSetNode, +} from '../language/ast'; +import { Kind } from '../language/kinds'; +import { visit } from '../language/visitor'; + +/** + * 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: DocumentNode, +): ObjMap<DocumentNode> { + const operations: Array<OperationDefinitionNode> = []; + const depGraph: 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; + } + } + + // 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; +} + +type DepGraph = ObjMap<Array<string>>; + +// From a dependency graph, collects a list of transitive dependencies by +// recursing through a dependency graph. +function collectTransitiveDependencies( + collected: Set<string>, + depGraph: DepGraph, + fromName: string, +): void { + 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: SelectionSetNode): Array<string> { + const dependencies = []; + + visit(selectionSet, { + FragmentSpread(node) { + dependencies.push(node.name.value); + }, + }); + return dependencies; +} diff --git a/school/node_modules/graphql/utilities/separateOperations.mjs b/school/node_modules/graphql/utilities/separateOperations.mjs new file mode 100644 index 0000000..69c75da --- /dev/null +++ b/school/node_modules/graphql/utilities/separateOperations.mjs @@ -0,0 +1,84 @@ +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) { + var operations = []; + var depGraph = Object.create(null); // Populate metadata and build a dependency graph. + + for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) { + var definitionNode = _documentAST$definiti2[_i2]; + + switch (definitionNode.kind) { + case Kind.OPERATION_DEFINITION: + operations.push(definitionNode); + break; + + case Kind.FRAGMENT_DEFINITION: + depGraph[definitionNode.name.value] = collectDependencies(definitionNode.selectionSet); + break; + } + } // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + + var separatedDocumentASTs = Object.create(null); + + var _loop = function _loop(_i4) { + var operation = operations[_i4]; + var dependencies = new Set(); + + for (var _i6 = 0, _collectDependencies2 = collectDependencies(operation.selectionSet); _i6 < _collectDependencies2.length; _i6++) { + var fragmentName = _collectDependencies2[_i6]; + collectTransitiveDependencies(dependencies, depGraph, fragmentName); + } // Provides the empty string for anonymous operations. + + + var 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(function (node) { + return node === operation || node.kind === Kind.FRAGMENT_DEFINITION && dependencies.has(node.name.value); + }) + }; + }; + + for (var _i4 = 0; _i4 < operations.length; _i4++) { + _loop(_i4); + } + + 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); + var immediateDeps = depGraph[fromName]; + + if (immediateDeps !== undefined) { + for (var _i8 = 0; _i8 < immediateDeps.length; _i8++) { + var toName = immediateDeps[_i8]; + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } +} + +function collectDependencies(selectionSet) { + var dependencies = []; + visit(selectionSet, { + FragmentSpread: function FragmentSpread(node) { + dependencies.push(node.name.value); + } + }); + return dependencies; +} diff --git a/school/node_modules/graphql/utilities/stripIgnoredCharacters.d.ts b/school/node_modules/graphql/utilities/stripIgnoredCharacters.d.ts new file mode 100644 index 0000000..a131af0 --- /dev/null +++ b/school/node_modules/graphql/utilities/stripIgnoredCharacters.d.ts @@ -0,0 +1,55 @@ +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: + * + * query SomeQuery($foo: String!, $bar: String) { + * someField(foo: $foo, bar: $bar) { + * a + * b { + * c + * d + * } + * } + * } + * + * Becomes: + * + * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} + * + * SDL example: + * + * """ + * Type description + * """ + * type Foo { + * """ + * Field description + * """ + * bar: String + * } + * + * Becomes: + * + * """Type description""" type Foo{"""Field description""" bar:String} + */ +export function stripIgnoredCharacters(source: string | Source): string; diff --git a/school/node_modules/graphql/utilities/stripIgnoredCharacters.js b/school/node_modules/graphql/utilities/stripIgnoredCharacters.js new file mode 100644 index 0000000..aac5ddc --- /dev/null +++ b/school/node_modules/graphql/utilities/stripIgnoredCharacters.js @@ -0,0 +1,123 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.stripIgnoredCharacters = stripIgnoredCharacters; + +var _source = require("../language/source.js"); + +var _tokenKind = require("../language/tokenKind.js"); + +var _lexer = require("../language/lexer.js"); + +var _blockString = require("../language/blockString.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: + * + * query SomeQuery($foo: String!, $bar: String) { + * someField(foo: $foo, bar: $bar) { + * a + * b { + * c + * d + * } + * } + * } + * + * Becomes: + * + * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} + * + * SDL example: + * + * """ + * Type description + * """ + * type Foo { + * """ + * Field description + * """ + * bar: String + * } + * + * Becomes: + * + * """Type description""" type Foo{"""Field description""" bar:String} + */ +function stripIgnoredCharacters(source) { + var sourceObj = (0, _source.isSource)(source) ? source : new _source.Source(source); + var body = sourceObj.body; + var lexer = new _lexer.Lexer(sourceObj); + var strippedBody = ''; + var wasLastAddedTokenNonPunctuator = false; + + while (lexer.advance().kind !== _tokenKind.TokenKind.EOF) { + var currentToken = lexer.token; + var 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). + */ + + var isNonPunctuator = !(0, _lexer.isPunctuatorTokenKind)(currentToken.kind); + + if (wasLastAddedTokenNonPunctuator) { + if (isNonPunctuator || currentToken.kind === _tokenKind.TokenKind.SPREAD) { + strippedBody += ' '; + } + } + + var tokenBody = body.slice(currentToken.start, currentToken.end); + + if (tokenKind === _tokenKind.TokenKind.BLOCK_STRING) { + strippedBody += dedentBlockString(tokenBody); + } else { + strippedBody += tokenBody; + } + + wasLastAddedTokenNonPunctuator = isNonPunctuator; + } + + return strippedBody; +} + +function dedentBlockString(blockStr) { + // skip leading and trailing triple quotations + var rawStr = blockStr.slice(3, -3); + var body = (0, _blockString.dedentBlockStringValue)(rawStr); + + if ((0, _blockString.getBlockStringIndentation)(body) > 0) { + body = '\n' + body; + } + + var lastChar = body[body.length - 1]; + var hasTrailingQuote = lastChar === '"' && body.slice(-4) !== '\\"""'; + + if (hasTrailingQuote || lastChar === '\\') { + body += '\n'; + } + + return '"""' + body + '"""'; +} diff --git a/school/node_modules/graphql/utilities/stripIgnoredCharacters.js.flow b/school/node_modules/graphql/utilities/stripIgnoredCharacters.js.flow new file mode 100644 index 0000000..a5a6aa9 --- /dev/null +++ b/school/node_modules/graphql/utilities/stripIgnoredCharacters.js.flow @@ -0,0 +1,115 @@ +// @flow strict +import { Source, isSource } from '../language/source'; +import { TokenKind } from '../language/tokenKind'; +import { Lexer, isPunctuatorTokenKind } from '../language/lexer'; +import { + dedentBlockStringValue, + getBlockStringIndentation, +} from '../language/blockString'; + +/** + * 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: + * + * query SomeQuery($foo: String!, $bar: String) { + * someField(foo: $foo, bar: $bar) { + * a + * b { + * c + * d + * } + * } + * } + * + * Becomes: + * + * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} + * + * SDL example: + * + * """ + * Type description + * """ + * type Foo { + * """ + * Field description + * """ + * bar: String + * } + * + * Becomes: + * + * """Type description""" type Foo{"""Field description""" bar:String} + */ +export function stripIgnoredCharacters(source: string | Source): string { + 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 += dedentBlockString(tokenBody); + } else { + strippedBody += tokenBody; + } + + wasLastAddedTokenNonPunctuator = isNonPunctuator; + } + + return strippedBody; +} + +function dedentBlockString(blockStr: string): string { + // skip leading and trailing triple quotations + const rawStr = blockStr.slice(3, -3); + let body = dedentBlockStringValue(rawStr); + + if (getBlockStringIndentation(body) > 0) { + body = '\n' + body; + } + + const lastChar = body[body.length - 1]; + const hasTrailingQuote = lastChar === '"' && body.slice(-4) !== '\\"""'; + if (hasTrailingQuote || lastChar === '\\') { + body += '\n'; + } + + return '"""' + body + '"""'; +} diff --git a/school/node_modules/graphql/utilities/stripIgnoredCharacters.mjs b/school/node_modules/graphql/utilities/stripIgnoredCharacters.mjs new file mode 100644 index 0000000..a0a0758 --- /dev/null +++ b/school/node_modules/graphql/utilities/stripIgnoredCharacters.mjs @@ -0,0 +1,113 @@ +import { Source, isSource } from "../language/source.mjs"; +import { TokenKind } from "../language/tokenKind.mjs"; +import { Lexer, isPunctuatorTokenKind } from "../language/lexer.mjs"; +import { dedentBlockStringValue, getBlockStringIndentation } from "../language/blockString.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: + * + * query SomeQuery($foo: String!, $bar: String) { + * someField(foo: $foo, bar: $bar) { + * a + * b { + * c + * d + * } + * } + * } + * + * Becomes: + * + * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} + * + * SDL example: + * + * """ + * Type description + * """ + * type Foo { + * """ + * Field description + * """ + * bar: String + * } + * + * Becomes: + * + * """Type description""" type Foo{"""Field description""" bar:String} + */ + +export function stripIgnoredCharacters(source) { + var sourceObj = isSource(source) ? source : new Source(source); + var body = sourceObj.body; + var lexer = new Lexer(sourceObj); + var strippedBody = ''; + var wasLastAddedTokenNonPunctuator = false; + + while (lexer.advance().kind !== TokenKind.EOF) { + var currentToken = lexer.token; + var 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). + */ + + var isNonPunctuator = !isPunctuatorTokenKind(currentToken.kind); + + if (wasLastAddedTokenNonPunctuator) { + if (isNonPunctuator || currentToken.kind === TokenKind.SPREAD) { + strippedBody += ' '; + } + } + + var tokenBody = body.slice(currentToken.start, currentToken.end); + + if (tokenKind === TokenKind.BLOCK_STRING) { + strippedBody += dedentBlockString(tokenBody); + } else { + strippedBody += tokenBody; + } + + wasLastAddedTokenNonPunctuator = isNonPunctuator; + } + + return strippedBody; +} + +function dedentBlockString(blockStr) { + // skip leading and trailing triple quotations + var rawStr = blockStr.slice(3, -3); + var body = dedentBlockStringValue(rawStr); + + if (getBlockStringIndentation(body) > 0) { + body = '\n' + body; + } + + var lastChar = body[body.length - 1]; + var hasTrailingQuote = lastChar === '"' && body.slice(-4) !== '\\"""'; + + if (hasTrailingQuote || lastChar === '\\') { + body += '\n'; + } + + return '"""' + body + '"""'; +} diff --git a/school/node_modules/graphql/utilities/typeComparators.d.ts b/school/node_modules/graphql/utilities/typeComparators.d.ts new file mode 100644 index 0000000..7de3e00 --- /dev/null +++ b/school/node_modules/graphql/utilities/typeComparators.d.ts @@ -0,0 +1,32 @@ +import { GraphQLSchema } from '../type/schema'; +import { GraphQLType, GraphQLCompositeType } from '../type/definition'; + +/** + * Provided two types, return true if the types are equal (invariant). + */ +export 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 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 function doTypesOverlap( + schema: GraphQLSchema, + typeA: GraphQLCompositeType, + typeB: GraphQLCompositeType, +): boolean; diff --git a/school/node_modules/graphql/utilities/typeComparators.js b/school/node_modules/graphql/utilities/typeComparators.js new file mode 100644 index 0000000..42ad5fd --- /dev/null +++ b/school/node_modules/graphql/utilities/typeComparators.js @@ -0,0 +1,115 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isEqualType = isEqualType; +exports.isTypeSubTypeOf = isTypeSubTypeOf; +exports.doTypesOverlap = doTypesOverlap; + +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(function (type) { + return 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; +} diff --git a/school/node_modules/graphql/utilities/typeComparators.js.flow b/school/node_modules/graphql/utilities/typeComparators.js.flow new file mode 100644 index 0000000..c3b3af1 --- /dev/null +++ b/school/node_modules/graphql/utilities/typeComparators.js.flow @@ -0,0 +1,120 @@ +// @flow strict +import type { GraphQLSchema } from '../type/schema'; +import type { GraphQLType, GraphQLCompositeType } from '../type/definition'; +import { + isInterfaceType, + isObjectType, + isListType, + isNonNullType, + isAbstractType, +} from '../type/definition'; + +/** + * Provided two types, return true if the types are equal (invariant). + */ +export function isEqualType(typeA: GraphQLType, typeB: GraphQLType): boolean { + // 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: GraphQLSchema, + maybeSubType: GraphQLType, + superType: GraphQLType, +): boolean { + // 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: GraphQLSchema, + typeA: GraphQLCompositeType, + typeB: GraphQLCompositeType, +): boolean { + // 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; +} diff --git a/school/node_modules/graphql/utilities/typeComparators.mjs b/school/node_modules/graphql/utilities/typeComparators.mjs new file mode 100644 index 0000000..ad3288a --- /dev/null +++ b/school/node_modules/graphql/utilities/typeComparators.mjs @@ -0,0 +1,104 @@ +import { isInterfaceType, isObjectType, isListType, isNonNullType, isAbstractType } 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(function (type) { + return 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; +} diff --git a/school/node_modules/graphql/utilities/typeFromAST.d.ts b/school/node_modules/graphql/utilities/typeFromAST.d.ts new file mode 100644 index 0000000..cf32ac7 --- /dev/null +++ b/school/node_modules/graphql/utilities/typeFromAST.d.ts @@ -0,0 +1,29 @@ +import { NamedTypeNode, ListTypeNode, NonNullTypeNode } from '../language/ast'; +import { GraphQLSchema } from '../type/schema'; +import { + GraphQLNamedType, + GraphQLList, + GraphQLNonNull, +} from '../type/definition'; + +/** + * 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 function typeFromAST( + schema: GraphQLSchema, + typeNode: NamedTypeNode, +): GraphQLNamedType | undefined; + +export function typeFromAST( + schema: GraphQLSchema, + typeNode: ListTypeNode, +): GraphQLList<any> | undefined; + +export function typeFromAST( + schema: GraphQLSchema, + typeNode: NonNullTypeNode, +): GraphQLNonNull<any> | undefined; diff --git a/school/node_modules/graphql/utilities/typeFromAST.js b/school/node_modules/graphql/utilities/typeFromAST.js new file mode 100644 index 0000000..5e85944 --- /dev/null +++ b/school/node_modules/graphql/utilities/typeFromAST.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.typeFromAST = typeFromAST; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _kinds = require("../language/kinds.js"); + +var _definition = require("../type/definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function typeFromAST(schema, typeNode) { + /* eslint-enable no-redeclare */ + var innerType; + + if (typeNode.kind === _kinds.Kind.LIST_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLList(innerType); + } + + if (typeNode.kind === _kinds.Kind.NON_NULL_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLNonNull(innerType); + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if (typeNode.kind === _kinds.Kind.NAMED_TYPE) { + return schema.getType(typeNode.name.value); + } // istanbul ignore next (Not reachable. All possible type nodes have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected type node: ' + (0, _inspect.default)(typeNode)); +} diff --git a/school/node_modules/graphql/utilities/typeFromAST.js.flow b/school/node_modules/graphql/utilities/typeFromAST.js.flow new file mode 100644 index 0000000..a8450d8 --- /dev/null +++ b/school/node_modules/graphql/utilities/typeFromAST.js.flow @@ -0,0 +1,55 @@ +// @flow strict +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; + +import type { + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, +} from '../language/ast'; + +import { Kind } from '../language/kinds'; + +import type { GraphQLSchema } from '../type/schema'; +import type { GraphQLNamedType } from '../type/definition'; +import { GraphQLList, GraphQLNonNull } from '../type/definition'; + +/** + * 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. + */ +/* eslint-disable no-redeclare */ +declare function typeFromAST( + schema: GraphQLSchema, + typeNode: NamedTypeNode, +): GraphQLNamedType | void; +declare function typeFromAST( + schema: GraphQLSchema, + typeNode: ListTypeNode, +): GraphQLList<any> | void; +declare function typeFromAST( + schema: GraphQLSchema, + typeNode: NonNullTypeNode, +): GraphQLNonNull<any> | void; +export function typeFromAST(schema, typeNode) { + /* eslint-enable no-redeclare */ + let innerType; + if (typeNode.kind === Kind.LIST_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && new GraphQLList(innerType); + } + if (typeNode.kind === Kind.NON_NULL_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && new GraphQLNonNull(innerType); + } + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + if (typeNode.kind === Kind.NAMED_TYPE) { + return schema.getType(typeNode.name.value); + } + + // istanbul ignore next (Not reachable. All possible type nodes have been considered) + invariant(false, 'Unexpected type node: ' + inspect((typeNode: empty))); +} diff --git a/school/node_modules/graphql/utilities/typeFromAST.mjs b/school/node_modules/graphql/utilities/typeFromAST.mjs new file mode 100644 index 0000000..740cfeb --- /dev/null +++ b/school/node_modules/graphql/utilities/typeFromAST.mjs @@ -0,0 +1,36 @@ +import inspect from "../jsutils/inspect.mjs"; +import invariant from "../jsutils/invariant.mjs"; +import { Kind } from "../language/kinds.mjs"; +import { GraphQLList, GraphQLNonNull } from "../type/definition.mjs"; +/** + * 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. + */ + +/* eslint-disable no-redeclare */ + +export function typeFromAST(schema, typeNode) { + /* eslint-enable no-redeclare */ + var innerType; + + if (typeNode.kind === Kind.LIST_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && new GraphQLList(innerType); + } + + if (typeNode.kind === Kind.NON_NULL_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && new GraphQLNonNull(innerType); + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if (typeNode.kind === Kind.NAMED_TYPE) { + return schema.getType(typeNode.name.value); + } // istanbul ignore next (Not reachable. All possible type nodes have been considered) + + + false || invariant(0, 'Unexpected type node: ' + inspect(typeNode)); +} diff --git a/school/node_modules/graphql/utilities/typedQueryDocumentNode.d.ts b/school/node_modules/graphql/utilities/typedQueryDocumentNode.d.ts new file mode 100644 index 0000000..0d7b8de --- /dev/null +++ b/school/node_modules/graphql/utilities/typedQueryDocumentNode.d.ts @@ -0,0 +1,20 @@ +import { DocumentNode, ExecutableDefinitionNode } from '../language/ast'; + +/** + * Wrapper type that contains DocumentNode and types that can be deduced from it. + */ +export interface TypedQueryDocumentNode< + TResponseData = Record<string, any>, + TRequestVariables = Record<string, any> +> extends DocumentNode { + readonly definitions: ReadonlyArray<ExecutableDefinitionNode>; + // FIXME: remove once TS implements proper way to enforce nominal typing + /** + * 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; +} diff --git a/school/node_modules/graphql/utilities/valueFromAST.d.ts b/school/node_modules/graphql/utilities/valueFromAST.d.ts new file mode 100644 index 0000000..acde6ba --- /dev/null +++ b/school/node_modules/graphql/utilities/valueFromAST.d.ts @@ -0,0 +1,30 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { ValueNode } from '../language/ast'; +import { 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 | Mixed | + * | NullValue | null | + * + */ +export function valueFromAST( + valueNode: Maybe<ValueNode>, + type: GraphQLInputType, + variables?: Maybe<{ [key: string]: any }>, +): any; diff --git a/school/node_modules/graphql/utilities/valueFromAST.js b/school/node_modules/graphql/utilities/valueFromAST.js new file mode 100644 index 0000000..0b0230c --- /dev/null +++ b/school/node_modules/graphql/utilities/valueFromAST.js @@ -0,0 +1,186 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.valueFromAST = valueFromAST; + +var _objectValues3 = _interopRequireDefault(require("../polyfills/objectValues.js")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap.js")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _kinds = require("../language/kinds.js"); + +var _definition = require("../type/definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * 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 | Mixed | + * | 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) { + var variableName = valueNode.name.value; + + if (variables == null || variables[variableName] === undefined) { + // No valid return value. + return; + } + + var 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)) { + var itemType = type.ofType; + + if (valueNode.kind === _kinds.Kind.LIST) { + var coercedValues = []; + + for (var _i2 = 0, _valueNode$values2 = valueNode.values; _i2 < _valueNode$values2.length; _i2++) { + var itemNode = _valueNode$values2[_i2]; + + 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 { + var itemValue = valueFromAST(itemNode, itemType, variables); + + if (itemValue === undefined) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(itemValue); + } + } + + return coercedValues; + } + + var 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. + } + + var coercedObj = Object.create(null); + var fieldNodes = (0, _keyMap.default)(valueNode.fields, function (field) { + return field.name.value; + }); + + for (var _i4 = 0, _objectValues2 = (0, _objectValues3.default)(type.getFields()); _i4 < _objectValues2.length; _i4++) { + var field = _objectValues2[_i4]; + var 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; + } + + var fieldValue = valueFromAST(fieldNode.value, field.type, variables); + + if (fieldValue === undefined) { + return; // Invalid: intentionally return no value. + } + + coercedObj[field.name] = fieldValue; + } + + return coercedObj; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + 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. + var 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; + } // istanbul ignore next (Not reachable. All possible input types have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected input type: ' + (0, _inspect.default)(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); +} diff --git a/school/node_modules/graphql/utilities/valueFromAST.js.flow b/school/node_modules/graphql/utilities/valueFromAST.js.flow new file mode 100644 index 0000000..23d5588 --- /dev/null +++ b/school/node_modules/graphql/utilities/valueFromAST.js.flow @@ -0,0 +1,164 @@ +// @flow strict +import objectValues from '../polyfills/objectValues'; + +import type { ObjMap } from '../jsutils/ObjMap'; +import keyMap from '../jsutils/keyMap'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; + +import type { ValueNode } from '../language/ast'; +import { Kind } from '../language/kinds'; + +import type { GraphQLInputType } from '../type/definition'; +import { + isLeafType, + isInputObjectType, + isListType, + isNonNullType, +} 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 | Mixed | + * | NullValue | null | + * + */ +export function valueFromAST( + valueNode: ?ValueNode, + type: GraphQLInputType, + variables?: ?ObjMap<mixed>, +): mixed | void { + 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 objectValues(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; + } + + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + 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; + } + + // istanbul ignore next (Not reachable. All possible input types have been considered) + invariant(false, 'Unexpected input type: ' + inspect((type: empty))); +} + +// Returns true if the provided valueNode is a variable which is not defined +// in the set of variables. +function isMissingVariable( + valueNode: ValueNode, + variables: ?ObjMap<mixed>, +): boolean { + return ( + valueNode.kind === Kind.VARIABLE && + (variables == null || variables[valueNode.name.value] === undefined) + ); +} diff --git a/school/node_modules/graphql/utilities/valueFromAST.mjs b/school/node_modules/graphql/utilities/valueFromAST.mjs new file mode 100644 index 0000000..5879ea7 --- /dev/null +++ b/school/node_modules/graphql/utilities/valueFromAST.mjs @@ -0,0 +1,171 @@ +import objectValues from "../polyfills/objectValues.mjs"; +import keyMap from "../jsutils/keyMap.mjs"; +import inspect from "../jsutils/inspect.mjs"; +import invariant from "../jsutils/invariant.mjs"; +import { Kind } from "../language/kinds.mjs"; +import { isLeafType, isInputObjectType, 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 | Mixed | + * | 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) { + var variableName = valueNode.name.value; + + if (variables == null || variables[variableName] === undefined) { + // No valid return value. + return; + } + + var 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)) { + var itemType = type.ofType; + + if (valueNode.kind === Kind.LIST) { + var coercedValues = []; + + for (var _i2 = 0, _valueNode$values2 = valueNode.values; _i2 < _valueNode$values2.length; _i2++) { + var itemNode = _valueNode$values2[_i2]; + + 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 { + var itemValue = valueFromAST(itemNode, itemType, variables); + + if (itemValue === undefined) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(itemValue); + } + } + + return coercedValues; + } + + var 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. + } + + var coercedObj = Object.create(null); + var fieldNodes = keyMap(valueNode.fields, function (field) { + return field.name.value; + }); + + for (var _i4 = 0, _objectValues2 = objectValues(type.getFields()); _i4 < _objectValues2.length; _i4++) { + var field = _objectValues2[_i4]; + var 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; + } + + var fieldValue = valueFromAST(fieldNode.value, field.type, variables); + + if (fieldValue === undefined) { + return; // Invalid: intentionally return no value. + } + + coercedObj[field.name] = fieldValue; + } + + return coercedObj; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + 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. + var 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; + } // istanbul ignore next (Not reachable. All possible input types have been considered) + + + false || invariant(0, '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); +} diff --git a/school/node_modules/graphql/utilities/valueFromASTUntyped.d.ts b/school/node_modules/graphql/utilities/valueFromASTUntyped.d.ts new file mode 100644 index 0000000..a44959d --- /dev/null +++ b/school/node_modules/graphql/utilities/valueFromASTUntyped.d.ts @@ -0,0 +1,24 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { 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 function valueFromASTUntyped( + valueNode: ValueNode, + variables?: Maybe<{ [key: string]: any }>, +): any; diff --git a/school/node_modules/graphql/utilities/valueFromASTUntyped.js b/school/node_modules/graphql/utilities/valueFromASTUntyped.js new file mode 100644 index 0000000..5cdb413 --- /dev/null +++ b/school/node_modules/graphql/utilities/valueFromASTUntyped.js @@ -0,0 +1,68 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.valueFromASTUntyped = valueFromASTUntyped; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect.js")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant.js")); + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap.js")); + +var _kinds = require("../language/kinds.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * 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(function (node) { + return valueFromASTUntyped(node, variables); + }); + + case _kinds.Kind.OBJECT: + return (0, _keyValMap.default)(valueNode.fields, function (field) { + return field.name.value; + }, function (field) { + return valueFromASTUntyped(field.value, variables); + }); + + case _kinds.Kind.VARIABLE: + return variables === null || variables === void 0 ? void 0 : variables[valueNode.name.value]; + } // istanbul ignore next (Not reachable. All possible value nodes have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected value node: ' + (0, _inspect.default)(valueNode)); +} diff --git a/school/node_modules/graphql/utilities/valueFromASTUntyped.js.flow b/school/node_modules/graphql/utilities/valueFromASTUntyped.js.flow new file mode 100644 index 0000000..e98779d --- /dev/null +++ b/school/node_modules/graphql/utilities/valueFromASTUntyped.js.flow @@ -0,0 +1,57 @@ +// @flow strict +import type { ObjMap } from '../jsutils/ObjMap'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyValMap from '../jsutils/keyValMap'; + +import { Kind } from '../language/kinds'; +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 function valueFromASTUntyped( + valueNode: ValueNode, + variables?: ?ObjMap<mixed>, +): mixed { + 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?.[valueNode.name.value]; + } + + // istanbul ignore next (Not reachable. All possible value nodes have been considered) + invariant(false, 'Unexpected value node: ' + inspect((valueNode: empty))); +} diff --git a/school/node_modules/graphql/utilities/valueFromASTUntyped.mjs b/school/node_modules/graphql/utilities/valueFromASTUntyped.mjs new file mode 100644 index 0000000..e70622c --- /dev/null +++ b/school/node_modules/graphql/utilities/valueFromASTUntyped.mjs @@ -0,0 +1,56 @@ +import inspect from "../jsutils/inspect.mjs"; +import invariant from "../jsutils/invariant.mjs"; +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(function (node) { + return valueFromASTUntyped(node, variables); + }); + + case Kind.OBJECT: + return keyValMap(valueNode.fields, function (field) { + return field.name.value; + }, function (field) { + return valueFromASTUntyped(field.value, variables); + }); + + case Kind.VARIABLE: + return variables === null || variables === void 0 ? void 0 : variables[valueNode.name.value]; + } // istanbul ignore next (Not reachable. All possible value nodes have been considered) + + + false || invariant(0, 'Unexpected value node: ' + inspect(valueNode)); +} diff --git a/school/node_modules/graphql/validation/ValidationContext.d.ts b/school/node_modules/graphql/validation/ValidationContext.d.ts new file mode 100644 index 0000000..e0ca546 --- /dev/null +++ b/school/node_modules/graphql/validation/ValidationContext.d.ts @@ -0,0 +1,98 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { GraphQLError } from '../error/GraphQLError'; +import { ASTVisitor } from '../language/visitor'; +import { + DocumentNode, + OperationDefinitionNode, + VariableNode, + SelectionSetNode, + FragmentSpreadNode, + FragmentDefinitionNode, +} from '../language/ast'; +import { GraphQLSchema } from '../type/schema'; +import { GraphQLDirective } from '../type/directives'; +import { + GraphQLInputType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, + GraphQLArgument, + GraphQLEnumValue, +} from '../type/definition'; +import { TypeInfo } from '../utilities/TypeInfo'; + +type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; +interface VariableUsage { + readonly node: VariableNode; + readonly type: Maybe<GraphQLInputType>; + readonly defaultValue: Maybe<any>; +} + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +export class ASTValidationContext { + constructor(ast: DocumentNode, onError: (err: GraphQLError) => void); + + reportError(error: GraphQLError): undefined; + + getDocument(): DocumentNode; + + getFragment(name: string): Maybe<FragmentDefinitionNode>; + + getFragmentSpreads(node: SelectionSetNode): ReadonlyArray<FragmentSpreadNode>; + + getRecursivelyReferencedFragments( + operation: OperationDefinitionNode, + ): ReadonlyArray<FragmentDefinitionNode>; +} + +export class SDLValidationContext extends ASTValidationContext { + constructor( + ast: DocumentNode, + schema: Maybe<GraphQLSchema>, + onError: (err: GraphQLError) => void, + ); + + getSchema(): Maybe<GraphQLSchema>; +} + +export type SDLValidationRule = (context: SDLValidationContext) => ASTVisitor; + +export class ValidationContext extends ASTValidationContext { + constructor( + schema: GraphQLSchema, + ast: DocumentNode, + typeInfo: TypeInfo, + onError: (err: GraphQLError) => void, + ); + + getSchema(): GraphQLSchema; + + getVariableUsages(node: NodeWithSelectionSet): ReadonlyArray<VariableUsage>; + + getRecursivelyReferencedFragments( + operation: OperationDefinitionNode, + ): ReadonlyArray<FragmentDefinitionNode>; + + getType(): Maybe<GraphQLOutputType>; + + getParentType(): Maybe<GraphQLCompositeType>; + + getInputType(): Maybe<GraphQLInputType>; + + getParentInputType(): Maybe<GraphQLInputType>; + + getFieldDef(): Maybe<GraphQLField<any, any>>; + + getDirective(): Maybe<GraphQLDirective>; + + getArgument(): Maybe<GraphQLArgument>; + + getEnumValue(): Maybe<GraphQLEnumValue>; +} + +export type ValidationRule = (context: ValidationContext) => ASTVisitor; diff --git a/school/node_modules/graphql/validation/ValidationContext.js b/school/node_modules/graphql/validation/ValidationContext.js new file mode 100644 index 0000000..c70da64 --- /dev/null +++ b/school/node_modules/graphql/validation/ValidationContext.js @@ -0,0 +1,241 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ValidationContext = exports.SDLValidationContext = exports.ASTValidationContext = void 0; + +var _kinds = require("../language/kinds.js"); + +var _visitor = require("../language/visitor.js"); + +var _TypeInfo = require("../utilities/TypeInfo.js"); + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +var ASTValidationContext = /*#__PURE__*/function () { + function ASTValidationContext(ast, onError) { + this._ast = ast; + this._fragments = undefined; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._onError = onError; + } + + var _proto = ASTValidationContext.prototype; + + _proto.reportError = function reportError(error) { + this._onError(error); + }; + + _proto.getDocument = function getDocument() { + return this._ast; + }; + + _proto.getFragment = function getFragment(name) { + var fragments = this._fragments; + + if (!fragments) { + this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) { + if (statement.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + frags[statement.name.value] = statement; + } + + return frags; + }, Object.create(null)); + } + + return fragments[name]; + }; + + _proto.getFragmentSpreads = function getFragmentSpreads(node) { + var spreads = this._fragmentSpreads.get(node); + + if (!spreads) { + spreads = []; + var setsToVisit = [node]; + + while (setsToVisit.length !== 0) { + var set = setsToVisit.pop(); + + for (var _i2 = 0, _set$selections2 = set.selections; _i2 < _set$selections2.length; _i2++) { + var selection = _set$selections2[_i2]; + + if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + + this._fragmentSpreads.set(node, spreads); + } + + return spreads; + }; + + _proto.getRecursivelyReferencedFragments = function getRecursivelyReferencedFragments(operation) { + var fragments = this._recursivelyReferencedFragments.get(operation); + + if (!fragments) { + fragments = []; + var collectedNames = Object.create(null); + var nodesToVisit = [operation.selectionSet]; + + while (nodesToVisit.length !== 0) { + var node = nodesToVisit.pop(); + + for (var _i4 = 0, _this$getFragmentSpre2 = this.getFragmentSpreads(node); _i4 < _this$getFragmentSpre2.length; _i4++) { + var spread = _this$getFragmentSpre2[_i4]; + var fragName = spread.name.value; + + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + var fragment = this.getFragment(fragName); + + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + + this._recursivelyReferencedFragments.set(operation, fragments); + } + + return fragments; + }; + + return ASTValidationContext; +}(); + +exports.ASTValidationContext = ASTValidationContext; + +var SDLValidationContext = /*#__PURE__*/function (_ASTValidationContext) { + _inheritsLoose(SDLValidationContext, _ASTValidationContext); + + function SDLValidationContext(ast, schema, onError) { + var _this; + + _this = _ASTValidationContext.call(this, ast, onError) || this; + _this._schema = schema; + return _this; + } + + var _proto2 = SDLValidationContext.prototype; + + _proto2.getSchema = function getSchema() { + return this._schema; + }; + + return SDLValidationContext; +}(ASTValidationContext); + +exports.SDLValidationContext = SDLValidationContext; + +var ValidationContext = /*#__PURE__*/function (_ASTValidationContext2) { + _inheritsLoose(ValidationContext, _ASTValidationContext2); + + function ValidationContext(schema, ast, typeInfo, onError) { + var _this2; + + _this2 = _ASTValidationContext2.call(this, ast, onError) || this; + _this2._schema = schema; + _this2._typeInfo = typeInfo; + _this2._variableUsages = new Map(); + _this2._recursiveVariableUsages = new Map(); + return _this2; + } + + var _proto3 = ValidationContext.prototype; + + _proto3.getSchema = function getSchema() { + return this._schema; + }; + + _proto3.getVariableUsages = function getVariableUsages(node) { + var usages = this._variableUsages.get(node); + + if (!usages) { + var newUsages = []; + var typeInfo = new _TypeInfo.TypeInfo(this._schema); + (0, _visitor.visit)(node, (0, _TypeInfo.visitWithTypeInfo)(typeInfo, { + VariableDefinition: function VariableDefinition() { + return false; + }, + Variable: function Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue() + }); + } + })); + usages = newUsages; + + this._variableUsages.set(node, usages); + } + + return usages; + }; + + _proto3.getRecursiveVariableUsages = function getRecursiveVariableUsages(operation) { + var usages = this._recursiveVariableUsages.get(operation); + + if (!usages) { + usages = this.getVariableUsages(operation); + + for (var _i6 = 0, _this$getRecursivelyR2 = this.getRecursivelyReferencedFragments(operation); _i6 < _this$getRecursivelyR2.length; _i6++) { + var frag = _this$getRecursivelyR2[_i6]; + usages = usages.concat(this.getVariableUsages(frag)); + } + + this._recursiveVariableUsages.set(operation, usages); + } + + return usages; + }; + + _proto3.getType = function getType() { + return this._typeInfo.getType(); + }; + + _proto3.getParentType = function getParentType() { + return this._typeInfo.getParentType(); + }; + + _proto3.getInputType = function getInputType() { + return this._typeInfo.getInputType(); + }; + + _proto3.getParentInputType = function getParentInputType() { + return this._typeInfo.getParentInputType(); + }; + + _proto3.getFieldDef = function getFieldDef() { + return this._typeInfo.getFieldDef(); + }; + + _proto3.getDirective = function getDirective() { + return this._typeInfo.getDirective(); + }; + + _proto3.getArgument = function getArgument() { + return this._typeInfo.getArgument(); + }; + + _proto3.getEnumValue = function getEnumValue() { + return this._typeInfo.getEnumValue(); + }; + + return ValidationContext; +}(ASTValidationContext); + +exports.ValidationContext = ValidationContext; diff --git a/school/node_modules/graphql/validation/ValidationContext.js.flow b/school/node_modules/graphql/validation/ValidationContext.js.flow new file mode 100644 index 0000000..dabe4ba --- /dev/null +++ b/school/node_modules/graphql/validation/ValidationContext.js.flow @@ -0,0 +1,254 @@ +// @flow strict +import type { ObjMap } from '../jsutils/ObjMap'; + +import type { GraphQLError } from '../error/GraphQLError'; + +import type { ASTVisitor } from '../language/visitor'; +import type { + DocumentNode, + OperationDefinitionNode, + VariableNode, + SelectionSetNode, + FragmentSpreadNode, + FragmentDefinitionNode, +} from '../language/ast'; + +import { Kind } from '../language/kinds'; +import { visit } from '../language/visitor'; + +import type { GraphQLSchema } from '../type/schema'; +import type { GraphQLDirective } from '../type/directives'; +import type { + GraphQLInputType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, + GraphQLArgument, + GraphQLEnumValue, +} from '../type/definition'; + +import { TypeInfo, visitWithTypeInfo } from '../utilities/TypeInfo'; + +type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; +type VariableUsage = {| + +node: VariableNode, + +type: ?GraphQLInputType, + +defaultValue: ?mixed, +|}; + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +export class ASTValidationContext { + _ast: DocumentNode; + _onError: (err: GraphQLError) => void; + _fragments: ?ObjMap<FragmentDefinitionNode>; + _fragmentSpreads: Map<SelectionSetNode, $ReadOnlyArray<FragmentSpreadNode>>; + _recursivelyReferencedFragments: Map< + OperationDefinitionNode, + $ReadOnlyArray<FragmentDefinitionNode>, + >; + + constructor(ast: DocumentNode, onError: (err: GraphQLError) => void) { + this._ast = ast; + this._fragments = undefined; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._onError = onError; + } + + reportError(error: GraphQLError): void { + this._onError(error); + } + + getDocument(): DocumentNode { + return this._ast; + } + + getFragment(name: string): ?FragmentDefinitionNode { + let fragments = this._fragments; + if (!fragments) { + this._fragments = fragments = this.getDocument().definitions.reduce( + (frags, statement) => { + if (statement.kind === Kind.FRAGMENT_DEFINITION) { + frags[statement.name.value] = statement; + } + return frags; + }, + Object.create(null), + ); + } + return fragments[name]; + } + + getFragmentSpreads( + node: SelectionSetNode, + ): $ReadOnlyArray<FragmentSpreadNode> { + let spreads = this._fragmentSpreads.get(node); + if (!spreads) { + spreads = []; + const setsToVisit: Array<SelectionSetNode> = [node]; + while (setsToVisit.length !== 0) { + const set = setsToVisit.pop(); + for (const selection of set.selections) { + if (selection.kind === Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + this._fragmentSpreads.set(node, spreads); + } + return spreads; + } + + getRecursivelyReferencedFragments( + operation: OperationDefinitionNode, + ): $ReadOnlyArray<FragmentDefinitionNode> { + let fragments = this._recursivelyReferencedFragments.get(operation); + if (!fragments) { + fragments = []; + const collectedNames = Object.create(null); + const nodesToVisit: Array<SelectionSetNode> = [operation.selectionSet]; + while (nodesToVisit.length !== 0) { + const node = nodesToVisit.pop(); + for (const spread of this.getFragmentSpreads(node)) { + const fragName = spread.name.value; + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + const fragment = this.getFragment(fragName); + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + this._recursivelyReferencedFragments.set(operation, fragments); + } + return fragments; + } +} + +export type ASTValidationRule = (ASTValidationContext) => ASTVisitor; + +export class SDLValidationContext extends ASTValidationContext { + _schema: ?GraphQLSchema; + + constructor( + ast: DocumentNode, + schema: ?GraphQLSchema, + onError: (err: GraphQLError) => void, + ) { + super(ast, onError); + this._schema = schema; + } + + getSchema(): ?GraphQLSchema { + return this._schema; + } +} + +export type SDLValidationRule = (SDLValidationContext) => ASTVisitor; + +export class ValidationContext extends ASTValidationContext { + _schema: GraphQLSchema; + _typeInfo: TypeInfo; + _variableUsages: Map<NodeWithSelectionSet, $ReadOnlyArray<VariableUsage>>; + _recursiveVariableUsages: Map< + OperationDefinitionNode, + $ReadOnlyArray<VariableUsage>, + >; + + constructor( + schema: GraphQLSchema, + ast: DocumentNode, + typeInfo: TypeInfo, + onError: (err: GraphQLError) => void, + ) { + super(ast, onError); + this._schema = schema; + this._typeInfo = typeInfo; + this._variableUsages = new Map(); + this._recursiveVariableUsages = new Map(); + } + + getSchema(): GraphQLSchema { + return this._schema; + } + + getVariableUsages(node: NodeWithSelectionSet): $ReadOnlyArray<VariableUsage> { + let usages = this._variableUsages.get(node); + if (!usages) { + const newUsages = []; + const typeInfo = new TypeInfo(this._schema); + visit( + node, + visitWithTypeInfo(typeInfo, { + VariableDefinition: () => false, + Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue(), + }); + }, + }), + ); + usages = newUsages; + this._variableUsages.set(node, usages); + } + return usages; + } + + getRecursiveVariableUsages( + operation: OperationDefinitionNode, + ): $ReadOnlyArray<VariableUsage> { + let usages = this._recursiveVariableUsages.get(operation); + if (!usages) { + usages = this.getVariableUsages(operation); + for (const frag of this.getRecursivelyReferencedFragments(operation)) { + usages = usages.concat(this.getVariableUsages(frag)); + } + this._recursiveVariableUsages.set(operation, usages); + } + return usages; + } + + getType(): ?GraphQLOutputType { + return this._typeInfo.getType(); + } + + getParentType(): ?GraphQLCompositeType { + return this._typeInfo.getParentType(); + } + + getInputType(): ?GraphQLInputType { + return this._typeInfo.getInputType(); + } + + getParentInputType(): ?GraphQLInputType { + return this._typeInfo.getParentInputType(); + } + + getFieldDef(): ?GraphQLField<mixed, mixed> { + return this._typeInfo.getFieldDef(); + } + + getDirective(): ?GraphQLDirective { + return this._typeInfo.getDirective(); + } + + getArgument(): ?GraphQLArgument { + return this._typeInfo.getArgument(); + } + + getEnumValue(): ?GraphQLEnumValue { + return this._typeInfo.getEnumValue(); + } +} + +export type ValidationRule = (ValidationContext) => ASTVisitor; diff --git a/school/node_modules/graphql/validation/ValidationContext.mjs b/school/node_modules/graphql/validation/ValidationContext.mjs new file mode 100644 index 0000000..5572265 --- /dev/null +++ b/school/node_modules/graphql/validation/ValidationContext.mjs @@ -0,0 +1,224 @@ +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +import { Kind } from "../language/kinds.mjs"; +import { visit } from "../language/visitor.mjs"; +import { TypeInfo, visitWithTypeInfo } from "../utilities/TypeInfo.mjs"; + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +export var ASTValidationContext = /*#__PURE__*/function () { + function ASTValidationContext(ast, onError) { + this._ast = ast; + this._fragments = undefined; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._onError = onError; + } + + var _proto = ASTValidationContext.prototype; + + _proto.reportError = function reportError(error) { + this._onError(error); + }; + + _proto.getDocument = function getDocument() { + return this._ast; + }; + + _proto.getFragment = function getFragment(name) { + var fragments = this._fragments; + + if (!fragments) { + this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) { + if (statement.kind === Kind.FRAGMENT_DEFINITION) { + frags[statement.name.value] = statement; + } + + return frags; + }, Object.create(null)); + } + + return fragments[name]; + }; + + _proto.getFragmentSpreads = function getFragmentSpreads(node) { + var spreads = this._fragmentSpreads.get(node); + + if (!spreads) { + spreads = []; + var setsToVisit = [node]; + + while (setsToVisit.length !== 0) { + var set = setsToVisit.pop(); + + for (var _i2 = 0, _set$selections2 = set.selections; _i2 < _set$selections2.length; _i2++) { + var selection = _set$selections2[_i2]; + + if (selection.kind === Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + + this._fragmentSpreads.set(node, spreads); + } + + return spreads; + }; + + _proto.getRecursivelyReferencedFragments = function getRecursivelyReferencedFragments(operation) { + var fragments = this._recursivelyReferencedFragments.get(operation); + + if (!fragments) { + fragments = []; + var collectedNames = Object.create(null); + var nodesToVisit = [operation.selectionSet]; + + while (nodesToVisit.length !== 0) { + var node = nodesToVisit.pop(); + + for (var _i4 = 0, _this$getFragmentSpre2 = this.getFragmentSpreads(node); _i4 < _this$getFragmentSpre2.length; _i4++) { + var spread = _this$getFragmentSpre2[_i4]; + var fragName = spread.name.value; + + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + var fragment = this.getFragment(fragName); + + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + + this._recursivelyReferencedFragments.set(operation, fragments); + } + + return fragments; + }; + + return ASTValidationContext; +}(); +export var SDLValidationContext = /*#__PURE__*/function (_ASTValidationContext) { + _inheritsLoose(SDLValidationContext, _ASTValidationContext); + + function SDLValidationContext(ast, schema, onError) { + var _this; + + _this = _ASTValidationContext.call(this, ast, onError) || this; + _this._schema = schema; + return _this; + } + + var _proto2 = SDLValidationContext.prototype; + + _proto2.getSchema = function getSchema() { + return this._schema; + }; + + return SDLValidationContext; +}(ASTValidationContext); +export var ValidationContext = /*#__PURE__*/function (_ASTValidationContext2) { + _inheritsLoose(ValidationContext, _ASTValidationContext2); + + function ValidationContext(schema, ast, typeInfo, onError) { + var _this2; + + _this2 = _ASTValidationContext2.call(this, ast, onError) || this; + _this2._schema = schema; + _this2._typeInfo = typeInfo; + _this2._variableUsages = new Map(); + _this2._recursiveVariableUsages = new Map(); + return _this2; + } + + var _proto3 = ValidationContext.prototype; + + _proto3.getSchema = function getSchema() { + return this._schema; + }; + + _proto3.getVariableUsages = function getVariableUsages(node) { + var usages = this._variableUsages.get(node); + + if (!usages) { + var newUsages = []; + var typeInfo = new TypeInfo(this._schema); + visit(node, visitWithTypeInfo(typeInfo, { + VariableDefinition: function VariableDefinition() { + return false; + }, + Variable: function Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue() + }); + } + })); + usages = newUsages; + + this._variableUsages.set(node, usages); + } + + return usages; + }; + + _proto3.getRecursiveVariableUsages = function getRecursiveVariableUsages(operation) { + var usages = this._recursiveVariableUsages.get(operation); + + if (!usages) { + usages = this.getVariableUsages(operation); + + for (var _i6 = 0, _this$getRecursivelyR2 = this.getRecursivelyReferencedFragments(operation); _i6 < _this$getRecursivelyR2.length; _i6++) { + var frag = _this$getRecursivelyR2[_i6]; + usages = usages.concat(this.getVariableUsages(frag)); + } + + this._recursiveVariableUsages.set(operation, usages); + } + + return usages; + }; + + _proto3.getType = function getType() { + return this._typeInfo.getType(); + }; + + _proto3.getParentType = function getParentType() { + return this._typeInfo.getParentType(); + }; + + _proto3.getInputType = function getInputType() { + return this._typeInfo.getInputType(); + }; + + _proto3.getParentInputType = function getParentInputType() { + return this._typeInfo.getParentInputType(); + }; + + _proto3.getFieldDef = function getFieldDef() { + return this._typeInfo.getFieldDef(); + }; + + _proto3.getDirective = function getDirective() { + return this._typeInfo.getDirective(); + }; + + _proto3.getArgument = function getArgument() { + return this._typeInfo.getArgument(); + }; + + _proto3.getEnumValue = function getEnumValue() { + return this._typeInfo.getEnumValue(); + }; + + return ValidationContext; +}(ASTValidationContext); diff --git a/school/node_modules/graphql/validation/index.d.ts b/school/node_modules/graphql/validation/index.d.ts new file mode 100644 index 0000000..f049bf3 --- /dev/null +++ b/school/node_modules/graphql/validation/index.d.ts @@ -0,0 +1,96 @@ +export { validate } from './validate'; + +export { ValidationContext, ValidationRule } from './ValidationContext'; + +export { specifiedRules } from './specifiedRules'; + +// Spec Section: "Executable Definitions" +export { ExecutableDefinitionsRule } from './rules/ExecutableDefinitionsRule'; + +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +export { FieldsOnCorrectTypeRule } from './rules/FieldsOnCorrectTypeRule'; + +// Spec Section: "Fragments on Composite Types" +export { FragmentsOnCompositeTypesRule } from './rules/FragmentsOnCompositeTypesRule'; + +// Spec Section: "Argument Names" +export { KnownArgumentNamesRule } from './rules/KnownArgumentNamesRule'; + +// Spec Section: "Directives Are Defined" +export { KnownDirectivesRule } from './rules/KnownDirectivesRule'; + +// Spec Section: "Fragment spread target defined" +export { KnownFragmentNamesRule } from './rules/KnownFragmentNamesRule'; + +// Spec Section: "Fragment Spread Type Existence" +export { KnownTypeNamesRule } from './rules/KnownTypeNamesRule'; + +// Spec Section: "Lone Anonymous Operation" +export { LoneAnonymousOperationRule } from './rules/LoneAnonymousOperationRule'; + +// Spec Section: "Fragments must not form cycles" +export { NoFragmentCyclesRule } from './rules/NoFragmentCyclesRule'; + +// Spec Section: "All Variable Used Defined" +export { NoUndefinedVariablesRule } from './rules/NoUndefinedVariablesRule'; + +// Spec Section: "Fragments must be used" +export { NoUnusedFragmentsRule } from './rules/NoUnusedFragmentsRule'; + +// Spec Section: "All Variables Used" +export { NoUnusedVariablesRule } from './rules/NoUnusedVariablesRule'; + +// Spec Section: "Field Selection Merging" +export { OverlappingFieldsCanBeMergedRule } from './rules/OverlappingFieldsCanBeMergedRule'; + +// Spec Section: "Fragment spread is possible" +export { PossibleFragmentSpreadsRule } from './rules/PossibleFragmentSpreadsRule'; + +// Spec Section: "Argument Optionality" +export { ProvidedRequiredArgumentsRule } from './rules/ProvidedRequiredArgumentsRule'; + +// Spec Section: "Leaf Field Selections" +export { ScalarLeafsRule } from './rules/ScalarLeafsRule'; + +// Spec Section: "Subscriptions with Single Root Field" +export { SingleFieldSubscriptionsRule } from './rules/SingleFieldSubscriptionsRule'; + +// Spec Section: "Argument Uniqueness" +export { UniqueArgumentNamesRule } from './rules/UniqueArgumentNamesRule'; + +// Spec Section: "Directives Are Unique Per Location" +export { UniqueDirectivesPerLocationRule } from './rules/UniqueDirectivesPerLocationRule'; + +// Spec Section: "Fragment Name Uniqueness" +export { UniqueFragmentNamesRule } from './rules/UniqueFragmentNamesRule'; + +// Spec Section: "Input Object Field Uniqueness" +export { UniqueInputFieldNamesRule } from './rules/UniqueInputFieldNamesRule'; + +// Spec Section: "Operation Name Uniqueness" +export { UniqueOperationNamesRule } from './rules/UniqueOperationNamesRule'; + +// Spec Section: "Variable Uniqueness" +export { UniqueVariableNamesRule } from './rules/UniqueVariableNamesRule'; + +// Spec Section: "Values Type Correctness" +export { ValuesOfCorrectTypeRule } from './rules/ValuesOfCorrectTypeRule'; + +// Spec Section: "Variables are Input Types" +export { VariablesAreInputTypesRule } from './rules/VariablesAreInputTypesRule'; + +// Spec Section: "All Variable Usages Are Allowed" +export { VariablesInAllowedPositionRule } from './rules/VariablesInAllowedPositionRule'; + +// SDL-specific validation rules +export { LoneSchemaDefinitionRule } from './rules/LoneSchemaDefinitionRule'; +export { UniqueOperationTypesRule } from './rules/UniqueOperationTypesRule'; +export { UniqueTypeNamesRule } from './rules/UniqueTypeNamesRule'; +export { UniqueEnumValueNamesRule } from './rules/UniqueEnumValueNamesRule'; +export { UniqueFieldDefinitionNamesRule } from './rules/UniqueFieldDefinitionNamesRule'; +export { UniqueDirectiveNamesRule } from './rules/UniqueDirectiveNamesRule'; +export { PossibleTypeExtensionsRule } from './rules/PossibleTypeExtensionsRule'; + +// Optional rules not defined by the GraphQL Specification +export { NoDeprecatedCustomRule } from './rules/custom/NoDeprecatedCustomRule'; +export { NoSchemaIntrospectionCustomRule } from './rules/custom/NoSchemaIntrospectionCustomRule'; diff --git a/school/node_modules/graphql/validation/index.js b/school/node_modules/graphql/validation/index.js new file mode 100644 index 0000000..a36e4a9 --- /dev/null +++ b/school/node_modules/graphql/validation/index.js @@ -0,0 +1,309 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function get() { + return _validate.validate; + } +}); +Object.defineProperty(exports, "ValidationContext", { + enumerable: true, + get: function get() { + return _ValidationContext.ValidationContext; + } +}); +Object.defineProperty(exports, "specifiedRules", { + enumerable: true, + get: function get() { + return _specifiedRules.specifiedRules; + } +}); +Object.defineProperty(exports, "ExecutableDefinitionsRule", { + enumerable: true, + get: function get() { + return _ExecutableDefinitionsRule.ExecutableDefinitionsRule; + } +}); +Object.defineProperty(exports, "FieldsOnCorrectTypeRule", { + enumerable: true, + get: function get() { + return _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule; + } +}); +Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", { + enumerable: true, + get: function get() { + return _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule; + } +}); +Object.defineProperty(exports, "KnownArgumentNamesRule", { + enumerable: true, + get: function get() { + return _KnownArgumentNamesRule.KnownArgumentNamesRule; + } +}); +Object.defineProperty(exports, "KnownDirectivesRule", { + enumerable: true, + get: function get() { + return _KnownDirectivesRule.KnownDirectivesRule; + } +}); +Object.defineProperty(exports, "KnownFragmentNamesRule", { + enumerable: true, + get: function get() { + return _KnownFragmentNamesRule.KnownFragmentNamesRule; + } +}); +Object.defineProperty(exports, "KnownTypeNamesRule", { + enumerable: true, + get: function get() { + return _KnownTypeNamesRule.KnownTypeNamesRule; + } +}); +Object.defineProperty(exports, "LoneAnonymousOperationRule", { + enumerable: true, + get: function get() { + return _LoneAnonymousOperationRule.LoneAnonymousOperationRule; + } +}); +Object.defineProperty(exports, "NoFragmentCyclesRule", { + enumerable: true, + get: function get() { + return _NoFragmentCyclesRule.NoFragmentCyclesRule; + } +}); +Object.defineProperty(exports, "NoUndefinedVariablesRule", { + enumerable: true, + get: function get() { + return _NoUndefinedVariablesRule.NoUndefinedVariablesRule; + } +}); +Object.defineProperty(exports, "NoUnusedFragmentsRule", { + enumerable: true, + get: function get() { + return _NoUnusedFragmentsRule.NoUnusedFragmentsRule; + } +}); +Object.defineProperty(exports, "NoUnusedVariablesRule", { + enumerable: true, + get: function get() { + return _NoUnusedVariablesRule.NoUnusedVariablesRule; + } +}); +Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", { + enumerable: true, + get: function get() { + return _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule; + } +}); +Object.defineProperty(exports, "PossibleFragmentSpreadsRule", { + enumerable: true, + get: function get() { + return _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule; + } +}); +Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", { + enumerable: true, + get: function get() { + return _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule; + } +}); +Object.defineProperty(exports, "ScalarLeafsRule", { + enumerable: true, + get: function get() { + return _ScalarLeafsRule.ScalarLeafsRule; + } +}); +Object.defineProperty(exports, "SingleFieldSubscriptionsRule", { + enumerable: true, + get: function get() { + return _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule; + } +}); +Object.defineProperty(exports, "UniqueArgumentNamesRule", { + enumerable: true, + get: function get() { + return _UniqueArgumentNamesRule.UniqueArgumentNamesRule; + } +}); +Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", { + enumerable: true, + get: function get() { + return _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule; + } +}); +Object.defineProperty(exports, "UniqueFragmentNamesRule", { + enumerable: true, + get: function get() { + return _UniqueFragmentNamesRule.UniqueFragmentNamesRule; + } +}); +Object.defineProperty(exports, "UniqueInputFieldNamesRule", { + enumerable: true, + get: function get() { + return _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule; + } +}); +Object.defineProperty(exports, "UniqueOperationNamesRule", { + enumerable: true, + get: function get() { + return _UniqueOperationNamesRule.UniqueOperationNamesRule; + } +}); +Object.defineProperty(exports, "UniqueVariableNamesRule", { + enumerable: true, + get: function get() { + return _UniqueVariableNamesRule.UniqueVariableNamesRule; + } +}); +Object.defineProperty(exports, "ValuesOfCorrectTypeRule", { + enumerable: true, + get: function get() { + return _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule; + } +}); +Object.defineProperty(exports, "VariablesAreInputTypesRule", { + enumerable: true, + get: function get() { + return _VariablesAreInputTypesRule.VariablesAreInputTypesRule; + } +}); +Object.defineProperty(exports, "VariablesInAllowedPositionRule", { + enumerable: true, + get: function get() { + return _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule; + } +}); +Object.defineProperty(exports, "LoneSchemaDefinitionRule", { + enumerable: true, + get: function get() { + return _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule; + } +}); +Object.defineProperty(exports, "UniqueOperationTypesRule", { + enumerable: true, + get: function get() { + return _UniqueOperationTypesRule.UniqueOperationTypesRule; + } +}); +Object.defineProperty(exports, "UniqueTypeNamesRule", { + enumerable: true, + get: function get() { + return _UniqueTypeNamesRule.UniqueTypeNamesRule; + } +}); +Object.defineProperty(exports, "UniqueEnumValueNamesRule", { + enumerable: true, + get: function get() { + return _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule; + } +}); +Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", { + enumerable: true, + get: function get() { + return _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule; + } +}); +Object.defineProperty(exports, "UniqueDirectiveNamesRule", { + enumerable: true, + get: function get() { + return _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule; + } +}); +Object.defineProperty(exports, "PossibleTypeExtensionsRule", { + enumerable: true, + get: function get() { + return _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule; + } +}); +Object.defineProperty(exports, "NoDeprecatedCustomRule", { + enumerable: true, + get: function get() { + return _NoDeprecatedCustomRule.NoDeprecatedCustomRule; + } +}); +Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", { + enumerable: true, + get: function get() { + return _NoSchemaIntrospectionCustomRule.NoSchemaIntrospectionCustomRule; + } +}); + +var _validate = require("./validate.js"); + +var _ValidationContext = require("./ValidationContext.js"); + +var _specifiedRules = require("./specifiedRules.js"); + +var _ExecutableDefinitionsRule = require("./rules/ExecutableDefinitionsRule.js"); + +var _FieldsOnCorrectTypeRule = require("./rules/FieldsOnCorrectTypeRule.js"); + +var _FragmentsOnCompositeTypesRule = require("./rules/FragmentsOnCompositeTypesRule.js"); + +var _KnownArgumentNamesRule = require("./rules/KnownArgumentNamesRule.js"); + +var _KnownDirectivesRule = require("./rules/KnownDirectivesRule.js"); + +var _KnownFragmentNamesRule = require("./rules/KnownFragmentNamesRule.js"); + +var _KnownTypeNamesRule = require("./rules/KnownTypeNamesRule.js"); + +var _LoneAnonymousOperationRule = require("./rules/LoneAnonymousOperationRule.js"); + +var _NoFragmentCyclesRule = require("./rules/NoFragmentCyclesRule.js"); + +var _NoUndefinedVariablesRule = require("./rules/NoUndefinedVariablesRule.js"); + +var _NoUnusedFragmentsRule = require("./rules/NoUnusedFragmentsRule.js"); + +var _NoUnusedVariablesRule = require("./rules/NoUnusedVariablesRule.js"); + +var _OverlappingFieldsCanBeMergedRule = require("./rules/OverlappingFieldsCanBeMergedRule.js"); + +var _PossibleFragmentSpreadsRule = require("./rules/PossibleFragmentSpreadsRule.js"); + +var _ProvidedRequiredArgumentsRule = require("./rules/ProvidedRequiredArgumentsRule.js"); + +var _ScalarLeafsRule = require("./rules/ScalarLeafsRule.js"); + +var _SingleFieldSubscriptionsRule = require("./rules/SingleFieldSubscriptionsRule.js"); + +var _UniqueArgumentNamesRule = require("./rules/UniqueArgumentNamesRule.js"); + +var _UniqueDirectivesPerLocationRule = require("./rules/UniqueDirectivesPerLocationRule.js"); + +var _UniqueFragmentNamesRule = require("./rules/UniqueFragmentNamesRule.js"); + +var _UniqueInputFieldNamesRule = require("./rules/UniqueInputFieldNamesRule.js"); + +var _UniqueOperationNamesRule = require("./rules/UniqueOperationNamesRule.js"); + +var _UniqueVariableNamesRule = require("./rules/UniqueVariableNamesRule.js"); + +var _ValuesOfCorrectTypeRule = require("./rules/ValuesOfCorrectTypeRule.js"); + +var _VariablesAreInputTypesRule = require("./rules/VariablesAreInputTypesRule.js"); + +var _VariablesInAllowedPositionRule = require("./rules/VariablesInAllowedPositionRule.js"); + +var _LoneSchemaDefinitionRule = require("./rules/LoneSchemaDefinitionRule.js"); + +var _UniqueOperationTypesRule = require("./rules/UniqueOperationTypesRule.js"); + +var _UniqueTypeNamesRule = require("./rules/UniqueTypeNamesRule.js"); + +var _UniqueEnumValueNamesRule = require("./rules/UniqueEnumValueNamesRule.js"); + +var _UniqueFieldDefinitionNamesRule = require("./rules/UniqueFieldDefinitionNamesRule.js"); + +var _UniqueDirectiveNamesRule = require("./rules/UniqueDirectiveNamesRule.js"); + +var _PossibleTypeExtensionsRule = require("./rules/PossibleTypeExtensionsRule.js"); + +var _NoDeprecatedCustomRule = require("./rules/custom/NoDeprecatedCustomRule.js"); + +var _NoSchemaIntrospectionCustomRule = require("./rules/custom/NoSchemaIntrospectionCustomRule.js"); diff --git a/school/node_modules/graphql/validation/index.js.flow b/school/node_modules/graphql/validation/index.js.flow new file mode 100644 index 0000000..3def649 --- /dev/null +++ b/school/node_modules/graphql/validation/index.js.flow @@ -0,0 +1,99 @@ +// @flow strict +export { validate } from './validate'; + +export { ValidationContext } from './ValidationContext'; +export type { ValidationRule } from './ValidationContext'; + +// All validation rules in the GraphQL Specification. +export { specifiedRules } from './specifiedRules'; + +// Spec Section: "Executable Definitions" +export { ExecutableDefinitionsRule } from './rules/ExecutableDefinitionsRule'; + +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +export { FieldsOnCorrectTypeRule } from './rules/FieldsOnCorrectTypeRule'; + +// Spec Section: "Fragments on Composite Types" +export { FragmentsOnCompositeTypesRule } from './rules/FragmentsOnCompositeTypesRule'; + +// Spec Section: "Argument Names" +export { KnownArgumentNamesRule } from './rules/KnownArgumentNamesRule'; + +// Spec Section: "Directives Are Defined" +export { KnownDirectivesRule } from './rules/KnownDirectivesRule'; + +// Spec Section: "Fragment spread target defined" +export { KnownFragmentNamesRule } from './rules/KnownFragmentNamesRule'; + +// Spec Section: "Fragment Spread Type Existence" +export { KnownTypeNamesRule } from './rules/KnownTypeNamesRule'; + +// Spec Section: "Lone Anonymous Operation" +export { LoneAnonymousOperationRule } from './rules/LoneAnonymousOperationRule'; + +// Spec Section: "Fragments must not form cycles" +export { NoFragmentCyclesRule } from './rules/NoFragmentCyclesRule'; + +// Spec Section: "All Variable Used Defined" +export { NoUndefinedVariablesRule } from './rules/NoUndefinedVariablesRule'; + +// Spec Section: "Fragments must be used" +export { NoUnusedFragmentsRule } from './rules/NoUnusedFragmentsRule'; + +// Spec Section: "All Variables Used" +export { NoUnusedVariablesRule } from './rules/NoUnusedVariablesRule'; + +// Spec Section: "Field Selection Merging" +export { OverlappingFieldsCanBeMergedRule } from './rules/OverlappingFieldsCanBeMergedRule'; + +// Spec Section: "Fragment spread is possible" +export { PossibleFragmentSpreadsRule } from './rules/PossibleFragmentSpreadsRule'; + +// Spec Section: "Argument Optionality" +export { ProvidedRequiredArgumentsRule } from './rules/ProvidedRequiredArgumentsRule'; + +// Spec Section: "Leaf Field Selections" +export { ScalarLeafsRule } from './rules/ScalarLeafsRule'; + +// Spec Section: "Subscriptions with Single Root Field" +export { SingleFieldSubscriptionsRule } from './rules/SingleFieldSubscriptionsRule'; + +// Spec Section: "Argument Uniqueness" +export { UniqueArgumentNamesRule } from './rules/UniqueArgumentNamesRule'; + +// Spec Section: "Directives Are Unique Per Location" +export { UniqueDirectivesPerLocationRule } from './rules/UniqueDirectivesPerLocationRule'; + +// Spec Section: "Fragment Name Uniqueness" +export { UniqueFragmentNamesRule } from './rules/UniqueFragmentNamesRule'; + +// Spec Section: "Input Object Field Uniqueness" +export { UniqueInputFieldNamesRule } from './rules/UniqueInputFieldNamesRule'; + +// Spec Section: "Operation Name Uniqueness" +export { UniqueOperationNamesRule } from './rules/UniqueOperationNamesRule'; + +// Spec Section: "Variable Uniqueness" +export { UniqueVariableNamesRule } from './rules/UniqueVariableNamesRule'; + +// Spec Section: "Values Type Correctness" +export { ValuesOfCorrectTypeRule } from './rules/ValuesOfCorrectTypeRule'; + +// Spec Section: "Variables are Input Types" +export { VariablesAreInputTypesRule } from './rules/VariablesAreInputTypesRule'; + +// Spec Section: "All Variable Usages Are Allowed" +export { VariablesInAllowedPositionRule } from './rules/VariablesInAllowedPositionRule'; + +// SDL-specific validation rules +export { LoneSchemaDefinitionRule } from './rules/LoneSchemaDefinitionRule'; +export { UniqueOperationTypesRule } from './rules/UniqueOperationTypesRule'; +export { UniqueTypeNamesRule } from './rules/UniqueTypeNamesRule'; +export { UniqueEnumValueNamesRule } from './rules/UniqueEnumValueNamesRule'; +export { UniqueFieldDefinitionNamesRule } from './rules/UniqueFieldDefinitionNamesRule'; +export { UniqueDirectiveNamesRule } from './rules/UniqueDirectiveNamesRule'; +export { PossibleTypeExtensionsRule } from './rules/PossibleTypeExtensionsRule'; + +// Optional rules not defined by the GraphQL Specification +export { NoDeprecatedCustomRule } from './rules/custom/NoDeprecatedCustomRule'; +export { NoSchemaIntrospectionCustomRule } from './rules/custom/NoSchemaIntrospectionCustomRule'; diff --git a/school/node_modules/graphql/validation/index.mjs b/school/node_modules/graphql/validation/index.mjs new file mode 100644 index 0000000..e6a0d98 --- /dev/null +++ b/school/node_modules/graphql/validation/index.mjs @@ -0,0 +1,67 @@ +export { validate } from "./validate.mjs"; +export { ValidationContext } from "./ValidationContext.mjs"; +// All validation rules in the GraphQL Specification. +export { specifiedRules } from "./specifiedRules.mjs"; // Spec Section: "Executable Definitions" + +export { ExecutableDefinitionsRule } from "./rules/ExecutableDefinitionsRule.mjs"; // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + +export { FieldsOnCorrectTypeRule } from "./rules/FieldsOnCorrectTypeRule.mjs"; // Spec Section: "Fragments on Composite Types" + +export { FragmentsOnCompositeTypesRule } from "./rules/FragmentsOnCompositeTypesRule.mjs"; // Spec Section: "Argument Names" + +export { KnownArgumentNamesRule } from "./rules/KnownArgumentNamesRule.mjs"; // Spec Section: "Directives Are Defined" + +export { KnownDirectivesRule } from "./rules/KnownDirectivesRule.mjs"; // Spec Section: "Fragment spread target defined" + +export { KnownFragmentNamesRule } from "./rules/KnownFragmentNamesRule.mjs"; // Spec Section: "Fragment Spread Type Existence" + +export { KnownTypeNamesRule } from "./rules/KnownTypeNamesRule.mjs"; // Spec Section: "Lone Anonymous Operation" + +export { LoneAnonymousOperationRule } from "./rules/LoneAnonymousOperationRule.mjs"; // Spec Section: "Fragments must not form cycles" + +export { NoFragmentCyclesRule } from "./rules/NoFragmentCyclesRule.mjs"; // Spec Section: "All Variable Used Defined" + +export { NoUndefinedVariablesRule } from "./rules/NoUndefinedVariablesRule.mjs"; // Spec Section: "Fragments must be used" + +export { NoUnusedFragmentsRule } from "./rules/NoUnusedFragmentsRule.mjs"; // Spec Section: "All Variables Used" + +export { NoUnusedVariablesRule } from "./rules/NoUnusedVariablesRule.mjs"; // Spec Section: "Field Selection Merging" + +export { OverlappingFieldsCanBeMergedRule } from "./rules/OverlappingFieldsCanBeMergedRule.mjs"; // Spec Section: "Fragment spread is possible" + +export { PossibleFragmentSpreadsRule } from "./rules/PossibleFragmentSpreadsRule.mjs"; // Spec Section: "Argument Optionality" + +export { ProvidedRequiredArgumentsRule } from "./rules/ProvidedRequiredArgumentsRule.mjs"; // Spec Section: "Leaf Field Selections" + +export { ScalarLeafsRule } from "./rules/ScalarLeafsRule.mjs"; // Spec Section: "Subscriptions with Single Root Field" + +export { SingleFieldSubscriptionsRule } from "./rules/SingleFieldSubscriptionsRule.mjs"; // Spec Section: "Argument Uniqueness" + +export { UniqueArgumentNamesRule } from "./rules/UniqueArgumentNamesRule.mjs"; // Spec Section: "Directives Are Unique Per Location" + +export { UniqueDirectivesPerLocationRule } from "./rules/UniqueDirectivesPerLocationRule.mjs"; // Spec Section: "Fragment Name Uniqueness" + +export { UniqueFragmentNamesRule } from "./rules/UniqueFragmentNamesRule.mjs"; // Spec Section: "Input Object Field Uniqueness" + +export { UniqueInputFieldNamesRule } from "./rules/UniqueInputFieldNamesRule.mjs"; // Spec Section: "Operation Name Uniqueness" + +export { UniqueOperationNamesRule } from "./rules/UniqueOperationNamesRule.mjs"; // Spec Section: "Variable Uniqueness" + +export { UniqueVariableNamesRule } from "./rules/UniqueVariableNamesRule.mjs"; // Spec Section: "Values Type Correctness" + +export { ValuesOfCorrectTypeRule } from "./rules/ValuesOfCorrectTypeRule.mjs"; // Spec Section: "Variables are Input Types" + +export { VariablesAreInputTypesRule } from "./rules/VariablesAreInputTypesRule.mjs"; // Spec Section: "All Variable Usages Are Allowed" + +export { VariablesInAllowedPositionRule } from "./rules/VariablesInAllowedPositionRule.mjs"; // SDL-specific validation rules + +export { LoneSchemaDefinitionRule } from "./rules/LoneSchemaDefinitionRule.mjs"; +export { UniqueOperationTypesRule } from "./rules/UniqueOperationTypesRule.mjs"; +export { UniqueTypeNamesRule } from "./rules/UniqueTypeNamesRule.mjs"; +export { UniqueEnumValueNamesRule } from "./rules/UniqueEnumValueNamesRule.mjs"; +export { UniqueFieldDefinitionNamesRule } from "./rules/UniqueFieldDefinitionNamesRule.mjs"; +export { UniqueDirectiveNamesRule } from "./rules/UniqueDirectiveNamesRule.mjs"; +export { PossibleTypeExtensionsRule } from "./rules/PossibleTypeExtensionsRule.mjs"; // Optional rules not defined by the GraphQL Specification + +export { NoDeprecatedCustomRule } from "./rules/custom/NoDeprecatedCustomRule.mjs"; +export { NoSchemaIntrospectionCustomRule } from "./rules/custom/NoSchemaIntrospectionCustomRule.mjs"; diff --git a/school/node_modules/graphql/validation/rules/ExecutableDefinitions.d.ts b/school/node_modules/graphql/validation/rules/ExecutableDefinitions.d.ts new file mode 100644 index 0000000..94557ad --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ExecutableDefinitions.d.ts @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { ExecutableDefinitionsRule } from 'graphql' + * or + * import { ExecutableDefinitionsRule } from 'graphql/validation' + */ +export { ExecutableDefinitionsRule as ExecutableDefinitions } from './ExecutableDefinitionsRule'; diff --git a/school/node_modules/graphql/validation/rules/ExecutableDefinitions.js b/school/node_modules/graphql/validation/rules/ExecutableDefinitions.js new file mode 100644 index 0000000..ed8c46b --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ExecutableDefinitions.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ExecutableDefinitions", { + enumerable: true, + get: function get() { + return _ExecutableDefinitionsRule.ExecutableDefinitionsRule; + } +}); + +var _ExecutableDefinitionsRule = require("./ExecutableDefinitionsRule.js"); diff --git a/school/node_modules/graphql/validation/rules/ExecutableDefinitions.js.flow b/school/node_modules/graphql/validation/rules/ExecutableDefinitions.js.flow new file mode 100644 index 0000000..aac4efb --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ExecutableDefinitions.js.flow @@ -0,0 +1,9 @@ +// @flow strict +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { ExecutableDefinitionsRule } from 'graphql' + * or + * import { ExecutableDefinitionsRule } from 'graphql/validation' + */ +export { ExecutableDefinitionsRule as ExecutableDefinitions } from './ExecutableDefinitionsRule'; diff --git a/school/node_modules/graphql/validation/rules/ExecutableDefinitions.mjs b/school/node_modules/graphql/validation/rules/ExecutableDefinitions.mjs new file mode 100644 index 0000000..9dc914e --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ExecutableDefinitions.mjs @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { ExecutableDefinitionsRule } from 'graphql' + * or + * import { ExecutableDefinitionsRule } from 'graphql/validation' + */ +export { ExecutableDefinitionsRule as ExecutableDefinitions } from "./ExecutableDefinitionsRule.mjs"; diff --git a/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.d.ts b/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.d.ts new file mode 100644 index 0000000..9709256 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.d.ts @@ -0,0 +1,12 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ASTValidationContext } from '../ValidationContext'; + +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + */ +export function ExecutableDefinitionsRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.js b/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.js new file mode 100644 index 0000000..0c070a8 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ExecutableDefinitionsRule = ExecutableDefinitionsRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _kinds = require("../../language/kinds.js"); + +var _predicates = require("../../language/predicates.js"); + +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + */ +function ExecutableDefinitionsRule(context) { + return { + Document: function Document(node) { + for (var _i2 = 0, _node$definitions2 = node.definitions; _i2 < _node$definitions2.length; _i2++) { + var definition = _node$definitions2[_i2]; + + if (!(0, _predicates.isExecutableDefinitionNode)(definition)) { + var defName = definition.kind === _kinds.Kind.SCHEMA_DEFINITION || definition.kind === _kinds.Kind.SCHEMA_EXTENSION ? 'schema' : '"' + definition.name.value + '"'; + context.reportError(new _GraphQLError.GraphQLError("The ".concat(defName, " definition is not executable."), definition)); + } + } + + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.js.flow b/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.js.flow new file mode 100644 index 0000000..06c0d52 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.js.flow @@ -0,0 +1,39 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import { Kind } from '../../language/kinds'; +import { isExecutableDefinitionNode } from '../../language/predicates'; + +import type { ASTValidationContext } from '../ValidationContext'; + +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + */ +export function ExecutableDefinitionsRule( + context: ASTValidationContext, +): ASTVisitor { + return { + Document(node) { + for (const definition of node.definitions) { + if (!isExecutableDefinitionNode(definition)) { + const defName = + definition.kind === Kind.SCHEMA_DEFINITION || + definition.kind === Kind.SCHEMA_EXTENSION + ? 'schema' + : '"' + definition.name.value + '"'; + context.reportError( + new GraphQLError( + `The ${defName} definition is not executable.`, + definition, + ), + ); + } + } + return false; + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs b/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs new file mode 100644 index 0000000..c47b996 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs @@ -0,0 +1,26 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { Kind } from "../../language/kinds.mjs"; +import { isExecutableDefinitionNode } from "../../language/predicates.mjs"; + +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + */ +export function ExecutableDefinitionsRule(context) { + return { + Document: function Document(node) { + for (var _i2 = 0, _node$definitions2 = node.definitions; _i2 < _node$definitions2.length; _i2++) { + var definition = _node$definitions2[_i2]; + + if (!isExecutableDefinitionNode(definition)) { + var defName = definition.kind === Kind.SCHEMA_DEFINITION || definition.kind === Kind.SCHEMA_EXTENSION ? 'schema' : '"' + definition.name.value + '"'; + context.reportError(new GraphQLError("The ".concat(defName, " definition is not executable."), definition)); + } + } + + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.d.ts b/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.d.ts new file mode 100644 index 0000000..6091c6c --- /dev/null +++ b/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.d.ts @@ -0,0 +1,10 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ +export function FieldsOnCorrectTypeRule(context: ValidationContext): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.js b/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.js new file mode 100644 index 0000000..ddd25a0 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.js @@ -0,0 +1,132 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FieldsOnCorrectTypeRule = FieldsOnCorrectTypeRule; + +var _arrayFrom = _interopRequireDefault(require("../../polyfills/arrayFrom.js")); + +var _didYouMean = _interopRequireDefault(require("../../jsutils/didYouMean.js")); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList.js")); + +var _naturalCompare = _interopRequireDefault(require("../../jsutils/naturalCompare.js")); + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _definition = require("../../type/definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ +function FieldsOnCorrectTypeRule(context) { + return { + Field: function Field(node) { + var type = context.getParentType(); + + if (type) { + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + var schema = context.getSchema(); + var fieldName = node.name.value; // First determine if there are any suggested types to condition on. + + var suggestion = (0, _didYouMean.default)('to use an inline fragment on', getSuggestedTypeNames(schema, type, fieldName)); // If there are no suggested types, then perhaps this was a typo? + + if (suggestion === '') { + suggestion = (0, _didYouMean.default)(getSuggestedFieldNames(type, fieldName)); + } // Report an error, including helpful suggestions. + + + context.reportError(new _GraphQLError.GraphQLError("Cannot query field \"".concat(fieldName, "\" on type \"").concat(type.name, "\".") + suggestion, node)); + } + } + } + }; +} +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest them, + * sorted by how often the type is referenced. + */ + + +function getSuggestedTypeNames(schema, type, fieldName) { + if (!(0, _definition.isAbstractType)(type)) { + // Must be an Object type, which does not have possible fields. + return []; + } + + var suggestedTypes = new Set(); + var usageCount = Object.create(null); + + for (var _i2 = 0, _schema$getPossibleTy2 = schema.getPossibleTypes(type); _i2 < _schema$getPossibleTy2.length; _i2++) { + var possibleType = _schema$getPossibleTy2[_i2]; + + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. + + + suggestedTypes.add(possibleType); + usageCount[possibleType.name] = 1; + + for (var _i4 = 0, _possibleType$getInte2 = possibleType.getInterfaces(); _i4 < _possibleType$getInte2.length; _i4++) { + var _usageCount$possibleI; + + var possibleInterface = _possibleType$getInte2[_i4]; + + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. + + + suggestedTypes.add(possibleInterface); + usageCount[possibleInterface.name] = ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== null && _usageCount$possibleI !== void 0 ? _usageCount$possibleI : 0) + 1; + } + } + + return (0, _arrayFrom.default)(suggestedTypes).sort(function (typeA, typeB) { + // Suggest both interface and object types based on how common they are. + var usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; + + if (usageCountDiff !== 0) { + return usageCountDiff; + } // Suggest super types first followed by subtypes + + + if ((0, _definition.isInterfaceType)(typeA) && schema.isSubType(typeA, typeB)) { + return -1; + } + + if ((0, _definition.isInterfaceType)(typeB) && schema.isSubType(typeB, typeA)) { + return 1; + } + + return (0, _naturalCompare.default)(typeA.name, typeB.name); + }).map(function (x) { + return x.name; + }); +} +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ + + +function getSuggestedFieldNames(type, fieldName) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + var possibleFieldNames = Object.keys(type.getFields()); + return (0, _suggestionList.default)(fieldName, possibleFieldNames); + } // Otherwise, must be a Union type, which does not define fields. + + + return []; +} diff --git a/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.js.flow b/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.js.flow new file mode 100644 index 0000000..2170606 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.js.flow @@ -0,0 +1,146 @@ +// @flow strict +import arrayFrom from '../../polyfills/arrayFrom'; + +import didYouMean from '../../jsutils/didYouMean'; +import suggestionList from '../../jsutils/suggestionList'; +import naturalCompare from '../../jsutils/naturalCompare'; + +import { GraphQLError } from '../../error/GraphQLError'; + +import type { FieldNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; + +import type { GraphQLSchema } from '../../type/schema'; +import type { + GraphQLOutputType, + GraphQLObjectType, + GraphQLInterfaceType, +} from '../../type/definition'; +import { + isObjectType, + isInterfaceType, + isAbstractType, +} from '../../type/definition'; + +import type { ValidationContext } from '../ValidationContext'; + +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ +export function FieldsOnCorrectTypeRule( + context: ValidationContext, +): ASTVisitor { + return { + Field(node: FieldNode) { + const type = context.getParentType(); + if (type) { + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + const schema = context.getSchema(); + const fieldName = node.name.value; + + // First determine if there are any suggested types to condition on. + let suggestion = didYouMean( + 'to use an inline fragment on', + getSuggestedTypeNames(schema, type, fieldName), + ); + + // If there are no suggested types, then perhaps this was a typo? + if (suggestion === '') { + suggestion = didYouMean(getSuggestedFieldNames(type, fieldName)); + } + + // Report an error, including helpful suggestions. + context.reportError( + new GraphQLError( + `Cannot query field "${fieldName}" on type "${type.name}".` + + suggestion, + node, + ), + ); + } + } + }, + }; +} + +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest them, + * sorted by how often the type is referenced. + */ +function getSuggestedTypeNames( + schema: GraphQLSchema, + type: GraphQLOutputType, + fieldName: string, +): Array<string> { + if (!isAbstractType(type)) { + // Must be an Object type, which does not have possible fields. + return []; + } + + const suggestedTypes: Set< + GraphQLObjectType | GraphQLInterfaceType, + > = new Set(); + const usageCount = Object.create(null); + for (const possibleType of schema.getPossibleTypes(type)) { + if (!possibleType.getFields()[fieldName]) { + continue; + } + + // This object type defines this field. + suggestedTypes.add(possibleType); + usageCount[possibleType.name] = 1; + + for (const possibleInterface of possibleType.getInterfaces()) { + if (!possibleInterface.getFields()[fieldName]) { + continue; + } + + // This interface type defines this field. + suggestedTypes.add(possibleInterface); + usageCount[possibleInterface.name] = + (usageCount[possibleInterface.name] ?? 0) + 1; + } + } + + return arrayFrom(suggestedTypes) + .sort((typeA, typeB) => { + // Suggest both interface and object types based on how common they are. + const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; + if (usageCountDiff !== 0) { + return usageCountDiff; + } + + // Suggest super types first followed by subtypes + if (isInterfaceType(typeA) && schema.isSubType(typeA, typeB)) { + return -1; + } + if (isInterfaceType(typeB) && schema.isSubType(typeB, typeA)) { + return 1; + } + + return naturalCompare(typeA.name, typeB.name); + }) + .map((x) => x.name); +} + +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ +function getSuggestedFieldNames( + type: GraphQLOutputType, + fieldName: string, +): Array<string> { + if (isObjectType(type) || isInterfaceType(type)) { + const possibleFieldNames = Object.keys(type.getFields()); + return suggestionList(fieldName, possibleFieldNames); + } + // Otherwise, must be a Union type, which does not define fields. + return []; +} diff --git a/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs b/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs new file mode 100644 index 0000000..f10b21d --- /dev/null +++ b/school/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs @@ -0,0 +1,117 @@ +import arrayFrom from "../../polyfills/arrayFrom.mjs"; +import didYouMean from "../../jsutils/didYouMean.mjs"; +import suggestionList from "../../jsutils/suggestionList.mjs"; +import naturalCompare from "../../jsutils/naturalCompare.mjs"; +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { isObjectType, isInterfaceType, isAbstractType } from "../../type/definition.mjs"; + +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ +export function FieldsOnCorrectTypeRule(context) { + return { + Field: function Field(node) { + var type = context.getParentType(); + + if (type) { + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + var schema = context.getSchema(); + var fieldName = node.name.value; // First determine if there are any suggested types to condition on. + + var suggestion = didYouMean('to use an inline fragment on', getSuggestedTypeNames(schema, type, fieldName)); // If there are no suggested types, then perhaps this was a typo? + + if (suggestion === '') { + suggestion = didYouMean(getSuggestedFieldNames(type, fieldName)); + } // Report an error, including helpful suggestions. + + + context.reportError(new GraphQLError("Cannot query field \"".concat(fieldName, "\" on type \"").concat(type.name, "\".") + suggestion, node)); + } + } + } + }; +} +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest them, + * sorted by how often the type is referenced. + */ + +function getSuggestedTypeNames(schema, type, fieldName) { + if (!isAbstractType(type)) { + // Must be an Object type, which does not have possible fields. + return []; + } + + var suggestedTypes = new Set(); + var usageCount = Object.create(null); + + for (var _i2 = 0, _schema$getPossibleTy2 = schema.getPossibleTypes(type); _i2 < _schema$getPossibleTy2.length; _i2++) { + var possibleType = _schema$getPossibleTy2[_i2]; + + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. + + + suggestedTypes.add(possibleType); + usageCount[possibleType.name] = 1; + + for (var _i4 = 0, _possibleType$getInte2 = possibleType.getInterfaces(); _i4 < _possibleType$getInte2.length; _i4++) { + var _usageCount$possibleI; + + var possibleInterface = _possibleType$getInte2[_i4]; + + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. + + + suggestedTypes.add(possibleInterface); + usageCount[possibleInterface.name] = ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== null && _usageCount$possibleI !== void 0 ? _usageCount$possibleI : 0) + 1; + } + } + + return arrayFrom(suggestedTypes).sort(function (typeA, typeB) { + // Suggest both interface and object types based on how common they are. + var usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; + + if (usageCountDiff !== 0) { + return usageCountDiff; + } // Suggest super types first followed by subtypes + + + if (isInterfaceType(typeA) && schema.isSubType(typeA, typeB)) { + return -1; + } + + if (isInterfaceType(typeB) && schema.isSubType(typeB, typeA)) { + return 1; + } + + return naturalCompare(typeA.name, typeB.name); + }).map(function (x) { + return x.name; + }); +} +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ + + +function getSuggestedFieldNames(type, fieldName) { + if (isObjectType(type) || isInterfaceType(type)) { + var possibleFieldNames = Object.keys(type.getFields()); + return suggestionList(fieldName, possibleFieldNames); + } // Otherwise, must be a Union type, which does not define fields. + + + return []; +} diff --git a/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.d.ts b/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.d.ts new file mode 100644 index 0000000..70b9b14 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.d.ts @@ -0,0 +1,13 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ +export function FragmentsOnCompositeTypesRule( + context: ValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.js b/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.js new file mode 100644 index 0000000..423ffcc --- /dev/null +++ b/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FragmentsOnCompositeTypesRule = FragmentsOnCompositeTypesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _printer = require("../../language/printer.js"); + +var _definition = require("../../type/definition.js"); + +var _typeFromAST = require("../../utilities/typeFromAST.js"); + +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ +function FragmentsOnCompositeTypesRule(context) { + return { + InlineFragment: function InlineFragment(node) { + var typeCondition = node.typeCondition; + + if (typeCondition) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition); + + if (type && !(0, _definition.isCompositeType)(type)) { + var typeStr = (0, _printer.print)(typeCondition); + context.reportError(new _GraphQLError.GraphQLError("Fragment cannot condition on non composite type \"".concat(typeStr, "\"."), typeCondition)); + } + } + }, + FragmentDefinition: function FragmentDefinition(node) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition); + + if (type && !(0, _definition.isCompositeType)(type)) { + var typeStr = (0, _printer.print)(node.typeCondition); + context.reportError(new _GraphQLError.GraphQLError("Fragment \"".concat(node.name.value, "\" cannot condition on non composite type \"").concat(typeStr, "\"."), node.typeCondition)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.js.flow b/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.js.flow new file mode 100644 index 0000000..53ed6b9 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.js.flow @@ -0,0 +1,52 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import { print } from '../../language/printer'; + +import { isCompositeType } from '../../type/definition'; + +import { typeFromAST } from '../../utilities/typeFromAST'; + +import type { ValidationContext } from '../ValidationContext'; + +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ +export function FragmentsOnCompositeTypesRule( + context: ValidationContext, +): ASTVisitor { + return { + InlineFragment(node) { + const typeCondition = node.typeCondition; + if (typeCondition) { + const type = typeFromAST(context.getSchema(), typeCondition); + if (type && !isCompositeType(type)) { + const typeStr = print(typeCondition); + context.reportError( + new GraphQLError( + `Fragment cannot condition on non composite type "${typeStr}".`, + typeCondition, + ), + ); + } + } + }, + FragmentDefinition(node) { + const type = typeFromAST(context.getSchema(), node.typeCondition); + if (type && !isCompositeType(type)) { + const typeStr = print(node.typeCondition); + context.reportError( + new GraphQLError( + `Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`, + node.typeCondition, + ), + ); + } + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs b/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs new file mode 100644 index 0000000..44aaac6 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs @@ -0,0 +1,36 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { print } from "../../language/printer.mjs"; +import { isCompositeType } from "../../type/definition.mjs"; +import { typeFromAST } from "../../utilities/typeFromAST.mjs"; + +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ +export function FragmentsOnCompositeTypesRule(context) { + return { + InlineFragment: function InlineFragment(node) { + var typeCondition = node.typeCondition; + + if (typeCondition) { + var type = typeFromAST(context.getSchema(), typeCondition); + + if (type && !isCompositeType(type)) { + var typeStr = print(typeCondition); + context.reportError(new GraphQLError("Fragment cannot condition on non composite type \"".concat(typeStr, "\"."), typeCondition)); + } + } + }, + FragmentDefinition: function FragmentDefinition(node) { + var type = typeFromAST(context.getSchema(), node.typeCondition); + + if (type && !isCompositeType(type)) { + var typeStr = print(node.typeCondition); + context.reportError(new GraphQLError("Fragment \"".concat(node.name.value, "\" cannot condition on non composite type \"").concat(typeStr, "\"."), node.typeCondition)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.d.ts b/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.d.ts new file mode 100644 index 0000000..8c0f828 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.d.ts @@ -0,0 +1,17 @@ +import { ValidationContext, SDLValidationContext } from '../ValidationContext'; +import { ASTVisitor } from '../../language/visitor'; + +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ +export function KnownArgumentNamesRule(context: ValidationContext): ASTVisitor; + +/** + * @internal + */ +export function KnownArgumentNamesOnDirectivesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.js b/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.js new file mode 100644 index 0000000..4742b84 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.KnownArgumentNamesRule = KnownArgumentNamesRule; +exports.KnownArgumentNamesOnDirectivesRule = KnownArgumentNamesOnDirectivesRule; + +var _didYouMean = _interopRequireDefault(require("../../jsutils/didYouMean.js")); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList.js")); + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _kinds = require("../../language/kinds.js"); + +var _directives = require("../../type/directives.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ +function KnownArgumentNamesRule(context) { + return _objectSpread(_objectSpread({}, KnownArgumentNamesOnDirectivesRule(context)), {}, { + Argument: function Argument(argNode) { + var argDef = context.getArgument(); + var fieldDef = context.getFieldDef(); + var parentType = context.getParentType(); + + if (!argDef && fieldDef && parentType) { + var argName = argNode.name.value; + var knownArgsNames = fieldDef.args.map(function (arg) { + return arg.name; + }); + var suggestions = (0, _suggestionList.default)(argName, knownArgsNames); + context.reportError(new _GraphQLError.GraphQLError("Unknown argument \"".concat(argName, "\" on field \"").concat(parentType.name, ".").concat(fieldDef.name, "\".") + (0, _didYouMean.default)(suggestions), argNode)); + } + } + }); +} +/** + * @internal + */ + + +function KnownArgumentNamesOnDirectivesRule(context) { + var directiveArgs = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + + for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) { + var directive = definedDirectives[_i2]; + directiveArgs[directive.name] = directive.args.map(function (arg) { + return arg.name; + }); + } + + var astDefinitions = context.getDocument().definitions; + + for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) { + var def = astDefinitions[_i4]; + + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var argsNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; + directiveArgs[def.name.value] = argsNodes.map(function (arg) { + return arg.name.value; + }); + } + } + + return { + Directive: function Directive(directiveNode) { + var directiveName = directiveNode.name.value; + var knownArgs = directiveArgs[directiveName]; + + if (directiveNode.arguments && knownArgs) { + for (var _i6 = 0, _directiveNode$argume2 = directiveNode.arguments; _i6 < _directiveNode$argume2.length; _i6++) { + var argNode = _directiveNode$argume2[_i6]; + var argName = argNode.name.value; + + if (knownArgs.indexOf(argName) === -1) { + var suggestions = (0, _suggestionList.default)(argName, knownArgs); + context.reportError(new _GraphQLError.GraphQLError("Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\".") + (0, _didYouMean.default)(suggestions), argNode)); + } + } + } + + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.js.flow b/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.js.flow new file mode 100644 index 0000000..a5f420b --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.js.flow @@ -0,0 +1,98 @@ +// @flow strict +import didYouMean from '../../jsutils/didYouMean'; +import suggestionList from '../../jsutils/suggestionList'; + +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import { Kind } from '../../language/kinds'; + +import { specifiedDirectives } from '../../type/directives'; + +import type { + ValidationContext, + SDLValidationContext, +} from '../ValidationContext'; + +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ +export function KnownArgumentNamesRule(context: ValidationContext): ASTVisitor { + return { + // eslint-disable-next-line new-cap + ...KnownArgumentNamesOnDirectivesRule(context), + Argument(argNode) { + const argDef = context.getArgument(); + const fieldDef = context.getFieldDef(); + const parentType = context.getParentType(); + + if (!argDef && fieldDef && parentType) { + const argName = argNode.name.value; + const knownArgsNames = fieldDef.args.map((arg) => arg.name); + const suggestions = suggestionList(argName, knownArgsNames); + context.reportError( + new GraphQLError( + `Unknown argument "${argName}" on field "${parentType.name}.${fieldDef.name}".` + + didYouMean(suggestions), + argNode, + ), + ); + } + }, + }; +} + +/** + * @internal + */ +export function KnownArgumentNamesOnDirectivesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor { + const directiveArgs = Object.create(null); + + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + for (const directive of definedDirectives) { + directiveArgs[directive.name] = directive.args.map((arg) => arg.name); + } + + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const argsNodes = def.arguments ?? []; + + directiveArgs[def.name.value] = argsNodes.map((arg) => arg.name.value); + } + } + + return { + Directive(directiveNode) { + const directiveName = directiveNode.name.value; + const knownArgs = directiveArgs[directiveName]; + + if (directiveNode.arguments && knownArgs) { + for (const argNode of directiveNode.arguments) { + const argName = argNode.name.value; + if (knownArgs.indexOf(argName) === -1) { + const suggestions = suggestionList(argName, knownArgs); + context.reportError( + new GraphQLError( + `Unknown argument "${argName}" on directive "@${directiveName}".` + + didYouMean(suggestions), + argNode, + ), + ); + } + } + } + + return false; + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs b/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs new file mode 100644 index 0000000..d21057e --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs @@ -0,0 +1,89 @@ +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +import didYouMean from "../../jsutils/didYouMean.mjs"; +import suggestionList from "../../jsutils/suggestionList.mjs"; +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { Kind } from "../../language/kinds.mjs"; +import { specifiedDirectives } from "../../type/directives.mjs"; + +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ +export function KnownArgumentNamesRule(context) { + return _objectSpread(_objectSpread({}, KnownArgumentNamesOnDirectivesRule(context)), {}, { + Argument: function Argument(argNode) { + var argDef = context.getArgument(); + var fieldDef = context.getFieldDef(); + var parentType = context.getParentType(); + + if (!argDef && fieldDef && parentType) { + var argName = argNode.name.value; + var knownArgsNames = fieldDef.args.map(function (arg) { + return arg.name; + }); + var suggestions = suggestionList(argName, knownArgsNames); + context.reportError(new GraphQLError("Unknown argument \"".concat(argName, "\" on field \"").concat(parentType.name, ".").concat(fieldDef.name, "\".") + didYouMean(suggestions), argNode)); + } + } + }); +} +/** + * @internal + */ + +export function KnownArgumentNamesOnDirectivesRule(context) { + var directiveArgs = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives; + + for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) { + var directive = definedDirectives[_i2]; + directiveArgs[directive.name] = directive.args.map(function (arg) { + return arg.name; + }); + } + + var astDefinitions = context.getDocument().definitions; + + for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) { + var def = astDefinitions[_i4]; + + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var argsNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; + directiveArgs[def.name.value] = argsNodes.map(function (arg) { + return arg.name.value; + }); + } + } + + return { + Directive: function Directive(directiveNode) { + var directiveName = directiveNode.name.value; + var knownArgs = directiveArgs[directiveName]; + + if (directiveNode.arguments && knownArgs) { + for (var _i6 = 0, _directiveNode$argume2 = directiveNode.arguments; _i6 < _directiveNode$argume2.length; _i6++) { + var argNode = _directiveNode$argume2[_i6]; + var argName = argNode.name.value; + + if (knownArgs.indexOf(argName) === -1) { + var suggestions = suggestionList(argName, knownArgs); + context.reportError(new GraphQLError("Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\".") + didYouMean(suggestions), argNode)); + } + } + } + + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/KnownDirectivesRule.d.ts b/school/node_modules/graphql/validation/rules/KnownDirectivesRule.d.ts new file mode 100644 index 0000000..dcb6af6 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownDirectivesRule.d.ts @@ -0,0 +1,12 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext, SDLValidationContext } from '../ValidationContext'; + +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ +export function KnownDirectivesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/KnownDirectivesRule.js b/school/node_modules/graphql/validation/rules/KnownDirectivesRule.js new file mode 100644 index 0000000..ef2ab61 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownDirectivesRule.js @@ -0,0 +1,148 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.KnownDirectivesRule = KnownDirectivesRule; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect.js")); + +var _invariant = _interopRequireDefault(require("../../jsutils/invariant.js")); + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _kinds = require("../../language/kinds.js"); + +var _directiveLocation = require("../../language/directiveLocation.js"); + +var _directives = require("../../type/directives.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ +function KnownDirectivesRule(context) { + var locationsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + + for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) { + var directive = definedDirectives[_i2]; + locationsMap[directive.name] = directive.locations; + } + + var astDefinitions = context.getDocument().definitions; + + for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) { + var def = astDefinitions[_i4]; + + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map(function (name) { + return name.value; + }); + } + } + + return { + Directive: function Directive(node, _key, _parent, _path, ancestors) { + var name = node.name.value; + var locations = locationsMap[name]; + + if (!locations) { + context.reportError(new _GraphQLError.GraphQLError("Unknown directive \"@".concat(name, "\"."), node)); + return; + } + + var candidateLocation = getDirectiveLocationForASTPath(ancestors); + + if (candidateLocation && locations.indexOf(candidateLocation) === -1) { + context.reportError(new _GraphQLError.GraphQLError("Directive \"@".concat(name, "\" may not be used on ").concat(candidateLocation, "."), node)); + } + } + }; +} + +function getDirectiveLocationForASTPath(ancestors) { + var appliedTo = ancestors[ancestors.length - 1]; + !Array.isArray(appliedTo) || (0, _invariant.default)(0); + + switch (appliedTo.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + return getDirectiveLocationForOperation(appliedTo.operation); + + case _kinds.Kind.FIELD: + return _directiveLocation.DirectiveLocation.FIELD; + + case _kinds.Kind.FRAGMENT_SPREAD: + return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD; + + case _kinds.Kind.INLINE_FRAGMENT: + return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT; + + case _kinds.Kind.FRAGMENT_DEFINITION: + return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION; + + case _kinds.Kind.VARIABLE_DEFINITION: + return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION; + + case _kinds.Kind.SCHEMA_DEFINITION: + case _kinds.Kind.SCHEMA_EXTENSION: + return _directiveLocation.DirectiveLocation.SCHEMA; + + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.SCALAR; + + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.OBJECT; + + case _kinds.Kind.FIELD_DEFINITION: + return _directiveLocation.DirectiveLocation.FIELD_DEFINITION; + + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INTERFACE; + + case _kinds.Kind.UNION_TYPE_DEFINITION: + case _kinds.Kind.UNION_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.UNION; + + case _kinds.Kind.ENUM_TYPE_DEFINITION: + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.ENUM; + + case _kinds.Kind.ENUM_VALUE_DEFINITION: + return _directiveLocation.DirectiveLocation.ENUM_VALUE; + + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INPUT_OBJECT; + + case _kinds.Kind.INPUT_VALUE_DEFINITION: + { + var parentNode = ancestors[ancestors.length - 3]; + return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION; + } + } +} + +function getDirectiveLocationForOperation(operation) { + switch (operation) { + case 'query': + return _directiveLocation.DirectiveLocation.QUERY; + + case 'mutation': + return _directiveLocation.DirectiveLocation.MUTATION; + + case 'subscription': + return _directiveLocation.DirectiveLocation.SUBSCRIPTION; + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected operation: ' + (0, _inspect.default)(operation)); +} diff --git a/school/node_modules/graphql/validation/rules/KnownDirectivesRule.js.flow b/school/node_modules/graphql/validation/rules/KnownDirectivesRule.js.flow new file mode 100644 index 0000000..79e047a --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownDirectivesRule.js.flow @@ -0,0 +1,138 @@ +// @flow strict +import inspect from '../../jsutils/inspect'; +import invariant from '../../jsutils/invariant'; + +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import type { ASTNode, OperationTypeNode } from '../../language/ast'; +import type { DirectiveLocationEnum } from '../../language/directiveLocation'; +import { Kind } from '../../language/kinds'; +import { DirectiveLocation } from '../../language/directiveLocation'; + +import { specifiedDirectives } from '../../type/directives'; + +import type { + ValidationContext, + SDLValidationContext, +} from '../ValidationContext'; + +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ +export function KnownDirectivesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor { + const locationsMap = Object.create(null); + + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + for (const directive of definedDirectives) { + locationsMap[directive.name] = directive.locations; + } + + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map((name) => name.value); + } + } + + return { + Directive(node, _key, _parent, _path, ancestors) { + const name = node.name.value; + const locations = locationsMap[name]; + + if (!locations) { + context.reportError( + new GraphQLError(`Unknown directive "@${name}".`, node), + ); + return; + } + + const candidateLocation = getDirectiveLocationForASTPath(ancestors); + if (candidateLocation && locations.indexOf(candidateLocation) === -1) { + context.reportError( + new GraphQLError( + `Directive "@${name}" may not be used on ${candidateLocation}.`, + node, + ), + ); + } + }, + }; +} + +function getDirectiveLocationForASTPath( + ancestors: $ReadOnlyArray<ASTNode | $ReadOnlyArray<ASTNode>>, +): DirectiveLocationEnum | void { + const appliedTo = ancestors[ancestors.length - 1]; + invariant(!Array.isArray(appliedTo)); + + switch (appliedTo.kind) { + case Kind.OPERATION_DEFINITION: + return getDirectiveLocationForOperation(appliedTo.operation); + case Kind.FIELD: + return DirectiveLocation.FIELD; + case Kind.FRAGMENT_SPREAD: + return DirectiveLocation.FRAGMENT_SPREAD; + case Kind.INLINE_FRAGMENT: + return DirectiveLocation.INLINE_FRAGMENT; + case Kind.FRAGMENT_DEFINITION: + return DirectiveLocation.FRAGMENT_DEFINITION; + case Kind.VARIABLE_DEFINITION: + return DirectiveLocation.VARIABLE_DEFINITION; + case Kind.SCHEMA_DEFINITION: + case Kind.SCHEMA_EXTENSION: + return DirectiveLocation.SCHEMA; + case Kind.SCALAR_TYPE_DEFINITION: + case Kind.SCALAR_TYPE_EXTENSION: + return DirectiveLocation.SCALAR; + case Kind.OBJECT_TYPE_DEFINITION: + case Kind.OBJECT_TYPE_EXTENSION: + return DirectiveLocation.OBJECT; + case Kind.FIELD_DEFINITION: + return DirectiveLocation.FIELD_DEFINITION; + case Kind.INTERFACE_TYPE_DEFINITION: + case Kind.INTERFACE_TYPE_EXTENSION: + return DirectiveLocation.INTERFACE; + case Kind.UNION_TYPE_DEFINITION: + case Kind.UNION_TYPE_EXTENSION: + return DirectiveLocation.UNION; + case Kind.ENUM_TYPE_DEFINITION: + case Kind.ENUM_TYPE_EXTENSION: + return DirectiveLocation.ENUM; + case Kind.ENUM_VALUE_DEFINITION: + return DirectiveLocation.ENUM_VALUE; + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + return DirectiveLocation.INPUT_OBJECT; + case Kind.INPUT_VALUE_DEFINITION: { + const parentNode = ancestors[ancestors.length - 3]; + return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION + ? DirectiveLocation.INPUT_FIELD_DEFINITION + : DirectiveLocation.ARGUMENT_DEFINITION; + } + } +} + +function getDirectiveLocationForOperation( + operation: OperationTypeNode, +): DirectiveLocationEnum { + switch (operation) { + case 'query': + return DirectiveLocation.QUERY; + case 'mutation': + return DirectiveLocation.MUTATION; + case 'subscription': + return DirectiveLocation.SUBSCRIPTION; + } + + // istanbul ignore next (Not reachable. All possible types have been considered) + invariant(false, 'Unexpected operation: ' + inspect((operation: empty))); +} diff --git a/school/node_modules/graphql/validation/rules/KnownDirectivesRule.mjs b/school/node_modules/graphql/validation/rules/KnownDirectivesRule.mjs new file mode 100644 index 0000000..8889bbb --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownDirectivesRule.mjs @@ -0,0 +1,134 @@ +import inspect from "../../jsutils/inspect.mjs"; +import invariant from "../../jsutils/invariant.mjs"; +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { Kind } from "../../language/kinds.mjs"; +import { DirectiveLocation } from "../../language/directiveLocation.mjs"; +import { specifiedDirectives } from "../../type/directives.mjs"; + +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ +export function KnownDirectivesRule(context) { + var locationsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives; + + for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) { + var directive = definedDirectives[_i2]; + locationsMap[directive.name] = directive.locations; + } + + var astDefinitions = context.getDocument().definitions; + + for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) { + var def = astDefinitions[_i4]; + + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map(function (name) { + return name.value; + }); + } + } + + return { + Directive: function Directive(node, _key, _parent, _path, ancestors) { + var name = node.name.value; + var locations = locationsMap[name]; + + if (!locations) { + context.reportError(new GraphQLError("Unknown directive \"@".concat(name, "\"."), node)); + return; + } + + var candidateLocation = getDirectiveLocationForASTPath(ancestors); + + if (candidateLocation && locations.indexOf(candidateLocation) === -1) { + context.reportError(new GraphQLError("Directive \"@".concat(name, "\" may not be used on ").concat(candidateLocation, "."), node)); + } + } + }; +} + +function getDirectiveLocationForASTPath(ancestors) { + var appliedTo = ancestors[ancestors.length - 1]; + !Array.isArray(appliedTo) || invariant(0); + + switch (appliedTo.kind) { + case Kind.OPERATION_DEFINITION: + return getDirectiveLocationForOperation(appliedTo.operation); + + case Kind.FIELD: + return DirectiveLocation.FIELD; + + case Kind.FRAGMENT_SPREAD: + return DirectiveLocation.FRAGMENT_SPREAD; + + case Kind.INLINE_FRAGMENT: + return DirectiveLocation.INLINE_FRAGMENT; + + case Kind.FRAGMENT_DEFINITION: + return DirectiveLocation.FRAGMENT_DEFINITION; + + case Kind.VARIABLE_DEFINITION: + return DirectiveLocation.VARIABLE_DEFINITION; + + case Kind.SCHEMA_DEFINITION: + case Kind.SCHEMA_EXTENSION: + return DirectiveLocation.SCHEMA; + + case Kind.SCALAR_TYPE_DEFINITION: + case Kind.SCALAR_TYPE_EXTENSION: + return DirectiveLocation.SCALAR; + + case Kind.OBJECT_TYPE_DEFINITION: + case Kind.OBJECT_TYPE_EXTENSION: + return DirectiveLocation.OBJECT; + + case Kind.FIELD_DEFINITION: + return DirectiveLocation.FIELD_DEFINITION; + + case Kind.INTERFACE_TYPE_DEFINITION: + case Kind.INTERFACE_TYPE_EXTENSION: + return DirectiveLocation.INTERFACE; + + case Kind.UNION_TYPE_DEFINITION: + case Kind.UNION_TYPE_EXTENSION: + return DirectiveLocation.UNION; + + case Kind.ENUM_TYPE_DEFINITION: + case Kind.ENUM_TYPE_EXTENSION: + return DirectiveLocation.ENUM; + + case Kind.ENUM_VALUE_DEFINITION: + return DirectiveLocation.ENUM_VALUE; + + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + return DirectiveLocation.INPUT_OBJECT; + + case Kind.INPUT_VALUE_DEFINITION: + { + var parentNode = ancestors[ancestors.length - 3]; + return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION ? DirectiveLocation.INPUT_FIELD_DEFINITION : DirectiveLocation.ARGUMENT_DEFINITION; + } + } +} + +function getDirectiveLocationForOperation(operation) { + switch (operation) { + case 'query': + return DirectiveLocation.QUERY; + + case 'mutation': + return DirectiveLocation.MUTATION; + + case 'subscription': + return DirectiveLocation.SUBSCRIPTION; + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || invariant(0, 'Unexpected operation: ' + inspect(operation)); +} diff --git a/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.d.ts b/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.d.ts new file mode 100644 index 0000000..7b594fd --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.d.ts @@ -0,0 +1,10 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ +export function KnownFragmentNamesRule(context: ValidationContext): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.js b/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.js new file mode 100644 index 0000000..2902ef4 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.KnownFragmentNamesRule = KnownFragmentNamesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ +function KnownFragmentNamesRule(context) { + return { + FragmentSpread: function FragmentSpread(node) { + var fragmentName = node.name.value; + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + context.reportError(new _GraphQLError.GraphQLError("Unknown fragment \"".concat(fragmentName, "\"."), node.name)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.js.flow b/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.js.flow new file mode 100644 index 0000000..0c02736 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.js.flow @@ -0,0 +1,26 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; + +import type { ValidationContext } from '../ValidationContext'; + +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ +export function KnownFragmentNamesRule(context: ValidationContext): ASTVisitor { + return { + FragmentSpread(node) { + const fragmentName = node.name.value; + const fragment = context.getFragment(fragmentName); + if (!fragment) { + context.reportError( + new GraphQLError(`Unknown fragment "${fragmentName}".`, node.name), + ); + } + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs b/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs new file mode 100644 index 0000000..72f935d --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs @@ -0,0 +1,20 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ +export function KnownFragmentNamesRule(context) { + return { + FragmentSpread: function FragmentSpread(node) { + var fragmentName = node.name.value; + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + context.reportError(new GraphQLError("Unknown fragment \"".concat(fragmentName, "\"."), node.name)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.d.ts b/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.d.ts new file mode 100644 index 0000000..b7cd75d --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.d.ts @@ -0,0 +1,12 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext, SDLValidationContext } from '../ValidationContext'; + +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ +export function KnownTypeNamesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.js b/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.js new file mode 100644 index 0000000..249e3d6 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.KnownTypeNamesRule = KnownTypeNamesRule; + +var _didYouMean = _interopRequireDefault(require("../../jsutils/didYouMean.js")); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList.js")); + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _predicates = require("../../language/predicates.js"); + +var _scalars = require("../../type/scalars.js"); + +var _introspection = require("../../type/introspection.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ +function KnownTypeNamesRule(context) { + var schema = context.getSchema(); + var existingTypesMap = schema ? schema.getTypeMap() : Object.create(null); + var definedTypes = Object.create(null); + + for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) { + var def = _context$getDocument$2[_i2]; + + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = true; + } + } + + var typeNames = Object.keys(existingTypesMap).concat(Object.keys(definedTypes)); + return { + NamedType: function NamedType(node, _1, parent, _2, ancestors) { + var typeName = node.name.value; + + if (!existingTypesMap[typeName] && !definedTypes[typeName]) { + var _ancestors$; + + var definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent; + var isSDL = definitionNode != null && isSDLNode(definitionNode); + + if (isSDL && isStandardTypeName(typeName)) { + return; + } + + var suggestedTypes = (0, _suggestionList.default)(typeName, isSDL ? standardTypeNames.concat(typeNames) : typeNames); + context.reportError(new _GraphQLError.GraphQLError("Unknown type \"".concat(typeName, "\".") + (0, _didYouMean.default)(suggestedTypes), node)); + } + } + }; +} + +var standardTypeNames = [].concat(_scalars.specifiedScalarTypes, _introspection.introspectionTypes).map(function (type) { + return type.name; +}); + +function isStandardTypeName(typeName) { + return standardTypeNames.indexOf(typeName) !== -1; +} + +function isSDLNode(value) { + return !Array.isArray(value) && ((0, _predicates.isTypeSystemDefinitionNode)(value) || (0, _predicates.isTypeSystemExtensionNode)(value)); +} diff --git a/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.js.flow b/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.js.flow new file mode 100644 index 0000000..b0120db --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.js.flow @@ -0,0 +1,84 @@ +// @flow strict +import didYouMean from '../../jsutils/didYouMean'; +import suggestionList from '../../jsutils/suggestionList'; + +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; +import { + isTypeDefinitionNode, + isTypeSystemDefinitionNode, + isTypeSystemExtensionNode, +} from '../../language/predicates'; + +import { specifiedScalarTypes } from '../../type/scalars'; +import { introspectionTypes } from '../../type/introspection'; + +import type { + ValidationContext, + SDLValidationContext, +} from '../ValidationContext'; + +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ +export function KnownTypeNamesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor { + const schema = context.getSchema(); + const existingTypesMap = schema ? schema.getTypeMap() : Object.create(null); + + const definedTypes = Object.create(null); + for (const def of context.getDocument().definitions) { + if (isTypeDefinitionNode(def)) { + definedTypes[def.name.value] = true; + } + } + + const typeNames = Object.keys(existingTypesMap).concat( + Object.keys(definedTypes), + ); + + return { + NamedType(node, _1, parent, _2, ancestors) { + const typeName = node.name.value; + if (!existingTypesMap[typeName] && !definedTypes[typeName]) { + const definitionNode = ancestors[2] ?? parent; + const isSDL = definitionNode != null && isSDLNode(definitionNode); + if (isSDL && isStandardTypeName(typeName)) { + return; + } + + const suggestedTypes = suggestionList( + typeName, + isSDL ? standardTypeNames.concat(typeNames) : typeNames, + ); + context.reportError( + new GraphQLError( + `Unknown type "${typeName}".` + didYouMean(suggestedTypes), + node, + ), + ); + } + }, + }; +} + +const standardTypeNames = [...specifiedScalarTypes, ...introspectionTypes].map( + (type) => type.name, +); + +function isStandardTypeName(typeName: string): boolean { + return standardTypeNames.indexOf(typeName) !== -1; +} + +function isSDLNode(value: ASTNode | $ReadOnlyArray<ASTNode>): boolean { + return ( + !Array.isArray(value) && + (isTypeSystemDefinitionNode(value) || isTypeSystemExtensionNode(value)) + ); +} diff --git a/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs b/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs new file mode 100644 index 0000000..69116f5 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs @@ -0,0 +1,58 @@ +import didYouMean from "../../jsutils/didYouMean.mjs"; +import suggestionList from "../../jsutils/suggestionList.mjs"; +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { isTypeDefinitionNode, isTypeSystemDefinitionNode, isTypeSystemExtensionNode } from "../../language/predicates.mjs"; +import { specifiedScalarTypes } from "../../type/scalars.mjs"; +import { introspectionTypes } from "../../type/introspection.mjs"; + +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ +export function KnownTypeNamesRule(context) { + var schema = context.getSchema(); + var existingTypesMap = schema ? schema.getTypeMap() : Object.create(null); + var definedTypes = Object.create(null); + + for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) { + var def = _context$getDocument$2[_i2]; + + if (isTypeDefinitionNode(def)) { + definedTypes[def.name.value] = true; + } + } + + var typeNames = Object.keys(existingTypesMap).concat(Object.keys(definedTypes)); + return { + NamedType: function NamedType(node, _1, parent, _2, ancestors) { + var typeName = node.name.value; + + if (!existingTypesMap[typeName] && !definedTypes[typeName]) { + var _ancestors$; + + var definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent; + var isSDL = definitionNode != null && isSDLNode(definitionNode); + + if (isSDL && isStandardTypeName(typeName)) { + return; + } + + var suggestedTypes = suggestionList(typeName, isSDL ? standardTypeNames.concat(typeNames) : typeNames); + context.reportError(new GraphQLError("Unknown type \"".concat(typeName, "\".") + didYouMean(suggestedTypes), node)); + } + } + }; +} +var standardTypeNames = [].concat(specifiedScalarTypes, introspectionTypes).map(function (type) { + return type.name; +}); + +function isStandardTypeName(typeName) { + return standardTypeNames.indexOf(typeName) !== -1; +} + +function isSDLNode(value) { + return !Array.isArray(value) && (isTypeSystemDefinitionNode(value) || isTypeSystemExtensionNode(value)); +} diff --git a/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.d.ts b/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.d.ts new file mode 100644 index 0000000..1ac19ef --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.d.ts @@ -0,0 +1,12 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ASTValidationContext } from '../ValidationContext'; + +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ +export function LoneAnonymousOperationRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.js b/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.js new file mode 100644 index 0000000..116a9fb --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LoneAnonymousOperationRule = LoneAnonymousOperationRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _kinds = require("../../language/kinds.js"); + +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ +function LoneAnonymousOperationRule(context) { + var operationCount = 0; + return { + Document: function Document(node) { + operationCount = node.definitions.filter(function (definition) { + return definition.kind === _kinds.Kind.OPERATION_DEFINITION; + }).length; + }, + OperationDefinition: function OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError(new _GraphQLError.GraphQLError('This anonymous operation must be the only defined operation.', node)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.js.flow b/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.js.flow new file mode 100644 index 0000000..e6370aa --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.js.flow @@ -0,0 +1,36 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import { Kind } from '../../language/kinds'; + +import type { ASTValidationContext } from '../ValidationContext'; + +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ +export function LoneAnonymousOperationRule( + context: ASTValidationContext, +): ASTVisitor { + let operationCount = 0; + return { + Document(node) { + operationCount = node.definitions.filter( + (definition) => definition.kind === Kind.OPERATION_DEFINITION, + ).length; + }, + OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError( + new GraphQLError( + 'This anonymous operation must be the only defined operation.', + node, + ), + ); + } + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs b/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs new file mode 100644 index 0000000..134322d --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs @@ -0,0 +1,24 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { Kind } from "../../language/kinds.mjs"; + +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ +export function LoneAnonymousOperationRule(context) { + var operationCount = 0; + return { + Document: function Document(node) { + operationCount = node.definitions.filter(function (definition) { + return definition.kind === Kind.OPERATION_DEFINITION; + }).length; + }, + OperationDefinition: function OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError(new GraphQLError('This anonymous operation must be the only defined operation.', node)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.d.ts b/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.d.ts new file mode 100644 index 0000000..a38ad06 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.d.ts @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { LoneSchemaDefinitionRule } from 'graphql' + * or + * import { LoneSchemaDefinitionRule } from 'graphql/validation' + */ +export { LoneSchemaDefinitionRule as LoneSchemaDefinition } from './LoneSchemaDefinitionRule'; diff --git a/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.js b/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.js new file mode 100644 index 0000000..55d0b20 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "LoneSchemaDefinition", { + enumerable: true, + get: function get() { + return _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule; + } +}); + +var _LoneSchemaDefinitionRule = require("./LoneSchemaDefinitionRule.js"); diff --git a/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.js.flow b/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.js.flow new file mode 100644 index 0000000..6d0466a --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.js.flow @@ -0,0 +1,9 @@ +// @flow strict +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { LoneSchemaDefinitionRule } from 'graphql' + * or + * import { LoneSchemaDefinitionRule } from 'graphql/validation' + */ +export { LoneSchemaDefinitionRule as LoneSchemaDefinition } from './LoneSchemaDefinitionRule'; diff --git a/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.mjs b/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.mjs new file mode 100644 index 0000000..5485db0 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneSchemaDefinition.mjs @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { LoneSchemaDefinitionRule } from 'graphql' + * or + * import { LoneSchemaDefinitionRule } from 'graphql/validation' + */ +export { LoneSchemaDefinitionRule as LoneSchemaDefinition } from "./LoneSchemaDefinitionRule.mjs"; diff --git a/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.d.ts b/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.d.ts new file mode 100644 index 0000000..5075e74 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.d.ts @@ -0,0 +1,11 @@ +import { ASTVisitor } from '../../language/visitor'; +import { SDLValidationContext } from '../ValidationContext'; + +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ +export function LoneSchemaDefinitionRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.js b/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.js new file mode 100644 index 0000000..ca270c1 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LoneSchemaDefinitionRule = LoneSchemaDefinitionRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ +function LoneSchemaDefinitionRule(context) { + var _ref, _ref2, _oldSchema$astNode; + + var oldSchema = context.getSchema(); + var alreadyDefined = (_ref = (_ref2 = (_oldSchema$astNode = oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 ? _oldSchema$astNode : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getQueryType()) !== null && _ref2 !== void 0 ? _ref2 : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getMutationType()) !== null && _ref !== void 0 ? _ref : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getSubscriptionType(); + var schemaDefinitionsCount = 0; + return { + SchemaDefinition: function SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError(new _GraphQLError.GraphQLError('Cannot define a new schema within a schema extension.', node)); + return; + } + + if (schemaDefinitionsCount > 0) { + context.reportError(new _GraphQLError.GraphQLError('Must provide only one schema definition.', node)); + } + + ++schemaDefinitionsCount; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.js.flow b/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.js.flow new file mode 100644 index 0000000..420a2a0 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.js.flow @@ -0,0 +1,43 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +import type { SDLValidationContext } from '../ValidationContext'; + +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ +export function LoneSchemaDefinitionRule( + context: SDLValidationContext, +): ASTVisitor { + const oldSchema = context.getSchema(); + const alreadyDefined = + oldSchema?.astNode ?? + oldSchema?.getQueryType() ?? + oldSchema?.getMutationType() ?? + oldSchema?.getSubscriptionType(); + + let schemaDefinitionsCount = 0; + return { + SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError( + new GraphQLError( + 'Cannot define a new schema within a schema extension.', + node, + ), + ); + return; + } + + if (schemaDefinitionsCount > 0) { + context.reportError( + new GraphQLError('Must provide only one schema definition.', node), + ); + } + ++schemaDefinitionsCount; + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs b/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs new file mode 100644 index 0000000..ccc5493 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs @@ -0,0 +1,28 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ +export function LoneSchemaDefinitionRule(context) { + var _ref, _ref2, _oldSchema$astNode; + + var oldSchema = context.getSchema(); + var alreadyDefined = (_ref = (_ref2 = (_oldSchema$astNode = oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 ? _oldSchema$astNode : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getQueryType()) !== null && _ref2 !== void 0 ? _ref2 : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getMutationType()) !== null && _ref !== void 0 ? _ref : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getSubscriptionType(); + var schemaDefinitionsCount = 0; + return { + SchemaDefinition: function SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError(new GraphQLError('Cannot define a new schema within a schema extension.', node)); + return; + } + + if (schemaDefinitionsCount > 0) { + context.reportError(new GraphQLError('Must provide only one schema definition.', node)); + } + + ++schemaDefinitionsCount; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.d.ts b/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.d.ts new file mode 100644 index 0000000..85b2b10 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.d.ts @@ -0,0 +1,4 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +export function NoFragmentCyclesRule(context: ValidationContext): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.js b/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.js new file mode 100644 index 0000000..afabeb5 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.js @@ -0,0 +1,70 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NoFragmentCyclesRule = NoFragmentCyclesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +function NoFragmentCyclesRule(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors + + var spreadPath = []; // Position in the spread path + + var spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + } + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; + } + + var fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + var spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (var _i2 = 0; _i2 < spreadNodes.length; _i2++) { + var spreadNode = spreadNodes[_i2]; + var spreadName = spreadNode.name.value; + var cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + + if (cycleIndex === undefined) { + var spreadFragment = context.getFragment(spreadName); + + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + var cyclePath = spreadPath.slice(cycleIndex); + var viaPath = cyclePath.slice(0, -1).map(function (s) { + return '"' + s.name.value + '"'; + }).join(', '); + context.reportError(new _GraphQLError.GraphQLError("Cannot spread fragment \"".concat(spreadName, "\" within itself") + (viaPath !== '' ? " via ".concat(viaPath, ".") : '.'), cyclePath)); + } + + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} diff --git a/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.js.flow b/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.js.flow new file mode 100644 index 0000000..5687322 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.js.flow @@ -0,0 +1,78 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import type { FragmentDefinitionNode } from '../../language/ast'; + +import type { ASTValidationContext } from '../ValidationContext'; + +export function NoFragmentCyclesRule( + context: ASTValidationContext, +): ASTVisitor { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedFrags = Object.create(null); + + // Array of AST nodes used to produce meaningful errors + const spreadPath = []; + + // Position in the spread path + const spreadPathIndexByName = Object.create(null); + + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + }, + }; + + // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + function detectCycleRecursive(fragment: FragmentDefinitionNode): void { + if (visitedFrags[fragment.name.value]) { + return; + } + + const fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + + const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (const spreadNode of spreadNodes) { + const spreadName = spreadNode.name.value; + const cycleIndex = spreadPathIndexByName[spreadName]; + + spreadPath.push(spreadNode); + if (cycleIndex === undefined) { + const spreadFragment = context.getFragment(spreadName); + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + const cyclePath = spreadPath.slice(cycleIndex); + const viaPath = cyclePath + .slice(0, -1) + .map((s) => '"' + s.name.value + '"') + .join(', '); + + context.reportError( + new GraphQLError( + `Cannot spread fragment "${spreadName}" within itself` + + (viaPath !== '' ? ` via ${viaPath}.` : '.'), + cyclePath, + ), + ); + } + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} diff --git a/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs b/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs new file mode 100644 index 0000000..8d7618e --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs @@ -0,0 +1,62 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; +export function NoFragmentCyclesRule(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors + + var spreadPath = []; // Position in the spread path + + var spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + } + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; + } + + var fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + var spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (var _i2 = 0; _i2 < spreadNodes.length; _i2++) { + var spreadNode = spreadNodes[_i2]; + var spreadName = spreadNode.name.value; + var cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + + if (cycleIndex === undefined) { + var spreadFragment = context.getFragment(spreadName); + + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + var cyclePath = spreadPath.slice(cycleIndex); + var viaPath = cyclePath.slice(0, -1).map(function (s) { + return '"' + s.name.value + '"'; + }).join(', '); + context.reportError(new GraphQLError("Cannot spread fragment \"".concat(spreadName, "\" within itself") + (viaPath !== '' ? " via ".concat(viaPath, ".") : '.'), cyclePath)); + } + + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} diff --git a/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.d.ts b/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.d.ts new file mode 100644 index 0000000..d1a0806 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.d.ts @@ -0,0 +1,12 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ +export function NoUndefinedVariablesRule( + context: ValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.js b/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.js new file mode 100644 index 0000000..d3371ec --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NoUndefinedVariablesRule = NoUndefinedVariablesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ +function NoUndefinedVariablesRule(context) { + var variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + variableNameDefined = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + + for (var _i2 = 0; _i2 < usages.length; _i2++) { + var _ref2 = usages[_i2]; + var node = _ref2.node; + var varName = node.name.value; + + if (variableNameDefined[varName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(operation.name ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(operation.name.value, "\".") : "Variable \"$".concat(varName, "\" is not defined."), [node, operation])); + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.js.flow b/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.js.flow new file mode 100644 index 0000000..1773ada --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.js.flow @@ -0,0 +1,46 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; + +import type { ValidationContext } from '../ValidationContext'; + +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ +export function NoUndefinedVariablesRule( + context: ValidationContext, +): ASTVisitor { + let variableNameDefined = Object.create(null); + + return { + OperationDefinition: { + enter() { + variableNameDefined = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node } of usages) { + const varName = node.name.value; + if (variableNameDefined[varName] !== true) { + context.reportError( + new GraphQLError( + operation.name + ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` + : `Variable "$${varName}" is not defined.`, + [node, operation], + ), + ); + } + } + }, + }, + VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs b/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs new file mode 100644 index 0000000..004059f --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs @@ -0,0 +1,34 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ +export function NoUndefinedVariablesRule(context) { + var variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + variableNameDefined = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + + for (var _i2 = 0; _i2 < usages.length; _i2++) { + var _ref2 = usages[_i2]; + var node = _ref2.node; + var varName = node.name.value; + + if (variableNameDefined[varName] !== true) { + context.reportError(new GraphQLError(operation.name ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(operation.name.value, "\".") : "Variable \"$".concat(varName, "\" is not defined."), [node, operation])); + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.d.ts b/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.d.ts new file mode 100644 index 0000000..8435bab --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.d.ts @@ -0,0 +1,10 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ +export function NoUnusedFragmentsRule(context: ValidationContext): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.js b/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.js new file mode 100644 index 0000000..2fa3ba2 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NoUnusedFragmentsRule = NoUnusedFragmentsRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ +function NoUnusedFragmentsRule(context) { + var operationDefs = []; + var fragmentDefs = []; + return { + OperationDefinition: function OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave: function leave() { + var fragmentNameUsed = Object.create(null); + + for (var _i2 = 0; _i2 < operationDefs.length; _i2++) { + var operation = operationDefs[_i2]; + + for (var _i4 = 0, _context$getRecursive2 = context.getRecursivelyReferencedFragments(operation); _i4 < _context$getRecursive2.length; _i4++) { + var fragment = _context$getRecursive2[_i4]; + fragmentNameUsed[fragment.name.value] = true; + } + } + + for (var _i6 = 0; _i6 < fragmentDefs.length; _i6++) { + var fragmentDef = fragmentDefs[_i6]; + var fragName = fragmentDef.name.value; + + if (fragmentNameUsed[fragName] !== true) { + context.reportError(new _GraphQLError.GraphQLError("Fragment \"".concat(fragName, "\" is never used."), fragmentDef)); + } + } + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.js.flow b/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.js.flow new file mode 100644 index 0000000..fd5801b --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.js.flow @@ -0,0 +1,54 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; + +import type { ASTValidationContext } from '../ValidationContext'; + +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ +export function NoUnusedFragmentsRule( + context: ASTValidationContext, +): ASTVisitor { + const operationDefs = []; + const fragmentDefs = []; + + return { + OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave() { + const fragmentNameUsed = Object.create(null); + for (const operation of operationDefs) { + for (const fragment of context.getRecursivelyReferencedFragments( + operation, + )) { + fragmentNameUsed[fragment.name.value] = true; + } + } + + for (const fragmentDef of fragmentDefs) { + const fragName = fragmentDef.name.value; + if (fragmentNameUsed[fragName] !== true) { + context.reportError( + new GraphQLError( + `Fragment "${fragName}" is never used.`, + fragmentDef, + ), + ); + } + } + }, + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs b/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs new file mode 100644 index 0000000..1f5f816 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs @@ -0,0 +1,45 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ +export function NoUnusedFragmentsRule(context) { + var operationDefs = []; + var fragmentDefs = []; + return { + OperationDefinition: function OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave: function leave() { + var fragmentNameUsed = Object.create(null); + + for (var _i2 = 0; _i2 < operationDefs.length; _i2++) { + var operation = operationDefs[_i2]; + + for (var _i4 = 0, _context$getRecursive2 = context.getRecursivelyReferencedFragments(operation); _i4 < _context$getRecursive2.length; _i4++) { + var fragment = _context$getRecursive2[_i4]; + fragmentNameUsed[fragment.name.value] = true; + } + } + + for (var _i6 = 0; _i6 < fragmentDefs.length; _i6++) { + var fragmentDef = fragmentDefs[_i6]; + var fragName = fragmentDef.name.value; + + if (fragmentNameUsed[fragName] !== true) { + context.reportError(new GraphQLError("Fragment \"".concat(fragName, "\" is never used."), fragmentDef)); + } + } + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.d.ts b/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.d.ts new file mode 100644 index 0000000..351449d --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.d.ts @@ -0,0 +1,10 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ +export function NoUnusedVariablesRule(context: ValidationContext): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.js b/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.js new file mode 100644 index 0000000..10fa8c8 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NoUnusedVariablesRule = NoUnusedVariablesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ +function NoUnusedVariablesRule(context) { + var variableDefs = []; + return { + OperationDefinition: { + enter: function enter() { + variableDefs = []; + }, + leave: function leave(operation) { + var variableNameUsed = Object.create(null); + var usages = context.getRecursiveVariableUsages(operation); + + for (var _i2 = 0; _i2 < usages.length; _i2++) { + var _ref2 = usages[_i2]; + var node = _ref2.node; + variableNameUsed[node.name.value] = true; + } + + for (var _i4 = 0, _variableDefs2 = variableDefs; _i4 < _variableDefs2.length; _i4++) { + var variableDef = _variableDefs2[_i4]; + var variableName = variableDef.variable.name.value; + + if (variableNameUsed[variableName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(operation.name ? "Variable \"$".concat(variableName, "\" is never used in operation \"").concat(operation.name.value, "\".") : "Variable \"$".concat(variableName, "\" is never used."), variableDef)); + } + } + } + }, + VariableDefinition: function VariableDefinition(def) { + variableDefs.push(def); + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.js.flow b/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.js.flow new file mode 100644 index 0000000..ed284c8 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.js.flow @@ -0,0 +1,49 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; + +import type { ValidationContext } from '../ValidationContext'; + +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ +export function NoUnusedVariablesRule(context: ValidationContext): ASTVisitor { + let variableDefs = []; + + return { + OperationDefinition: { + enter() { + variableDefs = []; + }, + leave(operation) { + const variableNameUsed = Object.create(null); + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node } of usages) { + variableNameUsed[node.name.value] = true; + } + + for (const variableDef of variableDefs) { + const variableName = variableDef.variable.name.value; + if (variableNameUsed[variableName] !== true) { + context.reportError( + new GraphQLError( + operation.name + ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` + : `Variable "$${variableName}" is never used.`, + variableDef, + ), + ); + } + } + }, + }, + VariableDefinition(def) { + variableDefs.push(def); + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs b/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs new file mode 100644 index 0000000..df62472 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs @@ -0,0 +1,40 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ +export function NoUnusedVariablesRule(context) { + var variableDefs = []; + return { + OperationDefinition: { + enter: function enter() { + variableDefs = []; + }, + leave: function leave(operation) { + var variableNameUsed = Object.create(null); + var usages = context.getRecursiveVariableUsages(operation); + + for (var _i2 = 0; _i2 < usages.length; _i2++) { + var _ref2 = usages[_i2]; + var node = _ref2.node; + variableNameUsed[node.name.value] = true; + } + + for (var _i4 = 0, _variableDefs2 = variableDefs; _i4 < _variableDefs2.length; _i4++) { + var variableDef = _variableDefs2[_i4]; + var variableName = variableDef.variable.name.value; + + if (variableNameUsed[variableName] !== true) { + context.reportError(new GraphQLError(operation.name ? "Variable \"$".concat(variableName, "\" is never used in operation \"").concat(operation.name.value, "\".") : "Variable \"$".concat(variableName, "\" is never used."), variableDef)); + } + } + } + }, + VariableDefinition: function VariableDefinition(def) { + variableDefs.push(def); + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.d.ts b/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.d.ts new file mode 100644 index 0000000..c1671c2 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.d.ts @@ -0,0 +1,13 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ +export function OverlappingFieldsCanBeMergedRule( + context: ValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.js b/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.js new file mode 100644 index 0000000..3fd1813 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.js @@ -0,0 +1,584 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OverlappingFieldsCanBeMergedRule = OverlappingFieldsCanBeMergedRule; + +var _find = _interopRequireDefault(require("../../polyfills/find.js")); + +var _objectEntries3 = _interopRequireDefault(require("../../polyfills/objectEntries.js")); + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect.js")); + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _kinds = require("../../language/kinds.js"); + +var _printer = require("../../language/printer.js"); + +var _definition = require("../../type/definition.js"); + +var _typeFromAST = require("../../utilities/typeFromAST.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason.map(function (_ref) { + var responseName = _ref[0], + subReason = _ref[1]; + return "subfields \"".concat(responseName, "\" conflict because ") + reasonMessage(subReason); + }).join(' and '); + } + + return reason; +} +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ + + +function OverlappingFieldsCanBeMergedRule(context) { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + + var cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet: function SelectionSet(selectionSet) { + var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet); + + for (var _i2 = 0; _i2 < conflicts.length; _i2++) { + var _ref3 = conflicts[_i2]; + var _ref2$ = _ref3[0]; + var responseName = _ref2$[0]; + var reason = _ref2$[1]; + var fields1 = _ref3[1]; + var fields2 = _ref3[2]; + var reasonMsg = reasonMessage(reason); + context.reportError(new _GraphQLError.GraphQLError("Fields \"".concat(responseName, "\" conflict because ").concat(reasonMsg, ". Use different aliases on the fields to fetch both if this was intentional."), fields1.concat(fields2))); + } + } + }; +} + +/** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ +// Find all conflicts found "within" a selection set, including those found +// via spreading in fragments. Called when visiting each SelectionSet in the +// GraphQL Document. +function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) { + var conflicts = []; + + var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet), + fieldMap = _getFieldsAndFragment[0], + fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + + + collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap); + + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + for (var i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + + for (var j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]); + } + } + } + + return conflicts; +} // Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. + + +function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) { + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + return; + } + + var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment), + fieldMap2 = _getReferencedFieldsA[0], + fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself. + + + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + + for (var i = 0; i < fragmentNames2.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]); + } +} // Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. + + +function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + + + if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { + return; + } + + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + var fragment1 = context.getFragment(fragmentName1); + var fragment2 = context.getFragment(fragmentName2); + + if (!fragment1 || !fragment2) { + return; + } + + var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1), + fieldMap1 = _getReferencedFieldsA2[0], + fragmentNames1 = _getReferencedFieldsA2[1]; + + var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2), + fieldMap2 = _getReferencedFieldsA3[0], + fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + + + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2); + } +} // Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. + + +function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) { + var conflicts = []; + + var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1), + fieldMap1 = _getFieldsAndFragment2[0], + fragmentNames1 = _getFieldsAndFragment2[1]; + + var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2), + fieldMap2 = _getFieldsAndFragment3[0], + fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + + if (fragmentNames2.length !== 0) { + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]); + } + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + + + if (fragmentNames1.length !== 0) { + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]); + } + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + + + for (var _i3 = 0; _i3 < fragmentNames1.length; _i3++) { + for (var _j = 0; _j < fragmentNames2.length; _j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i3], fragmentNames2[_j]); + } + } + + return conflicts; +} // Collect all Conflicts "within" one collection of fields. + + +function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + for (var _i5 = 0, _objectEntries2 = (0, _objectEntries3.default)(fieldMap); _i5 < _objectEntries2.length; _i5++) { + var _ref5 = _objectEntries2[_i5]; + var responseName = _ref5[0]; + var fields = _ref5[1]; + + // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + if (fields.length > 1) { + for (var i = 0; i < fields.length; i++) { + for (var j = i + 1; j < fields.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive + responseName, fields[i], fields[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. + + +function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + for (var _i7 = 0, _Object$keys2 = Object.keys(fieldMap1); _i7 < _Object$keys2.length; _i7++) { + var responseName = _Object$keys2[_i7]; + var fields2 = fieldMap2[responseName]; + + if (fields2) { + var fields1 = fieldMap1[responseName]; + + for (var i = 0; i < fields1.length; i++) { + for (var j = 0; j < fields2.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. + + +function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) { + var parentType1 = field1[0], + node1 = field1[1], + def1 = field1[2]; + var parentType2 = field2[0], + node2 = field2[1], + def2 = field2[2]; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + + var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, _definition.isObjectType)(parentType1) && (0, _definition.isObjectType)(parentType2); + + if (!areMutuallyExclusive) { + var _node1$arguments, _node2$arguments; + + // Two aliases must refer to the same field. + var name1 = node1.name.value; + var name2 = node2.name.value; + + if (name1 !== name2) { + return [[responseName, "\"".concat(name1, "\" and \"").concat(name2, "\" are different fields")], [node1], [node2]]; + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + + var args1 = (_node1$arguments = node1.arguments) !== null && _node1$arguments !== void 0 ? _node1$arguments : []; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + var args2 = (_node2$arguments = node2.arguments) !== null && _node2$arguments !== void 0 ? _node2$arguments : []; // Two field calls must have the same arguments. + + if (!sameArguments(args1, args2)) { + return [[responseName, 'they have differing arguments'], [node1], [node2]]; + } + } // The return type for each field. + + + var type1 = def1 === null || def1 === void 0 ? void 0 : def1.type; + var type2 = def2 === null || def2 === void 0 ? void 0 : def2.type; + + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [[responseName, "they return conflicting types \"".concat((0, _inspect.default)(type1), "\" and \"").concat((0, _inspect.default)(type2), "\"")], [node1], [node2]]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + + + var selectionSet1 = node1.selectionSet; + var selectionSet2 = node2.selectionSet; + + if (selectionSet1 && selectionSet2) { + var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, (0, _definition.getNamedType)(type1), selectionSet1, (0, _definition.getNamedType)(type2), selectionSet2); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} + +function sameArguments(arguments1, arguments2) { + if (arguments1.length !== arguments2.length) { + return false; + } + + return arguments1.every(function (argument1) { + var argument2 = (0, _find.default)(arguments2, function (argument) { + return argument.name.value === argument1.name.value; + }); + + if (!argument2) { + return false; + } + + return sameValue(argument1.value, argument2.value); + }); +} + +function sameValue(value1, value2) { + return (0, _printer.print)(value1) === (0, _printer.print)(value2); +} // Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. + + +function doTypesConflict(type1, type2) { + if ((0, _definition.isListType)(type1)) { + return (0, _definition.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if ((0, _definition.isListType)(type2)) { + return true; + } + + if ((0, _definition.isNonNullType)(type1)) { + return (0, _definition.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if ((0, _definition.isNonNullType)(type2)) { + return true; + } + + if ((0, _definition.isLeafType)(type1) || (0, _definition.isLeafType)(type2)) { + return type1 !== type2; + } + + return false; +} // Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. + + +function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) { + var cached = cachedFieldsAndFragmentNames.get(selectionSet); + + if (!cached) { + var nodeAndDefs = Object.create(null); + var fragmentNames = Object.create(null); + + _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames); + + cached = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, cached); + } + + return cached; +} // Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. + + +function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) { + // Short-circuit building a type from the node if possible. + var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + + if (cached) { + return cached; + } + + var fragmentType = (0, _typeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet); +} + +function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) { + for (var _i9 = 0, _selectionSet$selecti2 = selectionSet.selections; _i9 < _selectionSet$selecti2.length; _i9++) { + var selection = _selectionSet$selecti2[_i9]; + + switch (selection.kind) { + case _kinds.Kind.FIELD: + { + var fieldName = selection.name.value; + var fieldDef = void 0; + + if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + + var responseName = selection.alias ? selection.alias.value : fieldName; + + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + } + + case _kinds.Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + + case _kinds.Kind.INLINE_FRAGMENT: + { + var typeCondition = selection.typeCondition; + var inlineFragmentType = typeCondition ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) : parentType; + + _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames); + + break; + } + } + } +} // Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. + + +function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [[responseName, conflicts.map(function (_ref6) { + var reason = _ref6[0]; + return reason; + })], conflicts.reduce(function (allFields, _ref7) { + var fields1 = _ref7[1]; + return allFields.concat(fields1); + }, [node1]), conflicts.reduce(function (allFields, _ref8) { + var fields2 = _ref8[2]; + return allFields.concat(fields2); + }, [node2])]; + } +} +/** + * A way to keep track of pairs of things when the ordering of the pair does + * not matter. We do this by maintaining a sort of double adjacency sets. + */ + + +var PairSet = /*#__PURE__*/function () { + function PairSet() { + this._data = Object.create(null); + } + + var _proto = PairSet.prototype; + + _proto.has = function has(a, b, areMutuallyExclusive) { + var first = this._data[a]; + var result = first && first[b]; + + if (result === undefined) { + return false; + } // areMutuallyExclusive being false is a superset of being true, + // hence if we want to know if this PairSet "has" these two with no + // exclusivity, we have to ensure it was added as such. + + + if (areMutuallyExclusive === false) { + return result === false; + } + + return true; + }; + + _proto.add = function add(a, b, areMutuallyExclusive) { + this._pairSetAdd(a, b, areMutuallyExclusive); + + this._pairSetAdd(b, a, areMutuallyExclusive); + }; + + _proto._pairSetAdd = function _pairSetAdd(a, b, areMutuallyExclusive) { + var map = this._data[a]; + + if (!map) { + map = Object.create(null); + this._data[a] = map; + } + + map[b] = areMutuallyExclusive; + }; + + return PairSet; +}(); diff --git a/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.js.flow b/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.js.flow new file mode 100644 index 0000000..eea7e45 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.js.flow @@ -0,0 +1,833 @@ +// @flow strict +import find from '../../polyfills/find'; +import objectEntries from '../../polyfills/objectEntries'; + +import type { ObjMap } from '../../jsutils/ObjMap'; +import inspect from '../../jsutils/inspect'; + +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import type { + SelectionSetNode, + ValueNode, + FieldNode, + ArgumentNode, + FragmentDefinitionNode, +} from '../../language/ast'; +import { Kind } from '../../language/kinds'; +import { print } from '../../language/printer'; + +import type { + GraphQLNamedType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, +} from '../../type/definition'; +import { + getNamedType, + isNonNullType, + isLeafType, + isObjectType, + isListType, + isInterfaceType, +} from '../../type/definition'; + +import { typeFromAST } from '../../utilities/typeFromAST'; + +import type { ValidationContext } from '../ValidationContext'; + +function reasonMessage(reason: ConflictReasonMessage): string { + if (Array.isArray(reason)) { + return reason + .map( + ([responseName, subReason]) => + `subfields "${responseName}" conflict because ` + + reasonMessage(subReason), + ) + .join(' and '); + } + return reason; +} + +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ +export function OverlappingFieldsCanBeMergedRule( + context: ValidationContext, +): ASTVisitor { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + const comparedFragmentPairs = new PairSet(); + + // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + const cachedFieldsAndFragmentNames = new Map(); + + return { + SelectionSet(selectionSet) { + const conflicts = findConflictsWithinSelectionSet( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + context.getParentType(), + selectionSet, + ); + for (const [[responseName, reason], fields1, fields2] of conflicts) { + const reasonMsg = reasonMessage(reason); + context.reportError( + new GraphQLError( + `Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, + fields1.concat(fields2), + ), + ); + } + }, + }; +} + +type Conflict = [ConflictReason, Array<FieldNode>, Array<FieldNode>]; +// Field name and reason. +type ConflictReason = [string, ConflictReasonMessage]; +// Reason is a string, or a nested list of conflicts. +type ConflictReasonMessage = string | Array<ConflictReason>; +// Tuple defining a field node in a context. +type NodeAndDef = [ + GraphQLCompositeType, + FieldNode, + ?GraphQLField<mixed, mixed>, +]; +// Map of array of those. +type NodeAndDefCollection = ObjMap<Array<NodeAndDef>>; + +/** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ + +// Find all conflicts found "within" a selection set, including those found +// via spreading in fragments. Called when visiting each SelectionSet in the +// GraphQL Document. +function findConflictsWithinSelectionSet( + context: ValidationContext, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + parentType: ?GraphQLNamedType, + selectionSet: SelectionSetNode, +): Array<Conflict> { + const conflicts = []; + + const [fieldMap, fragmentNames] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType, + selectionSet, + ); + + // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + collectConflictsWithin( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + fieldMap, + ); + + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + for (let i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + false, + fieldMap, + fragmentNames[i], + ); + // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + for (let j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + false, + fragmentNames[i], + fragmentNames[j], + ); + } + } + } + return conflicts; +} + +// Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. +function collectConflictsBetweenFieldsAndFragment( + context: ValidationContext, + conflicts: Array<Conflict>, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + areMutuallyExclusive: boolean, + fieldMap: NodeAndDefCollection, + fragmentName: string, +): void { + const fragment = context.getFragment(fragmentName); + if (!fragment) { + return; + } + + const [fieldMap2, fragmentNames2] = getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment, + ); + + // Do not compare a fragment's fieldMap to itself. + if (fieldMap === fieldMap2) { + return; + } + + // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fieldMap2, + ); + + // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + for (let i = 0; i < fragmentNames2.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fragmentNames2[i], + ); + } +} + +// Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. +function collectConflictsBetweenFragments( + context: ValidationContext, + conflicts: Array<Conflict>, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + areMutuallyExclusive: boolean, + fragmentName1: string, + fragmentName2: string, +): void { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } + + // Memoize so two fragments are not compared for conflicts more than once. + if ( + comparedFragmentPairs.has( + fragmentName1, + fragmentName2, + areMutuallyExclusive, + ) + ) { + return; + } + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + + const fragment1 = context.getFragment(fragmentName1); + const fragment2 = context.getFragment(fragmentName2); + if (!fragment1 || !fragment2) { + return; + } + + const [fieldMap1, fragmentNames1] = getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment1, + ); + const [fieldMap2, fragmentNames2] = getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment2, + ); + + // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); + + // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + for (let j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentNames2[j], + ); + } + + // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + for (let i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentNames1[i], + fragmentName2, + ); + } +} + +// Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. +function findConflictsBetweenSubSelectionSets( + context: ValidationContext, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + areMutuallyExclusive: boolean, + parentType1: ?GraphQLNamedType, + selectionSet1: SelectionSetNode, + parentType2: ?GraphQLNamedType, + selectionSet2: SelectionSetNode, +): Array<Conflict> { + const conflicts = []; + + const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType1, + selectionSet1, + ); + const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType2, + selectionSet2, + ); + + // (H) First, collect all conflicts between these two collections of field. + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); + + // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + if (fragmentNames2.length !== 0) { + for (let j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fragmentNames2[j], + ); + } + } + + // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + if (fragmentNames1.length !== 0) { + for (let i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap2, + fragmentNames1[i], + ); + } + } + + // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + for (let i = 0; i < fragmentNames1.length; i++) { + for (let j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentNames1[i], + fragmentNames2[j], + ); + } + } + return conflicts; +} + +// Collect all Conflicts "within" one collection of fields. +function collectConflictsWithin( + context: ValidationContext, + conflicts: Array<Conflict>, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + fieldMap: NodeAndDefCollection, +): void { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + for (const [responseName, fields] of objectEntries(fieldMap)) { + // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + if (fields.length > 1) { + for (let i = 0; i < fields.length; i++) { + for (let j = i + 1; j < fields.length; j++) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + false, // within one collection is never mutually exclusive + responseName, + fields[i], + fields[j], + ); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} + +// Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. +function collectConflictsBetween( + context: ValidationContext, + conflicts: Array<Conflict>, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + parentFieldsAreMutuallyExclusive: boolean, + fieldMap1: NodeAndDefCollection, + fieldMap2: NodeAndDefCollection, +): void { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + for (const responseName of Object.keys(fieldMap1)) { + const fields2 = fieldMap2[responseName]; + if (fields2) { + const fields1 = fieldMap1[responseName]; + for (let i = 0; i < fields1.length; i++) { + for (let j = 0; j < fields2.length; j++) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + fields1[i], + fields2[j], + ); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} + +// Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. +function findConflict( + context: ValidationContext, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + parentFieldsAreMutuallyExclusive: boolean, + responseName: string, + field1: NodeAndDef, + field2: NodeAndDef, +): ?Conflict { + const [parentType1, node1, def1] = field1; + const [parentType2, node2, def2] = field2; + + // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + const areMutuallyExclusive = + parentFieldsAreMutuallyExclusive || + (parentType1 !== parentType2 && + isObjectType(parentType1) && + isObjectType(parentType2)); + + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + const name1 = node1.name.value; + const name2 = node2.name.value; + if (name1 !== name2) { + return [ + [responseName, `"${name1}" and "${name2}" are different fields`], + [node1], + [node2], + ]; + } + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const args1 = node1.arguments ?? []; + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const args2 = node2.arguments ?? []; + // Two field calls must have the same arguments. + if (!sameArguments(args1, args2)) { + return [ + [responseName, 'they have differing arguments'], + [node1], + [node2], + ]; + } + } + + // The return type for each field. + const type1 = def1?.type; + const type2 = def2?.type; + + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [ + [ + responseName, + `they return conflicting types "${inspect(type1)}" and "${inspect( + type2, + )}"`, + ], + [node1], + [node2], + ]; + } + + // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + const selectionSet1 = node1.selectionSet; + const selectionSet2 = node2.selectionSet; + if (selectionSet1 && selectionSet2) { + const conflicts = findConflictsBetweenSubSelectionSets( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + getNamedType(type1), + selectionSet1, + getNamedType(type2), + selectionSet2, + ); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} + +function sameArguments( + arguments1: $ReadOnlyArray<ArgumentNode>, + arguments2: $ReadOnlyArray<ArgumentNode>, +): boolean { + if (arguments1.length !== arguments2.length) { + return false; + } + return arguments1.every((argument1) => { + const argument2 = find( + arguments2, + (argument) => argument.name.value === argument1.name.value, + ); + if (!argument2) { + return false; + } + return sameValue(argument1.value, argument2.value); + }); +} + +function sameValue(value1: ValueNode, value2: ValueNode): boolean { + return print(value1) === print(value2); +} + +// Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. +function doTypesConflict( + type1: GraphQLOutputType, + type2: GraphQLOutputType, +): boolean { + if (isListType(type1)) { + return isListType(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + if (isListType(type2)) { + return true; + } + if (isNonNullType(type1)) { + return isNonNullType(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + if (isNonNullType(type2)) { + return true; + } + if (isLeafType(type1) || isLeafType(type2)) { + return type1 !== type2; + } + return false; +} + +// Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. +function getFieldsAndFragmentNames( + context: ValidationContext, + cachedFieldsAndFragmentNames, + parentType: ?GraphQLNamedType, + selectionSet: SelectionSetNode, +): [NodeAndDefCollection, Array<string>] { + let cached = cachedFieldsAndFragmentNames.get(selectionSet); + if (!cached) { + const nodeAndDefs = Object.create(null); + const fragmentNames = Object.create(null); + _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames, + ); + cached = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, cached); + } + return cached; +} + +// Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. +function getReferencedFieldsAndFragmentNames( + context: ValidationContext, + cachedFieldsAndFragmentNames, + fragment: FragmentDefinitionNode, +) { + // Short-circuit building a type from the node if possible. + const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + if (cached) { + return cached; + } + + const fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragmentType, + fragment.selectionSet, + ); +} + +function _collectFieldsAndFragmentNames( + context: ValidationContext, + parentType: ?GraphQLNamedType, + selectionSet: SelectionSetNode, + nodeAndDefs, + fragmentNames, +): void { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case Kind.FIELD: { + const fieldName = selection.name.value; + let fieldDef; + if (isObjectType(parentType) || isInterfaceType(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + const responseName = selection.alias + ? selection.alias.value + : fieldName; + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + } + case Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + case Kind.INLINE_FRAGMENT: { + const typeCondition = selection.typeCondition; + const inlineFragmentType = typeCondition + ? typeFromAST(context.getSchema(), typeCondition) + : parentType; + _collectFieldsAndFragmentNames( + context, + inlineFragmentType, + selection.selectionSet, + nodeAndDefs, + fragmentNames, + ); + break; + } + } + } +} + +// Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. +function subfieldConflicts( + conflicts: $ReadOnlyArray<Conflict>, + responseName: string, + node1: FieldNode, + node2: FieldNode, +): ?Conflict { + if (conflicts.length > 0) { + return [ + [responseName, conflicts.map(([reason]) => reason)], + conflicts.reduce((allFields, [, fields1]) => allFields.concat(fields1), [ + node1, + ]), + conflicts.reduce( + (allFields, [, , fields2]) => allFields.concat(fields2), + [node2], + ), + ]; + } +} + +/** + * A way to keep track of pairs of things when the ordering of the pair does + * not matter. We do this by maintaining a sort of double adjacency sets. + */ +class PairSet { + _data: ObjMap<ObjMap<boolean>>; + + constructor() { + this._data = Object.create(null); + } + + has(a: string, b: string, areMutuallyExclusive: boolean): boolean { + const first = this._data[a]; + const result = first && first[b]; + if (result === undefined) { + return false; + } + // areMutuallyExclusive being false is a superset of being true, + // hence if we want to know if this PairSet "has" these two with no + // exclusivity, we have to ensure it was added as such. + if (areMutuallyExclusive === false) { + return result === false; + } + return true; + } + + add(a: string, b: string, areMutuallyExclusive: boolean): void { + this._pairSetAdd(a, b, areMutuallyExclusive); + this._pairSetAdd(b, a, areMutuallyExclusive); + } + + _pairSetAdd(a: string, b: string, areMutuallyExclusive: boolean): void { + let map = this._data[a]; + if (!map) { + map = Object.create(null); + this._data[a] = map; + } + map[b] = areMutuallyExclusive; + } +} diff --git a/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs b/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs new file mode 100644 index 0000000..afc5243 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs @@ -0,0 +1,568 @@ +import find from "../../polyfills/find.mjs"; +import objectEntries from "../../polyfills/objectEntries.mjs"; +import inspect from "../../jsutils/inspect.mjs"; +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { Kind } from "../../language/kinds.mjs"; +import { print } from "../../language/printer.mjs"; +import { getNamedType, isNonNullType, isLeafType, isObjectType, isListType, isInterfaceType } from "../../type/definition.mjs"; +import { typeFromAST } from "../../utilities/typeFromAST.mjs"; + +function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason.map(function (_ref) { + var responseName = _ref[0], + subReason = _ref[1]; + return "subfields \"".concat(responseName, "\" conflict because ") + reasonMessage(subReason); + }).join(' and '); + } + + return reason; +} +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ + + +export function OverlappingFieldsCanBeMergedRule(context) { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + + var cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet: function SelectionSet(selectionSet) { + var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet); + + for (var _i2 = 0; _i2 < conflicts.length; _i2++) { + var _ref3 = conflicts[_i2]; + var _ref2$ = _ref3[0]; + var responseName = _ref2$[0]; + var reason = _ref2$[1]; + var fields1 = _ref3[1]; + var fields2 = _ref3[2]; + var reasonMsg = reasonMessage(reason); + context.reportError(new GraphQLError("Fields \"".concat(responseName, "\" conflict because ").concat(reasonMsg, ". Use different aliases on the fields to fetch both if this was intentional."), fields1.concat(fields2))); + } + } + }; +} + +/** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ +// Find all conflicts found "within" a selection set, including those found +// via spreading in fragments. Called when visiting each SelectionSet in the +// GraphQL Document. +function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) { + var conflicts = []; + + var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet), + fieldMap = _getFieldsAndFragment[0], + fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + + + collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap); + + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + for (var i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + + for (var j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]); + } + } + } + + return conflicts; +} // Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. + + +function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) { + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + return; + } + + var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment), + fieldMap2 = _getReferencedFieldsA[0], + fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself. + + + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + + for (var i = 0; i < fragmentNames2.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]); + } +} // Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. + + +function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + + + if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { + return; + } + + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + var fragment1 = context.getFragment(fragmentName1); + var fragment2 = context.getFragment(fragmentName2); + + if (!fragment1 || !fragment2) { + return; + } + + var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1), + fieldMap1 = _getReferencedFieldsA2[0], + fragmentNames1 = _getReferencedFieldsA2[1]; + + var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2), + fieldMap2 = _getReferencedFieldsA3[0], + fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + + + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2); + } +} // Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. + + +function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) { + var conflicts = []; + + var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1), + fieldMap1 = _getFieldsAndFragment2[0], + fragmentNames1 = _getFieldsAndFragment2[1]; + + var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2), + fieldMap2 = _getFieldsAndFragment3[0], + fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + + if (fragmentNames2.length !== 0) { + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]); + } + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + + + if (fragmentNames1.length !== 0) { + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]); + } + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + + + for (var _i3 = 0; _i3 < fragmentNames1.length; _i3++) { + for (var _j = 0; _j < fragmentNames2.length; _j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i3], fragmentNames2[_j]); + } + } + + return conflicts; +} // Collect all Conflicts "within" one collection of fields. + + +function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + for (var _i5 = 0, _objectEntries2 = objectEntries(fieldMap); _i5 < _objectEntries2.length; _i5++) { + var _ref5 = _objectEntries2[_i5]; + var responseName = _ref5[0]; + var fields = _ref5[1]; + + // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + if (fields.length > 1) { + for (var i = 0; i < fields.length; i++) { + for (var j = i + 1; j < fields.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive + responseName, fields[i], fields[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. + + +function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + for (var _i7 = 0, _Object$keys2 = Object.keys(fieldMap1); _i7 < _Object$keys2.length; _i7++) { + var responseName = _Object$keys2[_i7]; + var fields2 = fieldMap2[responseName]; + + if (fields2) { + var fields1 = fieldMap1[responseName]; + + for (var i = 0; i < fields1.length; i++) { + for (var j = 0; j < fields2.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. + + +function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) { + var parentType1 = field1[0], + node1 = field1[1], + def1 = field1[2]; + var parentType2 = field2[0], + node2 = field2[1], + def2 = field2[2]; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + + var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && isObjectType(parentType1) && isObjectType(parentType2); + + if (!areMutuallyExclusive) { + var _node1$arguments, _node2$arguments; + + // Two aliases must refer to the same field. + var name1 = node1.name.value; + var name2 = node2.name.value; + + if (name1 !== name2) { + return [[responseName, "\"".concat(name1, "\" and \"").concat(name2, "\" are different fields")], [node1], [node2]]; + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + + var args1 = (_node1$arguments = node1.arguments) !== null && _node1$arguments !== void 0 ? _node1$arguments : []; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + var args2 = (_node2$arguments = node2.arguments) !== null && _node2$arguments !== void 0 ? _node2$arguments : []; // Two field calls must have the same arguments. + + if (!sameArguments(args1, args2)) { + return [[responseName, 'they have differing arguments'], [node1], [node2]]; + } + } // The return type for each field. + + + var type1 = def1 === null || def1 === void 0 ? void 0 : def1.type; + var type2 = def2 === null || def2 === void 0 ? void 0 : def2.type; + + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [[responseName, "they return conflicting types \"".concat(inspect(type1), "\" and \"").concat(inspect(type2), "\"")], [node1], [node2]]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + + + var selectionSet1 = node1.selectionSet; + var selectionSet2 = node2.selectionSet; + + if (selectionSet1 && selectionSet2) { + var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, getNamedType(type1), selectionSet1, getNamedType(type2), selectionSet2); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} + +function sameArguments(arguments1, arguments2) { + if (arguments1.length !== arguments2.length) { + return false; + } + + return arguments1.every(function (argument1) { + var argument2 = find(arguments2, function (argument) { + return argument.name.value === argument1.name.value; + }); + + if (!argument2) { + return false; + } + + return sameValue(argument1.value, argument2.value); + }); +} + +function sameValue(value1, value2) { + return print(value1) === print(value2); +} // Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. + + +function doTypesConflict(type1, type2) { + if (isListType(type1)) { + return isListType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if (isListType(type2)) { + return true; + } + + if (isNonNullType(type1)) { + return isNonNullType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if (isNonNullType(type2)) { + return true; + } + + if (isLeafType(type1) || isLeafType(type2)) { + return type1 !== type2; + } + + return false; +} // Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. + + +function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) { + var cached = cachedFieldsAndFragmentNames.get(selectionSet); + + if (!cached) { + var nodeAndDefs = Object.create(null); + var fragmentNames = Object.create(null); + + _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames); + + cached = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, cached); + } + + return cached; +} // Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. + + +function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) { + // Short-circuit building a type from the node if possible. + var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + + if (cached) { + return cached; + } + + var fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet); +} + +function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) { + for (var _i9 = 0, _selectionSet$selecti2 = selectionSet.selections; _i9 < _selectionSet$selecti2.length; _i9++) { + var selection = _selectionSet$selecti2[_i9]; + + switch (selection.kind) { + case Kind.FIELD: + { + var fieldName = selection.name.value; + var fieldDef = void 0; + + if (isObjectType(parentType) || isInterfaceType(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + + var responseName = selection.alias ? selection.alias.value : fieldName; + + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + } + + case Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + + case Kind.INLINE_FRAGMENT: + { + var typeCondition = selection.typeCondition; + var inlineFragmentType = typeCondition ? typeFromAST(context.getSchema(), typeCondition) : parentType; + + _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames); + + break; + } + } + } +} // Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. + + +function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [[responseName, conflicts.map(function (_ref6) { + var reason = _ref6[0]; + return reason; + })], conflicts.reduce(function (allFields, _ref7) { + var fields1 = _ref7[1]; + return allFields.concat(fields1); + }, [node1]), conflicts.reduce(function (allFields, _ref8) { + var fields2 = _ref8[2]; + return allFields.concat(fields2); + }, [node2])]; + } +} +/** + * A way to keep track of pairs of things when the ordering of the pair does + * not matter. We do this by maintaining a sort of double adjacency sets. + */ + + +var PairSet = /*#__PURE__*/function () { + function PairSet() { + this._data = Object.create(null); + } + + var _proto = PairSet.prototype; + + _proto.has = function has(a, b, areMutuallyExclusive) { + var first = this._data[a]; + var result = first && first[b]; + + if (result === undefined) { + return false; + } // areMutuallyExclusive being false is a superset of being true, + // hence if we want to know if this PairSet "has" these two with no + // exclusivity, we have to ensure it was added as such. + + + if (areMutuallyExclusive === false) { + return result === false; + } + + return true; + }; + + _proto.add = function add(a, b, areMutuallyExclusive) { + this._pairSetAdd(a, b, areMutuallyExclusive); + + this._pairSetAdd(b, a, areMutuallyExclusive); + }; + + _proto._pairSetAdd = function _pairSetAdd(a, b, areMutuallyExclusive) { + var map = this._data[a]; + + if (!map) { + map = Object.create(null); + this._data[a] = map; + } + + map[b] = areMutuallyExclusive; + }; + + return PairSet; +}(); diff --git a/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.d.ts b/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.d.ts new file mode 100644 index 0000000..36f551d --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.d.ts @@ -0,0 +1,13 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ +export function PossibleFragmentSpreadsRule( + context: ValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.js b/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.js new file mode 100644 index 0000000..427905d --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.js @@ -0,0 +1,63 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PossibleFragmentSpreadsRule = PossibleFragmentSpreadsRule; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect.js")); + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _definition = require("../../type/definition.js"); + +var _typeFromAST = require("../../utilities/typeFromAST.js"); + +var _typeComparators = require("../../utilities/typeComparators.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ +function PossibleFragmentSpreadsRule(context) { + return { + InlineFragment: function InlineFragment(node) { + var fragType = context.getType(); + var parentType = context.getParentType(); + + if ((0, _definition.isCompositeType)(fragType) && (0, _definition.isCompositeType)(parentType) && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + var parentTypeStr = (0, _inspect.default)(parentType); + var fragTypeStr = (0, _inspect.default)(fragType); + context.reportError(new _GraphQLError.GraphQLError("Fragment cannot be spread here as objects of type \"".concat(parentTypeStr, "\" can never be of type \"").concat(fragTypeStr, "\"."), node)); + } + }, + FragmentSpread: function FragmentSpread(node) { + var fragName = node.name.value; + var fragType = getFragmentType(context, fragName); + var parentType = context.getParentType(); + + if (fragType && parentType && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + var parentTypeStr = (0, _inspect.default)(parentType); + var fragTypeStr = (0, _inspect.default)(fragType); + context.reportError(new _GraphQLError.GraphQLError("Fragment \"".concat(fragName, "\" cannot be spread here as objects of type \"").concat(parentTypeStr, "\" can never be of type \"").concat(fragTypeStr, "\"."), node)); + } + } + }; +} + +function getFragmentType(context, name) { + var frag = context.getFragment(name); + + if (frag) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition); + + if ((0, _definition.isCompositeType)(type)) { + return type; + } + } +} diff --git a/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.js.flow b/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.js.flow new file mode 100644 index 0000000..9c275bb --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.js.flow @@ -0,0 +1,78 @@ +// @flow strict +import inspect from '../../jsutils/inspect'; + +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; + +import type { GraphQLCompositeType } from '../../type/definition'; +import { isCompositeType } from '../../type/definition'; + +import { typeFromAST } from '../../utilities/typeFromAST'; +import { doTypesOverlap } from '../../utilities/typeComparators'; + +import type { ValidationContext } from '../ValidationContext'; + +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ +export function PossibleFragmentSpreadsRule( + context: ValidationContext, +): ASTVisitor { + return { + InlineFragment(node) { + const fragType = context.getType(); + const parentType = context.getParentType(); + if ( + isCompositeType(fragType) && + isCompositeType(parentType) && + !doTypesOverlap(context.getSchema(), fragType, parentType) + ) { + const parentTypeStr = inspect(parentType); + const fragTypeStr = inspect(fragType); + context.reportError( + new GraphQLError( + `Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, + node, + ), + ); + } + }, + FragmentSpread(node) { + const fragName = node.name.value; + const fragType = getFragmentType(context, fragName); + const parentType = context.getParentType(); + if ( + fragType && + parentType && + !doTypesOverlap(context.getSchema(), fragType, parentType) + ) { + const parentTypeStr = inspect(parentType); + const fragTypeStr = inspect(fragType); + context.reportError( + new GraphQLError( + `Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, + node, + ), + ); + } + }, + }; +} + +function getFragmentType( + context: ValidationContext, + name: string, +): ?GraphQLCompositeType { + const frag = context.getFragment(name); + if (frag) { + const type = typeFromAST(context.getSchema(), frag.typeCondition); + if (isCompositeType(type)) { + return type; + } + } +} diff --git a/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs b/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs new file mode 100644 index 0000000..da45925 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs @@ -0,0 +1,50 @@ +import inspect from "../../jsutils/inspect.mjs"; +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { isCompositeType } from "../../type/definition.mjs"; +import { typeFromAST } from "../../utilities/typeFromAST.mjs"; +import { doTypesOverlap } from "../../utilities/typeComparators.mjs"; + +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ +export function PossibleFragmentSpreadsRule(context) { + return { + InlineFragment: function InlineFragment(node) { + var fragType = context.getType(); + var parentType = context.getParentType(); + + if (isCompositeType(fragType) && isCompositeType(parentType) && !doTypesOverlap(context.getSchema(), fragType, parentType)) { + var parentTypeStr = inspect(parentType); + var fragTypeStr = inspect(fragType); + context.reportError(new GraphQLError("Fragment cannot be spread here as objects of type \"".concat(parentTypeStr, "\" can never be of type \"").concat(fragTypeStr, "\"."), node)); + } + }, + FragmentSpread: function FragmentSpread(node) { + var fragName = node.name.value; + var fragType = getFragmentType(context, fragName); + var parentType = context.getParentType(); + + if (fragType && parentType && !doTypesOverlap(context.getSchema(), fragType, parentType)) { + var parentTypeStr = inspect(parentType); + var fragTypeStr = inspect(fragType); + context.reportError(new GraphQLError("Fragment \"".concat(fragName, "\" cannot be spread here as objects of type \"").concat(parentTypeStr, "\" can never be of type \"").concat(fragTypeStr, "\"."), node)); + } + } + }; +} + +function getFragmentType(context, name) { + var frag = context.getFragment(name); + + if (frag) { + var type = typeFromAST(context.getSchema(), frag.typeCondition); + + if (isCompositeType(type)) { + return type; + } + } +} diff --git a/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.d.ts b/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.d.ts new file mode 100644 index 0000000..7573375 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.d.ts @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { PossibleTypeExtensionsRule } from 'graphql' + * or + * import { PossibleTypeExtensionsRule } from 'graphql/validation' + */ +export { PossibleTypeExtensionsRule as PossibleTypeExtensions } from './PossibleTypeExtensionsRule'; diff --git a/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.js b/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.js new file mode 100644 index 0000000..fc15d85 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "PossibleTypeExtensions", { + enumerable: true, + get: function get() { + return _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule; + } +}); + +var _PossibleTypeExtensionsRule = require("./PossibleTypeExtensionsRule.js"); diff --git a/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.js.flow b/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.js.flow new file mode 100644 index 0000000..ed223f1 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.js.flow @@ -0,0 +1,9 @@ +// @flow strict +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { PossibleTypeExtensionsRule } from 'graphql' + * or + * import { PossibleTypeExtensionsRule } from 'graphql/validation' + */ +export { PossibleTypeExtensionsRule as PossibleTypeExtensions } from './PossibleTypeExtensionsRule'; diff --git a/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.mjs b/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.mjs new file mode 100644 index 0000000..99796c8 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleTypeExtensions.mjs @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { PossibleTypeExtensionsRule } from 'graphql' + * or + * import { PossibleTypeExtensionsRule } from 'graphql/validation' + */ +export { PossibleTypeExtensionsRule as PossibleTypeExtensions } from "./PossibleTypeExtensionsRule.mjs"; diff --git a/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.d.ts b/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.d.ts new file mode 100644 index 0000000..8337dc5 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.d.ts @@ -0,0 +1,11 @@ +import { ASTVisitor } from '../../language/visitor'; +import { SDLValidationContext } from '../ValidationContext'; + +/** + * Possible type extension + * + * A type extension is only valid if the type is defined and has the same kind. + */ +export function PossibleTypeExtensionsRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.js b/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.js new file mode 100644 index 0000000..309b12b --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.js @@ -0,0 +1,141 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PossibleTypeExtensionsRule = PossibleTypeExtensionsRule; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect.js")); + +var _invariant = _interopRequireDefault(require("../../jsutils/invariant.js")); + +var _didYouMean = _interopRequireDefault(require("../../jsutils/didYouMean.js")); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList.js")); + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _kinds = require("../../language/kinds.js"); + +var _predicates = require("../../language/predicates.js"); + +var _definition = require("../../type/definition.js"); + +var _defKindToExtKind; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Possible type extension + * + * A type extension is only valid if the type is defined and has the same kind. + */ +function PossibleTypeExtensionsRule(context) { + var schema = context.getSchema(); + var definedTypes = Object.create(null); + + for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) { + var def = _context$getDocument$2[_i2]; + + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = def; + } + } + + return { + ScalarTypeExtension: checkExtension, + ObjectTypeExtension: checkExtension, + InterfaceTypeExtension: checkExtension, + UnionTypeExtension: checkExtension, + EnumTypeExtension: checkExtension, + InputObjectTypeExtension: checkExtension + }; + + function checkExtension(node) { + var typeName = node.name.value; + var defNode = definedTypes[typeName]; + var existingType = schema === null || schema === void 0 ? void 0 : schema.getType(typeName); + var expectedKind; + + if (defNode) { + expectedKind = defKindToExtKind[defNode.kind]; + } else if (existingType) { + expectedKind = typeToExtKind(existingType); + } + + if (expectedKind) { + if (expectedKind !== node.kind) { + var kindStr = extensionKindToTypeName(node.kind); + context.reportError(new _GraphQLError.GraphQLError("Cannot extend non-".concat(kindStr, " type \"").concat(typeName, "\"."), defNode ? [defNode, node] : node)); + } + } else { + var allTypeNames = Object.keys(definedTypes); + + if (schema) { + allTypeNames = allTypeNames.concat(Object.keys(schema.getTypeMap())); + } + + var suggestedTypes = (0, _suggestionList.default)(typeName, allTypeNames); + context.reportError(new _GraphQLError.GraphQLError("Cannot extend type \"".concat(typeName, "\" because it is not defined.") + (0, _didYouMean.default)(suggestedTypes), node.name)); + } + } +} + +var defKindToExtKind = (_defKindToExtKind = {}, _defineProperty(_defKindToExtKind, _kinds.Kind.SCALAR_TYPE_DEFINITION, _kinds.Kind.SCALAR_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.OBJECT_TYPE_DEFINITION, _kinds.Kind.OBJECT_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.INTERFACE_TYPE_DEFINITION, _kinds.Kind.INTERFACE_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.UNION_TYPE_DEFINITION, _kinds.Kind.UNION_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.ENUM_TYPE_DEFINITION, _kinds.Kind.ENUM_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION), _defKindToExtKind); + +function typeToExtKind(type) { + if ((0, _definition.isScalarType)(type)) { + return _kinds.Kind.SCALAR_TYPE_EXTENSION; + } + + if ((0, _definition.isObjectType)(type)) { + return _kinds.Kind.OBJECT_TYPE_EXTENSION; + } + + if ((0, _definition.isInterfaceType)(type)) { + return _kinds.Kind.INTERFACE_TYPE_EXTENSION; + } + + if ((0, _definition.isUnionType)(type)) { + return _kinds.Kind.UNION_TYPE_EXTENSION; + } + + if ((0, _definition.isEnumType)(type)) { + return _kinds.Kind.ENUM_TYPE_EXTENSION; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if ((0, _definition.isInputObjectType)(type)) { + return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected type: ' + (0, _inspect.default)(type)); +} + +function extensionKindToTypeName(kind) { + switch (kind) { + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return 'scalar'; + + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return 'object'; + + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return 'interface'; + + case _kinds.Kind.UNION_TYPE_EXTENSION: + return 'union'; + + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return 'enum'; + + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return 'input object'; + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || (0, _invariant.default)(0, 'Unexpected kind: ' + (0, _inspect.default)(kind)); +} diff --git a/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.js.flow b/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.js.flow new file mode 100644 index 0000000..15ec1b4 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.js.flow @@ -0,0 +1,145 @@ +// @flow strict +import inspect from '../../jsutils/inspect'; +import invariant from '../../jsutils/invariant'; +import didYouMean from '../../jsutils/didYouMean'; +import suggestionList from '../../jsutils/suggestionList'; + +import { GraphQLError } from '../../error/GraphQLError'; + +import type { KindEnum } from '../../language/kinds'; +import type { ASTVisitor } from '../../language/visitor'; +import type { TypeExtensionNode } from '../../language/ast'; +import { Kind } from '../../language/kinds'; +import { isTypeDefinitionNode } from '../../language/predicates'; + +import type { GraphQLNamedType } from '../../type/definition'; +import { + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, +} from '../../type/definition'; + +import type { SDLValidationContext } from '../ValidationContext'; + +/** + * Possible type extension + * + * A type extension is only valid if the type is defined and has the same kind. + */ +export function PossibleTypeExtensionsRule( + context: SDLValidationContext, +): ASTVisitor { + const schema = context.getSchema(); + const definedTypes = Object.create(null); + + for (const def of context.getDocument().definitions) { + if (isTypeDefinitionNode(def)) { + definedTypes[def.name.value] = def; + } + } + + return { + ScalarTypeExtension: checkExtension, + ObjectTypeExtension: checkExtension, + InterfaceTypeExtension: checkExtension, + UnionTypeExtension: checkExtension, + EnumTypeExtension: checkExtension, + InputObjectTypeExtension: checkExtension, + }; + + function checkExtension(node: TypeExtensionNode): void { + const typeName = node.name.value; + const defNode = definedTypes[typeName]; + const existingType = schema?.getType(typeName); + + let expectedKind; + if (defNode) { + expectedKind = defKindToExtKind[defNode.kind]; + } else if (existingType) { + expectedKind = typeToExtKind(existingType); + } + + if (expectedKind) { + if (expectedKind !== node.kind) { + const kindStr = extensionKindToTypeName(node.kind); + context.reportError( + new GraphQLError( + `Cannot extend non-${kindStr} type "${typeName}".`, + defNode ? [defNode, node] : node, + ), + ); + } + } else { + let allTypeNames = Object.keys(definedTypes); + if (schema) { + allTypeNames = allTypeNames.concat(Object.keys(schema.getTypeMap())); + } + + const suggestedTypes = suggestionList(typeName, allTypeNames); + context.reportError( + new GraphQLError( + `Cannot extend type "${typeName}" because it is not defined.` + + didYouMean(suggestedTypes), + node.name, + ), + ); + } + } +} + +const defKindToExtKind = { + [Kind.SCALAR_TYPE_DEFINITION]: Kind.SCALAR_TYPE_EXTENSION, + [Kind.OBJECT_TYPE_DEFINITION]: Kind.OBJECT_TYPE_EXTENSION, + [Kind.INTERFACE_TYPE_DEFINITION]: Kind.INTERFACE_TYPE_EXTENSION, + [Kind.UNION_TYPE_DEFINITION]: Kind.UNION_TYPE_EXTENSION, + [Kind.ENUM_TYPE_DEFINITION]: Kind.ENUM_TYPE_EXTENSION, + [Kind.INPUT_OBJECT_TYPE_DEFINITION]: Kind.INPUT_OBJECT_TYPE_EXTENSION, +}; + +function typeToExtKind(type: GraphQLNamedType): KindEnum { + if (isScalarType(type)) { + return Kind.SCALAR_TYPE_EXTENSION; + } + if (isObjectType(type)) { + return Kind.OBJECT_TYPE_EXTENSION; + } + if (isInterfaceType(type)) { + return Kind.INTERFACE_TYPE_EXTENSION; + } + if (isUnionType(type)) { + return Kind.UNION_TYPE_EXTENSION; + } + if (isEnumType(type)) { + return Kind.ENUM_TYPE_EXTENSION; + } + // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + if (isInputObjectType(type)) { + return Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + + // istanbul ignore next (Not reachable. All possible types have been considered) + invariant(false, 'Unexpected type: ' + inspect((type: empty))); +} + +function extensionKindToTypeName(kind: KindEnum): string { + switch (kind) { + case Kind.SCALAR_TYPE_EXTENSION: + return 'scalar'; + case Kind.OBJECT_TYPE_EXTENSION: + return 'object'; + case Kind.INTERFACE_TYPE_EXTENSION: + return 'interface'; + case Kind.UNION_TYPE_EXTENSION: + return 'union'; + case Kind.ENUM_TYPE_EXTENSION: + return 'enum'; + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + return 'input object'; + } + + // istanbul ignore next (Not reachable. All possible types have been considered) + invariant(false, 'Unexpected kind: ' + inspect(kind)); +} diff --git a/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs b/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs new file mode 100644 index 0000000..b1066b5 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs @@ -0,0 +1,124 @@ +var _defKindToExtKind; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +import inspect from "../../jsutils/inspect.mjs"; +import invariant from "../../jsutils/invariant.mjs"; +import didYouMean from "../../jsutils/didYouMean.mjs"; +import suggestionList from "../../jsutils/suggestionList.mjs"; +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { Kind } from "../../language/kinds.mjs"; +import { isTypeDefinitionNode } from "../../language/predicates.mjs"; +import { isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType } from "../../type/definition.mjs"; + +/** + * Possible type extension + * + * A type extension is only valid if the type is defined and has the same kind. + */ +export function PossibleTypeExtensionsRule(context) { + var schema = context.getSchema(); + var definedTypes = Object.create(null); + + for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) { + var def = _context$getDocument$2[_i2]; + + if (isTypeDefinitionNode(def)) { + definedTypes[def.name.value] = def; + } + } + + return { + ScalarTypeExtension: checkExtension, + ObjectTypeExtension: checkExtension, + InterfaceTypeExtension: checkExtension, + UnionTypeExtension: checkExtension, + EnumTypeExtension: checkExtension, + InputObjectTypeExtension: checkExtension + }; + + function checkExtension(node) { + var typeName = node.name.value; + var defNode = definedTypes[typeName]; + var existingType = schema === null || schema === void 0 ? void 0 : schema.getType(typeName); + var expectedKind; + + if (defNode) { + expectedKind = defKindToExtKind[defNode.kind]; + } else if (existingType) { + expectedKind = typeToExtKind(existingType); + } + + if (expectedKind) { + if (expectedKind !== node.kind) { + var kindStr = extensionKindToTypeName(node.kind); + context.reportError(new GraphQLError("Cannot extend non-".concat(kindStr, " type \"").concat(typeName, "\"."), defNode ? [defNode, node] : node)); + } + } else { + var allTypeNames = Object.keys(definedTypes); + + if (schema) { + allTypeNames = allTypeNames.concat(Object.keys(schema.getTypeMap())); + } + + var suggestedTypes = suggestionList(typeName, allTypeNames); + context.reportError(new GraphQLError("Cannot extend type \"".concat(typeName, "\" because it is not defined.") + didYouMean(suggestedTypes), node.name)); + } + } +} +var defKindToExtKind = (_defKindToExtKind = {}, _defineProperty(_defKindToExtKind, Kind.SCALAR_TYPE_DEFINITION, Kind.SCALAR_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, Kind.OBJECT_TYPE_DEFINITION, Kind.OBJECT_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, Kind.INTERFACE_TYPE_DEFINITION, Kind.INTERFACE_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, Kind.UNION_TYPE_DEFINITION, Kind.UNION_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, Kind.ENUM_TYPE_DEFINITION, Kind.ENUM_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, Kind.INPUT_OBJECT_TYPE_DEFINITION, Kind.INPUT_OBJECT_TYPE_EXTENSION), _defKindToExtKind); + +function typeToExtKind(type) { + if (isScalarType(type)) { + return Kind.SCALAR_TYPE_EXTENSION; + } + + if (isObjectType(type)) { + return Kind.OBJECT_TYPE_EXTENSION; + } + + if (isInterfaceType(type)) { + return Kind.INTERFACE_TYPE_EXTENSION; + } + + if (isUnionType(type)) { + return Kind.UNION_TYPE_EXTENSION; + } + + if (isEnumType(type)) { + return Kind.ENUM_TYPE_EXTENSION; + } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618') + + + if (isInputObjectType(type)) { + return Kind.INPUT_OBJECT_TYPE_EXTENSION; + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || invariant(0, 'Unexpected type: ' + inspect(type)); +} + +function extensionKindToTypeName(kind) { + switch (kind) { + case Kind.SCALAR_TYPE_EXTENSION: + return 'scalar'; + + case Kind.OBJECT_TYPE_EXTENSION: + return 'object'; + + case Kind.INTERFACE_TYPE_EXTENSION: + return 'interface'; + + case Kind.UNION_TYPE_EXTENSION: + return 'union'; + + case Kind.ENUM_TYPE_EXTENSION: + return 'enum'; + + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + return 'input object'; + } // istanbul ignore next (Not reachable. All possible types have been considered) + + + false || invariant(0, 'Unexpected kind: ' + inspect(kind)); +} diff --git a/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.d.ts b/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.d.ts new file mode 100644 index 0000000..116069c --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.d.ts @@ -0,0 +1,19 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext, SDLValidationContext } from '../ValidationContext'; + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ +export function ProvidedRequiredArgumentsRule( + context: ValidationContext, +): ASTVisitor; + +/** + * @internal + */ +export function ProvidedRequiredArgumentsOnDirectivesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.js b/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.js new file mode 100644 index 0000000..b4735cf --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.js @@ -0,0 +1,136 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ProvidedRequiredArgumentsRule = ProvidedRequiredArgumentsRule; +exports.ProvidedRequiredArgumentsOnDirectivesRule = ProvidedRequiredArgumentsOnDirectivesRule; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect.js")); + +var _keyMap = _interopRequireDefault(require("../../jsutils/keyMap.js")); + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _kinds = require("../../language/kinds.js"); + +var _printer = require("../../language/printer.js"); + +var _directives = require("../../type/directives.js"); + +var _definition = require("../../type/definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ +function ProvidedRequiredArgumentsRule(context) { + return _objectSpread(_objectSpread({}, ProvidedRequiredArgumentsOnDirectivesRule(context)), {}, { + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(fieldNode) { + var _fieldNode$arguments; + + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + return false; + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + + var argNodes = (_fieldNode$arguments = fieldNode.arguments) !== null && _fieldNode$arguments !== void 0 ? _fieldNode$arguments : []; + var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) { + return arg.name.value; + }); + + for (var _i2 = 0, _fieldDef$args2 = fieldDef.args; _i2 < _fieldDef$args2.length; _i2++) { + var argDef = _fieldDef$args2[_i2]; + var argNode = argNodeMap[argDef.name]; + + if (!argNode && (0, _definition.isRequiredArgument)(argDef)) { + var argTypeStr = (0, _inspect.default)(argDef.type); + context.reportError(new _GraphQLError.GraphQLError("Field \"".concat(fieldDef.name, "\" argument \"").concat(argDef.name, "\" of type \"").concat(argTypeStr, "\" is required, but it was not provided."), fieldNode)); + } + } + } + } + }); +} +/** + * @internal + */ + + +function ProvidedRequiredArgumentsOnDirectivesRule(context) { + var requiredArgsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + + for (var _i4 = 0; _i4 < definedDirectives.length; _i4++) { + var directive = definedDirectives[_i4]; + requiredArgsMap[directive.name] = (0, _keyMap.default)(directive.args.filter(_definition.isRequiredArgument), function (arg) { + return arg.name; + }); + } + + var astDefinitions = context.getDocument().definitions; + + for (var _i6 = 0; _i6 < astDefinitions.length; _i6++) { + var def = astDefinitions[_i6]; + + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var argNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; + requiredArgsMap[def.name.value] = (0, _keyMap.default)(argNodes.filter(isRequiredArgumentNode), function (arg) { + return arg.name.value; + }); + } + } + + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(directiveNode) { + var directiveName = directiveNode.name.value; + var requiredArgs = requiredArgsMap[directiveName]; + + if (requiredArgs) { + var _directiveNode$argume; + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var _argNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : []; + + var argNodeMap = (0, _keyMap.default)(_argNodes, function (arg) { + return arg.name.value; + }); + + for (var _i8 = 0, _Object$keys2 = Object.keys(requiredArgs); _i8 < _Object$keys2.length; _i8++) { + var argName = _Object$keys2[_i8]; + + if (!argNodeMap[argName]) { + var argType = requiredArgs[argName].type; + var argTypeStr = (0, _definition.isType)(argType) ? (0, _inspect.default)(argType) : (0, _printer.print)(argType); + context.reportError(new _GraphQLError.GraphQLError("Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type \"").concat(argTypeStr, "\" is required, but it was not provided."), directiveNode)); + } + } + } + } + } + }; +} + +function isRequiredArgumentNode(arg) { + return arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null; +} diff --git a/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.js.flow b/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.js.flow new file mode 100644 index 0000000..11b9b3e --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.js.flow @@ -0,0 +1,125 @@ +// @flow strict +import inspect from '../../jsutils/inspect'; +import keyMap from '../../jsutils/keyMap'; + +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import type { InputValueDefinitionNode } from '../../language/ast'; +import { Kind } from '../../language/kinds'; +import { print } from '../../language/printer'; + +import { specifiedDirectives } from '../../type/directives'; +import { isType, isRequiredArgument } from '../../type/definition'; + +import type { + ValidationContext, + SDLValidationContext, +} from '../ValidationContext'; + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ +export function ProvidedRequiredArgumentsRule( + context: ValidationContext, +): ASTVisitor { + return { + // eslint-disable-next-line new-cap + ...ProvidedRequiredArgumentsOnDirectivesRule(context), + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave(fieldNode) { + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + return false; + } + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const argNodes = fieldNode.arguments ?? []; + const argNodeMap = keyMap(argNodes, (arg) => arg.name.value); + for (const argDef of fieldDef.args) { + const argNode = argNodeMap[argDef.name]; + if (!argNode && isRequiredArgument(argDef)) { + const argTypeStr = inspect(argDef.type); + context.reportError( + new GraphQLError( + `Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`, + fieldNode, + ), + ); + } + } + }, + }, + }; +} + +/** + * @internal + */ +export function ProvidedRequiredArgumentsOnDirectivesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor { + const requiredArgsMap = Object.create(null); + + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + for (const directive of definedDirectives) { + requiredArgsMap[directive.name] = keyMap( + directive.args.filter(isRequiredArgument), + (arg) => arg.name, + ); + } + + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const argNodes = def.arguments ?? []; + + requiredArgsMap[def.name.value] = keyMap( + argNodes.filter(isRequiredArgumentNode), + (arg) => arg.name.value, + ); + } + } + + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave(directiveNode) { + const directiveName = directiveNode.name.value; + const requiredArgs = requiredArgsMap[directiveName]; + if (requiredArgs) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const argNodes = directiveNode.arguments ?? []; + const argNodeMap = keyMap(argNodes, (arg) => arg.name.value); + for (const argName of Object.keys(requiredArgs)) { + if (!argNodeMap[argName]) { + const argType = requiredArgs[argName].type; + const argTypeStr = isType(argType) + ? inspect(argType) + : print(argType); + + context.reportError( + new GraphQLError( + `Directive "@${directiveName}" argument "${argName}" of type "${argTypeStr}" is required, but it was not provided.`, + directiveNode, + ), + ); + } + } + } + }, + }, + }; +} + +function isRequiredArgumentNode(arg: InputValueDefinitionNode): boolean { + return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null; +} diff --git a/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs b/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs new file mode 100644 index 0000000..dc476b4 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs @@ -0,0 +1,119 @@ +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +import inspect from "../../jsutils/inspect.mjs"; +import keyMap from "../../jsutils/keyMap.mjs"; +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { Kind } from "../../language/kinds.mjs"; +import { print } from "../../language/printer.mjs"; +import { specifiedDirectives } from "../../type/directives.mjs"; +import { isType, isRequiredArgument } from "../../type/definition.mjs"; + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ +export function ProvidedRequiredArgumentsRule(context) { + return _objectSpread(_objectSpread({}, ProvidedRequiredArgumentsOnDirectivesRule(context)), {}, { + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(fieldNode) { + var _fieldNode$arguments; + + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + return false; + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + + var argNodes = (_fieldNode$arguments = fieldNode.arguments) !== null && _fieldNode$arguments !== void 0 ? _fieldNode$arguments : []; + var argNodeMap = keyMap(argNodes, function (arg) { + return arg.name.value; + }); + + for (var _i2 = 0, _fieldDef$args2 = fieldDef.args; _i2 < _fieldDef$args2.length; _i2++) { + var argDef = _fieldDef$args2[_i2]; + var argNode = argNodeMap[argDef.name]; + + if (!argNode && isRequiredArgument(argDef)) { + var argTypeStr = inspect(argDef.type); + context.reportError(new GraphQLError("Field \"".concat(fieldDef.name, "\" argument \"").concat(argDef.name, "\" of type \"").concat(argTypeStr, "\" is required, but it was not provided."), fieldNode)); + } + } + } + } + }); +} +/** + * @internal + */ + +export function ProvidedRequiredArgumentsOnDirectivesRule(context) { + var requiredArgsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives; + + for (var _i4 = 0; _i4 < definedDirectives.length; _i4++) { + var directive = definedDirectives[_i4]; + requiredArgsMap[directive.name] = keyMap(directive.args.filter(isRequiredArgument), function (arg) { + return arg.name; + }); + } + + var astDefinitions = context.getDocument().definitions; + + for (var _i6 = 0; _i6 < astDefinitions.length; _i6++) { + var def = astDefinitions[_i6]; + + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var argNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; + requiredArgsMap[def.name.value] = keyMap(argNodes.filter(isRequiredArgumentNode), function (arg) { + return arg.name.value; + }); + } + } + + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(directiveNode) { + var directiveName = directiveNode.name.value; + var requiredArgs = requiredArgsMap[directiveName]; + + if (requiredArgs) { + var _directiveNode$argume; + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var _argNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : []; + + var argNodeMap = keyMap(_argNodes, function (arg) { + return arg.name.value; + }); + + for (var _i8 = 0, _Object$keys2 = Object.keys(requiredArgs); _i8 < _Object$keys2.length; _i8++) { + var argName = _Object$keys2[_i8]; + + if (!argNodeMap[argName]) { + var argType = requiredArgs[argName].type; + var argTypeStr = isType(argType) ? inspect(argType) : print(argType); + context.reportError(new GraphQLError("Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type \"").concat(argTypeStr, "\" is required, but it was not provided."), directiveNode)); + } + } + } + } + } + }; +} + +function isRequiredArgumentNode(arg) { + return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null; +} diff --git a/school/node_modules/graphql/validation/rules/ScalarLeafsRule.d.ts b/school/node_modules/graphql/validation/rules/ScalarLeafsRule.d.ts new file mode 100644 index 0000000..ae956ef --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ScalarLeafsRule.d.ts @@ -0,0 +1,10 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ +export function ScalarLeafsRule(context: ValidationContext): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/ScalarLeafsRule.js b/school/node_modules/graphql/validation/rules/ScalarLeafsRule.js new file mode 100644 index 0000000..fc1d5de --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ScalarLeafsRule.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ScalarLeafsRule = ScalarLeafsRule; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect.js")); + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _definition = require("../../type/definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ +function ScalarLeafsRule(context) { + return { + Field: function Field(node) { + var type = context.getType(); + var selectionSet = node.selectionSet; + + if (type) { + if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) { + if (selectionSet) { + var fieldName = node.name.value; + var typeStr = (0, _inspect.default)(type); + context.reportError(new _GraphQLError.GraphQLError("Field \"".concat(fieldName, "\" must not have a selection since type \"").concat(typeStr, "\" has no subfields."), selectionSet)); + } + } else if (!selectionSet) { + var _fieldName = node.name.value; + + var _typeStr = (0, _inspect.default)(type); + + context.reportError(new _GraphQLError.GraphQLError("Field \"".concat(_fieldName, "\" of type \"").concat(_typeStr, "\" must have a selection of subfields. Did you mean \"").concat(_fieldName, " { ... }\"?"), node)); + } + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/ScalarLeafsRule.js.flow b/school/node_modules/graphql/validation/rules/ScalarLeafsRule.js.flow new file mode 100644 index 0000000..cac22c5 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ScalarLeafsRule.js.flow @@ -0,0 +1,49 @@ +// @flow strict +import inspect from '../../jsutils/inspect'; + +import { GraphQLError } from '../../error/GraphQLError'; + +import type { FieldNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; + +import { getNamedType, isLeafType } from '../../type/definition'; + +import type { ValidationContext } from '../ValidationContext'; + +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ +export function ScalarLeafsRule(context: ValidationContext): ASTVisitor { + return { + Field(node: FieldNode) { + const type = context.getType(); + const selectionSet = node.selectionSet; + if (type) { + if (isLeafType(getNamedType(type))) { + if (selectionSet) { + const fieldName = node.name.value; + const typeStr = inspect(type); + context.reportError( + new GraphQLError( + `Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`, + selectionSet, + ), + ); + } + } else if (!selectionSet) { + const fieldName = node.name.value; + const typeStr = inspect(type); + context.reportError( + new GraphQLError( + `Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`, + node, + ), + ); + } + } + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/ScalarLeafsRule.mjs b/school/node_modules/graphql/validation/rules/ScalarLeafsRule.mjs new file mode 100644 index 0000000..8a5111d --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ScalarLeafsRule.mjs @@ -0,0 +1,34 @@ +import inspect from "../../jsutils/inspect.mjs"; +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { getNamedType, isLeafType } from "../../type/definition.mjs"; + +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ +export function ScalarLeafsRule(context) { + return { + Field: function Field(node) { + var type = context.getType(); + var selectionSet = node.selectionSet; + + if (type) { + if (isLeafType(getNamedType(type))) { + if (selectionSet) { + var fieldName = node.name.value; + var typeStr = inspect(type); + context.reportError(new GraphQLError("Field \"".concat(fieldName, "\" must not have a selection since type \"").concat(typeStr, "\" has no subfields."), selectionSet)); + } + } else if (!selectionSet) { + var _fieldName = node.name.value; + + var _typeStr = inspect(type); + + context.reportError(new GraphQLError("Field \"".concat(_fieldName, "\" of type \"").concat(_typeStr, "\" must have a selection of subfields. Did you mean \"").concat(_fieldName, " { ... }\"?"), node)); + } + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.d.ts b/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.d.ts new file mode 100644 index 0000000..d56c4fd --- /dev/null +++ b/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.d.ts @@ -0,0 +1,11 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ASTValidationContext } from '../ValidationContext'; + +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ +export function SingleFieldSubscriptionsRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.js b/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.js new file mode 100644 index 0000000..80d199f --- /dev/null +++ b/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SingleFieldSubscriptionsRule = SingleFieldSubscriptionsRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ +function SingleFieldSubscriptionsRule(context) { + return { + OperationDefinition: function OperationDefinition(node) { + if (node.operation === 'subscription') { + if (node.selectionSet.selections.length !== 1) { + context.reportError(new _GraphQLError.GraphQLError(node.name ? "Subscription \"".concat(node.name.value, "\" must select only one top level field.") : 'Anonymous Subscription must select only one top level field.', node.selectionSet.selections.slice(1))); + } + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.js.flow b/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.js.flow new file mode 100644 index 0000000..290432f --- /dev/null +++ b/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.js.flow @@ -0,0 +1,33 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import type { OperationDefinitionNode } from '../../language/ast'; + +import type { ASTValidationContext } from '../ValidationContext'; + +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ +export function SingleFieldSubscriptionsRule( + context: ASTValidationContext, +): ASTVisitor { + return { + OperationDefinition(node: OperationDefinitionNode) { + if (node.operation === 'subscription') { + if (node.selectionSet.selections.length !== 1) { + context.reportError( + new GraphQLError( + node.name + ? `Subscription "${node.name.value}" must select only one top level field.` + : 'Anonymous Subscription must select only one top level field.', + node.selectionSet.selections.slice(1), + ), + ); + } + } + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs b/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs new file mode 100644 index 0000000..0dd5351 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs @@ -0,0 +1,18 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ +export function SingleFieldSubscriptionsRule(context) { + return { + OperationDefinition: function OperationDefinition(node) { + if (node.operation === 'subscription') { + if (node.selectionSet.selections.length !== 1) { + context.reportError(new GraphQLError(node.name ? "Subscription \"".concat(node.name.value, "\" must select only one top level field.") : 'Anonymous Subscription must select only one top level field.', node.selectionSet.selections.slice(1))); + } + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.d.ts b/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.d.ts new file mode 100644 index 0000000..1d0d4f4 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.d.ts @@ -0,0 +1,12 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ASTValidationContext } from '../ValidationContext'; + +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ +export function UniqueArgumentNamesRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.js b/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.js new file mode 100644 index 0000000..f3fe599 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UniqueArgumentNamesRule = UniqueArgumentNamesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ +function UniqueArgumentNamesRule(context) { + var knownArgNames = Object.create(null); + return { + Field: function Field() { + knownArgNames = Object.create(null); + }, + Directive: function Directive() { + knownArgNames = Object.create(null); + }, + Argument: function Argument(node) { + var argName = node.name.value; + + if (knownArgNames[argName]) { + context.reportError(new _GraphQLError.GraphQLError("There can be only one argument named \"".concat(argName, "\"."), [knownArgNames[argName], node.name])); + } else { + knownArgNames[argName] = node.name; + } + + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.js.flow b/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.js.flow new file mode 100644 index 0000000..499e6ed --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.js.flow @@ -0,0 +1,39 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +import type { ASTValidationContext } from '../ValidationContext'; + +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ +export function UniqueArgumentNamesRule( + context: ASTValidationContext, +): ASTVisitor { + let knownArgNames = Object.create(null); + return { + Field() { + knownArgNames = Object.create(null); + }, + Directive() { + knownArgNames = Object.create(null); + }, + Argument(node) { + const argName = node.name.value; + if (knownArgNames[argName]) { + context.reportError( + new GraphQLError( + `There can be only one argument named "${argName}".`, + [knownArgNames[argName], node.name], + ), + ); + } else { + knownArgNames[argName] = node.name; + } + return false; + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs b/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs new file mode 100644 index 0000000..5359d08 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs @@ -0,0 +1,30 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ +export function UniqueArgumentNamesRule(context) { + var knownArgNames = Object.create(null); + return { + Field: function Field() { + knownArgNames = Object.create(null); + }, + Directive: function Directive() { + knownArgNames = Object.create(null); + }, + Argument: function Argument(node) { + var argName = node.name.value; + + if (knownArgNames[argName]) { + context.reportError(new GraphQLError("There can be only one argument named \"".concat(argName, "\"."), [knownArgNames[argName], node.name])); + } else { + knownArgNames[argName] = node.name; + } + + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.d.ts b/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.d.ts new file mode 100644 index 0000000..c197e87 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.d.ts @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueDirectiveNamesRule } from 'graphql' + * or + * import { UniqueDirectiveNamesRule } from 'graphql/validation' + */ +export { UniqueDirectiveNamesRule as UniqueDirectiveNames } from './UniqueDirectiveNamesRule'; diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.js b/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.js new file mode 100644 index 0000000..0e94e14 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "UniqueDirectiveNames", { + enumerable: true, + get: function get() { + return _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule; + } +}); + +var _UniqueDirectiveNamesRule = require("./UniqueDirectiveNamesRule.js"); diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.js.flow b/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.js.flow new file mode 100644 index 0000000..0dc4598 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.js.flow @@ -0,0 +1,9 @@ +// @flow strict +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueDirectiveNamesRule } from 'graphql' + * or + * import { UniqueDirectiveNamesRule } from 'graphql/validation' + */ +export { UniqueDirectiveNamesRule as UniqueDirectiveNames } from './UniqueDirectiveNamesRule'; diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.mjs b/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.mjs new file mode 100644 index 0000000..24f4e39 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectiveNames.mjs @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueDirectiveNamesRule } from 'graphql' + * or + * import { UniqueDirectiveNamesRule } from 'graphql/validation' + */ +export { UniqueDirectiveNamesRule as UniqueDirectiveNames } from "./UniqueDirectiveNamesRule.mjs"; diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.d.ts b/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.d.ts new file mode 100644 index 0000000..a4dd841 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.d.ts @@ -0,0 +1,11 @@ +import { ASTVisitor } from '../../language/visitor'; +import { SDLValidationContext } from '../ValidationContext'; + +/** + * Unique directive names + * + * A GraphQL document is only valid if all defined directives have unique names. + */ +export function UniqueDirectiveNamesRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.js b/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.js new file mode 100644 index 0000000..15731e5 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.js @@ -0,0 +1,36 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UniqueDirectiveNamesRule = UniqueDirectiveNamesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * Unique directive names + * + * A GraphQL document is only valid if all defined directives have unique names. + */ +function UniqueDirectiveNamesRule(context) { + var knownDirectiveNames = Object.create(null); + var schema = context.getSchema(); + return { + DirectiveDefinition: function DirectiveDefinition(node) { + var directiveName = node.name.value; + + if (schema !== null && schema !== void 0 && schema.getDirective(directiveName)) { + context.reportError(new _GraphQLError.GraphQLError("Directive \"@".concat(directiveName, "\" already exists in the schema. It cannot be redefined."), node.name)); + return; + } + + if (knownDirectiveNames[directiveName]) { + context.reportError(new _GraphQLError.GraphQLError("There can be only one directive named \"@".concat(directiveName, "\"."), [knownDirectiveNames[directiveName], node.name])); + } else { + knownDirectiveNames[directiveName] = node.name; + } + + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.js.flow b/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.js.flow new file mode 100644 index 0000000..688a2bb --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.js.flow @@ -0,0 +1,46 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +import type { SDLValidationContext } from '../ValidationContext'; + +/** + * Unique directive names + * + * A GraphQL document is only valid if all defined directives have unique names. + */ +export function UniqueDirectiveNamesRule( + context: SDLValidationContext, +): ASTVisitor { + const knownDirectiveNames = Object.create(null); + const schema = context.getSchema(); + + return { + DirectiveDefinition(node) { + const directiveName = node.name.value; + + if (schema?.getDirective(directiveName)) { + context.reportError( + new GraphQLError( + `Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`, + node.name, + ), + ); + return; + } + + if (knownDirectiveNames[directiveName]) { + context.reportError( + new GraphQLError( + `There can be only one directive named "@${directiveName}".`, + [knownDirectiveNames[directiveName], node.name], + ), + ); + } else { + knownDirectiveNames[directiveName] = node.name; + } + + return false; + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs b/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs new file mode 100644 index 0000000..8d0f843 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs @@ -0,0 +1,29 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * Unique directive names + * + * A GraphQL document is only valid if all defined directives have unique names. + */ +export function UniqueDirectiveNamesRule(context) { + var knownDirectiveNames = Object.create(null); + var schema = context.getSchema(); + return { + DirectiveDefinition: function DirectiveDefinition(node) { + var directiveName = node.name.value; + + if (schema !== null && schema !== void 0 && schema.getDirective(directiveName)) { + context.reportError(new GraphQLError("Directive \"@".concat(directiveName, "\" already exists in the schema. It cannot be redefined."), node.name)); + return; + } + + if (knownDirectiveNames[directiveName]) { + context.reportError(new GraphQLError("There can be only one directive named \"@".concat(directiveName, "\"."), [knownDirectiveNames[directiveName], node.name])); + } else { + knownDirectiveNames[directiveName] = node.name; + } + + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.d.ts b/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.d.ts new file mode 100644 index 0000000..d059446 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.d.ts @@ -0,0 +1,12 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ASTValidationContext } from '../ValidationContext'; + +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all directives at a given location + * are uniquely named. + */ +export function UniqueDirectivesPerLocationRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.js b/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.js new file mode 100644 index 0000000..9505a37 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.js @@ -0,0 +1,82 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UniqueDirectivesPerLocationRule = UniqueDirectivesPerLocationRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _kinds = require("../../language/kinds.js"); + +var _predicates = require("../../language/predicates.js"); + +var _directives = require("../../type/directives.js"); + +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all non-repeatable directives at + * a given location are uniquely named. + */ +function UniqueDirectivesPerLocationRule(context) { + var uniqueDirectiveMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + + for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) { + var directive = definedDirectives[_i2]; + uniqueDirectiveMap[directive.name] = !directive.isRepeatable; + } + + var astDefinitions = context.getDocument().definitions; + + for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) { + var def = astDefinitions[_i4]; + + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + uniqueDirectiveMap[def.name.value] = !def.repeatable; + } + } + + var schemaDirectives = Object.create(null); + var typeDirectivesMap = Object.create(null); + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter: function enter(node) { + if (node.directives == null) { + return; + } + + var seenDirectives; + + if (node.kind === _kinds.Kind.SCHEMA_DEFINITION || node.kind === _kinds.Kind.SCHEMA_EXTENSION) { + seenDirectives = schemaDirectives; + } else if ((0, _predicates.isTypeDefinitionNode)(node) || (0, _predicates.isTypeExtensionNode)(node)) { + var typeName = node.name.value; + seenDirectives = typeDirectivesMap[typeName]; + + if (seenDirectives === undefined) { + typeDirectivesMap[typeName] = seenDirectives = Object.create(null); + } + } else { + seenDirectives = Object.create(null); + } + + for (var _i6 = 0, _node$directives2 = node.directives; _i6 < _node$directives2.length; _i6++) { + var _directive = _node$directives2[_i6]; + var directiveName = _directive.name.value; + + if (uniqueDirectiveMap[directiveName]) { + if (seenDirectives[directiveName]) { + context.reportError(new _GraphQLError.GraphQLError("The directive \"@".concat(directiveName, "\" can only be used once at this location."), [seenDirectives[directiveName], _directive])); + } else { + seenDirectives[directiveName] = _directive; + } + } + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.js.flow b/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.js.flow new file mode 100644 index 0000000..a753a84 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.js.flow @@ -0,0 +1,90 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import { Kind } from '../../language/kinds'; +import type { ASTVisitor } from '../../language/visitor'; +import { + isTypeDefinitionNode, + isTypeExtensionNode, +} from '../../language/predicates'; + +import { specifiedDirectives } from '../../type/directives'; + +import type { + SDLValidationContext, + ValidationContext, +} from '../ValidationContext'; + +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all non-repeatable directives at + * a given location are uniquely named. + */ +export function UniqueDirectivesPerLocationRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor { + const uniqueDirectiveMap = Object.create(null); + + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + for (const directive of definedDirectives) { + uniqueDirectiveMap[directive.name] = !directive.isRepeatable; + } + + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + uniqueDirectiveMap[def.name.value] = !def.repeatable; + } + } + + const schemaDirectives = Object.create(null); + const typeDirectivesMap = Object.create(null); + + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter(node) { + if (node.directives == null) { + return; + } + + let seenDirectives; + if ( + node.kind === Kind.SCHEMA_DEFINITION || + node.kind === Kind.SCHEMA_EXTENSION + ) { + seenDirectives = schemaDirectives; + } else if (isTypeDefinitionNode(node) || isTypeExtensionNode(node)) { + const typeName = node.name.value; + seenDirectives = typeDirectivesMap[typeName]; + if (seenDirectives === undefined) { + typeDirectivesMap[typeName] = seenDirectives = Object.create(null); + } + } else { + seenDirectives = Object.create(null); + } + + for (const directive of node.directives) { + const directiveName = directive.name.value; + + if (uniqueDirectiveMap[directiveName]) { + if (seenDirectives[directiveName]) { + context.reportError( + new GraphQLError( + `The directive "@${directiveName}" can only be used once at this location.`, + [seenDirectives[directiveName], directive], + ), + ); + } else { + seenDirectives[directiveName] = directive; + } + } + } + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs b/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs new file mode 100644 index 0000000..9a3951a --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs @@ -0,0 +1,72 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { Kind } from "../../language/kinds.mjs"; +import { isTypeDefinitionNode, isTypeExtensionNode } from "../../language/predicates.mjs"; +import { specifiedDirectives } from "../../type/directives.mjs"; + +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all non-repeatable directives at + * a given location are uniquely named. + */ +export function UniqueDirectivesPerLocationRule(context) { + var uniqueDirectiveMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives; + + for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) { + var directive = definedDirectives[_i2]; + uniqueDirectiveMap[directive.name] = !directive.isRepeatable; + } + + var astDefinitions = context.getDocument().definitions; + + for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) { + var def = astDefinitions[_i4]; + + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + uniqueDirectiveMap[def.name.value] = !def.repeatable; + } + } + + var schemaDirectives = Object.create(null); + var typeDirectivesMap = Object.create(null); + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter: function enter(node) { + if (node.directives == null) { + return; + } + + var seenDirectives; + + if (node.kind === Kind.SCHEMA_DEFINITION || node.kind === Kind.SCHEMA_EXTENSION) { + seenDirectives = schemaDirectives; + } else if (isTypeDefinitionNode(node) || isTypeExtensionNode(node)) { + var typeName = node.name.value; + seenDirectives = typeDirectivesMap[typeName]; + + if (seenDirectives === undefined) { + typeDirectivesMap[typeName] = seenDirectives = Object.create(null); + } + } else { + seenDirectives = Object.create(null); + } + + for (var _i6 = 0, _node$directives2 = node.directives; _i6 < _node$directives2.length; _i6++) { + var _directive = _node$directives2[_i6]; + var directiveName = _directive.name.value; + + if (uniqueDirectiveMap[directiveName]) { + if (seenDirectives[directiveName]) { + context.reportError(new GraphQLError("The directive \"@".concat(directiveName, "\" can only be used once at this location."), [seenDirectives[directiveName], _directive])); + } else { + seenDirectives[directiveName] = _directive; + } + } + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.d.ts b/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.d.ts new file mode 100644 index 0000000..96d9b78 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.d.ts @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueEnumValueNamesRule } from 'graphql' + * or + * import { UniqueEnumValueNamesRule } from 'graphql/validation' + */ +export { UniqueEnumValueNamesRule as UniqueEnumValueNames } from './UniqueEnumValueNamesRule'; diff --git a/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.js b/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.js new file mode 100644 index 0000000..4a9b5e5 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "UniqueEnumValueNames", { + enumerable: true, + get: function get() { + return _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule; + } +}); + +var _UniqueEnumValueNamesRule = require("./UniqueEnumValueNamesRule.js"); diff --git a/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.js.flow b/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.js.flow new file mode 100644 index 0000000..4c67b17 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.js.flow @@ -0,0 +1,9 @@ +// @flow strict +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueEnumValueNamesRule } from 'graphql' + * or + * import { UniqueEnumValueNamesRule } from 'graphql/validation' + */ +export { UniqueEnumValueNamesRule as UniqueEnumValueNames } from './UniqueEnumValueNamesRule'; diff --git a/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.mjs b/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.mjs new file mode 100644 index 0000000..05f361a --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueEnumValueNames.mjs @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueEnumValueNamesRule } from 'graphql' + * or + * import { UniqueEnumValueNamesRule } from 'graphql/validation' + */ +export { UniqueEnumValueNamesRule as UniqueEnumValueNames } from "./UniqueEnumValueNamesRule.mjs"; diff --git a/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.d.ts b/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.d.ts new file mode 100644 index 0000000..9c5ff50 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.d.ts @@ -0,0 +1,11 @@ +import { ASTVisitor } from '../../language/visitor'; +import { SDLValidationContext } from '../ValidationContext'; + +/** + * Unique enum value names + * + * A GraphQL enum type is only valid if all its values are uniquely named. + */ +export function UniqueEnumValueNamesRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.js b/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.js new file mode 100644 index 0000000..1fed87a --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UniqueEnumValueNamesRule = UniqueEnumValueNamesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _definition = require("../../type/definition.js"); + +/** + * Unique enum value names + * + * A GraphQL enum type is only valid if all its values are uniquely named. + */ +function UniqueEnumValueNamesRule(context) { + var schema = context.getSchema(); + var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + var knownValueNames = Object.create(null); + return { + EnumTypeDefinition: checkValueUniqueness, + EnumTypeExtension: checkValueUniqueness + }; + + function checkValueUniqueness(node) { + var _node$values; + + var typeName = node.name.value; + + if (!knownValueNames[typeName]) { + knownValueNames[typeName] = Object.create(null); + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + + var valueNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; + var valueNames = knownValueNames[typeName]; + + for (var _i2 = 0; _i2 < valueNodes.length; _i2++) { + var valueDef = valueNodes[_i2]; + var valueName = valueDef.name.value; + var existingType = existingTypeMap[typeName]; + + if ((0, _definition.isEnumType)(existingType) && existingType.getValue(valueName)) { + context.reportError(new _GraphQLError.GraphQLError("Enum value \"".concat(typeName, ".").concat(valueName, "\" already exists in the schema. It cannot also be defined in this type extension."), valueDef.name)); + } else if (valueNames[valueName]) { + context.reportError(new _GraphQLError.GraphQLError("Enum value \"".concat(typeName, ".").concat(valueName, "\" can only be defined once."), [valueNames[valueName], valueDef.name])); + } else { + valueNames[valueName] = valueDef.name; + } + } + + return false; + } +} diff --git a/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.js.flow b/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.js.flow new file mode 100644 index 0000000..09515e8 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.js.flow @@ -0,0 +1,69 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import type { + EnumTypeDefinitionNode, + EnumTypeExtensionNode, +} from '../../language/ast'; + +import { isEnumType } from '../../type/definition'; + +import type { SDLValidationContext } from '../ValidationContext'; + +/** + * Unique enum value names + * + * A GraphQL enum type is only valid if all its values are uniquely named. + */ +export function UniqueEnumValueNamesRule( + context: SDLValidationContext, +): ASTVisitor { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownValueNames = Object.create(null); + + return { + EnumTypeDefinition: checkValueUniqueness, + EnumTypeExtension: checkValueUniqueness, + }; + + function checkValueUniqueness( + node: EnumTypeDefinitionNode | EnumTypeExtensionNode, + ) { + const typeName = node.name.value; + + if (!knownValueNames[typeName]) { + knownValueNames[typeName] = Object.create(null); + } + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const valueNodes = node.values ?? []; + const valueNames = knownValueNames[typeName]; + + for (const valueDef of valueNodes) { + const valueName = valueDef.name.value; + + const existingType = existingTypeMap[typeName]; + if (isEnumType(existingType) && existingType.getValue(valueName)) { + context.reportError( + new GraphQLError( + `Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`, + valueDef.name, + ), + ); + } else if (valueNames[valueName]) { + context.reportError( + new GraphQLError( + `Enum value "${typeName}.${valueName}" can only be defined once.`, + [valueNames[valueName], valueDef.name], + ), + ); + } else { + valueNames[valueName] = valueDef.name; + } + } + + return false; + } +} diff --git a/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs b/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs new file mode 100644 index 0000000..4e821b8 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs @@ -0,0 +1,47 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { isEnumType } from "../../type/definition.mjs"; + +/** + * Unique enum value names + * + * A GraphQL enum type is only valid if all its values are uniquely named. + */ +export function UniqueEnumValueNamesRule(context) { + var schema = context.getSchema(); + var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + var knownValueNames = Object.create(null); + return { + EnumTypeDefinition: checkValueUniqueness, + EnumTypeExtension: checkValueUniqueness + }; + + function checkValueUniqueness(node) { + var _node$values; + + var typeName = node.name.value; + + if (!knownValueNames[typeName]) { + knownValueNames[typeName] = Object.create(null); + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + + var valueNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; + var valueNames = knownValueNames[typeName]; + + for (var _i2 = 0; _i2 < valueNodes.length; _i2++) { + var valueDef = valueNodes[_i2]; + var valueName = valueDef.name.value; + var existingType = existingTypeMap[typeName]; + + if (isEnumType(existingType) && existingType.getValue(valueName)) { + context.reportError(new GraphQLError("Enum value \"".concat(typeName, ".").concat(valueName, "\" already exists in the schema. It cannot also be defined in this type extension."), valueDef.name)); + } else if (valueNames[valueName]) { + context.reportError(new GraphQLError("Enum value \"".concat(typeName, ".").concat(valueName, "\" can only be defined once."), [valueNames[valueName], valueDef.name])); + } else { + valueNames[valueName] = valueDef.name; + } + } + + return false; + } +} diff --git a/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.d.ts b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.d.ts new file mode 100644 index 0000000..26ebb06 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.d.ts @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueFieldDefinitionNamesRule } from 'graphql' + * or + * import { UniqueFieldDefinitionNamesRule } from 'graphql/validation' + */ +export { UniqueFieldDefinitionNamesRule as UniqueFieldDefinitionNames } from './UniqueFieldDefinitionNamesRule'; diff --git a/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.js b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.js new file mode 100644 index 0000000..7af0dca --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "UniqueFieldDefinitionNames", { + enumerable: true, + get: function get() { + return _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule; + } +}); + +var _UniqueFieldDefinitionNamesRule = require("./UniqueFieldDefinitionNamesRule.js"); diff --git a/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.js.flow b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.js.flow new file mode 100644 index 0000000..dc54877 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.js.flow @@ -0,0 +1,9 @@ +// @flow strict +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueFieldDefinitionNamesRule } from 'graphql' + * or + * import { UniqueFieldDefinitionNamesRule } from 'graphql/validation' + */ +export { UniqueFieldDefinitionNamesRule as UniqueFieldDefinitionNames } from './UniqueFieldDefinitionNamesRule'; diff --git a/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.mjs b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.mjs new file mode 100644 index 0000000..c2a3add --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNames.mjs @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueFieldDefinitionNamesRule } from 'graphql' + * or + * import { UniqueFieldDefinitionNamesRule } from 'graphql/validation' + */ +export { UniqueFieldDefinitionNamesRule as UniqueFieldDefinitionNames } from "./UniqueFieldDefinitionNamesRule.mjs"; diff --git a/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.d.ts b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.d.ts new file mode 100644 index 0000000..6f356ed --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.d.ts @@ -0,0 +1,11 @@ +import { ASTVisitor } from '../../language/visitor'; +import { SDLValidationContext } from '../ValidationContext'; + +/** + * Unique field definition names + * + * A GraphQL complex type is only valid if all its fields are uniquely named. + */ +export function UniqueFieldDefinitionNamesRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.js b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.js new file mode 100644 index 0000000..3cdaa71 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UniqueFieldDefinitionNamesRule = UniqueFieldDefinitionNamesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _definition = require("../../type/definition.js"); + +/** + * Unique field definition names + * + * A GraphQL complex type is only valid if all its fields are uniquely named. + */ +function UniqueFieldDefinitionNamesRule(context) { + var schema = context.getSchema(); + var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + var knownFieldNames = Object.create(null); + return { + InputObjectTypeDefinition: checkFieldUniqueness, + InputObjectTypeExtension: checkFieldUniqueness, + InterfaceTypeDefinition: checkFieldUniqueness, + InterfaceTypeExtension: checkFieldUniqueness, + ObjectTypeDefinition: checkFieldUniqueness, + ObjectTypeExtension: checkFieldUniqueness + }; + + function checkFieldUniqueness(node) { + var _node$fields; + + var typeName = node.name.value; + + if (!knownFieldNames[typeName]) { + knownFieldNames[typeName] = Object.create(null); + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + + var fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; + var fieldNames = knownFieldNames[typeName]; + + for (var _i2 = 0; _i2 < fieldNodes.length; _i2++) { + var fieldDef = fieldNodes[_i2]; + var fieldName = fieldDef.name.value; + + if (hasField(existingTypeMap[typeName], fieldName)) { + context.reportError(new _GraphQLError.GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" already exists in the schema. It cannot also be defined in this type extension."), fieldDef.name)); + } else if (fieldNames[fieldName]) { + context.reportError(new _GraphQLError.GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" can only be defined once."), [fieldNames[fieldName], fieldDef.name])); + } else { + fieldNames[fieldName] = fieldDef.name; + } + } + + return false; + } +} + +function hasField(type, fieldName) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type) || (0, _definition.isInputObjectType)(type)) { + return type.getFields()[fieldName] != null; + } + + return false; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.js.flow b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.js.flow new file mode 100644 index 0000000..1193111 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.js.flow @@ -0,0 +1,87 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import type { + NameNode, + FieldDefinitionNode, + InputValueDefinitionNode, +} from '../../language/ast'; + +import type { GraphQLNamedType } from '../../type/definition'; +import { + isObjectType, + isInterfaceType, + isInputObjectType, +} from '../../type/definition'; + +import type { SDLValidationContext } from '../ValidationContext'; + +/** + * Unique field definition names + * + * A GraphQL complex type is only valid if all its fields are uniquely named. + */ +export function UniqueFieldDefinitionNamesRule( + context: SDLValidationContext, +): ASTVisitor { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownFieldNames = Object.create(null); + + return { + InputObjectTypeDefinition: checkFieldUniqueness, + InputObjectTypeExtension: checkFieldUniqueness, + InterfaceTypeDefinition: checkFieldUniqueness, + InterfaceTypeExtension: checkFieldUniqueness, + ObjectTypeDefinition: checkFieldUniqueness, + ObjectTypeExtension: checkFieldUniqueness, + }; + + function checkFieldUniqueness(node: { + +name: NameNode, + +fields?: $ReadOnlyArray<InputValueDefinitionNode | FieldDefinitionNode>, + ... + }) { + const typeName = node.name.value; + + if (!knownFieldNames[typeName]) { + knownFieldNames[typeName] = Object.create(null); + } + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const fieldNodes = node.fields ?? []; + const fieldNames = knownFieldNames[typeName]; + + for (const fieldDef of fieldNodes) { + const fieldName = fieldDef.name.value; + + if (hasField(existingTypeMap[typeName], fieldName)) { + context.reportError( + new GraphQLError( + `Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`, + fieldDef.name, + ), + ); + } else if (fieldNames[fieldName]) { + context.reportError( + new GraphQLError( + `Field "${typeName}.${fieldName}" can only be defined once.`, + [fieldNames[fieldName], fieldDef.name], + ), + ); + } else { + fieldNames[fieldName] = fieldDef.name; + } + } + + return false; + } +} + +function hasField(type: GraphQLNamedType, fieldName: string): boolean { + if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) { + return type.getFields()[fieldName] != null; + } + return false; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs new file mode 100644 index 0000000..176bb68 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs @@ -0,0 +1,58 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { isObjectType, isInterfaceType, isInputObjectType } from "../../type/definition.mjs"; + +/** + * Unique field definition names + * + * A GraphQL complex type is only valid if all its fields are uniquely named. + */ +export function UniqueFieldDefinitionNamesRule(context) { + var schema = context.getSchema(); + var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + var knownFieldNames = Object.create(null); + return { + InputObjectTypeDefinition: checkFieldUniqueness, + InputObjectTypeExtension: checkFieldUniqueness, + InterfaceTypeDefinition: checkFieldUniqueness, + InterfaceTypeExtension: checkFieldUniqueness, + ObjectTypeDefinition: checkFieldUniqueness, + ObjectTypeExtension: checkFieldUniqueness + }; + + function checkFieldUniqueness(node) { + var _node$fields; + + var typeName = node.name.value; + + if (!knownFieldNames[typeName]) { + knownFieldNames[typeName] = Object.create(null); + } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + + + var fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; + var fieldNames = knownFieldNames[typeName]; + + for (var _i2 = 0; _i2 < fieldNodes.length; _i2++) { + var fieldDef = fieldNodes[_i2]; + var fieldName = fieldDef.name.value; + + if (hasField(existingTypeMap[typeName], fieldName)) { + context.reportError(new GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" already exists in the schema. It cannot also be defined in this type extension."), fieldDef.name)); + } else if (fieldNames[fieldName]) { + context.reportError(new GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" can only be defined once."), [fieldNames[fieldName], fieldDef.name])); + } else { + fieldNames[fieldName] = fieldDef.name; + } + } + + return false; + } +} + +function hasField(type, fieldName) { + if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) { + return type.getFields()[fieldName] != null; + } + + return false; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.d.ts b/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.d.ts new file mode 100644 index 0000000..6154158 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.d.ts @@ -0,0 +1,11 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ASTValidationContext } from '../ValidationContext'; + +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ +export function UniqueFragmentNamesRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.js b/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.js new file mode 100644 index 0000000..d03a74e --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UniqueFragmentNamesRule = UniqueFragmentNamesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ +function UniqueFragmentNamesRule(context) { + var knownFragmentNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + var fragmentName = node.name.value; + + if (knownFragmentNames[fragmentName]) { + context.reportError(new _GraphQLError.GraphQLError("There can be only one fragment named \"".concat(fragmentName, "\"."), [knownFragmentNames[fragmentName], node.name])); + } else { + knownFragmentNames[fragmentName] = node.name; + } + + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.js.flow b/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.js.flow new file mode 100644 index 0000000..cb1b777 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.js.flow @@ -0,0 +1,34 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; + +import type { ASTValidationContext } from '../ValidationContext'; + +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ +export function UniqueFragmentNamesRule( + context: ASTValidationContext, +): ASTVisitor { + const knownFragmentNames = Object.create(null); + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + const fragmentName = node.name.value; + if (knownFragmentNames[fragmentName]) { + context.reportError( + new GraphQLError( + `There can be only one fragment named "${fragmentName}".`, + [knownFragmentNames[fragmentName], node.name], + ), + ); + } else { + knownFragmentNames[fragmentName] = node.name; + } + return false; + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs b/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs new file mode 100644 index 0000000..d9b0ef3 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs @@ -0,0 +1,26 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ +export function UniqueFragmentNamesRule(context) { + var knownFragmentNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + var fragmentName = node.name.value; + + if (knownFragmentNames[fragmentName]) { + context.reportError(new GraphQLError("There can be only one fragment named \"".concat(fragmentName, "\"."), [knownFragmentNames[fragmentName], node.name])); + } else { + knownFragmentNames[fragmentName] = node.name; + } + + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.d.ts b/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.d.ts new file mode 100644 index 0000000..c66d65f --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.d.ts @@ -0,0 +1,12 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ASTValidationContext } from '../ValidationContext'; + +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ +export function UniqueInputFieldNamesRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.js b/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.js new file mode 100644 index 0000000..4a7dfda --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UniqueInputFieldNamesRule = UniqueInputFieldNamesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ +function UniqueInputFieldNamesRule(context) { + var knownNameStack = []; + var knownNames = Object.create(null); + return { + ObjectValue: { + enter: function enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave: function leave() { + knownNames = knownNameStack.pop(); + } + }, + ObjectField: function ObjectField(node) { + var fieldName = node.name.value; + + if (knownNames[fieldName]) { + context.reportError(new _GraphQLError.GraphQLError("There can be only one input field named \"".concat(fieldName, "\"."), [knownNames[fieldName], node.name])); + } else { + knownNames[fieldName] = node.name; + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.js.flow b/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.js.flow new file mode 100644 index 0000000..e79cd7a --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.js.flow @@ -0,0 +1,44 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; + +import type { ASTValidationContext } from '../ValidationContext'; + +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ +export function UniqueInputFieldNamesRule( + context: ASTValidationContext, +): ASTVisitor { + const knownNameStack = []; + let knownNames = Object.create(null); + + return { + ObjectValue: { + enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave() { + knownNames = knownNameStack.pop(); + }, + }, + ObjectField(node) { + const fieldName = node.name.value; + if (knownNames[fieldName]) { + context.reportError( + new GraphQLError( + `There can be only one input field named "${fieldName}".`, + [knownNames[fieldName], node.name], + ), + ); + } else { + knownNames[fieldName] = node.name; + } + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs b/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs new file mode 100644 index 0000000..ae0c884 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs @@ -0,0 +1,32 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ +export function UniqueInputFieldNamesRule(context) { + var knownNameStack = []; + var knownNames = Object.create(null); + return { + ObjectValue: { + enter: function enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave: function leave() { + knownNames = knownNameStack.pop(); + } + }, + ObjectField: function ObjectField(node) { + var fieldName = node.name.value; + + if (knownNames[fieldName]) { + context.reportError(new GraphQLError("There can be only one input field named \"".concat(fieldName, "\"."), [knownNames[fieldName], node.name])); + } else { + knownNames[fieldName] = node.name; + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.d.ts b/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.d.ts new file mode 100644 index 0000000..aa2d06a --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.d.ts @@ -0,0 +1,11 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ASTValidationContext } from '../ValidationContext'; + +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ +export function UniqueOperationNamesRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.js b/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.js new file mode 100644 index 0000000..5c31464 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UniqueOperationNamesRule = UniqueOperationNamesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ +function UniqueOperationNamesRule(context) { + var knownOperationNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition(node) { + var operationName = node.name; + + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError(new _GraphQLError.GraphQLError("There can be only one operation named \"".concat(operationName.value, "\"."), [knownOperationNames[operationName.value], operationName])); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + + return false; + }, + FragmentDefinition: function FragmentDefinition() { + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.js.flow b/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.js.flow new file mode 100644 index 0000000..5e6afef --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.js.flow @@ -0,0 +1,36 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; + +import type { ASTValidationContext } from '../ValidationContext'; + +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ +export function UniqueOperationNamesRule( + context: ASTValidationContext, +): ASTVisitor { + const knownOperationNames = Object.create(null); + return { + OperationDefinition(node) { + const operationName = node.name; + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError( + new GraphQLError( + `There can be only one operation named "${operationName.value}".`, + [knownOperationNames[operationName.value], operationName], + ), + ); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + return false; + }, + FragmentDefinition: () => false, + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs b/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs new file mode 100644 index 0000000..28190c5 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs @@ -0,0 +1,28 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ +export function UniqueOperationNamesRule(context) { + var knownOperationNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition(node) { + var operationName = node.name; + + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError(new GraphQLError("There can be only one operation named \"".concat(operationName.value, "\"."), [knownOperationNames[operationName.value], operationName])); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + + return false; + }, + FragmentDefinition: function FragmentDefinition() { + return false; + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationTypes.d.ts b/school/node_modules/graphql/validation/rules/UniqueOperationTypes.d.ts new file mode 100644 index 0000000..423932d --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationTypes.d.ts @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueOperationTypesRule } from 'graphql' + * or + * import { UniqueOperationTypesRule } from 'graphql/validation' + */ +export { UniqueOperationTypesRule as UniqueOperationTypes } from './UniqueOperationTypesRule'; diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationTypes.js b/school/node_modules/graphql/validation/rules/UniqueOperationTypes.js new file mode 100644 index 0000000..814f2e2 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationTypes.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "UniqueOperationTypes", { + enumerable: true, + get: function get() { + return _UniqueOperationTypesRule.UniqueOperationTypesRule; + } +}); + +var _UniqueOperationTypesRule = require("./UniqueOperationTypesRule.js"); diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationTypes.js.flow b/school/node_modules/graphql/validation/rules/UniqueOperationTypes.js.flow new file mode 100644 index 0000000..8649852 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationTypes.js.flow @@ -0,0 +1,9 @@ +// @flow strict +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueOperationTypesRule } from 'graphql' + * or + * import { UniqueOperationTypesRule } from 'graphql/validation' + */ +export { UniqueOperationTypesRule as UniqueOperationTypes } from './UniqueOperationTypesRule'; diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationTypes.mjs b/school/node_modules/graphql/validation/rules/UniqueOperationTypes.mjs new file mode 100644 index 0000000..4cd53b3 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationTypes.mjs @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueOperationTypesRule } from 'graphql' + * or + * import { UniqueOperationTypesRule } from 'graphql/validation' + */ +export { UniqueOperationTypesRule as UniqueOperationTypes } from "./UniqueOperationTypesRule.mjs"; diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.d.ts b/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.d.ts new file mode 100644 index 0000000..a0d6441 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.d.ts @@ -0,0 +1,11 @@ +import { ASTVisitor } from '../../language/visitor'; +import { SDLValidationContext } from '../ValidationContext'; + +/** + * Unique operation types + * + * A GraphQL document is only valid if it has only one type per operation. + */ +export function UniqueOperationTypesRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.js b/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.js new file mode 100644 index 0000000..fa59189 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.js @@ -0,0 +1,50 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UniqueOperationTypesRule = UniqueOperationTypesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * Unique operation types + * + * A GraphQL document is only valid if it has only one type per operation. + */ +function UniqueOperationTypesRule(context) { + var schema = context.getSchema(); + var definedOperationTypes = Object.create(null); + var existingOperationTypes = schema ? { + query: schema.getQueryType(), + mutation: schema.getMutationType(), + subscription: schema.getSubscriptionType() + } : {}; + return { + SchemaDefinition: checkOperationTypes, + SchemaExtension: checkOperationTypes + }; + + function checkOperationTypes(node) { + var _node$operationTypes; + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; + + for (var _i2 = 0; _i2 < operationTypesNodes.length; _i2++) { + var operationType = operationTypesNodes[_i2]; + var operation = operationType.operation; + var alreadyDefinedOperationType = definedOperationTypes[operation]; + + if (existingOperationTypes[operation]) { + context.reportError(new _GraphQLError.GraphQLError("Type for ".concat(operation, " already defined in the schema. It cannot be redefined."), operationType)); + } else if (alreadyDefinedOperationType) { + context.reportError(new _GraphQLError.GraphQLError("There can be only one ".concat(operation, " type in schema."), [alreadyDefinedOperationType, operationType])); + } else { + definedOperationTypes[operation] = operationType; + } + } + + return false; + } +} diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.js.flow b/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.js.flow new file mode 100644 index 0000000..8a9d4bd --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.js.flow @@ -0,0 +1,66 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import type { + SchemaDefinitionNode, + SchemaExtensionNode, +} from '../../language/ast'; + +import type { SDLValidationContext } from '../ValidationContext'; + +/** + * Unique operation types + * + * A GraphQL document is only valid if it has only one type per operation. + */ +export function UniqueOperationTypesRule( + context: SDLValidationContext, +): ASTVisitor { + const schema = context.getSchema(); + const definedOperationTypes = Object.create(null); + const existingOperationTypes = schema + ? { + query: schema.getQueryType(), + mutation: schema.getMutationType(), + subscription: schema.getSubscriptionType(), + } + : {}; + + return { + SchemaDefinition: checkOperationTypes, + SchemaExtension: checkOperationTypes, + }; + + function checkOperationTypes( + node: SchemaDefinitionNode | SchemaExtensionNode, + ) { + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + const operationTypesNodes = node.operationTypes ?? []; + + for (const operationType of operationTypesNodes) { + const operation = operationType.operation; + const alreadyDefinedOperationType = definedOperationTypes[operation]; + + if (existingOperationTypes[operation]) { + context.reportError( + new GraphQLError( + `Type for ${operation} already defined in the schema. It cannot be redefined.`, + operationType, + ), + ); + } else if (alreadyDefinedOperationType) { + context.reportError( + new GraphQLError( + `There can be only one ${operation} type in schema.`, + [alreadyDefinedOperationType, operationType], + ), + ); + } else { + definedOperationTypes[operation] = operationType; + } + } + + return false; + } +} diff --git a/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs b/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs new file mode 100644 index 0000000..e79b684 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs @@ -0,0 +1,43 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * Unique operation types + * + * A GraphQL document is only valid if it has only one type per operation. + */ +export function UniqueOperationTypesRule(context) { + var schema = context.getSchema(); + var definedOperationTypes = Object.create(null); + var existingOperationTypes = schema ? { + query: schema.getQueryType(), + mutation: schema.getMutationType(), + subscription: schema.getSubscriptionType() + } : {}; + return { + SchemaDefinition: checkOperationTypes, + SchemaExtension: checkOperationTypes + }; + + function checkOperationTypes(node) { + var _node$operationTypes; + + // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203') + var operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; + + for (var _i2 = 0; _i2 < operationTypesNodes.length; _i2++) { + var operationType = operationTypesNodes[_i2]; + var operation = operationType.operation; + var alreadyDefinedOperationType = definedOperationTypes[operation]; + + if (existingOperationTypes[operation]) { + context.reportError(new GraphQLError("Type for ".concat(operation, " already defined in the schema. It cannot be redefined."), operationType)); + } else if (alreadyDefinedOperationType) { + context.reportError(new GraphQLError("There can be only one ".concat(operation, " type in schema."), [alreadyDefinedOperationType, operationType])); + } else { + definedOperationTypes[operation] = operationType; + } + } + + return false; + } +} diff --git a/school/node_modules/graphql/validation/rules/UniqueTypeNames.d.ts b/school/node_modules/graphql/validation/rules/UniqueTypeNames.d.ts new file mode 100644 index 0000000..1740eef --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueTypeNames.d.ts @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueTypeNamesRule } from 'graphql' + * or + * import { UniqueTypeNamesRule } from 'graphql/validation' + */ +export { UniqueTypeNamesRule as UniqueTypeNames } from './UniqueTypeNamesRule'; diff --git a/school/node_modules/graphql/validation/rules/UniqueTypeNames.js b/school/node_modules/graphql/validation/rules/UniqueTypeNames.js new file mode 100644 index 0000000..82e72ce --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueTypeNames.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "UniqueTypeNames", { + enumerable: true, + get: function get() { + return _UniqueTypeNamesRule.UniqueTypeNamesRule; + } +}); + +var _UniqueTypeNamesRule = require("./UniqueTypeNamesRule.js"); diff --git a/school/node_modules/graphql/validation/rules/UniqueTypeNames.js.flow b/school/node_modules/graphql/validation/rules/UniqueTypeNames.js.flow new file mode 100644 index 0000000..2b43e1c --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueTypeNames.js.flow @@ -0,0 +1,9 @@ +// @flow strict +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueTypeNamesRule } from 'graphql' + * or + * import { UniqueTypeNamesRule } from 'graphql/validation' + */ +export { UniqueTypeNamesRule as UniqueTypeNames } from './UniqueTypeNamesRule'; diff --git a/school/node_modules/graphql/validation/rules/UniqueTypeNames.mjs b/school/node_modules/graphql/validation/rules/UniqueTypeNames.mjs new file mode 100644 index 0000000..ea0c5bf --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueTypeNames.mjs @@ -0,0 +1,8 @@ +/** + * @deprecated and will be removed in v16 + * Please use either: + * import { UniqueTypeNamesRule } from 'graphql' + * or + * import { UniqueTypeNamesRule } from 'graphql/validation' + */ +export { UniqueTypeNamesRule as UniqueTypeNames } from "./UniqueTypeNamesRule.mjs"; diff --git a/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.d.ts b/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.d.ts new file mode 100644 index 0000000..e2b3759 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.d.ts @@ -0,0 +1,9 @@ +import { ASTVisitor } from '../../language/visitor'; +import { SDLValidationContext } from '../ValidationContext'; + +/** + * Unique type names + * + * A GraphQL document is only valid if all defined types have unique names. + */ +export function UniqueTypeNamesRule(context: SDLValidationContext): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.js b/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.js new file mode 100644 index 0000000..afae028 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UniqueTypeNamesRule = UniqueTypeNamesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * Unique type names + * + * A GraphQL document is only valid if all defined types have unique names. + */ +function UniqueTypeNamesRule(context) { + var knownTypeNames = Object.create(null); + var schema = context.getSchema(); + return { + ScalarTypeDefinition: checkTypeName, + ObjectTypeDefinition: checkTypeName, + InterfaceTypeDefinition: checkTypeName, + UnionTypeDefinition: checkTypeName, + EnumTypeDefinition: checkTypeName, + InputObjectTypeDefinition: checkTypeName + }; + + function checkTypeName(node) { + var typeName = node.name.value; + + if (schema !== null && schema !== void 0 && schema.getType(typeName)) { + context.reportError(new _GraphQLError.GraphQLError("Type \"".concat(typeName, "\" already exists in the schema. It cannot also be defined in this type definition."), node.name)); + return; + } + + if (knownTypeNames[typeName]) { + context.reportError(new _GraphQLError.GraphQLError("There can be only one type named \"".concat(typeName, "\"."), [knownTypeNames[typeName], node.name])); + } else { + knownTypeNames[typeName] = node.name; + } + + return false; + } +} diff --git a/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.js.flow b/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.js.flow new file mode 100644 index 0000000..3dd0e7c --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.js.flow @@ -0,0 +1,53 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import type { TypeDefinitionNode } from '../../language/ast'; + +import type { SDLValidationContext } from '../ValidationContext'; + +/** + * Unique type names + * + * A GraphQL document is only valid if all defined types have unique names. + */ +export function UniqueTypeNamesRule(context: SDLValidationContext): ASTVisitor { + const knownTypeNames = Object.create(null); + const schema = context.getSchema(); + + return { + ScalarTypeDefinition: checkTypeName, + ObjectTypeDefinition: checkTypeName, + InterfaceTypeDefinition: checkTypeName, + UnionTypeDefinition: checkTypeName, + EnumTypeDefinition: checkTypeName, + InputObjectTypeDefinition: checkTypeName, + }; + + function checkTypeName(node: TypeDefinitionNode) { + const typeName = node.name.value; + + if (schema?.getType(typeName)) { + context.reportError( + new GraphQLError( + `Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`, + node.name, + ), + ); + return; + } + + if (knownTypeNames[typeName]) { + context.reportError( + new GraphQLError(`There can be only one type named "${typeName}".`, [ + knownTypeNames[typeName], + node.name, + ]), + ); + } else { + knownTypeNames[typeName] = node.name; + } + + return false; + } +} diff --git a/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs b/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs new file mode 100644 index 0000000..55d2f95 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs @@ -0,0 +1,36 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * Unique type names + * + * A GraphQL document is only valid if all defined types have unique names. + */ +export function UniqueTypeNamesRule(context) { + var knownTypeNames = Object.create(null); + var schema = context.getSchema(); + return { + ScalarTypeDefinition: checkTypeName, + ObjectTypeDefinition: checkTypeName, + InterfaceTypeDefinition: checkTypeName, + UnionTypeDefinition: checkTypeName, + EnumTypeDefinition: checkTypeName, + InputObjectTypeDefinition: checkTypeName + }; + + function checkTypeName(node) { + var typeName = node.name.value; + + if (schema !== null && schema !== void 0 && schema.getType(typeName)) { + context.reportError(new GraphQLError("Type \"".concat(typeName, "\" already exists in the schema. It cannot also be defined in this type definition."), node.name)); + return; + } + + if (knownTypeNames[typeName]) { + context.reportError(new GraphQLError("There can be only one type named \"".concat(typeName, "\"."), [knownTypeNames[typeName], node.name])); + } else { + knownTypeNames[typeName] = node.name; + } + + return false; + } +} diff --git a/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.d.ts b/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.d.ts new file mode 100644 index 0000000..6f15764 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.d.ts @@ -0,0 +1,11 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ASTValidationContext } from '../ValidationContext'; + +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ +export function UniqueVariableNamesRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.js b/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.js new file mode 100644 index 0000000..d6cae4a --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UniqueVariableNamesRule = UniqueVariableNamesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ +function UniqueVariableNamesRule(context) { + var knownVariableNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + knownVariableNames = Object.create(null); + }, + VariableDefinition: function VariableDefinition(node) { + var variableName = node.variable.name.value; + + if (knownVariableNames[variableName]) { + context.reportError(new _GraphQLError.GraphQLError("There can be only one variable named \"$".concat(variableName, "\"."), [knownVariableNames[variableName], node.variable.name])); + } else { + knownVariableNames[variableName] = node.variable.name; + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.js.flow b/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.js.flow new file mode 100644 index 0000000..4865dc6 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.js.flow @@ -0,0 +1,36 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ASTVisitor } from '../../language/visitor'; +import type { VariableDefinitionNode } from '../../language/ast'; + +import type { ASTValidationContext } from '../ValidationContext'; + +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ +export function UniqueVariableNamesRule( + context: ASTValidationContext, +): ASTVisitor { + let knownVariableNames = Object.create(null); + return { + OperationDefinition() { + knownVariableNames = Object.create(null); + }, + VariableDefinition(node: VariableDefinitionNode) { + const variableName = node.variable.name.value; + if (knownVariableNames[variableName]) { + context.reportError( + new GraphQLError( + `There can be only one variable named "$${variableName}".`, + [knownVariableNames[variableName], node.variable.name], + ), + ); + } else { + knownVariableNames[variableName] = node.variable.name; + } + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs b/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs new file mode 100644 index 0000000..3b650a4 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs @@ -0,0 +1,24 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; + +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ +export function UniqueVariableNamesRule(context) { + var knownVariableNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + knownVariableNames = Object.create(null); + }, + VariableDefinition: function VariableDefinition(node) { + var variableName = node.variable.name.value; + + if (knownVariableNames[variableName]) { + context.reportError(new GraphQLError("There can be only one variable named \"$".concat(variableName, "\"."), [knownVariableNames[variableName], node.variable.name])); + } else { + knownVariableNames[variableName] = node.variable.name; + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.d.ts b/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.d.ts new file mode 100644 index 0000000..98ff7a7 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.d.ts @@ -0,0 +1,10 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + */ +export function ValuesOfCorrectTypeRule(context: ValidationContext): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js b/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js new file mode 100644 index 0000000..d898200 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js @@ -0,0 +1,143 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ValuesOfCorrectTypeRule = ValuesOfCorrectTypeRule; + +var _objectValues3 = _interopRequireDefault(require("../../polyfills/objectValues.js")); + +var _keyMap = _interopRequireDefault(require("../../jsutils/keyMap.js")); + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect.js")); + +var _didYouMean = _interopRequireDefault(require("../../jsutils/didYouMean.js")); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList.js")); + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _printer = require("../../language/printer.js"); + +var _definition = require("../../type/definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + */ +function ValuesOfCorrectTypeRule(context) { + return { + ListValue: function ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + var type = (0, _definition.getNullableType)(context.getParentInputType()); + + if (!(0, _definition.isListType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } + }, + ObjectValue: function ObjectValue(node) { + var type = (0, _definition.getNamedType)(context.getInputType()); + + if (!(0, _definition.isInputObjectType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. + + + var fieldNodeMap = (0, _keyMap.default)(node.fields, function (field) { + return field.name.value; + }); + + for (var _i2 = 0, _objectValues2 = (0, _objectValues3.default)(type.getFields()); _i2 < _objectValues2.length; _i2++) { + var fieldDef = _objectValues2[_i2]; + var fieldNode = fieldNodeMap[fieldDef.name]; + + if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) { + var typeStr = (0, _inspect.default)(fieldDef.type); + context.reportError(new _GraphQLError.GraphQLError("Field \"".concat(type.name, ".").concat(fieldDef.name, "\" of required type \"").concat(typeStr, "\" was not provided."), node)); + } + } + }, + ObjectField: function ObjectField(node) { + var parentType = (0, _definition.getNamedType)(context.getParentInputType()); + var fieldType = context.getInputType(); + + if (!fieldType && (0, _definition.isInputObjectType)(parentType)) { + var suggestions = (0, _suggestionList.default)(node.name.value, Object.keys(parentType.getFields())); + context.reportError(new _GraphQLError.GraphQLError("Field \"".concat(node.name.value, "\" is not defined by type \"").concat(parentType.name, "\".") + (0, _didYouMean.default)(suggestions), node)); + } + }, + NullValue: function NullValue(node) { + var type = context.getInputType(); + + if ((0, _definition.isNonNullType)(type)) { + context.reportError(new _GraphQLError.GraphQLError("Expected value of type \"".concat((0, _inspect.default)(type), "\", found ").concat((0, _printer.print)(node), "."), node)); + } + }, + EnumValue: function EnumValue(node) { + return isValidValueNode(context, node); + }, + IntValue: function IntValue(node) { + return isValidValueNode(context, node); + }, + FloatValue: function FloatValue(node) { + return isValidValueNode(context, node); + }, + StringValue: function StringValue(node) { + return isValidValueNode(context, node); + }, + BooleanValue: function BooleanValue(node) { + return isValidValueNode(context, node); + } + }; +} +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ + + +function isValidValueNode(context, node) { + // Report any error at the full type expected by the location. + var locationType = context.getInputType(); + + if (!locationType) { + return; + } + + var type = (0, _definition.getNamedType)(locationType); + + if (!(0, _definition.isLeafType)(type)) { + var typeStr = (0, _inspect.default)(locationType); + context.reportError(new _GraphQLError.GraphQLError("Expected value of type \"".concat(typeStr, "\", found ").concat((0, _printer.print)(node), "."), node)); + return; + } // Scalars and Enums determine if a literal value is valid via parseLiteral(), + // which may throw or return an invalid value to indicate failure. + + + try { + var parseResult = type.parseLiteral(node, undefined + /* variables */ + ); + + if (parseResult === undefined) { + var _typeStr = (0, _inspect.default)(locationType); + + context.reportError(new _GraphQLError.GraphQLError("Expected value of type \"".concat(_typeStr, "\", found ").concat((0, _printer.print)(node), "."), node)); + } + } catch (error) { + var _typeStr2 = (0, _inspect.default)(locationType); + + if (error instanceof _GraphQLError.GraphQLError) { + context.reportError(error); + } else { + context.reportError(new _GraphQLError.GraphQLError("Expected value of type \"".concat(_typeStr2, "\", found ").concat((0, _printer.print)(node), "; ") + error.message, node, undefined, undefined, undefined, error)); + } + } +} diff --git a/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js.flow b/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js.flow new file mode 100644 index 0000000..09a922c --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js.flow @@ -0,0 +1,158 @@ +// @flow strict +import objectValues from '../../polyfills/objectValues'; + +import keyMap from '../../jsutils/keyMap'; +import inspect from '../../jsutils/inspect'; +import didYouMean from '../../jsutils/didYouMean'; +import suggestionList from '../../jsutils/suggestionList'; + +import { GraphQLError } from '../../error/GraphQLError'; + +import type { ValueNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; +import { print } from '../../language/printer'; + +import { + isLeafType, + isInputObjectType, + isListType, + isNonNullType, + isRequiredInputField, + getNullableType, + getNamedType, +} from '../../type/definition'; + +import type { ValidationContext } from '../ValidationContext'; + +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + */ +export function ValuesOfCorrectTypeRule( + context: ValidationContext, +): ASTVisitor { + return { + ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + const type = getNullableType(context.getParentInputType()); + if (!isListType(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } + }, + ObjectValue(node) { + const type = getNamedType(context.getInputType()); + if (!isInputObjectType(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } + // Ensure every required field exists. + const fieldNodeMap = keyMap(node.fields, (field) => field.name.value); + for (const fieldDef of objectValues(type.getFields())) { + const fieldNode = fieldNodeMap[fieldDef.name]; + if (!fieldNode && isRequiredInputField(fieldDef)) { + const typeStr = inspect(fieldDef.type); + context.reportError( + new GraphQLError( + `Field "${type.name}.${fieldDef.name}" of required type "${typeStr}" was not provided.`, + node, + ), + ); + } + } + }, + ObjectField(node) { + const parentType = getNamedType(context.getParentInputType()); + const fieldType = context.getInputType(); + if (!fieldType && isInputObjectType(parentType)) { + const suggestions = suggestionList( + node.name.value, + Object.keys(parentType.getFields()), + ); + context.reportError( + new GraphQLError( + `Field "${node.name.value}" is not defined by type "${parentType.name}".` + + didYouMean(suggestions), + node, + ), + ); + } + }, + NullValue(node) { + const type = context.getInputType(); + if (isNonNullType(type)) { + context.reportError( + new GraphQLError( + `Expected value of type "${inspect(type)}", found ${print(node)}.`, + node, + ), + ); + } + }, + EnumValue: (node) => isValidValueNode(context, node), + IntValue: (node) => isValidValueNode(context, node), + FloatValue: (node) => isValidValueNode(context, node), + StringValue: (node) => isValidValueNode(context, node), + BooleanValue: (node) => isValidValueNode(context, node), + }; +} + +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ +function isValidValueNode(context: ValidationContext, node: ValueNode): void { + // Report any error at the full type expected by the location. + const locationType = context.getInputType(); + if (!locationType) { + return; + } + + const type = getNamedType(locationType); + + if (!isLeafType(type)) { + const typeStr = inspect(locationType); + context.reportError( + new GraphQLError( + `Expected value of type "${typeStr}", found ${print(node)}.`, + node, + ), + ); + return; + } + + // Scalars and Enums determine if a literal value is valid via parseLiteral(), + // which may throw or return an invalid value to indicate failure. + try { + const parseResult = type.parseLiteral(node, undefined /* variables */); + if (parseResult === undefined) { + const typeStr = inspect(locationType); + context.reportError( + new GraphQLError( + `Expected value of type "${typeStr}", found ${print(node)}.`, + node, + ), + ); + } + } catch (error) { + const typeStr = inspect(locationType); + if (error instanceof GraphQLError) { + context.reportError(error); + } else { + context.reportError( + new GraphQLError( + `Expected value of type "${typeStr}", found ${print(node)}; ` + + error.message, + node, + undefined, + undefined, + undefined, + error, // Ensure a reference to the original error is maintained. + ), + ); + } + } +} diff --git a/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs b/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs new file mode 100644 index 0000000..01c8967 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs @@ -0,0 +1,126 @@ +import objectValues from "../../polyfills/objectValues.mjs"; +import keyMap from "../../jsutils/keyMap.mjs"; +import inspect from "../../jsutils/inspect.mjs"; +import didYouMean from "../../jsutils/didYouMean.mjs"; +import suggestionList from "../../jsutils/suggestionList.mjs"; +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { print } from "../../language/printer.mjs"; +import { isLeafType, isInputObjectType, isListType, isNonNullType, isRequiredInputField, getNullableType, getNamedType } from "../../type/definition.mjs"; + +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + */ +export function ValuesOfCorrectTypeRule(context) { + return { + ListValue: function ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + var type = getNullableType(context.getParentInputType()); + + if (!isListType(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } + }, + ObjectValue: function ObjectValue(node) { + var type = getNamedType(context.getInputType()); + + if (!isInputObjectType(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. + + + var fieldNodeMap = keyMap(node.fields, function (field) { + return field.name.value; + }); + + for (var _i2 = 0, _objectValues2 = objectValues(type.getFields()); _i2 < _objectValues2.length; _i2++) { + var fieldDef = _objectValues2[_i2]; + var fieldNode = fieldNodeMap[fieldDef.name]; + + if (!fieldNode && isRequiredInputField(fieldDef)) { + var typeStr = inspect(fieldDef.type); + context.reportError(new GraphQLError("Field \"".concat(type.name, ".").concat(fieldDef.name, "\" of required type \"").concat(typeStr, "\" was not provided."), node)); + } + } + }, + ObjectField: function ObjectField(node) { + var parentType = getNamedType(context.getParentInputType()); + var fieldType = context.getInputType(); + + if (!fieldType && isInputObjectType(parentType)) { + var suggestions = suggestionList(node.name.value, Object.keys(parentType.getFields())); + context.reportError(new GraphQLError("Field \"".concat(node.name.value, "\" is not defined by type \"").concat(parentType.name, "\".") + didYouMean(suggestions), node)); + } + }, + NullValue: function NullValue(node) { + var type = context.getInputType(); + + if (isNonNullType(type)) { + context.reportError(new GraphQLError("Expected value of type \"".concat(inspect(type), "\", found ").concat(print(node), "."), node)); + } + }, + EnumValue: function EnumValue(node) { + return isValidValueNode(context, node); + }, + IntValue: function IntValue(node) { + return isValidValueNode(context, node); + }, + FloatValue: function FloatValue(node) { + return isValidValueNode(context, node); + }, + StringValue: function StringValue(node) { + return isValidValueNode(context, node); + }, + BooleanValue: function BooleanValue(node) { + return isValidValueNode(context, node); + } + }; +} +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ + +function isValidValueNode(context, node) { + // Report any error at the full type expected by the location. + var locationType = context.getInputType(); + + if (!locationType) { + return; + } + + var type = getNamedType(locationType); + + if (!isLeafType(type)) { + var typeStr = inspect(locationType); + context.reportError(new GraphQLError("Expected value of type \"".concat(typeStr, "\", found ").concat(print(node), "."), node)); + return; + } // Scalars and Enums determine if a literal value is valid via parseLiteral(), + // which may throw or return an invalid value to indicate failure. + + + try { + var parseResult = type.parseLiteral(node, undefined + /* variables */ + ); + + if (parseResult === undefined) { + var _typeStr = inspect(locationType); + + context.reportError(new GraphQLError("Expected value of type \"".concat(_typeStr, "\", found ").concat(print(node), "."), node)); + } + } catch (error) { + var _typeStr2 = inspect(locationType); + + if (error instanceof GraphQLError) { + context.reportError(error); + } else { + context.reportError(new GraphQLError("Expected value of type \"".concat(_typeStr2, "\", found ").concat(print(node), "; ") + error.message, node, undefined, undefined, undefined, error)); + } + } +} diff --git a/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.d.ts b/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.d.ts new file mode 100644 index 0000000..c82229c --- /dev/null +++ b/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.d.ts @@ -0,0 +1,12 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ +export function VariablesAreInputTypesRule( + context: ValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.js b/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.js new file mode 100644 index 0000000..885d309 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.VariablesAreInputTypesRule = VariablesAreInputTypesRule; + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _printer = require("../../language/printer.js"); + +var _definition = require("../../type/definition.js"); + +var _typeFromAST = require("../../utilities/typeFromAST.js"); + +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ +function VariablesAreInputTypesRule(context) { + return { + VariableDefinition: function VariableDefinition(node) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.type); + + if (type && !(0, _definition.isInputType)(type)) { + var variableName = node.variable.name.value; + var typeName = (0, _printer.print)(node.type); + context.reportError(new _GraphQLError.GraphQLError("Variable \"$".concat(variableName, "\" cannot be non-input type \"").concat(typeName, "\"."), node.type)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.js.flow b/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.js.flow new file mode 100644 index 0000000..2de0819 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.js.flow @@ -0,0 +1,40 @@ +// @flow strict +import { GraphQLError } from '../../error/GraphQLError'; + +import { print } from '../../language/printer'; +import type { ASTVisitor } from '../../language/visitor'; +import type { VariableDefinitionNode } from '../../language/ast'; + +import { isInputType } from '../../type/definition'; + +import { typeFromAST } from '../../utilities/typeFromAST'; + +import type { ValidationContext } from '../ValidationContext'; + +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ +export function VariablesAreInputTypesRule( + context: ValidationContext, +): ASTVisitor { + return { + VariableDefinition(node: VariableDefinitionNode): ?GraphQLError { + const type = typeFromAST(context.getSchema(), node.type); + + if (type && !isInputType(type)) { + const variableName = node.variable.name.value; + const typeName = print(node.type); + + context.reportError( + new GraphQLError( + `Variable "$${variableName}" cannot be non-input type "${typeName}".`, + node.type, + ), + ); + } + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs b/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs new file mode 100644 index 0000000..f6e5d11 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs @@ -0,0 +1,24 @@ +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { print } from "../../language/printer.mjs"; +import { isInputType } from "../../type/definition.mjs"; +import { typeFromAST } from "../../utilities/typeFromAST.mjs"; + +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ +export function VariablesAreInputTypesRule(context) { + return { + VariableDefinition: function VariableDefinition(node) { + var type = typeFromAST(context.getSchema(), node.type); + + if (type && !isInputType(type)) { + var variableName = node.variable.name.value; + var typeName = print(node.type); + context.reportError(new GraphQLError("Variable \"$".concat(variableName, "\" cannot be non-input type \"").concat(typeName, "\"."), node.type)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.d.ts b/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.d.ts new file mode 100644 index 0000000..6ee5737 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.d.ts @@ -0,0 +1,9 @@ +import { ASTVisitor } from '../../language/visitor'; +import { ValidationContext } from '../ValidationContext'; + +/** + * Variables passed to field arguments conform to type + */ +export function VariablesInAllowedPositionRule( + context: ValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.js b/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.js new file mode 100644 index 0000000..ad0ce8c --- /dev/null +++ b/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.js @@ -0,0 +1,87 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.VariablesInAllowedPositionRule = VariablesInAllowedPositionRule; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect.js")); + +var _GraphQLError = require("../../error/GraphQLError.js"); + +var _kinds = require("../../language/kinds.js"); + +var _definition = require("../../type/definition.js"); + +var _typeFromAST = require("../../utilities/typeFromAST.js"); + +var _typeComparators = require("../../utilities/typeComparators.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Variables passed to field arguments conform to type + */ +function VariablesInAllowedPositionRule(context) { + var varDefMap = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + varDefMap = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + + for (var _i2 = 0; _i2 < usages.length; _i2++) { + var _ref2 = usages[_i2]; + var node = _ref2.node; + var type = _ref2.type; + var defaultValue = _ref2.defaultValue; + var varName = node.name.value; + var varDef = varDefMap[varName]; + + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + var schema = context.getSchema(); + var varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type); + + if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) { + var varTypeStr = (0, _inspect.default)(varType); + var typeStr = (0, _inspect.default)(type); + context.reportError(new _GraphQLError.GraphQLError("Variable \"$".concat(varName, "\" of type \"").concat(varTypeStr, "\" used in position expecting type \"").concat(typeStr, "\"."), [varDef, node])); + } + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + } + }; +} +/** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ + + +function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) { + if ((0, _definition.isNonNullType)(locationType) && !(0, _definition.isNonNullType)(varType)) { + var hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== _kinds.Kind.NULL; + var hasLocationDefaultValue = locationDefaultValue !== undefined; + + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + + var nullableLocationType = locationType.ofType; + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, nullableLocationType); + } + + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType); +} diff --git a/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.js.flow b/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.js.flow new file mode 100644 index 0000000..722ee99 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.js.flow @@ -0,0 +1,98 @@ +// @flow strict +import inspect from '../../jsutils/inspect'; + +import { GraphQLError } from '../../error/GraphQLError'; + +import { Kind } from '../../language/kinds'; +import type { ValueNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; + +import type { GraphQLSchema } from '../../type/schema'; +import type { GraphQLType } from '../../type/definition'; +import { isNonNullType } from '../../type/definition'; + +import { typeFromAST } from '../../utilities/typeFromAST'; +import { isTypeSubTypeOf } from '../../utilities/typeComparators'; + +import type { ValidationContext } from '../ValidationContext'; + +/** + * Variables passed to field arguments conform to type + */ +export function VariablesInAllowedPositionRule( + context: ValidationContext, +): ASTVisitor { + let varDefMap = Object.create(null); + + return { + OperationDefinition: { + enter() { + varDefMap = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node, type, defaultValue } of usages) { + const varName = node.name.value; + const varDef = varDefMap[varName]; + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + const schema = context.getSchema(); + const varType = typeFromAST(schema, varDef.type); + if ( + varType && + !allowedVariableUsage( + schema, + varType, + varDef.defaultValue, + type, + defaultValue, + ) + ) { + const varTypeStr = inspect(varType); + const typeStr = inspect(type); + context.reportError( + new GraphQLError( + `Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`, + [varDef, node], + ), + ); + } + } + } + }, + }, + VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + }, + }; +} + +/** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ +function allowedVariableUsage( + schema: GraphQLSchema, + varType: GraphQLType, + varDefaultValue: ?ValueNode, + locationType: GraphQLType, + locationDefaultValue: ?mixed, +): boolean { + if (isNonNullType(locationType) && !isNonNullType(varType)) { + const hasNonNullVariableDefaultValue = + varDefaultValue != null && varDefaultValue.kind !== Kind.NULL; + const hasLocationDefaultValue = locationDefaultValue !== undefined; + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + const nullableLocationType = locationType.ofType; + return isTypeSubTypeOf(schema, varType, nullableLocationType); + } + return isTypeSubTypeOf(schema, varType, locationType); +} diff --git a/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs b/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs new file mode 100644 index 0000000..bdddb2f --- /dev/null +++ b/school/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs @@ -0,0 +1,72 @@ +import inspect from "../../jsutils/inspect.mjs"; +import { GraphQLError } from "../../error/GraphQLError.mjs"; +import { Kind } from "../../language/kinds.mjs"; +import { isNonNullType } from "../../type/definition.mjs"; +import { typeFromAST } from "../../utilities/typeFromAST.mjs"; +import { isTypeSubTypeOf } from "../../utilities/typeComparators.mjs"; + +/** + * Variables passed to field arguments conform to type + */ +export function VariablesInAllowedPositionRule(context) { + var varDefMap = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + varDefMap = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + + for (var _i2 = 0; _i2 < usages.length; _i2++) { + var _ref2 = usages[_i2]; + var node = _ref2.node; + var type = _ref2.type; + var defaultValue = _ref2.defaultValue; + var varName = node.name.value; + var varDef = varDefMap[varName]; + + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + var schema = context.getSchema(); + var varType = typeFromAST(schema, varDef.type); + + if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) { + var varTypeStr = inspect(varType); + var typeStr = inspect(type); + context.reportError(new GraphQLError("Variable \"$".concat(varName, "\" of type \"").concat(varTypeStr, "\" used in position expecting type \"").concat(typeStr, "\"."), [varDef, node])); + } + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + } + }; +} +/** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ + +function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) { + if (isNonNullType(locationType) && !isNonNullType(varType)) { + var hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== Kind.NULL; + var hasLocationDefaultValue = locationDefaultValue !== undefined; + + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + + var nullableLocationType = locationType.ofType; + return isTypeSubTypeOf(schema, varType, nullableLocationType); + } + + return isTypeSubTypeOf(schema, varType, locationType); +} diff --git a/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.d.ts b/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.d.ts new file mode 100644 index 0000000..d376cf8 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.d.ts @@ -0,0 +1,14 @@ +import { ASTVisitor } from '../../../language/visitor'; +import { ValidationContext } from '../../ValidationContext'; + +/** + * No deprecated + * + * A GraphQL document is only valid if all selected fields and all used enum values have not been + * deprecated. + * + * Note: This rule is optional and is not part of the Validation section of the GraphQL + * Specification. The main purpose of this rule is detection of deprecated usages and not + * necessarily to forbid their use when querying a service. + */ +export function NoDeprecatedCustomRule(context: ValidationContext): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.js b/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.js new file mode 100644 index 0000000..63ad4dc --- /dev/null +++ b/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NoDeprecatedCustomRule = NoDeprecatedCustomRule; + +var _invariant = _interopRequireDefault(require("../../../jsutils/invariant.js")); + +var _GraphQLError = require("../../../error/GraphQLError.js"); + +var _definition = require("../../../type/definition.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * No deprecated + * + * A GraphQL document is only valid if all selected fields and all used enum values have not been + * deprecated. + * + * Note: This rule is optional and is not part of the Validation section of the GraphQL + * Specification. The main purpose of this rule is detection of deprecated usages and not + * necessarily to forbid their use when querying a service. + */ +function NoDeprecatedCustomRule(context) { + return { + Field: function Field(node) { + var fieldDef = context.getFieldDef(); + var deprecationReason = fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.deprecationReason; + + if (fieldDef && deprecationReason != null) { + var parentType = context.getParentType(); + parentType != null || (0, _invariant.default)(0); + context.reportError(new _GraphQLError.GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated. ").concat(deprecationReason), node)); + } + }, + Argument: function Argument(node) { + var argDef = context.getArgument(); + var deprecationReason = argDef === null || argDef === void 0 ? void 0 : argDef.deprecationReason; + + if (argDef && deprecationReason != null) { + var directiveDef = context.getDirective(); + + if (directiveDef != null) { + context.reportError(new _GraphQLError.GraphQLError("Directive \"@".concat(directiveDef.name, "\" argument \"").concat(argDef.name, "\" is deprecated. ").concat(deprecationReason), node)); + } else { + var parentType = context.getParentType(); + var fieldDef = context.getFieldDef(); + parentType != null && fieldDef != null || (0, _invariant.default)(0); + context.reportError(new _GraphQLError.GraphQLError("Field \"".concat(parentType.name, ".").concat(fieldDef.name, "\" argument \"").concat(argDef.name, "\" is deprecated. ").concat(deprecationReason), node)); + } + } + }, + ObjectField: function ObjectField(node) { + var inputObjectDef = (0, _definition.getNamedType)(context.getParentInputType()); + + if ((0, _definition.isInputObjectType)(inputObjectDef)) { + var inputFieldDef = inputObjectDef.getFields()[node.name.value]; // flowlint-next-line unnecessary-optional-chain:off + + var deprecationReason = inputFieldDef === null || inputFieldDef === void 0 ? void 0 : inputFieldDef.deprecationReason; + + if (deprecationReason != null) { + context.reportError(new _GraphQLError.GraphQLError("The input field ".concat(inputObjectDef.name, ".").concat(inputFieldDef.name, " is deprecated. ").concat(deprecationReason), node)); + } + } + }, + EnumValue: function EnumValue(node) { + var enumValueDef = context.getEnumValue(); + var deprecationReason = enumValueDef === null || enumValueDef === void 0 ? void 0 : enumValueDef.deprecationReason; + + if (enumValueDef && deprecationReason != null) { + var enumTypeDef = (0, _definition.getNamedType)(context.getInputType()); + enumTypeDef != null || (0, _invariant.default)(0); + context.reportError(new _GraphQLError.GraphQLError("The enum value \"".concat(enumTypeDef.name, ".").concat(enumValueDef.name, "\" is deprecated. ").concat(deprecationReason), node)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.js.flow b/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.js.flow new file mode 100644 index 0000000..6b61065 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.js.flow @@ -0,0 +1,94 @@ +// @flow strict +import invariant from '../../../jsutils/invariant'; + +import { GraphQLError } from '../../../error/GraphQLError'; + +import type { ASTVisitor } from '../../../language/visitor'; + +import { getNamedType, isInputObjectType } from '../../../type/definition'; + +import type { ValidationContext } from '../../ValidationContext'; + +/** + * No deprecated + * + * A GraphQL document is only valid if all selected fields and all used enum values have not been + * deprecated. + * + * Note: This rule is optional and is not part of the Validation section of the GraphQL + * Specification. The main purpose of this rule is detection of deprecated usages and not + * necessarily to forbid their use when querying a service. + */ +export function NoDeprecatedCustomRule(context: ValidationContext): ASTVisitor { + return { + Field(node) { + const fieldDef = context.getFieldDef(); + const deprecationReason = fieldDef?.deprecationReason; + if (fieldDef && deprecationReason != null) { + const parentType = context.getParentType(); + invariant(parentType != null); + context.reportError( + new GraphQLError( + `The field ${parentType.name}.${fieldDef.name} is deprecated. ${deprecationReason}`, + node, + ), + ); + } + }, + Argument(node) { + const argDef = context.getArgument(); + const deprecationReason = argDef?.deprecationReason; + if (argDef && deprecationReason != null) { + const directiveDef = context.getDirective(); + if (directiveDef != null) { + context.reportError( + new GraphQLError( + `Directive "@${directiveDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, + node, + ), + ); + } else { + const parentType = context.getParentType(); + const fieldDef = context.getFieldDef(); + invariant(parentType != null && fieldDef != null); + context.reportError( + new GraphQLError( + `Field "${parentType.name}.${fieldDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, + node, + ), + ); + } + } + }, + ObjectField(node) { + const inputObjectDef = getNamedType(context.getParentInputType()); + if (isInputObjectType(inputObjectDef)) { + const inputFieldDef = inputObjectDef.getFields()[node.name.value]; + // flowlint-next-line unnecessary-optional-chain:off + const deprecationReason = inputFieldDef?.deprecationReason; + if (deprecationReason != null) { + context.reportError( + new GraphQLError( + `The input field ${inputObjectDef.name}.${inputFieldDef.name} is deprecated. ${deprecationReason}`, + node, + ), + ); + } + } + }, + EnumValue(node) { + const enumValueDef = context.getEnumValue(); + const deprecationReason = enumValueDef?.deprecationReason; + if (enumValueDef && deprecationReason != null) { + const enumTypeDef = getNamedType(context.getInputType()); + invariant(enumTypeDef != null); + context.reportError( + new GraphQLError( + `The enum value "${enumTypeDef.name}.${enumValueDef.name}" is deprecated. ${deprecationReason}`, + node, + ), + ); + } + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs b/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs new file mode 100644 index 0000000..f0e0b36 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs @@ -0,0 +1,68 @@ +import invariant from "../../../jsutils/invariant.mjs"; +import { GraphQLError } from "../../../error/GraphQLError.mjs"; +import { getNamedType, isInputObjectType } from "../../../type/definition.mjs"; + +/** + * No deprecated + * + * A GraphQL document is only valid if all selected fields and all used enum values have not been + * deprecated. + * + * Note: This rule is optional and is not part of the Validation section of the GraphQL + * Specification. The main purpose of this rule is detection of deprecated usages and not + * necessarily to forbid their use when querying a service. + */ +export function NoDeprecatedCustomRule(context) { + return { + Field: function Field(node) { + var fieldDef = context.getFieldDef(); + var deprecationReason = fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.deprecationReason; + + if (fieldDef && deprecationReason != null) { + var parentType = context.getParentType(); + parentType != null || invariant(0); + context.reportError(new GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated. ").concat(deprecationReason), node)); + } + }, + Argument: function Argument(node) { + var argDef = context.getArgument(); + var deprecationReason = argDef === null || argDef === void 0 ? void 0 : argDef.deprecationReason; + + if (argDef && deprecationReason != null) { + var directiveDef = context.getDirective(); + + if (directiveDef != null) { + context.reportError(new GraphQLError("Directive \"@".concat(directiveDef.name, "\" argument \"").concat(argDef.name, "\" is deprecated. ").concat(deprecationReason), node)); + } else { + var parentType = context.getParentType(); + var fieldDef = context.getFieldDef(); + parentType != null && fieldDef != null || invariant(0); + context.reportError(new GraphQLError("Field \"".concat(parentType.name, ".").concat(fieldDef.name, "\" argument \"").concat(argDef.name, "\" is deprecated. ").concat(deprecationReason), node)); + } + } + }, + ObjectField: function ObjectField(node) { + var inputObjectDef = getNamedType(context.getParentInputType()); + + if (isInputObjectType(inputObjectDef)) { + var inputFieldDef = inputObjectDef.getFields()[node.name.value]; // flowlint-next-line unnecessary-optional-chain:off + + var deprecationReason = inputFieldDef === null || inputFieldDef === void 0 ? void 0 : inputFieldDef.deprecationReason; + + if (deprecationReason != null) { + context.reportError(new GraphQLError("The input field ".concat(inputObjectDef.name, ".").concat(inputFieldDef.name, " is deprecated. ").concat(deprecationReason), node)); + } + } + }, + EnumValue: function EnumValue(node) { + var enumValueDef = context.getEnumValue(); + var deprecationReason = enumValueDef === null || enumValueDef === void 0 ? void 0 : enumValueDef.deprecationReason; + + if (enumValueDef && deprecationReason != null) { + var enumTypeDef = getNamedType(context.getInputType()); + enumTypeDef != null || invariant(0); + context.reportError(new GraphQLError("The enum value \"".concat(enumTypeDef.name, ".").concat(enumValueDef.name, "\" is deprecated. ").concat(deprecationReason), node)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.d.ts b/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.d.ts new file mode 100644 index 0000000..3677fa1 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.d.ts @@ -0,0 +1,16 @@ +import { ASTVisitor } from '../../../language/visitor'; +import { ValidationContext } from '../../ValidationContext'; + +/** + * Prohibit introspection queries + * + * A GraphQL document is only valid if all fields selected are not fields that + * return an introspection type. + * + * Note: This rule is optional and is not part of the Validation section of the + * GraphQL Specification. This rule effectively disables introspection, which + * does not reflect best practices and should only be done if absolutely necessary. + */ +export function NoSchemaIntrospectionCustomRule( + context: ValidationContext, +): ASTVisitor; diff --git a/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.js b/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.js new file mode 100644 index 0000000..6861bd4 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NoSchemaIntrospectionCustomRule = NoSchemaIntrospectionCustomRule; + +var _GraphQLError = require("../../../error/GraphQLError.js"); + +var _definition = require("../../../type/definition.js"); + +var _introspection = require("../../../type/introspection.js"); + +/** + * Prohibit introspection queries + * + * A GraphQL document is only valid if all fields selected are not fields that + * return an introspection type. + * + * Note: This rule is optional and is not part of the Validation section of the + * GraphQL Specification. This rule effectively disables introspection, which + * does not reflect best practices and should only be done if absolutely necessary. + */ +function NoSchemaIntrospectionCustomRule(context) { + return { + Field: function Field(node) { + var type = (0, _definition.getNamedType)(context.getType()); + + if (type && (0, _introspection.isIntrospectionType)(type)) { + context.reportError(new _GraphQLError.GraphQLError("GraphQL introspection has been disabled, but the requested query contained the field \"".concat(node.name.value, "\"."), node)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.js.flow b/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.js.flow new file mode 100644 index 0000000..333ba41 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.js.flow @@ -0,0 +1,38 @@ +// @flow strict +import { GraphQLError } from '../../../error/GraphQLError'; + +import type { FieldNode } from '../../../language/ast'; +import type { ASTVisitor } from '../../../language/visitor'; + +import { getNamedType } from '../../../type/definition'; +import { isIntrospectionType } from '../../../type/introspection'; + +import type { ValidationContext } from '../../ValidationContext'; + +/** + * Prohibit introspection queries + * + * A GraphQL document is only valid if all fields selected are not fields that + * return an introspection type. + * + * Note: This rule is optional and is not part of the Validation section of the + * GraphQL Specification. This rule effectively disables introspection, which + * does not reflect best practices and should only be done if absolutely necessary. + */ +export function NoSchemaIntrospectionCustomRule( + context: ValidationContext, +): ASTVisitor { + return { + Field(node: FieldNode) { + const type = getNamedType(context.getType()); + if (type && isIntrospectionType(type)) { + context.reportError( + new GraphQLError( + `GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`, + node, + ), + ); + } + }, + }; +} diff --git a/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs b/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs new file mode 100644 index 0000000..26f7d74 --- /dev/null +++ b/school/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs @@ -0,0 +1,25 @@ +import { GraphQLError } from "../../../error/GraphQLError.mjs"; +import { getNamedType } from "../../../type/definition.mjs"; +import { isIntrospectionType } from "../../../type/introspection.mjs"; + +/** + * Prohibit introspection queries + * + * A GraphQL document is only valid if all fields selected are not fields that + * return an introspection type. + * + * Note: This rule is optional and is not part of the Validation section of the + * GraphQL Specification. This rule effectively disables introspection, which + * does not reflect best practices and should only be done if absolutely necessary. + */ +export function NoSchemaIntrospectionCustomRule(context) { + return { + Field: function Field(node) { + var type = getNamedType(context.getType()); + + if (type && isIntrospectionType(type)) { + context.reportError(new GraphQLError("GraphQL introspection has been disabled, but the requested query contained the field \"".concat(node.name.value, "\"."), node)); + } + } + }; +} diff --git a/school/node_modules/graphql/validation/specifiedRules.d.ts b/school/node_modules/graphql/validation/specifiedRules.d.ts new file mode 100644 index 0000000..ffb5570 --- /dev/null +++ b/school/node_modules/graphql/validation/specifiedRules.d.ts @@ -0,0 +1,14 @@ +import { ValidationRule, SDLValidationRule } from './ValidationContext'; + +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ +export const specifiedRules: ReadonlyArray<ValidationRule>; + +/** + * @internal + */ +export const specifiedSDLRules: ReadonlyArray<SDLValidationRule>; diff --git a/school/node_modules/graphql/validation/specifiedRules.js b/school/node_modules/graphql/validation/specifiedRules.js new file mode 100644 index 0000000..a204849 --- /dev/null +++ b/school/node_modules/graphql/validation/specifiedRules.js @@ -0,0 +1,115 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.specifiedSDLRules = exports.specifiedRules = void 0; + +var _ExecutableDefinitionsRule = require("./rules/ExecutableDefinitionsRule.js"); + +var _UniqueOperationNamesRule = require("./rules/UniqueOperationNamesRule.js"); + +var _LoneAnonymousOperationRule = require("./rules/LoneAnonymousOperationRule.js"); + +var _SingleFieldSubscriptionsRule = require("./rules/SingleFieldSubscriptionsRule.js"); + +var _KnownTypeNamesRule = require("./rules/KnownTypeNamesRule.js"); + +var _FragmentsOnCompositeTypesRule = require("./rules/FragmentsOnCompositeTypesRule.js"); + +var _VariablesAreInputTypesRule = require("./rules/VariablesAreInputTypesRule.js"); + +var _ScalarLeafsRule = require("./rules/ScalarLeafsRule.js"); + +var _FieldsOnCorrectTypeRule = require("./rules/FieldsOnCorrectTypeRule.js"); + +var _UniqueFragmentNamesRule = require("./rules/UniqueFragmentNamesRule.js"); + +var _KnownFragmentNamesRule = require("./rules/KnownFragmentNamesRule.js"); + +var _NoUnusedFragmentsRule = require("./rules/NoUnusedFragmentsRule.js"); + +var _PossibleFragmentSpreadsRule = require("./rules/PossibleFragmentSpreadsRule.js"); + +var _NoFragmentCyclesRule = require("./rules/NoFragmentCyclesRule.js"); + +var _UniqueVariableNamesRule = require("./rules/UniqueVariableNamesRule.js"); + +var _NoUndefinedVariablesRule = require("./rules/NoUndefinedVariablesRule.js"); + +var _NoUnusedVariablesRule = require("./rules/NoUnusedVariablesRule.js"); + +var _KnownDirectivesRule = require("./rules/KnownDirectivesRule.js"); + +var _UniqueDirectivesPerLocationRule = require("./rules/UniqueDirectivesPerLocationRule.js"); + +var _KnownArgumentNamesRule = require("./rules/KnownArgumentNamesRule.js"); + +var _UniqueArgumentNamesRule = require("./rules/UniqueArgumentNamesRule.js"); + +var _ValuesOfCorrectTypeRule = require("./rules/ValuesOfCorrectTypeRule.js"); + +var _ProvidedRequiredArgumentsRule = require("./rules/ProvidedRequiredArgumentsRule.js"); + +var _VariablesInAllowedPositionRule = require("./rules/VariablesInAllowedPositionRule.js"); + +var _OverlappingFieldsCanBeMergedRule = require("./rules/OverlappingFieldsCanBeMergedRule.js"); + +var _UniqueInputFieldNamesRule = require("./rules/UniqueInputFieldNamesRule.js"); + +var _LoneSchemaDefinitionRule = require("./rules/LoneSchemaDefinitionRule.js"); + +var _UniqueOperationTypesRule = require("./rules/UniqueOperationTypesRule.js"); + +var _UniqueTypeNamesRule = require("./rules/UniqueTypeNamesRule.js"); + +var _UniqueEnumValueNamesRule = require("./rules/UniqueEnumValueNamesRule.js"); + +var _UniqueFieldDefinitionNamesRule = require("./rules/UniqueFieldDefinitionNamesRule.js"); + +var _UniqueDirectiveNamesRule = require("./rules/UniqueDirectiveNamesRule.js"); + +var _PossibleTypeExtensionsRule = require("./rules/PossibleTypeExtensionsRule.js"); + +// Spec Section: "Executable Definitions" +// Spec Section: "Operation Name Uniqueness" +// Spec Section: "Lone Anonymous Operation" +// Spec Section: "Subscriptions with Single Root Field" +// Spec Section: "Fragment Spread Type Existence" +// Spec Section: "Fragments on Composite Types" +// Spec Section: "Variables are Input Types" +// Spec Section: "Leaf Field Selections" +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +// Spec Section: "Fragment Name Uniqueness" +// Spec Section: "Fragment spread target defined" +// Spec Section: "Fragments must be used" +// Spec Section: "Fragment spread is possible" +// Spec Section: "Fragments must not form cycles" +// Spec Section: "Variable Uniqueness" +// Spec Section: "All Variable Used Defined" +// Spec Section: "All Variables Used" +// Spec Section: "Directives Are Defined" +// Spec Section: "Directives Are Unique Per Location" +// Spec Section: "Argument Names" +// Spec Section: "Argument Uniqueness" +// Spec Section: "Value Type Correctness" +// Spec Section: "Argument Optionality" +// Spec Section: "All Variable Usages Are Allowed" +// Spec Section: "Field Selection Merging" +// Spec Section: "Input Object Field Uniqueness" +// SDL-specific validation rules + +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ +var specifiedRules = Object.freeze([_ExecutableDefinitionsRule.ExecutableDefinitionsRule, _UniqueOperationNamesRule.UniqueOperationNamesRule, _LoneAnonymousOperationRule.LoneAnonymousOperationRule, _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule, _KnownTypeNamesRule.KnownTypeNamesRule, _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule, _VariablesAreInputTypesRule.VariablesAreInputTypesRule, _ScalarLeafsRule.ScalarLeafsRule, _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule, _UniqueFragmentNamesRule.UniqueFragmentNamesRule, _KnownFragmentNamesRule.KnownFragmentNamesRule, _NoUnusedFragmentsRule.NoUnusedFragmentsRule, _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule, _NoFragmentCyclesRule.NoFragmentCyclesRule, _UniqueVariableNamesRule.UniqueVariableNamesRule, _NoUndefinedVariablesRule.NoUndefinedVariablesRule, _NoUnusedVariablesRule.NoUnusedVariablesRule, _KnownDirectivesRule.KnownDirectivesRule, _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, _KnownArgumentNamesRule.KnownArgumentNamesRule, _UniqueArgumentNamesRule.UniqueArgumentNamesRule, _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule, _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule, _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule, _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule, _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule]); +/** + * @internal + */ + +exports.specifiedRules = specifiedRules; +var specifiedSDLRules = Object.freeze([_LoneSchemaDefinitionRule.LoneSchemaDefinitionRule, _UniqueOperationTypesRule.UniqueOperationTypesRule, _UniqueTypeNamesRule.UniqueTypeNamesRule, _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule, _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule, _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule, _KnownTypeNamesRule.KnownTypeNamesRule, _KnownDirectivesRule.KnownDirectivesRule, _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule, _KnownArgumentNamesRule.KnownArgumentNamesOnDirectivesRule, _UniqueArgumentNamesRule.UniqueArgumentNamesRule, _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsOnDirectivesRule]); +exports.specifiedSDLRules = specifiedSDLRules; diff --git a/school/node_modules/graphql/validation/specifiedRules.js.flow b/school/node_modules/graphql/validation/specifiedRules.js.flow new file mode 100644 index 0000000..179e9fb --- /dev/null +++ b/school/node_modules/graphql/validation/specifiedRules.js.flow @@ -0,0 +1,148 @@ +// @flow strict +// Spec Section: "Executable Definitions" +import { ExecutableDefinitionsRule } from './rules/ExecutableDefinitionsRule'; + +// Spec Section: "Operation Name Uniqueness" +import { UniqueOperationNamesRule } from './rules/UniqueOperationNamesRule'; + +// Spec Section: "Lone Anonymous Operation" +import { LoneAnonymousOperationRule } from './rules/LoneAnonymousOperationRule'; + +// Spec Section: "Subscriptions with Single Root Field" +import { SingleFieldSubscriptionsRule } from './rules/SingleFieldSubscriptionsRule'; + +// Spec Section: "Fragment Spread Type Existence" +import { KnownTypeNamesRule } from './rules/KnownTypeNamesRule'; + +// Spec Section: "Fragments on Composite Types" +import { FragmentsOnCompositeTypesRule } from './rules/FragmentsOnCompositeTypesRule'; + +// Spec Section: "Variables are Input Types" +import { VariablesAreInputTypesRule } from './rules/VariablesAreInputTypesRule'; + +// Spec Section: "Leaf Field Selections" +import { ScalarLeafsRule } from './rules/ScalarLeafsRule'; + +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +import { FieldsOnCorrectTypeRule } from './rules/FieldsOnCorrectTypeRule'; + +// Spec Section: "Fragment Name Uniqueness" +import { UniqueFragmentNamesRule } from './rules/UniqueFragmentNamesRule'; + +// Spec Section: "Fragment spread target defined" +import { KnownFragmentNamesRule } from './rules/KnownFragmentNamesRule'; + +// Spec Section: "Fragments must be used" +import { NoUnusedFragmentsRule } from './rules/NoUnusedFragmentsRule'; + +// Spec Section: "Fragment spread is possible" +import { PossibleFragmentSpreadsRule } from './rules/PossibleFragmentSpreadsRule'; + +// Spec Section: "Fragments must not form cycles" +import { NoFragmentCyclesRule } from './rules/NoFragmentCyclesRule'; + +// Spec Section: "Variable Uniqueness" +import { UniqueVariableNamesRule } from './rules/UniqueVariableNamesRule'; + +// Spec Section: "All Variable Used Defined" +import { NoUndefinedVariablesRule } from './rules/NoUndefinedVariablesRule'; + +// Spec Section: "All Variables Used" +import { NoUnusedVariablesRule } from './rules/NoUnusedVariablesRule'; + +// Spec Section: "Directives Are Defined" +import { KnownDirectivesRule } from './rules/KnownDirectivesRule'; + +// Spec Section: "Directives Are Unique Per Location" +import { UniqueDirectivesPerLocationRule } from './rules/UniqueDirectivesPerLocationRule'; + +// Spec Section: "Argument Names" +import { + KnownArgumentNamesRule, + KnownArgumentNamesOnDirectivesRule, +} from './rules/KnownArgumentNamesRule'; + +// Spec Section: "Argument Uniqueness" +import { UniqueArgumentNamesRule } from './rules/UniqueArgumentNamesRule'; + +// Spec Section: "Value Type Correctness" +import { ValuesOfCorrectTypeRule } from './rules/ValuesOfCorrectTypeRule'; + +// Spec Section: "Argument Optionality" +import { + ProvidedRequiredArgumentsRule, + ProvidedRequiredArgumentsOnDirectivesRule, +} from './rules/ProvidedRequiredArgumentsRule'; + +// Spec Section: "All Variable Usages Are Allowed" +import { VariablesInAllowedPositionRule } from './rules/VariablesInAllowedPositionRule'; + +// Spec Section: "Field Selection Merging" +import { OverlappingFieldsCanBeMergedRule } from './rules/OverlappingFieldsCanBeMergedRule'; + +// Spec Section: "Input Object Field Uniqueness" +import { UniqueInputFieldNamesRule } from './rules/UniqueInputFieldNamesRule'; + +// SDL-specific validation rules +import { LoneSchemaDefinitionRule } from './rules/LoneSchemaDefinitionRule'; +import { UniqueOperationTypesRule } from './rules/UniqueOperationTypesRule'; +import { UniqueTypeNamesRule } from './rules/UniqueTypeNamesRule'; +import { UniqueEnumValueNamesRule } from './rules/UniqueEnumValueNamesRule'; +import { UniqueFieldDefinitionNamesRule } from './rules/UniqueFieldDefinitionNamesRule'; +import { UniqueDirectiveNamesRule } from './rules/UniqueDirectiveNamesRule'; +import { PossibleTypeExtensionsRule } from './rules/PossibleTypeExtensionsRule'; + +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ +export const specifiedRules = Object.freeze([ + ExecutableDefinitionsRule, + UniqueOperationNamesRule, + LoneAnonymousOperationRule, + SingleFieldSubscriptionsRule, + KnownTypeNamesRule, + FragmentsOnCompositeTypesRule, + VariablesAreInputTypesRule, + ScalarLeafsRule, + FieldsOnCorrectTypeRule, + UniqueFragmentNamesRule, + KnownFragmentNamesRule, + NoUnusedFragmentsRule, + PossibleFragmentSpreadsRule, + NoFragmentCyclesRule, + UniqueVariableNamesRule, + NoUndefinedVariablesRule, + NoUnusedVariablesRule, + KnownDirectivesRule, + UniqueDirectivesPerLocationRule, + KnownArgumentNamesRule, + UniqueArgumentNamesRule, + ValuesOfCorrectTypeRule, + ProvidedRequiredArgumentsRule, + VariablesInAllowedPositionRule, + OverlappingFieldsCanBeMergedRule, + UniqueInputFieldNamesRule, +]); + +/** + * @internal + */ +export const specifiedSDLRules = Object.freeze([ + LoneSchemaDefinitionRule, + UniqueOperationTypesRule, + UniqueTypeNamesRule, + UniqueEnumValueNamesRule, + UniqueFieldDefinitionNamesRule, + UniqueDirectiveNamesRule, + KnownTypeNamesRule, + KnownDirectivesRule, + UniqueDirectivesPerLocationRule, + PossibleTypeExtensionsRule, + KnownArgumentNamesOnDirectivesRule, + UniqueArgumentNamesRule, + UniqueInputFieldNamesRule, + ProvidedRequiredArgumentsOnDirectivesRule, +]); diff --git a/school/node_modules/graphql/validation/specifiedRules.mjs b/school/node_modules/graphql/validation/specifiedRules.mjs new file mode 100644 index 0000000..97f4664 --- /dev/null +++ b/school/node_modules/graphql/validation/specifiedRules.mjs @@ -0,0 +1,73 @@ +// Spec Section: "Executable Definitions" +import { ExecutableDefinitionsRule } from "./rules/ExecutableDefinitionsRule.mjs"; // Spec Section: "Operation Name Uniqueness" + +import { UniqueOperationNamesRule } from "./rules/UniqueOperationNamesRule.mjs"; // Spec Section: "Lone Anonymous Operation" + +import { LoneAnonymousOperationRule } from "./rules/LoneAnonymousOperationRule.mjs"; // Spec Section: "Subscriptions with Single Root Field" + +import { SingleFieldSubscriptionsRule } from "./rules/SingleFieldSubscriptionsRule.mjs"; // Spec Section: "Fragment Spread Type Existence" + +import { KnownTypeNamesRule } from "./rules/KnownTypeNamesRule.mjs"; // Spec Section: "Fragments on Composite Types" + +import { FragmentsOnCompositeTypesRule } from "./rules/FragmentsOnCompositeTypesRule.mjs"; // Spec Section: "Variables are Input Types" + +import { VariablesAreInputTypesRule } from "./rules/VariablesAreInputTypesRule.mjs"; // Spec Section: "Leaf Field Selections" + +import { ScalarLeafsRule } from "./rules/ScalarLeafsRule.mjs"; // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + +import { FieldsOnCorrectTypeRule } from "./rules/FieldsOnCorrectTypeRule.mjs"; // Spec Section: "Fragment Name Uniqueness" + +import { UniqueFragmentNamesRule } from "./rules/UniqueFragmentNamesRule.mjs"; // Spec Section: "Fragment spread target defined" + +import { KnownFragmentNamesRule } from "./rules/KnownFragmentNamesRule.mjs"; // Spec Section: "Fragments must be used" + +import { NoUnusedFragmentsRule } from "./rules/NoUnusedFragmentsRule.mjs"; // Spec Section: "Fragment spread is possible" + +import { PossibleFragmentSpreadsRule } from "./rules/PossibleFragmentSpreadsRule.mjs"; // Spec Section: "Fragments must not form cycles" + +import { NoFragmentCyclesRule } from "./rules/NoFragmentCyclesRule.mjs"; // Spec Section: "Variable Uniqueness" + +import { UniqueVariableNamesRule } from "./rules/UniqueVariableNamesRule.mjs"; // Spec Section: "All Variable Used Defined" + +import { NoUndefinedVariablesRule } from "./rules/NoUndefinedVariablesRule.mjs"; // Spec Section: "All Variables Used" + +import { NoUnusedVariablesRule } from "./rules/NoUnusedVariablesRule.mjs"; // Spec Section: "Directives Are Defined" + +import { KnownDirectivesRule } from "./rules/KnownDirectivesRule.mjs"; // Spec Section: "Directives Are Unique Per Location" + +import { UniqueDirectivesPerLocationRule } from "./rules/UniqueDirectivesPerLocationRule.mjs"; // Spec Section: "Argument Names" + +import { KnownArgumentNamesRule, KnownArgumentNamesOnDirectivesRule } from "./rules/KnownArgumentNamesRule.mjs"; // Spec Section: "Argument Uniqueness" + +import { UniqueArgumentNamesRule } from "./rules/UniqueArgumentNamesRule.mjs"; // Spec Section: "Value Type Correctness" + +import { ValuesOfCorrectTypeRule } from "./rules/ValuesOfCorrectTypeRule.mjs"; // Spec Section: "Argument Optionality" + +import { ProvidedRequiredArgumentsRule, ProvidedRequiredArgumentsOnDirectivesRule } from "./rules/ProvidedRequiredArgumentsRule.mjs"; // Spec Section: "All Variable Usages Are Allowed" + +import { VariablesInAllowedPositionRule } from "./rules/VariablesInAllowedPositionRule.mjs"; // Spec Section: "Field Selection Merging" + +import { OverlappingFieldsCanBeMergedRule } from "./rules/OverlappingFieldsCanBeMergedRule.mjs"; // Spec Section: "Input Object Field Uniqueness" + +import { UniqueInputFieldNamesRule } from "./rules/UniqueInputFieldNamesRule.mjs"; // SDL-specific validation rules + +import { LoneSchemaDefinitionRule } from "./rules/LoneSchemaDefinitionRule.mjs"; +import { UniqueOperationTypesRule } from "./rules/UniqueOperationTypesRule.mjs"; +import { UniqueTypeNamesRule } from "./rules/UniqueTypeNamesRule.mjs"; +import { UniqueEnumValueNamesRule } from "./rules/UniqueEnumValueNamesRule.mjs"; +import { UniqueFieldDefinitionNamesRule } from "./rules/UniqueFieldDefinitionNamesRule.mjs"; +import { UniqueDirectiveNamesRule } from "./rules/UniqueDirectiveNamesRule.mjs"; +import { PossibleTypeExtensionsRule } from "./rules/PossibleTypeExtensionsRule.mjs"; +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ + +export var specifiedRules = Object.freeze([ExecutableDefinitionsRule, UniqueOperationNamesRule, LoneAnonymousOperationRule, SingleFieldSubscriptionsRule, KnownTypeNamesRule, FragmentsOnCompositeTypesRule, VariablesAreInputTypesRule, ScalarLeafsRule, FieldsOnCorrectTypeRule, UniqueFragmentNamesRule, KnownFragmentNamesRule, NoUnusedFragmentsRule, PossibleFragmentSpreadsRule, NoFragmentCyclesRule, UniqueVariableNamesRule, NoUndefinedVariablesRule, NoUnusedVariablesRule, KnownDirectivesRule, UniqueDirectivesPerLocationRule, KnownArgumentNamesRule, UniqueArgumentNamesRule, ValuesOfCorrectTypeRule, ProvidedRequiredArgumentsRule, VariablesInAllowedPositionRule, OverlappingFieldsCanBeMergedRule, UniqueInputFieldNamesRule]); +/** + * @internal + */ + +export var specifiedSDLRules = Object.freeze([LoneSchemaDefinitionRule, UniqueOperationTypesRule, UniqueTypeNamesRule, UniqueEnumValueNamesRule, UniqueFieldDefinitionNamesRule, UniqueDirectiveNamesRule, KnownTypeNamesRule, KnownDirectivesRule, UniqueDirectivesPerLocationRule, PossibleTypeExtensionsRule, KnownArgumentNamesOnDirectivesRule, UniqueArgumentNamesRule, UniqueInputFieldNamesRule, ProvidedRequiredArgumentsOnDirectivesRule]); diff --git a/school/node_modules/graphql/validation/validate.d.ts b/school/node_modules/graphql/validation/validate.d.ts new file mode 100644 index 0000000..5e93a8c --- /dev/null +++ b/school/node_modules/graphql/validation/validate.d.ts @@ -0,0 +1,63 @@ +import { Maybe } from '../jsutils/Maybe'; + +import { GraphQLError } from '../error/GraphQLError'; + +import { DocumentNode } from '../language/ast'; + +import { GraphQLSchema } from '../type/schema'; + +import { TypeInfo } from '../utilities/TypeInfo'; + +import { ValidationRule, SDLValidationRule } from './ValidationContext'; + +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ +export function validate( + schema: GraphQLSchema, + documentAST: DocumentNode, + rules?: ReadonlyArray<ValidationRule>, + typeInfo?: TypeInfo, + options?: { maxErrors?: number }, +): ReadonlyArray<GraphQLError>; + +/** + * @internal + */ +export function validateSDL( + documentAST: DocumentNode, + schemaToExtend?: Maybe<GraphQLSchema>, + rules?: ReadonlyArray<SDLValidationRule>, +): Array<GraphQLError>; + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDL(documentAST: DocumentNode): void; + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDLExtension( + documentAST: DocumentNode, + schema: GraphQLSchema, +): void; diff --git a/school/node_modules/graphql/validation/validate.js b/school/node_modules/graphql/validation/validate.js new file mode 100644 index 0000000..04b823f --- /dev/null +++ b/school/node_modules/graphql/validation/validate.js @@ -0,0 +1,128 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validate = validate; +exports.validateSDL = validateSDL; +exports.assertValidSDL = assertValidSDL; +exports.assertValidSDLExtension = assertValidSDLExtension; + +var _devAssert = _interopRequireDefault(require("../jsutils/devAssert.js")); + +var _GraphQLError = require("../error/GraphQLError.js"); + +var _visitor = require("../language/visitor.js"); + +var _validate = require("../type/validate.js"); + +var _TypeInfo = require("../utilities/TypeInfo.js"); + +var _specifiedRules = require("./specifiedRules.js"); + +var _ValidationContext = require("./ValidationContext.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ +function validate(schema, documentAST) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _specifiedRules.specifiedRules; + var typeInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new _TypeInfo.TypeInfo(schema); + var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : { + maxErrors: undefined + }; + documentAST || (0, _devAssert.default)(0, 'Must provide document.'); // If the schema used for validation is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); + var abortObj = Object.freeze({}); + var errors = []; + var context = new _ValidationContext.ValidationContext(schema, documentAST, typeInfo, function (error) { + if (options.maxErrors != null && errors.length >= options.maxErrors) { + errors.push(new _GraphQLError.GraphQLError('Too many validation errors, error limit reached. Validation aborted.')); + throw abortObj; + } + + errors.push(error); + }); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + + var visitor = (0, _visitor.visitInParallel)(rules.map(function (rule) { + return rule(context); + })); // Visit the whole document with each instance of all provided rules. + + try { + (0, _visitor.visit)(documentAST, (0, _TypeInfo.visitWithTypeInfo)(typeInfo, visitor)); + } catch (e) { + if (e !== abortObj) { + throw e; + } + } + + return errors; +} +/** + * @internal + */ + + +function validateSDL(documentAST, schemaToExtend) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _specifiedRules.specifiedSDLRules; + var errors = []; + var context = new _ValidationContext.SDLValidationContext(documentAST, schemaToExtend, function (error) { + errors.push(error); + }); + var visitors = rules.map(function (rule) { + return rule(context); + }); + (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors)); + return errors; +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + + +function assertValidSDL(documentAST) { + var errors = validateSDL(documentAST); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + + +function assertValidSDLExtension(documentAST, schema) { + var errors = validateSDL(documentAST, schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} diff --git a/school/node_modules/graphql/validation/validate.js.flow b/school/node_modules/graphql/validation/validate.js.flow new file mode 100644 index 0000000..26dc0a5 --- /dev/null +++ b/school/node_modules/graphql/validation/validate.js.flow @@ -0,0 +1,128 @@ +// @flow strict +import devAssert from '../jsutils/devAssert'; + +import { GraphQLError } from '../error/GraphQLError'; + +import type { DocumentNode } from '../language/ast'; +import { visit, visitInParallel } from '../language/visitor'; + +import type { GraphQLSchema } from '../type/schema'; +import { assertValidSchema } from '../type/validate'; + +import { TypeInfo, visitWithTypeInfo } from '../utilities/TypeInfo'; + +import type { SDLValidationRule, ValidationRule } from './ValidationContext'; +import { specifiedRules, specifiedSDLRules } from './specifiedRules'; +import { SDLValidationContext, ValidationContext } from './ValidationContext'; + +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ +export function validate( + schema: GraphQLSchema, + documentAST: DocumentNode, + rules: $ReadOnlyArray<ValidationRule> = specifiedRules, + typeInfo: TypeInfo = new TypeInfo(schema), + options: {| maxErrors?: number |} = { maxErrors: undefined }, +): $ReadOnlyArray<GraphQLError> { + devAssert(documentAST, 'Must provide document.'); + // If the schema used for validation is invalid, throw an error. + assertValidSchema(schema); + + const abortObj = Object.freeze({}); + const errors = []; + const context = new ValidationContext( + schema, + documentAST, + typeInfo, + (error) => { + if (options.maxErrors != null && errors.length >= options.maxErrors) { + errors.push( + new GraphQLError( + 'Too many validation errors, error limit reached. Validation aborted.', + ), + ); + throw abortObj; + } + errors.push(error); + }, + ); + + // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + const visitor = visitInParallel(rules.map((rule) => rule(context))); + + // Visit the whole document with each instance of all provided rules. + try { + visit(documentAST, visitWithTypeInfo(typeInfo, visitor)); + } catch (e) { + if (e !== abortObj) { + throw e; + } + } + return errors; +} + +/** + * @internal + */ +export function validateSDL( + documentAST: DocumentNode, + schemaToExtend?: ?GraphQLSchema, + rules: $ReadOnlyArray<SDLValidationRule> = specifiedSDLRules, +): $ReadOnlyArray<GraphQLError> { + const errors = []; + const context = new SDLValidationContext( + documentAST, + schemaToExtend, + (error) => { + errors.push(error); + }, + ); + + const visitors = rules.map((rule) => rule(context)); + visit(documentAST, visitInParallel(visitors)); + return errors; +} + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDL(documentAST: DocumentNode): void { + const errors = validateSDL(documentAST); + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); + } +} + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDLExtension( + documentAST: DocumentNode, + schema: GraphQLSchema, +): void { + const errors = validateSDL(documentAST, schema); + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); + } +} diff --git a/school/node_modules/graphql/validation/validate.mjs b/school/node_modules/graphql/validation/validate.mjs new file mode 100644 index 0000000..2ae71e7 --- /dev/null +++ b/school/node_modules/graphql/validation/validate.mjs @@ -0,0 +1,107 @@ +import devAssert from "../jsutils/devAssert.mjs"; +import { GraphQLError } from "../error/GraphQLError.mjs"; +import { visit, visitInParallel } from "../language/visitor.mjs"; +import { assertValidSchema } from "../type/validate.mjs"; +import { TypeInfo, visitWithTypeInfo } from "../utilities/TypeInfo.mjs"; +import { specifiedRules, specifiedSDLRules } from "./specifiedRules.mjs"; +import { SDLValidationContext, ValidationContext } from "./ValidationContext.mjs"; +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ + +export function validate(schema, documentAST) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : specifiedRules; + var typeInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new TypeInfo(schema); + var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : { + maxErrors: undefined + }; + documentAST || devAssert(0, 'Must provide document.'); // If the schema used for validation is invalid, throw an error. + + assertValidSchema(schema); + var abortObj = Object.freeze({}); + var errors = []; + var context = new ValidationContext(schema, documentAST, typeInfo, function (error) { + if (options.maxErrors != null && errors.length >= options.maxErrors) { + errors.push(new GraphQLError('Too many validation errors, error limit reached. Validation aborted.')); + throw abortObj; + } + + errors.push(error); + }); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + + var visitor = visitInParallel(rules.map(function (rule) { + return rule(context); + })); // Visit the whole document with each instance of all provided rules. + + try { + visit(documentAST, visitWithTypeInfo(typeInfo, visitor)); + } catch (e) { + if (e !== abortObj) { + throw e; + } + } + + return errors; +} +/** + * @internal + */ + +export function validateSDL(documentAST, schemaToExtend) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : specifiedSDLRules; + var errors = []; + var context = new SDLValidationContext(documentAST, schemaToExtend, function (error) { + errors.push(error); + }); + var visitors = rules.map(function (rule) { + return rule(context); + }); + visit(documentAST, visitInParallel(visitors)); + return errors; +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +export function assertValidSDL(documentAST) { + var errors = validateSDL(documentAST); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +export function assertValidSDLExtension(documentAST, schema) { + var errors = validateSDL(documentAST, schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} diff --git a/school/node_modules/graphql/version.d.ts b/school/node_modules/graphql/version.d.ts new file mode 100644 index 0000000..765329b --- /dev/null +++ b/school/node_modules/graphql/version.d.ts @@ -0,0 +1,14 @@ +/** + * A string containing the version of the GraphQL.js library + */ +export const version: string; + +/** + * An object containing the components of the GraphQL.js version string + */ +export const versionInfo: { + major: number; + minor: number; + patch: number; + preReleaseTag: number | null; +}; diff --git a/school/node_modules/graphql/version.js b/school/node_modules/graphql/version.js new file mode 100644 index 0000000..39b33a3 --- /dev/null +++ b/school/node_modules/graphql/version.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.versionInfo = exports.version = void 0; + +/** + * Note: This file is autogenerated using "resources/gen-version.js" script and + * automatically updated by "npm version" command. + */ + +/** + * A string containing the version of the GraphQL.js library + */ +var version = '15.8.0'; +/** + * An object containing the components of the GraphQL.js version string + */ + +exports.version = version; +var versionInfo = Object.freeze({ + major: 15, + minor: 8, + patch: 0, + preReleaseTag: null +}); +exports.versionInfo = versionInfo; diff --git a/school/node_modules/graphql/version.js.flow b/school/node_modules/graphql/version.js.flow new file mode 100644 index 0000000..5747017 --- /dev/null +++ b/school/node_modules/graphql/version.js.flow @@ -0,0 +1,20 @@ +// @flow strict +/** + * Note: This file is autogenerated using "resources/gen-version.js" script and + * automatically updated by "npm version" command. + */ + +/** + * A string containing the version of the GraphQL.js library + */ +export const version = '15.8.0'; + +/** + * An object containing the components of the GraphQL.js version string + */ +export const versionInfo = Object.freeze({ + major: 15, + minor: 8, + patch: 0, + preReleaseTag: null, +}); diff --git a/school/node_modules/graphql/version.mjs b/school/node_modules/graphql/version.mjs new file mode 100644 index 0000000..9c9bb82 --- /dev/null +++ b/school/node_modules/graphql/version.mjs @@ -0,0 +1,19 @@ +/** + * Note: This file is autogenerated using "resources/gen-version.js" script and + * automatically updated by "npm version" command. + */ + +/** + * A string containing the version of the GraphQL.js library + */ +export var version = '15.8.0'; +/** + * An object containing the components of the GraphQL.js version string + */ + +export var versionInfo = Object.freeze({ + major: 15, + minor: 8, + patch: 0, + preReleaseTag: null +}); |