Initial Sample.

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

View File

@@ -0,0 +1,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.

View File

@@ -0,0 +1 @@
"Package 'graphql' support only TS versions that are >=4.1.0".

View File

@@ -0,0 +1,158 @@
# 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=main)](https://github.com/graphql/graphql-js/actions?query=branch%3Amain)
[![Coverage Status](https://codecov.io/gh/graphql/graphql-js/branch/main/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/main/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 source = '{ hello }';
graphql({ schema, source }).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 source = '{ BoyHowdy }';
graphql({ schema, source }).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 `main` 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).
This repository is managed by EasyCLA. Project participants must sign the free ([GraphQL Specification Membership agreement](https://preview-spec-membership.graphql.org) before making a contribution. You only need to do this one time, and it can be signed by [individual contributors](http://individual-spec-membership.graphql.org/) or their [employers](http://corporate-spec-membership.graphql.org/).
To initiate the signature process please open a PR against this repo. The EasyCLA bot will block the merge if we still need a membership agreement from you.
You can find [detailed information here](https://github.com/graphql/graphql-wg/tree/main/membership). If you have issues, please email [operations@graphql.org](mailto:operations@graphql.org).
If your company benefits from GraphQL and you would like to provide essential financial support for the systems and people that power our community, please also consider membership in the [GraphQL Foundation](https://foundation.graphql.org/join).
### Changelog
Changes are tracked as [GitHub releases](https://github.com/graphql/graphql-js/releases).
### License
GraphQL.js is [MIT-licensed](./LICENSE).

View File

@@ -0,0 +1,142 @@
import type { Maybe } from '../jsutils/Maybe';
import type { ASTNode } from '../language/ast';
import type { SourceLocation } from '../language/location';
import type { Source } from '../language/source';
/**
* 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]: unknown;
}
export interface GraphQLErrorOptions {
nodes?: ReadonlyArray<ASTNode> | ASTNode | null;
source?: Maybe<Source>;
positions?: Maybe<ReadonlyArray<number>>;
path?: Maybe<ReadonlyArray<string | number>>;
originalError?: Maybe<
Error & {
readonly extensions?: unknown;
}
>;
extensions?: Maybe<GraphQLErrorExtensions>;
}
/**
* 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 declare 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().
*/
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 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.
*/
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;
/**
* Extension fields to add to the formatted error.
*/
readonly extensions: GraphQLErrorExtensions;
constructor(message: string, options?: GraphQLErrorOptions);
/**
* @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.
*/
constructor(
message: string,
nodes?: ReadonlyArray<ASTNode> | ASTNode | null,
source?: Maybe<Source>,
positions?: Maybe<ReadonlyArray<number>>,
path?: Maybe<ReadonlyArray<string | number>>,
originalError?: Maybe<
Error & {
readonly extensions?: unknown;
}
>,
extensions?: Maybe<GraphQLErrorExtensions>,
);
get [Symbol.toStringTag](): string;
toString(): string;
toJSON(): GraphQLFormattedError;
}
/**
* See: https://spec.graphql.org/draft/#sec-Errors
*/
export interface 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.
*/
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?: {
[key: string]: unknown;
};
}
/**
* Prints a GraphQLError to a string, representing useful location information
* about the error's position in the source.
*
* @deprecated Please use `error.toString` instead. Will be removed in v17
*/
export declare function printError(error: GraphQLError): string;
/**
* Given a GraphQLError, format it according to the rules described by the
* Response Format, Errors section of the GraphQL Specification.
*
* @deprecated Please use `error.toJSON` instead. Will be removed in v17
*/
export declare function formatError(error: GraphQLError): GraphQLFormattedError;

View File

@@ -0,0 +1,267 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.GraphQLError = void 0;
exports.formatError = formatError;
exports.printError = printError;
var _isObjectLike = require('../jsutils/isObjectLike.js');
var _location = require('../language/location.js');
var _printLocation = require('../language/printLocation.js');
function toNormalizedOptions(args) {
const firstArg = args[0];
if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) {
return {
nodes: firstArg,
source: args[1],
positions: args[2],
path: args[3],
originalError: args[4],
extensions: args[5],
};
}
return firstArg;
}
/**
* 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.
*/
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().
*/
/**
* 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.
*/
/**
* @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.
*/
constructor(message, ...rawArgs) {
var _this$nodes, _nodeLocations$, _ref;
const { nodes, source, positions, path, originalError, extensions } =
toNormalizedOptions(rawArgs);
super(message);
this.name = 'GraphQLError';
this.path = path !== null && path !== void 0 ? path : undefined;
this.originalError =
originalError !== null && originalError !== void 0
? originalError
: undefined; // Compute list of blame nodes.
this.nodes = undefinedIfEmpty(
Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined,
);
const nodeLocations = undefinedIfEmpty(
(_this$nodes = this.nodes) === null || _this$nodes === void 0
? void 0
: _this$nodes.map((node) => node.loc).filter((loc) => loc != null),
); // Compute locations in the source for the given nodes/positions.
this.source =
source !== null && source !== void 0
? source
: nodeLocations === null || nodeLocations === void 0
? void 0
: (_nodeLocations$ = nodeLocations[0]) === null ||
_nodeLocations$ === void 0
? void 0
: _nodeLocations$.source;
this.positions =
positions !== null && positions !== void 0
? positions
: nodeLocations === null || nodeLocations === void 0
? void 0
: nodeLocations.map((loc) => loc.start);
this.locations =
positions && source
? positions.map((pos) => (0, _location.getLocation)(source, pos))
: nodeLocations === null || nodeLocations === void 0
? void 0
: nodeLocations.map((loc) =>
(0, _location.getLocation)(loc.source, loc.start),
);
const originalExtensions = (0, _isObjectLike.isObjectLike)(
originalError === null || originalError === void 0
? void 0
: originalError.extensions,
)
? originalError === null || originalError === void 0
? void 0
: originalError.extensions
: undefined;
this.extensions =
(_ref =
extensions !== null && extensions !== void 0
? extensions
: originalExtensions) !== null && _ref !== void 0
? _ref
: Object.create(null); // Only properties prescribed by the spec should be enumerable.
// Keep the rest as non-enumerable.
Object.defineProperties(this, {
message: {
writable: true,
enumerable: true,
},
name: {
enumerable: false,
},
nodes: {
enumerable: false,
},
source: {
enumerable: false,
},
positions: {
enumerable: false,
},
originalError: {
enumerable: false,
},
}); // Include (non-enumerable) stack trace.
/* c8 ignore start */
// FIXME: https://github.com/graphql/graphql-js/issues/2317
if (
originalError !== null &&
originalError !== void 0 &&
originalError.stack
) {
Object.defineProperty(this, 'stack', {
value: originalError.stack,
writable: true,
configurable: true,
});
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, GraphQLError);
} else {
Object.defineProperty(this, 'stack', {
value: Error().stack,
writable: true,
configurable: true,
});
}
/* c8 ignore stop */
}
get [Symbol.toStringTag]() {
return 'GraphQLError';
}
toString() {
let output = this.message;
if (this.nodes) {
for (const node of this.nodes) {
if (node.loc) {
output += '\n\n' + (0, _printLocation.printLocation)(node.loc);
}
}
} else if (this.source && this.locations) {
for (const location of this.locations) {
output +=
'\n\n' +
(0, _printLocation.printSourceLocation)(this.source, location);
}
}
return output;
}
toJSON() {
const formattedError = {
message: this.message,
};
if (this.locations != null) {
formattedError.locations = this.locations;
}
if (this.path != null) {
formattedError.path = this.path;
}
if (this.extensions != null && Object.keys(this.extensions).length > 0) {
formattedError.extensions = this.extensions;
}
return formattedError;
}
}
exports.GraphQLError = GraphQLError;
function undefinedIfEmpty(array) {
return array === undefined || array.length === 0 ? undefined : array;
}
/**
* See: https://spec.graphql.org/draft/#sec-Errors
*/
/**
* Prints a GraphQLError to a string, representing useful location information
* about the error's position in the source.
*
* @deprecated Please use `error.toString` instead. Will be removed in v17
*/
function printError(error) {
return error.toString();
}
/**
* Given a GraphQLError, format it according to the rules described by the
* Response Format, Errors section of the GraphQL Specification.
*
* @deprecated Please use `error.toJSON` instead. Will be removed in v17
*/
function formatError(error) {
return error.toJSON();
}

View File

@@ -0,0 +1,253 @@
import { isObjectLike } from '../jsutils/isObjectLike.mjs';
import { getLocation } from '../language/location.mjs';
import {
printLocation,
printSourceLocation,
} from '../language/printLocation.mjs';
function toNormalizedOptions(args) {
const firstArg = args[0];
if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) {
return {
nodes: firstArg,
source: args[1],
positions: args[2],
path: args[3],
originalError: args[4],
extensions: args[5],
};
}
return firstArg;
}
/**
* 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().
*/
/**
* 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.
*/
/**
* @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.
*/
constructor(message, ...rawArgs) {
var _this$nodes, _nodeLocations$, _ref;
const { nodes, source, positions, path, originalError, extensions } =
toNormalizedOptions(rawArgs);
super(message);
this.name = 'GraphQLError';
this.path = path !== null && path !== void 0 ? path : undefined;
this.originalError =
originalError !== null && originalError !== void 0
? originalError
: undefined; // Compute list of blame nodes.
this.nodes = undefinedIfEmpty(
Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined,
);
const nodeLocations = undefinedIfEmpty(
(_this$nodes = this.nodes) === null || _this$nodes === void 0
? void 0
: _this$nodes.map((node) => node.loc).filter((loc) => loc != null),
); // Compute locations in the source for the given nodes/positions.
this.source =
source !== null && source !== void 0
? source
: nodeLocations === null || nodeLocations === void 0
? void 0
: (_nodeLocations$ = nodeLocations[0]) === null ||
_nodeLocations$ === void 0
? void 0
: _nodeLocations$.source;
this.positions =
positions !== null && positions !== void 0
? positions
: nodeLocations === null || nodeLocations === void 0
? void 0
: nodeLocations.map((loc) => loc.start);
this.locations =
positions && source
? positions.map((pos) => getLocation(source, pos))
: nodeLocations === null || nodeLocations === void 0
? void 0
: nodeLocations.map((loc) => getLocation(loc.source, loc.start));
const originalExtensions = isObjectLike(
originalError === null || originalError === void 0
? void 0
: originalError.extensions,
)
? originalError === null || originalError === void 0
? void 0
: originalError.extensions
: undefined;
this.extensions =
(_ref =
extensions !== null && extensions !== void 0
? extensions
: originalExtensions) !== null && _ref !== void 0
? _ref
: Object.create(null); // Only properties prescribed by the spec should be enumerable.
// Keep the rest as non-enumerable.
Object.defineProperties(this, {
message: {
writable: true,
enumerable: true,
},
name: {
enumerable: false,
},
nodes: {
enumerable: false,
},
source: {
enumerable: false,
},
positions: {
enumerable: false,
},
originalError: {
enumerable: false,
},
}); // Include (non-enumerable) stack trace.
/* c8 ignore start */
// FIXME: https://github.com/graphql/graphql-js/issues/2317
if (
originalError !== null &&
originalError !== void 0 &&
originalError.stack
) {
Object.defineProperty(this, 'stack', {
value: originalError.stack,
writable: true,
configurable: true,
});
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, GraphQLError);
} else {
Object.defineProperty(this, 'stack', {
value: Error().stack,
writable: true,
configurable: true,
});
}
/* c8 ignore stop */
}
get [Symbol.toStringTag]() {
return 'GraphQLError';
}
toString() {
let output = this.message;
if (this.nodes) {
for (const node of this.nodes) {
if (node.loc) {
output += '\n\n' + printLocation(node.loc);
}
}
} else if (this.source && this.locations) {
for (const location of this.locations) {
output += '\n\n' + printSourceLocation(this.source, location);
}
}
return output;
}
toJSON() {
const formattedError = {
message: this.message,
};
if (this.locations != null) {
formattedError.locations = this.locations;
}
if (this.path != null) {
formattedError.path = this.path;
}
if (this.extensions != null && Object.keys(this.extensions).length > 0) {
formattedError.extensions = this.extensions;
}
return formattedError;
}
}
function undefinedIfEmpty(array) {
return array === undefined || array.length === 0 ? undefined : array;
}
/**
* See: https://spec.graphql.org/draft/#sec-Errors
*/
/**
* Prints a GraphQLError to a string, representing useful location information
* about the error's position in the source.
*
* @deprecated Please use `error.toString` instead. Will be removed in v17
*/
export function printError(error) {
return error.toString();
}
/**
* Given a GraphQLError, format it according to the rules described by the
* Response Format, Errors section of the GraphQL Specification.
*
* @deprecated Please use `error.toJSON` instead. Will be removed in v17
*/
export function formatError(error) {
return error.toJSON();
}

View File

@@ -0,0 +1,8 @@
export { GraphQLError, printError, formatError } from './GraphQLError';
export type {
GraphQLErrorOptions,
GraphQLFormattedError,
GraphQLErrorExtensions,
} from './GraphQLError';
export { syntaxError } from './syntaxError';
export { locatedError } from './locatedError';

View File

@@ -0,0 +1,41 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
Object.defineProperty(exports, 'GraphQLError', {
enumerable: true,
get: function () {
return _GraphQLError.GraphQLError;
},
});
Object.defineProperty(exports, 'formatError', {
enumerable: true,
get: function () {
return _GraphQLError.formatError;
},
});
Object.defineProperty(exports, 'locatedError', {
enumerable: true,
get: function () {
return _locatedError.locatedError;
},
});
Object.defineProperty(exports, 'printError', {
enumerable: true,
get: function () {
return _GraphQLError.printError;
},
});
Object.defineProperty(exports, 'syntaxError', {
enumerable: true,
get: function () {
return _syntaxError.syntaxError;
},
});
var _GraphQLError = require('./GraphQLError.js');
var _syntaxError = require('./syntaxError.js');
var _locatedError = require('./locatedError.js');

View File

@@ -0,0 +1,3 @@
export { GraphQLError, printError, formatError } from './GraphQLError.mjs';
export { syntaxError } from './syntaxError.mjs';
export { locatedError } from './locatedError.mjs';

View File

@@ -0,0 +1,13 @@
import type { Maybe } from '../jsutils/Maybe';
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 declare function locatedError(
rawOriginalError: unknown,
nodes: ASTNode | ReadonlyArray<ASTNode> | undefined | null,
path?: Maybe<ReadonlyArray<string | number>>,
): GraphQLError;

View File

@@ -0,0 +1,40 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.locatedError = locatedError;
var _toError = require('../jsutils/toError.js');
var _GraphQLError = require('./GraphQLError.js');
/**
* 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;
const originalError = (0, _toError.toError)(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts.
if (isLocatedGraphQLError(originalError)) {
return originalError;
}
return new _GraphQLError.GraphQLError(originalError.message, {
nodes:
(_nodes = originalError.nodes) !== null && _nodes !== void 0
? _nodes
: nodes,
source: originalError.source,
positions: originalError.positions,
path,
originalError,
});
}
function isLocatedGraphQLError(error) {
return Array.isArray(error.path);
}

View File

@@ -0,0 +1,32 @@
import { toError } from '../jsutils/toError.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;
const originalError = toError(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts.
if (isLocatedGraphQLError(originalError)) {
return originalError;
}
return new GraphQLError(originalError.message, {
nodes:
(_nodes = originalError.nodes) !== null && _nodes !== void 0
? _nodes
: nodes,
source: originalError.source,
positions: originalError.positions,
path,
originalError,
});
}
function isLocatedGraphQLError(error) {
return Array.isArray(error.path);
}

View File

@@ -0,0 +1,11 @@
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 declare function syntaxError(
source: Source,
position: number,
description: string,
): GraphQLError;

View File

@@ -0,0 +1,19 @@
'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: ${description}`, {
source,
positions: [position],
});
}

View File

@@ -0,0 +1,12 @@
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: ${description}`, {
source,
positions: [position],
});
}

View File

@@ -0,0 +1,45 @@
import type { ObjMap } from '../jsutils/ObjMap';
import type {
FieldNode,
FragmentDefinitionNode,
SelectionSetNode,
} from '../language/ast';
import type { GraphQLObjectType } from '../type/definition';
import type { GraphQLSchema } from '../type/schema';
/**
* Given a selectionSet, collects all of the fields and returns them.
*
* CollectFields requires the "runtime type" of an object. For a field that
* returns an Interface or Union type, the "runtime type" will be the actual
* object type returned by that field.
*
* @internal
*/
export declare function collectFields(
schema: GraphQLSchema,
fragments: ObjMap<FragmentDefinitionNode>,
variableValues: {
[variable: string]: unknown;
},
runtimeType: GraphQLObjectType,
selectionSet: SelectionSetNode,
): Map<string, ReadonlyArray<FieldNode>>;
/**
* Given an array of field nodes, collects all of the subfields of the passed
* in fields, and returns them at the end.
*
* CollectSubFields requires the "return type" of an object. For a field that
* returns an Interface or Union type, the "return type" will be the actual
* object type returned by that field.
*
* @internal
*/
export declare function collectSubfields(
schema: GraphQLSchema,
fragments: ObjMap<FragmentDefinitionNode>,
variableValues: {
[variable: string]: unknown;
},
returnType: GraphQLObjectType,
fieldNodes: ReadonlyArray<FieldNode>,
): Map<string, ReadonlyArray<FieldNode>>;

View File

@@ -0,0 +1,229 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.collectFields = collectFields;
exports.collectSubfields = collectSubfields;
var _kinds = require('../language/kinds.js');
var _definition = require('../type/definition.js');
var _directives = require('../type/directives.js');
var _typeFromAST = require('../utilities/typeFromAST.js');
var _values = require('./values.js');
/**
* Given a selectionSet, collects all of the fields and returns them.
*
* CollectFields requires the "runtime type" of an object. For a field that
* returns an Interface or Union type, the "runtime type" will be the actual
* object type returned by that field.
*
* @internal
*/
function collectFields(
schema,
fragments,
variableValues,
runtimeType,
selectionSet,
) {
const fields = new Map();
collectFieldsImpl(
schema,
fragments,
variableValues,
runtimeType,
selectionSet,
fields,
new Set(),
);
return fields;
}
/**
* Given an array of field nodes, collects all of the subfields of the passed
* in fields, and returns them at the end.
*
* CollectSubFields requires the "return type" of an object. For a field that
* returns an Interface or Union type, the "return type" will be the actual
* object type returned by that field.
*
* @internal
*/
function collectSubfields(
schema,
fragments,
variableValues,
returnType,
fieldNodes,
) {
const subFieldNodes = new Map();
const visitedFragmentNames = new Set();
for (const node of fieldNodes) {
if (node.selectionSet) {
collectFieldsImpl(
schema,
fragments,
variableValues,
returnType,
node.selectionSet,
subFieldNodes,
visitedFragmentNames,
);
}
}
return subFieldNodes;
}
function collectFieldsImpl(
schema,
fragments,
variableValues,
runtimeType,
selectionSet,
fields,
visitedFragmentNames,
) {
for (const selection of selectionSet.selections) {
switch (selection.kind) {
case _kinds.Kind.FIELD: {
if (!shouldIncludeNode(variableValues, selection)) {
continue;
}
const name = getFieldEntryKey(selection);
const fieldList = fields.get(name);
if (fieldList !== undefined) {
fieldList.push(selection);
} else {
fields.set(name, [selection]);
}
break;
}
case _kinds.Kind.INLINE_FRAGMENT: {
if (
!shouldIncludeNode(variableValues, selection) ||
!doesFragmentConditionMatch(schema, selection, runtimeType)
) {
continue;
}
collectFieldsImpl(
schema,
fragments,
variableValues,
runtimeType,
selection.selectionSet,
fields,
visitedFragmentNames,
);
break;
}
case _kinds.Kind.FRAGMENT_SPREAD: {
const fragName = selection.name.value;
if (
visitedFragmentNames.has(fragName) ||
!shouldIncludeNode(variableValues, selection)
) {
continue;
}
visitedFragmentNames.add(fragName);
const fragment = fragments[fragName];
if (
!fragment ||
!doesFragmentConditionMatch(schema, fragment, runtimeType)
) {
continue;
}
collectFieldsImpl(
schema,
fragments,
variableValues,
runtimeType,
fragment.selectionSet,
fields,
visitedFragmentNames,
);
break;
}
}
}
}
/**
* Determines if a field should be included based on the `@include` and `@skip`
* directives, where `@skip` has higher precedence than `@include`.
*/
function shouldIncludeNode(variableValues, node) {
const skip = (0, _values.getDirectiveValues)(
_directives.GraphQLSkipDirective,
node,
variableValues,
);
if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) {
return false;
}
const include = (0, _values.getDirectiveValues)(
_directives.GraphQLIncludeDirective,
node,
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(schema, fragment, type) {
const typeConditionNode = fragment.typeCondition;
if (!typeConditionNode) {
return true;
}
const conditionalType = (0, _typeFromAST.typeFromAST)(
schema,
typeConditionNode,
);
if (conditionalType === type) {
return true;
}
if ((0, _definition.isAbstractType)(conditionalType)) {
return 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;
}

View File

@@ -0,0 +1,213 @@
import { Kind } from '../language/kinds.mjs';
import { isAbstractType } from '../type/definition.mjs';
import {
GraphQLIncludeDirective,
GraphQLSkipDirective,
} from '../type/directives.mjs';
import { typeFromAST } from '../utilities/typeFromAST.mjs';
import { getDirectiveValues } from './values.mjs';
/**
* Given a selectionSet, collects all of the fields and returns them.
*
* CollectFields requires the "runtime type" of an object. For a field that
* returns an Interface or Union type, the "runtime type" will be the actual
* object type returned by that field.
*
* @internal
*/
export function collectFields(
schema,
fragments,
variableValues,
runtimeType,
selectionSet,
) {
const fields = new Map();
collectFieldsImpl(
schema,
fragments,
variableValues,
runtimeType,
selectionSet,
fields,
new Set(),
);
return fields;
}
/**
* Given an array of field nodes, collects all of the subfields of the passed
* in fields, and returns them at the end.
*
* CollectSubFields requires the "return type" of an object. For a field that
* returns an Interface or Union type, the "return type" will be the actual
* object type returned by that field.
*
* @internal
*/
export function collectSubfields(
schema,
fragments,
variableValues,
returnType,
fieldNodes,
) {
const subFieldNodes = new Map();
const visitedFragmentNames = new Set();
for (const node of fieldNodes) {
if (node.selectionSet) {
collectFieldsImpl(
schema,
fragments,
variableValues,
returnType,
node.selectionSet,
subFieldNodes,
visitedFragmentNames,
);
}
}
return subFieldNodes;
}
function collectFieldsImpl(
schema,
fragments,
variableValues,
runtimeType,
selectionSet,
fields,
visitedFragmentNames,
) {
for (const selection of selectionSet.selections) {
switch (selection.kind) {
case Kind.FIELD: {
if (!shouldIncludeNode(variableValues, selection)) {
continue;
}
const name = getFieldEntryKey(selection);
const fieldList = fields.get(name);
if (fieldList !== undefined) {
fieldList.push(selection);
} else {
fields.set(name, [selection]);
}
break;
}
case Kind.INLINE_FRAGMENT: {
if (
!shouldIncludeNode(variableValues, selection) ||
!doesFragmentConditionMatch(schema, selection, runtimeType)
) {
continue;
}
collectFieldsImpl(
schema,
fragments,
variableValues,
runtimeType,
selection.selectionSet,
fields,
visitedFragmentNames,
);
break;
}
case Kind.FRAGMENT_SPREAD: {
const fragName = selection.name.value;
if (
visitedFragmentNames.has(fragName) ||
!shouldIncludeNode(variableValues, selection)
) {
continue;
}
visitedFragmentNames.add(fragName);
const fragment = fragments[fragName];
if (
!fragment ||
!doesFragmentConditionMatch(schema, fragment, runtimeType)
) {
continue;
}
collectFieldsImpl(
schema,
fragments,
variableValues,
runtimeType,
fragment.selectionSet,
fields,
visitedFragmentNames,
);
break;
}
}
}
}
/**
* Determines if a field should be included based on the `@include` and `@skip`
* directives, where `@skip` has higher precedence than `@include`.
*/
function shouldIncludeNode(variableValues, node) {
const skip = getDirectiveValues(GraphQLSkipDirective, node, variableValues);
if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) {
return false;
}
const include = getDirectiveValues(
GraphQLIncludeDirective,
node,
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(schema, fragment, type) {
const typeConditionNode = fragment.typeCondition;
if (!typeConditionNode) {
return true;
}
const conditionalType = typeFromAST(schema, typeConditionNode);
if (conditionalType === type) {
return true;
}
if (isAbstractType(conditionalType)) {
return 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;
}

View File

@@ -0,0 +1,185 @@
import type { Maybe } from '../jsutils/Maybe';
import type { ObjMap } from '../jsutils/ObjMap';
import type { Path } from '../jsutils/Path';
import type { PromiseOrValue } from '../jsutils/PromiseOrValue';
import type { GraphQLFormattedError } from '../error/GraphQLError';
import { GraphQLError } from '../error/GraphQLError';
import type {
DocumentNode,
FieldNode,
FragmentDefinitionNode,
OperationDefinitionNode,
} from '../language/ast';
import type {
GraphQLField,
GraphQLFieldResolver,
GraphQLObjectType,
GraphQLResolveInfo,
GraphQLTypeResolver,
} from '../type/definition';
import type { GraphQLSchema } from '../type/schema';
/**
* 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 interface ExecutionContext {
schema: GraphQLSchema;
fragments: ObjMap<FragmentDefinitionNode>;
rootValue: unknown;
contextValue: unknown;
operation: OperationDefinitionNode;
variableValues: {
[variable: string]: unknown;
};
fieldResolver: GraphQLFieldResolver<any, any>;
typeResolver: GraphQLTypeResolver<any, any>;
subscribeFieldResolver: 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 = ObjMap<unknown>,
TExtensions = ObjMap<unknown>,
> {
errors?: ReadonlyArray<GraphQLError>;
data?: TData | null;
extensions?: TExtensions;
}
export interface FormattedExecutionResult<
TData = ObjMap<unknown>,
TExtensions = ObjMap<unknown>,
> {
errors?: ReadonlyArray<GraphQLFormattedError>;
data?: TData | null;
extensions?: TExtensions;
}
export interface ExecutionArgs {
schema: GraphQLSchema;
document: DocumentNode;
rootValue?: unknown;
contextValue?: unknown;
variableValues?: Maybe<{
readonly [variable: string]: unknown;
}>;
operationName?: Maybe<string>;
fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>;
typeResolver?: Maybe<GraphQLTypeResolver<any, any>>;
subscribeFieldResolver?: Maybe<GraphQLFieldResolver<any, any>>;
}
/**
* Implements the "Executing 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.
*/
export declare function execute(
args: ExecutionArgs,
): PromiseOrValue<ExecutionResult>;
/**
* Also implements the "Executing 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 declare function executeSync(args: ExecutionArgs): ExecutionResult;
/**
* Essential assertions before executing to provide developer feedback for
* improper use of the GraphQL library.
*
* @internal
*/
export declare function assertValidExecutionArguments(
schema: GraphQLSchema,
document: DocumentNode,
rawVariableValues: Maybe<{
readonly [variable: string]: unknown;
}>,
): 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.
*
* @internal
*/
export declare function buildExecutionContext(
args: ExecutionArgs,
): ReadonlyArray<GraphQLError> | ExecutionContext;
/**
* @internal
*/
export declare function buildResolveInfo(
exeContext: ExecutionContext,
fieldDef: GraphQLField<unknown, unknown>,
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 declare const defaultTypeResolver: GraphQLTypeResolver<unknown, unknown>;
/**
* 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 declare const defaultFieldResolver: GraphQLFieldResolver<
unknown,
unknown
>;
/**
* 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 declare function getFieldDef(
schema: GraphQLSchema,
parentType: GraphQLObjectType,
fieldNode: FieldNode,
): Maybe<GraphQLField<unknown, unknown>>;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,18 @@
export { pathToArray as responsePathAsArray } from '../jsutils/Path';
export {
execute,
executeSync,
defaultFieldResolver,
defaultTypeResolver,
} from './execute';
export type {
ExecutionArgs,
ExecutionResult,
FormattedExecutionResult,
} from './execute';
export { subscribe, createSourceEventStream } from './subscribe';
export {
getArgumentValues,
getVariableValues,
getDirectiveValues,
} from './values';

View File

@@ -0,0 +1,73 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
Object.defineProperty(exports, 'createSourceEventStream', {
enumerable: true,
get: function () {
return _subscribe.createSourceEventStream;
},
});
Object.defineProperty(exports, 'defaultFieldResolver', {
enumerable: true,
get: function () {
return _execute.defaultFieldResolver;
},
});
Object.defineProperty(exports, 'defaultTypeResolver', {
enumerable: true,
get: function () {
return _execute.defaultTypeResolver;
},
});
Object.defineProperty(exports, 'execute', {
enumerable: true,
get: function () {
return _execute.execute;
},
});
Object.defineProperty(exports, 'executeSync', {
enumerable: true,
get: function () {
return _execute.executeSync;
},
});
Object.defineProperty(exports, 'getArgumentValues', {
enumerable: true,
get: function () {
return _values.getArgumentValues;
},
});
Object.defineProperty(exports, 'getDirectiveValues', {
enumerable: true,
get: function () {
return _values.getDirectiveValues;
},
});
Object.defineProperty(exports, 'getVariableValues', {
enumerable: true,
get: function () {
return _values.getVariableValues;
},
});
Object.defineProperty(exports, 'responsePathAsArray', {
enumerable: true,
get: function () {
return _Path.pathToArray;
},
});
Object.defineProperty(exports, 'subscribe', {
enumerable: true,
get: function () {
return _subscribe.subscribe;
},
});
var _Path = require('../jsutils/Path.js');
var _execute = require('./execute.js');
var _subscribe = require('./subscribe.js');
var _values = require('./values.js');

View File

@@ -0,0 +1,13 @@
export { pathToArray as responsePathAsArray } from '../jsutils/Path.mjs';
export {
execute,
executeSync,
defaultFieldResolver,
defaultTypeResolver,
} from './execute.mjs';
export { subscribe, createSourceEventStream } from './subscribe.mjs';
export {
getArgumentValues,
getVariableValues,
getDirectiveValues,
} from './values.mjs';

View File

@@ -0,0 +1,9 @@
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 declare function mapAsyncIterator<T, U, R = undefined>(
iterable: AsyncGenerator<T, R, void> | AsyncIterable<T>,
callback: (value: T) => PromiseOrValue<U>,
): AsyncGenerator<U, R, void>;

View File

@@ -0,0 +1,68 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.mapAsyncIterator = mapAsyncIterator;
/**
* Given an AsyncIterable and a callback function, return an AsyncIterator
* which produces values mapped via calling the callback function.
*/
function mapAsyncIterator(iterable, callback) {
const iterator = iterable[Symbol.asyncIterator]();
async function mapResult(result) {
if (result.done) {
return result;
}
try {
return {
value: await callback(result.value),
done: false,
};
} catch (error) {
/* c8 ignore start */
// FIXME: add test case
if (typeof iterator.return === 'function') {
try {
await iterator.return();
} catch (_e) {
/* ignore error */
}
}
throw error;
/* c8 ignore stop */
}
}
return {
async next() {
return mapResult(await iterator.next());
},
async return() {
// If iterator.return() does not exist, then type R must be undefined.
return typeof iterator.return === 'function'
? mapResult(await iterator.return())
: {
value: undefined,
done: true,
};
},
async throw(error) {
if (typeof iterator.throw === 'function') {
return mapResult(await iterator.throw(error));
}
throw error;
},
[Symbol.asyncIterator]() {
return this;
},
};
}

View File

@@ -0,0 +1,61 @@
/**
* Given an AsyncIterable and a callback function, return an AsyncIterator
* which produces values mapped via calling the callback function.
*/
export function mapAsyncIterator(iterable, callback) {
const iterator = iterable[Symbol.asyncIterator]();
async function mapResult(result) {
if (result.done) {
return result;
}
try {
return {
value: await callback(result.value),
done: false,
};
} catch (error) {
/* c8 ignore start */
// FIXME: add test case
if (typeof iterator.return === 'function') {
try {
await iterator.return();
} catch (_e) {
/* ignore error */
}
}
throw error;
/* c8 ignore stop */
}
}
return {
async next() {
return mapResult(await iterator.next());
},
async return() {
// If iterator.return() does not exist, then type R must be undefined.
return typeof iterator.return === 'function'
? mapResult(await iterator.return())
: {
value: undefined,
done: true,
};
},
async throw(error) {
if (typeof iterator.throw === 'function') {
return mapResult(await iterator.throw(error));
}
throw error;
},
[Symbol.asyncIterator]() {
return this;
},
};
}

View File

@@ -0,0 +1,72 @@
import type { Maybe } from '../jsutils/Maybe';
import type { DocumentNode } from '../language/ast';
import type { GraphQLFieldResolver } from '../type/definition';
import type { GraphQLSchema } from '../type/schema';
import type { ExecutionArgs, ExecutionResult } from './execute';
/**
* 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.
*/
export declare function subscribe(
args: ExecutionArgs,
): Promise<AsyncGenerator<ExecutionResult, void, void> | 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 declare function createSourceEventStream(
args: ExecutionArgs,
): Promise<AsyncIterable<unknown> | ExecutionResult>;
/** @deprecated will be removed in next major version in favor of named arguments */
export declare function createSourceEventStream(
schema: GraphQLSchema,
document: DocumentNode,
rootValue?: unknown,
contextValue?: unknown,
variableValues?: Maybe<{
readonly [variable: string]: unknown;
}>,
operationName?: Maybe<string>,
subscribeFieldResolver?: Maybe<GraphQLFieldResolver<any, any>>,
): Promise<AsyncIterable<unknown> | ExecutionResult>;

View File

@@ -0,0 +1,244 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.createSourceEventStream = createSourceEventStream;
exports.subscribe = subscribe;
var _devAssert = require('../jsutils/devAssert.js');
var _inspect = require('../jsutils/inspect.js');
var _isAsyncIterable = require('../jsutils/isAsyncIterable.js');
var _Path = require('../jsutils/Path.js');
var _GraphQLError = require('../error/GraphQLError.js');
var _locatedError = require('../error/locatedError.js');
var _collectFields = require('./collectFields.js');
var _execute = require('./execute.js');
var _mapAsyncIterator = require('./mapAsyncIterator.js');
var _values = require('./values.js');
/**
* 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.
*/
async function subscribe(args) {
// Temporary for v15 to v16 migration. Remove in v17
arguments.length < 2 ||
(0, _devAssert.devAssert)(
false,
'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.',
);
const resultOrStream = await createSourceEventStream(args);
if (!(0, _isAsyncIterable.isAsyncIterable)(resultOrStream)) {
return resultOrStream;
} // 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) =>
(0, _execute.execute)({ ...args, rootValue: payload }); // Map every source value to a ExecutionResult value as described above.
return (0, _mapAsyncIterator.mapAsyncIterator)(
resultOrStream,
mapSourceToResponse,
);
}
function toNormalizedArgs(args) {
const firstArg = args[0];
if (firstArg && 'document' in firstArg) {
return firstArg;
}
return {
schema: firstArg,
// FIXME: when underlying TS bug fixed, see https://github.com/microsoft/TypeScript/issues/31613
document: args[1],
rootValue: args[2],
contextValue: args[3],
variableValues: args[4],
operationName: args[5],
subscribeFieldResolver: args[6],
};
}
/**
* 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.
*/
async function createSourceEventStream(...rawArgs) {
const args = toNormalizedArgs(rawArgs);
const { schema, document, variableValues } = args; // 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); // If a valid execution context cannot be created due to incorrect arguments,
// a "Response" with only errors is returned.
const exeContext = (0, _execute.buildExecutionContext)(args); // Return early errors if execution context failed.
if (!('schema' in exeContext)) {
return {
errors: exeContext,
};
}
try {
const eventStream = await executeSubscription(exeContext); // Assert field returned an event stream, otherwise yield an error.
if (!(0, _isAsyncIterable.isAsyncIterable)(eventStream)) {
throw new Error(
'Subscription field must return Async Iterable. ' +
`Received: ${(0, _inspect.inspect)(eventStream)}.`,
);
}
return eventStream;
} catch (error) {
// If it GraphQLError, report it as an ExecutionResult, containing only errors and no data.
// Otherwise treat the error as a system-class error and re-throw it.
if (error instanceof _GraphQLError.GraphQLError) {
return {
errors: [error],
};
}
throw error;
}
}
async function executeSubscription(exeContext) {
const { schema, fragments, operation, variableValues, rootValue } =
exeContext;
const rootType = schema.getSubscriptionType();
if (rootType == null) {
throw new _GraphQLError.GraphQLError(
'Schema is not configured to execute subscription operation.',
{
nodes: operation,
},
);
}
const rootFields = (0, _collectFields.collectFields)(
schema,
fragments,
variableValues,
rootType,
operation.selectionSet,
);
const [responseName, fieldNodes] = [...rootFields.entries()][0];
const fieldDef = (0, _execute.getFieldDef)(schema, rootType, fieldNodes[0]);
if (!fieldDef) {
const fieldName = fieldNodes[0].name.value;
throw new _GraphQLError.GraphQLError(
`The subscription field "${fieldName}" is not defined.`,
{
nodes: fieldNodes,
},
);
}
const path = (0, _Path.addPath)(undefined, responseName, rootType.name);
const info = (0, _execute.buildResolveInfo)(
exeContext,
fieldDef,
fieldNodes,
rootType,
path,
);
try {
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.
const 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.
const contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an
// AsyncIterable yielding raw payloads.
const resolveFn =
(_fieldDef$subscribe = fieldDef.subscribe) !== null &&
_fieldDef$subscribe !== void 0
? _fieldDef$subscribe
: exeContext.subscribeFieldResolver;
const eventStream = await resolveFn(rootValue, args, contextValue, info);
if (eventStream instanceof Error) {
throw eventStream;
}
return eventStream;
} catch (error) {
throw (0, _locatedError.locatedError)(
error,
fieldNodes,
(0, _Path.pathToArray)(path),
);
}
}

View File

@@ -0,0 +1,222 @@
import { devAssert } from '../jsutils/devAssert.mjs';
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 { collectFields } from './collectFields.mjs';
import {
assertValidExecutionArguments,
buildExecutionContext,
buildResolveInfo,
execute,
getFieldDef,
} from './execute.mjs';
import { mapAsyncIterator } from './mapAsyncIterator.mjs';
import { getArgumentValues } from './values.mjs';
/**
* 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.
*/
export async function subscribe(args) {
// Temporary for v15 to v16 migration. Remove in v17
arguments.length < 2 ||
devAssert(
false,
'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.',
);
const resultOrStream = await createSourceEventStream(args);
if (!isAsyncIterable(resultOrStream)) {
return resultOrStream;
} // 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({ ...args, rootValue: payload }); // Map every source value to a ExecutionResult value as described above.
return mapAsyncIterator(resultOrStream, mapSourceToResponse);
}
function toNormalizedArgs(args) {
const firstArg = args[0];
if (firstArg && 'document' in firstArg) {
return firstArg;
}
return {
schema: firstArg,
// FIXME: when underlying TS bug fixed, see https://github.com/microsoft/TypeScript/issues/31613
document: args[1],
rootValue: args[2],
contextValue: args[3],
variableValues: args[4],
operationName: args[5],
subscribeFieldResolver: args[6],
};
}
/**
* 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 async function createSourceEventStream(...rawArgs) {
const args = toNormalizedArgs(rawArgs);
const { schema, document, variableValues } = args; // If arguments are missing or incorrectly typed, this is an internal
// developer mistake which should throw an early 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(args); // Return early errors if execution context failed.
if (!('schema' in exeContext)) {
return {
errors: exeContext,
};
}
try {
const eventStream = await executeSubscription(exeContext); // 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;
} catch (error) {
// If it GraphQLError, report it as an ExecutionResult, containing only errors and no data.
// Otherwise treat the error as a system-class error and re-throw it.
if (error instanceof GraphQLError) {
return {
errors: [error],
};
}
throw error;
}
}
async function executeSubscription(exeContext) {
const { schema, fragments, operation, variableValues, rootValue } =
exeContext;
const rootType = schema.getSubscriptionType();
if (rootType == null) {
throw new GraphQLError(
'Schema is not configured to execute subscription operation.',
{
nodes: operation,
},
);
}
const rootFields = collectFields(
schema,
fragments,
variableValues,
rootType,
operation.selectionSet,
);
const [responseName, fieldNodes] = [...rootFields.entries()][0];
const fieldDef = getFieldDef(schema, rootType, fieldNodes[0]);
if (!fieldDef) {
const fieldName = fieldNodes[0].name.value;
throw new GraphQLError(
`The subscription field "${fieldName}" is not defined.`,
{
nodes: fieldNodes,
},
);
}
const path = addPath(undefined, responseName, rootType.name);
const info = buildResolveInfo(
exeContext,
fieldDef,
fieldNodes,
rootType,
path,
);
try {
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.
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 = fieldDef.subscribe) !== null &&
_fieldDef$subscribe !== void 0
? _fieldDef$subscribe
: exeContext.subscribeFieldResolver;
const eventStream = await resolveFn(rootValue, args, contextValue, info);
if (eventStream instanceof Error) {
throw eventStream;
}
return eventStream;
} catch (error) {
throw locatedError(error, fieldNodes, pathToArray(path));
}
}

View File

@@ -0,0 +1,79 @@
import type { Maybe } from '../jsutils/Maybe';
import type { ObjMap } from '../jsutils/ObjMap';
import { GraphQLError } from '../error/GraphQLError';
import type {
DirectiveNode,
FieldNode,
VariableDefinitionNode,
} from '../language/ast';
import type { GraphQLField } from '../type/definition';
import type { GraphQLDirective } from '../type/directives';
import type { GraphQLSchema } from '../type/schema';
declare type CoercedVariableValues =
| {
errors: ReadonlyArray<GraphQLError>;
coerced?: never;
}
| {
coerced: {
[variable: string]: unknown;
};
errors?: never;
};
/**
* 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 declare function getVariableValues(
schema: GraphQLSchema,
varDefNodes: ReadonlyArray<VariableDefinitionNode>,
inputs: {
readonly [variable: string]: unknown;
},
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 declare function getArgumentValues(
def: GraphQLField<unknown, unknown> | GraphQLDirective,
node: FieldNode | DirectiveNode,
variableValues?: Maybe<ObjMap<unknown>>,
): {
[argument: string]: unknown;
};
/**
* 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 declare function getDirectiveValues(
directiveDef: GraphQLDirective,
node: {
readonly directives?: ReadonlyArray<DirectiveNode>;
},
variableValues?: Maybe<ObjMap<unknown>>,
):
| undefined
| {
[argument: string]: unknown;
};
export {};

View File

@@ -0,0 +1,300 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.getArgumentValues = getArgumentValues;
exports.getDirectiveValues = getDirectiveValues;
exports.getVariableValues = getVariableValues;
var _inspect = require('../jsutils/inspect.js');
var _keyMap = require('../jsutils/keyMap.js');
var _printPathArray = 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 _coerceInputValue = require('../utilities/coerceInputValue.js');
var _typeFromAST = require('../utilities/typeFromAST.js');
var _valueFromAST = require('../utilities/valueFromAST.js');
/**
* 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.
*/
function getVariableValues(schema, varDefNodes, inputs, options) {
const errors = [];
const maxErrors =
options === null || options === void 0 ? void 0 : options.maxErrors;
try {
const coerced = coerceVariableValues(
schema,
varDefNodes,
inputs,
(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,
};
}
} catch (error) {
errors.push(error);
}
return {
errors,
};
}
function coerceVariableValues(schema, varDefNodes, inputs, onError) {
const coercedValues = {};
for (const varDefNode of varDefNodes) {
const varName = varDefNode.variable.name.value;
const 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.
const varTypeStr = (0, _printer.print)(varDefNode.type);
onError(
new _GraphQLError.GraphQLError(
`Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`,
{
nodes: varDefNode.type,
},
),
);
continue;
}
if (!hasOwnProperty(inputs, varName)) {
if (varDefNode.defaultValue) {
coercedValues[varName] = (0, _valueFromAST.valueFromAST)(
varDefNode.defaultValue,
varType,
);
} else if ((0, _definition.isNonNullType)(varType)) {
const varTypeStr = (0, _inspect.inspect)(varType);
onError(
new _GraphQLError.GraphQLError(
`Variable "$${varName}" of required type "${varTypeStr}" was not provided.`,
{
nodes: varDefNode,
},
),
);
}
continue;
}
const value = inputs[varName];
if (value === null && (0, _definition.isNonNullType)(varType)) {
const varTypeStr = (0, _inspect.inspect)(varType);
onError(
new _GraphQLError.GraphQLError(
`Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`,
{
nodes: varDefNode,
},
),
);
continue;
}
coercedValues[varName] = (0, _coerceInputValue.coerceInputValue)(
value,
varType,
(path, invalidValue, error) => {
let prefix =
`Variable "$${varName}" got invalid value ` +
(0, _inspect.inspect)(invalidValue);
if (path.length > 0) {
prefix += ` at "${varName}${(0, _printPathArray.printPathArray)(
path,
)}"`;
}
onError(
new _GraphQLError.GraphQLError(prefix + '; ' + error.message, {
nodes: varDefNode,
originalError: error,
}),
);
},
);
}
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.
*/
function getArgumentValues(def, node, variableValues) {
var _node$arguments;
const coercedValues = {}; // FIXME: https://github.com/graphql/graphql-js/issues/2203
/* c8 ignore next */
const argumentNodes =
(_node$arguments = node.arguments) !== null && _node$arguments !== void 0
? _node$arguments
: [];
const argNodeMap = (0, _keyMap.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 ((0, _definition.isNonNullType)(argType)) {
throw new _GraphQLError.GraphQLError(
`Argument "${name}" of required type "${(0, _inspect.inspect)(
argType,
)}" ` + 'was not provided.',
{
nodes: node,
},
);
}
continue;
}
const valueNode = argumentNode.value;
let isNull = valueNode.kind === _kinds.Kind.NULL;
if (valueNode.kind === _kinds.Kind.VARIABLE) {
const 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 "${name}" of required type "${(0, _inspect.inspect)(
argType,
)}" ` +
`was provided the variable "$${variableName}" which was not provided a runtime value.`,
{
nodes: valueNode,
},
);
}
continue;
}
isNull = variableValues[variableName] == null;
}
if (isNull && (0, _definition.isNonNullType)(argType)) {
throw new _GraphQLError.GraphQLError(
`Argument "${name}" of non-null type "${(0, _inspect.inspect)(
argType,
)}" ` + 'must not be null.',
{
nodes: valueNode,
},
);
}
const 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 "${name}" has invalid value ${(0, _printer.print)(
valueNode,
)}.`,
{
nodes: 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 _node$directives;
const directiveNode =
(_node$directives = node.directives) === null || _node$directives === void 0
? void 0
: _node$directives.find(
(directive) => directive.name.value === directiveDef.name,
);
if (directiveNode) {
return getArgumentValues(directiveDef, directiveNode, variableValues);
}
}
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}

View File

@@ -0,0 +1,263 @@
import { inspect } from '../jsutils/inspect.mjs';
import { keyMap } from '../jsutils/keyMap.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 { coerceInputValue } from '../utilities/coerceInputValue.mjs';
import { typeFromAST } from '../utilities/typeFromAST.mjs';
import { valueFromAST } from '../utilities/valueFromAST.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.
*/
export function getVariableValues(schema, varDefNodes, inputs, options) {
const errors = [];
const maxErrors =
options === null || options === void 0 ? void 0 : 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, varDefNodes, inputs, onError) {
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.`,
{
nodes: 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.`,
{
nodes: 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.`,
{
nodes: 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, {
nodes: varDefNode,
originalError: error,
}),
);
},
);
}
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.
*/
export function getArgumentValues(def, node, variableValues) {
var _node$arguments;
const coercedValues = {}; // FIXME: https://github.com/graphql/graphql-js/issues/2203
/* c8 ignore next */
const argumentNodes =
(_node$arguments = node.arguments) !== null && _node$arguments !== void 0
? _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.',
{
nodes: 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.`,
{
nodes: 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.',
{
nodes: 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)}.`,
{
nodes: 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 _node$directives;
const directiveNode =
(_node$directives = node.directives) === null || _node$directives === void 0
? void 0
: _node$directives.find(
(directive) => directive.name.value === directiveDef.name,
);
if (directiveNode) {
return getArgumentValues(directiveDef, directiveNode, variableValues);
}
}
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}

View File

@@ -0,0 +1,67 @@
import type { Maybe } from './jsutils/Maybe';
import type { Source } from './language/source';
import type {
GraphQLFieldResolver,
GraphQLTypeResolver,
} from './type/definition';
import type { GraphQLSchema } from './type/schema';
import type { 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).
* 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 interface GraphQLArgs {
schema: GraphQLSchema;
source: string | Source;
rootValue?: unknown;
contextValue?: unknown;
variableValues?: Maybe<{
readonly [variable: string]: unknown;
}>;
operationName?: Maybe<string>;
fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>;
typeResolver?: Maybe<GraphQLTypeResolver<any, any>>;
}
export declare function graphql(args: GraphQLArgs): 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 declare function graphqlSync(args: GraphQLArgs): ExecutionResult;

View File

@@ -0,0 +1,96 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.graphql = graphql;
exports.graphqlSync = graphqlSync;
var _devAssert = require('./jsutils/devAssert.js');
var _isPromise = require('./jsutils/isPromise.js');
var _parser = require('./language/parser.js');
var _validate = require('./type/validate.js');
var _validate2 = require('./validation/validate.js');
var _execute = require('./execution/execute.js');
function graphql(args) {
// Always return a Promise for a consistent API.
return new Promise((resolve) => resolve(graphqlImpl(args)));
}
/**
* 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(args) {
const result = graphqlImpl(args); // Assert that the execution was synchronous.
if ((0, _isPromise.isPromise)(result)) {
throw new Error('GraphQL execution failed to complete synchronously.');
}
return result;
}
function graphqlImpl(args) {
// Temporary for v15 to v16 migration. Remove in v17
arguments.length < 2 ||
(0, _devAssert.devAssert)(
false,
'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.',
);
const {
schema,
source,
rootValue,
contextValue,
variableValues,
operationName,
fieldResolver,
typeResolver,
} = args; // Validate Schema
const schemaValidationErrors = (0, _validate.validateSchema)(schema);
if (schemaValidationErrors.length > 0) {
return {
errors: schemaValidationErrors,
};
} // Parse
let document;
try {
document = (0, _parser.parse)(source);
} catch (syntaxError) {
return {
errors: [syntaxError],
};
} // Validate
const validationErrors = (0, _validate2.validate)(schema, document);
if (validationErrors.length > 0) {
return {
errors: validationErrors,
};
} // Execute
return (0, _execute.execute)({
schema,
document,
rootValue,
contextValue,
variableValues,
operationName,
fieldResolver,
typeResolver,
});
}

View File

@@ -0,0 +1,122 @@
import { devAssert } from './jsutils/devAssert.mjs';
import { isPromise } from './jsutils/isPromise.mjs';
import { parse } from './language/parser.mjs';
import { validateSchema } from './type/validate.mjs';
import { validate } from './validation/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(args) {
// Always return a Promise for a consistent API.
return new Promise((resolve) => resolve(graphqlImpl(args)));
}
/**
* 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) {
const result = graphqlImpl(args); // Assert that the execution was synchronous.
if (isPromise(result)) {
throw new Error('GraphQL execution failed to complete synchronously.');
}
return result;
}
function graphqlImpl(args) {
// Temporary for v15 to v16 migration. Remove in v17
arguments.length < 2 ||
devAssert(
false,
'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.',
);
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,
});
}

View File

@@ -0,0 +1,413 @@
/**
* 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:
*
* ```ts
* import { parse } from 'graphql';
* import { parse } from 'graphql/language';
* ```
*
* @packageDocumentation
*/
export { version, versionInfo } from './version';
export type { GraphQLArgs } from './graphql';
export { graphql, graphqlSync } from './graphql';
export {
resolveObjMapThunk,
resolveReadonlyArrayThunk,
GraphQLSchema,
GraphQLDirective,
GraphQLScalarType,
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLUnionType,
GraphQLEnumType,
GraphQLInputObjectType,
GraphQLList,
GraphQLNonNull,
specifiedScalarTypes,
GraphQLInt,
GraphQLFloat,
GraphQLString,
GraphQLBoolean,
GraphQLID,
GRAPHQL_MAX_INT,
GRAPHQL_MIN_INT,
specifiedDirectives,
GraphQLIncludeDirective,
GraphQLSkipDirective,
GraphQLDeprecatedDirective,
GraphQLSpecifiedByDirective,
TypeKind,
DEFAULT_DEPRECATION_REASON,
introspectionTypes,
__Schema,
__Directive,
__DirectiveLocation,
__Type,
__Field,
__InputValue,
__EnumValue,
__TypeKind,
SchemaMetaFieldDef,
TypeMetaFieldDef,
TypeNameMetaFieldDef,
isSchema,
isDirective,
isType,
isScalarType,
isObjectType,
isInterfaceType,
isUnionType,
isEnumType,
isInputObjectType,
isListType,
isNonNullType,
isInputType,
isOutputType,
isLeafType,
isCompositeType,
isAbstractType,
isWrappingType,
isNullableType,
isNamedType,
isRequiredArgument,
isRequiredInputField,
isSpecifiedScalarType,
isIntrospectionType,
isSpecifiedDirective,
assertSchema,
assertDirective,
assertType,
assertScalarType,
assertObjectType,
assertInterfaceType,
assertUnionType,
assertEnumType,
assertInputObjectType,
assertListType,
assertNonNullType,
assertInputType,
assertOutputType,
assertLeafType,
assertCompositeType,
assertAbstractType,
assertWrappingType,
assertNullableType,
assertNamedType,
getNullableType,
getNamedType,
validateSchema,
assertValidSchema,
assertName,
assertEnumValueName,
} from './type/index';
export type {
GraphQLType,
GraphQLInputType,
GraphQLOutputType,
GraphQLLeafType,
GraphQLCompositeType,
GraphQLAbstractType,
GraphQLWrappingType,
GraphQLNullableType,
GraphQLNamedType,
GraphQLNamedInputType,
GraphQLNamedOutputType,
ThunkReadonlyArray,
ThunkObjMap,
GraphQLSchemaConfig,
GraphQLSchemaExtensions,
GraphQLDirectiveConfig,
GraphQLDirectiveExtensions,
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,
ResponsePath,
GraphQLScalarTypeConfig,
GraphQLScalarTypeExtensions,
GraphQLTypeResolver,
GraphQLUnionTypeConfig,
GraphQLUnionTypeExtensions,
GraphQLScalarSerializer,
GraphQLScalarValueParser,
GraphQLScalarLiteralParser,
} from './type/index';
export {
Token,
Source,
Location,
OperationTypeNode,
getLocation,
printLocation,
printSourceLocation,
Lexer,
TokenKind,
parse,
parseValue,
parseConstValue,
parseType,
print,
visit,
visitInParallel,
getVisitFn,
getEnterLeaveForKind,
BREAK,
Kind,
DirectiveLocation,
isDefinitionNode,
isExecutableDefinitionNode,
isSelectionNode,
isValueNode,
isConstValueNode,
isTypeNode,
isTypeSystemDefinitionNode,
isTypeDefinitionNode,
isTypeSystemExtensionNode,
isTypeExtensionNode,
} from './language/index';
export type {
ParseOptions,
SourceLocation,
TokenKindEnum,
KindEnum,
DirectiveLocationEnum,
ASTVisitor,
ASTVisitFn,
ASTVisitorKeyMap,
ASTNode,
ASTKindToNode,
NameNode,
DocumentNode,
DefinitionNode,
ExecutableDefinitionNode,
OperationDefinitionNode,
VariableDefinitionNode,
VariableNode,
SelectionSetNode,
SelectionNode,
FieldNode,
ArgumentNode,
ConstArgumentNode,
FragmentSpreadNode,
InlineFragmentNode,
FragmentDefinitionNode,
ValueNode,
ConstValueNode,
IntValueNode,
FloatValueNode,
StringValueNode,
BooleanValueNode,
NullValueNode,
EnumValueNode,
ListValueNode,
ConstListValueNode,
ObjectValueNode,
ConstObjectValueNode,
ObjectFieldNode,
ConstObjectFieldNode,
DirectiveNode,
ConstDirectiveNode,
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';
export {
execute,
executeSync,
defaultFieldResolver,
defaultTypeResolver,
responsePathAsArray,
getArgumentValues,
getVariableValues,
getDirectiveValues,
subscribe,
createSourceEventStream,
} from './execution/index';
export type {
ExecutionArgs,
ExecutionResult,
FormattedExecutionResult,
} from './execution/index';
export type { SubscriptionArgs } from './subscription/index';
export {
validate,
ValidationContext,
specifiedRules,
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,
LoneSchemaDefinitionRule,
UniqueOperationTypesRule,
UniqueTypeNamesRule,
UniqueEnumValueNamesRule,
UniqueFieldDefinitionNamesRule,
UniqueArgumentDefinitionNamesRule,
UniqueDirectiveNamesRule,
PossibleTypeExtensionsRule,
NoDeprecatedCustomRule,
NoSchemaIntrospectionCustomRule,
} from './validation/index';
export type { ValidationRule } from './validation/index';
export {
GraphQLError,
syntaxError,
locatedError,
printError,
formatError,
} from './error/index';
export type {
GraphQLErrorOptions,
GraphQLFormattedError,
GraphQLErrorExtensions,
} from './error/index';
export {
getIntrospectionQuery,
getOperationAST,
getOperationRootType,
introspectionFromSchema,
buildClientSchema,
buildASTSchema,
buildSchema,
extendSchema,
lexicographicSortSchema,
printSchema,
printType,
printIntrospectionSchema,
typeFromAST,
valueFromAST,
valueFromASTUntyped,
astFromValue,
TypeInfo,
visitWithTypeInfo,
coerceInputValue,
concatAST,
separateOperations,
stripIgnoredCharacters,
isEqualType,
isTypeSubTypeOf,
doTypesOverlap,
assertValidName,
isValidNameError,
BreakingChangeType,
DangerousChangeType,
findBreakingChanges,
findDangerousChanges,
} 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,
TypedQueryDocumentNode,
} from './utilities/index';

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,255 @@
/**
* 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:
*
* ```ts
* import { parse } from 'graphql';
* import { parse } from 'graphql/language';
* ```
*
* @packageDocumentation
*/
// 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 {
resolveObjMapThunk,
resolveReadonlyArrayThunk, // Definitions
GraphQLSchema,
GraphQLDirective,
GraphQLScalarType,
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLUnionType,
GraphQLEnumType,
GraphQLInputObjectType,
GraphQLList,
GraphQLNonNull, // Standard GraphQL Scalars
specifiedScalarTypes,
GraphQLInt,
GraphQLFloat,
GraphQLString,
GraphQLBoolean,
GraphQLID, // Int boundaries constants
GRAPHQL_MAX_INT,
GRAPHQL_MIN_INT, // 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, // Upholds the spec rules about naming.
assertName,
assertEnumValueName,
} from './type/index.mjs';
// Parse and operate on GraphQL language source files.
export {
Token,
Source,
Location,
OperationTypeNode,
getLocation, // Print source location.
printLocation,
printSourceLocation, // Lex
Lexer,
TokenKind, // Parse
parse,
parseValue,
parseConstValue,
parseType, // Print
print, // Visit
visit,
visitInParallel,
getVisitFn,
getEnterLeaveForKind,
BREAK,
Kind,
DirectiveLocation, // Predicates
isDefinitionNode,
isExecutableDefinitionNode,
isSelectionNode,
isValueNode,
isConstValueNode,
isTypeNode,
isTypeSystemDefinitionNode,
isTypeDefinitionNode,
isTypeSystemExtensionNode,
isTypeExtensionNode,
} from './language/index.mjs';
// Execute GraphQL queries.
export {
execute,
executeSync,
defaultFieldResolver,
defaultTypeResolver,
responsePathAsArray,
getArgumentValues,
getVariableValues,
getDirectiveValues,
subscribe,
createSourceEventStream,
} from './execution/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,
UniqueArgumentDefinitionNamesRule,
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, // 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,
} from './utilities/index.mjs';

View File

@@ -0,0 +1,2 @@
/** Conveniently represents flow's "Maybe" type https://flow.org/en/docs/types/maybe/ */
export declare type Maybe<T> = null | undefined | T;

View File

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

View File

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

View File

@@ -0,0 +1,16 @@
export interface ObjMap<T> {
[key: string]: T;
}
export declare type ObjMapLike<T> =
| ObjMap<T>
| {
[key: string]: T;
};
export interface ReadOnlyObjMap<T> {
readonly [key: string]: T;
}
export declare type ReadOnlyObjMapLike<T> =
| ReadOnlyObjMap<T>
| {
readonly [key: string]: T;
};

View File

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

View File

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

View File

@@ -0,0 +1,20 @@
import type { Maybe } from './Maybe';
export interface Path {
readonly prev: Path | undefined;
readonly key: string | number;
readonly typename: string | undefined;
}
/**
* Given a Path and a key, return a new Path containing the new key.
*/
export declare function addPath(
prev: Readonly<Path> | undefined,
key: string | number,
typename: string | undefined,
): Path;
/**
* Given a Path, return an Array of the path keys.
*/
export declare function pathToArray(
path: Maybe<Readonly<Path>>,
): Array<string | number>;

View File

@@ -0,0 +1,33 @@
'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,
key,
typename,
};
}
/**
* Given a Path, return an Array of the path keys.
*/
function pathToArray(path) {
const flattened = [];
let curr = path;
while (curr) {
flattened.push(curr.key);
curr = curr.prev;
}
return flattened.reverse();
}

View File

@@ -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,
key,
typename,
};
}
/**
* Given a Path, return an Array of the path keys.
*/
export function pathToArray(path) {
const flattened = [];
let curr = path;
while (curr) {
flattened.push(curr.key);
curr = curr.prev;
}
return flattened.reverse();
}

View File

@@ -0,0 +1 @@
export declare type PromiseOrValue<T> = Promise<T> | T;

View File

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

View File

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

View File

@@ -0,0 +1 @@
export declare function devAssert(condition: unknown, message: string): void;

View File

@@ -0,0 +1,14 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.devAssert = devAssert;
function devAssert(condition, message) {
const booleanCondition = Boolean(condition);
if (!booleanCondition) {
throw new Error(message);
}
}

View File

@@ -0,0 +1,7 @@
export function devAssert(condition, message) {
const booleanCondition = Boolean(condition);
if (!booleanCondition) {
throw new Error(message);
}
}

View File

@@ -0,0 +1,8 @@
/**
* Given [ A, B, C ] return ' Did you mean A, B, or C?'.
*/
export declare function didYouMean(suggestions: ReadonlyArray<string>): string;
export declare function didYouMean(
subMessage: string,
suggestions: ReadonlyArray<string>,
): string;

View File

@@ -0,0 +1,38 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.didYouMean = didYouMean;
const MAX_SUGGESTIONS = 5;
/**
* Given [ A, B, C ] return ' Did you mean A, B, or C?'.
*/
function didYouMean(firstArg, secondArg) {
const [subMessage, suggestionsArg] = secondArg
? [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 + '?';
}

View File

@@ -0,0 +1,32 @@
const MAX_SUGGESTIONS = 5;
/**
* Given [ A, B, C ] return ' Did you mean A, B, or C?'.
*/
export function didYouMean(firstArg, secondArg) {
const [subMessage, suggestionsArg] = secondArg
? [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 + '?';
}

View File

@@ -0,0 +1,7 @@
/**
* Groups array items into a Map, given a function to produce grouping key.
*/
export declare function groupBy<K, T>(
list: ReadonlyArray<T>,
keyFn: (item: T) => K,
): Map<K, ReadonlyArray<T>>;

View File

@@ -0,0 +1,26 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.groupBy = groupBy;
/**
* Groups array items into a Map, given a function to produce grouping key.
*/
function groupBy(list, keyFn) {
const result = new Map();
for (const item of list) {
const key = keyFn(item);
const group = result.get(key);
if (group === undefined) {
result.set(key, [item]);
} else {
group.push(item);
}
}
return result;
}

View File

@@ -0,0 +1,19 @@
/**
* Groups array items into a Map, given a function to produce grouping key.
*/
export function groupBy(list, keyFn) {
const result = new Map();
for (const item of list) {
const key = keyFn(item);
const group = result.get(key);
if (group === undefined) {
result.set(key, [item]);
} else {
group.push(item);
}
}
return result;
}

View File

@@ -0,0 +1,4 @@
/**
* Returns the first argument it receives.
*/
export declare function identityFunc<T>(x: T): T;

View File

@@ -0,0 +1,13 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.identityFunc = identityFunc;
/**
* Returns the first argument it receives.
*/
function identityFunc(x) {
return x;
}

View File

@@ -0,0 +1,6 @@
/**
* Returns the first argument it receives.
*/
export function identityFunc(x) {
return x;
}

View File

@@ -0,0 +1,4 @@
/**
* Used to print values in error messages.
*/
export declare function inspect(value: unknown): string;

View File

@@ -0,0 +1,121 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.inspect = inspect;
const MAX_ARRAY_LENGTH = 10;
const 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 ${value.name}]` : '[function]';
case 'object':
return formatObjectValue(value, seenValues);
default:
return String(value);
}
}
function formatObjectValue(value, previouslySeenValues) {
if (value === null) {
return 'null';
}
if (previouslySeenValues.includes(value)) {
return '[Circular]';
}
const seenValues = [...previouslySeenValues, value];
if (isJSONable(value)) {
const jsonValue = value.toJSON(); // check for infinite recursion
if (jsonValue !== value) {
return typeof jsonValue === 'string'
? jsonValue
: formatValue(jsonValue, seenValues);
}
} else if (Array.isArray(value)) {
return formatArray(value, seenValues);
}
return formatObject(value, seenValues);
}
function isJSONable(value) {
return typeof value.toJSON === 'function';
}
function formatObject(object, seenValues) {
const entries = Object.entries(object);
if (entries.length === 0) {
return '{}';
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return '[' + getObjectTag(object) + ']';
}
const properties = entries.map(
([key, value]) => key + ': ' + formatValue(value, seenValues),
);
return '{ ' + properties.join(', ') + ' }';
}
function formatArray(array, seenValues) {
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 getObjectTag(object) {
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;
}

View File

@@ -0,0 +1,115 @@
const MAX_ARRAY_LENGTH = 10;
const MAX_RECURSIVE_DEPTH = 2;
/**
* Used to print values in error messages.
*/
export 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 ${value.name}]` : '[function]';
case 'object':
return formatObjectValue(value, seenValues);
default:
return String(value);
}
}
function formatObjectValue(value, previouslySeenValues) {
if (value === null) {
return 'null';
}
if (previouslySeenValues.includes(value)) {
return '[Circular]';
}
const seenValues = [...previouslySeenValues, value];
if (isJSONable(value)) {
const jsonValue = value.toJSON(); // check for infinite recursion
if (jsonValue !== value) {
return typeof jsonValue === 'string'
? jsonValue
: formatValue(jsonValue, seenValues);
}
} else if (Array.isArray(value)) {
return formatArray(value, seenValues);
}
return formatObject(value, seenValues);
}
function isJSONable(value) {
return typeof value.toJSON === 'function';
}
function formatObject(object, seenValues) {
const entries = Object.entries(object);
if (entries.length === 0) {
return '{}';
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return '[' + getObjectTag(object) + ']';
}
const properties = entries.map(
([key, value]) => key + ': ' + formatValue(value, seenValues),
);
return '{ ' + properties.join(', ') + ' }';
}
function formatArray(array, seenValues) {
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 getObjectTag(object) {
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;
}

View File

@@ -0,0 +1,16 @@
/**
* 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 declare const instanceOf: (
value: unknown,
constructor: Constructor,
) => boolean;
interface Constructor extends Function {
prototype: {
[Symbol.toStringTag]: string;
};
}
export {};

View File

@@ -0,0 +1,60 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.instanceOf = void 0;
var _inspect = require('./inspect.js');
/**
* 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/
*/
const instanceOf =
/* c8 ignore next 6 */
// FIXME: https://github.com/graphql/graphql-js/issues/2317
globalThis.process && globalThis.process.env.NODE_ENV === 'production'
? function instanceOf(value, constructor) {
return value instanceof constructor;
}
: function instanceOf(value, constructor) {
if (value instanceof constructor) {
return true;
}
if (typeof value === 'object' && value !== null) {
var _value$constructor;
// Prefer Symbol.toStringTag since it is immune to minification.
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 // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009
? value[Symbol.toStringTag]
: (_value$constructor = value.constructor) === null ||
_value$constructor === void 0
? void 0
: _value$constructor.name;
if (className === valueClassName) {
const stringifiedValue = (0, _inspect.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;
};
exports.instanceOf = instanceOf;

View File

@@ -0,0 +1,52 @@
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 const instanceOf =
/* c8 ignore next 6 */
// FIXME: https://github.com/graphql/graphql-js/issues/2317
globalThis.process && globalThis.process.env.NODE_ENV === 'production'
? function instanceOf(value, constructor) {
return value instanceof constructor;
}
: function instanceOf(value, constructor) {
if (value instanceof constructor) {
return true;
}
if (typeof value === 'object' && value !== null) {
var _value$constructor;
// Prefer Symbol.toStringTag since it is immune to minification.
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 // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009
? value[Symbol.toStringTag]
: (_value$constructor = value.constructor) === null ||
_value$constructor === void 0
? void 0
: _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;
};

View File

@@ -0,0 +1,4 @@
export declare function invariant(
condition: unknown,
message?: string,
): asserts condition;

View File

@@ -0,0 +1,16 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.invariant = invariant;
function invariant(condition, message) {
const booleanCondition = Boolean(condition);
if (!booleanCondition) {
throw new Error(
message != null ? message : 'Unexpected invariant triggered.',
);
}
}

View File

@@ -0,0 +1,9 @@
export function invariant(condition, message) {
const booleanCondition = Boolean(condition);
if (!booleanCondition) {
throw new Error(
message != null ? message : 'Unexpected invariant triggered.',
);
}
}

View File

@@ -0,0 +1,7 @@
/**
* Returns true if the provided object implements the AsyncIterator protocol via
* implementing a `Symbol.asyncIterator` method.
*/
export declare function isAsyncIterable(
maybeAsyncIterable: any,
): maybeAsyncIterable is AsyncIterable<unknown>;

View File

@@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.isAsyncIterable = isAsyncIterable;
/**
* Returns true if the provided object implements the AsyncIterator protocol via
* implementing a `Symbol.asyncIterator` method.
*/
function isAsyncIterable(maybeAsyncIterable) {
return (
typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0
? void 0
: maybeAsyncIterable[Symbol.asyncIterator]) === 'function'
);
}

View File

@@ -0,0 +1,11 @@
/**
* Returns true if the provided object implements the AsyncIterator protocol via
* implementing a `Symbol.asyncIterator` method.
*/
export function isAsyncIterable(maybeAsyncIterable) {
return (
typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0
? void 0
: maybeAsyncIterable[Symbol.asyncIterator]) === 'function'
);
}

View File

@@ -0,0 +1,20 @@
/**
* Returns true if the provided object is an Object (i.e. not a string literal)
* and implements the Iterator protocol.
*
* This may be used in place of [Array.isArray()][isArray] to determine if
* an object should be iterated-over e.g. Array, Map, Set, Int8Array,
* TypedArray, etc. but excludes string literals.
*
* @example
* ```ts
* isIterableObject([ 1, 2, 3 ]) // true
* isIterableObject(new Map()) // true
* isIterableObject('ABC') // false
* isIterableObject({ key: 'value' }) // false
* isIterableObject({ length: 1, 0: 'Alpha' }) // false
* ```
*/
export declare function isIterableObject(
maybeIterable: any,
): maybeIterable is Iterable<unknown>;

View File

@@ -0,0 +1,32 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.isIterableObject = isIterableObject;
/**
* Returns true if the provided object is an Object (i.e. not a string literal)
* and implements the Iterator protocol.
*
* This may be used in place of [Array.isArray()][isArray] to determine if
* an object should be iterated-over e.g. Array, Map, Set, Int8Array,
* TypedArray, etc. but excludes string literals.
*
* @example
* ```ts
* isIterableObject([ 1, 2, 3 ]) // true
* isIterableObject(new Map()) // true
* isIterableObject('ABC') // false
* isIterableObject({ key: 'value' }) // false
* isIterableObject({ length: 1, 0: 'Alpha' }) // false
* ```
*/
function isIterableObject(maybeIterable) {
return (
typeof maybeIterable === 'object' &&
typeof (maybeIterable === null || maybeIterable === void 0
? void 0
: maybeIterable[Symbol.iterator]) === 'function'
);
}

View File

@@ -0,0 +1,25 @@
/**
* Returns true if the provided object is an Object (i.e. not a string literal)
* and implements the Iterator protocol.
*
* This may be used in place of [Array.isArray()][isArray] to determine if
* an object should be iterated-over e.g. Array, Map, Set, Int8Array,
* TypedArray, etc. but excludes string literals.
*
* @example
* ```ts
* isIterableObject([ 1, 2, 3 ]) // true
* isIterableObject(new Map()) // true
* isIterableObject('ABC') // false
* isIterableObject({ key: 'value' }) // false
* isIterableObject({ length: 1, 0: 'Alpha' }) // false
* ```
*/
export function isIterableObject(maybeIterable) {
return (
typeof maybeIterable === 'object' &&
typeof (maybeIterable === null || maybeIterable === void 0
? void 0
: maybeIterable[Symbol.iterator]) === 'function'
);
}

View File

@@ -0,0 +1,7 @@
/**
* 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 declare function isObjectLike(value: unknown): value is {
[key: string]: unknown;
};

View File

@@ -0,0 +1,14 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.isObjectLike = isObjectLike;
/**
* 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;
}

View File

@@ -0,0 +1,7 @@
/**
* 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 function isObjectLike(value) {
return typeof value == 'object' && value !== null;
}

View File

@@ -0,0 +1,5 @@
/**
* Returns true if the value acts like a Promise, i.e. has a "then" function,
* otherwise returns false.
*/
export declare function isPromise(value: any): value is Promise<unknown>;

View File

@@ -0,0 +1,17 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.isPromise = isPromise;
/**
* Returns true if the value acts like a Promise, i.e. has a "then" function,
* otherwise returns false.
*/
function isPromise(value) {
return (
typeof (value === null || value === void 0 ? void 0 : value.then) ===
'function'
);
}

View File

@@ -0,0 +1,10 @@
/**
* Returns true if the value acts like a Promise, i.e. has a "then" function,
* otherwise returns false.
*/
export function isPromise(value) {
return (
typeof (value === null || value === void 0 ? void 0 : value.then) ===
'function'
);
}

View File

@@ -0,0 +1,32 @@
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.
* ```ts
* const phoneBook = [
* { name: 'Jon', num: '555-1234' },
* { name: 'Jenny', num: '867-5309' }
* ]
*
* const entriesByName = keyMap(
* phoneBook,
* entry => entry.name
* )
*
* // {
* // Jon: { name: 'Jon', num: '555-1234' },
* // Jenny: { name: 'Jenny', num: '867-5309' }
* // }
*
* const jennyEntry = entriesByName['Jenny']
*
* // { name: 'Jenny', num: '857-6309' }
* ```
*/
export declare function keyMap<T>(
list: ReadonlyArray<T>,
keyFn: (item: T) => string,
): ObjMap<T>;

View File

@@ -0,0 +1,43 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.keyMap = 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.
* ```ts
* const phoneBook = [
* { name: 'Jon', num: '555-1234' },
* { name: 'Jenny', num: '867-5309' }
* ]
*
* const entriesByName = keyMap(
* phoneBook,
* entry => entry.name
* )
*
* // {
* // Jon: { name: 'Jon', num: '555-1234' },
* // Jenny: { name: 'Jenny', num: '867-5309' }
* // }
*
* const jennyEntry = entriesByName['Jenny']
*
* // { name: 'Jenny', num: '857-6309' }
* ```
*/
function keyMap(list, keyFn) {
const result = Object.create(null);
for (const item of list) {
result[keyFn(item)] = item;
}
return result;
}

View File

@@ -0,0 +1,36 @@
/**
* 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.
* ```ts
* const phoneBook = [
* { name: 'Jon', num: '555-1234' },
* { name: 'Jenny', num: '867-5309' }
* ]
*
* const entriesByName = keyMap(
* phoneBook,
* entry => entry.name
* )
*
* // {
* // Jon: { name: 'Jon', num: '555-1234' },
* // Jenny: { name: 'Jenny', num: '867-5309' }
* // }
*
* const jennyEntry = entriesByName['Jenny']
*
* // { name: 'Jenny', num: '857-6309' }
* ```
*/
export function keyMap(list, keyFn) {
const result = Object.create(null);
for (const item of list) {
result[keyFn(item)] = item;
}
return result;
}

View File

@@ -0,0 +1,23 @@
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.
* ```ts
* 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 declare function keyValMap<T, V>(
list: ReadonlyArray<T>,
keyFn: (item: T) => string,
valFn: (item: T) => V,
): ObjMap<V>;

View File

@@ -0,0 +1,33 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.keyValMap = 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.
* ```ts
* 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) {
const result = Object.create(null);
for (const item of list) {
result[keyFn(item)] = valFn(item);
}
return result;
}

View File

@@ -0,0 +1,26 @@
/**
* 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.
* ```ts
* 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 function keyValMap(list, keyFn, valFn) {
const result = Object.create(null);
for (const item of list) {
result[keyFn(item)] = valFn(item);
}
return result;
}

View File

@@ -0,0 +1,9 @@
import type { ObjMap, ReadOnlyObjMap } from './ObjMap';
/**
* Creates an object map with the same keys as `map` and values generated by
* running each value of `map` thru `fn`.
*/
export declare function mapValue<T, V>(
map: ReadOnlyObjMap<T>,
fn: (value: T, key: string) => V,
): ObjMap<V>;

View File

@@ -0,0 +1,20 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.mapValue = mapValue;
/**
* 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) {
const result = Object.create(null);
for (const key of Object.keys(map)) {
result[key] = fn(map[key], key);
}
return result;
}

View File

@@ -0,0 +1,13 @@
/**
* Creates an object map with the same keys as `map` and values generated by
* running each value of `map` thru `fn`.
*/
export function mapValue(map, fn) {
const result = Object.create(null);
for (const key of Object.keys(map)) {
result[key] = fn(map[key], key);
}
return result;
}

View File

@@ -0,0 +1,9 @@
/**
* Memoizes the provided three-argument function.
*/
export declare function memoize3<
A1 extends object,
A2 extends object,
A3 extends object,
R,
>(fn: (a1: A1, a2: A2, a3: A3) => R): (a1: A1, a2: A2, a3: A3) => R;

View File

@@ -0,0 +1,41 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.memoize3 = memoize3;
/**
* Memoizes the provided three-argument function.
*/
function memoize3(fn) {
let cache0;
return function memoized(a1, a2, a3) {
if (cache0 === undefined) {
cache0 = new WeakMap();
}
let cache1 = cache0.get(a1);
if (cache1 === undefined) {
cache1 = new WeakMap();
cache0.set(a1, cache1);
}
let cache2 = cache1.get(a2);
if (cache2 === undefined) {
cache2 = new WeakMap();
cache1.set(a2, cache2);
}
let fnResult = cache2.get(a3);
if (fnResult === undefined) {
fnResult = fn(a1, a2, a3);
cache2.set(a3, fnResult);
}
return fnResult;
};
}

View File

@@ -0,0 +1,34 @@
/**
* Memoizes the provided three-argument function.
*/
export function memoize3(fn) {
let cache0;
return function memoized(a1, a2, a3) {
if (cache0 === undefined) {
cache0 = new WeakMap();
}
let cache1 = cache0.get(a1);
if (cache1 === undefined) {
cache1 = new WeakMap();
cache0.set(a1, cache1);
}
let cache2 = cache1.get(a2);
if (cache2 === undefined) {
cache2 = new WeakMap();
cache1.set(a2, cache2);
}
let fnResult = cache2.get(a3);
if (fnResult === undefined) {
fnResult = fn(a1, a2, a3);
cache2.set(a3, fnResult);
}
return fnResult;
};
}

View File

@@ -0,0 +1,8 @@
/**
* 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 declare function naturalCompare(aStr: string, bStr: string): number;

View File

@@ -0,0 +1,69 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.naturalCompare = 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) {
let aIndex = 0;
let bIndex = 0;
while (aIndex < aStr.length && bIndex < bStr.length) {
let aChar = aStr.charCodeAt(aIndex);
let bChar = bStr.charCodeAt(bIndex);
if (isDigit(aChar) && isDigit(bChar)) {
let aNum = 0;
do {
++aIndex;
aNum = aNum * 10 + aChar - DIGIT_0;
aChar = aStr.charCodeAt(aIndex);
} while (isDigit(aChar) && aNum > 0);
let bNum = 0;
do {
++bIndex;
bNum = bNum * 10 + bChar - DIGIT_0;
bChar = bStr.charCodeAt(bIndex);
} 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;
}
++aIndex;
++bIndex;
}
}
return aStr.length - bStr.length;
}
const DIGIT_0 = 48;
const DIGIT_9 = 57;
function isDigit(code) {
return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9;
}

View File

@@ -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 function naturalCompare(aStr, bStr) {
let aIndex = 0;
let bIndex = 0;
while (aIndex < aStr.length && bIndex < bStr.length) {
let aChar = aStr.charCodeAt(aIndex);
let bChar = bStr.charCodeAt(bIndex);
if (isDigit(aChar) && isDigit(bChar)) {
let aNum = 0;
do {
++aIndex;
aNum = aNum * 10 + aChar - DIGIT_0;
aChar = aStr.charCodeAt(aIndex);
} while (isDigit(aChar) && aNum > 0);
let bNum = 0;
do {
++bIndex;
bNum = bNum * 10 + bChar - DIGIT_0;
bChar = bStr.charCodeAt(bIndex);
} 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;
}
++aIndex;
++bIndex;
}
}
return aStr.length - bStr.length;
}
const DIGIT_0 = 48;
const DIGIT_9 = 57;
function isDigit(code) {
return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9;
}

View File

@@ -0,0 +1,6 @@
/**
* Build a string describing the path.
*/
export declare function printPathArray(
path: ReadonlyArray<string | number>,
): string;

Some files were not shown because too many files have changed in this diff Show More