diff --git a/@types/index.d.ts b/@types/index.d.ts deleted file mode 100644 index 5fdc1fe..0000000 --- a/@types/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -declare module "@grapher" { - export interface GrapherQuery {} -} diff --git a/@types/src/index.d.ts b/@types/src/index.d.ts new file mode 100644 index 0000000..96dcecf --- /dev/null +++ b/@types/src/index.d.ts @@ -0,0 +1,132 @@ +/** @format */ + +/// + +declare module 'meteor/cultofcoders:grapher' { + import { Mongo } from 'meteor/mongo' + import { DocumentNode } from 'graphql' + + module Grapher { + type TypesEnum = 'one' | 'many' + + interface Query { + setParams(): any + resolve(): any + expose(): any + } // WIP + + interface ILink { + collection: Mongo.Collection + type: TypesEnum + metadata?: true + field: string + index?: boolean + denormalize?: iDenormalize + } + + interface ILink { + collection: Mongo.Collection + inversedBy: string + denormalize?: iDenormalize + } + + type Link = { + [field: string]: ILink + } + + type QueryOptions = { + $filter?: Mongo.FieldExpression + } + type Body = { + [field: string]: DependencyGraph | Body | QueryOptions + } + type createQuery = ( + name: string, + body: Body | {}, + options?: {} + ) => any + + type QueryBody = Body + + type BodyEnum = 0 | 1 + + type GrapherBody = TSchema extends object + ? SelectionSet> + : SelectionSet + + type TEmbodyArgs = { + body: GrapherBody + getArgs(): TArgs + } + + type DependencyGraph = { + [field: string]: GrapherBody | DependencyGraph + } + + type TFirewall = ( + filters: TFilters, + options: TOptions, + userId: string + ) => void + + interface SelectionSet { + [field: string]: BodyType + } + interface iDenormalize { + field: string + body: { + [field: string]: number + } + } + + interface GraphQLQuery { + embody?: (transform: TEmbodyArgs) => void + $filter?: Mongo.Selector + $options?: Mongo.Options + // Integer + maxDepth?: number + // Integer + maxLimit?: number + deny?: string[] + intersect?: GrapherBody + } + + interface Exposure { + firewall?: TFirewall | TFirewall[] + publication?: boolean // Boolean + method?: boolean // Boolean + blocking?: boolean // Boolean + maxLimit?: number // Number + maxDepth?: number // Number + restrictedFields?: string[] // [String] + restrictLinks?: string[] | ((...args: any[]) => any) // [String] or Function, + } + + interface ASTToQueryOptions { + maxLimit: number + maxDepth: number + } + } + + export function setAstToQueryDefaults( + options: Grapher.ASTToQueryOptions + ): void + + export const db: Readonly<{ + [key: string]: Mongo.CollectionStatic + }> + + export class MemoryResultCacher { + constructor({ ttl }: { ttl: number }) + + public fetch( + cacheId: string, + options: { + query: any + countCursor: any + } + ): TResult + + public storeData(cacheId: string, data: T): void + } +} diff --git a/@types/src/mongo/index.d.ts b/@types/src/mongo/index.d.ts new file mode 100644 index 0000000..f5514d4 --- /dev/null +++ b/@types/src/mongo/index.d.ts @@ -0,0 +1,29 @@ +import { Grapher } from 'meteor/cultofcoders:grapher' +import { Mongo } from 'meteor/mongo' +import { DocumentNode } from 'graphql' + +declare module 'meteor/mongo' { + module Mongo { + interface Options {} + + interface Collection { + attachSchema(schema: T): void + astToQuery( + ast: DocumentNode, + query: Grapher.GraphQLQuery + ): Mongo.Cursor + createQuery( + name: string, + body: Grapher.Body | {}, + options?: {} + ): Grapher.Query + createQuery( + body: Grapher.Body | {}, + options?: {} + ): Grapher.Query + expose: Grapher.Exposure + addLinks(links: Grapher.Link): void + addReducers(): void + } + } +} diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..259307a --- /dev/null +++ b/index.ts @@ -0,0 +1,5 @@ +/// + +import { db } from "meteor/cultofcoders:grapher"; + +db.stress = 8 \ No newline at end of file diff --git a/index.d.ts b/mongo.d.ts similarity index 68% rename from index.d.ts rename to mongo.d.ts index 3b4dd79..7cd6da9 100644 --- a/index.d.ts +++ b/mongo.d.ts @@ -1,13 +1,7 @@ -/// - import { GrapherQuery } from "@grapher"; import { Mongo } from "meteor/mongo"; import { DocumentNode } from "graphql"; -declare module "meteor/cultofcoders:grapher" { - export * from "@grapher"; -} - declare module "meteor/mongo" { export interface Collection { astToQuery(ast: DocumentNode, query: GrapherQuery): Mongo.Cursor; diff --git a/node_modules/@types/connect/LICENSE b/node_modules/@types/connect/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/node_modules/@types/connect/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/connect/README.md b/node_modules/@types/connect/README.md new file mode 100644 index 0000000..88b7569 --- /dev/null +++ b/node_modules/@types/connect/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/connect` + +# Summary +This package contains type definitions for connect (https://github.com/senchalabs/connect). + +# Details +Files were exported from https://www.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/connect + +Additional Details + * Last updated: Tue, 17 Apr 2018 01:01:05 GMT + * Dependencies: http, node + * Global values: none + +# Credits +These definitions were written by Maxime LUCE , Evan Hahn . diff --git a/node_modules/@types/connect/index.d.ts b/node_modules/@types/connect/index.d.ts new file mode 100644 index 0000000..a6eed0c --- /dev/null +++ b/node_modules/@types/connect/index.d.ts @@ -0,0 +1,94 @@ +// Type definitions for connect v3.4.0 +// Project: https://github.com/senchalabs/connect +// Definitions by: Maxime LUCE +// Evan Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import * as http from "http"; + +/** + * Create a new connect server. + * @public + */ +declare function createServer(): createServer.Server; + +declare namespace createServer { + export type ServerHandle = HandleFunction | http.Server; + + type NextFunction = (err?: any) => void; + + export type SimpleHandleFunction = (req: http.IncomingMessage, res: http.ServerResponse) => void; + export type NextHandleFunction = (req: http.IncomingMessage, res: http.ServerResponse, next: NextFunction) => void; + export type ErrorHandleFunction = (err: any, req: http.IncomingMessage, res: http.ServerResponse, next: NextFunction) => void; + export type HandleFunction = SimpleHandleFunction | NextHandleFunction | ErrorHandleFunction; + + export interface ServerStackItem { + route: string; + handle: ServerHandle; + } + + export interface Server extends NodeJS.EventEmitter { + (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void; + + route: string; + stack: ServerStackItem[]; + + /** + * Utilize the given middleware `handle` to the given `route`, + * defaulting to _/_. This "route" is the mount-point for the + * middleware, when given a value other than _/_ the middleware + * is only effective when that segment is present in the request's + * pathname. + * + * For example if we were to mount a function at _/admin_, it would + * be invoked on _/admin_, and _/admin/settings_, however it would + * not be invoked for _/_, or _/posts_. + * + * @public + */ + use(fn: HandleFunction): Server; + use(route: string, fn: HandleFunction): Server; + + /** + * Handle server requests, punting them down + * the middleware stack. + * + * @private + */ + handle(req: http.IncomingMessage, res: http.ServerResponse, next: Function): void; + + /** + * Listen for connections. + * + * This method takes the same arguments + * as node's `http.Server#listen()`. + * + * HTTP and HTTPS: + * + * If you run your application both as HTTP + * and HTTPS you may wrap them individually, + * since your Connect "server" is really just + * a JavaScript `Function`. + * + * var connect = require('connect') + * , http = require('http') + * , https = require('https'); + * + * var app = connect(); + * + * http.createServer(app).listen(80); + * https.createServer(options, app).listen(443); + * + * @api public + */ + listen(port: number, hostname?: string, backlog?: number, callback?: Function): http.Server; + listen(port: number, hostname?: string, callback?: Function): http.Server; + listen(path: string, callback?: Function): http.Server; + listen(handle: any, listeningListener?: Function): http.Server; + } +} + +export = createServer; diff --git a/node_modules/@types/graphql/LICENSE b/node_modules/@types/graphql/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/node_modules/@types/graphql/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/graphql/README.md b/node_modules/@types/graphql/README.md new file mode 100644 index 0000000..be5b639 --- /dev/null +++ b/node_modules/@types/graphql/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/graphql` + +# Summary +This package contains type definitions for graphql (https://www.npmjs.com/package/graphql). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/graphql + +Additional Details + * Last updated: Wed, 05 Sep 2018 16:29:25 GMT + * Dependencies: none + * Global values: none + +# Credits +These definitions were written by TonyYang , Caleb Meredith , Dominic Watson , Firede , Kepennar , Mikhail Novikov , Ivan Goncharov , Hagai Cohen , Ricardo Portugal , Tim Griesser , Dylan Stewart , Alessio Dionisi , Divyendu Singh , Brad Zacher , Curtis Layne . diff --git a/node_modules/@types/graphql/error/GraphQLError.d.ts b/node_modules/@types/graphql/error/GraphQLError.d.ts new file mode 100644 index 0000000..de97686 --- /dev/null +++ b/node_modules/@types/graphql/error/GraphQLError.d.ts @@ -0,0 +1,78 @@ +import Maybe from "../tsutils/Maybe"; +import { getLocation } from "../language"; +import { ASTNode } from "../language/ast"; +import { Source } from "../language/source"; +import { SourceLocation } from "../language/location"; + +/** + * 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 { + /** + * A message describing the Error for debugging purposes. + * + * Enumerable, and appears in the result of JSON.stringify(). + * + * Note: should be treated as readonly, despite invariant usage. + */ + message: string; + + /** + * 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 | 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 | undefined; + + /** + * An array of GraphQL AST Nodes corresponding to this error. + */ + readonly nodes: ReadonlyArray | undefined; + + /** + * The source GraphQL document corresponding to this error. + */ + readonly source: Source | undefined; + + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + readonly positions: ReadonlyArray | undefined; + + /** + * The original error thrown from a field resolver during execution. + */ + readonly originalError: Maybe & { readonly extensions: any }; + + /** + * Extension fields to add to the formatted error. + */ + readonly extensions: { [key: string]: any } | undefined; + + constructor( + message: string, + nodes?: ReadonlyArray | ASTNode | undefined, + source?: Maybe, + positions?: Maybe>, + path?: Maybe>, + originalError?: Maybe, + extensions?: Maybe<{ [key: string]: any }> + ); +} diff --git a/node_modules/@types/graphql/error/formatError.d.ts b/node_modules/@types/graphql/error/formatError.d.ts new file mode 100644 index 0000000..5930c02 --- /dev/null +++ b/node_modules/@types/graphql/error/formatError.d.ts @@ -0,0 +1,15 @@ +import { GraphQLError } from "./GraphQLError"; +import { SourceLocation } from "../language/location"; + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +export function formatError(error: GraphQLError): GraphQLFormattedError; + +export interface GraphQLFormattedError { + readonly message: string; + readonly locations: ReadonlyArray | undefined; + readonly path: ReadonlyArray | undefined; + readonly extensions?: { [key: string]: any }; +} diff --git a/node_modules/@types/graphql/error/index.d.ts b/node_modules/@types/graphql/error/index.d.ts new file mode 100644 index 0000000..ad00270 --- /dev/null +++ b/node_modules/@types/graphql/error/index.d.ts @@ -0,0 +1,5 @@ +export { GraphQLError } from "./GraphQLError"; +export { syntaxError } from "./syntaxError"; +export { locatedError } from "./locatedError"; +export { printError } from "./printError"; +export { formatError, GraphQLFormattedError } from "./formatError"; diff --git a/node_modules/@types/graphql/error/locatedError.d.ts b/node_modules/@types/graphql/error/locatedError.d.ts new file mode 100644 index 0000000..da366f6 --- /dev/null +++ b/node_modules/@types/graphql/error/locatedError.d.ts @@ -0,0 +1,13 @@ +import { GraphQLError } from "./GraphQLError"; +import { ASTNode } from "../language/ast"; + +/** + * Given an arbitrary Error, 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( + originalError: Error | GraphQLError, + nodes: ReadonlyArray, + path: ReadonlyArray +): GraphQLError; diff --git a/node_modules/@types/graphql/error/printError.d.ts b/node_modules/@types/graphql/error/printError.d.ts new file mode 100644 index 0000000..2d1758e --- /dev/null +++ b/node_modules/@types/graphql/error/printError.d.ts @@ -0,0 +1,7 @@ +import { GraphQLError } from "./GraphQLError"; + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + */ +export function printError(error: GraphQLError): string; diff --git a/node_modules/@types/graphql/error/syntaxError.d.ts b/node_modules/@types/graphql/error/syntaxError.d.ts new file mode 100644 index 0000000..e3756a6 --- /dev/null +++ b/node_modules/@types/graphql/error/syntaxError.d.ts @@ -0,0 +1,8 @@ +import { Source } from "../language/source"; +import { GraphQLError } from "./GraphQLError"; + +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ +export function syntaxError(source: Source, position: number, description: string): GraphQLError; diff --git a/node_modules/@types/graphql/execution/execute.d.ts b/node_modules/@types/graphql/execution/execute.d.ts new file mode 100644 index 0000000..0427a25 --- /dev/null +++ b/node_modules/@types/graphql/execution/execute.d.ts @@ -0,0 +1,185 @@ +import Maybe from "../tsutils/Maybe"; +import { GraphQLError, locatedError } from "../error"; +import { GraphQLSchema } from "../type/schema"; +import { + GraphQLField, + GraphQLFieldResolver, + ResponsePath, + GraphQLObjectType, + GraphQLResolveInfo, +} from "../type/definition"; +import { + DirectiveNode, + DocumentNode, + OperationDefinitionNode, + SelectionSetNode, + FieldNode, + InlineFragmentNode, + FragmentDefinitionNode, +} from "../language/ast"; +import { MaybePromise } from "../jsutils/MaybePromise"; + +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + */ +export interface ExecutionContext { + schema: GraphQLSchema; + fragments: { [key: string]: FragmentDefinitionNode }; + rootValue: any; + contextValue: any; + operation: OperationDefinitionNode; + variableValues: { [key: string]: any }; + fieldResolver: GraphQLFieldResolver; + errors: GraphQLError[]; +} + +export interface ExecutionResultDataDefault { + [key: string]: any +} + +/** + * 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. + */ +export interface ExecutionResult { + errors?: ReadonlyArray; + data?: TData; +} + +export type ExecutionArgs = { + schema: GraphQLSchema; + document: DocumentNode; + rootValue?: any; + contextValue?: any; + variableValues?: Maybe<{ [key: string]: any }>; + operationName?: Maybe; + fieldResolver?: Maybe>; +}; + +/** + * Implements the "Evaluating requests" section of the GraphQL specification. + * + * Returns either a synchronous ExecutionResult (if all encountered resolvers + * are synchronous), or a Promise of an ExecutionResult that will eventually be + * resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + * + * Accepts either an object with named arguments, or individual arguments. + */ +export function execute(args: ExecutionArgs): MaybePromise>; +export function execute( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: any, + contextValue?: any, + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe> +): MaybePromise>; + +/** + * Given a ResponsePath (found in the `path` entry in the information provided + * as the last argument to a field resolver), return an Array of the path keys. + */ +export function responsePathAsArray(path: ResponsePath): ReadonlyArray; + +/** + * Given a ResponsePath and a key, return a new ResponsePath containing the + * new key. + + */ +export function addPath( + prev: ResponsePath | undefined, + key: string | number +): { prev: ResponsePath | undefined; key: string | number }; + +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + */ +export function assertValidExecutionArguments( + schema: GraphQLSchema, + document: DocumentNode, + rawVariableValues: Maybe<{ [key: string]: any }> +): void; + +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + */ +export function buildExecutionContext( + schema: GraphQLSchema, + document: DocumentNode, + rootValue: any, + contextValue: any, + rawVariableValues: Maybe<{ [key: string]: any }>, + operationName: Maybe, + fieldResolver: Maybe> +): ReadonlyArray | ExecutionContext; + +/** + * Given a selectionSet, adds all of the fields in that selection to + * the passed in map of fields, and returns it at the end. + * + * CollectFields requires the "runtime type" of an object. For a field which + * returns an Interface or Union type, the "runtime type" will be the actual + * Object type returned by that field. + */ +export function collectFields( + exeContext: ExecutionContext, + runtimeType: GraphQLObjectType, + selectionSet: SelectionSetNode, + fields: { [key: string]: Array }, + visitedFragmentNames: { [key: string]: boolean } +): { [key: string]: Array }; + +export function buildResolveInfo( + exeContext: ExecutionContext, + fieldDef: GraphQLField, + fieldNodes: ReadonlyArray, + parentType: GraphQLObjectType, + path: ResponsePath +): GraphQLResolveInfo; + +// Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField` +// function. Returns the result of resolveFn or the abrupt-return Error object. +export function resolveFieldValueOrError( + exeContext: ExecutionContext, + fieldDef: GraphQLField, + fieldNodes: ReadonlyArray, + resolveFn: GraphQLFieldResolver, + source: TSource, + info: GraphQLResolveInfo +): Error | any; + +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context. + */ +export const defaultFieldResolver: GraphQLFieldResolver; + +/** + * This method looks up the field on the given type defintion. + * It has special casing for the two introspection fields, __schema + * and __typename. __typename is special because it can always be + * queried as a field, even in situations where no other fields + * are allowed, like on a Union. __schema could get automatically + * added to the query type, but that would require mutating type + * definitions, which would cause issues. + */ +export function getFieldDef( + schema: GraphQLSchema, + parentType: GraphQLObjectType, + fieldName: string +): Maybe>; diff --git a/node_modules/@types/graphql/execution/index.d.ts b/node_modules/@types/graphql/execution/index.d.ts new file mode 100644 index 0000000..333c271 --- /dev/null +++ b/node_modules/@types/graphql/execution/index.d.ts @@ -0,0 +1,3 @@ +export { execute, defaultFieldResolver, responsePathAsArray, ExecutionArgs, ExecutionResult } from "./execute"; + +export { getDirectiveValues } from "./values"; diff --git a/node_modules/@types/graphql/execution/values.d.ts b/node_modules/@types/graphql/execution/values.d.ts new file mode 100644 index 0000000..61e0408 --- /dev/null +++ b/node_modules/@types/graphql/execution/values.d.ts @@ -0,0 +1,59 @@ +import Maybe from "../tsutils/Maybe"; +import { GraphQLError } from "../error/GraphQLError"; +import { GraphQLInputType, GraphQLField, GraphQLArgument } from "../type/definition"; +import { GraphQLDirective } from "../type/directives"; +import { GraphQLSchema } from "../type/schema"; +import { FieldNode, DirectiveNode, VariableDefinitionNode } from "../language/ast"; + +interface CoercedVariableValues { + errors: ReadonlyArray | undefined; + coerced: { [key: string]: any } | undefined; +} + +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getVariableValues( + schema: GraphQLSchema, + varDefNodes: VariableDefinitionNode[], + inputs: { [key: string]: any } +): CoercedVariableValues; + +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getArgumentValues( + def: GraphQLField | GraphQLDirective, + node: FieldNode | DirectiveNode, + variableValues?: Maybe<{ [key: string]: any }> +): { [key: string]: any }; + +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getDirectiveValues( + directiveDef: GraphQLDirective, + node: { + readonly directives?: ReadonlyArray; + }, + variableValues?: Maybe<{ [key: string]: any }> +): undefined | { [key: string]: any }; diff --git a/node_modules/@types/graphql/graphql.d.ts b/node_modules/@types/graphql/graphql.d.ts new file mode 100644 index 0000000..2556269 --- /dev/null +++ b/node_modules/@types/graphql/graphql.d.ts @@ -0,0 +1,78 @@ +import Maybe from "./tsutils/Maybe"; +import { Source } from "./language/source"; +import { GraphQLFieldResolver } from "./type/definition"; +import { GraphQLSchema } from "./type/schema"; +import { ExecutionResult, ExecutionResultDataDefault } from "./execution/execute"; + +/** + * This is the primary entry point function for fulfilling GraphQL operations + * by parsing, validating, and executing a GraphQL document along side a + * GraphQL schema. + * + * More sophisticated GraphQL servers, such as those which persist queries, + * may wish to separate the validation and execution phases to a static time + * tooling step, and a server runtime step. + * + * Accepts either an object with named arguments, or individual arguments: + * + * schema: + * The GraphQL type system to use when validating and executing a query. + * source: + * A GraphQL language formatted string representing the requested operation. + * rootValue: + * The value provided as the first argument to resolver functions on the top + * level type (e.g. the query object type). + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. + * variableValues: + * A mapping of variable name to runtime value to use for all variables + * defined in the requestString. + * operationName: + * The name of the operation to use if requestString contains multiple + * possible operations. Can be omitted if requestString contains only + * one operation. + * fieldResolver: + * A resolver function to use when one is not provided by the schema. + * If not provided, the default field resolver is used (which looks for a + * value or method on the source value with the field's name). + */ +export interface GraphQLArgs { + schema: GraphQLSchema; + source: Source | string; + rootValue?: any; + contextValue?: any; + variableValues?: Maybe<{ [key: string]: any }>; + operationName?: Maybe; + fieldResolver?: Maybe>; +} + +export function graphql(args: GraphQLArgs): Promise>; +export function graphql( + schema: GraphQLSchema, + source: Source | string, + rootValue?: any, + contextValue?: any, + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe> +): Promise>; + +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ +export function graphqlSync(args: GraphQLArgs): ExecutionResult; +export function graphqlSync( + schema: GraphQLSchema, + source: Source | string, + rootValue?: any, + contextValue?: any, + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe> +): ExecutionResult; diff --git a/node_modules/@types/graphql/index.d.ts b/node_modules/@types/graphql/index.d.ts new file mode 100644 index 0000000..97f2374 --- /dev/null +++ b/node_modules/@types/graphql/index.d.ts @@ -0,0 +1,406 @@ +// Type definitions for graphql 14.0 +// Project: https://www.npmjs.com/package/graphql +// Definitions by: TonyYang +// Caleb Meredith +// Dominic Watson +// Firede +// Kepennar +// Mikhail Novikov +// Ivan Goncharov +// Hagai Cohen +// Ricardo Portugal +// Tim Griesser +// Dylan Stewart +// Alessio Dionisi +// Divyendu Singh +// Brad Zacher +// Curtis Layne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +// The primary entry point into fulfilling a GraphQL request. +export { graphql, graphqlSync, GraphQLArgs } from "./graphql"; + +// Create and operate on GraphQL type definitions and schema. +export { + GraphQLSchema, + // Definitions + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, + GraphQLDirective, + // "Enum" of Type Kinds + TypeKind, + // Scalars + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, + // Built-in Directives defined by the Spec + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, + // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, + // GraphQL Types for introspection. + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + // 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 + 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, + // type + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + Thunk, + GraphQLSchemaConfig, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLEnumTypeConfig, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueConfigMap, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldConfigMap, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInterfaceTypeConfig, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLResolveInfo, + ResponsePath, + GraphQLScalarTypeConfig, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLDirectiveConfig, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from "./type"; + +// Parse and operate on GraphQL language source files. +export { + Source, + getLocation, + // Parse + parse, + parseValue, + parseType, + // Print + print, + // Visit + visit, + visitInParallel, + visitWithTypeInfo, + getVisitFn, + Kind, + TokenKind, + DirectiveLocation, + BREAK, + // Predicates + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, + // type + Lexer, + ParseOptions, + SourceLocation, + // Visitor utilities + ASTVisitor, + Visitor, + VisitFn, + VisitorKeyMap, + // AST nodes + Location, + Token, + ASTNode, + ASTKindToNode, + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, + KindEnum, + TokenKindEnum, + DirectiveLocationEnum, +} from "./language"; + +// Execute GraphQL queries. +export { + execute, + defaultFieldResolver, + responsePathAsArray, + getDirectiveValues, + // type + ExecutionArgs, + ExecutionResult, +} from "./execution"; + +export { subscribe, createSourceEventStream } from "./subscription"; + +// Validate GraphQL queries. +export { + validate, + ValidationContext, + // All validation rules in the GraphQL Specification. + specifiedRules, + // Individual validation rules. + 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, +} from "./validation"; + +// Create and format GraphQL errors. +export { GraphQLError, formatError, printError, GraphQLFormattedError } from "./error"; + +// 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, + // @deprecated: use getIntrospectionQuery - will be removed in v15 + introspectionQuery, + // Gets the target Operation from a Document + getOperationAST, + // Gets the Type for the target Operation AST. + getOperationRootType, + // Convert a GraphQLSchema to an IntrospectionQuery + introspectionFromSchema, + // Build a GraphQLSchema from an introspection result. + buildClientSchema, + // Build a GraphQLSchema from a parsed GraphQL Schema language AST. + buildASTSchema, + // Build a GraphQLSchema from a GraphQL schema language document. + buildSchema, + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16 + getDescription, + // Extends an existing GraphQLSchema from a parsed GraphQL Schema + // language AST. + extendSchema, + // Sort a GraphQLSchema. + lexicographicSortSchema, + // Print a GraphQLSchema to GraphQL Schema language. + printSchema, + // Prints the built-in introspection schema in the Schema Language + // format. + printIntrospectionSchema, + // Print a GraphQLType to GraphQL Schema language. + printType, + // 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, + // Coerces a JavaScript value to a GraphQL type, or produces errors. + coerceValue, + // @deprecated use coerceValue - will be removed in v15 + isValidJSValue, + // @deprecated use validation - will be removed in v15 + isValidLiteralValue, + // Concatenates multiple AST together. + concatAST, + // Separates an AST into an AST per Operation. + separateOperations, + // 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. + findBreakingChanges, + findDangerousChanges, + BreakingChangeType, + DangerousChangeType, + // Report all deprecated usage within a GraphQL document. + findDeprecatedUsages, + // type + BuildSchemaOptions, + BreakingChange, + DangerousChange, + IntrospectionOptions, + IntrospectionDirective, + IntrospectionEnumType, + IntrospectionEnumValue, + IntrospectionField, + IntrospectionInputObjectType, + IntrospectionInputType, + IntrospectionInputTypeRef, + IntrospectionInputValue, + IntrospectionInterfaceType, + IntrospectionListTypeRef, + IntrospectionNamedTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionObjectType, + IntrospectionOutputType, + IntrospectionOutputTypeRef, + IntrospectionQuery, + IntrospectionScalarType, + IntrospectionSchema, + IntrospectionType, + IntrospectionTypeRef, + IntrospectionUnionType, +} from "./utilities"; diff --git a/node_modules/@types/graphql/jsutils/MaybePromise.d.ts b/node_modules/@types/graphql/jsutils/MaybePromise.d.ts new file mode 100644 index 0000000..78e029c --- /dev/null +++ b/node_modules/@types/graphql/jsutils/MaybePromise.d.ts @@ -0,0 +1 @@ +export type MaybePromise = Promise | T; diff --git a/node_modules/@types/graphql/language/ast.d.ts b/node_modules/@types/graphql/language/ast.d.ts new file mode 100644 index 0000000..42a98ef --- /dev/null +++ b/node_modules/@types/graphql/language/ast.d.ts @@ -0,0 +1,564 @@ +import { Source } from "./source"; +import { TokenKindEnum } from "./lexer"; + +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +export interface Location { + /** + * The character offset at which this Node begins. + */ + readonly start: number; + + /** + * The character offset at which this Node ends. + */ + readonly end: number; + + /** + * The Token at which this Node begins. + */ + readonly startToken: Token; + + /** + * The Token at which this Node ends. + */ + readonly endToken: Token; + + /** + * The Source document the AST represents. + */ + readonly source: Source; +} + +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ +export interface Token { + /** + * The kind of Token. + */ + readonly kind: TokenKindEnum; + + /** + * The character offset at which this Node begins. + */ + readonly start: number; + + /** + * The character offset at which this Node ends. + */ + readonly end: number; + + /** + * The 1-indexed line number on which this Token appears. + */ + readonly line: number; + + /** + * The 1-indexed column number at which this Token begins. + */ + readonly column: number; + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + */ + readonly value: string | undefined; + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. is always the first node and + * the last. + */ + readonly prev: Token | null; + readonly next: Token | null; +} + +/** + * The list of all possible AST node types. + */ +export type ASTNode = + | NameNode + | DocumentNode + | OperationDefinitionNode + | VariableDefinitionNode + | VariableNode + | SelectionSetNode + | FieldNode + | ArgumentNode + | FragmentSpreadNode + | InlineFragmentNode + | FragmentDefinitionNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode + | ObjectFieldNode + | DirectiveNode + | NamedTypeNode + | ListTypeNode + | NonNullTypeNode + | SchemaDefinitionNode + | OperationTypeDefinitionNode + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | FieldDefinitionNode + | InputValueDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | EnumValueDefinitionNode + | InputObjectTypeDefinitionNode + | DirectiveDefinitionNode + | SchemaExtensionNode + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode; + +/** + * Utility type listing all nodes indexed by their kind. + */ +export interface ASTKindToNode { + Name: NameNode; + Document: DocumentNode; + OperationDefinition: OperationDefinitionNode; + VariableDefinition: VariableDefinitionNode; + Variable: VariableNode; + SelectionSet: SelectionSetNode; + Field: FieldNode; + Argument: ArgumentNode; + FragmentSpread: FragmentSpreadNode; + InlineFragment: InlineFragmentNode; + FragmentDefinition: FragmentDefinitionNode; + IntValue: IntValueNode; + FloatValue: FloatValueNode; + StringValue: StringValueNode; + BooleanValue: BooleanValueNode; + NullValue: NullValueNode; + EnumValue: EnumValueNode; + ListValue: ListValueNode; + ObjectValue: ObjectValueNode; + ObjectField: ObjectFieldNode; + Directive: DirectiveNode; + NamedType: NamedTypeNode; + ListType: ListTypeNode; + NonNullType: NonNullTypeNode; + SchemaDefinition: SchemaDefinitionNode; + OperationTypeDefinition: OperationTypeDefinitionNode; + ScalarTypeDefinition: ScalarTypeDefinitionNode; + ObjectTypeDefinition: ObjectTypeDefinitionNode; + FieldDefinition: FieldDefinitionNode; + InputValueDefinition: InputValueDefinitionNode; + InterfaceTypeDefinition: InterfaceTypeDefinitionNode; + UnionTypeDefinition: UnionTypeDefinitionNode; + EnumTypeDefinition: EnumTypeDefinitionNode; + EnumValueDefinition: EnumValueDefinitionNode; + InputObjectTypeDefinition: InputObjectTypeDefinitionNode; + DirectiveDefinition: DirectiveDefinitionNode; + SchemaExtension: SchemaExtensionNode; + ScalarTypeExtension: ScalarTypeExtensionNode; + ObjectTypeExtension: ObjectTypeExtensionNode; + InterfaceTypeExtension: InterfaceTypeExtensionNode; + UnionTypeExtension: UnionTypeExtensionNode; + EnumTypeExtension: EnumTypeExtensionNode; + InputObjectTypeExtension: InputObjectTypeExtensionNode; +} + +// Name + +export interface NameNode { + readonly kind: "Name"; + readonly loc?: Location; + readonly value: string; +} + +// Document + +export interface DocumentNode { + readonly kind: "Document"; + readonly loc?: Location; + readonly definitions: ReadonlyArray; +} + +export type DefinitionNode = ExecutableDefinitionNode | TypeSystemDefinitionNode | TypeSystemExtensionNode; + +export type ExecutableDefinitionNode = OperationDefinitionNode | FragmentDefinitionNode; + +export interface OperationDefinitionNode { + readonly kind: "OperationDefinition"; + readonly loc?: Location; + readonly operation: OperationTypeNode; + readonly name?: NameNode; + readonly variableDefinitions?: ReadonlyArray; + readonly directives?: ReadonlyArray; + readonly selectionSet: SelectionSetNode; +} + +export type OperationTypeNode = "query" | "mutation" | "subscription"; + +export interface VariableDefinitionNode { + readonly kind: "VariableDefinition"; + readonly loc?: Location; + readonly variable: VariableNode; + readonly type: TypeNode; + readonly defaultValue?: ValueNode; + readonly directives?: ReadonlyArray; +} + +export interface VariableNode { + readonly kind: "Variable"; + readonly loc?: Location; + readonly name: NameNode; +} + +export interface SelectionSetNode { + kind: "SelectionSet"; + loc?: Location; + selections: ReadonlyArray; +} + +export type SelectionNode = FieldNode | FragmentSpreadNode | InlineFragmentNode; + +export interface FieldNode { + readonly kind: "Field"; + readonly loc?: Location; + readonly alias?: NameNode; + readonly name: NameNode; + readonly arguments?: ReadonlyArray; + readonly directives?: ReadonlyArray; + readonly selectionSet?: SelectionSetNode; +} + +export interface ArgumentNode { + readonly kind: "Argument"; + readonly loc?: Location; + readonly name: NameNode; + readonly value: ValueNode; +} + +// Fragments + +export interface FragmentSpreadNode { + readonly kind: "FragmentSpread"; + readonly loc?: Location; + readonly name: NameNode; + readonly directives?: ReadonlyArray; +} + +export interface InlineFragmentNode { + readonly kind: "InlineFragment"; + readonly loc?: Location; + readonly typeCondition?: NamedTypeNode; + readonly directives?: ReadonlyArray; + readonly selectionSet: SelectionSetNode; +} + +export interface FragmentDefinitionNode { + readonly kind: "FragmentDefinition"; + readonly loc?: Location; + readonly name: NameNode; + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + readonly variableDefinitions?: ReadonlyArray; + readonly typeCondition: NamedTypeNode; + readonly directives?: ReadonlyArray; + readonly selectionSet: SelectionSetNode; +} + +// Values + +export type ValueNode = + | VariableNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode; + +export interface IntValueNode { + readonly kind: "IntValue"; + readonly loc?: Location; + readonly value: string; +} + +export interface FloatValueNode { + readonly kind: "FloatValue"; + readonly loc?: Location; + readonly value: string; +} + +export interface StringValueNode { + readonly kind: "StringValue"; + readonly loc?: Location; + readonly value: string; + readonly block?: boolean; +} + +export interface BooleanValueNode { + readonly kind: "BooleanValue"; + readonly loc?: Location; + readonly value: boolean; +} + +export interface NullValueNode { + readonly kind: "NullValue"; + readonly loc?: Location; +} + +export interface EnumValueNode { + readonly kind: "EnumValue"; + readonly loc?: Location; + readonly value: string; +} + +export interface ListValueNode { + readonly kind: "ListValue"; + readonly loc?: Location; + readonly values: ReadonlyArray; +} + +export interface ObjectValueNode { + readonly kind: "ObjectValue"; + readonly loc?: Location; + readonly fields: ReadonlyArray; +} + +export interface ObjectFieldNode { + readonly kind: "ObjectField"; + readonly loc?: Location; + readonly name: NameNode; + readonly value: ValueNode; +} + +// Directives + +export interface DirectiveNode { + readonly kind: "Directive"; + readonly loc?: Location; + readonly name: NameNode; + readonly arguments?: ReadonlyArray; +} + +// Type Reference + +export type TypeNode = NamedTypeNode | ListTypeNode | NonNullTypeNode; + +export interface NamedTypeNode { + readonly kind: "NamedType"; + readonly loc?: Location; + readonly name: NameNode; +} + +export interface ListTypeNode { + readonly kind: "ListType"; + readonly loc?: Location; + readonly type: TypeNode; +} + +export interface NonNullTypeNode { + readonly kind: "NonNullType"; + readonly loc?: Location; + readonly type: NamedTypeNode | ListTypeNode; +} + +// Type System Definition + +export type TypeSystemDefinitionNode = SchemaDefinitionNode | TypeDefinitionNode | DirectiveDefinitionNode; + +export interface SchemaDefinitionNode { + readonly kind: "SchemaDefinition"; + readonly loc?: Location; + readonly directives?: ReadonlyArray; + readonly operationTypes: ReadonlyArray; +} + +export interface OperationTypeDefinitionNode { + readonly kind: "OperationTypeDefinition"; + readonly loc?: Location; + readonly operation: OperationTypeNode; + readonly type: NamedTypeNode; +} + +// Type Definition + +export type TypeDefinitionNode = + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | InputObjectTypeDefinitionNode; + +export interface ScalarTypeDefinitionNode { + readonly kind: "ScalarTypeDefinition"; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly directives?: ReadonlyArray; +} + +export interface ObjectTypeDefinitionNode { + readonly kind: "ObjectTypeDefinition"; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly interfaces?: ReadonlyArray; + readonly directives?: ReadonlyArray; + readonly fields?: ReadonlyArray; +} + +export interface FieldDefinitionNode { + readonly kind: "FieldDefinition"; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly arguments?: ReadonlyArray; + readonly type: TypeNode; + readonly directives?: ReadonlyArray; +} + +export interface InputValueDefinitionNode { + readonly kind: "InputValueDefinition"; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly type: TypeNode; + readonly defaultValue?: ValueNode; + readonly directives?: ReadonlyArray; +} + +export interface InterfaceTypeDefinitionNode { + readonly kind: "InterfaceTypeDefinition"; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly directives?: ReadonlyArray; + readonly fields?: ReadonlyArray; +} + +export interface UnionTypeDefinitionNode { + readonly kind: "UnionTypeDefinition"; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly directives?: ReadonlyArray; + readonly types?: ReadonlyArray; +} + +export interface EnumTypeDefinitionNode { + readonly kind: "EnumTypeDefinition"; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly directives?: ReadonlyArray; + readonly values?: ReadonlyArray; +} + +export interface EnumValueDefinitionNode { + readonly kind: "EnumValueDefinition"; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly directives?: ReadonlyArray; +} + +export interface InputObjectTypeDefinitionNode { + readonly kind: "InputObjectTypeDefinition"; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly directives?: ReadonlyArray; + readonly fields?: ReadonlyArray; +} + +// Directive Definitions + +export interface DirectiveDefinitionNode { + readonly kind: "DirectiveDefinition"; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly arguments?: ReadonlyArray; + readonly locations: ReadonlyArray; +} + +// Type System Extensions + +export type TypeSystemExtensionNode = SchemaExtensionNode | TypeExtensionNode; + +export type SchemaExtensionNode = { + readonly kind: "SchemaExtension"; + readonly loc?: Location; + readonly directives?: ReadonlyArray; + readonly operationTypes?: ReadonlyArray; +}; + +// Type Extensions + +export type TypeExtensionNode = + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode; + +export interface ScalarTypeExtensionNode { + readonly kind: "ScalarTypeExtension"; + readonly loc?: Location; + readonly name: NameNode; + readonly directives?: ReadonlyArray; +} + +export interface ObjectTypeExtensionNode { + readonly kind: "ObjectTypeExtension"; + readonly loc?: Location; + readonly name: NameNode; + readonly interfaces?: ReadonlyArray; + readonly directives?: ReadonlyArray; + readonly fields?: ReadonlyArray; +} + +export interface InterfaceTypeExtensionNode { + readonly kind: "InterfaceTypeExtension"; + readonly loc?: Location; + readonly name: NameNode; + readonly directives?: ReadonlyArray; + readonly fields?: ReadonlyArray; +} + +export interface UnionTypeExtensionNode { + readonly kind: "UnionTypeExtension"; + readonly loc?: Location; + readonly name: NameNode; + readonly directives?: ReadonlyArray; + readonly types?: ReadonlyArray; +} + +export interface EnumTypeExtensionNode { + readonly kind: "EnumTypeExtension"; + readonly loc?: Location; + readonly name: NameNode; + readonly directives?: ReadonlyArray; + readonly values?: ReadonlyArray; +} + +export interface InputObjectTypeExtensionNode { + readonly kind: "InputObjectTypeExtension"; + readonly loc?: Location; + readonly name: NameNode; + readonly directives?: ReadonlyArray; + readonly fields?: ReadonlyArray; +} diff --git a/node_modules/@types/graphql/language/blockStringValue.d.ts b/node_modules/@types/graphql/language/blockStringValue.d.ts new file mode 100644 index 0000000..61962c7 --- /dev/null +++ b/node_modules/@types/graphql/language/blockStringValue.d.ts @@ -0,0 +1,7 @@ +/** + * Produces the value of a block string from its parsed raw value, similar to + * Coffeescript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + */ +export default function blockStringValue(rawString: string): string; diff --git a/node_modules/@types/graphql/language/directiveLocation.d.ts b/node_modules/@types/graphql/language/directiveLocation.d.ts new file mode 100644 index 0000000..51c7623 --- /dev/null +++ b/node_modules/@types/graphql/language/directiveLocation.d.ts @@ -0,0 +1,35 @@ +/** + * The set of allowed directive location values. + */ +export const DirectiveLocation: _DirectiveLocation; + +// @internal +type _DirectiveLocation = { + // Request Definitions + QUERY: "QUERY"; + MUTATION: "MUTATION"; + SUBSCRIPTION: "SUBSCRIPTION"; + FIELD: "FIELD"; + FRAGMENT_DEFINITION: "FRAGMENT_DEFINITION"; + FRAGMENT_SPREAD: "FRAGMENT_SPREAD"; + INLINE_FRAGMENT: "INLINE_FRAGMENT"; + VARIABLE_DEFINITION: "VARIABLE_DEFINITION"; + + // Type System Definitions + SCHEMA: "SCHEMA"; + SCALAR: "SCALAR"; + OBJECT: "OBJECT"; + FIELD_DEFINITION: "FIELD_DEFINITION"; + ARGUMENT_DEFINITION: "ARGUMENT_DEFINITION"; + INTERFACE: "INTERFACE"; + UNION: "UNION"; + ENUM: "ENUM"; + ENUM_VALUE: "ENUM_VALUE"; + INPUT_OBJECT: "INPUT_OBJECT"; + INPUT_FIELD_DEFINITION: "INPUT_FIELD_DEFINITION"; +}; + +/** + * The enum type representing the directive location values. + */ +export type DirectiveLocationEnum = _DirectiveLocation[keyof _DirectiveLocation]; diff --git a/node_modules/@types/graphql/language/index.d.ts b/node_modules/@types/graphql/language/index.d.ts new file mode 100644 index 0000000..11ef4a6 --- /dev/null +++ b/node_modules/@types/graphql/language/index.d.ts @@ -0,0 +1,93 @@ +export { getLocation, SourceLocation } from "./location"; +export { Kind, KindEnum } from "./kinds"; +export { createLexer, TokenKind, Lexer, TokenKindEnum } from "./lexer"; +export { parse, parseValue, parseType, ParseOptions } from "./parser"; +export { print } from "./printer"; +export { Source } from "./source"; +export { + visit, + visitInParallel, + visitWithTypeInfo, + getVisitFn, + BREAK, + // type + ASTVisitor, + Visitor, + VisitFn, + VisitorKeyMap, +} from "./visitor"; + +export { + Location, + Token, + ASTNode, + ASTKindToNode, + // Each kind of AST node + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from "./ast"; + +export { + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, +} from "./predicates"; + +export { DirectiveLocation, DirectiveLocationEnum } from "./directiveLocation"; diff --git a/node_modules/@types/graphql/language/kinds.d.ts b/node_modules/@types/graphql/language/kinds.d.ts new file mode 100644 index 0000000..6b32e8e --- /dev/null +++ b/node_modules/@types/graphql/language/kinds.d.ts @@ -0,0 +1,77 @@ +/** + * The set of allowed kind values for AST nodes. + */ +export const Kind: _Kind; + +// @internal +type _Kind = { + // Name + NAME: "Name"; + + // Document + DOCUMENT: "Document"; + OPERATION_DEFINITION: "OperationDefinition"; + VARIABLE_DEFINITION: "VariableDefinition"; + SELECTION_SET: "SelectionSet"; + FIELD: "Field"; + ARGUMENT: "Argument"; + + // Fragments + FRAGMENT_SPREAD: "FragmentSpread"; + INLINE_FRAGMENT: "InlineFragment"; + FRAGMENT_DEFINITION: "FragmentDefinition"; + + // Values + VARIABLE: "Variable"; + INT: "IntValue"; + FLOAT: "FloatValue"; + STRING: "StringValue"; + BOOLEAN: "BooleanValue"; + NULL: "NullValue"; + ENUM: "EnumValue"; + LIST: "ListValue"; + OBJECT: "ObjectValue"; + OBJECT_FIELD: "ObjectField"; + + // Directives + DIRECTIVE: "Directive"; + + // Types + NAMED_TYPE: "NamedType"; + LIST_TYPE: "ListType"; + NON_NULL_TYPE: "NonNullType"; + + // Type System Definitions + SCHEMA_DEFINITION: "SchemaDefinition"; + OPERATION_TYPE_DEFINITION: "OperationTypeDefinition"; + + // Type Definitions + SCALAR_TYPE_DEFINITION: "ScalarTypeDefinition"; + OBJECT_TYPE_DEFINITION: "ObjectTypeDefinition"; + FIELD_DEFINITION: "FieldDefinition"; + INPUT_VALUE_DEFINITION: "InputValueDefinition"; + INTERFACE_TYPE_DEFINITION: "InterfaceTypeDefinition"; + UNION_TYPE_DEFINITION: "UnionTypeDefinition"; + ENUM_TYPE_DEFINITION: "EnumTypeDefinition"; + ENUM_VALUE_DEFINITION: "EnumValueDefinition"; + INPUT_OBJECT_TYPE_DEFINITION: "InputObjectTypeDefinition"; + + // Directive Definitions + DIRECTIVE_DEFINITION: "DirectiveDefinition"; + + // Type System Extensions + SCHEMA_EXTENSION: "SchemaExtension"; + + // Type Extensions + SCALAR_TYPE_EXTENSION: "ScalarTypeExtension"; + OBJECT_TYPE_EXTENSION: "ObjectTypeExtension"; + INTERFACE_TYPE_EXTENSION: "InterfaceTypeExtension"; + UNION_TYPE_EXTENSION: "UnionTypeExtension"; + ENUM_TYPE_EXTENSION: "EnumTypeExtension"; + INPUT_OBJECT_TYPE_EXTENSION: "InputObjectTypeExtension"; +}; + +/** + * The enum type representing the possible kind values of AST nodes. + */ +export type KindEnum = _Kind[keyof _Kind]; diff --git a/node_modules/@types/graphql/language/lexer.d.ts b/node_modules/@types/graphql/language/lexer.d.ts new file mode 100644 index 0000000..d0639b3 --- /dev/null +++ b/node_modules/@types/graphql/language/lexer.d.ts @@ -0,0 +1,94 @@ +import { Token } from "./ast"; +import { Source } from "./source"; +import { syntaxError } from "../error"; + +/** + * Given a Source object, this returns a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +export function createLexer(source: Source, options: TOptions): Lexer; + +/** + * The return type of createLexer. + */ +export interface Lexer { + source: Source; + options: TOptions; + + /** + * The previously focused non-ignored token. + */ + lastToken: Token; + + /** + * The currently focused non-ignored token. + */ + token: Token; + + /** + * The (1-indexed) line containing the current token. + */ + line: number; + + /** + * The character offset at which the current line begins. + */ + lineStart: number; + + /** + * Advances the token stream to the next non-ignored token. + */ + advance(): Token; + + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the Lexer's state. + */ + lookahead(): Token; +} + +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +export const TokenKind: _TokenKind; + +// @internal +type _TokenKind = { + SOF: ""; + EOF: ""; + BANG: "!"; + DOLLAR: "$"; + AMP: "&"; + PAREN_L: "("; + PAREN_R: ")"; + SPREAD: "..."; + COLON: ":"; + EQUALS: "="; + AT: "@"; + BRACKET_L: "["; + BRACKET_R: "]"; + BRACE_L: "{"; + PIPE: "|"; + BRACE_R: "}"; + NAME: "Name"; + INT: "Int"; + FLOAT: "Float"; + STRING: "String"; + BLOCK_STRING: "BlockString"; + COMMENT: "Comment"; +}; + +/** + * The enum type representing the token kinds values. + */ +export type TokenKindEnum = _TokenKind[keyof _TokenKind]; + +/** + * A helper function to describe a token as a string for debugging + */ +export function getTokenDesc(token: Token): string; diff --git a/node_modules/@types/graphql/language/location.d.ts b/node_modules/@types/graphql/language/location.d.ts new file mode 100644 index 0000000..281a542 --- /dev/null +++ b/node_modules/@types/graphql/language/location.d.ts @@ -0,0 +1,15 @@ +import { Source } from "./source"; + +/** + * Represents a location in a Source. + */ +export interface SourceLocation { + readonly line: number; + readonly column: number; +} + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +export function getLocation(source: Source, position: number): SourceLocation; diff --git a/node_modules/@types/graphql/language/parser.d.ts b/node_modules/@types/graphql/language/parser.d.ts new file mode 100644 index 0000000..f89ec3e --- /dev/null +++ b/node_modules/@types/graphql/language/parser.d.ts @@ -0,0 +1,106 @@ +import { NamedTypeNode, TypeNode, ValueNode, DocumentNode } from "./ast"; +import { Source } from "./source"; +import { Lexer } from "./lexer"; + +/** + * Configuration options to control parser behavior + */ +export interface ParseOptions { + /** + * By default, the parser creates AST nodes that know the location + * in the source that they correspond to. This configuration flag + * disables that behavior for performance or testing. + */ + noLocation?: boolean; + + /** + * If enabled, the parser will parse empty fields sets in the Schema + * Definition Language. Otherwise, the parser will follow the current + * specification. + * + * This option is provided to ease adoption of the final SDL specification + * and will be removed in v16. + */ + allowLegacySDLEmptyFields?: boolean; + + /** + * If enabled, the parser will parse implemented interfaces with no `&` + * character between each interface. Otherwise, the parser will follow the + * current specification. + * + * This option is provided to ease adoption of the final SDL specification + * and will be removed in v16. + */ + allowLegacySDLImplementsInterfaces?: boolean; + + /** + * EXPERIMENTAL: + * + * If enabled, the parser will understand and parse variable definitions + * contained in a fragment definition. They'll be represented in the + * `variableDefinitions` field of the FragmentDefinitionNode. + * + * The syntax is identical to normal, query-defined variables. For example: + * + * fragment A($var: Boolean = false) on T { + * ... + * } + * + * Note: this feature is experimental and may change or be removed in the + * future. + */ + experimentalFragmentVariables?: boolean; + + /** + * EXPERIMENTAL: + * + * If enabled, the parser understands directives on variable definitions: + * + * query Foo($var: String = "abc" @variable_definition_directive) { + * ... + * } + */ + experimentalVariableDefinitionDirectives?: boolean; +} + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +export function parse(source: string | Source, options?: ParseOptions): DocumentNode; + +/** + * Given a string containing a GraphQL value, parse the AST for that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + */ +export function parseValue(source: string | Source, options?: ParseOptions): ValueNode; + +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ +export function parseType(source: string | Source, options?: ParseOptions): TypeNode; + +export function parseConstValue(lexer: Lexer): ValueNode; + +/** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ +export function parseTypeReference(lexer: Lexer): TypeNode; + +/** + * NamedType : Name + */ +export function parseNamedType(lexer: Lexer): NamedTypeNode; diff --git a/node_modules/@types/graphql/language/predicates.d.ts b/node_modules/@types/graphql/language/predicates.d.ts new file mode 100644 index 0000000..9859944 --- /dev/null +++ b/node_modules/@types/graphql/language/predicates.d.ts @@ -0,0 +1,19 @@ +import { ASTNode } from "./ast"; + +export function isDefinitionNode(node: ASTNode): boolean; + +export function isExecutableDefinitionNode(node: ASTNode): boolean; + +export function isSelectionNode(node: ASTNode): boolean; + +export function isValueNode(node: ASTNode): boolean; + +export function isTypeNode(node: ASTNode): boolean; + +export function isTypeSystemDefinitionNode(node: ASTNode): boolean; + +export function isTypeDefinitionNode(node: ASTNode): boolean; + +export function isTypeSystemExtensionNode(node: ASTNode): boolean; + +export function isTypeExtensionNode(node: ASTNode): boolean; diff --git a/node_modules/@types/graphql/language/printer.d.ts b/node_modules/@types/graphql/language/printer.d.ts new file mode 100644 index 0000000..fde3888 --- /dev/null +++ b/node_modules/@types/graphql/language/printer.d.ts @@ -0,0 +1,5 @@ +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ +export function print(ast: any): string; diff --git a/node_modules/@types/graphql/language/source.d.ts b/node_modules/@types/graphql/language/source.d.ts new file mode 100644 index 0000000..7794dd3 --- /dev/null +++ b/node_modules/@types/graphql/language/source.d.ts @@ -0,0 +1,19 @@ +interface Location { + line: number; + column: number; +} + +/** + * A representation of source input to GraphQL. + * `name` and `locationOffset` are optional. They are useful for clients who + * store GraphQL documents in source files; for example, if the GraphQL input + * starts at line 40 in a file named Foo.graphql, it might be useful for name to + * be "Foo.graphql" and location to be `{ line: 40, column: 0 }`. + * line and column in locationOffset are 1-indexed + */ +export class Source { + body: string; + name: string; + locationOffset: Location; + constructor(body: string, name?: string, locationOffset?: Location); +} diff --git a/node_modules/@types/graphql/language/visitor.d.ts b/node_modules/@types/graphql/language/visitor.d.ts new file mode 100644 index 0000000..33a3a70 --- /dev/null +++ b/node_modules/@types/graphql/language/visitor.d.ts @@ -0,0 +1,161 @@ +import Maybe from "../tsutils/Maybe"; +import { ASTNode, ASTKindToNode } from "./ast"; +import { TypeInfo } from "../utilities/TypeInfo"; + +interface EnterLeave { + readonly enter?: T; + readonly leave?: T; +} + +type EnterLeaveVisitor = EnterLeave< + VisitFn | { [K in keyof KindToNode]?: VisitFn } +>; + +type ShapeMapVisitor = { + [K in keyof KindToNode]?: VisitFn | EnterLeave> +}; + +export type ASTVisitor = Visitor; +export type Visitor = + | EnterLeaveVisitor + | ShapeMapVisitor; + +/** + * A visitor is comprised of visit functions, which are called on each node + * during the visitor's traversal. + */ +export type VisitFn = ( + // The current node being visiting. + node: TVisitedNode, + // The index or key to this node from the parent node or Array. + key: string | number | undefined, + // The parent immediately above this node, which may be an Array. + parent: TAnyNode | ReadonlyArray | undefined, + // The key path to get to this node from the root node. + path: ReadonlyArray, + // All nodes and Arrays visited before reaching parent of this node. + // These correspond to array indices in `path`. + // Note: ancestors includes arrays which contain the parent of visited node. + ancestors: ReadonlyArray> +) => any; + +/** + * A KeyMap describes each the traversable properties of each kind of node. + */ +export type VisitorKeyMap = { [P in keyof T]: ReadonlyArray }; + +export const QueryDocumentKeys: { [key: string]: string[] }; + +export const BREAK: any; + +/** + * visit() will walk through an AST using a depth first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to four permutations of + * visitor API: + * + * 1) Named visitors triggered when entering a node a specific kind. + * + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * + * 2) Named visitors that trigger upon entering and leaving a node of + * a specific kind. + * + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * + * 4) Parallel visitors for entering and leaving nodes of a specific kind. + * + * visit(ast, { + * enter: { + * Kind(node) { + * // enter the "Kind" node + * } + * }, + * leave: { + * Kind(node) { + * // leave the "Kind" node + * } + * } + * }) + */ +export function visit( + root: ASTNode, + visitor: Visitor, + visitorKeys?: VisitorKeyMap // default: QueryDocumentKeys +): any; + +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ +export function visitInParallel(visitors: Array>): Visitor; + +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ +export function visitWithTypeInfo(typeInfo: TypeInfo, visitor: Visitor): Visitor; + +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + */ +export function getVisitFn(visitor: Visitor, kind: string, isLeaving: boolean): Maybe>; diff --git a/node_modules/@types/graphql/subscription/index.d.ts b/node_modules/@types/graphql/subscription/index.d.ts new file mode 100644 index 0000000..ac4c64f --- /dev/null +++ b/node_modules/@types/graphql/subscription/index.d.ts @@ -0,0 +1 @@ +export { subscribe, createSourceEventStream } from "./subscribe"; diff --git a/node_modules/@types/graphql/subscription/subscribe.d.ts b/node_modules/@types/graphql/subscription/subscribe.d.ts new file mode 100644 index 0000000..05a5f29 --- /dev/null +++ b/node_modules/@types/graphql/subscription/subscribe.d.ts @@ -0,0 +1,75 @@ +import Maybe from "../tsutils/Maybe"; +import { GraphQLSchema } from "../type/schema"; +import { DocumentNode } from "../language/ast"; +import { GraphQLFieldResolver } from "../type/definition"; +import { ExecutionResult, ExecutionResultDataDefault } from "../execution/execute"; + +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise which resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (client error). The promise will be rejected if a + * server error occurs. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Accepts either an object with named arguments, or individual arguments. + */ +export function subscribe(args: { + schema: GraphQLSchema; + document: DocumentNode; + rootValue?: any; + contextValue?: any; + variableValues?: Maybe<{ [key: string]: any }>; + operationName?: Maybe; + fieldResolver?: Maybe>; + subscribeFieldResolver?: Maybe>; +}): Promise> | ExecutionResult>; + +export function subscribe( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: any, + contextValue?: any, + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe>, + subscribeFieldResolver?: Maybe> +): Promise> | ExecutionResult>; + +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise. + * + * If the client-provided invalid arguments, the source stream could not be + * created, or the resolver did not return an AsyncIterable, this function will + * will throw an error, which should be caught and handled by the caller. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ +export function createSourceEventStream( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: any, + contextValue?: any, + variableValues?: { [key: string]: any }, + operationName?: Maybe, + fieldResolver?: Maybe> +): Promise | ExecutionResult>; diff --git a/node_modules/@types/graphql/tsutils/Maybe.d.ts b/node_modules/@types/graphql/tsutils/Maybe.d.ts new file mode 100644 index 0000000..83b04bc --- /dev/null +++ b/node_modules/@types/graphql/tsutils/Maybe.d.ts @@ -0,0 +1,4 @@ +// Conveniently represents flow's "Maybe" type https://flow.org/en/docs/types/maybe/ +type Maybe = null | undefined | T + +export default Maybe diff --git a/node_modules/@types/graphql/type/definition.d.ts b/node_modules/@types/graphql/type/definition.d.ts new file mode 100644 index 0000000..4f95a4d --- /dev/null +++ b/node_modules/@types/graphql/type/definition.d.ts @@ -0,0 +1,669 @@ +import Maybe from "../tsutils/Maybe"; +import { MaybePromise } from "../jsutils/MaybePromise"; +import { + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + OperationDefinitionNode, + FieldNode, + FragmentDefinitionNode, + ValueNode, + ScalarTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from "../language/ast"; +import { GraphQLSchema } from "./schema"; + +/** + * These are all of the possible kinds of types. + */ +export type GraphQLType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull; + +export function isType(type: any): type is GraphQLType; + +export function assertType(type: any): GraphQLType; + +export function isScalarType(type: any): type is GraphQLScalarType; + +export function assertScalarType(type: any): GraphQLScalarType; + +export function isObjectType(type: any): type is GraphQLObjectType; + +export function assertObjectType(type: any): GraphQLObjectType; + +export function isInterfaceType(type: any): type is GraphQLInterfaceType; + +export function assertInterfaceType(type: any): GraphQLInterfaceType; + +export function isUnionType(type: any): type is GraphQLUnionType; + +export function assertUnionType(type: any): GraphQLUnionType; + +export function isEnumType(type: any): type is GraphQLEnumType; + +export function assertEnumType(type: any): GraphQLEnumType; + +export function isInputObjectType(type: any): type is GraphQLInputObjectType; + +export function assertInputObjectType(type: any): GraphQLInputObjectType; + +export function isListType(type: any): type is GraphQLList; + +export function assertListType(type: any): GraphQLList; + +export function isNonNullType(type: any): type is GraphQLNonNull; + +export function assertNonNullType(type: any): GraphQLNonNull; + +/** + * These types may be used as input types for arguments and directives. + */ +export type GraphQLInputType = + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull>; + +export function isInputType(type: any): type is GraphQLInputType; + +export function assertInputType(type: any): GraphQLInputType; + +/** + * These types may be used as output types as the result of fields. + */ +export type GraphQLOutputType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList + >; + +export function isOutputType(type: any): type is GraphQLOutputType; + +export function assertOutputType(type: any): GraphQLOutputType; + +/** + * These types may describe types which may be leaf values. + */ +export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; + +export function isLeafType(type: any): type is GraphQLLeafType; + +export function assertLeafType(type: any): GraphQLLeafType; + +/** + * These types may describe the parent context of a selection set. + */ +export type GraphQLCompositeType = GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType; + +export function isCompositeType(type: any): type is GraphQLCompositeType; + +export function assertCompositeType(type: any): GraphQLCompositeType; + +/** + * These types may describe the parent context of a selection set. + */ +export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; + +export function isAbstractType(type: any): type is GraphQLAbstractType; + +export function assertAbstractType(type: any): GraphQLAbstractType; + +/** + * List Modifier + * + * A list is a kind of type marker, a wrapping type which points to another + * type. Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(Person) }, + * children: { type: new GraphQLList(Person) }, + * }) + * }) + * + */ +export class GraphQLList { + readonly ofType: T; + constructor(ofType: T); + toString(): string; + toJSON(): string; + inspect(): string; +} + +/** + * Non-Null Modifier + * + * A non-null is a kind of type marker, a wrapping type which points to another + * type. Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ +export class GraphQLNonNull { + readonly ofType: T; + constructor(ofType: T); + toString(): string; + toJSON(): string; + inspect(): string; +} + +export type GraphQLWrappingType = GraphQLList | GraphQLNonNull; + +export function isWrappingType(type: any): type is GraphQLWrappingType; + +export function assertWrappingType(type: any): GraphQLWrappingType; + +/** + * These types can all accept null as a value. + */ +export type GraphQLNullableType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList; + +export function isNullableType(type: any): type is GraphQLNullableType; + +export function assertNullableType(type: any): GraphQLNullableType; + +export function getNullableType(type: void): undefined; +export function getNullableType(type: T): T; +export function getNullableType(type: GraphQLNonNull): T; + +/** + * These named types do not include modifiers like List or NonNull. + */ +export type GraphQLNamedType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType; + +export function isNamedType(type: any): type is GraphQLNamedType; + +export function assertNamedType(type: any): GraphQLNamedType; + +export function getNamedType(type: void): undefined; +export function getNamedType(type: GraphQLType): GraphQLNamedType; + +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ +export type Thunk = (() => T) | T; + +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * return value % 2 === 1 ? value : null; + * } + * }); + * + */ +export class GraphQLScalarType { + name: string; + description: Maybe; + serialize: GraphQLScalarSerializer; + parseValue: GraphQLScalarValueParser; + parseLiteral: GraphQLScalarLiteralParser; + astNode: Maybe; + extensionASTNodes: Maybe>; + constructor(config: GraphQLScalarTypeConfig); + + toString(): string; + toJSON(): string; + inspect(): string; +} + +export type GraphQLScalarSerializer = (value: any) => Maybe; +export type GraphQLScalarValueParser = (value: any) => Maybe; +export type GraphQLScalarLiteralParser = ( + valueNode: ValueNode, + variables: Maybe<{ [key: string]: any }> +) => Maybe; + +export interface GraphQLScalarTypeConfig { + name: string; + description?: Maybe; + // Serializes an internal value to include in a response. + serialize: GraphQLScalarSerializer; + // Parses an externally provided value to use as an input. + parseValue?: GraphQLScalarValueParser; + // Parses an externally provided literal value to use as an input. + parseLiteral?: GraphQLScalarLiteralParser; + astNode?: Maybe; + extensionASTNodes?: Maybe>; +} + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * + */ +export class GraphQLObjectType { + name: string; + description: Maybe; + astNode: Maybe; + extensionASTNodes: Maybe>; + isTypeOf: Maybe>; + + constructor(config: GraphQLObjectTypeConfig); + getFields(): GraphQLFieldMap; + getInterfaces(): GraphQLInterfaceType[]; + toString(): string; + toJSON(): string; + inspect(): string; +} + +export interface GraphQLObjectTypeConfig { + name: string; + interfaces?: Thunk>; + fields: Thunk>; + isTypeOf?: Maybe>; + description?: Maybe; + astNode?: Maybe; + extensionASTNodes?: Maybe>; +} + +export type GraphQLTypeResolver = ( + value: TSource, + context: TContext, + info: GraphQLResolveInfo +) => MaybePromise>; + +export type GraphQLIsTypeOfFn = ( + source: TSource, + context: TContext, + info: GraphQLResolveInfo +) => MaybePromise; + +export type GraphQLFieldResolver = ( + source: TSource, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo +) => any; + +export interface GraphQLResolveInfo { + readonly fieldName: string; + readonly fieldNodes: ReadonlyArray; + readonly returnType: GraphQLOutputType; + readonly parentType: GraphQLObjectType; + readonly path: ResponsePath; + readonly schema: GraphQLSchema; + readonly fragments: { [key: string]: FragmentDefinitionNode }; + readonly rootValue: any; + readonly operation: OperationDefinitionNode; + readonly variableValues: { [variableName: string]: any }; +} + +export type ResponsePath = { + readonly prev: ResponsePath | undefined; + readonly key: string | number; +}; + +export interface GraphQLFieldConfig { + type: GraphQLOutputType; + args?: GraphQLFieldConfigArgumentMap; + resolve?: GraphQLFieldResolver; + subscribe?: GraphQLFieldResolver; + deprecationReason?: Maybe; + description?: Maybe; + astNode?: Maybe; +} + +export type GraphQLFieldConfigArgumentMap = { [key: string]: GraphQLArgumentConfig }; + +export interface GraphQLArgumentConfig { + type: GraphQLInputType; + defaultValue?: any; + description?: Maybe; + astNode?: Maybe; +} + +export type GraphQLFieldConfigMap = { + [key: string]: GraphQLFieldConfig; +}; + +export interface GraphQLField { + name: string; + description: Maybe; + type: GraphQLOutputType; + args: GraphQLArgument[]; + resolve?: GraphQLFieldResolver; + subscribe?: GraphQLFieldResolver; + isDeprecated?: boolean; + deprecationReason?: Maybe; + astNode?: Maybe; +} + +export interface GraphQLArgument { + name: string; + type: GraphQLInputType; + defaultValue?: any; + description?: Maybe; + astNode?: Maybe; +} + +export function isRequiredArgument(arg: GraphQLArgument): boolean; + +export type GraphQLFieldMap = { + [key: string]: GraphQLField; +}; + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * + */ +export class GraphQLInterfaceType { + name: string; + description: Maybe; + astNode?: Maybe; + extensionASTNodes: Maybe>; + resolveType: Maybe>; + + constructor(config: GraphQLInterfaceTypeConfig); + + getFields(): GraphQLFieldMap; + + toString(): string; + toJSON(): string; + inspect(): string; +} + +export interface GraphQLInterfaceTypeConfig { + name: string; + fields: Thunk>; + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: Maybe>; + description?: Maybe; + astNode?: Maybe; + extensionASTNodes?: Maybe>; +} + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * + */ +export class GraphQLUnionType { + name: string; + description: Maybe; + astNode: Maybe; + extensionASTNodes: Maybe>; + resolveType: Maybe>; + + constructor(config: GraphQLUnionTypeConfig); + + getTypes(): GraphQLObjectType[]; + + toString(): string; + toJSON(): string; + inspect(): string; +} + +export interface GraphQLUnionTypeConfig { + name: string; + types: Thunk; + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: Maybe>; + description?: Maybe; + astNode?: Maybe; + extensionASTNodes?: Maybe>; +} + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +export class GraphQLEnumType { + name: string; + description: Maybe; + astNode: Maybe; + extensionASTNodes: Maybe>; + + constructor(config: GraphQLEnumTypeConfig); + getValues(): GraphQLEnumValue[]; + getValue(name: string): Maybe; + serialize(value: any): Maybe; + parseValue(value: any): Maybe; + parseLiteral(valueNode: ValueNode, _variables: Maybe<{ [key: string]: any }>): Maybe; + toString(): string; + toJSON(): string; + inspect(): string; +} + +export interface GraphQLEnumTypeConfig { + name: string; + values: GraphQLEnumValueConfigMap; + description?: Maybe; + astNode?: Maybe; + extensionASTNodes?: Maybe>; +} + +export type GraphQLEnumValueConfigMap = { [key: string]: GraphQLEnumValueConfig }; + +export interface GraphQLEnumValueConfig { + value?: any; + deprecationReason?: Maybe; + description?: Maybe; + astNode?: Maybe; +} + +export interface GraphQLEnumValue { + name: string; + description: Maybe; + isDeprecated?: boolean; + deprecationReason: Maybe; + astNode?: Maybe; + value: any; +} + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +export class GraphQLInputObjectType { + name: string; + description: Maybe; + astNode: Maybe; + extensionASTNodes: Maybe>; + constructor(config: GraphQLInputObjectTypeConfig); + getFields(): GraphQLInputFieldMap; + toString(): string; + toJSON(): string; + inspect(): string; +} + +export interface GraphQLInputObjectTypeConfig { + name: string; + fields: Thunk; + description?: Maybe; + astNode?: Maybe; + extensionASTNodes?: Maybe>; +} + +export interface GraphQLInputFieldConfig { + type: GraphQLInputType; + defaultValue?: any; + description?: Maybe; + astNode?: Maybe; +} + +export type GraphQLInputFieldConfigMap = { + [key: string]: GraphQLInputFieldConfig; +}; + +export interface GraphQLInputField { + name: string; + type: GraphQLInputType; + defaultValue?: any; + description?: Maybe; + astNode?: Maybe; +} + +export function isRequiredInputField(field: GraphQLInputField): boolean; + +export type GraphQLInputFieldMap = { [key: string]: GraphQLInputField }; diff --git a/node_modules/@types/graphql/type/directives.d.ts b/node_modules/@types/graphql/type/directives.d.ts new file mode 100644 index 0000000..961faa0 --- /dev/null +++ b/node_modules/@types/graphql/type/directives.d.ts @@ -0,0 +1,58 @@ +import Maybe from "../tsutils/Maybe"; +import { GraphQLFieldConfigArgumentMap, GraphQLArgument } from "./definition"; +import { DirectiveDefinitionNode } from "../language/ast"; +import { DirectiveLocationEnum } from "../language/directiveLocation"; + +/** + * Test if the given value is a GraphQL directive. + */ +export function isDirective(directive: any): directive is GraphQLDirective; + +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ +export class GraphQLDirective { + name: string; + description: Maybe; + locations: DirectiveLocationEnum[]; + args: GraphQLArgument[]; + astNode: Maybe; + + constructor(config: GraphQLDirectiveConfig); +} + +export interface GraphQLDirectiveConfig { + name: string; + description?: Maybe; + locations: DirectiveLocationEnum[]; + args?: Maybe; + astNode?: Maybe; +} + +/** + * Used to conditionally include fields or fragments. + */ +export const GraphQLIncludeDirective: GraphQLDirective; + +/** + * Used to conditionally skip (exclude) fields or fragments. + */ +export const GraphQLSkipDirective: GraphQLDirective; + +/** + * Constant string used for default reason for a deprecation. + */ +export const DEFAULT_DEPRECATION_REASON: "No longer supported"; + +/** + * Used to declare element of a GraphQL schema as deprecated. + */ +export const GraphQLDeprecatedDirective: GraphQLDirective; + +/** + * The full list of specified directives. + */ +export const specifiedDirectives: ReadonlyArray; + +export function isSpecifiedDirective(directive: GraphQLDirective): boolean; diff --git a/node_modules/@types/graphql/type/index.d.ts b/node_modules/@types/graphql/type/index.d.ts new file mode 100644 index 0000000..3a316ab --- /dev/null +++ b/node_modules/@types/graphql/type/index.d.ts @@ -0,0 +1,150 @@ +export { + // Predicate + isSchema, + // GraphQL Schema definition + GraphQLSchema, + GraphQLSchemaConfig, +} from "./schema"; + +export { + // Predicates + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, + // Assertions + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, + // Un-modifiers + getNullableType, + getNamedType, + // Definitions + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + // Type Wrappers + GraphQLList, + GraphQLNonNull, + // type + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + Thunk, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLEnumTypeConfig, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueConfigMap, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldConfigMap, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInterfaceTypeConfig, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLResolveInfo, + ResponsePath, + GraphQLScalarTypeConfig, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from "./definition"; + +export { + // Predicate + isDirective, + // Directives Definition + GraphQLDirective, + // Built-in Directives defined by the Spec + isSpecifiedDirective, + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, + // type + GraphQLDirectiveConfig, +} from "./directives"; + +// Common built-in scalar instances. +export { + isSpecifiedScalarType, + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, +} from "./scalars"; + +export { + // "Enum" of Type Kinds + TypeKind, + // GraphQL Types for introspection. + isIntrospectionType, + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from "./introspection"; + +export { validateSchema, assertValidSchema } from "./validate"; diff --git a/node_modules/@types/graphql/type/introspection.d.ts b/node_modules/@types/graphql/type/introspection.d.ts new file mode 100644 index 0000000..aa1617f --- /dev/null +++ b/node_modules/@types/graphql/type/introspection.d.ts @@ -0,0 +1,45 @@ +import { + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, +} from "./definition"; +import { GraphQLField } from "./definition"; + +export const __Schema: GraphQLObjectType; +export const __Directive: GraphQLObjectType; +export const __DirectiveLocation: GraphQLEnumType; +export const __Type: GraphQLObjectType; +export const __Field: GraphQLObjectType; +export const __InputValue: GraphQLObjectType; +export const __EnumValue: GraphQLObjectType; + +export const TypeKind: { + SCALAR: "SCALAR"; + OBJECT: "OBJECT"; + INTERFACE: "INTERFACE"; + UNION: "UNION"; + ENUM: "ENUM"; + INPUT_OBJECT: "INPUT_OBJECT"; + LIST: "LIST"; + NON_NULL: "NON_NULL"; +}; + +export const __TypeKind: GraphQLEnumType; + +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +export const SchemaMetaFieldDef: GraphQLField; +export const TypeMetaFieldDef: GraphQLField; +export const TypeNameMetaFieldDef: GraphQLField; + +export const introspectionTypes: ReadonlyArray; + +export function isIntrospectionType(type: any): boolean; diff --git a/node_modules/@types/graphql/type/scalars.d.ts b/node_modules/@types/graphql/type/scalars.d.ts new file mode 100644 index 0000000..7bec564 --- /dev/null +++ b/node_modules/@types/graphql/type/scalars.d.ts @@ -0,0 +1,11 @@ +import { GraphQLScalarType } from "./definition"; + +export const GraphQLInt: GraphQLScalarType; +export const GraphQLFloat: GraphQLScalarType; +export const GraphQLString: GraphQLScalarType; +export const GraphQLBoolean: GraphQLScalarType; +export const GraphQLID: GraphQLScalarType; + +export const specifiedScalarTypes: ReadonlyArray; + +export function isSpecifiedScalarType(type: GraphQLScalarType): boolean; diff --git a/node_modules/@types/graphql/type/schema.d.ts b/node_modules/@types/graphql/type/schema.d.ts new file mode 100644 index 0000000..9ed0f4a --- /dev/null +++ b/node_modules/@types/graphql/type/schema.d.ts @@ -0,0 +1,87 @@ +import Maybe from "../tsutils/Maybe"; +import { GraphQLObjectType } from "./definition"; +import { GraphQLType, GraphQLNamedType, GraphQLAbstractType } from "./definition"; +import { SchemaDefinitionNode, SchemaExtensionNode } from "../language/ast"; +import { GraphQLDirective } from "./directives"; + +/** + * Test if the given value is a GraphQL schema. + */ +export function isSchema(schema: any): schema is GraphQLSchema; + +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. @include and + * @skip) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * + */ +export class GraphQLSchema { + astNode: Maybe; + extensionASTNodes: Maybe>; + + constructor(config: GraphQLSchemaConfig); + + getQueryType(): Maybe; + getMutationType(): Maybe; + getSubscriptionType(): Maybe; + getTypeMap(): TypeMap; + getType(name: string): Maybe; + getPossibleTypes(abstractType: GraphQLAbstractType): ReadonlyArray; + + isPossibleType(abstractType: GraphQLAbstractType, possibleType: GraphQLObjectType): boolean; + + getDirectives(): ReadonlyArray; + getDirective(name: string): Maybe; +} + +type TypeMap = { [key: string]: GraphQLNamedType }; + +export interface GraphQLSchemaValidationOptions { + /** + * When building a schema from a GraphQL service's introspection result, it + * might be safe to assume the schema is valid. Set to true to assume the + * produced schema is valid. + * + * Default: false + */ + assumeValid?: boolean; + + /** + * If provided, the schema will consider fields or types with names included + * in this list valid, even if they do not adhere to the specification's + * schema validation rules. + * + * This option is provided to ease adoption and will be removed in v15. + */ + allowedLegacyNames?: Maybe>; +} + +export interface GraphQLSchemaConfig extends GraphQLSchemaValidationOptions { + query: Maybe; + mutation?: Maybe; + subscription?: Maybe; + types?: Maybe; + directives?: Maybe; + astNode?: Maybe; + extensionASTNodes?: Maybe>; +} diff --git a/node_modules/@types/graphql/type/validate.d.ts b/node_modules/@types/graphql/type/validate.d.ts new file mode 100644 index 0000000..92d5120 --- /dev/null +++ b/node_modules/@types/graphql/type/validate.d.ts @@ -0,0 +1,17 @@ +import { GraphQLSchema } from "./schema"; +import { GraphQLError } from "../error/GraphQLError"; + +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ +export function validateSchema(schema: GraphQLSchema): ReadonlyArray; + +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ +export function assertValidSchema(schema: GraphQLSchema): void; diff --git a/node_modules/@types/graphql/utilities/TypeInfo.d.ts b/node_modules/@types/graphql/utilities/TypeInfo.d.ts new file mode 100644 index 0000000..04d8e6e --- /dev/null +++ b/node_modules/@types/graphql/utilities/TypeInfo.d.ts @@ -0,0 +1,49 @@ +import Maybe from "../tsutils/Maybe"; +import { GraphQLSchema } from "../type/schema"; +import { + GraphQLOutputType, + GraphQLCompositeType, + GraphQLInputType, + GraphQLField, + GraphQLArgument, + GraphQLEnumValue, + GraphQLType, +} from "../type/definition"; +import { GraphQLDirective } from "../type/directives"; +import { ASTNode, FieldNode } from "../language/ast"; + +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ +export class TypeInfo { + constructor( + schema: GraphQLSchema, + // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant codebases. You should never need to use it. + // It may disappear in the future. + getFieldDefFn?: getFieldDef, + // Initial type may be provided in rare cases to facilitate traversals + // beginning somewhere other than documents. + initialType?: GraphQLType + ); + + getType(): Maybe; + getParentType(): Maybe; + getInputType(): Maybe; + getParentInputType(): Maybe; + getFieldDef(): GraphQLField>; + getDefaultValue(): Maybe; + getDirective(): Maybe; + getArgument(): Maybe; + getEnumValue(): Maybe; + enter(node: ASTNode): any; + leave(node: ASTNode): any; +} + +type getFieldDef = ( + schema: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode +) => Maybe>; diff --git a/node_modules/@types/graphql/utilities/assertValidName.d.ts b/node_modules/@types/graphql/utilities/assertValidName.d.ts new file mode 100644 index 0000000..3711a4e --- /dev/null +++ b/node_modules/@types/graphql/utilities/assertValidName.d.ts @@ -0,0 +1,12 @@ +import { GraphQLError } from "../error/GraphQLError"; +import { ASTNode } from "../language/ast"; + +/** + * Upholds the spec rules about naming. + */ +export function assertValidName(name: string): string; + +/** + * Returns an Error if a name is invalid. + */ +export function isValidNameError(name: string, node?: ASTNode | undefined): GraphQLError | undefined; diff --git a/node_modules/@types/graphql/utilities/astFromValue.d.ts b/node_modules/@types/graphql/utilities/astFromValue.d.ts new file mode 100644 index 0000000..22bda75 --- /dev/null +++ b/node_modules/@types/graphql/utilities/astFromValue.d.ts @@ -0,0 +1,22 @@ +import Maybe from "../tsutils/Maybe"; +import { ValueNode } from "../language/ast"; +import { GraphQLInputType } from "../type/definition"; + +/** + * Produces a GraphQL Value AST given a JavaScript value. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Mixed | Enum Value | + * | null | NullValue | + * + */ +export function astFromValue(value: any, type: GraphQLInputType): Maybe; diff --git a/node_modules/@types/graphql/utilities/buildASTSchema.d.ts b/node_modules/@types/graphql/utilities/buildASTSchema.d.ts new file mode 100644 index 0000000..d16bfa8 --- /dev/null +++ b/node_modules/@types/graphql/utilities/buildASTSchema.d.ts @@ -0,0 +1,95 @@ +import Maybe from "../tsutils/Maybe"; +import { + DocumentNode, + Location, + StringValueNode, + TypeDefinitionNode, + NamedTypeNode, + DirectiveDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + EnumValueDefinitionNode, +} from "../language/ast"; +import { GraphQLNamedType, GraphQLFieldConfig, GraphQLInputField, GraphQLEnumValueConfig } from "../type/definition"; +import { GraphQLDirective } from "../type/directives"; +import { Source } from "../language/source"; +import { GraphQLSchema, GraphQLSchemaValidationOptions } from "../type/schema"; +import { ParseOptions } from "../language/parser"; +import blockStringValue from "../language/blockStringValue"; + +interface BuildSchemaOptions extends GraphQLSchemaValidationOptions { + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean; + + /** + * Set to true to assume the SDL is valid. + * + * Default: false + */ + assumeValidSDL?: boolean; +} + +/** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function buildASTSchema(documentAST: DocumentNode, options?: BuildSchemaOptions): GraphQLSchema; + +type TypeDefinitionsMap = { [key: string]: TypeDefinitionNode }; +type TypeResolver = (typeRef: NamedTypeNode) => GraphQLNamedType; + +export class ASTDefinitionBuilder { + constructor(typeDefinitionsMap: TypeDefinitionsMap, options: Maybe, resolveType: TypeResolver); + + buildTypes(nodes: ReadonlyArray): Array; + + buildType(node: NamedTypeNode | TypeDefinitionNode): GraphQLNamedType; + + buildDirective(directiveNode: DirectiveDefinitionNode): GraphQLDirective; + + buildField(field: FieldDefinitionNode): GraphQLFieldConfig; + + buildInputField(value: InputValueDefinitionNode): GraphQLInputField; + + buildEnumValue(value: EnumValueDefinitionNode): GraphQLEnumValueConfig; +} + +/** + * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function getDescription( + node: { readonly description?: StringValueNode; readonly loc?: Location }, + options: Maybe +): string | undefined; + +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ +export function buildSchema(source: string | Source, options?: BuildSchemaOptions & ParseOptions): GraphQLSchema; diff --git a/node_modules/@types/graphql/utilities/buildClientSchema.d.ts b/node_modules/@types/graphql/utilities/buildClientSchema.d.ts new file mode 100644 index 0000000..21e25f3 --- /dev/null +++ b/node_modules/@types/graphql/utilities/buildClientSchema.d.ts @@ -0,0 +1,18 @@ +import { IntrospectionQuery } from "./introspectionQuery"; +import { GraphQLSchema, GraphQLSchemaValidationOptions } from "../type/schema"; + +interface Options extends GraphQLSchemaValidationOptions {} + +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + */ +export function buildClientSchema(introspection: IntrospectionQuery, options?: Options): GraphQLSchema; diff --git a/node_modules/@types/graphql/utilities/coerceValue.d.ts b/node_modules/@types/graphql/utilities/coerceValue.d.ts new file mode 100644 index 0000000..95d371e --- /dev/null +++ b/node_modules/@types/graphql/utilities/coerceValue.d.ts @@ -0,0 +1,22 @@ +import { GraphQLError } from "../error/GraphQLError"; +import { ASTNode } from "../language/ast"; +import { GraphQLInputType } from "../type/definition"; + +interface CoercedValue { + readonly errors: ReadonlyArray | undefined; + readonly value: any; +} + +interface Path { + readonly prev: Path | undefined; + readonly key: string | number; +} + +/** + * Coerces a JavaScript value given a GraphQL Type. + * + * Returns either a value which is valid for the provided type or a list of + * encountered coercion errors. + * + */ +export function coerceValue(value: any, type: GraphQLInputType, blameNode?: ASTNode, path?: Path): CoercedValue; diff --git a/node_modules/@types/graphql/utilities/concatAST.d.ts b/node_modules/@types/graphql/utilities/concatAST.d.ts new file mode 100644 index 0000000..52a272a --- /dev/null +++ b/node_modules/@types/graphql/utilities/concatAST.d.ts @@ -0,0 +1,8 @@ +import { DocumentNode } from "../language/ast"; + +/** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ +export function concatAST(asts: ReadonlyArray): DocumentNode; diff --git a/node_modules/@types/graphql/utilities/extendSchema.d.ts b/node_modules/@types/graphql/utilities/extendSchema.d.ts new file mode 100644 index 0000000..f319259 --- /dev/null +++ b/node_modules/@types/graphql/utilities/extendSchema.d.ts @@ -0,0 +1,42 @@ +import { DocumentNode } from "../language/ast"; +import { GraphQLSchema } from "../type/schema"; +import { GraphQLSchemaValidationOptions } from "../type/schema"; + +interface Options extends GraphQLSchemaValidationOptions { + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean; + + /** + * Set to true to assume the SDL is valid. + * + * Default: false + */ + assumeValidSDL?: boolean; +} + +/** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + * + * Accepts options as a third argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function extendSchema(schema: GraphQLSchema, documentAST: DocumentNode, options?: Options): GraphQLSchema; diff --git a/node_modules/@types/graphql/utilities/findBreakingChanges.d.ts b/node_modules/@types/graphql/utilities/findBreakingChanges.d.ts new file mode 100644 index 0000000..6f09cac --- /dev/null +++ b/node_modules/@types/graphql/utilities/findBreakingChanges.d.ts @@ -0,0 +1,160 @@ +import { + getNamedType, + GraphQLScalarType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLInterfaceType, + GraphQLObjectType, + GraphQLUnionType, + GraphQLNamedType, +} from "../type/definition"; +import { GraphQLDirective } from "../type/directives"; +import { GraphQLSchema } from "../type/schema"; +import { DirectiveLocationEnum } from "../language/directiveLocation"; + +export const BreakingChangeType: _BreakingChangeType; + +// @internal +type _BreakingChangeType = { + FIELD_CHANGED_KIND: "FIELD_CHANGED_KIND"; + FIELD_REMOVED: "FIELD_REMOVED"; + TYPE_CHANGED_KIND: "TYPE_CHANGED_KIND"; + TYPE_REMOVED: "TYPE_REMOVED"; + TYPE_REMOVED_FROM_UNION: "TYPE_REMOVED_FROM_UNION"; + VALUE_REMOVED_FROM_ENUM: "VALUE_REMOVED_FROM_ENUM"; + ARG_REMOVED: "ARG_REMOVED"; + ARG_CHANGED_KIND: "ARG_CHANGED_KIND"; + REQUIRED_ARG_ADDED: "REQUIRED_ARG_ADDED"; + REQUIRED_INPUT_FIELD_ADDED: "REQUIRED_INPUT_FIELD_ADDED"; + INTERFACE_REMOVED_FROM_OBJECT: "INTERFACE_REMOVED_FROM_OBJECT"; + DIRECTIVE_REMOVED: "DIRECTIVE_REMOVED"; + DIRECTIVE_ARG_REMOVED: "DIRECTIVE_ARG_REMOVED"; + DIRECTIVE_LOCATION_REMOVED: "DIRECTIVE_LOCATION_REMOVED"; + REQUIRED_DIRECTIVE_ARG_ADDED: "REQUIRED_DIRECTIVE_ARG_ADDED"; +}; + +export const DangerousChangeType: _DangerousChangeType; + +// @internal +type _DangerousChangeType = { + ARG_DEFAULT_VALUE_CHANGE: "ARG_DEFAULT_VALUE_CHANGE"; + VALUE_ADDED_TO_ENUM: "VALUE_ADDED_TO_ENUM"; + INTERFACE_ADDED_TO_OBJECT: "INTERFACE_ADDED_TO_OBJECT"; + TYPE_ADDED_TO_UNION: "TYPE_ADDED_TO_UNION"; + OPTIONAL_INPUT_FIELD_ADDED: "OPTIONAL_INPUT_FIELD_ADDED"; + OPTIONAL_ARG_ADDED: "OPTIONAL_ARG_ADDED"; +}; + +export interface BreakingChange { + type: keyof _BreakingChangeType; + description: string; +} + +export interface DangerousChange { + type: keyof _DangerousChangeType; + description: string; +} + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ +export function findBreakingChanges(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): Array; + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + */ +export function findDangerousChanges(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): Array; + +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing an entire type. + */ +export function findRemovedTypes(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): Array; + +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to changing the type of a type. + */ +export function findTypesThatChangedKind(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): Array; + +/** + * Given two schemas, returns an Array containing descriptions of any + * breaking or dangerous changes in the newSchema related to arguments + * (such as removal or change of type of an argument, or a change in an + * argument's default value). + */ +export function findArgChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema +): { + breakingChanges: Array; + dangerousChanges: Array; +}; + +export function findFieldsThatChangedTypeOnObjectOrInterfaceTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema +): Array; + +export function findFieldsThatChangedTypeOnInputObjectTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema +): { + breakingChanges: Array; + dangerousChanges: Array; +}; + +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing types from a union type. + */ +export function findTypesRemovedFromUnions(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): Array; + +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding types to a union type. + */ +export function findTypesAddedToUnions(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): Array; + +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing values from an enum type. + */ +export function findValuesRemovedFromEnums(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): Array; + +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding values to an enum type. + */ +export function findValuesAddedToEnums(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): Array; + +export function findInterfacesRemovedFromObjectTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema +): Array; + +export function findInterfacesAddedToObjectTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema +): Array; + +export function findRemovedDirectives(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): Array; + +export function findRemovedDirectiveArgs(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): Array; + +export function findAddedNonNullDirectiveArgs( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema +): Array; + +export function findRemovedLocationsForDirective( + oldDirective: GraphQLDirective, + newDirective: GraphQLDirective +): Array; + +export function findRemovedDirectiveLocations( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema +): Array; diff --git a/node_modules/@types/graphql/utilities/findDeprecatedUsages.d.ts b/node_modules/@types/graphql/utilities/findDeprecatedUsages.d.ts new file mode 100644 index 0000000..51d8ecb --- /dev/null +++ b/node_modules/@types/graphql/utilities/findDeprecatedUsages.d.ts @@ -0,0 +1,10 @@ +import { GraphQLSchema } from "../type/schema"; +import { DocumentNode } from "../language/ast"; +import { GraphQLError } from "../error/GraphQLError"; + +/** + * A validation rule which reports deprecated usages. + * + * Returns a list of GraphQLError instances describing each deprecated use. + */ +export function findDeprecatedUsages(schema: GraphQLSchema, ast: DocumentNode): GraphQLError[]; diff --git a/node_modules/@types/graphql/utilities/getOperationAST.d.ts b/node_modules/@types/graphql/utilities/getOperationAST.d.ts new file mode 100644 index 0000000..127034b --- /dev/null +++ b/node_modules/@types/graphql/utilities/getOperationAST.d.ts @@ -0,0 +1,12 @@ +import Maybe from "../tsutils/Maybe"; +import { DocumentNode, OperationDefinitionNode } from "../language/ast"; + +/** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ +export function getOperationAST( + documentAST: DocumentNode, + operationName: Maybe +): Maybe; diff --git a/node_modules/@types/graphql/utilities/getOperationRootType.d.ts b/node_modules/@types/graphql/utilities/getOperationRootType.d.ts new file mode 100644 index 0000000..f3bd543 --- /dev/null +++ b/node_modules/@types/graphql/utilities/getOperationRootType.d.ts @@ -0,0 +1,11 @@ +import { GraphQLSchema } from "../type/schema"; +import { OperationDefinitionNode, OperationTypeDefinitionNode } from "../language/ast"; +import { GraphQLObjectType } from "../type/definition"; + +/** + * Extracts the root type of the operation from the schema. + */ +export function getOperationRootType( + schema: GraphQLSchema, + operation: OperationDefinitionNode | OperationTypeDefinitionNode +): GraphQLObjectType; diff --git a/node_modules/@types/graphql/utilities/index.d.ts b/node_modules/@types/graphql/utilities/index.d.ts new file mode 100644 index 0000000..9e2a51d --- /dev/null +++ b/node_modules/@types/graphql/utilities/index.d.ts @@ -0,0 +1,112 @@ +// The GraphQL query recommended for a full schema introspection. +export { + getIntrospectionQuery, + // @deprecated, use getIntrospectionQuery() - will be removed in v15 + introspectionQuery, +} from "./introspectionQuery"; + +export { + IntrospectionOptions, + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionInputType, + IntrospectionOutputType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionInputTypeRef, + IntrospectionOutputTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, +} from "./introspectionQuery"; + +// Gets the target Operation from a Document +export { getOperationAST } from "./getOperationAST"; + +// Gets the Type for the target Operation AST. +export { getOperationRootType } from "./getOperationRootType"; + +// Convert a GraphQLSchema to an IntrospectionQuery +export { introspectionFromSchema } from "./introspectionFromSchema"; + +// Build a GraphQLSchema from an introspection result. +export { buildClientSchema } from "./buildClientSchema"; + +// Build a GraphQLSchema from GraphQL Schema language. +export { + buildASTSchema, + buildSchema, + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16 + getDescription, + BuildSchemaOptions, +} from "./buildASTSchema"; + +// Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. +export { extendSchema } from "./extendSchema"; + +// Sort a GraphQLSchema. +export { lexicographicSortSchema } from "./lexicographicSortSchema"; + +// Print a GraphQLSchema to GraphQL Schema language. +export { printSchema, printType, printIntrospectionSchema } from "./schemaPrinter"; + +// Create a GraphQLType from a GraphQL language AST. +export { typeFromAST } from "./typeFromAST"; + +// Create a JavaScript value from a GraphQL language AST with a type. +export { valueFromAST } from "./valueFromAST"; + +// Create a JavaScript value from a GraphQL language AST without a type. +export { valueFromASTUntyped } from "./valueFromASTUntyped"; + +// Create a GraphQL language AST from a JavaScript value. +export { astFromValue } from "./astFromValue"; + +// A helper to use within recursive-descent visitors which need to be aware of +// the GraphQL type system. +export { TypeInfo } from "./TypeInfo"; + +// Coerces a JavaScript value to a GraphQL type, or produces errors. +export { coerceValue } from "./coerceValue"; + +// @deprecated use coerceValue - will be removed in v15 +export { isValidJSValue } from "./isValidJSValue"; + +// @deprecated use validation - will be removed in v15 +export { isValidLiteralValue } from "./isValidLiteralValue"; + +// Concatenates multiple AST together. +export { concatAST } from "./concatAST"; + +// Separates an AST into an AST per Operation. +export { separateOperations } from "./separateOperations"; + +// Comparators for types +export { isEqualType, isTypeSubTypeOf, doTypesOverlap } from "./typeComparators"; + +// Asserts that a string is a valid GraphQL name +export { assertValidName, isValidNameError } from "./assertValidName"; + +// Compares two GraphQLSchemas and detects breaking changes. +export { + BreakingChangeType, + DangerousChangeType, + findBreakingChanges, + findDangerousChanges, + BreakingChange, + DangerousChange, +} from "./findBreakingChanges"; + +// Report all deprecated usage within a GraphQL document. +export { findDeprecatedUsages } from "./findDeprecatedUsages"; diff --git a/node_modules/@types/graphql/utilities/introspectionFromSchema.d.ts b/node_modules/@types/graphql/utilities/introspectionFromSchema.d.ts new file mode 100644 index 0000000..ad5724c --- /dev/null +++ b/node_modules/@types/graphql/utilities/introspectionFromSchema.d.ts @@ -0,0 +1,13 @@ +import { GraphQLSchema } from "../type/schema"; +import { IntrospectionQuery, IntrospectionOptions } from "./introspectionQuery"; + +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + */ +export function introspectionFromSchema(schema: GraphQLSchema, options?: IntrospectionOptions): IntrospectionQuery; diff --git a/node_modules/@types/graphql/utilities/introspectionQuery.d.ts b/node_modules/@types/graphql/utilities/introspectionQuery.d.ts new file mode 100644 index 0000000..ddabcb7 --- /dev/null +++ b/node_modules/@types/graphql/utilities/introspectionQuery.d.ts @@ -0,0 +1,149 @@ +import Maybe from "../tsutils/Maybe"; +import { DirectiveLocationEnum } from "../language/directiveLocation"; + +export interface IntrospectionOptions { + // Whether to include descriptions in the introspection result. + // Default: true + descriptions: boolean; +} + +export function getIntrospectionQuery(options?: IntrospectionOptions): string; + +/** + * Deprecated, call getIntrospectionQuery directly. + * + * This function will be removed in v15 + */ +export const introspectionQuery: string; + +export interface IntrospectionQuery { + readonly __schema: IntrospectionSchema; +} + +export interface IntrospectionSchema { + readonly queryType: IntrospectionNamedTypeRef; + readonly mutationType: Maybe>; + readonly subscriptionType: Maybe>; + readonly types: ReadonlyArray; + readonly directives: ReadonlyArray; +} + +export type IntrospectionType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType + | IntrospectionInputObjectType; + +export type IntrospectionOutputType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType; + +export type IntrospectionInputType = IntrospectionScalarType | IntrospectionEnumType | IntrospectionInputObjectType; + +export interface IntrospectionScalarType { + readonly kind: "SCALAR"; + readonly name: string; + readonly description?: Maybe; +} + +export interface IntrospectionObjectType { + readonly kind: "OBJECT"; + readonly name: string; + readonly description?: Maybe; + readonly fields: ReadonlyArray; + readonly interfaces: ReadonlyArray>; +} + +export interface IntrospectionInterfaceType { + readonly kind: "INTERFACE"; + readonly name: string; + readonly description?: Maybe; + readonly fields: ReadonlyArray; + readonly possibleTypes: ReadonlyArray>; +} + +export interface IntrospectionUnionType { + readonly kind: "UNION"; + readonly name: string; + readonly description?: Maybe; + readonly possibleTypes: ReadonlyArray>; +} + +export interface IntrospectionEnumType { + readonly kind: "ENUM"; + readonly name: string; + readonly description?: Maybe; + readonly enumValues: ReadonlyArray; +} + +export interface IntrospectionInputObjectType { + readonly kind: "INPUT_OBJECT"; + readonly name: string; + readonly description?: Maybe; + readonly inputFields: ReadonlyArray; +} + +export interface IntrospectionListTypeRef { + readonly kind: "LIST"; + readonly ofType: T; +} + +export interface IntrospectionNonNullTypeRef { + readonly kind: "NON_NULL"; + readonly ofType: T; +} + +export type IntrospectionTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef | IntrospectionListTypeRef>; + +export type IntrospectionOutputTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef | IntrospectionListTypeRef>; + +export type IntrospectionInputTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef | IntrospectionListTypeRef>; + +export interface IntrospectionNamedTypeRef { + readonly kind: T["kind"]; + readonly name: string; +} + +export interface IntrospectionField { + readonly name: string; + readonly description?: Maybe; + readonly args: ReadonlyArray; + readonly type: IntrospectionOutputTypeRef; + readonly isDeprecated: boolean; + readonly deprecationReason?: Maybe; +} + +export interface IntrospectionInputValue { + readonly name: string; + readonly description?: Maybe; + readonly type: IntrospectionInputTypeRef; + readonly defaultValue?: Maybe; +} + +export interface IntrospectionEnumValue { + readonly name: string; + readonly description?: Maybe; + readonly isDeprecated: boolean; + readonly deprecationReason?: Maybe; +} + +export interface IntrospectionDirective { + readonly name: string; + readonly description?: Maybe; + readonly locations: ReadonlyArray; + readonly args: ReadonlyArray; +} diff --git a/node_modules/@types/graphql/utilities/isValidJSValue.d.ts b/node_modules/@types/graphql/utilities/isValidJSValue.d.ts new file mode 100644 index 0000000..e8ee3fd --- /dev/null +++ b/node_modules/@types/graphql/utilities/isValidJSValue.d.ts @@ -0,0 +1,8 @@ +import { GraphQLInputType } from "../type/definition"; + +/** + * Deprecated. Use coerceValue() directly for richer information. + * + * This function will be removed in v15 + */ +export function isValidJSValue(value: any, type: GraphQLInputType): string[]; diff --git a/node_modules/@types/graphql/utilities/isValidLiteralValue.d.ts b/node_modules/@types/graphql/utilities/isValidLiteralValue.d.ts new file mode 100644 index 0000000..3ea79e8 --- /dev/null +++ b/node_modules/@types/graphql/utilities/isValidLiteralValue.d.ts @@ -0,0 +1,12 @@ +import { GraphQLError } from "../error/GraphQLError"; +import { ValueNode } from "../language/ast"; +import { GraphQLInputType } from "../type/definition"; + +/** + * Utility which determines if a value literal node is valid for an input type. + * + * Deprecated. Rely on validation for documents containing literal values. + * + * This function will be removed in v15 + */ +export function isValidLiteralValue(type: GraphQLInputType, valueNode: ValueNode): ReadonlyArray; diff --git a/node_modules/@types/graphql/utilities/lexicographicSortSchema.d.ts b/node_modules/@types/graphql/utilities/lexicographicSortSchema.d.ts new file mode 100644 index 0000000..e52ecb0 --- /dev/null +++ b/node_modules/@types/graphql/utilities/lexicographicSortSchema.d.ts @@ -0,0 +1,6 @@ +import { GraphQLSchema } from "../type/schema"; + +/** + * Sort GraphQLSchema. + */ +export function lexicographicSortSchema(schema: GraphQLSchema): GraphQLSchema; diff --git a/node_modules/@types/graphql/utilities/schemaPrinter.d.ts b/node_modules/@types/graphql/utilities/schemaPrinter.d.ts new file mode 100644 index 0000000..2105942 --- /dev/null +++ b/node_modules/@types/graphql/utilities/schemaPrinter.d.ts @@ -0,0 +1,27 @@ +import { GraphQLSchema } from "../type/schema"; +import { GraphQLType, GraphQLNamedType } from "../type/definition"; + +export interface Options { + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean; +} + +/** + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function printSchema(schema: GraphQLSchema, options?: Options): string; + +export function printIntrospectionSchema(schema: GraphQLSchema, options?: Options): string; + +export function printType(type: GraphQLNamedType, options?: Options): string; diff --git a/node_modules/@types/graphql/utilities/separateOperations.d.ts b/node_modules/@types/graphql/utilities/separateOperations.d.ts new file mode 100644 index 0000000..80907c0 --- /dev/null +++ b/node_modules/@types/graphql/utilities/separateOperations.d.ts @@ -0,0 +1,9 @@ +import { DocumentNode, OperationDefinitionNode } from "../language/ast"; + +/** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + */ +export function separateOperations(documentAST: DocumentNode): { [key: string]: DocumentNode }; diff --git a/node_modules/@types/graphql/utilities/typeComparators.d.ts b/node_modules/@types/graphql/utilities/typeComparators.d.ts new file mode 100644 index 0000000..858b394 --- /dev/null +++ b/node_modules/@types/graphql/utilities/typeComparators.d.ts @@ -0,0 +1,28 @@ +import { GraphQLType, GraphQLCompositeType, GraphQLAbstractType } from "../type/definition"; +import { GraphQLSchema } from "../type/schema"; + +/** + * Provided two types, return true if the types are equal (invariant). + */ +export function isEqualType(typeA: GraphQLType, typeB: GraphQLType): boolean; + +/** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ +export function isTypeSubTypeOf(schema: GraphQLSchema, maybeSubType: GraphQLType, superType: GraphQLType): boolean; + +/** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ +export function doTypesOverlap( + schema: GraphQLSchema, + typeA: GraphQLCompositeType, + typeB: GraphQLCompositeType +): boolean; diff --git a/node_modules/@types/graphql/utilities/typeFromAST.d.ts b/node_modules/@types/graphql/utilities/typeFromAST.d.ts new file mode 100644 index 0000000..362bc0c --- /dev/null +++ b/node_modules/@types/graphql/utilities/typeFromAST.d.ts @@ -0,0 +1,16 @@ +import { TypeNode, NamedTypeNode, ListTypeNode, NonNullTypeNode } from "../language/ast"; +import { GraphQLType, GraphQLNullableType, GraphQLNamedType, GraphQLList, GraphQLNonNull } from "../type/definition"; +import { GraphQLSchema } from "../type/schema"; + +/** + * Given a Schema and an AST node describing a type, return a GraphQLType + * definition which applies to that type. For example, if provided the parsed + * AST node for `[User]`, a GraphQLList instance will be returned, containing + * the type called "User" found in the schema. If a type called "User" is not + * found in the schema, then undefined will be returned. + */ +export function typeFromAST(schema: GraphQLSchema, typeNode: NamedTypeNode): GraphQLNamedType | undefined; + +export function typeFromAST(schema: GraphQLSchema, typeNode: ListTypeNode): GraphQLList | undefined; + +export function typeFromAST(schema: GraphQLSchema, typeNode: NonNullTypeNode): GraphQLNonNull | undefined; diff --git a/node_modules/@types/graphql/utilities/valueFromAST.d.ts b/node_modules/@types/graphql/utilities/valueFromAST.d.ts new file mode 100644 index 0000000..6ffcefe --- /dev/null +++ b/node_modules/@types/graphql/utilities/valueFromAST.d.ts @@ -0,0 +1,29 @@ +import Maybe from "../tsutils/Maybe"; +import { GraphQLInputType } from "../type/definition"; +import { ValueNode, VariableNode, ListValueNode, ObjectValueNode } from "../language/ast"; + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Mixed | + * | NullValue | null | + * + */ +export function valueFromAST( + valueNode: Maybe, + type: GraphQLInputType, + variables?: Maybe<{ [key: string]: any }> +): any; diff --git a/node_modules/@types/graphql/utilities/valueFromASTUntyped.d.ts b/node_modules/@types/graphql/utilities/valueFromASTUntyped.d.ts new file mode 100644 index 0000000..47fb4fc --- /dev/null +++ b/node_modules/@types/graphql/utilities/valueFromASTUntyped.d.ts @@ -0,0 +1,20 @@ +import Maybe from "../tsutils/Maybe"; +import { ValueNode } from "../language/ast"; + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value + * will reflect the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * + */ +export function valueFromASTUntyped(valueNode: ValueNode, variables?: Maybe<{ [key: string]: any }>): any; diff --git a/node_modules/@types/graphql/validation/ValidationContext.d.ts b/node_modules/@types/graphql/validation/ValidationContext.d.ts new file mode 100644 index 0000000..9771934 --- /dev/null +++ b/node_modules/@types/graphql/validation/ValidationContext.d.ts @@ -0,0 +1,83 @@ +import Maybe from "../tsutils/Maybe"; +import { GraphQLError } from "../error"; +import { + DocumentNode, + OperationDefinitionNode, + VariableNode, + SelectionSetNode, + FragmentSpreadNode, + FragmentDefinitionNode, +} from "../language/ast"; +import { GraphQLSchema } from "../type/schema"; +import { + GraphQLInputType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, + GraphQLArgument, +} from "../type/definition"; +import { GraphQLDirective } from "../type/directives"; +import { TypeInfo } from "../utilities/TypeInfo"; +import { ASTVisitor } from "../language/visitor"; + +type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; +type VariableUsage = { + readonly node: VariableNode; + readonly type: Maybe; + readonly defaultValue: Maybe; +}; + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +export class ASTValidationContext { + constructor(ast: DocumentNode); + + reportError(error: GraphQLError): undefined; + + getErrors(): ReadonlyArray; + + getDocument(): DocumentNode; +} + +export class SDLValidationContext extends ASTValidationContext { + constructor(ast: DocumentNode, schema?: Maybe); + + getSchema(): Maybe; +} + +export type SDLValidationRule = (context: SDLValidationContext) => ASTVisitor; + +export class ValidationContext extends ASTValidationContext { + constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo); + + getSchema(): GraphQLSchema; + + getFragment(name: string): Maybe; + + getFragmentSpreads(node: SelectionSetNode): ReadonlyArray; + + getRecursivelyReferencedFragments(operation: OperationDefinitionNode): ReadonlyArray; + + getVariableUsages(node: NodeWithSelectionSet): ReadonlyArray; + + getRecursiveVariableUsages(operation: OperationDefinitionNode): ReadonlyArray; + + getType(): Maybe; + + getParentType(): Maybe; + + getInputType(): Maybe; + + getParentInputType(): Maybe; + + getFieldDef(): Maybe>; + + getDirective(): Maybe; + + getArgument(): Maybe; +} + +export type ValidationRule = (context: ValidationContext) => ASTVisitor; diff --git a/node_modules/@types/graphql/validation/index.d.ts b/node_modules/@types/graphql/validation/index.d.ts new file mode 100644 index 0000000..22c1008 --- /dev/null +++ b/node_modules/@types/graphql/validation/index.d.ts @@ -0,0 +1,80 @@ +export { validate } from "./validate"; + +export { ValidationContext } from "./ValidationContext"; + +export { specifiedRules } from "./specifiedRules"; + +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +export { FieldsOnCorrectType as FieldsOnCorrectTypeRule } from "./rules/FieldsOnCorrectType"; + +// Spec Section: "Fragments on Composite Types" +export { FragmentsOnCompositeTypes as FragmentsOnCompositeTypesRule } from "./rules/FragmentsOnCompositeTypes"; + +// Spec Section: "Argument Names" +export { KnownArgumentNames as KnownArgumentNamesRule } from "./rules/KnownArgumentNames"; + +// Spec Section: "Directives Are Defined" +export { KnownDirectives as KnownDirectivesRule } from "./rules/KnownDirectives"; + +// Spec Section: "Fragment spread target defined" +export { KnownFragmentNames as KnownFragmentNamesRule } from "./rules/KnownFragmentNames"; + +// Spec Section: "Fragment Spread Type Existence" +export { KnownTypeNames as KnownTypeNamesRule } from "./rules/KnownTypeNames"; + +// Spec Section: "Lone Anonymous Operation" +export { LoneAnonymousOperation as LoneAnonymousOperationRule } from "./rules/LoneAnonymousOperation"; + +// Spec Section: "Fragments must not form cycles" +export { NoFragmentCycles as NoFragmentCyclesRule } from "./rules/NoFragmentCycles"; + +// Spec Section: "All Variable Used Defined" +export { NoUndefinedVariables as NoUndefinedVariablesRule } from "./rules/NoUndefinedVariables"; + +// Spec Section: "Fragments must be used" +export { NoUnusedFragments as NoUnusedFragmentsRule } from "./rules/NoUnusedFragments"; + +// Spec Section: "All Variables Used" +export { NoUnusedVariables as NoUnusedVariablesRule } from "./rules/NoUnusedVariables"; + +// Spec Section: "Field Selection Merging" +export { OverlappingFieldsCanBeMerged as OverlappingFieldsCanBeMergedRule } from "./rules/OverlappingFieldsCanBeMerged"; + +// Spec Section: "Fragment spread is possible" +export { PossibleFragmentSpreads as PossibleFragmentSpreadsRule } from "./rules/PossibleFragmentSpreads"; + +// Spec Section: "Argument Optionality" +export { ProvidedRequiredArguments as ProvidedRequiredArgumentsRule } from "./rules/ProvidedRequiredArguments"; + +// Spec Section: "Leaf Field Selections" +export { ScalarLeafs as ScalarLeafsRule } from "./rules/ScalarLeafs"; + +// Spec Section: "Subscriptions with Single Root Field" +export { SingleFieldSubscriptions as SingleFieldSubscriptionsRule } from "./rules/SingleFieldSubscriptions"; + +// Spec Section: "Argument Uniqueness" +export { UniqueArgumentNames as UniqueArgumentNamesRule } from "./rules/UniqueArgumentNames"; + +// Spec Section: "Directives Are Unique Per Location" +export { UniqueDirectivesPerLocation as UniqueDirectivesPerLocationRule } from "./rules/UniqueDirectivesPerLocation"; + +// Spec Section: "Fragment Name Uniqueness" +export { UniqueFragmentNames as UniqueFragmentNamesRule } from "./rules/UniqueFragmentNames"; + +// Spec Section: "Input Object Field Uniqueness" +export { UniqueInputFieldNames as UniqueInputFieldNamesRule } from "./rules/UniqueInputFieldNames"; + +// Spec Section: "Operation Name Uniqueness" +export { UniqueOperationNames as UniqueOperationNamesRule } from "./rules/UniqueOperationNames"; + +// Spec Section: "Variable Uniqueness" +export { UniqueVariableNames as UniqueVariableNamesRule } from "./rules/UniqueVariableNames"; + +// Spec Section: "Values Type Correctness" +export { ValuesOfCorrectType as ValuesOfCorrectTypeRule } from "./rules/ValuesOfCorrectType"; + +// Spec Section: "Variables are Input Types" +export { VariablesAreInputTypes as VariablesAreInputTypesRule } from "./rules/VariablesAreInputTypes"; + +// Spec Section: "All Variable Usages Are Allowed" +export { VariablesInAllowedPosition as VariablesInAllowedPositionRule } from "./rules/VariablesInAllowedPosition"; diff --git a/node_modules/@types/graphql/validation/rules/ExecutableDefinitions.d.ts b/node_modules/@types/graphql/validation/rules/ExecutableDefinitions.d.ts new file mode 100644 index 0000000..d02e64a --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/ExecutableDefinitions.d.ts @@ -0,0 +1,12 @@ +import { ASTValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function nonExecutableDefinitionMessage(defName: string): string; + +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + */ +export function ExecutableDefinitions(context: ASTValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/FieldsOnCorrectType.d.ts b/node_modules/@types/graphql/validation/rules/FieldsOnCorrectType.d.ts new file mode 100644 index 0000000..50d1541 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/FieldsOnCorrectType.d.ts @@ -0,0 +1,10 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ +export function FieldsOnCorrectType(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/FragmentsOnCompositeTypes.d.ts b/node_modules/@types/graphql/validation/rules/FragmentsOnCompositeTypes.d.ts new file mode 100644 index 0000000..aacc80a --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/FragmentsOnCompositeTypes.d.ts @@ -0,0 +1,15 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function inlineFragmentOnNonCompositeErrorMessage(type: string): string; + +export function fragmentOnNonCompositeErrorMessage(fragName: string, type: string): string; + +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ +export function FragmentsOnCompositeTypes(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/KnownArgumentNames.d.ts b/node_modules/@types/graphql/validation/rules/KnownArgumentNames.d.ts new file mode 100644 index 0000000..4326197 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/KnownArgumentNames.d.ts @@ -0,0 +1,26 @@ +import { ValidationContext, SDLValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function unknownArgMessage( + argName: string, + fieldName: string, + typeName: string, + suggestedArgs: Array +): string; + +export function unknownDirectiveArgMessage( + argName: string, + directiveName: string, + suggestedArgs: Array +): string; + +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ +export function KnownArgumentNames(context: ValidationContext): ASTVisitor; + +// @internal +export function KnownArgumentNamesOnDirectives(context: ValidationContext | SDLValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/KnownDirectives.d.ts b/node_modules/@types/graphql/validation/rules/KnownDirectives.d.ts new file mode 100644 index 0000000..b98e746 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/KnownDirectives.d.ts @@ -0,0 +1,14 @@ +import { ValidationContext, SDLValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function unknownDirectiveMessage(directiveName: string): string; + +export function misplacedDirectiveMessage(directiveName: string, location: string): string; + +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ +export function KnownDirectives(context: ValidationContext | SDLValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/KnownFragmentNames.d.ts b/node_modules/@types/graphql/validation/rules/KnownFragmentNames.d.ts new file mode 100644 index 0000000..6af8d4b --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/KnownFragmentNames.d.ts @@ -0,0 +1,12 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function unknownFragmentMessage(fragName: string): string; + +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ +export function KnownFragmentNames(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/KnownTypeNames.d.ts b/node_modules/@types/graphql/validation/rules/KnownTypeNames.d.ts new file mode 100644 index 0000000..7824a81 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/KnownTypeNames.d.ts @@ -0,0 +1,12 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function unknownTypeMessage(typeName: string, suggestedTypes: Array): string; + +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ +export function KnownTypeNames(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/LoneAnonymousOperation.d.ts b/node_modules/@types/graphql/validation/rules/LoneAnonymousOperation.d.ts new file mode 100644 index 0000000..62fa334 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/LoneAnonymousOperation.d.ts @@ -0,0 +1,12 @@ +import { ASTValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function anonOperationNotAloneMessage(): string; + +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ +export function LoneAnonymousOperation(context: ASTValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/LoneSchemaDefinition.d.ts b/node_modules/@types/graphql/validation/rules/LoneSchemaDefinition.d.ts new file mode 100644 index 0000000..93ed4ae --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/LoneSchemaDefinition.d.ts @@ -0,0 +1,13 @@ +import { SDLValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function schemaDefinitionNotAloneMessage(): string; + +export function canNotDefineSchemaWithinExtensionMessage(): string; + +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ +export function LoneSchemaDefinition(context: SDLValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/NoFragmentCycles.d.ts b/node_modules/@types/graphql/validation/rules/NoFragmentCycles.d.ts new file mode 100644 index 0000000..b598455 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/NoFragmentCycles.d.ts @@ -0,0 +1,6 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function cycleErrorMessage(fragName: string, spreadNames: Array): string; + +export function NoFragmentCycles(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/NoUndefinedVariables.d.ts b/node_modules/@types/graphql/validation/rules/NoUndefinedVariables.d.ts new file mode 100644 index 0000000..dc2c6f8 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/NoUndefinedVariables.d.ts @@ -0,0 +1,13 @@ +import Maybe from "../../tsutils/Maybe"; +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function undefinedVarMessage(varName: string, opName: Maybe): string; + +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ +export function NoUndefinedVariables(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/NoUnusedFragments.d.ts b/node_modules/@types/graphql/validation/rules/NoUnusedFragments.d.ts new file mode 100644 index 0000000..f22d1d9 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/NoUnusedFragments.d.ts @@ -0,0 +1,12 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function unusedFragMessage(fragName: string): string; + +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ +export function NoUnusedFragments(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/NoUnusedVariables.d.ts b/node_modules/@types/graphql/validation/rules/NoUnusedVariables.d.ts new file mode 100644 index 0000000..2bd765e --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/NoUnusedVariables.d.ts @@ -0,0 +1,13 @@ +import Maybe from "../../tsutils/Maybe"; +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function unusedVariableMessage(varName: string, opName: Maybe): string; + +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ +export function NoUnusedVariables(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/OverlappingFieldsCanBeMerged.d.ts b/node_modules/@types/graphql/validation/rules/OverlappingFieldsCanBeMerged.d.ts new file mode 100644 index 0000000..e657134 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/OverlappingFieldsCanBeMerged.d.ts @@ -0,0 +1,19 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function fieldsConflictMessage(responseName: string, reason: ConflictReasonMessage): string; + +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ +export function OverlappingFieldsCanBeMerged(context: ValidationContext): ASTVisitor; + +// Field name and reason. +type ConflictReason = [string, string]; + +// Reason is a string, or a nested list of conflicts. +type ConflictReasonMessage = string | Array; diff --git a/node_modules/@types/graphql/validation/rules/PossibleFragmentSpreads.d.ts b/node_modules/@types/graphql/validation/rules/PossibleFragmentSpreads.d.ts new file mode 100644 index 0000000..bf5a19d --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/PossibleFragmentSpreads.d.ts @@ -0,0 +1,15 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function typeIncompatibleSpreadMessage(fragName: string, parentType: string, fragType: string): string; + +export function typeIncompatibleAnonSpreadMessage(parentType: string, fragType: string): string; + +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ +export function PossibleFragmentSpreads(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/ProvidedRequiredArguments.d.ts b/node_modules/@types/graphql/validation/rules/ProvidedRequiredArguments.d.ts new file mode 100644 index 0000000..c4fb880 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/ProvidedRequiredArguments.d.ts @@ -0,0 +1,17 @@ +import { ValidationContext, SDLValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function missingFieldArgMessage(fieldName: string, argName: string, type: string): string; + +export function missingDirectiveArgMessage(directiveName: string, argName: string, type: string): string; + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ +export function ProvidedRequiredArguments(context: ValidationContext): ASTVisitor; + +// @internal +export function ProvidedRequiredArgumentsOnDirectives(context: ValidationContext | SDLValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/ScalarLeafs.d.ts b/node_modules/@types/graphql/validation/rules/ScalarLeafs.d.ts new file mode 100644 index 0000000..a0456d3 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/ScalarLeafs.d.ts @@ -0,0 +1,14 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function noSubselectionAllowedMessage(fieldName: string, type: string): string; + +export function requiredSubselectionMessage(fieldName: string, type: string): string; + +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ +export function ScalarLeafs(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/SingleFieldSubscriptions.d.ts b/node_modules/@types/graphql/validation/rules/SingleFieldSubscriptions.d.ts new file mode 100644 index 0000000..8723468 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/SingleFieldSubscriptions.d.ts @@ -0,0 +1,12 @@ +import Maybe from "../../tsutils/Maybe"; +import { ASTValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function singleFieldOnlyMessage(name: Maybe): string; + +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ +export function SingleFieldSubscriptions(context: ASTValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/UniqueArgumentNames.d.ts b/node_modules/@types/graphql/validation/rules/UniqueArgumentNames.d.ts new file mode 100644 index 0000000..851ba97 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/UniqueArgumentNames.d.ts @@ -0,0 +1,12 @@ +import { ASTValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function duplicateArgMessage(argName: string): string; + +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ +export function UniqueArgumentNames(context: ASTValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/UniqueDirectivesPerLocation.d.ts b/node_modules/@types/graphql/validation/rules/UniqueDirectivesPerLocation.d.ts new file mode 100644 index 0000000..2fb2205 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/UniqueDirectivesPerLocation.d.ts @@ -0,0 +1,12 @@ +import { ASTValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function duplicateDirectiveMessage(directiveName: string): string; + +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all directives at a given location + * are uniquely named. + */ +export function UniqueDirectivesPerLocation(context: ASTValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/UniqueFragmentNames.d.ts b/node_modules/@types/graphql/validation/rules/UniqueFragmentNames.d.ts new file mode 100644 index 0000000..80ed4bd --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/UniqueFragmentNames.d.ts @@ -0,0 +1,11 @@ +import { ASTValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function duplicateFragmentNameMessage(fragName: string): string; + +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ +export function UniqueFragmentNames(context: ASTValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/UniqueInputFieldNames.d.ts b/node_modules/@types/graphql/validation/rules/UniqueInputFieldNames.d.ts new file mode 100644 index 0000000..ea58177 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/UniqueInputFieldNames.d.ts @@ -0,0 +1,12 @@ +import { ASTValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function duplicateInputFieldMessage(fieldName: string): string; + +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ +export function UniqueInputFieldNames(context: ASTValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/UniqueOperationNames.d.ts b/node_modules/@types/graphql/validation/rules/UniqueOperationNames.d.ts new file mode 100644 index 0000000..c9d25a7 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/UniqueOperationNames.d.ts @@ -0,0 +1,11 @@ +import { ASTValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function duplicateOperationNameMessage(operationName: string): string; + +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ +export function UniqueOperationNames(context: ASTValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/UniqueVariableNames.d.ts b/node_modules/@types/graphql/validation/rules/UniqueVariableNames.d.ts new file mode 100644 index 0000000..ac79060 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/UniqueVariableNames.d.ts @@ -0,0 +1,11 @@ +import { ASTValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function duplicateVariableMessage(variableName: string): string; + +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ +export function UniqueVariableNames(context: ASTValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/ValuesOfCorrectType.d.ts b/node_modules/@types/graphql/validation/rules/ValuesOfCorrectType.d.ts new file mode 100644 index 0000000..406ece7 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/ValuesOfCorrectType.d.ts @@ -0,0 +1,16 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function badValueMessage(typeName: string, valueName: string, message?: string): string; + +export function requiredFieldMessage(typeName: string, fieldName: string, fieldTypeName: string): string; + +export function unknownFieldMessage(typeName: string, fieldName: string, message?: string): string; + +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + */ +export function ValuesOfCorrectType(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/VariablesAreInputTypes.d.ts b/node_modules/@types/graphql/validation/rules/VariablesAreInputTypes.d.ts new file mode 100644 index 0000000..665e707 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/VariablesAreInputTypes.d.ts @@ -0,0 +1,12 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function nonInputTypeOnVarMessage(variableName: string, typeName: string): string; + +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ +export function VariablesAreInputTypes(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/rules/VariablesInAllowedPosition.d.ts b/node_modules/@types/graphql/validation/rules/VariablesInAllowedPosition.d.ts new file mode 100644 index 0000000..1937ac5 --- /dev/null +++ b/node_modules/@types/graphql/validation/rules/VariablesInAllowedPosition.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function badVarPosMessage(varName: string, varType: string, expectedType: string): string; + +/** + * Variables passed to field arguments conform to type + */ +export function VariablesInAllowedPosition(context: ValidationContext): ASTVisitor; diff --git a/node_modules/@types/graphql/validation/specifiedRules.d.ts b/node_modules/@types/graphql/validation/specifiedRules.d.ts new file mode 100644 index 0000000..071642b --- /dev/null +++ b/node_modules/@types/graphql/validation/specifiedRules.d.ts @@ -0,0 +1,92 @@ +import { ValidationRule, SDLValidationRule } from "./ValidationContext"; + +// Spec Section: "Executable Definitions" +import { ExecutableDefinitions } from "./rules/ExecutableDefinitions"; + +// Spec Section: "Operation Name Uniqueness" +import { UniqueOperationNames } from "./rules/UniqueOperationNames"; + +// Spec Section: "Lone Anonymous Operation" +import { LoneAnonymousOperation } from "./rules/LoneAnonymousOperation"; + +// Spec Section: "Subscriptions with Single Root Field" +import { SingleFieldSubscriptions } from "./rules/SingleFieldSubscriptions"; + +// Spec Section: "Fragment Spread Type Existence" +import { KnownTypeNames } from "./rules/KnownTypeNames"; + +// Spec Section: "Fragments on Composite Types" +import { FragmentsOnCompositeTypes } from "./rules/FragmentsOnCompositeTypes"; + +// Spec Section: "Variables are Input Types" +import { VariablesAreInputTypes } from "./rules/VariablesAreInputTypes"; + +// Spec Section: "Leaf Field Selections" +import { ScalarLeafs } from "./rules/ScalarLeafs"; + +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +import { FieldsOnCorrectType } from "./rules/FieldsOnCorrectType"; + +// Spec Section: "Fragment Name Uniqueness" +import { UniqueFragmentNames } from "./rules/UniqueFragmentNames"; + +// Spec Section: "Fragment spread target defined" +import { KnownFragmentNames } from "./rules/KnownFragmentNames"; + +// Spec Section: "Fragments must be used" +import { NoUnusedFragments } from "./rules/NoUnusedFragments"; + +// Spec Section: "Fragment spread is possible" +import { PossibleFragmentSpreads } from "./rules/PossibleFragmentSpreads"; + +// Spec Section: "Fragments must not form cycles" +import { NoFragmentCycles } from "./rules/NoFragmentCycles"; + +// Spec Section: "Variable Uniqueness" +import { UniqueVariableNames } from "./rules/UniqueVariableNames"; + +// Spec Section: "All Variable Used Defined" +import { NoUndefinedVariables } from "./rules/NoUndefinedVariables"; + +// Spec Section: "All Variables Used" +import { NoUnusedVariables } from "./rules/NoUnusedVariables"; + +// Spec Section: "Directives Are Defined" +import { KnownDirectives } from "./rules/KnownDirectives"; + +// Spec Section: "Directives Are Unique Per Location" +import { UniqueDirectivesPerLocation } from "./rules/UniqueDirectivesPerLocation"; + +// Spec Section: "Argument Names" +import { KnownArgumentNames } from "./rules/KnownArgumentNames"; + +// Spec Section: "Argument Uniqueness" +import { UniqueArgumentNames } from "./rules/UniqueArgumentNames"; + +// Spec Section: "Value Type Correctness" +import { ValuesOfCorrectType } from "./rules/ValuesOfCorrectType"; + +// Spec Section: "Argument Optionality" +import { ProvidedRequiredArguments } from "./rules/ProvidedRequiredArguments"; + +// Spec Section: "All Variable Usages Are Allowed" +import { VariablesInAllowedPosition } from "./rules/VariablesInAllowedPosition"; + +// Spec Section: "Field Selection Merging" +import { OverlappingFieldsCanBeMerged } from "./rules/OverlappingFieldsCanBeMerged"; + +// Spec Section: "Input Object Field Uniqueness" +import { UniqueInputFieldNames } from "./rules/UniqueInputFieldNames"; + +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ +export const specifiedRules: ReadonlyArray; + +import { LoneSchemaDefinition } from "./rules/LoneSchemaDefinition"; + +// @internal +export const specifiedSDLRules: ReadonlyArray; diff --git a/node_modules/@types/graphql/validation/validate.d.ts b/node_modules/@types/graphql/validation/validate.d.ts new file mode 100644 index 0000000..7036f5c --- /dev/null +++ b/node_modules/@types/graphql/validation/validate.d.ts @@ -0,0 +1,44 @@ +import { GraphQLError } from "../error"; +import { DocumentNode } from "../language/ast"; +import { GraphQLSchema } from "../type/schema"; +import { TypeInfo } from "../utilities/TypeInfo"; +import { ValidationRule } from "./ValidationContext"; + +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ +export function validate( + schema: GraphQLSchema, + documentAST: DocumentNode, + rules?: ReadonlyArray, + typeInfo?: TypeInfo +): ReadonlyArray; + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDL(documentAST: DocumentNode): undefined; + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDLExtension(documentAST: DocumentNode, schema: GraphQLSchema): undefined; diff --git a/node_modules/@types/meteor/LICENSE b/node_modules/@types/meteor/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/node_modules/@types/meteor/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/meteor/README.md b/node_modules/@types/meteor/README.md new file mode 100644 index 0000000..9898238 --- /dev/null +++ b/node_modules/@types/meteor/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/meteor` + +# Summary +This package contains type definitions for Meteor (http://www.meteor.com/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/meteor + +Additional Details + * Last updated: Mon, 10 Sep 2018 22:02:19 GMT + * Dependencies: underscore, http, connect + * Global values: Accounts, App, Assets, Blaze, BrowserPolicy, Cordova, DDP, DDPRateLimiter, EJSON, Email, HTTP, MailComposer, Match, Meteor, Mongo, Npm, Package, Random, ReactiveVar, Session, Template, Tinytest, Tracker, check, console, execFileAsync, execFileSync + +# Credits +These definitions were written by Alex Borodach , Dave Allen , Olivier Refalo , Daniel Neveux , Birk Skyum , Arda TANRIKULU , Stefan Holzapfel , Andrey Markeev , Leon Machens . diff --git a/node_modules/@types/meteor/accounts-base.d.ts b/node_modules/@types/meteor/accounts-base.d.ts new file mode 100644 index 0000000..8690a4d --- /dev/null +++ b/node_modules/@types/meteor/accounts-base.d.ts @@ -0,0 +1,150 @@ +declare module "meteor/accounts-base" { + interface URLS { + resetPassword: (token: string) => string; + verifyEmail: (token: string) => string; + enrollAccount: (token: string) => string; + } + + interface EmailFields { + from?: () => string; + subject?: (user: Meteor.User) => string; + text?: (user: Meteor.User, url: string) => string; + html?: (user: Meteor.User, url: string) => string; + } + + module Accounts { + var urls: URLS; + + function user(): Meteor.User; + + function userId(): string; + + function createUser(options: { + username?: string; + email?: string; + password?: string; + profile?: Object; + }, callback?: Function): string; + + function config(options: { + sendVerificationEmail?: boolean; + forbidClientAccountCreation?: boolean; + restrictCreationByEmailDomain?: string | Function; + loginExpirationInDays?: number; + oauthSecretKey?: string; + passwordResetTokenExpirationInDays?: number; + passwordEnrollTokenExpirationInDays?: number; + ambiguousErrorMessages?: boolean; + }): void; + + function onLogin(func: Function): { + stop: () => void + }; + + function onLoginFailure(func: Function): { + stop: () => void + }; + + function loginServicesConfigured(): boolean; + + function onPageLoadLogin(func: Function): void; + } + + module Accounts { + function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; + + function forgotPassword(options: { + email?: string; + }, callback?: Function): void; + + function resetPassword(token: string, newPassword: string, callback?: Function): void; + + function verifyEmail(token: string, callback?: Function): void; + + function onEmailVerificationLink(callback: Function): void; + + function onEnrollmentLink(callback: Function): void; + + function onResetPasswordLink(callback: Function): void; + + function loggingIn(): boolean; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + + var ui: { + config(options: { + requestPermissions?: Object; + requestOfflineToken?: Object; + forceApprovalPrompt?: Object; + passwordSignupFields?: string; + }): void; + }; + } + + interface Header { + [id: string]: string; + } + + interface EmailTemplates { + from: string; + siteName: string; + headers?: Header; + resetPassword: EmailFields; + enrollAccount: EmailFields; + verifyEmail: EmailFields; + } + + module Accounts { + var emailTemplates: EmailTemplates; + + function addEmail(userId: string, newEmail: string, verified?: boolean): void; + + function removeEmail(userId: string, email: string): void; + + function onCreateUser(func: Function): void; + + function findUserByEmail(email: string): Object; + + function findUserByUsername(username: string): Object; + + function sendEnrollmentEmail(userId: string, email?: string): void; + + function sendResetPasswordEmail(userId: string, email?: string): void; + + function sendVerificationEmail(userId: string, email?: string): void; + + function setUsername(userId: string, newUsername: string): void; + + function setPassword(userId: string, newPassword: string, options?: { + logout?: Object; + }): void; + + function validateNewUser(func: Function): boolean; + + function validateLoginAttempt(func: Function): { + stop: () => void + }; + + function _hashPassword(password: string): { digest: string; algorithm: string; }; + + interface IValidateLoginAttemptCbOpts { + type: string; + allowed: boolean; + error: Meteor.Error; + user: Meteor.User; + connection: Meteor.Connection; + methodName: string; + methodArguments: any[]; + } + } + + module Accounts { + function onLogout(func: Function): void; + } + + module Accounts { + function onLogout(func: (user: Meteor.User, connection: Meteor.Connection) => void): void; + } +} diff --git a/node_modules/@types/meteor/blaze.d.ts b/node_modules/@types/meteor/blaze.d.ts new file mode 100644 index 0000000..4afca73 --- /dev/null +++ b/node_modules/@types/meteor/blaze.d.ts @@ -0,0 +1,109 @@ +declare module "meteor/blaze" { + module Blaze { + var View: ViewStatic; + + interface ViewStatic { + new (name?: string, renderFunction?: Function): View; + } + + interface View { + name: string; + parentView: View; + isCreated: boolean; + isRendered: boolean; + isDestroyed: boolean; + renderCount: number; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + onViewCreated(func: Function): void; + onViewReady(func: Function): void; + onViewDestroyed(func: Function): void; + firstNode(): Node; + lastNode(): Node; + template: Template; + templateInstance(): TemplateInstance; + } + var currentView: View; + + function isTemplate(value: any): boolean; + + interface HelpersMap { + [key: string]: Function; + } + + interface EventsMap { + [key: string]: Function; + } + + var Template: TemplateStatic; + + interface TemplateStatic { + new (viewName?: string, renderFunction?: Function): Template; + + registerHelper(name: string, func: Function): void; + instance(): TemplateInstance; + currentData(): any; + parentData(numLevels: number): any; + } + + interface Template { + viewName: string; + renderFunction: Function; + constructView(): View; + head: Template; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + $: any; + onCreated(cb: Function): void; + onRendered(cb: Function): void; + onDestroyed(cb: Function): void; + created: Function; + rendered: Function; + destroyed: Function; + helpers(helpersMap: HelpersMap): void; + events(eventsMap: EventsMap): void; + } + + var TemplateInstance: TemplateInstanceStatic; + + interface TemplateInstanceStatic { + new (view: View): TemplateInstance; + } + + interface TemplateInstance { + $(selector: string): any; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + data: Object; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + firstNode: Object; + lastNode: Object; + subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + subscriptionsReady(): boolean; + view: Object; + } + + function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Let(bindings: Function, contentFunc: Function): View; + + function With(data: Object | Function, contentFunc: Function): View; + + function getData(elementOrView?: HTMLElement | View): Object; + + function getView(element?: HTMLElement): View; + + function remove(renderedView: View): void; + + function render(templateOrView: Template | View, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function renderWithData(templateOrView: Template | View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function toHTML(templateOrView: Template | View): string; + + function toHTMLWithData(templateOrView: Template | View, data: Object | Function): string; + } +} diff --git a/node_modules/@types/meteor/browser-policy-common.d.ts b/node_modules/@types/meteor/browser-policy-common.d.ts new file mode 100644 index 0000000..ae81483 --- /dev/null +++ b/node_modules/@types/meteor/browser-policy-common.d.ts @@ -0,0 +1,40 @@ +declare module "meteor/browser-policy-common" { + module BrowserPolicy { + var framing: { + disallow(): void; + restrictToOrigin(origin: string): void; + allowAll(): void; + }; + + var content: { + allowEval(): void; + allowInlineStyles(): void; + allowInlineScripts(): void; + allowSameOriginForAll(): void; + allowDataUrlForAll(): void; + allowOriginForAll(origin: string): void; + allowImageOrigin(origin: string): void; + allowMediaOrigin(origin: string): void; + allowFontOrigin(origin: string): void; + allowStyleOrigin(origin: string): void; + allowScriptOrigin(origin: string): void; + allowFrameOrigin(origin: string): void; + allowFrameAncestorsOrigin(origin: string): void; + allowContentTypeSniffing(): void; + allowAllContentOrigin(): void; + allowAllContentDataUrl(): void; + allowAllContentSameOrigin(): void; + allowConnectOrigin(origin: string): void; + allowObjectOrigin(origin: string): void; + + disallowAll(): void; + disallowInlineStyles(): void; + disallowEval(): void; + disallowInlineScripts(): void; + disallowFont(): void; + disallowObject(): void; + disallowAllContent(): void; + disallowConnect(): void; + }; + } +} diff --git a/node_modules/@types/meteor/check.d.ts b/node_modules/@types/meteor/check.d.ts new file mode 100644 index 0000000..bf3d447 --- /dev/null +++ b/node_modules/@types/meteor/check.d.ts @@ -0,0 +1,24 @@ +declare module "meteor/check" { + module Match { + var Any: any; + var String: any; + var Integer: any; + var Boolean: any; + var undefined: any; + var Object: any; + + function Maybe(pattern: any): boolean; + + function Optional(pattern: any): boolean; + + function ObjectIncluding(dico: any): boolean; + + function OneOf(...patterns: any[]): any; + + function Where(condition: any): any; + + function test(value: any, pattern: any): boolean; + } + + function check(value: any, pattern: any): void; +} diff --git a/node_modules/@types/meteor/ddp-rate-limiter.d.ts b/node_modules/@types/meteor/ddp-rate-limiter.d.ts new file mode 100644 index 0000000..7edd696 --- /dev/null +++ b/node_modules/@types/meteor/ddp-rate-limiter.d.ts @@ -0,0 +1,15 @@ +declare module "meteor/ddp-rate-limiter" { + module DDPRateLimiter { + interface Matcher { + type?: string | ((type: string) => boolean); + name?: string | ((name: string) => boolean); + userId?: string | ((userId: string) => boolean); + connectionId?: string | ((connectionId: string) => boolean); + clientAddress?: string | ((clientAddress: string) => boolean); + } + + function addRule(matcher: Matcher, numRequests: number, timeInterval: number): string; + + function removeRule(ruleId: string): boolean; + } +} diff --git a/node_modules/@types/meteor/ddp.d.ts b/node_modules/@types/meteor/ddp.d.ts new file mode 100644 index 0000000..7ae2439 --- /dev/null +++ b/node_modules/@types/meteor/ddp.d.ts @@ -0,0 +1,38 @@ +declare module "meteor/ddp" { + module DDP { + interface DDPStatic { + subscribe(name: string, ...rest: any[]): Meteor.SubscriptionHandle; + call(method: string, ...parameters: any[]): void; + apply(method: string, ...parameters: any[]): void; + methods(IMeteorMethodsDictionary: any): any; + status(): DDPStatus; + reconnect(): void; + disconnect(): void; + onReconnect(): void; + } + + function _allSubscriptionsReady(): boolean; + + type Status = 'connected' | 'connecting' | 'failed' | 'waiting' | 'offline'; + + interface DDPStatus { + connected: boolean; + status: Status; + retryCount: number; + retryTime?: number; + reason?: string; + } + + function connect(url: string): DDPStatic; + } + + module DDPCommon { + interface MethodInvocation { + new (options: {}): MethodInvocation; + + unblock(): void; + + setUserId(userId: number): void; + } + } +} diff --git a/node_modules/@types/meteor/ejson.d.ts b/node_modules/@types/meteor/ejson.d.ts new file mode 100644 index 0000000..792b08e --- /dev/null +++ b/node_modules/@types/meteor/ejson.d.ts @@ -0,0 +1,39 @@ +declare module "meteor/ejson" { + interface EJSONableCustomType { + clone?(): EJSONableCustomType; + equals?(other: Object): boolean; + toJSONValue(): JSONable; + typeName(): string; + } + interface EJSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSONableCustomType | undefined | null; + } + interface JSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | undefined | null; + } + interface EJSON extends EJSONable { } + + module EJSON { + function addType(name: string, factory: (val: JSONable) => EJSONableCustomType): void; + + function clone(val: T): T; + + function equals(a: EJSON, b: EJSON, options?: { + keyOrderSensitive?: boolean; + }): boolean; + + function fromJSONValue(val: JSONable): any; + + function isBinary(x: Object): boolean; + var newBinary: any; + + function parse(str: string): EJSON; + + function stringify(val: EJSON, options?: { + indent?: boolean | number | string; + canonical?: boolean; + }): string; + + function toJSONValue(val: EJSON): JSONable; + } +} diff --git a/node_modules/@types/meteor/email.d.ts b/node_modules/@types/meteor/email.d.ts new file mode 100644 index 0000000..e8c95a1 --- /dev/null +++ b/node_modules/@types/meteor/email.d.ts @@ -0,0 +1,36 @@ +declare module "meteor/email" { + module Email { + function send(options: { + from?: string; + to?: string | string[]; + cc?: string | string[]; + bcc?: string | string[]; + replyTo?: string | string[]; + subject?: string; + text?: string; + html?: string; + headers?: Object; + attachments?: Object[]; + mailComposer?: MailComposer; + }): void; + } + + interface MailComposerOptions { + escapeSMTP: boolean; + encoding: string; + charset: string; + keepBcc: boolean; + forceEmbeddedImages: boolean; + } + + var MailComposer: MailComposerStatic; + interface MailComposerStatic { + new (options: MailComposerOptions): MailComposer; + } + interface MailComposer { + addHeader(name: string, value: string): void; + setMessageOption(from: string, to: string, body: string, html: string): void; + streamMessage(): void; + pipe(stream: any /** fs.WriteStream **/): void; + } +} diff --git a/node_modules/@types/meteor/globals/accounts-base.d.ts b/node_modules/@types/meteor/globals/accounts-base.d.ts new file mode 100644 index 0000000..d1d18f8 --- /dev/null +++ b/node_modules/@types/meteor/globals/accounts-base.d.ts @@ -0,0 +1,148 @@ +declare interface URLS { + resetPassword: (token: string) => string; + verifyEmail: (token: string) => string; + enrollAccount: (token: string) => string; +} + +declare interface EmailFields { + from?: () => string; + subject?: (user: Meteor.User) => string; + text?: (user: Meteor.User, url: string) => string; + html?: (user: Meteor.User, url: string) => string; +} + +declare module Accounts { + var urls: URLS; + + function user(): Meteor.User; + + function userId(): string; + + function createUser(options: { + username?: string; + email?: string; + password?: string; + profile?: Object; + }, callback?: Function): string; + + function config(options: { + sendVerificationEmail?: boolean; + forbidClientAccountCreation?: boolean; + restrictCreationByEmailDomain?: string | Function; + loginExpirationInDays?: number; + oauthSecretKey?: string; + passwordResetTokenExpirationInDays?: number; + passwordEnrollTokenExpirationInDays?: number; + ambiguousErrorMessages?: boolean; + }): void; + + function onLogin(func: Function): { + stop: () => void + }; + + function onLoginFailure(func: Function): { + stop: () => void + }; + + function loginServicesConfigured(): boolean; + + function onPageLoadLogin(func: Function): void; +} + +declare module Accounts { + function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; + + function forgotPassword(options: { + email?: string; + }, callback?: Function): void; + + function resetPassword(token: string, newPassword: string, callback?: Function): void; + + function verifyEmail(token: string, callback?: Function): void; + + function onEmailVerificationLink(callback: Function): void; + + function onEnrollmentLink(callback: Function): void; + + function onResetPasswordLink(callback: Function): void; + + function loggingIn(): boolean; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + + var ui: { + config(options: { + requestPermissions?: Object; + requestOfflineToken?: Object; + forceApprovalPrompt?: Object; + passwordSignupFields?: string; + }): void; + }; +} + +declare interface Header { + [id: string]: string; +} + +declare interface EmailTemplates { + from: string; + siteName: string; + headers?: Header; + resetPassword: EmailFields; + enrollAccount: EmailFields; + verifyEmail: EmailFields; +} + +declare module Accounts { + var emailTemplates: EmailTemplates; + + function addEmail(userId: string, newEmail: string, verified?: boolean): void; + + function removeEmail(userId: string, email: string): void; + + function onCreateUser(func: Function): void; + + function findUserByEmail(email: string): Object; + + function findUserByUsername(username: string): Object; + + function sendEnrollmentEmail(userId: string, email?: string): void; + + function sendResetPasswordEmail(userId: string, email?: string): void; + + function sendVerificationEmail(userId: string, email?: string): void; + + function setUsername(userId: string, newUsername: string): void; + + function setPassword(userId: string, newPassword: string, options?: { + logout?: Object; + }): void; + + function validateNewUser(func: Function): boolean; + + function validateLoginAttempt(func: Function): { + stop: () => void + }; + + function _hashPassword(password: string): { digest: string; algorithm: string; }; + + interface IValidateLoginAttemptCbOpts { + type: string; + allowed: boolean; + error: Meteor.Error; + user: Meteor.User; + connection: Meteor.Connection; + methodName: string; + methodArguments: any[]; + } +} + +declare module Accounts { + function onLogout(func: Function): void; +} + +declare module Accounts { + function onLogout(func: (user: Meteor.User, connection: Meteor.Connection) => void): void; +} diff --git a/node_modules/@types/meteor/globals/blaze.d.ts b/node_modules/@types/meteor/globals/blaze.d.ts new file mode 100644 index 0000000..e40bc35 --- /dev/null +++ b/node_modules/@types/meteor/globals/blaze.d.ts @@ -0,0 +1,107 @@ +declare module Blaze { + var View: ViewStatic; + + interface ViewStatic { + new (name?: string, renderFunction?: Function): View; + } + + interface View { + name: string; + parentView: View; + isCreated: boolean; + isRendered: boolean; + isDestroyed: boolean; + renderCount: number; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + onViewCreated(func: Function): void; + onViewReady(func: Function): void; + onViewDestroyed(func: Function): void; + firstNode(): Node; + lastNode(): Node; + template: Template; + templateInstance(): TemplateInstance; + } + var currentView: View; + + function isTemplate(value: any): boolean; + + interface HelpersMap { + [key: string]: Function; + } + + interface EventsMap { + [key: string]: Function; + } + + var Template: TemplateStatic; + + interface TemplateStatic { + new (viewName?: string, renderFunction?: Function): Template; + + registerHelper(name: string, func: Function): void; + instance(): TemplateInstance; + currentData(): any; + parentData(numLevels: number): any; + } + + interface Template { + viewName: string; + renderFunction: Function; + constructView(): View; + head: Template; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + $: any; + onCreated(cb: Function): void; + onRendered(cb: Function): void; + onDestroyed(cb: Function): void; + created: Function; + rendered: Function; + destroyed: Function; + helpers(helpersMap: HelpersMap): void; + events(eventsMap: EventsMap): void; + } + + var TemplateInstance: TemplateInstanceStatic; + + interface TemplateInstanceStatic { + new (view: View): TemplateInstance; + } + + interface TemplateInstance { + $(selector: string): any; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + data: Object; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + firstNode: Object; + lastNode: Object; + subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + subscriptionsReady(): boolean; + view: Object; + } + + function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Let(bindings: Function, contentFunc: Function): View; + + function With(data: Object | Function, contentFunc: Function): View; + + function getData(elementOrView?: HTMLElement | View): Object; + + function getView(element?: HTMLElement): View; + + function remove(renderedView: View): void; + + function render(templateOrView: Template | View, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function renderWithData(templateOrView: Template | View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function toHTML(templateOrView: Template | View): string; + + function toHTMLWithData(templateOrView: Template | View, data: Object | Function): string; +} diff --git a/node_modules/@types/meteor/globals/browser-policy-common.d.ts b/node_modules/@types/meteor/globals/browser-policy-common.d.ts new file mode 100644 index 0000000..8dead79 --- /dev/null +++ b/node_modules/@types/meteor/globals/browser-policy-common.d.ts @@ -0,0 +1,34 @@ +declare module BrowserPolicy { + var framing: { + disallow(): void; + restrictToOrigin(origin: string): void; + allowAll(): void; + }; + + var content: { + allowEval(): void; + allowInlineStyles(): void; + allowInlineScripts(): void; + allowSameOriginForAll(): void; + allowDataUrlForAll(): void; + allowOriginForAll(origin: string): void; + allowImageOrigin(origin: string): void; + allowMediaOrigin(origin: string): void; + allowFontOrigin(origin: string): void; + allowStyleOrigin(origin: string): void; + allowScriptOrigin(origin: string): void; + allowFrameOrigin(origin: string): void; + allowContentTypeSniffing(): void; + allowAllContentOrigin(): void; + allowAllContentDataUrl(): void; + allowAllContentSameOrigin(): void; + + disallowAll(): void; + disallowInlineStyles(): void; + disallowEval(): void; + disallowInlineScripts(): void; + disallowFont(): void; + disallowObject(): void; + disallowAllContent(): void; + }; +} diff --git a/node_modules/@types/meteor/globals/check.d.ts b/node_modules/@types/meteor/globals/check.d.ts new file mode 100644 index 0000000..b919ffc --- /dev/null +++ b/node_modules/@types/meteor/globals/check.d.ts @@ -0,0 +1,22 @@ +declare module Match { + var Any: any; + var String: any; + var Integer: any; + var Boolean: any; + var undefined: any; + var Object: any; + + function Maybe(pattern: any): boolean; + + function Optional(pattern: any): boolean; + + function ObjectIncluding(dico: any): boolean; + + function OneOf(...patterns: any[]): any; + + function Where(condition: any): any; + + function test(value: any, pattern: any): boolean; +} + +declare function check(value: any, pattern: any): void; diff --git a/node_modules/@types/meteor/globals/ddp-rate-limiter.d.ts b/node_modules/@types/meteor/globals/ddp-rate-limiter.d.ts new file mode 100644 index 0000000..0131265 --- /dev/null +++ b/node_modules/@types/meteor/globals/ddp-rate-limiter.d.ts @@ -0,0 +1,13 @@ +declare module DDPRateLimiter { + interface Matcher { + type?: string | ((type: string) => boolean); + name?: string | ((name: string) => boolean); + userId?: string | ((userId: string) => boolean); + connectionId?: string | ((connectionId: string) => boolean); + clientAddress?: string | ((clientAddress: string) => boolean); + } + + function addRule(matcher: Matcher, numRequests: number, timeInterval: number): string; + + function removeRule(ruleId: string): boolean; +} diff --git a/node_modules/@types/meteor/globals/ddp.d.ts b/node_modules/@types/meteor/globals/ddp.d.ts new file mode 100644 index 0000000..6e7dfe9 --- /dev/null +++ b/node_modules/@types/meteor/globals/ddp.d.ts @@ -0,0 +1,36 @@ +declare module DDP { + interface DDPStatic { + subscribe(name: string, ...rest: any[]): Meteor.SubscriptionHandle; + call(method: string, ...parameters: any[]): void; + apply(method: string, ...parameters: any[]): void; + methods(IMeteorMethodsDictionary: any): any; + status(): DDPStatus; + reconnect(): void; + disconnect(): void; + onReconnect(): void; + } + + function _allSubscriptionsReady(): boolean; + + type Status = 'connected' | 'connecting' | 'failed' | 'waiting' | 'offline'; + + interface DDPStatus { + connected: boolean; + status: Status; + retryCount: number; + retryTime?: number; + reason?: string; + } + + function connect(url: string): DDPStatic; +} + +declare module DDPCommon { + interface MethodInvocation { + new (options: {}): MethodInvocation; + + unblock(): void; + + setUserId(userId: number): void; + } +} diff --git a/node_modules/@types/meteor/globals/ejson.d.ts b/node_modules/@types/meteor/globals/ejson.d.ts new file mode 100644 index 0000000..c70af96 --- /dev/null +++ b/node_modules/@types/meteor/globals/ejson.d.ts @@ -0,0 +1,37 @@ +declare interface EJSONableCustomType { + clone?(): EJSONableCustomType; + equals?(other: Object): boolean; + toJSONValue(): JSONable; + typeName(): string; +} +declare interface EJSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSONableCustomType | undefined | null; +} +declare interface JSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | undefined | null; +} +declare interface EJSON extends EJSONable { } + +declare module EJSON { + function addType(name: string, factory: (val: JSONable) => EJSONableCustomType): void; + + function clone(val: T): T; + + function equals(a: EJSON, b: EJSON, options?: { + keyOrderSensitive?: boolean; + }): boolean; + + function fromJSONValue(val: JSONable): any; + + function isBinary(x: Object): boolean; + var newBinary: any; + + function parse(str: string): EJSON; + + function stringify(val: EJSON, options?: { + indent?: boolean | number | string; + canonical?: boolean; + }): string; + + function toJSONValue(val: EJSON): JSONable; +} diff --git a/node_modules/@types/meteor/globals/email.d.ts b/node_modules/@types/meteor/globals/email.d.ts new file mode 100644 index 0000000..bfee483 --- /dev/null +++ b/node_modules/@types/meteor/globals/email.d.ts @@ -0,0 +1,34 @@ +declare module Email { + function send(options: { + from?: string; + to?: string | string[]; + cc?: string | string[]; + bcc?: string | string[]; + replyTo?: string | string[]; + subject?: string; + text?: string; + html?: string; + headers?: Object; + attachments?: Object[]; + mailComposer?: MailComposer; + }): void; +} + +declare interface MailComposerOptions { + escapeSMTP: boolean; + encoding: string; + charset: string; + keepBcc: boolean; + forceEmbeddedImages: boolean; +} + +declare var MailComposer: MailComposerStatic; +declare interface MailComposerStatic { + new (options: MailComposerOptions): MailComposer; +} +declare interface MailComposer { + addHeader(name: string, value: string): void; + setMessageOption(from: string, to: string, body: string, html: string): void; + streamMessage(): void; + pipe(stream: any /** fs.WriteStream **/): void; +} diff --git a/node_modules/@types/meteor/globals/http.d.ts b/node_modules/@types/meteor/globals/http.d.ts new file mode 100644 index 0000000..92518a9 --- /dev/null +++ b/node_modules/@types/meteor/globals/http.d.ts @@ -0,0 +1,48 @@ +declare module HTTP { + interface HTTPRequest { + content?: string; + data?: any; + query?: string; + params?: { + [id: string]: string + }; + auth?: string; + headers?: { + [id: string]: string + }; + timeout?: number; + followRedirects?: boolean; + } + + interface HTTPResponse { + statusCode?: number; + headers?: { + [id: string]: string + }; + content?: string; + data?: any; + } + + function call(method: string, url: string, options?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function del(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function get(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function post(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function put(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function call(method: string, url: string, options?: { + content?: string; + data?: Object; + query?: string; + params?: Object; + auth?: string; + headers?: Object; + timeout?: number; + followRedirects?: boolean; + npmRequestOptions?: Object; + beforeSend?: Function; + }, asyncCallback?: Function): HTTP.HTTPResponse; +} diff --git a/node_modules/@types/meteor/globals/meteor.d.ts b/node_modules/@types/meteor/globals/meteor.d.ts new file mode 100644 index 0000000..b6ec1ee --- /dev/null +++ b/node_modules/@types/meteor/globals/meteor.d.ts @@ -0,0 +1,220 @@ +declare module Meteor { + /** Global props **/ + var isClient: boolean; + var isCordova: boolean; + var isServer: boolean; + var isProduction: boolean; + var release: string; + /** Global props **/ + + /** Settings **/ + interface Settings { + public: { + [id: string]: any + }, [id: string]: any + } + var settings: Settings; + /** Settings **/ + + /** User **/ + interface UserEmail { + address: string; + verified: boolean; + } + interface User { + _id?: string; + username?: string; + emails?: UserEmail[]; + createdAt?: number; + profile?: any; + services?: any; + } + + function user(): User; + + function userId(): string; + var users: Mongo.Collection; + /** User **/ + + /** Error **/ + var Error: ErrorStatic; + interface ErrorStatic { + new (error: string | number, reason?: string, details?: string): Error; + } + interface Error { + error: string | number; + reason?: string; + details?: string; + } + /** Error **/ + + /** Method **/ + function methods(methods: Object): void; + + function call(name: string, ...args: any[]): any; + + function apply(name: string, args: EJSONable[], options?: { + wait?: boolean; + onResultReceived?: Function; + returnStubValue?: boolean; + throwStubExceptions?: boolean; + }, asyncCallback?: Function): any; + /** Method **/ + + /** Url **/ + function absoluteUrl(path?: string, options?: { + secure?: boolean; + replaceLocalhost?: boolean; + rootUrl?: string; + }): string; + /** Url **/ + + /** Timeout **/ + function setInterval(func: Function, delay: number): number; + + function setTimeout(func: Function, delay: number): number; + + function clearInterval(id: number): void; + + function clearTimeout(id: number): void; + + function defer(func: Function): void; + /** Timeout **/ + + /** utils **/ + function startup(func: Function): void; + + function wrapAsync(func: Function, context?: Object): any; + + function bindEnvironment(func: Function): any; + /** utils **/ + + /** Pub/Sub **/ + interface SubscriptionHandle { + stop(): void; + ready(): boolean; + } + interface LiveQueryHandle { + stop(): void; + } + /** Pub/Sub **/ +} + +declare module Meteor { + /** Login **/ + interface LoginWithExternalServiceOptions { + requestPermissions?: string[]; + requestOfflineToken?: Boolean; + forceApprovalPrompt?: Boolean; + loginUrlParameters?: Object; + redirectUrl?: string; + loginHint?: string; + loginStyle?: string; + } + + function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loggingIn(): boolean; + + function loginWith(options?: { + requestPermissions?: string[]; + requestOfflineToken?: boolean; + loginUrlParameters?: Object; + userEmail?: string; + loginStyle?: string; + redirectUrl?: string; + }, callback?: Function): void; + + function loginWithPassword(user: Object | string, password: string, callback?: Function): void; + + function loginWithToken(token: string, callback?: Function): void; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + /** Login **/ + + /** Event **/ + interface Event { + type: string; + target: HTMLElement; + currentTarget: HTMLElement; + which: number; + stopPropagation(): void; + stopImmediatePropagation(): void; + preventDefault(): void; + isPropagationStopped(): boolean; + isImmediatePropagationStopped(): boolean; + isDefaultPrevented(): boolean; + } + interface EventHandlerFunction extends Function { + (event?: Meteor.Event, templateInstance?: Blaze.TemplateInstance): void; + } + interface EventMap { + [id: string]: Meteor.EventHandlerFunction; + } + /** Event **/ + + /** Connection **/ + function reconnect(): void; + + function disconnect(): void; + /** Connection **/ + + /** Status **/ + function status(): DDP.DDPStatus; + /** Status **/ + + /** Pub/Sub **/ + function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + /** Pub/Sub **/ +} + +declare module Meteor { + /** Connection **/ + interface Connection { + id: string; + close: Function; + onClose: Function; + clientAddress: string; + httpHeaders: Object; + } + + function onConnection(callback: Function): void; + /** Connection **/ + + function publish(name: string, func: Function): void; + + function _debug(...args: any[]): void; +} + +declare interface Subscription { + added(collection: string, id: string, fields: Object): void; + changed(collection: string, id: string, fields: Object): void; + connection: Meteor.Connection; + error(error: Error): void; + onStop(func: Function): void; + ready(): void; + removed(collection: string, id: string): void; + stop(): void; + userId: string; +} + +declare module Meteor { + /** Global props **/ + var isDevelopment: boolean; + var isTest: boolean; + /** Global props **/ +} diff --git a/node_modules/@types/meteor/globals/mongo.d.ts b/node_modules/@types/meteor/globals/mongo.d.ts new file mode 100644 index 0000000..d99cad7 --- /dev/null +++ b/node_modules/@types/meteor/globals/mongo.d.ts @@ -0,0 +1,234 @@ +declare module Mongo { + + type BsonType = 1 | "double" | + 2 | "string" | + 3 | "object" | + 4 | "array" | + 5 | "binData" | + 6 | "undefined" | + 7 | "objectId" | + 8 | "bool" | + 9 | "date" | + 10 | "null" | + 11 | "regex" | + 12 | "dbPointer" | + 13 | "javascript" | + 14 | "symbol" | + 15 | "javascriptWithScope" | + 16 | "int" | + 17 | "timestamp" | + 18 | "long" | + 19 | "decimal" | + -1 | "minKey" | + 127 | "maxKey" | "number" + + type FieldExpression = { + $eq?: T, + $gt?: T, + $gte?: T, + $lt?: T, + $lte?: T, + $in?: T[], + $nin?: T[], + $ne?: T, + $exists?: boolean, + $type?: BsonType[] | BsonType, + $not?: FieldExpression, + $expr?: FieldExpression, + $jsonSchema?: any, + $mod?: number[], + $regex?: RegExp | string, + $options?: string, + $text?: { $search: string, $language?: string, $caseSensitive?: boolean, $diacriticSensitive?: boolean }, + $where?: string | Function, + $geoIntersects?: any, + $geoWithin?: any, + $near?: any, + $nearSphere?: any, + $all?: T[], + $elemMatch?: T extends {} ? Query : FieldExpression, + $size?: number, + $bitsAllClear?: any, + $bitsAllSet?: any, + $bitsAnyClear?: any, + $bitsAnySet?: any, + $comment?: string + } + + type Flatten = T extends any[] ? T[0] : T + + type Query = { + [P in keyof T]?: Flatten | RegExp | FieldExpression> + } & { + $or?: Query[], + $and?: Query[], + $nor?: Query[] + } & Dictionary + + type QueryWithModifiers = { + $query: Query, + $comment?: string, + $explain?: any, + $hint?: any, + $maxScan?: any, + $max?: any, + $maxTimeMS?: any, + $min?: any, + $orderby?: any, + $returnKey?: any, + $showDiskLoc?: any, + $natural?: any + } + + type Selector = Query | QueryWithModifiers + + type Dictionary = { [key: string]: T } + type PartialMapTo = Partial> + type OnlyArrays = T extends any[] ? T : never; + type OnlyElementsOfArrays = T extends any[] ? Partial : never + type ElementsOf = { + [P in keyof T]?: OnlyElementsOfArrays + } + type PushModifier = { + [P in keyof T]?: + OnlyElementsOfArrays | + { $each?: T[P], $position?: number, $slice?: number, $sort?: 1 | -1 | Dictionary } + } + type ArraysOrEach = { + [P in keyof T]?: OnlyArrays | { $each: T[P] } + } + type CurrentDateModifier = { $type: "timestamp" | "date" } | true + type Modifier = T | { + $currentDate?: Partial> & Dictionary, + $inc?: PartialMapTo & Dictionary, + $min?: PartialMapTo & Dictionary, + $max?: PartialMapTo & Dictionary, + $mul?: PartialMapTo & Dictionary, + $rename?: PartialMapTo & Dictionary, + $set?: Partial & Dictionary, + $setOnInsert?: Partial & Dictionary, + $unset?: PartialMapTo & Dictionary, + $addToSet?: ArraysOrEach & Dictionary, + $push?: PushModifier & Dictionary, + $pull?: ElementsOf & Dictionary, + $pullAll?: Partial & Dictionary, + $pop?: PartialMapTo & Dictionary<1 | -1>, + } + + + interface SortSpecifier { } + interface FieldSpecifier { + [id: string]: Number; + } + + var Collection: CollectionStatic; + interface CollectionStatic { + new (name: string, options?: { + connection?: Object | null; + idGeneration?: string; + transform?: Function; + }): Collection; + } + interface Collection { + allow(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + deny(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + find(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + limit?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): Cursor; + findOne(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): T; + insert(doc: T, callback?: Function): string; + rawCollection(): any; + rawDatabase(): any; + remove(selector: Selector | ObjectID | string, callback?: Function): number; + update(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + upsert?: boolean; + }, callback?: Function): number; + upsert(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + }, callback?: Function): { + numberAffected?: number; insertedId?: string; + }; + _ensureIndex(keys: { + [key: string]: number | string + } | string, options?: { + [key: string]: any + }): void; + _dropIndex(keys: { + [key: string]: number | string + } | string): void; + } + + var Cursor: CursorStatic; + interface CursorStatic { + new (): Cursor; + } + interface ObserveCallbacks { + added?(document: Object): void; + addedAt?(document: Object, atIndex: number, before: Object): void; + changed?(newDocument: Object, oldDocument: Object): void; + changedAt?(newDocument: Object, oldDocument: Object, indexAt: number): void; + removed?(oldDocument: Object): void; + removedAt?(oldDocument: Object, atIndex: number): void; + movedTo?(document: Object, fromIndex: number, toIndex: number, before: Object): void; + } + interface ObserveChangesCallbacks { + added?(id: string, fields: Object): void; + addedBefore?(id: string, fields: Object, before: Object): void; + changed?(id: string, fields: Object): void; + movedBefore?(id: string, before: Object): void; + removed?(id: string): void; + } + interface Cursor { + count(applySkipLimit?: boolean): number; + fetch(): Array; + forEach(callback: (doc: T, index: number, cursor: Cursor) => void, thisArg?: any): void; + map(callback: (doc: T, index: number, cursor: Cursor) => U, thisArg?: any): Array; + observe(callbacks: ObserveCallbacks): Meteor.LiveQueryHandle; + observeChanges(callbacks: ObserveChangesCallbacks): Meteor.LiveQueryHandle; + } + + var ObjectID: ObjectIDStatic; + interface ObjectIDStatic { + new(hexString?: string): ObjectID; + } + interface ObjectID { + toHexString(): string; + equals(otherID: ObjectID): boolean; + } + + function setConnectionOptions(options: any): void; +} + +declare module Mongo { + interface AllowDenyOptions { + insert?: (userId: string, doc: any) => boolean; + update?: (userId: string, doc: any, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: any) => boolean; + fetch?: string[]; + transform?: Function; + } +} diff --git a/node_modules/@types/meteor/globals/random.d.ts b/node_modules/@types/meteor/globals/random.d.ts new file mode 100644 index 0000000..72b1265 --- /dev/null +++ b/node_modules/@types/meteor/globals/random.d.ts @@ -0,0 +1,13 @@ +declare module Random { + function id(numberOfChars?: number): string; + + function secret(numberOfChars?: number): string; + + function fraction(): number; + // @param numberOfDigits, @returns a random hex string of the given length + function hexString(numberOfDigits: number): string; + // @param array, @return a random element in array + function choice(array: any[]): string; + // @param str, @return a random char in str + function choice(str: string): string; +} diff --git a/node_modules/@types/meteor/globals/reactive-var.d.ts b/node_modules/@types/meteor/globals/reactive-var.d.ts new file mode 100644 index 0000000..c649136 --- /dev/null +++ b/node_modules/@types/meteor/globals/reactive-var.d.ts @@ -0,0 +1,8 @@ +declare var ReactiveVar: ReactiveVarStatic; +declare interface ReactiveVarStatic { + new (initialValue: T, equalsFunc?: Function): ReactiveVar; +} +declare interface ReactiveVar { + get(): T; + set(newValue: T): void; +} diff --git a/node_modules/@types/meteor/globals/session.d.ts b/node_modules/@types/meteor/globals/session.d.ts new file mode 100644 index 0000000..45ac8db --- /dev/null +++ b/node_modules/@types/meteor/globals/session.d.ts @@ -0,0 +1,9 @@ +declare module Session { + function equals(key: string, value: string | number | boolean | any): boolean; + + function get(key: string): any; + + function set(key: string, value: EJSONable | any): void; + + function setDefault(key: string, value: EJSONable | any): void; +} diff --git a/node_modules/@types/meteor/globals/templating.d.ts b/node_modules/@types/meteor/globals/templating.d.ts new file mode 100644 index 0000000..54e486d --- /dev/null +++ b/node_modules/@types/meteor/globals/templating.d.ts @@ -0,0 +1,6 @@ +declare var Template: TemplateStatic; +declare interface TemplateStatic extends Blaze.TemplateStatic { + new (viewName?: string, renderFunction?: Function): Blaze.Template; + body: Blaze.Template; + [index: string]: any | Blaze.Template; +} diff --git a/node_modules/@types/meteor/globals/tiny-test.d.ts b/node_modules/@types/meteor/globals/tiny-test.d.ts new file mode 100644 index 0000000..27abd07 --- /dev/null +++ b/node_modules/@types/meteor/globals/tiny-test.d.ts @@ -0,0 +1,36 @@ +declare interface ILengthAble { + length: number; +} + +declare interface ITinytestAssertions { + ok(doc: Object): void; + expect_fail(): void; + fail(doc: Object): void; + runId(): string; + equal(actual: T, expected: T, message?: string, not?: boolean): void; + notEqual(actual: T, expected: T, message?: string): void; + instanceOf(obj: Object, klass: Function, message?: string): void; + notInstanceOf(obj: Object, klass: Function, message?: string): void; + matches(actual: any, regexp: RegExp, message?: string): void; + notMatches(actual: any, regexp: RegExp, message?: string): void; + throws(f: Function, expected?: string | RegExp): void; + isTrue(v: boolean, msg?: string): void; + isFalse(v: boolean, msg?: string): void; + isNull(v: any, msg?: string): void; + isNotNull(v: any, msg?: string): void; + isUndefined(v: any, msg?: string): void; + isNotUndefined(v: any, msg?: string): void; + isNan(v: any, msg?: string): void; + isNotNan(v: any, msg?: string): void; + include(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + + notInclude(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + length(obj: ILengthAble, expected_length: number, msg?: string): void; + _stringEqual(actual: string, expected: string, msg?: string): void; +} + +declare module Tinytest { + function add(description: string, func: (test: ITinytestAssertions) => void): void; + + function addAsync(description: string, func: (test: ITinytestAssertions) => void): void; +} diff --git a/node_modules/@types/meteor/globals/tools.d.ts b/node_modules/@types/meteor/globals/tools.d.ts new file mode 100644 index 0000000..68abe0b --- /dev/null +++ b/node_modules/@types/meteor/globals/tools.d.ts @@ -0,0 +1,102 @@ +declare module App { + function accessRule(pattern: string, options?: { + type?: string; + launchExternal?: boolean; + }): void; + + function configurePlugin(id: string, config: Object): void; + + function icons(icons: Object): void; + + function info(options: { + id?: string; + version?: string; + name?: string; + description?: string; + author?: string; + email?: string; + website?: string; + }): void; + + function launchScreens(launchScreens: Object): void; + + function setPreference(name: string, value: string, platform?: string): void; +} + +declare function execFileAsync(command: string, args?: any[], options?: { + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; +}): any; +declare function execFileSync(command: string, args?: any[], options?: { + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; +}): String; + +declare module Assets { + function getBinary(assetPath: string, asyncCallback?: Function): EJSON; + + function getText(assetPath: string, asyncCallback?: Function): string; + + function absoluteFilePath(assetPath: string): string; +} + +declare module Cordova { + function depends(dependencies: { + [id: string]: string + }): void; +} + +declare module Npm { + function depends(dependencies: { + [id: string]: string + }): void; + + function require(name: string): any; +} + +declare namespace Package { + function describe(options: { + summary?: string; + version?: string; + name?: string; + git?: string; + documentation?: string; + debugOnly?: boolean; + prodOnly?: boolean; + testOnly?: boolean; + }): void; + + function onTest(func: (api: PackageAPI) => void): void; + + function onUse(func: (api: PackageAPI) => void): void; + + function registerBuildPlugin(options?: { + name?: string; + use?: string | string[]; + sources?: string[]; + npmDependencies?: Object; + }): void; +} + +declare interface PackageAPI { + new (): PackageAPI; + addAssets(filenames: string | string[], architecture: string | string[]): void; + addFiles(filenames: string | string[], architecture?: string | string[], options?: { + bare?: boolean; + }): void; + export(exportedObjects: string | string[], architecture?: string | string[], exportOptions?: Object, testOnly?: boolean): void; + imply(packageNames: string | string[], architecture?: string | string[]): void; + use(packageNames: string | string[], architecture?: string | string[], options?: { + weak?: boolean; + unordered?: boolean; + }): void; + versionsFrom(meteorRelease: string | string[]): void; +} + +declare var console: Console; diff --git a/node_modules/@types/meteor/globals/tracker.d.ts b/node_modules/@types/meteor/globals/tracker.d.ts new file mode 100644 index 0000000..c243da5 --- /dev/null +++ b/node_modules/@types/meteor/globals/tracker.d.ts @@ -0,0 +1,37 @@ +declare module Tracker { + function Computation(): void; + interface Computation { + firstRun: boolean; + invalidate(): void; + invalidated: boolean; + onInvalidate(callback: Function): void; + onStop(callback: Function): void; + stop(): void; + stopped: boolean; + } + var currentComputation: Computation; + + var Dependency: DependencyStatic; + interface DependencyStatic { + new (): Dependency; + } + interface Dependency { + changed(): void; + depend(fromComputation?: Computation): boolean; + hasDependents(): boolean; + } + + var active: boolean; + + function afterFlush(callback: Function): void; + + function autorun(runFunc: (computation: Computation) => void, options?: { + onError?: Function; + }): Computation; + + function flush(): void; + + function nonreactive(func: Function): void; + + function onInvalidate(callback: Function): void; +} diff --git a/node_modules/@types/meteor/http.d.ts b/node_modules/@types/meteor/http.d.ts new file mode 100644 index 0000000..fc4b98d --- /dev/null +++ b/node_modules/@types/meteor/http.d.ts @@ -0,0 +1,50 @@ +declare module "meteor/http" { + module HTTP { + interface HTTPRequest { + content?: string; + data?: any; + query?: string; + params?: { + [id: string]: string + }; + auth?: string; + headers?: { + [id: string]: string + }; + timeout?: number; + followRedirects?: boolean; + } + + interface HTTPResponse { + statusCode?: number; + headers?: { + [id: string]: string + }; + content?: string; + data?: any; + } + + function call(method: string, url: string, options?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function del(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function get(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function post(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function put(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function call(method: string, url: string, options?: { + content?: string; + data?: Object; + query?: string; + params?: Object; + auth?: string; + headers?: Object; + timeout?: number; + followRedirects?: boolean; + npmRequestOptions?: Object; + beforeSend?: Function; + }, asyncCallback?: Function): HTTP.HTTPResponse; + } +} diff --git a/node_modules/@types/meteor/index.d.ts b/node_modules/@types/meteor/index.d.ts new file mode 100644 index 0000000..80c47fc --- /dev/null +++ b/node_modules/@types/meteor/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for Meteor 1.4 +// Project: http://www.meteor.com/ +// Definitions by: Alex Borodach +// Dave Allen +// Olivier Refalo +// Daniel Neveux +// Birk Skyum +// Arda TANRIKULU +// Stefan Holzapfel +// Andrey Markeev +// Leon Machens +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/@types/meteor/meteor.d.ts b/node_modules/@types/meteor/meteor.d.ts new file mode 100644 index 0000000..bb8ec6f --- /dev/null +++ b/node_modules/@types/meteor/meteor.d.ts @@ -0,0 +1,222 @@ +declare module "meteor/meteor" { + module Meteor { + /** Global props **/ + var isClient: boolean; + var isCordova: boolean; + var isServer: boolean; + var isProduction: boolean; + var release: string; + /** Global props **/ + + /** Settings **/ + interface Settings { + public: { + [id: string]: any + }, [id: string]: any + } + var settings: Settings; + /** Settings **/ + + /** User **/ + interface UserEmail { + address: string; + verified: boolean; + } + interface User { + _id?: string; + username?: string; + emails?: UserEmail[]; + createdAt?: number; + profile?: any; + services?: any; + } + + function user(): User; + + function userId(): string; + var users: Mongo.Collection; + /** User **/ + + /** Error **/ + var Error: ErrorStatic; + interface ErrorStatic { + new (error: string | number, reason?: string, details?: string): Error; + } + interface Error { + error: string | number; + reason?: string; + details?: string; + } + /** Error **/ + + /** Method **/ + function methods(methods: Object): void; + + function call(name: string, ...args: any[]): any; + + function apply(name: string, args: EJSONable[], options?: { + wait?: boolean; + onResultReceived?: Function; + returnStubValue?: boolean; + throwStubExceptions?: boolean; + }, asyncCallback?: Function): any; + /** Method **/ + + /** Url **/ + function absoluteUrl(path?: string, options?: { + secure?: boolean; + replaceLocalhost?: boolean; + rootUrl?: string; + }): string; + /** Url **/ + + /** Timeout **/ + function setInterval(func: Function, delay: number): number; + + function setTimeout(func: Function, delay: number): number; + + function clearInterval(id: number): void; + + function clearTimeout(id: number): void; + + function defer(func: Function): void; + /** Timeout **/ + + /** utils **/ + function startup(func: Function): void; + + function wrapAsync(func: Function, context?: Object): any; + + function bindEnvironment(func: Function): any; + /** utils **/ + + /** Pub/Sub **/ + interface SubscriptionHandle { + stop(): void; + ready(): boolean; + } + interface LiveQueryHandle { + stop(): void; + } + /** Pub/Sub **/ + } + + module Meteor { + /** Login **/ + interface LoginWithExternalServiceOptions { + requestPermissions?: string[]; + requestOfflineToken?: Boolean; + forceApprovalPrompt?: Boolean; + loginUrlParameters?: Object; + redirectUrl?: string; + loginHint?: string; + loginStyle?: string; + } + + function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loggingIn(): boolean; + + function loginWith(options?: { + requestPermissions?: string[]; + requestOfflineToken?: boolean; + loginUrlParameters?: Object; + userEmail?: string; + loginStyle?: string; + redirectUrl?: string; + }, callback?: Function): void; + + function loginWithPassword(user: Object | string, password: string, callback?: Function): void; + + function loginWithToken(token: string, callback?: Function): void; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + /** Login **/ + + /** Event **/ + interface Event { + type: string; + target: HTMLElement; + currentTarget: HTMLElement; + which: number; + stopPropagation(): void; + stopImmediatePropagation(): void; + preventDefault(): void; + isPropagationStopped(): boolean; + isImmediatePropagationStopped(): boolean; + isDefaultPrevented(): boolean; + } + interface EventHandlerFunction extends Function { + (event?: Meteor.Event, templateInstance?: Blaze.TemplateInstance): void; + } + interface EventMap { + [id: string]: Meteor.EventHandlerFunction; + } + /** Event **/ + + /** Connection **/ + function reconnect(): void; + + function disconnect(): void; + /** Connection **/ + + /** Status **/ + function status(): DDP.DDPStatus; + /** Status **/ + + /** Pub/Sub **/ + function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + /** Pub/Sub **/ + } + + module Meteor { + /** Connection **/ + interface Connection { + id: string; + close: Function; + onClose: Function; + clientAddress: string; + httpHeaders: Object; + } + + function onConnection(callback: Function): void; + /** Connection **/ + + function publish(name: string, func: Function): void; + + function _debug(...args: any[]): void; + } + + interface Subscription { + added(collection: string, id: string, fields: Object): void; + changed(collection: string, id: string, fields: Object): void; + connection: Meteor.Connection; + error(error: Error): void; + onStop(func: Function): void; + ready(): void; + removed(collection: string, id: string): void; + stop(): void; + userId: string; + } + + module Meteor { + /** Global props **/ + var isDevelopment: boolean; + var isTest: boolean; + /** Global props **/ + } +} diff --git a/node_modules/@types/meteor/mongo.d.ts b/node_modules/@types/meteor/mongo.d.ts new file mode 100644 index 0000000..c6a25df --- /dev/null +++ b/node_modules/@types/meteor/mongo.d.ts @@ -0,0 +1,236 @@ +declare module "meteor/mongo" { + module Mongo { + + type BsonType = 1 | "double" | + 2 | "string" | + 3 | "object" | + 4 | "array" | + 5 | "binData" | + 6 | "undefined" | + 7 | "objectId" | + 8 | "bool" | + 9 | "date" | + 10 | "null" | + 11 | "regex" | + 12 | "dbPointer" | + 13 | "javascript" | + 14 | "symbol" | + 15 | "javascriptWithScope" | + 16 | "int" | + 17 | "timestamp" | + 18 | "long" | + 19 | "decimal" | + -1 | "minKey" | + 127 | "maxKey" | "number" + + type FieldExpression = { + $eq?: T, + $gt?: T, + $gte?: T, + $lt?: T, + $lte?: T, + $in?: T[], + $nin?: T[], + $ne?: T, + $exists?: boolean, + $type?: BsonType[] | BsonType, + $not?: FieldExpression, + $expr?: FieldExpression, + $jsonSchema?: any, + $mod?: number[], + $regex?: RegExp | string, + $options?: string, + $text?: { $search: string, $language?: string, $caseSensitive?: boolean, $diacriticSensitive?: boolean }, + $where?: string | Function, + $geoIntersects?: any, + $geoWithin?: any, + $near?: any, + $nearSphere?: any, + $all?: T[], + $elemMatch?: T extends {} ? Query : FieldExpression, + $size?: number, + $bitsAllClear?: any, + $bitsAllSet?: any, + $bitsAnyClear?: any, + $bitsAnySet?: any, + $comment?: string + } + + type Flatten = T extends any[] ? T[0] : T + + type Query = { + [P in keyof T]?: Flatten | RegExp | FieldExpression> + } & { + $or?: Query[], + $and?: Query[], + $nor?: Query[] + } & Dictionary + + type QueryWithModifiers = { + $query: Query, + $comment?: string, + $explain?: any, + $hint?: any, + $maxScan?: any, + $max?: any, + $maxTimeMS?: any, + $min?: any, + $orderby?: any, + $returnKey?: any, + $showDiskLoc?: any, + $natural?: any + } + + type Selector = Query | QueryWithModifiers + + type Dictionary = { [key: string]: T } + type PartialMapTo = Partial> + type OnlyArrays = T extends any[] ? T : never; + type OnlyElementsOfArrays = T extends any[] ? Partial : never + type ElementsOf = { + [P in keyof T]?: OnlyElementsOfArrays + } + type PushModifier = { + [P in keyof T]?: + OnlyElementsOfArrays | + { $each?: T[P], $position?: number, $slice?: number, $sort?: 1 | -1 | Dictionary } + } + type ArraysOrEach = { + [P in keyof T]?: OnlyArrays | { $each: T[P] } + } + type CurrentDateModifier = { $type: "timestamp" | "date" } | true + type Modifier = T | { + $currentDate?: Partial> & Dictionary, + $inc?: PartialMapTo & Dictionary, + $min?: PartialMapTo & Dictionary, + $max?: PartialMapTo & Dictionary, + $mul?: PartialMapTo & Dictionary, + $rename?: PartialMapTo & Dictionary, + $set?: Partial & Dictionary, + $setOnInsert?: Partial & Dictionary, + $unset?: PartialMapTo & Dictionary, + $addToSet?: ArraysOrEach & Dictionary, + $push?: PushModifier & Dictionary, + $pull?: ElementsOf & Dictionary, + $pullAll?: Partial & Dictionary, + $pop?: PartialMapTo & Dictionary<1 | -1>, + } + + + interface SortSpecifier { } + interface FieldSpecifier { + [id: string]: Number; + } + + var Collection: CollectionStatic; + interface CollectionStatic { + new (name: string, options?: { + connection?: Object | null; + idGeneration?: string; + transform?: Function; + }): Collection; + } + interface Collection { + allow(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + deny(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + find(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + limit?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): Cursor; + findOne(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): T; + insert(doc: T, callback?: Function): string; + rawCollection(): any; + rawDatabase(): any; + remove(selector: Selector | ObjectID | string, callback?: Function): number; + update(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + upsert?: boolean; + }, callback?: Function): number; + upsert(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + }, callback?: Function): { + numberAffected?: number; insertedId?: string; + }; + _ensureIndex(keys: { + [key: string]: number | string + } | string, options?: { + [key: string]: any + }): void; + _dropIndex(keys: { + [key: string]: number | string + } | string): void; + } + + var Cursor: CursorStatic; + interface CursorStatic { + new (): Cursor; + } + interface ObserveCallbacks { + added?(document: Object): void; + addedAt?(document: Object, atIndex: number, before: Object): void; + changed?(newDocument: Object, oldDocument: Object): void; + changedAt?(newDocument: Object, oldDocument: Object, indexAt: number): void; + removed?(oldDocument: Object): void; + removedAt?(oldDocument: Object, atIndex: number): void; + movedTo?(document: Object, fromIndex: number, toIndex: number, before: Object): void; + } + interface ObserveChangesCallbacks { + added?(id: string, fields: Object): void; + addedBefore?(id: string, fields: Object, before: Object): void; + changed?(id: string, fields: Object): void; + movedBefore?(id: string, before: Object): void; + removed?(id: string): void; + } + interface Cursor { + count(applySkipLimit?: boolean): number; + fetch(): Array; + forEach(callback: (doc: T, index: number, cursor: Cursor) => void, thisArg?: any): void; + map(callback: (doc: T, index: number, cursor: Cursor) => U, thisArg?: any): Array; + observe(callbacks: ObserveCallbacks): Meteor.LiveQueryHandle; + observeChanges(callbacks: ObserveChangesCallbacks): Meteor.LiveQueryHandle; + } + + var ObjectID: ObjectIDStatic; + interface ObjectIDStatic { + new(hexString?: string): ObjectID; + } + interface ObjectID { + toHexString(): string; + equals(otherID: ObjectID): boolean; + } + + function setConnectionOptions(options: any): void; + } + + module Mongo { + interface AllowDenyOptions { + insert?: (userId: string, doc: any) => boolean; + update?: (userId: string, doc: any, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: any) => boolean; + fetch?: string[]; + transform?: Function; + } + } +} diff --git a/node_modules/@types/meteor/random.d.ts b/node_modules/@types/meteor/random.d.ts new file mode 100644 index 0000000..8b0a041 --- /dev/null +++ b/node_modules/@types/meteor/random.d.ts @@ -0,0 +1,15 @@ +declare module "meteor/random" { + module Random { + function id(numberOfChars?: number): string; + + function secret(numberOfChars?: number): string; + + function fraction(): number; + // @param numberOfDigits, @returns a random hex string of the given length + function hexString(numberOfDigits: number): string; + // @param array, @return a random element in array + function choice(array: any[]): string; + // @param str, @return a random char in str + function choice(str: string): string; + } +} diff --git a/node_modules/@types/meteor/reactive-var.d.ts b/node_modules/@types/meteor/reactive-var.d.ts new file mode 100644 index 0000000..470fef2 --- /dev/null +++ b/node_modules/@types/meteor/reactive-var.d.ts @@ -0,0 +1,10 @@ +declare module "meteor/reactive-var" { + var ReactiveVar: ReactiveVarStatic; + interface ReactiveVarStatic { + new (initialValue: T, equalsFunc?: Function): ReactiveVar; + } + interface ReactiveVar { + get(): T; + set(newValue: T): void; + } +} diff --git a/node_modules/@types/meteor/server-render.d.ts b/node_modules/@types/meteor/server-render.d.ts new file mode 100644 index 0000000..d8641ef --- /dev/null +++ b/node_modules/@types/meteor/server-render.d.ts @@ -0,0 +1,19 @@ +import * as http from "http"; +declare module "meteor/server-render" { + interface Sink { + request?: http.IncomingMessage; + arch?: string; + head?: string; + body?: string; + htmlById?: { [key: string]: string }; + maybeMadeChanges?: boolean; + appendToHead?(html: string): void; + appendToBody?(html: string): void; + appendToElementById?(id: string, html: string): void; + renderIntoElementById?(id: string, html: string): void; + renderIntoElementById?(id: string, html: NodeJS.ReadableStream): void; + } + + type Callback = (sink: Sink) => Promise | any; + export function onPageLoad(callback: T): T; +} diff --git a/node_modules/@types/meteor/service-configuration.d.ts b/node_modules/@types/meteor/service-configuration.d.ts new file mode 100644 index 0000000..ad938e1 --- /dev/null +++ b/node_modules/@types/meteor/service-configuration.d.ts @@ -0,0 +1,9 @@ +declare module "meteor/service-configuration" { + interface Configuration { + appId: string; + secret: string; + } + var ServiceConfiguration: { + configurations: Mongo.Collection; + } +} diff --git a/node_modules/@types/meteor/session.d.ts b/node_modules/@types/meteor/session.d.ts new file mode 100644 index 0000000..9a5b5b8 --- /dev/null +++ b/node_modules/@types/meteor/session.d.ts @@ -0,0 +1,11 @@ +declare module "meteor/session" { + module Session { + function equals(key: string, value: string | number | boolean | any): boolean; + + function get(key: string): any; + + function set(key: string, value: EJSONable | any): void; + + function setDefault(key: string, value: EJSONable | any): void; + } +} diff --git a/node_modules/@types/meteor/templating.d.ts b/node_modules/@types/meteor/templating.d.ts new file mode 100644 index 0000000..be1431a --- /dev/null +++ b/node_modules/@types/meteor/templating.d.ts @@ -0,0 +1,8 @@ +declare module "meteor/templating" { + var Template: TemplateStatic; + interface TemplateStatic extends Blaze.TemplateStatic { + new (viewName?: string, renderFunction?: Function): Blaze.Template; + body: Blaze.Template; + [index: string]: any | Blaze.Template; + } +} diff --git a/node_modules/@types/meteor/tiny-test.d.ts b/node_modules/@types/meteor/tiny-test.d.ts new file mode 100644 index 0000000..c11ca02 --- /dev/null +++ b/node_modules/@types/meteor/tiny-test.d.ts @@ -0,0 +1,38 @@ +declare module "meteor/tiny-test" { + interface ILengthAble { + length: number; + } + + interface ITinytestAssertions { + ok(doc: Object): void; + expect_fail(): void; + fail(doc: Object): void; + runId(): string; + equal(actual: T, expected: T, message?: string, not?: boolean): void; + notEqual(actual: T, expected: T, message?: string): void; + instanceOf(obj: Object, klass: Function, message?: string): void; + notInstanceOf(obj: Object, klass: Function, message?: string): void; + matches(actual: any, regexp: RegExp, message?: string): void; + notMatches(actual: any, regexp: RegExp, message?: string): void; + throws(f: Function, expected?: string | RegExp): void; + isTrue(v: boolean, msg?: string): void; + isFalse(v: boolean, msg?: string): void; + isNull(v: any, msg?: string): void; + isNotNull(v: any, msg?: string): void; + isUndefined(v: any, msg?: string): void; + isNotUndefined(v: any, msg?: string): void; + isNan(v: any, msg?: string): void; + isNotNan(v: any, msg?: string): void; + include(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + + notInclude(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + length(obj: ILengthAble, expected_length: number, msg?: string): void; + _stringEqual(actual: string, expected: string, msg?: string): void; + } + + module Tinytest { + function add(description: string, func: (test: ITinytestAssertions) => void): void; + + function addAsync(description: string, func: (test: ITinytestAssertions) => void): void; + } +} diff --git a/node_modules/@types/meteor/tools.d.ts b/node_modules/@types/meteor/tools.d.ts new file mode 100644 index 0000000..8538544 --- /dev/null +++ b/node_modules/@types/meteor/tools.d.ts @@ -0,0 +1,104 @@ +declare module "meteor/tools" { + module App { + function accessRule(pattern: string, options?: { + type?: string; + launchExternal?: boolean; + }): void; + + function configurePlugin(id: string, config: Object): void; + + function icons(icons: Object): void; + + function info(options: { + id?: string; + version?: string; + name?: string; + description?: string; + author?: string; + email?: string; + website?: string; + }): void; + + function launchScreens(launchScreens: Object): void; + + function setPreference(name: string, value: string, platform?: string): void; + } + + function execFileAsync(command: string, args?: any[], options?: { + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; + }): any; + function execFileSync(command: string, args?: any[], options?: { + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; + }): String; + + module Assets { + function getBinary(assetPath: string, asyncCallback?: Function): EJSON; + + function getText(assetPath: string, asyncCallback?: Function): string; + + function absoluteFilePath(assetPath: string): string; + } + + module Cordova { + function depends(dependencies: { + [id: string]: string + }): void; + } + + module Npm { + function depends(dependencies: { + [id: string]: string + }): void; + + function require(name: string): any; + } + + namespace Package { + function describe(options: { + summary?: string; + version?: string; + name?: string; + git?: string; + documentation?: string; + debugOnly?: boolean; + prodOnly?: boolean; + testOnly?: boolean; + }): void; + + function onTest(func: (api: PackageAPI) => void): void; + + function onUse(func: (api: PackageAPI) => void): void; + + function registerBuildPlugin(options?: { + name?: string; + use?: string | string[]; + sources?: string[]; + npmDependencies?: Object; + }): void; + } + + interface PackageAPI { + new (): PackageAPI; + addAssets(filenames: string | string[], architecture: string | string[]): void; + addFiles(filenames: string | string[], architecture?: string | string[], options?: { + bare?: boolean; + }): void; + export(exportedObjects: string | string[], architecture?: string | string[], exportOptions?: Object, testOnly?: boolean): void; + imply(packageNames: string | string[], architecture?: string | string[]): void; + use(packageNames: string | string[], architecture?: string | string[], options?: { + weak?: boolean; + unordered?: boolean; + }): void; + versionsFrom(meteorRelease: string | string[]): void; + } + + var console: Console; +} diff --git a/node_modules/@types/meteor/tracker.d.ts b/node_modules/@types/meteor/tracker.d.ts new file mode 100644 index 0000000..c356077 --- /dev/null +++ b/node_modules/@types/meteor/tracker.d.ts @@ -0,0 +1,39 @@ +declare module "meteor/tracker" { + module Tracker { + function Computation(): void; + interface Computation { + firstRun: boolean; + invalidate(): void; + invalidated: boolean; + onInvalidate(callback: Function): void; + onStop(callback: Function): void; + stop(): void; + stopped: boolean; + } + var currentComputation: Computation; + + var Dependency: DependencyStatic; + interface DependencyStatic { + new (): Dependency; + } + interface Dependency { + changed(): void; + depend(fromComputation?: Computation): boolean; + hasDependents(): boolean; + } + + var active: boolean; + + function afterFlush(callback: Function): void; + + function autorun(runFunc: (computation: Computation) => void, options?: { + onError?: Function; + }): Computation; + + function flush(): void; + + function nonreactive(func: Function): void; + + function onInvalidate(callback: Function): void; + } +} diff --git a/node_modules/@types/meteor/underscore.d.ts b/node_modules/@types/meteor/underscore.d.ts new file mode 100644 index 0000000..e26538a --- /dev/null +++ b/node_modules/@types/meteor/underscore.d.ts @@ -0,0 +1,4 @@ +declare module "meteor/underscore" { + import * as _ from 'underscore'; + export { _ }; +} diff --git a/node_modules/@types/meteor/webapp.d.ts b/node_modules/@types/meteor/webapp.d.ts new file mode 100644 index 0000000..e9b4b9e --- /dev/null +++ b/node_modules/@types/meteor/webapp.d.ts @@ -0,0 +1,64 @@ + +declare module "meteor/webapp" { + + import * as http from "http"; + import * as connect from "connect"; + interface StaticFiles { + [key: string]: { + content?: string, + absolutePath: string, + cacheable: boolean, + hash: string, + sourceMapUrl?: string, + type: string + } + } + module WebApp { + var defaultArch: string; + var clientPrograms: { + [key: string]: { + format: string, + manifest: any, + version: string, + cordovaCompatibilityVersions?: any, + PUBLIC_SETTINGS: any + } + }; + var connectHandlers: connect.Server; + var rawConnectHandlers: connect.Server; + var httpServer: http.Server; + var connectApp: connect.Server; + function suppressConnectErrors(): void; + function onListening(callback: Function): void; + } + module WebAppInternals { + var NpmModules: { + [key: string]: { + version: string, + module: any; + } + }; + function identifyBrowser(userAgentString: string): { + name: string, + major: string, + minor: string, + patch: string + }; + function registerBoilerplateDataCallback(key: string, callback: Function): Function; + function generateBoilerplateInstance(arch: string, manifest: any, additionalOptions: any): any; + + function staticFilesMiddleware(staticFiles: StaticFiles, req: http.IncomingMessage, res: http.ServerResponse, next: Function): void; + function parsePort(port: string): number; + function reloadClientPrograms(): void; + function generateBoilerplate(): void; + var staticFiles: StaticFiles; + function inlineScriptsAllowed(): boolean; + function setInlineScriptsAllowed(inlineScriptsAllowed: boolean): void; + + function setBundledJsCssUrlRewriteHook(hookFn: (url: string) => string): void; + function setBundledJsCssPrefix(bundledJsCssPrefix: string): void; + function addStaticJs(): void; + function getBoilerplate(request: http.IncomingMessage, arch: string): string; + var additionalStaticJs: any; + } +} diff --git a/node_modules/@types/node/LICENSE b/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/node/README.md b/node_modules/@types/node/README.md new file mode 100644 index 0000000..68a0c5f --- /dev/null +++ b/node_modules/@types/node/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for Node.js (http://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node + +Additional Details + * Last updated: Fri, 21 Sep 2018 18:00:19 GMT + * Dependencies: none + * Global values: Buffer, NodeJS, SlowBuffer, Symbol, __dirname, __filename, clearImmediate, clearInterval, clearTimeout, console, exports, global, module, process, require, setImmediate, setInterval, setTimeout + +# Credits +These definitions were written by Microsoft TypeScript , DefinitelyTyped , Parambir Singh , Christian Vaagland Tellnes , Wilco Bakker , Nicolas Voigt , Chigozirim C. , Flarna , Mariusz Wiktorczyk , wwwy3y3 , Deividas Bakanas , Kelvin Jin , Alvis HT Tang , Sebastian Silbermann , Hannes Magnusson , Alberto Schiabel , Klaus Meinhardt , Huw , Nicolas Even , Bruno Scheufler , Mohsen Azimi , Hoàng Văn Khải , Alexander T. , Lishude , Andrew Makarov , Zane Hannan AU , Thomas den Hollander , Eugene Y. Q. Shen , Matthieu Sieben . diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..82c44a9 --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,8250 @@ +// Type definitions for Node.js 10.10.x +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Parambir Singh +// Christian Vaagland Tellnes +// Wilco Bakker +// Nicolas Voigt +// Chigozirim C. +// Flarna +// Mariusz Wiktorczyk +// wwwy3y3 +// Deividas Bakanas +// Kelvin Jin +// Alvis HT Tang +// Sebastian Silbermann +// Hannes Magnusson +// Alberto Schiabel +// Klaus Meinhardt +// Huw +// Nicolas Even +// Bruno Scheufler +// Mohsen Azimi +// Hoàng Văn Khải +// Alexander T. +// Lishude +// Andrew Makarov +// Zane Hannan AU +// Thomas den Hollander +// Eugene Y. Q. Shen +// Matthieu Sieben +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** inspector module types */ +/// + +// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build +interface Console { + Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; + + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; +} + +interface Error { + stack?: string; +} + +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +// compat for TypeScript 1.8 +// if you use with --target es3 or --target es5 and use below definitions, +// use the lib.es6.d.ts that is bundled with TypeScript 1.8. +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } + +// Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) +interface Iterable { } +interface Iterator { + next(value?: any): IteratorResult; +} +interface IteratorResult { } +interface AsyncIterableIterator {} +interface SymbolConstructor { + readonly observable: symbol; + readonly iterator: symbol; + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +interface SharedArrayBuffer { + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare namespace setTimeout { + export function __promisify__(ms: number): Promise; + export function __promisify__(ms: number, value: T): Promise; +} +declare function clearTimeout(timeoutId: NodeJS.Timer): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearInterval(intervalId: NodeJS.Timer): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; +declare namespace setImmediate { + export function __promisify__(): Promise; + export function __promisify__(value: T): Promise; +} +declare function clearImmediate(immediateId: any): void; + +// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. +interface NodeRequireFunction { + /* tslint:disable-next-line:callable-types */ + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve: RequireResolve; + cache: any; + extensions: NodeExtensions; + main: NodeModule | undefined; +} + +interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; +} + +interface NodeExtensions { + '.js': (m: NodeModule, filename: string) => any; + '.json': (m: NodeModule, filename: string) => any; + '.node': (m: NodeModule, filename: string) => any; + [ext: string]: (m: NodeModule, filename: string) => any; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: NodeModule | null; + children: NodeModule[]; + paths: string[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; +declare var SlowBuffer: { + new(str: string, encoding?: string): Buffer; + new(size: number): Buffer; + new(size: Uint8Array): Buffer; + new(array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; +}; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; +interface Buffer extends Uint8Array { + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Uint8Array): boolean; + compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare var Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + prototype: Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of any TypedArray or a new ArrayBuffer() + */ + from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: any[]): Buffer; + from(data: Uint8Array): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from(str: string, encoding?: string): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean | undefined; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Uint8Array, buf2: Uint8Array): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + poolSize: number; +}; + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + export interface InspectOptions { + showHidden?: boolean; + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + breakLength?: number; + compact?: boolean; + } + + export interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream): Console; + } + + export interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + export interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + export class EventEmitter { + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + listenerCount(type: string | symbol): number; + // Added in Node 6... + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + eventNames(): Array; + } + + export interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): this; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + export interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface ReadWriteStream extends ReadableStream, WritableStream { } + + export interface Events extends EventEmitter { } + + export interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + } + + export interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + } + + export interface CpuUsage { + user: number; + system: number; + } + + export interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + export interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: any, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + + export interface Socket extends ReadWriteStream { + isTTY?: true; + } + + export interface ProcessEnv { + [key: string]: string | undefined; + } + + export interface WriteStream extends Socket { + readonly writableHighWaterMark: number; + readonly writableLength: number; + columns?: number; + rows?: number; + _write(chunk: any, encoding: string, callback: Function): void; + _destroy(err: Error | null, callback: Function): void; + _final(callback: Function): void; + setDefaultEncoding(encoding: string): this; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + } + export interface ReadStream extends Socket { + readonly readableHighWaterMark: number; + readonly readableLength: number; + isRaw?: boolean; + setRawMode?(mode: boolean): void; + _read(size: number): void; + _destroy(err: Error | null, callback: Function): void; + push(chunk: any, encoding?: string): boolean; + destroy(error?: Error): void; + } + + export interface Process extends EventEmitter { + stdout: WriteStream; + stderr: WriteStream; + stdin: ReadStream; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + env: ProcessEnv; + exit(code?: number): never; + exitCode: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + version: string; + versions: ProcessVersions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + ppid: number; + title: string; + arch: string; + platform: Platform; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + umask(mask?: number): number; + uptime(): number; + hrtime(time?: [number, number]): [number, number]; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + // TODO: This Set is readonly + allowedNodeEnvironmentFlags: Set; + + /** + * EventEmitter + * 1. beforeExit + * 2. disconnect + * 3. exit + * 4. message + * 5. rejectionHandled + * 6. uncaughtException + * 7. unhandledRejection + * 8. warning + * 9. message + * 10. + * 11. newListener/removeListener inherited from EventEmitter + */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + } + + export interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: any) => void; + clearInterval: (intervalId: NodeJS.Timer) => void; + clearTimeout: (timeoutId: NodeJS.Timer) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + export interface Timer { + ref(): void; + unref(): void; + } + + class Module { + static runMain(): void; + static wrap(code: string): string; + static builtinModules: string[]; + + static Module: typeof Module; + + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: Module | null; + children: Module[]; + paths: string[]; + + constructor(id: string, parent?: Module); + } + + type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; +} + +interface IterableIterator { } + +/*----------------------------------------------* +* * +* MODULES * +* * +*-----------------------------------------------*/ +declare module "buffer" { + export var INSPECT_MAX_BYTES: number; + var BuffType: typeof Buffer; + var SlowBuffType: typeof SlowBuffer; + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; +} + +declare module "querystring" { + export interface StringifyOptions { + encodeURIComponent?: Function; + } + + export interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } + + interface ParsedUrlQuery { [key: string]: string | string[] | undefined; } + + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; + export function escape(str: string): string; + export function unescape(str: string): string; +} + +declare module "events" { + class internal extends NodeJS.EventEmitter { } + + namespace internal { + export class EventEmitter extends internal { + /** @deprecated since v4.0.0 */ + static listenerCount(emitter: EventEmitter, event: string | symbol): number; + static defaultMaxListeners: number; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): Array; + listenerCount(type: string | symbol): number; + } + } + + export = internal; +} + +declare module "http" { + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; + import { URL } from "url"; + + // incoming headers will never contain number + export interface IncomingHttpHeaders { + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'authorization'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'date'?: string; + 'expires'?: string; + 'host'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'public-key-pins'?: string; + 'referer'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'user-agent'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + + export interface ClientRequestArgs { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number | string; + defaultPort?: number | string; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: OutgoingHttpHeaders; + auth?: string; + agent?: Agent | boolean; + _defaultAgent?: Agent; + timeout?: number; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: net.Socket) => void) => net.Socket; + } + + export class Server extends net.Server { + constructor(requestListener?: (req: IncomingMessage, res: ServerResponse) => void); + + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + maxHeadersCount: number; + timeout: number; + keepAliveTimeout: number; + } + /** + * @deprecated Use IncomingMessage + */ + export class ServerRequest extends IncomingMessage { + connection: net.Socket; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js + export class OutgoingMessage extends stream.Writable { + upgrading: boolean; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + finished: boolean; + headersSent: boolean; + connection: net.Socket; + + constructor(); + + setTimeout(msecs: number, callback?: () => void): this; + setHeader(name: string, value: number | string | string[]): void; + getHeader(name: string): number | string | string[] | undefined; + getHeaders(): OutgoingHttpHeaders; + getHeaderNames(): string[]; + hasHeader(name: string): boolean; + removeHeader(name: string): void; + addTrailers(headers: OutgoingHttpHeaders | Array<[string, string]>): void; + flushHeaders(): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 + export class ServerResponse extends OutgoingMessage { + statusCode: number; + statusMessage: string; + + constructor(req: IncomingMessage); + + assignSocket(socket: net.Socket): void; + detachSocket(socket: net.Socket): void; + // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 + // no args in writeContinue callback + writeContinue(callback?: () => void): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 + export class ClientRequest extends OutgoingMessage { + connection: net.Socket; + socket: net.Socket; + aborted: number; + + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + + abort(): void; + onSocket(socket: net.Socket): void; + setTimeout(timeout: number, callback?: () => void): this; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + } + + export class IncomingMessage extends stream.Readable { + constructor(socket: net.Socket); + + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + connection: net.Socket; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + trailers: { [key: string]: string | undefined }; + rawTrailers: string[]; + setTimeout(msecs: number, callback: () => void): this; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + destroy(error?: Error): void; + } + + /** + * @deprecated Use IncomingMessage + */ + export class ClientResponse extends IncomingMessage { } + + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number; + } + + export class Agent { + maxFreeSockets: number; + maxSockets: number; + sockets: any; + requests: any; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + export var METHODS: string[]; + + export var STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; + export function createClient(port?: number, host?: string): any; + + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + export interface RequestOptions extends ClientRequestArgs { } + export function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + export function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export var globalAgent: Agent; +} + +declare module "cluster" { + import * as child from "child_process"; + import * as events from "events"; + import * as net from "net"; + + // interfaces + export interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv + exec?: string; + args?: string[]; + silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + inspectPort?: number | (() => number); + } + + export interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } + + export class Worker extends events.EventEmitter { + id: number; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + + export interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSettings): void; + worker?: Worker; + workers?: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: any): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + } + + export function disconnect(callback?: Function): void; + export function fork(env?: any): Worker; + export var isMaster: boolean; + export var isWorker: boolean; + // TODO: cluster.schedulingPolicy + export var settings: ClusterSettings; + export function setupMaster(settings?: ClusterSettings): void; + export var worker: Worker; + export var workers: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + export function addListener(event: string, listener: (...args: any[]) => void): Cluster; + export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function emit(event: string | symbol, ...args: any[]): boolean; + export function emit(event: "disconnect", worker: Worker): boolean; + export function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + export function emit(event: "fork", worker: Worker): boolean; + export function emit(event: "listening", worker: Worker, address: Address): boolean; + export function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + export function emit(event: "online", worker: Worker): boolean; + export function emit(event: "setup", settings: any): boolean; + + export function on(event: string, listener: (...args: any[]) => void): Cluster; + export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function on(event: "fork", listener: (worker: Worker) => void): Cluster; + export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function on(event: "online", listener: (worker: Worker) => void): Cluster; + export function on(event: "setup", listener: (settings: any) => void): Cluster; + + export function once(event: string, listener: (...args: any[]) => void): Cluster; + export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function once(event: "fork", listener: (worker: Worker) => void): Cluster; + export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function once(event: "online", listener: (worker: Worker) => void): Cluster; + export function once(event: "setup", listener: (settings: any) => void): Cluster; + + export function removeListener(event: string, listener: (...args: any[]) => void): Cluster; + export function removeAllListeners(event?: string): Cluster; + export function setMaxListeners(n: number): Cluster; + export function getMaxListeners(): number; + export function listeners(event: string): Function[]; + export function listenerCount(type: string): number; + + export function prependListener(event: string, listener: (...args: any[]) => void): Cluster; + export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; + export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function eventNames(): string[]; +} + +declare module "zlib" { + import * as stream from "stream"; + + export interface ZlibOptions { + flush?: number; // default: zlib.constants.Z_NO_FLUSH + finishFlush?: number; // default: zlib.constants.Z_FINISH + chunkSize?: number; // default: 16*1024 + windowBits?: number; + level?: number; // compression only + memLevel?: number; // compression only + strategy?: number; // compression only + dictionary?: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default + } + + export interface Zlib { + readonly bytesRead: number; + close(callback?: () => void): void; + flush(kind?: number | (() => void), callback?: () => void): void; + } + + export interface ZlibParams { + params(level: number, strategy: number, callback: () => void): void; + } + + export interface ZlibReset { + reset(): void; + } + + export interface Gzip extends stream.Transform, Zlib { } + export interface Gunzip extends stream.Transform, Zlib { } + export interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + export interface Inflate extends stream.Transform, Zlib, ZlibReset { } + export interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + export interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } + export interface Unzip extends stream.Transform, Zlib { } + + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; + + type InputType = string | Buffer | DataView | ArrayBuffer | NodeJS.TypedArray; + export function deflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function deflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; + export function deflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function deflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + export function gzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function gzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; + export function gunzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function gunzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; + export function inflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function inflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; + export function inflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function inflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + export function unzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function unzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; + + export namespace constants { + // Allowed flush values. + + export const Z_NO_FLUSH: number; + export const Z_PARTIAL_FLUSH: number; + export const Z_SYNC_FLUSH: number; + export const Z_FULL_FLUSH: number; + export const Z_FINISH: number; + export const Z_BLOCK: number; + export const Z_TREES: number; + + // Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events. + + export const Z_OK: number; + export const Z_STREAM_END: number; + export const Z_NEED_DICT: number; + export const Z_ERRNO: number; + export const Z_STREAM_ERROR: number; + export const Z_DATA_ERROR: number; + export const Z_MEM_ERROR: number; + export const Z_BUF_ERROR: number; + export const Z_VERSION_ERROR: number; + + // Compression levels. + + export const Z_NO_COMPRESSION: number; + export const Z_BEST_SPEED: number; + export const Z_BEST_COMPRESSION: number; + export const Z_DEFAULT_COMPRESSION: number; + + // Compression strategy. + + export const Z_FILTERED: number; + export const Z_HUFFMAN_ONLY: number; + export const Z_RLE: number; + export const Z_FIXED: number; + export const Z_DEFAULT_STRATEGY: number; + } + + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; +} + +declare module "os" { + export interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + export interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + + export interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + + export interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + + export type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + + export function hostname(): string; + export function loadavg(): number[]; + export function uptime(): number; + export function freemem(): number; + export function totalmem(): number; + export function cpus(): CpuInfo[]; + export function type(): string; + export function release(): string; + export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + export function homedir(): string; + export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string }; + export const constants: { + UV_UDP_REUSEADDR: number; + signals: { + SIGHUP: number; + SIGINT: number; + SIGQUIT: number; + SIGILL: number; + SIGTRAP: number; + SIGABRT: number; + SIGIOT: number; + SIGBUS: number; + SIGFPE: number; + SIGKILL: number; + SIGUSR1: number; + SIGSEGV: number; + SIGUSR2: number; + SIGPIPE: number; + SIGALRM: number; + SIGTERM: number; + SIGCHLD: number; + SIGSTKFLT: number; + SIGCONT: number; + SIGSTOP: number; + SIGTSTP: number; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGPWR: number; + SIGSYS: number; + SIGUNUSED: number; + }; + errno: { + E2BIG: number; + EACCES: number; + EADDRINUSE: number; + EADDRNOTAVAIL: number; + EAFNOSUPPORT: number; + EAGAIN: number; + EALREADY: number; + EBADF: number; + EBADMSG: number; + EBUSY: number; + ECANCELED: number; + ECHILD: number; + ECONNABORTED: number; + ECONNREFUSED: number; + ECONNRESET: number; + EDEADLK: number; + EDESTADDRREQ: number; + EDOM: number; + EDQUOT: number; + EEXIST: number; + EFAULT: number; + EFBIG: number; + EHOSTUNREACH: number; + EIDRM: number; + EILSEQ: number; + EINPROGRESS: number; + EINTR: number; + EINVAL: number; + EIO: number; + EISCONN: number; + EISDIR: number; + ELOOP: number; + EMFILE: number; + EMLINK: number; + EMSGSIZE: number; + EMULTIHOP: number; + ENAMETOOLONG: number; + ENETDOWN: number; + ENETRESET: number; + ENETUNREACH: number; + ENFILE: number; + ENOBUFS: number; + ENODATA: number; + ENODEV: number; + ENOENT: number; + ENOEXEC: number; + ENOLCK: number; + ENOLINK: number; + ENOMEM: number; + ENOMSG: number; + ENOPROTOOPT: number; + ENOSPC: number; + ENOSR: number; + ENOSTR: number; + ENOSYS: number; + ENOTCONN: number; + ENOTDIR: number; + ENOTEMPTY: number; + ENOTSOCK: number; + ENOTSUP: number; + ENOTTY: number; + ENXIO: number; + EOPNOTSUPP: number; + EOVERFLOW: number; + EPERM: number; + EPIPE: number; + EPROTO: number; + EPROTONOSUPPORT: number; + EPROTOTYPE: number; + ERANGE: number; + EROFS: number; + ESPIPE: number; + ESRCH: number; + ESTALE: number; + ETIME: number; + ETIMEDOUT: number; + ETXTBSY: number; + EWOULDBLOCK: number; + EXDEV: number; + }; + priority: { + PRIORITY_LOW: number; + PRIORITY_BELOW_NORMAL: number; + PRIORITY_NORMAL: number; + PRIORITY_ABOVE_NORMAL: number; + PRIORITY_HIGH: number; + PRIORITY_HIGHEST: number; + } + }; + export function arch(): string; + export function platform(): NodeJS.Platform; + export function tmpdir(): string; + export const EOL: string; + export function endianness(): "BE" | "LE"; + /** + * Gets the priority of a process. + * Defaults to current process. + */ + export function getPriority(pid?: number): number; + /** + * Sets the priority of the current process. + * @param priority Must be in range of -20 to 19 + */ + export function setPriority(priority: number): void; + /** + * Sets the priority of the process specified process. + * @param priority Must be in range of -20 to 19 + */ + export function setPriority(pid: number, priority: number): void; +} + +declare module "https" { + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; + import { URL } from "url"; + + export type ServerOptions = tls.SecureContextOptions & tls.TlsOptions; + + export type RequestOptions = http.RequestOptions & tls.SecureContextOptions & { + rejectUnauthorized?: boolean; // Defaults to true + servername?: string; // SNI TLS Extension + }; + + export interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean; + maxCachedSessions?: number; + } + + export class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + + export class Server extends tls.Server { + setTimeout(callback: () => void): this; + setTimeout(msecs?: number, callback?: () => void): this; + timeout: number; + keepAliveTimeout: number; + } + + export function createServer(options: ServerOptions, requestListener?: (req: http.IncomingMessage, res: http.ServerResponse) => void): Server; + export function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export var globalAgent: Agent; +} + +declare module "punycode" { + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + export var version: any; +} + +declare module "repl" { + import * as stream from "stream"; + import * as readline from "readline"; + + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + completer?: Function; + replMode?: any; + breakEvalOnSigint?: any; + } + + export interface REPLServer extends readline.ReadLine { + context: any; + inputStream: NodeJS.ReadableStream; + outputStream: NodeJS.WritableStream; + + defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; + displayPrompt(preserveCursor?: boolean): void; + + /** + * events.EventEmitter + * 1. exit + * 2. reset + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (...args: any[]) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: any): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (...args: any[]) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (...args: any[]) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (...args: any[]) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (...args: any[]) => void): this; + } + + export function start(options?: string | ReplOptions): REPLServer; + + export class Recoverable extends SyntaxError { + err: Error; + + constructor(err: Error); + } +} + +declare module "readline" { + import * as events from "events"; + import * as stream from "stream"; + + export interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } + + export interface ReadLine extends events.EventEmitter { + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): ReadLine; + resume(): ReadLine; + close(): void; + write(data: string | Buffer, key?: Key): void; + + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: any) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: any): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: any) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: any) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: any) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: any) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + } + + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err: any, result: CompleterResult) => void) => any; + + export type CompleterResult = [string[], string]; + + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer | AsyncCompleter; + terminal?: boolean; + historySize?: number; + prompt?: string; + crlfDelay?: number; + removeHistoryDuplicates?: boolean; + } + + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): ReadLine; + export function createInterface(options: ReadLineOptions): ReadLine; + + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; + export function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: ReadLine): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + export function clearLine(stream: NodeJS.WritableStream, dir: number): void; + export function clearScreenDown(stream: NodeJS.WritableStream): void; +} + +declare module "vm" { + export interface Context { } + export interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * Default: `0` + */ + columnOffset?: number; + } + export interface ScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + export interface RunningScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + } + export interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context; + + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[]; + } + export class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + export function createContext(sandbox?: Context): Context; + export function isContext(sandbox: Context): boolean; + export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any; + /** @deprecated */ + export function runInDebugContext(code: string): any; + export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; + export function runInThisContext(code: string, options?: RunningScriptOptions | string): any; + export function compileFunction(code: string, params: string[], options: CompileFunctionOptions): Function; +} + +declare module "child_process" { + import * as events from "events"; + import * as stream from "stream"; + import * as net from "net"; + + export interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + killed: boolean; + pid: number; + kill(signal?: string): void; + send(message: any, callback?: (error: Error) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error) => void): boolean; + connected: boolean; + disconnect(): void; + unref(): void; + ref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number, signal: string) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number, signal: string): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number, signal: string) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number, signal: string) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number, signal: string) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + } + + export interface MessageOptions { + keepOpen?: boolean; + } + + export type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | stream.Stream | number | null | undefined)>; + + export interface SpawnOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + argv0?: string; + stdio?: StdioOptions; + detached?: boolean; + uid?: number; + gid?: number; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + windowsHide?: boolean; + } + + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; + + export interface ExecOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + shell?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + windowsHide?: boolean; + } + + export interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + + export interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string | null; // specify `null`. + } + + export interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: string; + } + + // no `options` definitely means stdout/stderr are `string`. + export function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + export function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + export function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + export function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + export function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + export function exec(command: string, options: ({ encoding?: string | null } & ExecOptions) | undefined | null, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace exec { + export function __promisify__(command: string): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): Promise<{ stdout: Buffer, stderr: Buffer }>; + export function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(command: string, options: ExecOptions): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(command: string, options?: ({ encoding?: string | null } & ExecOptions) | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + export interface ExecFileOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + windowsHide?: boolean; + windowsVerbatimArguments?: boolean; + } + export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + export interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: string; + } + + export function execFile(file: string): ChildProcess; + export function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + export function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; + export function execFile(file: string, args: ReadonlyArray | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + + // no `options` definitely means stdout/stderr are `string`. + export function execFile(file: string, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + export function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + export function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithStringEncoding, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + export function execFile(file: string, options: ExecFileOptionsWithOtherEncoding, callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + export function execFile(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithOtherEncoding, callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + export function execFile(file: string, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + export function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null): ChildProcess; + export function execFile(file: string, args: ReadonlyArray | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace execFile { + export function __promisify__(file: string): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(file: string, args: string[] | undefined | null): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + export function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + export function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + export function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + export function __promisify__(file: string, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + export function __promisify__(file: string, args: string[] | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + export interface ForkOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + stdio?: StdioOptions; + windowsVerbatimArguments?: boolean; + uid?: number; + gid?: number; + } + export function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; + + export interface SpawnSyncOptions { + argv0?: string; // Not specified in the docs + cwd?: string; + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + windowsHide?: boolean; + } + export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + export interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + export function spawnSync(command: string): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + export function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + + export interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer | Uint8Array; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + shell?: string; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + windowsHide?: boolean; + } + export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + export function execSync(command: string): Buffer; + export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + export function execSync(command: string, options?: ExecSyncOptions): Buffer; + + export interface ExecFileSyncOptions { + cwd?: string; + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + windowsHide?: boolean; + shell?: boolean | string; + } + export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + export function execFileSync(command: string): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + export function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): Buffer; +} + +declare module "url" { + import { ParsedUrlQuery } from 'querystring'; + + export interface UrlObjectCommon { + auth?: string; + hash?: string; + host?: string; + hostname?: string; + href?: string; + path?: string; + pathname?: string; + protocol?: string; + search?: string; + slashes?: boolean; + } + + // Input to `url.format` + export interface UrlObject extends UrlObjectCommon { + port?: string | number; + query?: string | null | { [key: string]: any }; + } + + // Output of `url.parse` + export interface Url extends UrlObjectCommon { + port?: string; + query?: string | null | ParsedUrlQuery; + } + + export interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + + export interface UrlWithStringQuery extends Url { + query: string | null; + } + + export function parse(urlStr: string): UrlWithStringQuery; + export function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + export function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + export function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + + export function format(URL: URL, options?: URLFormatOptions): string; + export function format(urlObject: UrlObject | string): string; + export function resolve(from: string, to: string): string; + + export function domainToASCII(domain: string): string; + export function domainToUnicode(domain: string): string; + + export interface URLFormatOptions { + auth?: boolean; + fragment?: boolean; + search?: boolean; + unicode?: boolean; + } + + export class URL { + constructor(input: string, base?: string | URL); + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toString(): string; + toJSON(): string; + } + + export class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | { [key: string]: string | string[] | undefined } | Iterable<[string, string]> | Array<[string, string]>); + append(name: string, value: string): void; + delete(name: string): void; + entries(): IterableIterator<[string, string]>; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + keys(): IterableIterator; + set(name: string, value: string): void; + sort(): void; + toString(): string; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } +} + +declare module "dns" { + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + + export interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; + } + + export interface LookupOneOptions extends LookupOptions { + all?: false; + } + + export interface LookupAllOptions extends LookupOptions { + all: true; + } + + export interface LookupAddress { + address: string; + family: number; + } + + export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; + export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; + export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lookup { + export function __promisify__(hostname: string, options: LookupAllOptions): Promise<{ address: LookupAddress[] }>; + export function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<{ address: string, family: number }>; + export function __promisify__(hostname: string, options?: LookupOptions | number): Promise<{ address: string | LookupAddress[], family?: number }>; + } + + export function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException, hostname: string, service: string) => void): void; + + export namespace lookupService { + export function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; + } + + export interface ResolveOptions { + ttl: boolean; + } + + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + + export interface RecordWithTtl { + address: string; + ttl: number; + } + + /** @deprecated Use AnyARecord or AnyAaaaRecord instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + + export interface AnyARecord extends RecordWithTtl { + type: "A"; + } + + export interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + + export interface MxRecord { + priority: number; + exchange: string; + } + + export interface AnyMxRecord extends MxRecord { + type: "MX"; + } + + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + + export interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + + export interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + + export interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + + export interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + + export interface AnyNsRecord { + type: "NS"; + value: string; + } + + export interface AnyPtrRecord { + type: "PTR"; + value: string; + } + + export interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + + export type AnyRecord = AnyARecord | + AnyAaaaRecord | + AnyCnameRecord | + AnyMxRecord | + AnyNaptrRecord | + AnyNsRecord | + AnyPtrRecord | + AnySoaRecord | + AnySrvRecord | + AnyTxtRecord; + + export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException, addresses: SoaRecord) => void): void; + export function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + export function resolve(hostname: string, rrtype: string, callback: (err: NodeJS.ErrnoException, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace resolve { + export function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + export function __promisify__(hostname: string, rrtype: "ANY"): Promise; + export function __promisify__(hostname: string, rrtype: "MX"): Promise; + export function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + export function __promisify__(hostname: string, rrtype: "SOA"): Promise; + export function __promisify__(hostname: string, rrtype: "SRV"): Promise; + export function __promisify__(hostname: string, rrtype: "TXT"): Promise; + export function __promisify__(hostname: string, rrtype: string): Promise; + } + + export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace resolve4 { + export function __promisify__(hostname: string): Promise; + export function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + export function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace resolve6 { + export function __promisify__(hostname: string): Promise; + export function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + export function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export namespace resolveCname { + export function __promisify__(hostname: string): Promise; + } + + export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + export namespace resolveMx { + export function __promisify__(hostname: string): Promise; + } + + export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + export namespace resolveNaptr { + export function __promisify__(hostname: string): Promise; + } + + export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export namespace resolveNs { + export function __promisify__(hostname: string): Promise; + } + + export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export namespace resolvePtr { + export function __promisify__(hostname: string): Promise; + } + + export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException, address: SoaRecord) => void): void; + export namespace resolveSoa { + export function __promisify__(hostname: string): Promise; + } + + export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + export namespace resolveSrv { + export function __promisify__(hostname: string): Promise; + } + + export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + export namespace resolveTxt { + export function __promisify__(hostname: string): Promise; + } + + export function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; + export namespace resolveAny { + export function __promisify__(hostname: string): Promise; + } + + export function reverse(ip: string, callback: (err: NodeJS.ErrnoException, hostnames: string[]) => void): void; + export function setServers(servers: string[]): void; + export function getServers(): string[]; + + // Error codes + export var NODATA: string; + export var FORMERR: string; + export var SERVFAIL: string; + export var NOTFOUND: string; + export var NOTIMP: string; + export var REFUSED: string; + export var BADQUERY: string; + export var BADNAME: string; + export var BADFAMILY: string; + export var BADRESP: string; + export var CONNREFUSED: string; + export var TIMEOUT: string; + export var EOF: string; + export var FILE: string; + export var NOMEM: string; + export var DESTRUCTION: string; + export var BADSTR: string; + export var BADFLAGS: string; + export var NONAME: string; + export var BADHINTS: string; + export var NOTINITIALIZED: string; + export var LOADIPHLPAPI: string; + export var ADDRGETNETWORKPARAMS: string; + export var CANCELLED: string; + + export class Resolver { + getServers: typeof getServers; + setServers: typeof setServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + cancel(): void; + } +} + +declare module "net" { + import * as stream from "stream"; + import * as events from "events"; + import * as dns from "dns"; + + type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + + export interface AddressInfo { + address: string; + family: string; + port: number; + } + + export interface SocketConstructorOpts { + fd?: number; + allowHalfOpen?: boolean; + readable?: boolean; + writable?: boolean; + } + + export interface TcpSocketConnectOpts { + port: number; + host?: string; + localAddress?: string; + localPort?: number; + hints?: number; + family?: number; + lookup?: LookupFunction; + } + + export interface IpcSocketConnectOpts { + path: string; + } + + export type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + + export class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + write(data: any, encoding?: string, callback?: Function): void; + + connect(options: SocketConnectOpts, connectionListener?: Function): this; + connect(port: number, host: string, connectionListener?: Function): this; + connect(port: number, connectionListener?: Function): this; + connect(path: string, connectionListener?: Function): this; + + bufferSize: number; + setEncoding(encoding?: string): this; + pause(): this; + resume(): this; + setTimeout(timeout: number, callback?: Function): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; + address(): AddressInfo | string; + unref(): void; + ref(): void; + + remoteAddress?: string; + remoteFamily?: string; + remotePort?: number; + localAddress: string; + localPort: number; + bytesRead: number; + bytesWritten: number; + connecting: boolean; + destroyed: boolean; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (had_error: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", had_error: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (had_error: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (had_error: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (had_error: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + export interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + readableAll?: boolean; + writableAll?: boolean; + } + + // https://github.com/nodejs/node/blob/master/lib/net.js + export class Server extends events.EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void); + + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: Function): this; + listen(port?: number, hostname?: string, listeningListener?: Function): this; + listen(port?: number, backlog?: number, listeningListener?: Function): this; + listen(port?: number, listeningListener?: Function): this; + listen(path: string, backlog?: number, listeningListener?: Function): this; + listen(path: string, listeningListener?: Function): this; + listen(options: ListenOptions, listeningListener?: Function): this; + listen(handle: any, backlog?: number, listeningListener?: Function): this; + listen(handle: any, listeningListener?: Function): this; + close(callback?: Function): this; + address(): AddressInfo | string; + getConnections(cb: (error: Error | null, count: number) => void): void; + ref(): this; + unref(): this; + maxConnections: number; + connections: number; + listening: boolean; + + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + } + + export interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + export interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + export type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + + export function createServer(connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; + export function connect(options: NetConnectOpts, connectionListener?: Function): Socket; + export function connect(port: number, host?: string, connectionListener?: Function): Socket; + export function connect(path: string, connectionListener?: Function): Socket; + export function createConnection(options: NetConnectOpts, connectionListener?: Function): Socket; + export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + export function createConnection(path: string, connectionListener?: Function): Socket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; +} + +declare module "dgram" { + import { AddressInfo } from "net"; + import * as dns from "dns"; + import * as events from "events"; + + export interface RemoteInfo { + address: string; + family: string; + port: number; + } + + export interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } + + type SocketType = "udp4" | "udp6"; + + export interface SocketOptions { + type: SocketType; + reuseAddr?: boolean; + recvBufferSize?: number; + sendBufferSize?: number; + lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void) => void; + } + + export function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + export class Socket extends events.EventEmitter { + send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + bind(port?: number, address?: string, callback?: () => void): void; + bind(port?: number, callback?: () => void): void; + bind(callback?: () => void): void; + bind(options: BindOptions, callback?: Function): void; + close(callback?: () => void): void; + address(): AddressInfo | string; + setBroadcast(flag: boolean): void; + setTTL(ttl: number): void; + setMulticastTTL(ttl: number): void; + setMulticastInterface(multicastInterface: string): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): this; + unref(): this; + setRecvBufferSize(size: number): void; + setSendBufferSize(size: number): void; + getRecvBufferSize(): number; + getSendBufferSize(): number; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + } +} + +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + import { URL } from "url"; + + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + + export type BinaryData = Buffer | DataView | NodeJS.TypedArray; + export class Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atimeMs: number; + mtimeMs: number; + ctimeMs: number; + birthtimeMs: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + export class Dirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; + } + + export interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + + export class ReadStream extends stream.Readable { + close(): void; + bytesRead: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + export class WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function truncate(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + export function __promisify__(path: PathLike, len?: number | null): Promise; + } + + /** + * Synchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + export function truncateSync(path: PathLike, len?: number | null): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + export function __promisify__(fd: number, len?: number | null): Promise; + } + + /** + * Synchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + export function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function chown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + export function __promisify__(fd: number, uid: number, gid: number): Promise; + } + + /** + * Synchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function chmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function chmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function __promisify__(fd: number, mode: string | number): Promise; + } + + /** + * Synchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function fchmodSync(fd: number, mode: string | number): void; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function lchmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function lchmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function statSync(path: PathLike): Stats; + + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + export function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + export function fstatSync(fd: number): Stats; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lstatSync(path: PathLike): Stats; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function link(existingPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + export function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + + export type Type = "dir" | "file" | "junction"; + } + + /** + * Synchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, linkString: Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string | Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + export function native(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + export function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; + export function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; + export function native(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + } + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + export namespace realpathSync { + export function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + export function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + export function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + } + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function unlink(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function unlinkSync(path: PathLike): void; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function rmdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function rmdirSync(path: PathLike): void; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, mode: number | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function __promisify__(path: PathLike, mode?: number | string | null): Promise; + } + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, mode?: number | string | null): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException, folder: Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string | Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir(path: PathLike, options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir(path: PathLike, options: { withFileTypes: true }, callback: (err: NodeJS.ErrnoException, files: Dirent[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + export function __promisify__(path: PathLike, options: { withFileTypes: true }): Promise; + } + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync(path: PathLike, options: { withFileTypes: true }): Dirent[]; + + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + export function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + export function __promisify__(fd: number): Promise; + } + + /** + * Synchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + export function closeSync(fd: number): void; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + export function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + export function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise; + } + + /** + * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + export function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + export function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + export function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + export function fsyncSync(fd: number): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write(fd: number, string: any, position: number | undefined | null, encoding: string | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + */ + export function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function __promisify__(fd: number, buffer?: TBuffer, offset?: number, length?: number, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + } + + /** + * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function writeSync(fd: number, buffer: BinaryData, offset?: number | null, length?: number | null, position?: number | null): number; + + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; + + /** + * Asynchronously reads data from the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + export function read(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + export function __promisify__(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + } + + /** + * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + export function readSync(fd: number, buffer: BinaryData, offset: number, length: number, position: number | null): number; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile(path: PathLike | number, options: { encoding?: string | null; flag?: string; } | string | undefined | null, callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise; + } + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; + + export type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + export function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile(path: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + export function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + export function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + export function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + export function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + export function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + */ + export function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Stop watching for changes on `filename`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, listener?: (event: string, filename: string) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, listener?: (event: string, filename: string | Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; + + /** + * Asynchronously tests whether or not the given path exists by checking with the file system. + * @deprecated + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronously tests whether or not the given path exists by checking with the file system. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function existsSync(path: PathLike): boolean; + + export namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + export const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + export const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + export const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + export const X_OK: number; + + // File Copy Constants + + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + export const COPYFILE_EXCL: number; + + /** Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. */ + export const COPYFILE_FICLONE: number; + + /** Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error. */ + export const COPYFILE_FICLONE_FORCE: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + export const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + export const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + export const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + export const O_CREAT: number; + + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + export const O_EXCL: number; + + /** Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one). */ + export const O_NOCTTY: number; + + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + export const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + export const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + export const O_DIRECTORY: number; + + /** Constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only. */ + export const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + export const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + export const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + export const O_DSYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + export const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + export const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + export const O_NONBLOCK: number; + + // File Type Constants + + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + export const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + export const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + export const S_IFDIR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + export const S_IFCHR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + export const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + export const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + export const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + export const S_IFSOCK: number; + + // File Mode Constants + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + export const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + export const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + export const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + export const S_IXUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + export const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + export const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + export const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + export const S_IXGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + export const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + export const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + export const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + export const S_IXOTH: number; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function access(path: PathLike, mode: number | undefined, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function access(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function __promisify__(path: PathLike, mode?: number): Promise; + } + + /** + * Synchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function accessSync(path: PathLike, mode?: number): void; + + /** + * Returns a new `ReadStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function createReadStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + highWaterMark?: number; + }): ReadStream; + + /** + * Returns a new `WriteStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function createWriteStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + }): WriteStream; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + export function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + export function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + export function fdatasyncSync(fd: number): void; + + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + export function copyFile(src: PathLike, dest: PathLike, flags: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace copyFile { + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + export function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; + } + + /** + * Synchronously copies src to dest. By default, dest is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + export function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; + + export namespace promises { + interface FileHandle { + /** + * Gets the file descriptor for this file handle. + */ + readonly fd: number; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for appending. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + appendFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + */ + chown(uid: number, gid: number): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + chmod(mode: string | number): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + */ + datasync(): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + */ + sync(): Promise; + + /** + * Asynchronously reads data from the file. + * The `FileHandle` must have been opened for reading. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + read(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + */ + stat(): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param len If not specified, defaults to `0`. + */ + truncate(len?: number): Promise; + + /** + * Asynchronously change file timestamps of the file. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously writes `buffer` to the file. + * The `FileHandle` must have been opened for writing. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + write(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + write(data: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + writeFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous close(2) - close a `FileHandle`. + */ + close(): Promise; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode?: number): Promise; + + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. The only + * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if + * `dest` already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not + * supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode?: string | number): Promise; + + /** + * Asynchronously reads data from the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If + * `null`, data will be read from the current position. + */ + function read(handle: FileHandle, buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write(handle: FileHandle, buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write(handle: FileHandle, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len?: number): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param handle A `FileHandle`. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(handle: FileHandle, len?: number): Promise; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param handle A `FileHandle`. + */ + function fdatasync(handle: FileHandle): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param handle A `FileHandle`. + */ + function fsync(handle: FileHandle): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, mode?: string | number): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + * @param handle A `FileHandle`. + */ + function fstat(handle: FileHandle): Promise; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike): Promise; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike): Promise; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param handle A `FileHandle`. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(handle: FileHandle, mode: string | number): Promise; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param handle A `FileHandle`. + */ + function fchown(handle: FileHandle, uid: number, gid: number): Promise; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + } +} + +declare module "path" { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + export interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + export interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string; + /** + * The file extension (if any) such as '.html' + */ + ext?: string; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string; + } + + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + export function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + export function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + export function resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + export function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + export function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + export function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + export function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + export function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + export var sep: '\\' | '/'; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + export var delimiter: ';' | ':'; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + export function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + export function format(pathObject: FormatInputPathObject): string; + + export module posix { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: FormatInputPathObject): string; + } + + export module win32 { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: FormatInputPathObject): string; + } +} + +declare module "string_decoder" { + export interface NodeStringDecoder { + write(buffer: Buffer): string; + end(buffer?: Buffer): string; + } + export var StringDecoder: { + new(encoding?: string): NodeStringDecoder; + }; +} + +declare module "tls" { + import * as crypto from "crypto"; + import * as dns from "dns"; + import * as net from "net"; + import * as stream from "stream"; + + var CLIENT_RENEG_LIMIT: number; + var CLIENT_RENEG_WINDOW: number; + + export interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + + export interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: { [index: string]: string[] | undefined }; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + + export interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + + export interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } + + export class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext, + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean, + /** + * An optional net.Server instance. + */ + server?: net.Server, + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean, + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. Defaults to false. + */ + rejectUnauthorized?: boolean, + /** + * An array of strings or a Buffer naming possible NPN protocols. + * (Protocols should be ordered by their priority.) + */ + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) When the server + * receives both NPN and ALPN extensions from the client, ALPN takes + * precedence over NPN and the server does not send an NPN extension + * to the client. + */ + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void, + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer, + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean + }); + + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. + * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. + * The value `null` will be returned for server sockets or disconnected client sockets. + * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. + * @returns negotiated SSL/TLS protocol version of the current connection + */ + getProtocol(): string | null; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): any; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): any; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + */ + renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): any; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; + + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + } + + export interface TlsOptions extends SecureContextOptions { + handshakeTimeout?: number; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; + sessionTimeout?: number; + ticketKeys?: Buffer; + } + + export interface ConnectionOptions extends SecureContextOptions { + host?: string; + port?: number; + path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket + rejectUnauthorized?: boolean; // Defaults to true + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + checkServerIdentity?: typeof checkServerIdentity; + servername?: string; // SNI TLS Extension + session?: Buffer; + minDHSize?: number; + secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() + lookup?: net.LookupFunction; + } + + export class Server extends net.Server { + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; + emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + } + + export interface SecurePair { + encrypted: any; + cleartext: any; + } + + export interface SecureContextOptions { + pfx?: string | Buffer | Array; + key?: string | Buffer | Array; + passphrase?: string; + cert?: string | Buffer | Array; + ca?: string | Buffer | Array; + ciphers?: string; + honorCipherOrder?: boolean; + ecdhCurve?: string; + clientCertEngine?: string; + crl?: string | Buffer | Array; + dhparam?: string | Buffer; + secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options + secureProtocol?: string; // SSL Method, e.g. SSLv23_method + sessionIdContext?: string; + } + + export interface SecureContext { + context: any; + } + + /* + * Verifies the certificate `cert` is issued to host `host`. + * @host The hostname to verify the certificate against + * @cert PeerCertificate representing the peer's certificate + * + * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. + */ + export function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; + export function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): TLSSocket; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + export function createSecureContext(details: SecureContextOptions): SecureContext; + export function getCiphers(): string[]; + + export var DEFAULT_ECDH_CURVE: string; +} + +declare module "crypto" { + import * as stream from "stream"; + + export interface Certificate { + exportChallenge(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + exportPublicKey(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + verifySpkac(spkac: Buffer | NodeJS.TypedArray | DataView): boolean; + } + export var Certificate: { + new(): Certificate; + (): Certificate; + }; + + /** @deprecated since v10.0.0 */ + export var fips: boolean; + + export interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: string | string[]; + crl: string | string[]; + ciphers: string; + } + export interface Credentials { context?: any; } + export function createCredentials(details: CredentialDetails): Credentials; + export function createHash(algorithm: string, options?: stream.TransformOptions): Hash; + export function createHmac(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Hmac; + + type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; + type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; + type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; + type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + + export interface Hash extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Hash; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + export interface Hmac extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Hmac; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + export type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm'; + export type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + export interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + export interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number; + } + /** @deprecated since v10.0.0 use createCipheriv() */ + export function createCipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + export function createCipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + export function createCipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; + + export function createCipheriv(algorithm: CipherCCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; + export function createCipheriv(algorithm: CipherGCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; + export function createCipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; + + export interface Cipher extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; + update(data: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64BinaryEncoding): string; + update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; + // second arg ignored + update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // getAuthTag(): Buffer; + // setAAD(buffer: Buffer): this; // docs only say buffer + } + export interface CipherCCM extends Cipher { + setAAD(buffer: Buffer, options: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + export interface CipherGCM extends Cipher { + setAAD(buffer: Buffer, options?: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + /** @deprecated since v10.0.0 use createCipheriv() */ + export function createDecipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + export function createDecipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + export function createDecipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; + + export function createDecipheriv(algorithm: CipherCCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): DecipherCCM; + export function createDecipheriv(algorithm: CipherGCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): DecipherGCM; + export function createDecipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; + + export interface Decipher extends NodeJS.ReadWriteStream { + update(data: Buffer | NodeJS.TypedArray | DataView): Buffer; + update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; + update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + // second arg is ignored + update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // setAuthTag(tag: Buffer | NodeJS.TypedArray | DataView): this; + // setAAD(buffer: Buffer | NodeJS.TypedArray | DataView): this; + } + export interface DecipherCCM extends Decipher { + setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; + setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options: { plaintextLength: number }): this; + } + export interface DecipherGCM extends Decipher { + setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; + setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options?: { plaintextLength: number }): this; + } + + export function createSign(algorithm: string, options?: stream.WritableOptions): Signer; + export interface Signer extends NodeJS.WritableStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Signer; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: string | { key: string; passphrase: string, padding?: number, saltLength?: number }): Buffer; + sign(private_key: string | { key: string; passphrase: string, padding?: number, saltLength?: number }, output_format: HexBase64Latin1Encoding): string; + } + export function createVerify(algorith: string, options?: stream.WritableOptions): Verify; + export interface Verify extends NodeJS.WritableStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Verify; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify; + verify(object: string | Object, signature: Buffer | NodeJS.TypedArray | DataView): boolean; + verify(object: string | Object, signature: string, signature_format: HexBase64Latin1Encoding): boolean; + // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format + // The signature field accepts a TypedArray type, but it is only available starting ES2017 + } + export function createDiffieHellman(prime_length: number, generator?: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + export function createDiffieHellman(prime: Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; + export interface DiffieHellman { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrime(): Buffer; + getPrime(encoding: HexBase64Latin1Encoding): string; + getGenerator(): Buffer; + getGenerator(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + setPublicKey(public_key: Buffer | NodeJS.TypedArray | DataView): void; + setPublicKey(public_key: string, encoding: string): void; + setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; + setPrivateKey(private_key: string, encoding: string): void; + verifyError: number; + } + export function getDiffieHellman(group_name: string): DiffieHellman; + export function pbkdf2(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, iterations: number, keylen: number, digest: string): Buffer; + + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + + export function randomFillSync(buffer: T, offset?: number, size?: number): T; + export function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + export function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + export function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + + export interface ScryptOptions { + N?: number; + r?: number; + p?: number; + maxmem?: number; + } + export function scrypt(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void): void; + export function scrypt(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, keylen: number, options: ScryptOptions, callback: (err: Error | null, derivedKey: Buffer) => void): void; + export function scryptSync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, keylen: number, options?: ScryptOptions): Buffer; + + export interface RsaPublicKey { + key: string; + padding?: number; + } + export interface RsaPrivateKey { + key: string; + passphrase?: string; + padding?: number; + } + export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + export function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + export function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + export function getCiphers(): string[]; + export function getCurves(): string[]; + export function getHashes(): string[]; + export class ECDH { + static convertKey(key: string | Buffer | NodeJS.TypedArray | DataView, curve: string, inputEncoding?: HexBase64Latin1Encoding, outputEncoding?: "latin1" | "hex" | "base64", format?: "uncompressed" | "compressed" | "hybrid"): Buffer | string; + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; + setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; + } + export function createECDH(curve_name: string): ECDH; + export function timingSafeEqual(a: Buffer | NodeJS.TypedArray | DataView, b: Buffer | NodeJS.TypedArray | DataView): boolean; + /** @deprecated since v10.0.0 */ + export var DEFAULT_ENCODING: string; +} + +declare module "stream" { + import * as events from "events"; + + class internal extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + + namespace internal { + export class Stream extends internal { } + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?(this: Readable, size: number): void; + destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; + } + + export class Readable extends Stream implements NodeJS.ReadableStream { + readable: boolean; + readonly readableHighWaterMark: number; + readonly readableLength: number; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + unpipe(destination?: T): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: string): boolean; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?(this: Writable, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Writable, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + + export class Writable extends Stream implements NodeJS.WritableStream { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements Writable { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; + cork(): void; + uncork(): void; + } + + type TransformCallback = (error?: Error, data?: any) => void; + + export interface TransformOptions extends DuplexOptions { + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Transform, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: string, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + + export class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + + export class PassThrough extends Transform { } + + export function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException) => void): () => void; + export namespace finished { + export function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream): Promise; + } + + export function pipeline(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException) => void): T; + export function pipeline(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T, callback?: (err: NodeJS.ErrnoException) => void): T; + export function pipeline(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: T, callback?: (err: NodeJS.ErrnoException) => void): T; + export function pipeline(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.ReadWriteStream, stream5: T, callback?: (err: NodeJS.ErrnoException) => void): T; + export function pipeline(streams: Array, callback?: (err: NodeJS.ErrnoException) => void): NodeJS.WritableStream; + export function pipeline(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, ...streams: Array void)>): NodeJS.WritableStream; + export namespace pipeline { + export function __promisify__(stream1: NodeJS.ReadableStream, stream2: T): Promise; + export function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T): Promise; + export function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: T): Promise; + export function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.ReadWriteStream, stream5: T): Promise; + export function __promisify__(streams: Array): Promise; + export function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, ...streams: Array): Promise; + } + } + + export = internal; +} + +declare module "util" { + export interface InspectOptions extends NodeJS.InspectOptions { } + export function format(format: any, ...param: any[]): string; + export function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + export function debug(string: string): void; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + export function error(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + export function puts(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + export function print(...param: any[]): void; + /** @deprecated since v0.11.3 - use a third party module instead. */ + export function log(string: string): void; + export var inspect: { + (object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + (object: any, options: InspectOptions): string; + colors: { + [color: string]: [number, number] | undefined + } + styles: { + [style: string]: string | undefined + } + defaultOptions: InspectOptions; + custom: symbol; + }; + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + export function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + export function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + export function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + export function isError(object: any): object is Error; + export function inherits(constructor: any, superConstructor: any): void; + export function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + export function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + export function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + export function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + export function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + export function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + export function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + export function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + export function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + export function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + export function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + export function isUndefined(object: any): object is undefined; + export function deprecate(fn: T, message: string): T; + export function isDeepStrictEqual(val1: any, val2: any): boolean; + + export interface CustomPromisify extends Function { + __promisify__: TCustom; + } + + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + + export function promisify(fn: CustomPromisify): TCustom; + export function promisify(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise; + export function promisify(fn: (callback: (err?: Error | null) => void) => void): () => Promise; + export function promisify(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: Error | null) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + const custom: symbol; + } + + export namespace types { + export function isAnyArrayBuffer(object: any): boolean; + export function isArgumentsObject(object: any): object is IArguments; + export function isArrayBuffer(object: any): object is ArrayBuffer; + export function isAsyncFunction(object: any): boolean; + export function isBooleanObject(object: any): object is Boolean; + export function isDataView(object: any): object is DataView; + export function isDate(object: any): object is Date; + export function isExternal(object: any): boolean; + export function isFloat32Array(object: any): object is Float32Array; + export function isFloat64Array(object: any): object is Float64Array; + export function isGeneratorFunction(object: any): boolean; + export function isGeneratorObject(object: any): boolean; + export function isInt8Array(object: any): object is Int8Array; + export function isInt16Array(object: any): object is Int16Array; + export function isInt32Array(object: any): object is Int32Array; + export function isMap(object: any): boolean; + export function isMapIterator(object: any): boolean; + export function isNativeError(object: any): object is Error; + export function isNumberObject(object: any): object is Number; + export function isPromise(object: any): boolean; + export function isProxy(object: any): boolean; + export function isRegExp(object: any): object is RegExp; + export function isSet(object: any): boolean; + export function isSetIterator(object: any): boolean; + export function isSharedArrayBuffer(object: any): boolean; + export function isStringObject(object: any): boolean; + export function isSymbolObject(object: any): boolean; + export function isTypedArray(object: any): object is NodeJS.TypedArray; + export function isUint8Array(object: any): object is Uint8Array; + export function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + export function isUint16Array(object: any): object is Uint16Array; + export function isUint32Array(object: any): object is Uint32Array; + export function isWeakMap(object: any): boolean; + export function isWeakSet(object: any): boolean; + export function isWebAssemblyCompiledModule(object: any): boolean; + } + + export class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + export class TextEncoder { + readonly encoding: string; + constructor(); + encode(input?: string): Uint8Array; + } +} + +declare module "assert" { + function internal(value: any, message?: string | Error): void; + namespace internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFn?: Function + }); + } + + export function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + export function fail(actual: any, expected: any, message?: string | Error, operator?: string, stackStartFn?: Function): never; + export function ok(value: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use strictEqual() instead. */ + export function equal(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ + export function notEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ + export function deepEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ + export function notDeepEqual(actual: any, expected: any, message?: string | Error): void; + export function strictEqual(actual: any, expected: any, message?: string | Error): void; + export function notStrictEqual(actual: any, expected: any, message?: string | Error): void; + export function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + export function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; + + export function throws(block: Function, message?: string | Error): void; + export function throws(block: Function, error: RegExp | Function | Object | Error, message?: string | Error): void; + export function doesNotThrow(block: Function, message?: string | Error): void; + export function doesNotThrow(block: Function, error: RegExp | Function, message?: string | Error): void; + + export function ifError(value: any): void; + + export function rejects(block: Function | Promise, message?: string | Error): Promise; + export function rejects(block: Function | Promise, error: RegExp | Function | Object | Error, message?: string | Error): Promise; + export function doesNotReject(block: Function | Promise, message?: string | Error): Promise; + export function doesNotReject(block: Function | Promise, error: RegExp | Function, message?: string | Error): Promise; + + export var strict: typeof internal; + } + + export = internal; +} + +declare module "tty" { + import * as net from "net"; + + export function isatty(fd: number): boolean; + export class ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + export class WriteStream extends net.Socket { + columns: number; + rows: number; + isTTY: boolean; + } +} + +declare module "domain" { + import * as events from "events"; + + export class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + members: any[]; + enter(): void; + exit(): void; + } + + export function create(): Domain; +} + +declare module "constants" { + export var E2BIG: number; + export var EACCES: number; + export var EADDRINUSE: number; + export var EADDRNOTAVAIL: number; + export var EAFNOSUPPORT: number; + export var EAGAIN: number; + export var EALREADY: number; + export var EBADF: number; + export var EBADMSG: number; + export var EBUSY: number; + export var ECANCELED: number; + export var ECHILD: number; + export var ECONNABORTED: number; + export var ECONNREFUSED: number; + export var ECONNRESET: number; + export var EDEADLK: number; + export var EDESTADDRREQ: number; + export var EDOM: number; + export var EEXIST: number; + export var EFAULT: number; + export var EFBIG: number; + export var EHOSTUNREACH: number; + export var EIDRM: number; + export var EILSEQ: number; + export var EINPROGRESS: number; + export var EINTR: number; + export var EINVAL: number; + export var EIO: number; + export var EISCONN: number; + export var EISDIR: number; + export var ELOOP: number; + export var EMFILE: number; + export var EMLINK: number; + export var EMSGSIZE: number; + export var ENAMETOOLONG: number; + export var ENETDOWN: number; + export var ENETRESET: number; + export var ENETUNREACH: number; + export var ENFILE: number; + export var ENOBUFS: number; + export var ENODATA: number; + export var ENODEV: number; + export var ENOENT: number; + export var ENOEXEC: number; + export var ENOLCK: number; + export var ENOLINK: number; + export var ENOMEM: number; + export var ENOMSG: number; + export var ENOPROTOOPT: number; + export var ENOSPC: number; + export var ENOSR: number; + export var ENOSTR: number; + export var ENOSYS: number; + export var ENOTCONN: number; + export var ENOTDIR: number; + export var ENOTEMPTY: number; + export var ENOTSOCK: number; + export var ENOTSUP: number; + export var ENOTTY: number; + export var ENXIO: number; + export var EOPNOTSUPP: number; + export var EOVERFLOW: number; + export var EPERM: number; + export var EPIPE: number; + export var EPROTO: number; + export var EPROTONOSUPPORT: number; + export var EPROTOTYPE: number; + export var ERANGE: number; + export var EROFS: number; + export var ESPIPE: number; + export var ESRCH: number; + export var ETIME: number; + export var ETIMEDOUT: number; + export var ETXTBSY: number; + export var EWOULDBLOCK: number; + export var EXDEV: number; + export var WSAEINTR: number; + export var WSAEBADF: number; + export var WSAEACCES: number; + export var WSAEFAULT: number; + export var WSAEINVAL: number; + export var WSAEMFILE: number; + export var WSAEWOULDBLOCK: number; + export var WSAEINPROGRESS: number; + export var WSAEALREADY: number; + export var WSAENOTSOCK: number; + export var WSAEDESTADDRREQ: number; + export var WSAEMSGSIZE: number; + export var WSAEPROTOTYPE: number; + export var WSAENOPROTOOPT: number; + export var WSAEPROTONOSUPPORT: number; + export var WSAESOCKTNOSUPPORT: number; + export var WSAEOPNOTSUPP: number; + export var WSAEPFNOSUPPORT: number; + export var WSAEAFNOSUPPORT: number; + export var WSAEADDRINUSE: number; + export var WSAEADDRNOTAVAIL: number; + export var WSAENETDOWN: number; + export var WSAENETUNREACH: number; + export var WSAENETRESET: number; + export var WSAECONNABORTED: number; + export var WSAECONNRESET: number; + export var WSAENOBUFS: number; + export var WSAEISCONN: number; + export var WSAENOTCONN: number; + export var WSAESHUTDOWN: number; + export var WSAETOOMANYREFS: number; + export var WSAETIMEDOUT: number; + export var WSAECONNREFUSED: number; + export var WSAELOOP: number; + export var WSAENAMETOOLONG: number; + export var WSAEHOSTDOWN: number; + export var WSAEHOSTUNREACH: number; + export var WSAENOTEMPTY: number; + export var WSAEPROCLIM: number; + export var WSAEUSERS: number; + export var WSAEDQUOT: number; + export var WSAESTALE: number; + export var WSAEREMOTE: number; + export var WSASYSNOTREADY: number; + export var WSAVERNOTSUPPORTED: number; + export var WSANOTINITIALISED: number; + export var WSAEDISCON: number; + export var WSAENOMORE: number; + export var WSAECANCELLED: number; + export var WSAEINVALIDPROCTABLE: number; + export var WSAEINVALIDPROVIDER: number; + export var WSAEPROVIDERFAILEDINIT: number; + export var WSASYSCALLFAILURE: number; + export var WSASERVICE_NOT_FOUND: number; + export var WSATYPE_NOT_FOUND: number; + export var WSA_E_NO_MORE: number; + export var WSA_E_CANCELLED: number; + export var WSAEREFUSED: number; + export var SIGHUP: number; + export var SIGINT: number; + export var SIGILL: number; + export var SIGABRT: number; + export var SIGFPE: number; + export var SIGKILL: number; + export var SIGSEGV: number; + export var SIGTERM: number; + export var SIGBREAK: number; + export var SIGWINCH: number; + export var SSL_OP_ALL: number; + export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; + export var SSL_OP_CISCO_ANYCONNECT: number; + export var SSL_OP_COOKIE_EXCHANGE: number; + export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + export var SSL_OP_EPHEMERAL_RSA: number; + export var SSL_OP_LEGACY_SERVER_CONNECT: number; + export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; + export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + export var SSL_OP_NETSCAPE_CA_DN_BUG: number; + export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NO_COMPRESSION: number; + export var SSL_OP_NO_QUERY_MTU: number; + export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + export var SSL_OP_NO_SSLv2: number; + export var SSL_OP_NO_SSLv3: number; + export var SSL_OP_NO_TICKET: number; + export var SSL_OP_NO_TLSv1: number; + export var SSL_OP_NO_TLSv1_1: number; + export var SSL_OP_NO_TLSv1_2: number; + export var SSL_OP_PKCS1_CHECK_1: number; + export var SSL_OP_PKCS1_CHECK_2: number; + export var SSL_OP_SINGLE_DH_USE: number; + export var SSL_OP_SINGLE_ECDH_USE: number; + export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; + export var SSL_OP_TLS_D5_BUG: number; + export var SSL_OP_TLS_ROLLBACK_BUG: number; + export var ENGINE_METHOD_DSA: number; + export var ENGINE_METHOD_DH: number; + export var ENGINE_METHOD_RAND: number; + export var ENGINE_METHOD_ECDH: number; + export var ENGINE_METHOD_ECDSA: number; + export var ENGINE_METHOD_CIPHERS: number; + export var ENGINE_METHOD_DIGESTS: number; + export var ENGINE_METHOD_STORE: number; + export var ENGINE_METHOD_PKEY_METHS: number; + export var ENGINE_METHOD_PKEY_ASN1_METHS: number; + export var ENGINE_METHOD_ALL: number; + export var ENGINE_METHOD_NONE: number; + export var DH_CHECK_P_NOT_SAFE_PRIME: number; + export var DH_CHECK_P_NOT_PRIME: number; + export var DH_UNABLE_TO_CHECK_GENERATOR: number; + export var DH_NOT_SUITABLE_GENERATOR: number; + export var NPN_ENABLED: number; + export var RSA_PKCS1_PADDING: number; + export var RSA_SSLV23_PADDING: number; + export var RSA_NO_PADDING: number; + export var RSA_PKCS1_OAEP_PADDING: number; + export var RSA_X931_PADDING: number; + export var RSA_PKCS1_PSS_PADDING: number; + export var POINT_CONVERSION_COMPRESSED: number; + export var POINT_CONVERSION_UNCOMPRESSED: number; + export var POINT_CONVERSION_HYBRID: number; + export var O_RDONLY: number; + export var O_WRONLY: number; + export var O_RDWR: number; + export var S_IFMT: number; + export var S_IFREG: number; + export var S_IFDIR: number; + export var S_IFCHR: number; + export var S_IFBLK: number; + export var S_IFIFO: number; + export var S_IFSOCK: number; + export var S_IRWXU: number; + export var S_IRUSR: number; + export var S_IWUSR: number; + export var S_IXUSR: number; + export var S_IRWXG: number; + export var S_IRGRP: number; + export var S_IWGRP: number; + export var S_IXGRP: number; + export var S_IRWXO: number; + export var S_IROTH: number; + export var S_IWOTH: number; + export var S_IXOTH: number; + export var S_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: number; + export var O_NOCTTY: number; + export var O_DIRECTORY: number; + export var O_NOATIME: number; + export var O_NOFOLLOW: number; + export var O_SYNC: number; + export var O_DSYNC: number; + export var O_SYMLINK: number; + export var O_DIRECT: number; + export var O_NONBLOCK: number; + export var O_TRUNC: number; + export var O_APPEND: number; + export var F_OK: number; + export var R_OK: number; + export var W_OK: number; + export var X_OK: number; + export var COPYFILE_EXCL: number; + export var COPYFILE_FICLONE: number; + export var COPYFILE_FICLONE_FORCE: number; + export var UV_UDP_REUSEADDR: number; + export var SIGQUIT: number; + export var SIGTRAP: number; + export var SIGIOT: number; + export var SIGBUS: number; + export var SIGUSR1: number; + export var SIGUSR2: number; + export var SIGPIPE: number; + export var SIGALRM: number; + export var SIGCHLD: number; + export var SIGSTKFLT: number; + export var SIGCONT: number; + export var SIGSTOP: number; + export var SIGTSTP: number; + export var SIGTTIN: number; + export var SIGTTOU: number; + export var SIGURG: number; + export var SIGXCPU: number; + export var SIGXFSZ: number; + export var SIGVTALRM: number; + export var SIGPROF: number; + export var SIGIO: number; + export var SIGPOLL: number; + export var SIGPWR: number; + export var SIGSYS: number; + export var SIGUNUSED: number; + export var defaultCoreCipherList: string; + export var defaultCipherList: string; + export var ENGINE_METHOD_RSA: number; + export var ALPN_ENABLED: number; +} + +declare module "module" { + export = NodeJS.Module; +} + +declare module "process" { + export = process; +} + +declare module "v8" { + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + } + + export function getHeapStatistics(): HeapInfo; + export function getHeapSpaceStatistics(): HeapSpaceInfo[]; + export function setFlagsFromString(flags: string): void; +} + +declare module "timers" { + export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export namespace setTimeout { + export function __promisify__(ms: number): Promise; + export function __promisify__(ms: number, value: T): Promise; + } + export function clearTimeout(timeoutId: NodeJS.Timer): void; + export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function clearInterval(intervalId: NodeJS.Timer): void; + export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; + export namespace setImmediate { + export function __promisify__(): Promise; + export function __promisify__(value: T): Promise; + } + export function clearImmediate(immediateId: any): void; +} + +declare module "console" { + export = console; +} + +/** + * Async Hooks module: https://nodejs.org/api/async_hooks.html + */ +declare module "async_hooks" { + /** + * Returns the asyncId of the current execution context. + */ + export function executionAsyncId(): number; + + /** + * Returns the ID of the resource responsible for calling the callback that is currently being executed. + */ + export function triggerAsyncId(): number; + + export interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: Object): void; + + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + + export interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + + /** + * Registers functions to be called for different lifetime events of each async operation. + * @param options the callbacks to register + * @return an AsyncHooks instance used for disabling and enabling hooks + */ + export function createHook(options: HookCallbacks): AsyncHook; + + export interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * Default: `executionAsyncId()` + */ + triggerAsyncId?: number; + + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * Default: `false` + */ + requireManualDestroy?: boolean; + } + + /** + * The class AsyncResource was designed to be extended by the embedder's async resources. + * Using this users can easily trigger the lifetime events of their own resources. + */ + export class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since 9.3) + */ + constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions); + + /** + * Call AsyncHooks before callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitBefore(): void; + + /** + * Call AsyncHooks after callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitAfter(): void; + + /** + * Call the provided function with the provided arguments in the + * execution context of the async resource. This will establish the + * context, trigger the AsyncHooks before callbacks, call the function, + * trigger the AsyncHooks after callbacks, and then restore the original + * execution context. + * @param fn The function to call in the execution context of this + * async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + + /** + * Call AsyncHooks destroy callbacks. + */ + emitDestroy(): void; + + /** + * @return the unique ID assigned to this AsyncResource instance. + */ + asyncId(): number; + + /** + * @return the trigger ID for this AsyncResource instance. + */ + triggerAsyncId(): number; + } +} + +declare module "http2" { + import * as events from "events"; + import * as fs from "fs"; + import * as net from "net"; + import * as stream from "stream"; + import * as tls from "tls"; + import * as url from "url"; + + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders } from "http"; + export { OutgoingHttpHeaders } from "http"; + + export interface IncomingHttpStatusHeader { + ":status"?: number; + } + + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string; + ":method"?: string; + ":authority"?: string; + ":scheme"?: string; + } + + // Http2Stream + + export interface StreamPriorityOptions { + exclusive?: boolean; + parent?: number; + weight?: number; + silent?: boolean; + } + + export interface StreamState { + localWindowSize?: number; + state?: number; + streamLocalClose?: number; + streamRemoteClose?: number; + sumDependencyWeight?: number; + weight?: number; + } + + export interface ServerStreamResponseOptions { + endStream?: boolean; + getTrailers?: (trailers: OutgoingHttpHeaders) => void; + } + + export interface StatOptions { + offset: number; + length: number; + } + + export interface ServerStreamFileResponseOptions { + statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean; + getTrailers?: (trailers: OutgoingHttpHeaders) => void; + offset?: number; + length?: number; + } + + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?: (err: NodeJS.ErrnoException) => void; + } + + export interface Http2Stream extends stream.Duplex { + readonly aborted: boolean; + close(code?: number, callback?: () => void): void; + readonly closed: boolean; + readonly destroyed: boolean; + readonly pending: boolean; + priority(options: StreamPriorityOptions): void; + readonly rstCode: number; + readonly session: Http2Session; + setTimeout(msecs: number, callback?: () => void): void; + readonly state: StreamState; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + } + + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + } + + export interface ServerHttp2Stream extends Http2Stream { + additionalHeaders(headers: OutgoingHttpHeaders): void; + readonly headersSent: boolean; + readonly pushAllowed: boolean; + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + respondWithFD(fd: number, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + + // Http2Session + + export interface Settings { + headerTableSize?: number; + enablePush?: boolean; + initialWindowSize?: number; + maxFrameSize?: number; + maxConcurrentStreams?: number; + maxHeaderListSize?: number; + } + + export interface ClientSessionRequestOptions { + endStream?: boolean; + exclusive?: boolean; + parent?: number; + weight?: number; + getTrailers?: (trailers: OutgoingHttpHeaders, flags: number) => void; + } + + export interface SessionState { + effectiveLocalWindowSize?: number; + effectiveRecvDataLength?: number; + nextStreamID?: number; + localWindowSize?: number; + lastProcStreamID?: number; + remoteWindowSize?: number; + outboundQueueSize?: number; + deflateDynamicTableSize?: number; + inflateDynamicTableSize?: number; + } + + export interface Http2Session extends events.EventEmitter { + readonly alpnProtocol?: string; + close(callback?: () => void): void; + readonly closed: boolean; + readonly connecting: boolean; + destroy(error?: Error, code?: number): void; + readonly destroyed: boolean; + readonly encrypted?: boolean; + goaway(code?: number, lastStreamID?: number, opaqueData?: Buffer | DataView | NodeJS.TypedArray): void; + readonly localSettings: Settings; + readonly originSet?: string[]; + readonly pendingSettingsAck: boolean; + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: Buffer | DataView | NodeJS.TypedArray , callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ref(): void; + readonly remoteSettings: Settings; + rstStream(stream: Http2Stream, code?: number): void; + setTimeout(msecs: number, callback?: () => void): void; + readonly socket: net.Socket | tls.TLSSocket; + readonly state: SessionState; + priority(stream: Http2Stream, options: StreamPriorityOptions): void; + settings(settings: Settings): void; + readonly type: number; + unref(): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + export interface ClientHttp2Session extends Http2Session { + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + } + + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + + export interface ServerHttp2Session extends Http2Session { + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + readonly server: Http2Server | Http2SecureServer; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + } + + // Http2Server + + export interface SessionOptions { + maxDeflateDynamicTableSize?: number; + maxReservedRemoteStreams?: number; + maxSendHeaderBlockLength?: number; + paddingStrategy?: number; + peerMaxConcurrentStreams?: number; + selectPadding?: (frameLen: number, maxFrameLen: number) => number; + settings?: Settings; + } + + export type ClientSessionOptions = SessionOptions; + export type ServerSessionOptions = SessionOptions; + + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } + + export interface ServerOptions extends ServerSessionOptions { + allowHTTP1?: boolean; + } + + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean; + } + + export interface Http2Server extends net.Server { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + export interface Http2SecureServer extends tls.Server { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + } + + export interface Http2ServerRequest extends stream.Readable { + headers: IncomingHttpHeaders; + httpVersion: string; + method: string; + rawHeaders: string[]; + rawTrailers: string[]; + setTimeout(msecs: number, callback?: () => void): void; + socket: net.Socket | tls.TLSSocket; + stream: ServerHttp2Stream; + trailers: IncomingHttpHeaders; + url: string; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted", hadError: boolean, code: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + } + + export interface Http2ServerResponse extends events.EventEmitter { + addTrailers(trailers: OutgoingHttpHeaders): void; + connection: net.Socket | tls.TLSSocket; + end(callback?: () => void): void; + end(data?: string | Buffer, callback?: () => void): void; + end(data?: string | Buffer, encoding?: string, callback?: () => void): void; + readonly finished: boolean; + getHeader(name: string): string; + getHeaderNames(): string[]; + getHeaders(): OutgoingHttpHeaders; + hasHeader(name: string): boolean; + readonly headersSent: boolean; + removeHeader(name: string): void; + sendDate: boolean; + setHeader(name: string, value: number | string | string[]): void; + setTimeout(msecs: number, callback?: () => void): void; + socket: net.Socket | tls.TLSSocket; + statusCode: number; + statusMessage: ''; + stream: ServerHttp2Stream; + write(chunk: string | Buffer, callback?: (err: Error) => void): boolean; + write(chunk: string | Buffer, encoding?: string, callback?: (err: Error) => void): boolean; + writeContinue(): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): void; + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + } + + // Public API + + export namespace constants { + export const NGHTTP2_SESSION_SERVER: number; + export const NGHTTP2_SESSION_CLIENT: number; + export const NGHTTP2_STREAM_STATE_IDLE: number; + export const NGHTTP2_STREAM_STATE_OPEN: number; + export const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + export const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + export const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + export const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + export const NGHTTP2_STREAM_STATE_CLOSED: number; + export const NGHTTP2_NO_ERROR: number; + export const NGHTTP2_PROTOCOL_ERROR: number; + export const NGHTTP2_INTERNAL_ERROR: number; + export const NGHTTP2_FLOW_CONTROL_ERROR: number; + export const NGHTTP2_SETTINGS_TIMEOUT: number; + export const NGHTTP2_STREAM_CLOSED: number; + export const NGHTTP2_FRAME_SIZE_ERROR: number; + export const NGHTTP2_REFUSED_STREAM: number; + export const NGHTTP2_CANCEL: number; + export const NGHTTP2_COMPRESSION_ERROR: number; + export const NGHTTP2_CONNECT_ERROR: number; + export const NGHTTP2_ENHANCE_YOUR_CALM: number; + export const NGHTTP2_INADEQUATE_SECURITY: number; + export const NGHTTP2_HTTP_1_1_REQUIRED: number; + export const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + export const NGHTTP2_FLAG_NONE: number; + export const NGHTTP2_FLAG_END_STREAM: number; + export const NGHTTP2_FLAG_END_HEADERS: number; + export const NGHTTP2_FLAG_ACK: number; + export const NGHTTP2_FLAG_PADDED: number; + export const NGHTTP2_FLAG_PRIORITY: number; + export const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + export const DEFAULT_SETTINGS_ENABLE_PUSH: number; + export const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + export const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + export const MAX_MAX_FRAME_SIZE: number; + export const MIN_MAX_FRAME_SIZE: number; + export const MAX_INITIAL_WINDOW_SIZE: number; + export const NGHTTP2_DEFAULT_WEIGHT: number; + export const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + export const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + export const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + export const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + export const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + export const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + export const PADDING_STRATEGY_NONE: number; + export const PADDING_STRATEGY_MAX: number; + export const PADDING_STRATEGY_CALLBACK: number; + export const HTTP2_HEADER_STATUS: string; + export const HTTP2_HEADER_METHOD: string; + export const HTTP2_HEADER_AUTHORITY: string; + export const HTTP2_HEADER_SCHEME: string; + export const HTTP2_HEADER_PATH: string; + export const HTTP2_HEADER_ACCEPT_CHARSET: string; + export const HTTP2_HEADER_ACCEPT_ENCODING: string; + export const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + export const HTTP2_HEADER_ACCEPT_RANGES: string; + export const HTTP2_HEADER_ACCEPT: string; + export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + export const HTTP2_HEADER_AGE: string; + export const HTTP2_HEADER_ALLOW: string; + export const HTTP2_HEADER_AUTHORIZATION: string; + export const HTTP2_HEADER_CACHE_CONTROL: string; + export const HTTP2_HEADER_CONNECTION: string; + export const HTTP2_HEADER_CONTENT_DISPOSITION: string; + export const HTTP2_HEADER_CONTENT_ENCODING: string; + export const HTTP2_HEADER_CONTENT_LANGUAGE: string; + export const HTTP2_HEADER_CONTENT_LENGTH: string; + export const HTTP2_HEADER_CONTENT_LOCATION: string; + export const HTTP2_HEADER_CONTENT_MD5: string; + export const HTTP2_HEADER_CONTENT_RANGE: string; + export const HTTP2_HEADER_CONTENT_TYPE: string; + export const HTTP2_HEADER_COOKIE: string; + export const HTTP2_HEADER_DATE: string; + export const HTTP2_HEADER_ETAG: string; + export const HTTP2_HEADER_EXPECT: string; + export const HTTP2_HEADER_EXPIRES: string; + export const HTTP2_HEADER_FROM: string; + export const HTTP2_HEADER_HOST: string; + export const HTTP2_HEADER_IF_MATCH: string; + export const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + export const HTTP2_HEADER_IF_NONE_MATCH: string; + export const HTTP2_HEADER_IF_RANGE: string; + export const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + export const HTTP2_HEADER_LAST_MODIFIED: string; + export const HTTP2_HEADER_LINK: string; + export const HTTP2_HEADER_LOCATION: string; + export const HTTP2_HEADER_MAX_FORWARDS: string; + export const HTTP2_HEADER_PREFER: string; + export const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + export const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + export const HTTP2_HEADER_RANGE: string; + export const HTTP2_HEADER_REFERER: string; + export const HTTP2_HEADER_REFRESH: string; + export const HTTP2_HEADER_RETRY_AFTER: string; + export const HTTP2_HEADER_SERVER: string; + export const HTTP2_HEADER_SET_COOKIE: string; + export const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + export const HTTP2_HEADER_TRANSFER_ENCODING: string; + export const HTTP2_HEADER_TE: string; + export const HTTP2_HEADER_UPGRADE: string; + export const HTTP2_HEADER_USER_AGENT: string; + export const HTTP2_HEADER_VARY: string; + export const HTTP2_HEADER_VIA: string; + export const HTTP2_HEADER_WWW_AUTHENTICATE: string; + export const HTTP2_HEADER_HTTP2_SETTINGS: string; + export const HTTP2_HEADER_KEEP_ALIVE: string; + export const HTTP2_HEADER_PROXY_CONNECTION: string; + export const HTTP2_METHOD_ACL: string; + export const HTTP2_METHOD_BASELINE_CONTROL: string; + export const HTTP2_METHOD_BIND: string; + export const HTTP2_METHOD_CHECKIN: string; + export const HTTP2_METHOD_CHECKOUT: string; + export const HTTP2_METHOD_CONNECT: string; + export const HTTP2_METHOD_COPY: string; + export const HTTP2_METHOD_DELETE: string; + export const HTTP2_METHOD_GET: string; + export const HTTP2_METHOD_HEAD: string; + export const HTTP2_METHOD_LABEL: string; + export const HTTP2_METHOD_LINK: string; + export const HTTP2_METHOD_LOCK: string; + export const HTTP2_METHOD_MERGE: string; + export const HTTP2_METHOD_MKACTIVITY: string; + export const HTTP2_METHOD_MKCALENDAR: string; + export const HTTP2_METHOD_MKCOL: string; + export const HTTP2_METHOD_MKREDIRECTREF: string; + export const HTTP2_METHOD_MKWORKSPACE: string; + export const HTTP2_METHOD_MOVE: string; + export const HTTP2_METHOD_OPTIONS: string; + export const HTTP2_METHOD_ORDERPATCH: string; + export const HTTP2_METHOD_PATCH: string; + export const HTTP2_METHOD_POST: string; + export const HTTP2_METHOD_PRI: string; + export const HTTP2_METHOD_PROPFIND: string; + export const HTTP2_METHOD_PROPPATCH: string; + export const HTTP2_METHOD_PUT: string; + export const HTTP2_METHOD_REBIND: string; + export const HTTP2_METHOD_REPORT: string; + export const HTTP2_METHOD_SEARCH: string; + export const HTTP2_METHOD_TRACE: string; + export const HTTP2_METHOD_UNBIND: string; + export const HTTP2_METHOD_UNCHECKOUT: string; + export const HTTP2_METHOD_UNLINK: string; + export const HTTP2_METHOD_UNLOCK: string; + export const HTTP2_METHOD_UPDATE: string; + export const HTTP2_METHOD_UPDATEREDIRECTREF: string; + export const HTTP2_METHOD_VERSION_CONTROL: string; + export const HTTP_STATUS_CONTINUE: number; + export const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + export const HTTP_STATUS_PROCESSING: number; + export const HTTP_STATUS_OK: number; + export const HTTP_STATUS_CREATED: number; + export const HTTP_STATUS_ACCEPTED: number; + export const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + export const HTTP_STATUS_NO_CONTENT: number; + export const HTTP_STATUS_RESET_CONTENT: number; + export const HTTP_STATUS_PARTIAL_CONTENT: number; + export const HTTP_STATUS_MULTI_STATUS: number; + export const HTTP_STATUS_ALREADY_REPORTED: number; + export const HTTP_STATUS_IM_USED: number; + export const HTTP_STATUS_MULTIPLE_CHOICES: number; + export const HTTP_STATUS_MOVED_PERMANENTLY: number; + export const HTTP_STATUS_FOUND: number; + export const HTTP_STATUS_SEE_OTHER: number; + export const HTTP_STATUS_NOT_MODIFIED: number; + export const HTTP_STATUS_USE_PROXY: number; + export const HTTP_STATUS_TEMPORARY_REDIRECT: number; + export const HTTP_STATUS_PERMANENT_REDIRECT: number; + export const HTTP_STATUS_BAD_REQUEST: number; + export const HTTP_STATUS_UNAUTHORIZED: number; + export const HTTP_STATUS_PAYMENT_REQUIRED: number; + export const HTTP_STATUS_FORBIDDEN: number; + export const HTTP_STATUS_NOT_FOUND: number; + export const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + export const HTTP_STATUS_NOT_ACCEPTABLE: number; + export const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + export const HTTP_STATUS_REQUEST_TIMEOUT: number; + export const HTTP_STATUS_CONFLICT: number; + export const HTTP_STATUS_GONE: number; + export const HTTP_STATUS_LENGTH_REQUIRED: number; + export const HTTP_STATUS_PRECONDITION_FAILED: number; + export const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + export const HTTP_STATUS_URI_TOO_LONG: number; + export const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + export const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + export const HTTP_STATUS_EXPECTATION_FAILED: number; + export const HTTP_STATUS_TEAPOT: number; + export const HTTP_STATUS_MISDIRECTED_REQUEST: number; + export const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + export const HTTP_STATUS_LOCKED: number; + export const HTTP_STATUS_FAILED_DEPENDENCY: number; + export const HTTP_STATUS_UNORDERED_COLLECTION: number; + export const HTTP_STATUS_UPGRADE_REQUIRED: number; + export const HTTP_STATUS_PRECONDITION_REQUIRED: number; + export const HTTP_STATUS_TOO_MANY_REQUESTS: number; + export const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + export const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + export const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + export const HTTP_STATUS_NOT_IMPLEMENTED: number; + export const HTTP_STATUS_BAD_GATEWAY: number; + export const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + export const HTTP_STATUS_GATEWAY_TIMEOUT: number; + export const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + export const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + export const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + export const HTTP_STATUS_LOOP_DETECTED: number; + export const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + export const HTTP_STATUS_NOT_EXTENDED: number; + export const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + + export function getDefaultSettings(): Settings; + export function getPackedSettings(settings: Settings): Settings; + export function getUnpackedSettings(buf: Buffer | Uint8Array): Settings; + + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + + export function connect(authority: string | url.URL, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect(authority: string | url.URL, options?: ClientSessionOptions | SecureClientSessionOptions, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; +} + +declare module "perf_hooks" { + import { AsyncResource } from "async_hooks"; + + export interface PerformanceEntry { + /** + * The total number of milliseconds elapsed for this entry. + * This value will not be meaningful for all Performance Entry types. + */ + readonly duration: number; + + /** + * The name of the performance entry. + */ + readonly name: string; + + /** + * The high resolution millisecond timestamp marking the starting time of the Performance Entry. + */ + readonly startTime: number; + + /** + * The type of the performance entry. + * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. + */ + readonly entryType: string; + + /** + * When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies + * the type of garbage collection operation that occurred. + * The value may be one of perf_hooks.constants. + */ + readonly kind?: number; + } + + export interface PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. + */ + readonly bootstrapComplete: number; + + /** + * The high resolution millisecond timestamp at which cluster processing ended. + */ + readonly clusterSetupEnd: number; + + /** + * The high resolution millisecond timestamp at which cluster processing started. + */ + readonly clusterSetupStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop exited. + */ + readonly loopExit: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop started. + */ + readonly loopStart: number; + + /** + * The high resolution millisecond timestamp at which main module load ended. + */ + readonly moduleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which main module load started. + */ + readonly moduleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + */ + readonly nodeStart: number; + + /** + * The high resolution millisecond timestamp at which preload module load ended. + */ + readonly preloadModuleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which preload module load started. + */ + readonly preloadModuleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing ended. + */ + readonly thirdPartyMainEnd: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing started. + */ + readonly thirdPartyMainStart: number; + + /** + * The high resolution millisecond timestamp at which the V8 platform was initialized. + */ + readonly v8Start: number; + } + + export interface Performance { + /** + * If name is not provided, removes all PerformanceFunction objects from the Performance Timeline. + * If name is provided, removes entries with name. + * @param name + */ + clearFunctions(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only objects whose performanceEntry.name matches name. + */ + clearMeasures(name?: string): void; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + * @return list of all PerformanceEntry objects + */ + getEntries(): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + * @param name + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByType(type: string): PerformanceEntry[]; + + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string): void; + + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark: string, endMark: string): void; + + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T): T; + } + + export interface PerformanceObserverEntryList { + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + */ + getEntries(): PerformanceEntry[]; + + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + */ + getEntriesByType(type: string): PerformanceEntry[]; + } + + export type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + + export class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + + /** + * Disconnects the PerformanceObserver instance from all notifications. + */ + disconnect(): void; + + /** + * Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. + * When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. + * Property buffered defaults to false. + * @param options + */ + observe(options: { entryTypes: string[], buffered?: boolean }): void; + } + + export namespace constants { + export const NODE_PERFORMANCE_GC_MAJOR: number; + export const NODE_PERFORMANCE_GC_MINOR: number; + export const NODE_PERFORMANCE_GC_INCREMENTAL: number; + export const NODE_PERFORMANCE_GC_WEAKCB: number; + } + + const performance: Performance; +} diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..d9d3dad --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2832 @@ +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module "inspector" { + import { EventEmitter } from 'events'; + + export interface InspectorNotification { + method: string; + params: T; + } + + export namespace Console { + /** + * Console message. + */ + export interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number; + } + + export interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: Console.ConsoleMessage; + } + } + + export namespace Debugger { + /** + * Breakpoint identifier. + */ + export type BreakpointId = string; + + /** + * Call frame identifier. + */ + export type CallFrameId = string; + + /** + * Location in the source code. + */ + export interface Location { + /** + * Script identifier as reported in the `Debugger.scriptParsed`. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + } + + /** + * Location in the source code. + * @experimental + */ + export interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + export interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: Debugger.CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Debugger.Location; + /** + * Location in the source code. + */ + location: Debugger.Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Debugger.Scope[]; + /** + * `this` object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject; + } + + /** + * Scope description. + */ + export interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For `global` and `with` scopes it represents the actual +object; for the rest of the scopes, it is artificial transient object enumerating scope +variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string; + /** + * Location in the source code where scope starts + */ + startLocation?: Debugger.Location; + /** + * Location in the source code where scope ends + */ + endLocation?: Debugger.Location; + } + + /** + * Search match for resource. + */ + export interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + + export interface BreakLocation { + /** + * Script identifier as reported in the `Debugger.scriptParsed`. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + type?: string; + } + + export interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Debugger.Location; + targetCallFrames?: string; + } + + export interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: Debugger.CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles +using `releaseObjectGroup`). + */ + objectGroup?: string; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults +to false. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause +execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean; + } + + export interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Debugger.Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end +of scripts is used as end of range. + */ + end?: Debugger.Location; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean; + } + + export interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + + export interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + + export interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + + export interface RemoveBreakpointParameterType { + breakpointId: Debugger.BreakpointId; + } + + export interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: Debugger.CallFrameId; + } + + export interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean; + } + + export interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async +call stacks (default). + */ + maxDepth: number; + } + + export interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + + export interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: Debugger.ScriptPosition[]; + } + + export interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Debugger.Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the +breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + export interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either `url` or +`urlRegex` must be specified. + */ + urlRegex?: string; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the +breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + export interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + + export interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + + export interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + + export interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result +description without actually modifying the code. + */ + dryRun?: boolean; + } + + export interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + + export interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' +scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: Debugger.CallFrameId; + } + + export interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled +before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean; + } + + export interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + + export interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: Debugger.BreakLocation[]; + } + + export interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + + export interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + + export interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: Debugger.CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + } + + export interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: Debugger.SearchMatch[]; + } + + export interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: Debugger.BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Debugger.Location; + } + + export interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: Debugger.BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Debugger.Location[]; + } + + export interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: Debugger.CallFrame[]; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: Debugger.BreakpointId; + /** + * Actual breakpoint location. + */ + location: Debugger.Location; + } + + export interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: Debugger.CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {}; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. +This field is available only after `Debugger.stepInto` call with `breakOnAsynCall` flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId; + } + + export interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + + export interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + } + + export namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + export type HeapSnapshotObjectId = string; + + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + export interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: HeapProfiler.SamplingHeapProfileNode[]; + } + + /** + * Profile. + */ + export interface SamplingHeapProfile { + head: HeapProfiler.SamplingHeapProfileNode; + } + + export interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapProfiler.HeapSnapshotObjectId; + } + + export interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + + export interface GetObjectByHeapObjectIdParameterType { + objectId: HeapProfiler.HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + } + + export interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The +default value is 32768 bytes. + */ + samplingInterval?: number; + } + + export interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean; + } + + export interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken +when the tracking is stopped. + */ + reportProgress?: boolean; + } + + export interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean; + } + + export interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapProfiler.HeapSnapshotObjectId; + } + + export interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + + export interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: HeapProfiler.SamplingHeapProfile; + } + + export interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: HeapProfiler.SamplingHeapProfile; + } + + export interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + + export interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment +index, the second integer is a total count of objects for the fragment, the third integer is +a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + + export interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + + export interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean; + } + } + + export namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + export interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number; + /** + * Child node ids. + */ + children?: number[]; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't +optimize. + */ + deoptReason?: string; + /** + * An array of source position ticks. + */ + positionTicks?: Profiler.PositionTickInfo[]; + } + + /** + * Profile. + */ + export interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: Profiler.ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[]; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the +profile startTime. + */ + timeDeltas?: number[]; + } + + /** + * Specifies a number of samples attributed to a certain source position. + */ + export interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + + /** + * Coverage data for a source range. + */ + export interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + + /** + * Coverage data for a JavaScript function. + */ + export interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: Profiler.CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + + /** + * Coverage data for a JavaScript script. + */ + export interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: Profiler.FunctionCoverage[]; + } + + /** + * Describes a type collected during runtime. + * @experimental + */ + export interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + export interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: Profiler.TypeObject[]; + } + + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + export interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: Profiler.TypeProfileEntry[]; + } + + export interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + + export interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean; + /** + * Collect block-based coverage. + */ + detailed?: boolean; + } + + export interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: Profiler.ScriptCoverage[]; + } + + export interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profiler.Profile; + } + + export interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: Profiler.ScriptCoverage[]; + } + + export interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: Profiler.ScriptTypeProfile[]; + } + + export interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profiler.Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + + export interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + } + + export namespace Runtime { + /** + * Unique script identifier. + */ + export type ScriptId = string; + + /** + * Unique object identifier. + */ + export type RemoteObjectId = string; + + /** + * Primitive value which cannot be JSON-stringified. Includes values `-0`, `NaN`, `Infinity`, +`-Infinity`, and bigint literals. + */ + export type UnserializableValue = string; + + /** + * Mirror object referencing original JavaScript object. + */ + export interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + /** + * Object class (constructor) name. Specified for `object` type values only. + */ + className?: string; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have `value`, but gets this +property. + */ + unserializableValue?: Runtime.UnserializableValue; + /** + * String representation of the object. + */ + description?: string; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: Runtime.RemoteObjectId; + /** + * Preview containing abbreviated property values. Specified for `object` type values only. + * @experimental + */ + preview?: Runtime.ObjectPreview; + /** + * @experimental + */ + customPreview?: Runtime.CustomPreview; + } + + /** + * @experimental + */ + export interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: Runtime.RemoteObjectId; + bindRemoteObjectFunctionId: Runtime.RemoteObjectId; + configObjectId?: Runtime.RemoteObjectId; + } + + /** + * Object containing abbreviated remote object value. + * @experimental + */ + export interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + /** + * String representation of the object. + */ + description?: string; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: Runtime.PropertyPreview[]; + /** + * List of the entries. Specified for `map` and `set` subtype values only. + */ + entries?: Runtime.EntryPreview[]; + } + + /** + * @experimental + */ + export interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string; + /** + * Nested value preview. + */ + valuePreview?: Runtime.ObjectPreview; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + } + + /** + * @experimental + */ + export interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: Runtime.ObjectPreview; + /** + * Preview of the value. + */ + value: Runtime.ObjectPreview; + } + + /** + * Object property descriptor. + */ + export interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: Runtime.RemoteObject; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean; + /** + * A function which serves as a getter for the property, or `undefined` if there is no getter +(accessor descriptors only). + */ + get?: Runtime.RemoteObject; + /** + * A function which serves as a setter for the property, or `undefined` if there is no setter +(accessor descriptors only). + */ + set?: Runtime.RemoteObject; + /** + * True if the type of this property descriptor may be changed and if the property may be +deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding +object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean; + /** + * Property symbol object, if the property is of the `symbol` type. + */ + symbol?: Runtime.RemoteObject; + } + + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + export interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: Runtime.RemoteObject; + } + + /** + * Represents function call argument. Either remote object id `objectId`, primitive `value`, +unserializable primitive value or neither of (for undefined) them should be specified. + */ + export interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: Runtime.UnserializableValue; + /** + * Remote object handle. + */ + objectId?: Runtime.RemoteObjectId; + } + + /** + * Id of an execution context. + */ + export type ExecutionContextId = number; + + /** + * Description of an isolated world. + */ + export interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context +script evaluation should be performed. + */ + id: Runtime.ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {}; + } + + /** + * Detailed information about exception (or error) that was thrown during script compilation or +execution. + */ + export interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: Runtime.ScriptId; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string; + /** + * JavaScript stack trace if available. + */ + stackTrace?: Runtime.StackTrace; + /** + * Exception object if available. + */ + exception?: Runtime.RemoteObject; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: Runtime.ExecutionContextId; + } + + /** + * Number of milliseconds since epoch. + */ + export type Timestamp = number; + + /** + * Stack entry for runtime errors and assertions. + */ + export interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + + /** + * Call frames for assertions or error messages. + */ + export interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that +initiated the async call. + */ + description?: string; + /** + * JavaScript function name. + */ + callFrames: Runtime.CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: Runtime.StackTrace; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: Runtime.StackTraceId; + } + + /** + * Unique identifier of current debugger. + * @experimental + */ + export type UniqueDebuggerId = string; + + /** + * If `debuggerId` is set stack trace comes from another debugger and can be resolved there. This +allows to track cross-debugger calls. See `Runtime.StackTrace` and `Debugger.paused` for usages. + * @experimental + */ + export interface StackTraceId { + id: string; + debuggerId?: Runtime.UniqueDebuggerId; + } + + export interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: Runtime.RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + } + + export interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should +be specified. + */ + objectId?: Runtime.RemoteObjectId; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target +object. + */ + arguments?: Runtime.CallArgument[]; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause +execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is +resolved. + */ + awaitPromise?: boolean; + /** + * Specifies execution context which global object will be used to call function on. Either +executionContextId or objectId should be specified. + */ + executionContextId?: Runtime.ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not +specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string; + } + + export interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the +evaluation will be performed in the context of the inspected page. + */ + executionContextId?: Runtime.ExecutionContextId; + } + + export interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause +execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the +evaluation will be performed in the context of the inspected page. + */ + contextId?: Runtime.ExecutionContextId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is +resolved. + */ + awaitPromise?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + * @experimental + */ + throwOnSideEffect?: boolean; + } + + export interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: Runtime.RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype +chain. + */ + ownProperties?: boolean; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not +returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean; + } + + export interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: Runtime.ExecutionContextId; + } + + export interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: Runtime.RemoteObjectId; + /** + * Symbolic group name that can be used to release the results. + */ + objectGroup?: string; + } + + export interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: Runtime.RemoteObjectId; + } + + export interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + + export interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: Runtime.ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the +evaluation will be performed in the context of the inspected page. + */ + executionContextId?: Runtime.ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause +execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is +resolved. + */ + awaitPromise?: boolean; + } + + export interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + + export interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: Runtime.RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: Runtime.ScriptId; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface GetIsolateIdReturnType { + /** + * The isolate id. + */ + id: string; + } + + export interface GetHeapUsageReturnType { + /** + * Used heap size in bytes. + */ + usedSize: number; + /** + * Allocated heap size in bytes. + */ + totalSize: number; + } + + export interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: Runtime.PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: Runtime.InternalPropertyDescriptor[]; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + + export interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: Runtime.RemoteObject; + } + + export interface RunScriptReturnType { + /** + * Run result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: Runtime.RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Runtime.Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: Runtime.StackTrace; + /** + * Console context descriptor for calls on non-default console context (not console.*): +'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call +on named context. + * @experimental + */ + context?: string; + } + + export interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in `exceptionThrown`. + */ + exceptionId: number; + } + + export interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Runtime.Timestamp; + exceptionDetails: Runtime.ExceptionDetails; + } + + export interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: Runtime.ExecutionContextDescription; + } + + export interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: Runtime.ExecutionContextId; + } + + export interface InspectRequestedEventDataType { + object: Runtime.RemoteObject; + hints: {}; + } + } + + export namespace Schema { + /** + * Description of the protocol domain. + */ + export interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + + export interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Schema.Domain[]; + } + } + + /** + * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. + */ + export class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. An exception will be thrown if there is already a connected session established either through the API or by a front-end connected to the Inspector WebSocket port. + */ + connect(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. session.connect() will need to be called to be able to send messages again. Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. callback will be notified when a response is received. callback is a function that accepts two optional arguments - error and message-specific result. + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + + /** + * Enables console domain, sends the messages collected so far to the client by means of the +`messageAdded` notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been +enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be +the same. + */ + post(method: "Debugger.getPossibleBreakpoints", params?: Debugger.GetPossibleBreakpointsParameterType, callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + + /** + * Returns stack trace with given `stackTraceId`. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; + + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and +Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled +before next pause. Returns success when async task is actually scheduled, returns error if no +task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in +scripts with url matching one of the patterns. VM will try to leave blackboxed script by +performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted +scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. +Positions array contains positions where blackbox state is changed. First interval isn't +blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this +command is issued, all existing parsed scripts will have breakpoints resolved and returned in +`locations` property. Further matching script parsing will result in subsequent +`breakpointResolved` events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or +no exceptions. Initial pause on exceptions state is `none`. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; + + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be +mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details +$x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + + post(method: "HeapProfiler.getObjectByHeapObjectId", params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + + post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to +garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code +coverage may be incomplete. Enabling prevents running optimized code and resets execution +counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Enable type profile. + * @experimental + */ + post(method: "Profiler.startTypeProfile", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows +executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: "Profiler.stopTypeProfile", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code +coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + + /** + * Collect type profile. + * @experimental + */ + post(method: "Profiler.takeTypeProfile", callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + + /** + * Calls function with given declaration on the given object. Object group of the result is +inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + + /** + * Enables reporting of execution contexts creation by means of `executionContextCreated` event. +When the reporting gets enabled the event will be sent immediately for each existing execution +context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + + /** + * Returns the isolate id. + * @experimental + */ + post(method: "Runtime.getIsolateId", callback?: (err: Error | null, params: Runtime.GetIsolateIdReturnType) => void): void; + + /** + * Returns the JavaScript heap usage. +It is the total usage of the corresponding isolate not scoped to a particular Runtime. + * @experimental + */ + post(method: "Runtime.getHeapUsage", callback?: (err: Error | null, params: Runtime.GetHeapUsageReturnType) => void): void; + + /** + * Returns properties of a given object. Object group of the result is inherited from the target +object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + + /** + * Returns all let, const and class variables from global scope. + */ + post(method: "Runtime.globalLexicalScopeNames", params?: Runtime.GlobalLexicalScopeNamesParameterType, callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + + /** + * Terminate current or next JavaScript execution. +Will cancel the termination when the outer-most script execution ends. + * @experimental + */ + post(method: "Runtime.terminateExecution", callback?: (err: Error | null) => void): void; + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + + // Events + + addListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected +scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last +seen object id and corresponding timestamp. If the were changes in the heap since last event +then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API +call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected +scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last +seen object id and corresponding timestamp. If the were changes in the heap since last event +then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API +call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected +scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last +seen object id and corresponding timestamp. If the were changes in the heap since last event +then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API +call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected +scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last +seen object id and corresponding timestamp. If the were changes in the heap since last event +then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API +call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected +scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last +seen object id and corresponding timestamp. If the were changes in the heap since last event +then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API +call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + } + + // Top Level API + + /** + * Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programatically after node has started. + * If wait is true, will block until a client has connected to the inspect port and flow control has been passed to the debugger client. + * @param port Port to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Optional, defaults to false. + */ + export function open(port?: number, host?: string, wait?: boolean): void; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + export function close(): void; + + /** + * Return the URL of the active inspector, or undefined if there is none. + */ + export function url(): string; +} diff --git a/node_modules/@types/underscore/LICENSE b/node_modules/@types/underscore/LICENSE new file mode 100644 index 0000000..2107107 --- /dev/null +++ b/node_modules/@types/underscore/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/underscore/README.md b/node_modules/@types/underscore/README.md new file mode 100644 index 0000000..43ef05c --- /dev/null +++ b/node_modules/@types/underscore/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/underscore` + +# Summary +This package contains type definitions for Underscore (http://underscorejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/underscore + +Additional Details + * Last updated: Wed, 15 Aug 2018 20:42:04 GMT + * Dependencies: none + * Global values: _ + +# Credits +These definitions were written by Boris Yankov , Josh Baldwin , Christopher Currens , Cassey Lottman , Ard Timmerman . diff --git a/node_modules/@types/underscore/index.d.ts b/node_modules/@types/underscore/index.d.ts new file mode 100644 index 0000000..72498e3 --- /dev/null +++ b/node_modules/@types/underscore/index.d.ts @@ -0,0 +1,6106 @@ +// Type definitions for Underscore 1.8 +// Project: http://underscorejs.org/ +// Definitions by: Boris Yankov , Josh Baldwin , Christopher Currens , Cassey Lottman , Ard Timmerman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var _: _.UnderscoreStatic; +export = _; +export as namespace _; + +// The DOM is not required to be present, but these definitions reference type Element for the +// isElement check. If the DOM is present, this declaration will merge. +declare global { + interface Element { } +} + +declare module _ { + /** + * underscore.js _.throttle options. + **/ + interface ThrottleSettings { + + /** + * If you'd like to disable the leading-edge call, pass this as false. + **/ + leading?: boolean; + + /** + * If you'd like to disable the execution on the trailing-edge, pass false. + **/ + trailing?: boolean; + } + + /** + * underscore.js template settings, set templateSettings or pass as an argument + * to 'template()' to override defaults. + **/ + interface TemplateSettings { + /** + * Default value is '/<%([\s\S]+?)%>/g'. + **/ + evaluate?: RegExp; + + /** + * Default value is '/<%=([\s\S]+?)%>/g'. + **/ + interpolate?: RegExp; + + /** + * Default value is '/<%-([\s\S]+?)%>/g'. + **/ + escape?: RegExp; + + /** + * By default, 'template()' places the values from your data in the local scope via the 'with' statement. + * However, you can specify a single variable name with this setting. + **/ + variable?: string; + } + + interface Collection { } + + // Common interface between Arrays and jQuery objects + interface List extends Collection { + [index: number]: T; + length: number; + } + + interface Dictionary extends Collection { + [index: string]: T; + } + + interface ListIterator { + (value: T, index: number, list: List): TResult; + } + + interface ObjectIterator { + (element: T, key: string, list: Dictionary): TResult; + } + + type IterateePropertyShorthand = string | number; + + type IterateeMatcherShorthand = Dictionary; + + interface MemoIterator { + (prev: TResult, curr: T, index: number, list: List): TResult; + } + + interface MemoObjectIterator { + (prev: TResult, curr: T, key: string, list: Dictionary): TResult; + } + + interface Cancelable { + cancel(): void; + } + + interface UnderscoreStatic { + /** + * Underscore OOP Wrapper, all Underscore functions that take an object + * as the first parameter can be invoked through this function. + * @param key First argument to Underscore object functions. + **/ + (value: _.Dictionary): Underscore; + (value: Array): Underscore; + (value: T): Underscore; + + /* ************* + * Collections * + ************* */ + + /** + * Iterates over a list of elements, yielding each in turn to an iterator function. The iterator is + * bound to the context object, if one is passed. Each invocation of iterator is called with three + * arguments: (element, index, list). If list is a JavaScript object, iterator's arguments will be + * (value, key, object). Delegates to the native forEach function if it exists. + * @param list Iterates over this list of elements. + * @param iterator Iterator function for each element `list`. + * @param context 'this' object in `iterator`, optional. + **/ + each( + list: _.List, + iterator: _.ListIterator, + context?: any): _.List; + + /** + * @see _.each + * @param object Iterates over properties of this object. + * @param iterator Iterator function for each property on `object`. + * @param context 'this' object in `iterator`, optional. + **/ + each( + object: _.Dictionary, + iterator: _.ObjectIterator, + context?: any): _.Dictionary; + + /** + * @see _.each + **/ + forEach( + list: _.List, + iterator: _.ListIterator, + context?: any): _.List; + + /** + * @see _.each + **/ + forEach( + object: _.Dictionary, + iterator: _.ObjectIterator, + context?: any): _.Dictionary; + + /** + * Produces a new array of values by mapping each value in list through a transformation function + * (iterator). If the native map method exists, it will be used instead. If list is a JavaScript + * object, iterator's arguments will be (value, key, object). + * @param list Maps the elements of this array. + * @param iterator Map iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The mapped array result. + **/ + map( + list: _.List, + iterator: _.ListIterator, + context?: any): TResult[]; + + map( + list: _.List, + iterator: _.IterateePropertyShorthand, + context?: any): T[]; + + map( + list: _.List, + iterator: _.IterateeMatcherShorthand, + context?: any): boolean[]; + + /** + * @see _.map + * @param object Maps the properties of this object. + * @param iterator Map iterator function for each property on `object`. + * @param context `this` object in `iterator`, optional. + * @return The mapped object result. + **/ + map( + object: _.Dictionary, + iterator: _.ObjectIterator, + context?: any): TResult[]; + + /** + * @see _.map + **/ + collect: typeof _.map; + + /** + * Also known as inject and foldl, reduce boils down a list of values into a single value. + * Memo is the initial state of the reduction, and each successive step of it should be + * returned by iterator. The iterator is passed four arguments: the memo, then the value + * and index (or key) of the iteration, and finally a reference to the entire list. + * @param list Reduces the elements of this array. + * @param iterator Reduce iterator function for each element in `list`. + * @param memo Initial reduce state. + * @param context `this` object in `iterator`, optional. + * @return Reduced object result. + **/ + reduce( + list: _.List, + iterator: _.MemoIterator, + memo?: TResult, + context?: any): TResult; + + reduce( + list: _.Dictionary, + iterator: _.MemoObjectIterator, + memo?: TResult, + context?: any): TResult; + + /** + * @see _.reduce + **/ + inject( + list: _.List, + iterator: _.MemoIterator, + memo?: TResult, + context?: any): TResult; + + inject( + list: _.Dictionary, + iterator: _.MemoObjectIterator, + memo?: TResult, + context?: any): TResult; + + /** + * @see _.reduce + **/ + foldl( + list: _.Collection, + iterator: _.MemoIterator, + memo?: TResult, + context?: any): TResult; + + /** + * The right-associative version of reduce. Delegates to the JavaScript 1.8 version of + * reduceRight, if it exists. `foldr` is not as useful in JavaScript as it would be in a + * language with lazy evaluation. + * @param list Reduces the elements of this array. + * @param iterator Reduce iterator function for each element in `list`. + * @param memo Initial reduce state. + * @param context `this` object in `iterator`, optional. + * @return Reduced object result. + **/ + reduceRight( + list: _.Collection, + iterator: _.MemoIterator, + memo?: TResult, + context?: any): TResult; + + /** + * @see _.reduceRight + **/ + foldr( + list: _.Collection, + iterator: _.MemoIterator, + memo?: TResult, + context?: any): TResult; + + /** + * Looks through each value in the list, returning the first one that passes a truth + * test (iterator). The function returns as soon as it finds an acceptable element, + * and doesn't traverse the entire list. + * @param list Searches for a value in this list. + * @param iterator Search iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The first acceptable found element in `list`, if nothing is found undefined/null is returned. + **/ + find( + list: _.List, + iterator: _.ListIterator, + context?: any): T | undefined; + + /** + * @see _.find + **/ + find( + object: _.Dictionary, + iterator: _.ObjectIterator, + context?: any): T | undefined; + + /** + * @see _.find + **/ + find( + object: _.List | _.Dictionary, + iterator: U): T | undefined; + + /** + * @see _.find + **/ + find( + object: _.List | _.Dictionary, + iterator: string): T | undefined; + + /** + * @see _.find + **/ + detect( + list: _.List, + iterator: _.ListIterator, + context?: any): T | undefined; + + /** + * @see _.find + **/ + detect( + object: _.Dictionary, + iterator: _.ObjectIterator, + context?: any): T | undefined; + + /** + * @see _.find + **/ + detect( + object: _.List | _.Dictionary, + iterator: U): T | undefined; + + /** + * @see _.find + **/ + detect( + object: _.List | _.Dictionary, + iterator: string): T | undefined; + + /** + * Looks through each value in the list, returning an array of all the values that pass a truth + * test (iterator). Delegates to the native filter method, if it exists. + * @param list Filter elements out of this list. + * @param iterator Filter iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The filtered list of elements. + **/ + filter( + list: _.List, + iterator: _.ListIterator, + context?: any): T[]; + + /** + * @see _.filter + **/ + filter( + object: _.Dictionary, + iterator: _.ObjectIterator, + context?: any): T[]; + + /** + * @see _.filter + **/ + select( + list: _.List, + iterator: _.ListIterator, + context?: any): T[]; + + /** + * @see _.filter + **/ + select( + object: _.Dictionary, + iterator: _.ObjectIterator, + context?: any): T[]; + + /** + * Looks through each value in the list, returning an array of all the values that contain all + * of the key-value pairs listed in properties. + * @param list List to match elements again `properties`. + * @param properties The properties to check for on each element within `list`. + * @return The elements within `list` that contain the required `properties`. + **/ + where( + list: _.List, + properties: U): T[]; + + /** + * Looks through the list and returns the first value that matches all of the key-value pairs listed in properties. + * @param list Search through this list's elements for the first object with all `properties`. + * @param properties Properties to look for on the elements within `list`. + * @return The first element in `list` that has all `properties`. + **/ + findWhere( + list: _.List, + properties: U): T | undefined; + + /** + * Returns the values in list without the elements that the truth test (iterator) passes. + * The opposite of filter. + * Return all the elements for which a truth test fails. + * @param list Reject elements within this list. + * @param iterator Reject iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return The rejected list of elements. + **/ + reject( + list: _.List, + iterator: _.ListIterator, + context?: any): T[]; + + /** + * @see _.reject + **/ + reject( + object: _.Dictionary, + iterator: _.ObjectIterator, + context?: any): T[]; + + /** + * Returns true if all of the values in the list pass the iterator truth test. Delegates to the + * native method every, if present. + * @param list Truth test against all elements within this list. + * @param iterator Trust test iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return True if all elements passed the truth test, otherwise false. + **/ + every( + list: _.List, + iterator?: _.ListIterator, + context?: any): boolean; + + /** + * @see _.every + **/ + every( + list: _.Dictionary, + iterator?: _.ObjectIterator, + context?: any): boolean; + + /** + * @see _.every + **/ + all( + list: _.List, + iterator?: _.ListIterator, + context?: any): boolean; + + /** + * @see _.every + **/ + all( + list: _.Dictionary, + iterator?: _.ObjectIterator, + context?: any): boolean; + + /** + * Returns true if any of the values in the list pass the iterator truth test. Short-circuits and + * stops traversing the list if a true element is found. Delegates to the native method some, if present. + * @param list Truth test against all elements within this list. + * @param iterator Trust test iterator function for each element in `list`. + * @param context `this` object in `iterator`, optional. + * @return True if any elements passed the truth test, otherwise false. + **/ + some( + list: _.List, + iterator?: _.ListIterator, + context?: any): boolean; + + /** + * @see _.some + **/ + some( + object: _.Dictionary, + iterator?: _.ObjectIterator, + context?: any): boolean; + + /** + * @see _.some + **/ + any( + list: _.List, + iterator?: _.ListIterator, + context?: any): boolean; + + /** + * @see _.some + **/ + any( + object: _.Dictionary, + iterator?: _.ObjectIterator, + context?: any): boolean; + + any( + list: _.List, + value: T): boolean; + + /** + * Returns true if the value is present in the list. Uses indexOf internally, + * if list is an Array. + * @param list Checks each element to see if `value` is present. + * @param value The value to check for within `list`. + * @return True if `value` is present in `list`, otherwise false. + **/ + contains( + list: _.List, + value: T, + fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + contains( + object: _.Dictionary, + value: T): boolean; + + /** + * @see _.contains + **/ + include( + list: _.Collection, + value: T, + fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + include( + object: _.Dictionary, + value: T): boolean; + + /** + * @see _.contains + **/ + includes( + list: _.Collection, + value: T, + fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes( + object: _.Dictionary, + value: T): boolean; + + /** + * Calls the method named by methodName on each value in the list. Any extra arguments passed to + * invoke will be forwarded on to the method invocation. + * @param list The element's in this list will each have the method `methodName` invoked. + * @param methodName The method's name to call on each element within `list`. + * @param arguments Additional arguments to pass to the method `methodName`. + **/ + invoke( + list: _.List, + methodName: string, + ...args: any[]): any; + + /** + * A convenient version of what is perhaps the most common use-case for map: extracting a list of + * property values. + * @param list The list to pluck elements out of that have the property `propertyName`. + * @param propertyName The property to look for on each element within `list`. + * @return The list of elements within `list` that have the property `propertyName`. + **/ + pluck( + list: _.List, + propertyName: string): any[]; + + /** + * Returns the maximum value in list. + * @param list Finds the maximum value in this list. + * @return Maximum value in `list`. + **/ + max(list: _.List): number; + + /** + * @see _.max + */ + max(object: _.Dictionary): number; + + /** + * Returns the maximum value in list. If iterator is passed, it will be used on each value to generate + * the criterion by which the value is ranked. + * @param list Finds the maximum value in this list. + * @param iterator Compares each element in `list` to find the maximum value. + * @param context `this` object in `iterator`, optional. + * @return The maximum element within `list`. + **/ + max( + list: _.List, + iterator?: _.ListIterator, + context?: any): T; + + /** + * @see _.max + */ + max( + list: _.Dictionary, + iterator?: _.ObjectIterator, + context?: any): T; + + /** + * Returns the minimum value in list. + * @param list Finds the minimum value in this list. + * @return Minimum value in `list`. + **/ + min(list: _.List): number; + + /** + * @see _.min + */ + min(o: _.Dictionary): number; + + /** + * Returns the minimum value in list. If iterator is passed, it will be used on each value to generate + * the criterion by which the value is ranked. + * @param list Finds the minimum value in this list. + * @param iterator Compares each element in `list` to find the minimum value. + * @param context `this` object in `iterator`, optional. + * @return The minimum element within `list`. + **/ + min( + list: _.List, + iterator?: _.ListIterator, + context?: any): T; + + /** + * @see _.min + */ + min( + list: _.Dictionary, + iterator?: _.ObjectIterator, + context?: any): T; + + /** + * Returns a sorted copy of list, ranked in ascending order by the results of running each value + * through iterator. Iterator may also be the string name of the property to sort by (eg. length). + * @param list Sorts this list. + * @param iterator Sort iterator for each element within `list`. + * @param context `this` object in `iterator`, optional. + * @return A sorted copy of `list`. + **/ + sortBy( + list: _.List, + iterator?: _.ListIterator, + context?: any): T[]; + + /** + * @see _.sortBy + * @param iterator Sort iterator for each element within `list`. + **/ + sortBy( + list: _.List, + iterator: string, + context?: any): T[]; + + /** + * Splits a collection into sets, grouped by the result of running each value through iterator. + * If iterator is a string instead of a function, groups by the property named by iterator on + * each of the values. + * @param list Groups this list. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the grouped elements from `list`. + **/ + groupBy( + list: _.List, + iterator?: _.ListIterator, + context?: any): _.Dictionary; + + /** + * @see _.groupBy + * @param iterator Property on each object to group them by. + **/ + groupBy( + list: _.List, + iterator: string, + context?: any): _.Dictionary; + + /** + * Given a `list`, and an `iterator` function that returns a key for each element in the list (or a property name), + * returns an object with an index of each item. Just like _.groupBy, but for when you know your keys are unique. + **/ + indexBy( + list: _.List, + iterator: _.ListIterator, + context?: any): _.Dictionary; + + /** + * @see _.indexBy + * @param iterator Property on each object to index them by. + **/ + indexBy( + list: _.List, + iterator: string, + context?: any): _.Dictionary; + + /** + * Sorts a list into groups and returns a count for the number of objects in each group. Similar + * to groupBy, but instead of returning a list of values, returns a count for the number of values + * in that group. + * @param list Group elements in this list and then count the number of elements in each group. + * @param iterator Group iterator for each element within `list`, return the key to group the element by. + * @param context `this` object in `iterator`, optional. + * @return An object with the group names as properties where each property contains the number of elements in that group. + **/ + countBy( + list: _.List, + iterator?: _.ListIterator, + context?: any): _.Dictionary; + + /** + * @see _.countBy + * @param iterator Function name + **/ + countBy( + list: _.List, + iterator: string, + context?: any): _.Dictionary; + + /** + * Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle. + * @param list List to shuffle. + * @return Shuffled copy of `list`. + **/ + shuffle(list: _.Collection): T[]; + + /** + * Produce a random sample from the `list`. Pass a number to return `n` random elements from the list. Otherwise a single random item will be returned. + * @param list List to sample. + * @return Random sample of `n` elements in `list`. + **/ + sample(list: _.Collection, n: number): T[]; + + /** + * @see _.sample + **/ + sample(list: _.Collection): T; + + /** + * Converts the list (anything that can be iterated over), into a real Array. Useful for transmuting + * the arguments object. + * @param list object to transform into an array. + * @return `list` as an array. + **/ + toArray(list: _.Collection): T[]; + + /** + * Return the number of values in the list. + * @param list Count the number of values/elements in this list. + * @return Number of values in `list`. + **/ + size(list: _.Collection): number; + + /** + * Split array into two arrays: + * one whose elements all satisfy predicate and one whose elements all do not satisfy predicate. + * @param array Array to split in two. + * @param iterator Filter iterator function for each element in `array`. + * @param context `this` object in `iterator`, optional. + * @return Array where Array[0] are the elements in `array` that satisfies the predicate, and Array[1] the elements that did not. + **/ + partition( + array: Array, + iterator: _.ListIterator, + context?: any): T[][]; + + /********* + * Arrays * + **********/ + + /** + * Returns the first element of an array. Passing n will return the first n elements of the array. + * @param array Retrieves the first element of this array. + * @return Returns the first element of `array`. + **/ + first(array: _.List): T | undefined; + + /** + * @see _.first + * @param n Return more than one element from `array`. + **/ + first( + array: _.List, + n: number): T[]; + + /** + * @see _.first + **/ + head(array: _.List): T | undefined; + + /** + * @see _.first + **/ + head( + array: _.List, + n: number): T[]; + + /** + * @see _.first + **/ + take(array: _.List): T; + + /** + * @see _.first + **/ + take( + array: _.List, + n: number): T[]; + + /** + * Returns everything but the last entry of the array. Especially useful on the arguments object. + * Pass n to exclude the last n elements from the result. + * @param array Retrieve all elements except the last `n`. + * @param n Leaves this many elements behind, optional. + * @return Returns everything but the last `n` elements of `array`. + **/ + initial( + array: _.List, + n?: number): T[]; + + /** + * Returns the last element of an array. Passing n will return the last n elements of the array. + * @param array Retrieves the last element of this array. + * @return Returns the last element of `array`. + **/ + last(array: _.List): T | undefined; + + /** + * @see _.last + * @param n Return more than one element from `array`. + **/ + last( + array: _.List, + n: number): T[]; + + /** + * Returns the rest of the elements in an array. Pass an index to return the values of the array + * from that index onward. + * @param array The array to retrieve all but the first `index` elements. + * @param n The index to start retrieving elements forward from, optional, default = 1. + * @return Returns the elements of `array` from `index` to the end of `array`. + **/ + rest( + array: _.List, + n?: number): T[]; + + /** + * @see _.rest + **/ + tail( + array: _.List, + n?: number): T[]; + + /** + * @see _.rest + **/ + drop( + array: _.List, + n?: number): T[]; + + /** + * Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", + * undefined and NaN are all falsy. + * @param array Array to compact. + * @return Copy of `array` without false values. + **/ + compact(array: _.List | null | undefined): T[] + + /** + * Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will + * only be flattened a single level. + * @param array The array to flatten. + * @param shallow If true then only flatten one level, optional, default = false. + * @return `array` flattened. + **/ + flatten( + array: _.List, + shallow?: boolean): any[]; + + /** + * Returns a copy of the array with all instances of the values removed. + * @param array The array to remove `values` from. + * @param values The values to remove from `array`. + * @return Copy of `array` without `values`. + **/ + without( + array: _.List, + ...values: T[]): T[]; + + /** + * Computes the union of the passed-in arrays: the list of unique items, in order, that are + * present in one or more of the arrays. + * @param arrays Array of arrays to compute the union of. + * @return The union of elements within `arrays`. + **/ + union(...arrays: _.List[]): T[]; + + /** + * Computes the list of values that are the intersection of all the arrays. Each value in the result + * is present in each of the arrays. + * @param arrays Array of arrays to compute the intersection of. + * @return The intersection of elements within `arrays`. + **/ + intersection(...arrays: _.List[]): T[]; + + /** + * Similar to without, but returns the values from array that are not present in the other arrays. + * @param array Keeps values that are within `others`. + * @param others The values to keep within `array`. + * @return Copy of `array` with only `others` values. + **/ + difference( + array: _.List, + ...others: _.List[]): T[]; + + /** + * Produces a duplicate-free version of the array, using === to test object equality. If you know in + * advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If + * you want to compute unique items based on a transformation, pass an iterator function. + * @param array Array to remove duplicates from. + * @param isSorted True if `array` is already sorted, optional, default = false. + * @param iterator Transform the elements of `array` before comparisons for uniqueness. + * @param context 'this' object in `iterator`, optional. + * @return Copy of `array` where all elements are unique. + **/ + uniq( + array: _.List, + isSorted?: boolean, + iterator?: _.ListIterator | _.IterateePropertyShorthand, + context?: any): T[]; + + /** + * @see _.uniq + **/ + uniq( + array: _.List, + iterator?: _.ListIterator | _.IterateePropertyShorthand, + context?: any): T[]; + + /** + * @see _.uniq + **/ + unique( + array: _.List, + iterator?: _.ListIterator | _.IterateePropertyShorthand, + context?: any): T[]; + + /** + * @see _.uniq + **/ + unique( + array: _.List, + isSorted?: boolean, + iterator?: _.ListIterator | _.IterateePropertyShorthand, + context?: any): T[]; + + + /** + * Merges together the values of each of the arrays with the values at the corresponding position. + * Useful when you have separate data sources that are coordinated through matching array indexes. + * If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion. + * @param arrays The arrays to merge/zip. + * @return Zipped version of `arrays`. + **/ + zip(...arrays: any[][]): any[][]; + + /** + * @see _.zip + **/ + zip(...arrays: any[]): any[]; + + /** + * The opposite of zip. Given a number of arrays, returns a series of new arrays, the first + * of which contains all of the first elements in the input arrays, the second of which + * contains all of the second elements, and so on. Use with apply to pass in an array + * of arrays + * @param arrays The arrays to unzip. + * @return Unzipped version of `arrays`. + **/ + unzip(...arrays: any[][]): any[][]; + + /** + * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a + * list of keys, and a list of values. + * @param keys Key array. + * @param values Value array. + * @return An object containing the `keys` as properties and `values` as the property values. + **/ + object( + keys: _.List, + values: _.List): TResult; + + /** + * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a + * list of keys, and a list of values. + * @param keyValuePairs Array of [key, value] pairs. + * @return An object containing the `keys` as properties and `values` as the property values. + **/ + object(...keyValuePairs: any[][]): TResult; + + /** + * @see _.object + **/ + object( + list: _.List, + values?: any): TResult; + + /** + * Returns the index at which value can be found in the array, or -1 if value is not present in the array. + * Uses the native indexOf function unless it's missing. If you're working with a large array, and you know + * that the array is already sorted, pass true for isSorted to use a faster binary search ... or, pass a number + * as the third argument in order to look for the first matching value in the array after the given index. + * @param array The array to search for the index of `value`. + * @param value The value to search for within `array`. + * @param isSorted True if the array is already sorted, optional, default = false. + * @return The index of `value` within `array`. + **/ + indexOf( + array: _.List, + value: T, + isSorted?: boolean): number; + + /** + * @see _indexof + **/ + indexOf( + array: _.List, + value: T, + startFrom: number): number; + + /** + * Returns the index of the last occurrence of value in the array, or -1 if value is not present. Uses the + * native lastIndexOf function if possible. Pass fromIndex to start your search at a given index. + * @param array The array to search for the last index of `value`. + * @param value The value to search for within `array`. + * @param from The starting index for the search, optional. + * @return The index of the last occurrence of `value` within `array`. + **/ + lastIndexOf( + array: _.List, + value: T, + from?: number): number; + + /** + * Returns the first index of an element in `array` where the predicate truth test passes + * @param array The array to search for the index of the first element where the predicate truth test passes. + * @param predicate Predicate function. + * @param context `this` object in `predicate`, optional. + * @return Returns the index of an element in `array` where the predicate truth test passes or -1.` + **/ + findIndex( + array: _.List, + predicate: _.ListIterator | {}, + context?: any): number; + + /** + * Returns the last index of an element in `array` where the predicate truth test passes + * @param array The array to search for the index of the last element where the predicate truth test passes. + * @param predicate Predicate function. + * @param context `this` object in `predicate`, optional. + * @return Returns the index of an element in `array` where the predicate truth test passes or -1.` + **/ + findLastIndex( + array: _.List, + predicate: _.ListIterator | {}, + context?: any): number; + + /** + * Uses a binary search to determine the index at which the value should be inserted into the list in order + * to maintain the list's sorted order. If an iterator is passed, it will be used to compute the sort ranking + * of each value, including the value you pass. + * @param list The sorted list. + * @param value The value to determine its index within `list`. + * @param iterator Iterator to compute the sort ranking of each value, optional. + * @param context `this` object in `iterator`, optional. + * @return The index where `value` should be inserted into `list`. + **/ + sortedIndex( + list: _.List, + value: T, + iterator?: ((x: T) => TSort) | string, + context?: any + ): number; + + /** + * A function to create flexibly-numbered lists of integers, handy for each and map loops. start, if omitted, + * defaults to 0; step defaults to 1. Returns a list of integers from start to stop, incremented (or decremented) + * by step, exclusive. + * @param start Start here. + * @param stop Stop here. + * @param step The number to count up by each iteration, optional, default = 1. + * @return Array of numbers from `start` to `stop` with increments of `step`. + **/ + + range( + start: number, + stop: number, + step?: number): number[]; + + /** + * @see _.range + * @param stop Stop here. + * @return Array of numbers from 0 to `stop` with increments of 1. + * @note If start is not specified the implementation will never pull the step (step = arguments[2] || 0) + **/ + range(stop: number): number[]; + + /** + * Split an **array** into several arrays containing **count** or less elements + * of initial array. + * @param array The array to split + * @param count The maximum size of the inner arrays. + */ + chunk(array: _.Collection, count: number): (_.Collection)[] + + /************* + * Functions * + *************/ + + /** + * Bind a function to an object, meaning that whenever the function is called, the value of this will + * be the object. Optionally, bind arguments to the function to pre-fill them, also known as partial application. + * @param func The function to bind `this` to `object`. + * @param context The `this` pointer whenever `fn` is called. + * @param arguments Additional arguments to pass to `fn` when called. + * @return `fn` with `this` bound to `object`. + **/ + bind( + func: Function, + context: any, + ...args: any[]): () => any; + + /** + * Binds a number of methods on the object, specified by methodNames, to be run in the context of that object + * whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, + * which would otherwise be invoked with a fairly useless this. If no methodNames are provided, all of the + * object's function properties will be bound to it. + * @param object The object to bind the methods `methodName` to. + * @param methodNames The methods to bind to `object`, optional and if not provided all of `object`'s + * methods are bound. + **/ + bindAll( + object: any, + ...methodNames: string[]): any; + + /** + * Partially apply a function by filling in any number of its arguments, without changing its dynamic this value. + * A close cousin of bind. You may pass _ in your list of arguments to specify an argument that should not be + * pre-filled, but left open to supply at call-time. + * @param fn Function to partially fill in arguments. + * @param arguments The partial arguments. + * @return `fn` with partially filled in arguments. + **/ + + partial( + fn: { (p1: T1): T2 }, + p1: T1 + ): { (): T2 }; + + partial( + fn: { (p1: T1, p2: T2): T3 }, + p1: T1 + ): { (p2: T2): T3 }; + + partial( + fn: { (p1: T1, p2: T2): T3 }, + p1: T1, + p2: T2 + ): { (): T3 }; + + partial( + fn: { (p1: T1, p2: T2): T3 }, + stub1: UnderscoreStatic, + p2: T2 + ): { (p1: T1): T3 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3): T4 }, + p1: T1 + ): { (p2: T2, p3: T3): T4 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3): T4 }, + p1: T1, + p2: T2 + ): { (p3: T3): T4 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3): T4 }, + stub1: UnderscoreStatic, + p2: T2 + ): { (p1: T1, p3: T3): T4 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3): T4 }, + p1: T1, + p2: T2, + p3: T3 + ): { (): T4 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3): T4 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3 + ): { (p1: T1): T4 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3): T4 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3 + ): { (p2: T2): T4 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3): T4 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3 + ): { (p1: T1, p2: T2): T4 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + p1: T1 + ): { (p2: T2, p3: T3, p4: T4): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + p1: T1, + p2: T2 + ): { (p3: T3, p4: T4): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + stub1: UnderscoreStatic, + p2: T2 + ): { (p1: T1, p3: T3, p4: T4): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + p1: T1, + p2: T2, + p3: T3 + ): { (p4: T4): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3 + ): { (p1: T1, p4: T4): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3 + ): { (p2: T2, p4: T4): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3 + ): { (p1: T1, p2: T2, p4: T4): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4 + ): { (): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4 + ): { (p1: T1): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4 + ): { (p2: T2): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4 + ): { (p1: T1, p2: T2): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4 + ): { (p3: T3): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4 + ): { (p1: T1, p3: T3): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4 + ): { (p2: T2, p3: T3): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4): T5 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4 + ): { (p1: T1, p2: T2, p3: T3): T5 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1 + ): { (p2: T2, p3: T3, p4: T4, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + p2: T2 + ): { (p3: T3, p4: T4, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + p2: T2 + ): { (p1: T1, p3: T3, p4: T4, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + p2: T2, + p3: T3 + ): { (p4: T4, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3 + ): { (p1: T1, p4: T4, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3 + ): { (p2: T2, p4: T4, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3 + ): { (p1: T1, p2: T2, p4: T4, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4 + ): { (p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4 + ): { (p1: T1, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4 + ): { (p2: T2, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4 + ): { (p1: T1, p2: T2, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4 + ): { (p3: T3, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4 + ): { (p1: T1, p3: T3, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4 + ): { (p2: T2, p3: T3, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4 + ): { (p1: T1, p2: T2, p3: T3, p5: T5): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4, + p5: T5 + ): { (): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4, + p5: T5 + ): { (p1: T1): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5 + ): { (p2: T2): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5 + ): { (p1: T1, p2: T2): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p3: T3): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p1: T1, p3: T3): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p2: T2, p3: T3): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p1: T1, p2: T2, p3: T3): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p4: T4): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p4: T4): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p2: T2, p4: T4): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p2: T2, p4: T4): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p3: T3, p4: T4): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p3: T3, p4: T4): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p2: T2, p3: T3, p4: T4): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T6 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p2: T2, p3: T3, p4: T4): T6 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1 + ): { (p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2 + ): { (p3: T3, p4: T4, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2 + ): { (p1: T1, p3: T3, p4: T4, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + p3: T3 + ): { (p4: T4, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3 + ): { (p1: T1, p4: T4, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3 + ): { (p2: T2, p4: T4, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3 + ): { (p1: T1, p2: T2, p4: T4, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4 + ): { (p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4 + ): { (p1: T1, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4 + ): { (p2: T2, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4 + ): { (p1: T1, p2: T2, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4 + ): { (p3: T3, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4 + ): { (p1: T1, p3: T3, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4 + ): { (p2: T2, p3: T3, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4 + ): { (p1: T1, p2: T2, p3: T3, p5: T5, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4, + p5: T5 + ): { (p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4, + p5: T5 + ): { (p1: T1, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5 + ): { (p2: T2, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5 + ): { (p1: T1, p2: T2, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p3: T3, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p1: T1, p3: T3, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p2: T2, p3: T3, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p1: T1, p2: T2, p3: T3, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p4: T4, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p4: T4, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p2: T2, p4: T4, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p2: T2, p4: T4, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p3: T3, p4: T4, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p3: T3, p4: T4, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p2: T2, p3: T3, p4: T4, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p2: T2, p3: T3, p4: T4, p6: T6): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4, + p5: T5, + p6: T6 + ): { (): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4, + p5: T5, + p6: T6 + ): { (p1: T1): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5, + p6: T6 + ): { (p2: T2): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5, + p6: T6 + ): { (p1: T1, p2: T2): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6 + ): { (p3: T3): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6 + ): { (p1: T1, p3: T3): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6 + ): { (p2: T2, p3: T3): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6 + ): { (p1: T1, p2: T2, p3: T3): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p4: T4): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p1: T1, p4: T4): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p2: T2, p4: T4): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p1: T1, p2: T2, p4: T4): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p3: T3, p4: T4): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p1: T1, p3: T3, p4: T4): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p2: T2, p3: T3, p4: T4): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p1: T1, p2: T2, p3: T3, p4: T4): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p2: T2, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p2: T2, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p3: T3, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p3: T3, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p2: T2, p3: T3, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p2: T2, p3: T3, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p4: T4, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p4: T4, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p2: T2, p4: T4, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p2: T2, p4: T4, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p3: T3, p4: T4, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p3: T3, p4: T4, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p2: T2, p3: T3, p4: T4, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T7 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1 + ): { (p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2 + ): { (p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2 + ): { (p1: T1, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3 + ): { (p4: T4, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3 + ): { (p1: T1, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3 + ): { (p2: T2, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3 + ): { (p1: T1, p2: T2, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4 + ): { (p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4 + ): { (p1: T1, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4 + ): { (p2: T2, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4 + ): { (p1: T1, p2: T2, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4 + ): { (p3: T3, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4 + ): { (p1: T1, p3: T3, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4 + ): { (p2: T2, p3: T3, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4 + ): { (p1: T1, p2: T2, p3: T3, p5: T5, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4, + p5: T5 + ): { (p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4, + p5: T5 + ): { (p1: T1, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5 + ): { (p2: T2, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5 + ): { (p1: T1, p2: T2, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p3: T3, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p1: T1, p3: T3, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p2: T2, p3: T3, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5 + ): { (p1: T1, p2: T2, p3: T3, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p4: T4, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p4: T4, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p2: T2, p4: T4, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p2: T2, p4: T4, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p3: T3, p4: T4, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p3: T3, p4: T4, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p2: T2, p3: T3, p4: T4, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5 + ): { (p1: T1, p2: T2, p3: T3, p4: T4, p6: T6, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4, + p5: T5, + p6: T6 + ): { (p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4, + p5: T5, + p6: T6 + ): { (p1: T1, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5, + p6: T6 + ): { (p2: T2, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5, + p6: T6 + ): { (p1: T1, p2: T2, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6 + ): { (p3: T3, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6 + ): { (p1: T1, p3: T3, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6 + ): { (p2: T2, p3: T3, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6 + ): { (p1: T1, p2: T2, p3: T3, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p4: T4, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p1: T1, p4: T4, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p2: T2, p4: T4, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p1: T1, p2: T2, p4: T4, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p3: T3, p4: T4, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p1: T1, p3: T3, p4: T4, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p2: T2, p3: T3, p4: T4, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6 + ): { (p1: T1, p2: T2, p3: T3, p4: T4, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p2: T2, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p2: T2, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p3: T3, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p3: T3, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p2: T2, p3: T3, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p2: T2, p3: T3, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p4: T4, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p4: T4, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p2: T2, p4: T4, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p2: T2, p4: T4, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p3: T3, p4: T4, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p3: T3, p4: T4, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p2: T2, p3: T3, p4: T4, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6 + ): { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p7: T7): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4, + p5: T5, + p6: T6, + p7: T7 + ): { (): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4, + p5: T5, + p6: T6, + p7: T7 + ): { (p1: T1): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5, + p6: T6, + p7: T7 + ): { (p2: T2): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5, + p6: T6, + p7: T7 + ): { (p1: T1, p2: T2): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6, + p7: T7 + ): { (p3: T3): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6, + p7: T7 + ): { (p1: T1, p3: T3): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6, + p7: T7 + ): { (p2: T2, p3: T3): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + p6: T6, + p7: T7 + ): { (p1: T1, p2: T2, p3: T3): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6, + p7: T7 + ): { (p4: T4): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6, + p7: T7 + ): { (p1: T1, p4: T4): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6, + p7: T7 + ): { (p2: T2, p4: T4): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + p6: T6, + p7: T7 + ): { (p1: T1, p2: T2, p4: T4): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6, + p7: T7 + ): { (p3: T3, p4: T4): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6, + p7: T7 + ): { (p1: T1, p3: T3, p4: T4): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6, + p7: T7 + ): { (p2: T2, p3: T3, p4: T4): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + p6: T6, + p7: T7 + ): { (p1: T1, p2: T2, p3: T3, p4: T4): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p1: T1, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p2: T2, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p1: T1, p2: T2, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p3: T3, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p1: T1, p3: T3, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p2: T2, p3: T3, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p1: T1, p2: T2, p3: T3, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p4: T4, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p1: T1, p4: T4, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p2: T2, p4: T4, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p1: T1, p2: T2, p4: T4, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p3: T3, p4: T4, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p1: T1, p3: T3, p4: T4, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p2: T2, p3: T3, p4: T4, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + p6: T6, + p7: T7 + ): { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p2: T2, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p2: T2, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p3: T3, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p3: T3, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p2: T2, p3: T3, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p2: T2, p3: T3, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p4: T4, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p4: T4, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p2: T2, p4: T4, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p2: T2, p4: T4, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p3: T3, p4: T4, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p3: T3, p4: T4, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p2: T2, p3: T3, p4: T4, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + p5: T5, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p2: T2, p3: T3, p4: T4, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p2: T2, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + p4: T4, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p2: T2, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p3: T3, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p3: T3, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p2: T2, p3: T3, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + p4: T4, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p2: T2, p3: T3, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p4: T4, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p4: T4, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p2: T2, p4: T4, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + p3: T3, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p2: T2, p4: T4, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p3: T3, p4: T4, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + p2: T2, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p3: T3, p4: T4, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + p1: T1, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T8 }; + + partial( + fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }, + stub1: UnderscoreStatic, + stub2: UnderscoreStatic, + stub3: UnderscoreStatic, + stub4: UnderscoreStatic, + stub5: UnderscoreStatic, + stub6: UnderscoreStatic, + p7: T7 + ): { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T8 }; + + /** + * Memoizes a given function by caching the computed result. Useful for speeding up slow-running computations. + * If passed an optional hashFunction, it will be used to compute the hash key for storing the result, based + * on the arguments to the original function. The default hashFunction just uses the first argument to the + * memoized function as the key. + * @param fn Computationally expensive function that will now memoized results. + * @param hashFn Hash function for storing the result of `fn`. + * @return Memoized version of `fn`. + **/ + memoize( + fn: Function, + hashFn?: (...args: any[]) => string): Function; + + /** + * Much like setTimeout, invokes function after wait milliseconds. If you pass the optional arguments, + * they will be forwarded on to the function when it is invoked. + * @param func Function to delay `waitMS` amount of ms. + * @param wait The amount of milliseconds to delay `fn`. + * @arguments Additional arguments to pass to `fn`. + **/ + delay( + func: Function, + wait: number, + ...args: any[]): any; + + /** + * @see _delay + **/ + delay( + func: Function, + ...args: any[]): any; + + /** + * Defers invoking the function until the current call stack has cleared, similar to using setTimeout + * with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without + * blocking the UI thread from updating. If you pass the optional arguments, they will be forwarded on + * to the function when it is invoked. + * @param fn The function to defer. + * @param arguments Additional arguments to pass to `fn`. + **/ + defer( + fn: Function, + ...args: any[]): void; + + /** + * Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, + * will only actually call the original function at most once per every wait milliseconds. Useful for + * rate-limiting events that occur faster than you can keep up with. + * By default, throttle will execute the function as soon as you call it for the first time, and, + * if you call it again any number of times during the wait period, as soon as that period is over. + * If you'd like to disable the leading-edge call, pass {leading: false}, and if you'd like to disable + * the execution on the trailing-edge, pass {trailing: false}. + * @param func Function to throttle `waitMS` ms. + * @param wait The number of milliseconds to wait before `fn` can be invoked again. + * @param options Allows for disabling execution of the throttled function on either the leading or trailing edge. + * @return `fn` with a throttle of `wait`. + **/ + throttle( + func: T, + wait: number, + options?: _.ThrottleSettings): T & _.Cancelable; + + /** + * Creates and returns a new debounced version of the passed function that will postpone its execution + * until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing + * behavior that should only happen after the input has stopped arriving. For example: rendering a preview + * of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on. + * + * Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead + * of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double + *-clicks on a "submit" button from firing a second time. + * @param fn Function to debounce `waitMS` ms. + * @param wait The number of milliseconds to wait before `fn` can be invoked again. + * @param immediate True if `fn` should be invoked on the leading edge of `waitMS` instead of the trailing edge. + * @return Debounced version of `fn` that waits `wait` ms when invoked. + **/ + debounce( + fn: T, + wait: number, + immediate?: boolean): T & _.Cancelable; + + /** + * Creates a version of the function that can only be called one time. Repeated calls to the modified + * function will have no effect, returning the value from the original call. Useful for initialization + * functions, instead of having to set a boolean flag and then check it later. + * @param fn Function to only execute once. + * @return Copy of `fn` that can only be invoked once. + **/ + once(fn: T): T; + + /** + * Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) + * This accumulates the arguments passed into an array, after a given index. + **/ + restArgs(func: Function, starIndex?: number): Function; + + /** + * Creates a version of the function that will only be run after first being called count times. Useful + * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, + * before proceeding. + * @param number count Number of times to be called before actually executing. + * @param Function fn The function to defer execution `count` times. + * @return Copy of `fn` that will not execute until it is invoked `count` times. + **/ + after( + count: number, + fn: Function): Function; + + /** + * Creates a version of the function that can be called no more than count times. The result of + * the last function call is memoized and returned when count has been reached. + * @param number count The maxmimum number of times the function can be called. + * @param Function fn The function to limit the number of times it can be called. + * @return Copy of `fn` that can only be called `count` times. + **/ + before( + count: number, + fn: Function): Function; + + /** + * Wraps the first function inside of the wrapper function, passing it as the first argument. This allows + * the wrapper to execute code before and after the function runs, adjust the arguments, and execute it + * conditionally. + * @param fn Function to wrap. + * @param wrapper The function that will wrap `fn`. + * @return Wrapped version of `fn. + **/ + wrap( + fn: Function, + wrapper: (fn: Function, ...args: any[]) => any): Function; + + /** + * Returns a negated version of the pass-in predicate. + * @param (...args: any[]) => boolean predicate + * @return (...args: any[]) => boolean + **/ + negate(predicate: (...args: any[]) => boolean): (...args: any[]) => boolean; + + /** + * Returns the composition of a list of functions, where each function consumes the return value of the + * function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())). + * @param functions List of functions to compose. + * @return Composition of `functions`. + **/ + compose(...functions: Function[]): Function; + + /********** + * Objects * + ***********/ + + /** + * Retrieve all the names of the object's properties. + * @param object Retrieve the key or property names from this object. + * @return List of all the property names on `object`. + **/ + keys(object: any): string[]; + + /** + * Retrieve all the names of object's own and inherited properties. + * @param object Retrieve the key or property names from this object. + * @return List of all the property names on `object`. + **/ + allKeys(object: any): string[]; + + /** + * Return all of the values of the object's properties. + * @param object Retrieve the values of all the properties on this object. + * @return List of all the values on `object`. + **/ + values(object: _.Dictionary): T[]; + + /** + * Return all of the values of the object's properties. + * @param object Retrieve the values of all the properties on this object. + * @return List of all the values on `object`. + **/ + values(object: any): any[]; + + /** + * Like map, but for objects. Transform the value of each property in turn. + * @param object The object to transform + * @param iteratee The function that transforms property values + * @param context The optional context (value of `this`) to bind to + * @return a new _.Dictionary of property values + */ + mapObject(object: _.Dictionary, iteratee: (val: T, key: string, object: _.Dictionary) => U, context?: any): _.Dictionary; + + /** + * Like map, but for objects. Transform the value of each property in turn. + * @param object The object to transform + * @param iteratee The function that tranforms property values + * @param context The optional context (value of `this`) to bind to + */ + mapObject(object: any, iteratee: (val: any, key: string, object: any) => T, context?: any): _.Dictionary; + + /** + * Like map, but for objects. Retrieves a property from each entry in the object, as if by _.property + * @param object The object to transform + * @param iteratee The property name to retrieve + * @param context The optional context (value of `this`) to bind to + */ + mapObject(object: any, iteratee: string, context?: any): _.Dictionary; + + /** + * Convert an object into a list of [key, value] pairs. + * @param object Convert this object to a list of [key, value] pairs. + * @return List of [key, value] pairs on `object`. + **/ + pairs(object: any): [string, any][]; + + /** + * Returns a copy of the object where the keys have become the values and the values the keys. + * For this to work, all of your object's values should be unique and string serializable. + * @param object Object to invert key/value pairs. + * @return An inverted key/value paired version of `object`. + **/ + invert(object: any): any; + + /** + * Returns a sorted list of the names of every method in an object - that is to say, + * the name of every function property of the object. + * @param object Object to pluck all function property names from. + * @return List of all the function names on `object`. + **/ + functions(object: any): string[]; + + /** + * @see _functions + **/ + methods(object: any): string[]; + + /** + * Copy all of the properties in the source objects over to the destination object, and return + * the destination object. It's in-order, so the last source will override properties of the + * same name in previous arguments. + * @param destination Object to extend all the properties from `sources`. + * @param sources Extends `destination` with all properties from these source objects. + * @return `destination` extended with all the properties from the `sources` objects. + **/ + extend( + destination: any, + ...sources: any[]): any; + + /** + * Like extend, but only copies own properties over to the destination object. (alias: assign) + */ + extendOwn( + destination: any, + ...source: any[]): any; + + /** + * Like extend, but only copies own properties over to the destination object. (alias: extendOwn) + */ + assign( + destination: any, + ...source: any[]): any; + + /** + * Returns the first key on an object that passes a predicate test. + * @param obj the object to search in + * @param predicate Predicate function. + * @param context `this` object in `iterator`, optional. + */ + findKey(obj: _.Dictionary, predicate: _.ObjectIterator, context?: any): string; + + /** + * Return a copy of the object, filtered to only have values for the whitelisted keys + * (or array of valid keys). + * @param object Object to strip unwanted key/value pairs. + * @keys The key/value pairs to keep on `object`. + * @return Copy of `object` with only the `keys` properties. + **/ + pick( + object: any, + ...keys: any[]): any; + + /** + * @see _.pick + **/ + pick( + object: any, + fn: (value: any, key: any, object: any) => any): any; + + /** + * Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). + * @param object Object to strip unwanted key/value pairs. + * @param keys The key/value pairs to remove on `object`. + * @return Copy of `object` without the `keys` properties. + **/ + omit( + object: any, + ...keys: string[]): any; + + /** + * @see _.omit + **/ + omit( + object: any, + keys: string[]): any; + + /** + * @see _.omit + **/ + omit( + object: any, + iteratee: Function): any; + + /** + * Fill in null and undefined properties in object with values from the defaults objects, + * and return the object. As soon as the property is filled, further defaults will have no effect. + * @param object Fill this object with default values. + * @param defaults The default values to add to `object`. + * @return `object` with added `defaults` values. + **/ + defaults( + object: any, + ...defaults: any[]): any; + + + /** + * Creates an object that inherits from the given prototype object. + * If additional properties are provided then they will be added to the + * created object. + * @param prototype The prototype that the returned object will inherit from. + * @param props Additional props added to the returned object. + **/ + create(prototype: any, props?: Object): any; + + /** + * Create a shallow-copied clone of the object. + * Any nested objects or arrays will be copied by reference, not duplicated. + * @param object Object to clone. + * @return Copy of `object`. + **/ + clone(object: T): T; + + /** + * Invokes interceptor with the object, and then returns object. The primary purpose of this method + * is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. + * @param object Argument to `interceptor`. + * @param intercepter The function to modify `object` before continuing the method chain. + * @return Modified `object`. + **/ + tap(object: T, intercepter: Function): T; + + /** + * Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe + * reference to the hasOwnProperty function, in case it's been overridden accidentally. + * @param object Object to check for `key`. + * @param key The key to check for on `object`. + * @return True if `key` is a property on `object`, otherwise false. + **/ + has(object: any, key: string): boolean; + + /** + * Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in attrs. + * @param attrs Object with key values pair + * @return Predicate function + **/ + matches(attrs: T): _.ListIterator; + + /** + * Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in attrs. + * @see _.matches + * @param attrs Object with key values pair + * @return Predicate function + **/ + matcher(attrs: T): _.ListIterator; + + /** + * Returns a function that will itself return the key property of any passed-in object. + * @param key Property of the object. + * @return Function which accept an object an returns the value of key in that object. + **/ + property(key: string): (object: Object) => any; + + /** + * Returns a function that will itself return the value of a object key property. + * @param key The object to get the property value from. + * @return Function which accept a key property in `object` and returns its value. + **/ + propertyOf(object: Object): (key: string) => any; + + /** + * Performs an optimized deep comparison between the two objects, + * to determine if they should be considered equal. + * @param object Compare to `other`. + * @param other Compare to `object`. + * @return True if `object` is equal to `other`. + **/ + isEqual(object: any, other: any): boolean; + + /** + * Returns true if object contains no values. + * @param object Check if this object has no properties or values. + * @return True if `object` is empty. + **/ + isEmpty(object: any): boolean; + + /** + * Returns true if the keys and values in `properties` matches with the `object` properties. + * @param object Object to be compared with `properties`. + * @param properties Properties be compared with `object` + * @return True if `object` has matching keys and values, otherwise false. + **/ + isMatch(object: any, properties: any): boolean; + + /** + * Returns true if object is a DOM element. + * @param object Check if this object is a DOM element. + * @return True if `object` is a DOM element, otherwise false. + **/ + isElement(object: any): object is Element; + + /** + * Returns true if object is an Array. + * @param object Check if this object is an Array. + * @return True if `object` is an Array, otherwise false. + **/ + isArray(object: any): object is any[]; + + /** + * Returns true if object is an Array. + * @param object Check if this object is an Array. + * @return True if `object` is an Array, otherwise false. + **/ + isArray(object: any): object is T[]; + + /** + * Returns true if object is a Symbol. + * @param object Check if this object is a Symbol. + * @return True if `object` is a Symbol, otherwise false. + **/ + isSymbol(object: any): object is symbol; + + /** + * Returns true if value is an Object. Note that JavaScript arrays and functions are objects, + * while (normal) strings and numbers are not. + * @param object Check if this object is an Object. + * @return True of `object` is an Object, otherwise false. + **/ + isObject(object: any): boolean; + + /** + * Returns true if object is an Arguments object. + * @param object Check if this object is an Arguments object. + * @return True if `object` is an Arguments object, otherwise false. + **/ + isArguments(object: any): object is IArguments; + + /** + * Returns true if object is a Function. + * @param object Check if this object is a Function. + * @return True if `object` is a Function, otherwise false. + **/ + isFunction(object: any): object is Function; + + /** + * Returns true if object inherits from an Error. + * @param object Check if this object is an Error. + * @return True if `object` is a Error, otherwise false. + **/ + isError(object: any): object is Error; + + /** + * Returns true if object is a String. + * @param object Check if this object is a String. + * @return True if `object` is a String, otherwise false. + **/ + isString(object: any): object is string; + + /** + * Returns true if object is a Number (including NaN). + * @param object Check if this object is a Number. + * @return True if `object` is a Number, otherwise false. + **/ + isNumber(object: any): object is number; + + /** + * Returns true if object is a finite Number. + * @param object Check if this object is a finite Number. + * @return True if `object` is a finite Number. + **/ + isFinite(object: any): boolean; + + /** + * Returns true if object is either true or false. + * @param object Check if this object is a bool. + * @return True if `object` is a bool, otherwise false. + **/ + isBoolean(object: any): object is boolean; + + /** + * Returns true if object is a Date. + * @param object Check if this object is a Date. + * @return True if `object` is a Date, otherwise false. + **/ + isDate(object: any): object is Date; + + /** + * Returns true if object is a RegExp. + * @param object Check if this object is a RegExp. + * @return True if `object` is a RegExp, otherwise false. + **/ + isRegExp(object: any): object is RegExp; + + /** + * Returns true if object is NaN. + * Note: this is not the same as the native isNaN function, + * which will also return true if the variable is undefined. + * @param object Check if this object is NaN. + * @return True if `object` is NaN, otherwise false. + **/ + isNaN(object: any): boolean; + + /** + * Returns true if the value of object is null. + * @param object Check if this object is null. + * @return True if `object` is null, otherwise false. + **/ + isNull(object: any): boolean; + + /** + * Returns true if value is undefined. + * @param object Check if this object is undefined. + * @return True if `object` is undefined, otherwise false. + **/ + isUndefined(value: any): boolean; + + /* ********* + * Utility * + ********** */ + + /** + * Give control of the "_" variable back to its previous owner. + * Returns a reference to the Underscore object. + * @return Underscore object reference. + **/ + noConflict(): any; + + /** + * Returns the same value that is used as the argument. In math: f(x) = x + * This function looks useless, but is used throughout Underscore as a default iterator. + * @param value Identity of this object. + * @return `value`. + **/ + identity(value: T): T; + + /** + * Creates a function that returns the same value that is used as the argument of _.constant + * @param value Identity of this object. + * @return Function that return value. + **/ + constant(value: T): () => T; + + /** + * Returns undefined irrespective of the arguments passed to it. Useful as the default + * for optional callback arguments. + * Note there is no way to indicate a 'undefined' return, so it is currently typed as void. + * @return undefined + **/ + noop(): void; + + /** + * Invokes the given iterator function n times. + * Each invocation of iterator is called with an index argument + * @param n Number of times to invoke `iterator`. + * @param iterator Function iterator to invoke `n` times. + * @param context `this` object in `iterator`, optional. + **/ + times(n: number, iterator: (n: number) => TResult, context?: any): TResult[]; + + /** + * Returns a random integer between min and max, inclusive. If you only pass one argument, + * it will return a number between 0 and that number. + * @param max The maximum random number. + * @return A random number between 0 and `max`. + **/ + random(max: number): number; + + /** + * @see _.random + * @param min The minimum random number. + * @return A random number between `min` and `max`. + **/ + random(min: number, max: number): number; + + /** + * Allows you to extend Underscore with your own utility functions. Pass a hash of + * {name: function} definitions to have your functions added to the Underscore object, + * as well as the OOP wrapper. + * @param object Mixin object containing key/function pairs to add to the Underscore object. + **/ + mixin(object: any): void; + + /** + * A mostly-internal function to generate callbacks that can be applied to each element + * in a collection, returning the desired result -- either identity, an arbitrary callback, + * a property matcher, or a propetery accessor. + * @param string|Function|Object value The value to iterate over, usually the key. + * @param any context + * @return Callback that can be applied to each element in a collection. + **/ + iteratee(value: string): Function; + iteratee(value: Function, context?: any): Function; + iteratee(value: Object): Function; + + /** + * Generate a globally-unique id for client-side models or DOM elements that need one. + * If prefix is passed, the id will be appended to it. Without prefix, returns an integer. + * @param prefix A prefix string to start the unique ID with. + * @return Unique string ID beginning with `prefix`. + **/ + uniqueId(prefix?: string): string; + + /** + * Escapes a string for insertion into HTML, replacing &, <, >, ", ', and / characters. + * @param str Raw string to escape. + * @return `str` HTML escaped. + **/ + escape(str: string): string; + + /** + * The opposite of escape, replaces &, <, >, ", and ' with their unescaped counterparts. + * @param str HTML escaped string. + * @return `str` Raw string. + **/ + unescape(str: string): string; + + /** + * If the value of the named property is a function then invoke it; otherwise, return it. + * @param object Object to maybe invoke function `property` on. + * @param property The function by name to invoke on `object`. + * @param defaultValue The value to be returned in case `property` doesn't exist or is undefined. + * @return The result of invoking the function `property` on `object. + **/ + result(object: any, property: string, defaultValue?: any): any; + + /** + * Compiles JavaScript templates into functions that can be evaluated for rendering. Useful + * for rendering complicated bits of HTML from JSON data sources. Template functions can both + * interpolate variables, using <%= ... %>, as well as execute arbitrary JavaScript code, with + * <% ... %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- ... %> When + * you evaluate a template function, pass in a data object that has properties corresponding to + * the template's free variables. If you're writing a one-off, you can pass the data object as + * the second parameter to template in order to render immediately instead of returning a template + * function. The settings argument should be a hash containing any _.templateSettings that should + * be overridden. + * @param templateString Underscore HTML template. + * @param data Data to use when compiling `templateString`. + * @param settings Settings to use while compiling. + * @return Returns the compiled Underscore HTML template. + **/ + template(templateString: string, settings?: _.TemplateSettings): (...data: any[]) => string; + + /** + * By default, Underscore uses ERB-style template delimiters, change the + * following template settings to use alternative delimiters. + **/ + templateSettings: _.TemplateSettings; + + /** + * Returns an integer timestamp for the current time, using the fastest method available in the runtime. Useful for implementing timing/animation functions. + **/ + now(): number; + + /* ********** + * Chaining * + *********** */ + + /** + * Returns a wrapped object. Calling methods on this object will continue to return wrapped objects + * until value() is used. + * @param obj Object to chain. + * @return Wrapped `obj`. + **/ + chain(obj: T[]): _Chain; + chain(obj: _.Dictionary): _Chain; + chain(obj: T): _Chain; + } + + interface Underscore { + + /* ************* + * Collections * + ************* */ + + /** + * Wrapped type `any[]`. + * @see _.each + **/ + each(iterator: _.ListIterator, context?: any): _.List; + + /** + * @see _.each + **/ + each(iterator: _.ObjectIterator, context?: any): _.List; + + /** + * @see _.each + **/ + forEach(iterator: _.ListIterator, context?: any): _.List; + + /** + * @see _.each + **/ + forEach(iterator: _.ObjectIterator, context?: any): _.List; + + /** + * Wrapped type `any[]`. + * @see _.map + **/ + map(iterator: _.ListIterator, context?: any): TResult[]; + + /** + * Wrapped type `any[]`. + * @see _.map + **/ + map(iterator: _.ObjectIterator, context?: any): TResult[]; + + /** + * @see _.map + **/ + collect(iterator: _.ListIterator, context?: any): TResult[]; + + /** + * @see _.map + **/ + collect(iterator: _.ObjectIterator, context?: any): TResult[]; + + /** + * Wrapped type `any[]`. + * @see _.reduce + **/ + reduce(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; + + /** + * @see _.reduce + **/ + inject(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; + + /** + * @see _.reduce + **/ + foldl(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; + + /** + * Wrapped type `any[]`. + * @see _.reduceRight + **/ + reduceRight(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; + + /** + * @see _.reduceRight + **/ + foldr(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; + + /** + * Wrapped type `any[]`. + * @see _.find + **/ + find(iterator: _.ListIterator | _.ObjectIterator, context?: any): T | undefined; + + /** + * @see _.find + **/ + find(interator: U): T | undefined; + + /** + * @see _.find + **/ + find(interator: string): T | undefined; + + /** + * @see _.find + **/ + detect(iterator: _.ListIterator | _.ObjectIterator, context?: any): T | undefined; + + /** + * @see _.find + **/ + detect(interator?: U): T | undefined; + + /** + * @see _.find + **/ + detect(interator?: string): T | undefined; + + /** + * Wrapped type `any[]`. + * @see _.filter + **/ + filter(iterator: _.ListIterator, context?: any): T[]; + + /** + * @see _.filter + **/ + select(iterator: _.ListIterator, context?: any): T[]; + + /** + * Wrapped type `any[]`. + * @see _.where + **/ + where(properties: U): T[]; + + /** + * Wrapped type `any[]`. + * @see _.findWhere + **/ + findWhere(properties: U): T | undefined; + + /** + * Wrapped type `any[]`. + * @see _.reject + **/ + reject(iterator: _.ListIterator, context?: any): T[]; + + /** + * Wrapped type `any[]`. + * @see _.all + **/ + all(iterator?: _.ListIterator, context?: any): boolean; + + /** + * @see _.all + **/ + every(iterator?: _.ListIterator, context?: any): boolean; + + /** + * Wrapped type `any[]`. + * @see _.any + **/ + any(iterator?: _.ListIterator, context?: any): boolean; + + /** + * @see _.any + **/ + some(iterator?: _.ListIterator, context?: any): boolean; + + /** + * Wrapped type `any[]`. + * @see _.contains + **/ + contains(value: T, fromIndex?: number): boolean; + + /** + * Alias for 'contains'. + * @see contains + **/ + include(value: T, fromIndex?: number): boolean; + + /** + * Alias for 'contains'. + * @see contains + **/ + includes(value: T, fromIndex?: number): boolean; + + /** + * Wrapped type `any[]`. + * @see _.invoke + **/ + invoke(methodName: string, ...args: any[]): any; + + /** + * Wrapped type `any[]`. + * @see _.pluck + **/ + pluck(propertyName: string): any[]; + + /** + * Wrapped type `number[]`. + * @see _.max + **/ + max(): number; + + /** + * Wrapped type `any[]`. + * @see _.max + **/ + max(iterator: _.ListIterator, context?: any): T; + + /** + * Wrapped type `any[]`. + * @see _.max + **/ + max(iterator?: _.ListIterator, context?: any): T; + + /** + * Wrapped type `number[]`. + * @see _.min + **/ + min(): number; + + /** + * Wrapped type `any[]`. + * @see _.min + **/ + min(iterator: _.ListIterator, context?: any): T; + + /** + * Wrapped type `any[]`. + * @see _.min + **/ + min(iterator?: _.ListIterator, context?: any): T; + + /** + * Wrapped type `any[]`. + * @see _.sortBy + **/ + sortBy(iterator?: _.ListIterator, context?: any): T[]; + + /** + * Wrapped type `any[]`. + * @see _.sortBy + **/ + sortBy(iterator: string, context?: any): T[]; + + /** + * Wrapped type `any[]`. + * @see _.groupBy + **/ + groupBy(iterator?: _.ListIterator, context?: any): _.Dictionary<_.List>; + + /** + * Wrapped type `any[]`. + * @see _.groupBy + **/ + groupBy(iterator: string, context?: any): _.Dictionary; + + /** + * Wrapped type `any[]`. + * @see _.indexBy + **/ + indexBy(iterator: _.ListIterator, context?: any): _.Dictionary; + + /** + * Wrapped type `any[]`. + * @see _.indexBy + **/ + indexBy(iterator: string, context?: any): _.Dictionary; + + /** + * Wrapped type `any[]`. + * @see _.countBy + **/ + countBy(iterator?: _.ListIterator, context?: any): _.Dictionary; + + /** + * Wrapped type `any[]`. + * @see _.countBy + **/ + countBy(iterator: string, context?: any): _.Dictionary; + + /** + * Wrapped type `any[]`. + * @see _.shuffle + **/ + shuffle(): T[]; + + /** + * Wrapped type `any[]`. + * @see _.sample + **/ + sample(n: number): T[]; + + /** + * @see _.sample + **/ + sample(): T; + + /** + * Wrapped type `any`. + * @see _.toArray + **/ + toArray(): T[]; + + /** + * Wrapped type `any`. + * @see _.size + **/ + size(): number; + + /********* + * Arrays * + **********/ + + /** + * Wrapped type `any[]`. + * @see _.first + **/ + first(): T | undefined; + + /** + * Wrapped type `any[]`. + * @see _.first + **/ + first(n: number): T[]; + + /** + * @see _.first + **/ + head(): T | undefined; + + /** + * @see _.first + **/ + head(n: number): T[]; + + /** + * @see _.first + **/ + take(): T; + + /** + * @see _.first + **/ + take(n: number): T[]; + + /** + * Wrapped type `any[]`. + * @see _.initial + **/ + initial(n?: number): T[]; + + /** + * Wrapped type `any[]`. + * @see _.last + **/ + last(): T | undefined; + + /** + * Wrapped type `any[]`. + * @see _.last + **/ + last(n: number): T[]; + + /** + * Wrapped type `any[]`. + * @see _.rest + **/ + rest(n?: number): T[]; + + /** + * @see _.rest + **/ + tail(n?: number): T[]; + + /** + * @see _.rest + **/ + drop(n?: number): T[]; + + /** + * Wrapped type `any[]`. + * @see _.compact + **/ + compact(): T[]; + + /** + * Wrapped type `any`. + * @see _.flatten + **/ + flatten(shallow?: boolean): any[]; + + /** + * Wrapped type `any[]`. + * @see _.without + **/ + without(...values: T[]): T[]; + + /** + * Wrapped type `any[]`. + * @see _.partition + **/ + partition(iterator: _.ListIterator, context?: any): T[][]; + + /** + * Wrapped type `any[][]`. + * @see _.union + **/ + union(...arrays: _.List[]): T[]; + + /** + * Wrapped type `any[][]`. + * @see _.intersection + **/ + intersection(...arrays: _.List[]): T[]; + + /** + * Wrapped type `any[]`. + * @see _.difference + **/ + difference(...others: _.List[]): T[]; + + /** + * Wrapped type `any[]`. + * @see _.uniq + **/ + uniq(isSorted?: boolean, iterator?: _.ListIterator | _.IterateePropertyShorthand): T[]; + + /** + * Wrapped type `any[]`. + * @see _.uniq + **/ + uniq(iterator?: _.ListIterator, context?: any): T[]; + + /** + * @see _.uniq + **/ + unique(isSorted?: boolean, iterator?: _.ListIterator): T[]; + + /** + * @see _.uniq + **/ + unique(iterator?: _.ListIterator, context?: any): T[]; + + /** + * Wrapped type `any[][]`. + * @see _.zip + **/ + zip(...arrays: any[][]): any[][]; + + /** + * Wrapped type `any[][]`. + * @see _.unzip + **/ + unzip(...arrays: any[][]): any[][]; + + /** + * Wrapped type `any[][]`. + * @see _.object + **/ + object(...keyValuePairs: any[][]): any; + + /** + * @see _.object + **/ + object(values?: any): any; + + /** + * Wrapped type `any[]`. + * @see _.indexOf + **/ + indexOf(value: T, isSorted?: boolean): number; + + /** + * @see _.indexOf + **/ + indexOf(value: T, startFrom: number): number; + + /** + * Wrapped type `any[]`. + * @see _.lastIndexOf + **/ + lastIndexOf(value: T, from?: number): number; + + /** + * @see _.findIndex + **/ + findIndex(array: _.List, predicate: _.ListIterator | {}, context?: any): number; + + /** + * @see _.findLastIndex + **/ + findLastIndex(array: _.List, predicate: _.ListIterator | {}, context?: any): number; + + /** + * Wrapped type `any[]`. + * @see _.sortedIndex + **/ + sortedIndex(value: T, iterator?: (x: T) => any, context?: any): number; + + /** + * Wrapped type `number`. + * @see _.range + **/ + range(stop: number, step?: number): number[]; + + /** + * Wrapped type `number`. + * @see _.range + **/ + range(): number[]; + + /** + * Wrapped type any[][]. + * @see _.chunk + **/ + chunk(): any[][]; + + /* *********** + * Functions * + ************ */ + + /** + * Wrapped type `Function`. + * @see _.bind + **/ + bind(object: any, ...args: any[]): Function; + + /** + * Wrapped type `object`. + * @see _.bindAll + **/ + bindAll(...methodNames: string[]): any; + + /** + * Wrapped type `Function`. + * @see _.partial + **/ + partial(...args: any[]): Function; + + /** + * Wrapped type `Function`. + * @see _.memoize + **/ + memoize(hashFn?: (n: any) => string): Function; + + /** + * Wrapped type `Function`. + * @see _.defer + **/ + defer(...args: any[]): void; + + /** + * Wrapped type `Function`. + * @see _.delay + **/ + delay(wait: number, ...args: any[]): any; + + /** + * @see _.delay + **/ + delay(...args: any[]): any; + + /** + * Wrapped type `Function`. + * @see _.throttle + **/ + throttle(wait: number, options?: _.ThrottleSettings): Function & _.Cancelable; + + /** + * Wrapped type `Function`. + * @see _.debounce + **/ + debounce(wait: number, immediate?: boolean): Function & _.Cancelable; + + /** + * Wrapped type `Function`. + * @see _.once + **/ + once(): Function; + + /** + * Wrapped type `Function`. + * @see _.once + **/ + restArgs(starIndex?: number): Function; + + /** + * Wrapped type `number`. + * @see _.after + **/ + after(fn: Function): Function; + + /** + * Wrapped type `number`. + * @see _.before + **/ + before(fn: Function): Function; + + /** + * Wrapped type `Function`. + * @see _.wrap + **/ + wrap(wrapper: Function): () => Function; + + /** + * Wrapped type `Function`. + * @see _.negate + **/ + negate(): (...args: any[]) => boolean; + + /** + * Wrapped type `Function[]`. + * @see _.compose + **/ + compose(...functions: Function[]): Function; + + /********* * + * Objects * + ********** */ + + /** + * Wrapped type `object`. + * @see _.keys + **/ + keys(): string[]; + + /** + * Wrapped type `object`. + * @see _.allKeys + **/ + allKeys(): string[]; + + /** + * Wrapped type `object`. + * @see _.values + **/ + values(): T[]; + + /** + * Wrapped type `object`. + * @see _.pairs + **/ + pairs(): [string, any][]; + + /** + * Wrapped type `object`. + * @see _.invert + **/ + invert(): any; + + /** + * Wrapped type `object`. + * @see _.functions + **/ + functions(): string[]; + + /** + * @see _.functions + **/ + methods(): string[]; + + /** + * Wrapped type `object`. + * @see _.extend + **/ + extend(...sources: any[]): any; + + /** + * Wrapped type `object`. + * @see _.extend + **/ + findKey(predicate: _.ObjectIterator, context?: any): any + + /** + * Wrapped type `object`. + * @see _.pick + **/ + pick(...keys: any[]): any; + pick(keys: any[]): any; + pick(fn: (value: any, key: any, object: any) => any): any; + + /** + * Wrapped type `object`. + * @see _.omit + **/ + omit(...keys: string[]): any; + omit(keys: string[]): any; + omit(fn: Function): any; + + /** + * Wrapped type `object`. + * @see _.defaults + **/ + defaults(...defaults: any[]): any; + + /** + * Wrapped type `any`. + * @see _.create + **/ + create(props?: Object): any; + + /** + * Wrapped type `any[]`. + * @see _.clone + **/ + clone(): T; + + /** + * Wrapped type `object`. + * @see _.tap + **/ + tap(interceptor: (...as: any[]) => any): any; + + /** + * Wrapped type `object`. + * @see _.has + **/ + has(key: string): boolean; + + /** + * Wrapped type `any[]`. + * @see _.matches + **/ + matches(): _.ListIterator; + + /** + * Wrapped type `any[]`. + * @see _.matcher + **/ + matcher(): _.ListIterator; + + /** + * Wrapped type `string`. + * @see _.property + **/ + property(): (object: Object) => any; + + /** + * Wrapped type `object`. + * @see _.propertyOf + **/ + propertyOf(): (key: string) => any; + + /** + * Wrapped type `object`. + * @see _.isEqual + **/ + isEqual(other: any): boolean; + + /** + * Wrapped type `object`. + * @see _.isEmpty + **/ + isEmpty(): boolean; + + /** + * Wrapped type `object`. + * @see _.isMatch + **/ + isMatch(): boolean; + + /** + * Wrapped type `object`. + * @see _.isElement + **/ + isElement(): boolean; + + /** + * Wrapped type `object`. + * @see _.isArray + **/ + isArray(): boolean; + + /** + * Wrapped type `object`. + * @see _.isSymbol + **/ + isSymbol(): boolean; + + /** + * Wrapped type `object`. + * @see _.isObject + **/ + isObject(): boolean; + + /** + * Wrapped type `object`. + * @see _.isArguments + **/ + isArguments(): boolean; + + /** + * Wrapped type `object`. + * @see _.isFunction + **/ + isFunction(): boolean; + + /** + * Wrapped type `object`. + * @see _.isError + **/ + isError(): boolean; + + /** + * Wrapped type `object`. + * @see _.isString + **/ + isString(): boolean; + + /** + * Wrapped type `object`. + * @see _.isNumber + **/ + isNumber(): boolean; + + /** + * Wrapped type `object`. + * @see _.isFinite + **/ + isFinite(): boolean; + + /** + * Wrapped type `object`. + * @see _.isBoolean + **/ + isBoolean(): boolean; + + /** + * Wrapped type `object`. + * @see _.isDate + **/ + isDate(): boolean; + + /** + * Wrapped type `object`. + * @see _.isRegExp + **/ + isRegExp(): boolean; + + /** + * Wrapped type `object`. + * @see _.isNaN + **/ + isNaN(): boolean; + + /** + * Wrapped type `object`. + * @see _.isNull + **/ + isNull(): boolean; + + /** + * Wrapped type `object`. + * @see _.isUndefined + **/ + isUndefined(): boolean; + + /********* * + * Utility * + ********** */ + + /** + * Wrapped type `any`. + * @see _.identity + **/ + identity(): any; + + /** + * Wrapped type `any`. + * @see _.constant + **/ + constant(): () => T; + + /** + * Wrapped type `any`. + * @see _.noop + **/ + noop(): void; + + /** + * Wrapped type `number`. + * @see _.times + **/ + times(iterator: (n: number) => TResult, context?: any): TResult[]; + + /** + * Wrapped type `number`. + * @see _.random + **/ + random(): number; + /** + * Wrapped type `number`. + * @see _.random + **/ + random(max: number): number; + + /** + * Wrapped type `object`. + * @see _.mixin + **/ + mixin(): void; + + /** + * Wrapped type `string|Function|Object`. + * @see _.iteratee + **/ + iteratee(context?: any): Function; + + /** + * Wrapped type `string`. + * @see _.uniqueId + **/ + uniqueId(): string; + + /** + * Wrapped type `string`. + * @see _.escape + **/ + escape(): string; + + /** + * Wrapped type `string`. + * @see _.unescape + **/ + unescape(): string; + + /** + * Wrapped type `object`. + * @see _.result + **/ + result(property: string, defaultValue?: any): any; + + /** + * Wrapped type `string`. + * @see _.template + **/ + template(settings?: _.TemplateSettings): (...data: any[]) => string; + + /********** * + * Chaining * + *********** */ + + /** + * Wrapped type `any`. + * @see _.chain + **/ + chain(): _Chain; + + /** + * Wrapped type `any`. + * Extracts the value of a wrapped object. + * @return Value of the wrapped object. + **/ + value(): TResult; + } + + interface _Chain { + + /* ************* + * Collections * + ************* */ + + /** + * Wrapped type `any[]`. + * @see _.each + **/ + each(iterator: _.ListIterator, context?: any): _Chain; + + /** + * @see _.each + **/ + each(iterator: _.ObjectIterator, context?: any): _Chain; + + /** + * @see _.each + **/ + forEach(iterator: _.ListIterator, context?: any): _Chain; + + /** + * @see _.each + **/ + forEach(iterator: _.ObjectIterator, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.map + **/ + map(iterator: _.ListIterator, context?: any): _ChainOfArrays; + + /** + * Wrapped type `any[]`. + * @see _.map + **/ + map(iterator: _.ListIterator, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.map + **/ + map(iterator: _.ObjectIterator, context?: any): _ChainOfArrays; + + /** + * Wrapped type `any[]`. + * @see _.map + **/ + map(iterator: _.ObjectIterator, context?: any): _Chain; + + /** + * @see _.map + **/ + collect(iterator: _.ListIterator, context?: any): _Chain; + + /** + * @see _.map + **/ + collect(iterator: _.ObjectIterator, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.reduce + **/ + reduce(iterator: _.MemoIterator, memo?: TResult, context?: any): _ChainSingle; + + /** + * @see _.reduce + **/ + inject(iterator: _.MemoIterator, memo?: TResult, context?: any): _ChainSingle; + + /** + * @see _.reduce + **/ + foldl(iterator: _.MemoIterator, memo?: TResult, context?: any): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.reduceRight + **/ + reduceRight(iterator: _.MemoIterator, memo?: TResult, context?: any): _ChainSingle; + + /** + * @see _.reduceRight + **/ + foldr(iterator: _.MemoIterator, memo?: TResult, context?: any): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.find + **/ + find(iterator: _.ListIterator | _.ObjectIterator, context?: any): _ChainSingle; + + /** + * @see _.find + **/ + find(interator: U): _ChainSingle; + + /** + * @see _.find + **/ + find(interator: string): _ChainSingle; + + /** + * @see _.find + **/ + detect(iterator: _.ListIterator | _.ObjectIterator, context?: any): _ChainSingle; + + /** + * @see _.find + **/ + detect(interator: U): _ChainSingle; + + /** + * @see _.find + **/ + detect(interator: string): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.filter + **/ + filter(iterator: _.ListIterator, context?: any): _Chain; + + /** + * @see _.filter + **/ + select(iterator: _.ListIterator, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.where + **/ + where(properties: U): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.findWhere + **/ + findWhere(properties: U): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.reject + **/ + reject(iterator: _.ListIterator, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.all + **/ + all(iterator?: _.ListIterator, context?: any): _ChainSingle; + + /** + * @see _.all + **/ + every(iterator?: _.ListIterator, context?: any): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.any + **/ + any(iterator?: _.ListIterator, context?: any): _ChainSingle; + + /** + * @see _.any + **/ + some(iterator?: _.ListIterator, context?: any): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.contains + **/ + contains(value: T, fromIndex?: number): _ChainSingle; + + /** + * Alias for 'contains'. + * @see contains + **/ + include(value: T, fromIndex?: number): _ChainSingle; + + /** + * Alias for 'contains'. + * @see contains + **/ + includes(value: T, fromIndex?: number): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.invoke + **/ + invoke(methodName: string, ...args: any[]): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.pluck + **/ + pluck(propertyName: string): _Chain; + + /** + * Wrapped type `number[]`. + * @see _.max + **/ + max(): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.max + **/ + max(iterator: _.ListIterator, context?: any): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.max + **/ + max(iterator?: _.ListIterator, context?: any): _ChainSingle; + + /** + * Wrapped type `number[]`. + * @see _.min + **/ + min(): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.min + **/ + min(iterator: _.ListIterator, context?: any): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.min + **/ + min(iterator?: _.ListIterator, context?: any): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.sortBy + **/ + sortBy(iterator?: _.ListIterator, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.sortBy + **/ + sortBy(iterator: string, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.groupBy + **/ + groupBy(iterator?: _.ListIterator, context?: any): _ChainOfArrays; + + /** + * Wrapped type `any[]`. + * @see _.groupBy + **/ + groupBy(iterator: string, context?: any): _ChainOfArrays; + + /** + * Wrapped type `any[]`. + * @see _.indexBy + **/ + indexBy(iterator: _.ListIterator, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.indexBy + **/ + indexBy(iterator: string, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.countBy + **/ + countBy(iterator?: _.ListIterator, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.countBy + **/ + countBy(iterator: string, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.shuffle + **/ + shuffle(): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.sample + **/ + sample(n: number): _Chain; + + /** + * @see _.sample + **/ + sample(): _Chain; + + /** + * Wrapped type `any`. + * @see _.toArray + **/ + toArray(): _Chain; + + /** + * Wrapped type `any`. + * @see _.size + **/ + size(): _ChainSingle; + + /********* + * Arrays * + **********/ + + /** + * Wrapped type `any[]`. + * @see _.first + **/ + first(): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.first + **/ + first(n: number): _Chain; + + /** + * @see _.first + **/ + head(): _Chain; + + /** + * @see _.first + **/ + head(n: number): _Chain; + + /** + * @see _.first + **/ + take(): _Chain; + + /** + * @see _.first + **/ + take(n: number): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.initial + **/ + initial(n?: number): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.last + **/ + last(): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.last + **/ + last(n: number): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.rest + **/ + rest(n?: number): _Chain; + + /** + * @see _.rest + **/ + tail(n?: number): _Chain; + + /** + * @see _.rest + **/ + drop(n?: number): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.compact + **/ + compact(): _Chain; + + /** + * Wrapped type `any`. + * @see _.flatten + **/ + flatten(shallow?: boolean): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.without + **/ + without(...values: T[]): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.partition + **/ + partition(iterator: _.ListIterator, context?: any): _Chain; + + /** + * Wrapped type `any[][]`. + * @see _.union + **/ + union(...arrays: _.List[]): _Chain; + + /** + * Wrapped type `any[][]`. + * @see _.intersection + **/ + intersection(...arrays: _.List[]): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.difference + **/ + difference(...others: _.List[]): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.uniq + **/ + uniq(isSorted?: boolean, iterator?: _.ListIterator | _.IterateePropertyShorthand): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.uniq + **/ + uniq(iterator?: _.ListIterator | _.IterateePropertyShorthand, context?: any): _Chain; + + /** + * @see _.uniq + **/ + unique(isSorted?: boolean, iterator?: _.ListIterator | _.IterateePropertyShorthand): _Chain; + + /** + * @see _.uniq + **/ + unique(iterator?: _.ListIterator | _.IterateePropertyShorthand, context?: any): _Chain; + + /** + * Wrapped type `any[][]`. + * @see _.zip + **/ + zip(...arrays: any[][]): _Chain; + + /** + * Wrapped type `any[][]`. + * @see _.unzip + **/ + unzip(...arrays: any[][]): _Chain; + + /** + * Wrapped type `any[][]`. + * @see _.object + **/ + object(...keyValuePairs: any[][]): _Chain; + + /** + * @see _.object + **/ + object(values?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.indexOf + **/ + indexOf(value: T, isSorted?: boolean): _ChainSingle; + + /** + * @see _.indexOf + **/ + indexOf(value: T, startFrom: number): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.lastIndexOf + **/ + lastIndexOf(value: T, from?: number): _ChainSingle; + + /** + * @see _.findIndex + **/ + findIndex(predicate: _.ListIterator | {}, context?: any): _ChainSingle; + + /** + * @see _.findLastIndex + **/ + findLastIndex(predicate: _.ListIterator | {}, context?: any): _ChainSingle; + + /** + * Wrapped type `any[]`. + * @see _.sortedIndex + **/ + sortedIndex(value: T, iterator?: (x: T) => any, context?: any): _ChainSingle; + + /** + * Wrapped type `number`. + * @see _.range + **/ + range(stop: number, step?: number): _Chain; + + /** + * Wrapped type `number`. + * @see _.range + **/ + range(): _Chain; + + /** + * Wrapped type `any[][]`. + * @see _.chunk + **/ + chunk(): _Chain; + + /* *********** + * Functions * + ************ */ + + /** + * Wrapped type `Function`. + * @see _.bind + **/ + bind(object: any, ...args: any[]): _Chain; + + /** + * Wrapped type `object`. + * @see _.bindAll + **/ + bindAll(...methodNames: string[]): _Chain; + + /** + * Wrapped type `Function`. + * @see _.partial + **/ + partial(...args: any[]): _Chain; + + /** + * Wrapped type `Function`. + * @see _.memoize + **/ + memoize(hashFn?: (n: any) => string): _Chain; + + /** + * Wrapped type `Function`. + * @see _.defer + **/ + defer(...args: any[]): _Chain; + + /** + * Wrapped type `Function`. + * @see _.delay + **/ + delay(wait: number, ...args: any[]): _Chain; + + /** + * @see _.delay + **/ + delay(...args: any[]): _Chain; + + /** + * Wrapped type `Function`. + * @see _.throttle + **/ + throttle(wait: number, options?: _.ThrottleSettings): _Chain; + + /** + * Wrapped type `Function`. + * @see _.debounce + **/ + debounce(wait: number, immediate?: boolean): _Chain; + + /** + * Wrapped type `Function`. + * @see _.once + **/ + once(): _Chain; + + /** + * Wrapped type `Function`. + * @see _.once + **/ + restArgs(startIndex?: number): _Chain; + + /** + * Wrapped type `number`. + * @see _.after + **/ + after(func: Function): _Chain; + + /** + * Wrapped type `number`. + * @see _.before + **/ + before(fn: Function): _Chain; + + /** + * Wrapped type `Function`. + * @see _.wrap + **/ + wrap(wrapper: Function): () => _Chain; + + /** + * Wrapped type `Function`. + * @see _.negate + **/ + negate(): _Chain; + + /** + * Wrapped type `Function[]`. + * @see _.compose + **/ + compose(...functions: Function[]): _Chain; + + /********* * + * Objects * + ********** */ + + /** + * Wrapped type `object`. + * @see _.keys + **/ + keys(): _Chain; + + /** + * Wrapped type `object`. + * @see _.allKeys + **/ + allKeys(): _Chain; + + /** + * Wrapped type `object`. + * @see _.values + **/ + values(): _Chain; + + /** + * Wrapped type `object`. + * @see _.mapObject + **/ + mapObject(fn: _.ListIterator): _Chain; + + /** + * Wrapped type `object`. + * @see _.pairs + **/ + pairs(): _Chain<[string, any]>; + + /** + * Wrapped type `object`. + * @see _.invert + **/ + invert(): _Chain; + + /** + * Wrapped type `object`. + * @see _.functions + **/ + functions(): _Chain; + + /** + * @see _.functions + **/ + methods(): _Chain; + + /** + * Wrapped type `object`. + * @see _.extend + **/ + extend(...sources: any[]): _Chain; + + /** + * Wrapped type `object`. + * @see _.extend + **/ + findKey(predicate: _.ObjectIterator, context?: any): _Chain + + /** + * Wrapped type `object`. + * @see _.pick + **/ + pick(...keys: any[]): _Chain; + pick(keys: any[]): _Chain; + pick(fn: (value: any, key: any, object: any) => any): _Chain; + + /** + * Wrapped type `object`. + * @see _.omit + **/ + omit(...keys: string[]): _Chain; + omit(keys: string[]): _Chain; + omit(iteratee: Function): _Chain; + + /** + * Wrapped type `object`. + * @see _.defaults + **/ + defaults(...defaults: any[]): _Chain; + + /** + * Wrapped type `any`. + * @see _.create + **/ + create(props?: Object): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.clone + **/ + clone(): _Chain; + + /** + * Wrapped type `object`. + * @see _.tap + **/ + tap(interceptor: (...as: any[]) => any): _Chain; + + /** + * Wrapped type `object`. + * @see _.has + **/ + has(key: string): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.matches + **/ + matches(): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.matcher + **/ + matcher(): _Chain; + + /** + * Wrapped type `string`. + * @see _.property + **/ + property(): _Chain; + + /** + * Wrapped type `object`. + * @see _.propertyOf + **/ + propertyOf(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isEqual + **/ + isEqual(other: any): _Chain; + + /** + * Wrapped type `object`. + * @see _.isEmpty + **/ + isEmpty(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isMatch + **/ + isMatch(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isElement + **/ + isElement(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isArray + **/ + isArray(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isSymbol + **/ + isSymbol(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isObject + **/ + isObject(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isArguments + **/ + isArguments(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isFunction + **/ + isFunction(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isError + **/ + isError(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isString + **/ + isString(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isNumber + **/ + isNumber(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isFinite + **/ + isFinite(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isBoolean + **/ + isBoolean(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isDate + **/ + isDate(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isRegExp + **/ + isRegExp(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isNaN + **/ + isNaN(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isNull + **/ + isNull(): _Chain; + + /** + * Wrapped type `object`. + * @see _.isUndefined + **/ + isUndefined(): _Chain; + + /********* * + * Utility * + ********** */ + + /** + * Wrapped type `any`. + * @see _.identity + **/ + identity(): _Chain; + + /** + * Wrapped type `any`. + * @see _.constant + **/ + constant(): _Chain; + + /** + * Wrapped type `any`. + * @see _.noop + **/ + noop(): _Chain; + + /** + * Wrapped type `number`. + * @see _.times + **/ + times(iterator: (n: number) => TResult, context?: any): _Chain; + + /** + * Wrapped type `number`. + * @see _.random + **/ + random(): _Chain; + /** + * Wrapped type `number`. + * @see _.random + **/ + random(max: number): _Chain; + + /** + * Wrapped type `object`. + * @see _.mixin + **/ + mixin(): _Chain; + + /** + * Wrapped type `string|Function|Object`. + * @see _.iteratee + **/ + iteratee(context?: any): _Chain; + + /** + * Wrapped type `string`. + * @see _.uniqueId + **/ + uniqueId(): _Chain; + + /** + * Wrapped type `string`. + * @see _.escape + **/ + escape(): _Chain; + + /** + * Wrapped type `string`. + * @see _.unescape + **/ + unescape(): _Chain; + + /** + * Wrapped type `object`. + * @see _.result + **/ + result(property: string, defaultValue?: any): _Chain; + + /** + * Wrapped type `string`. + * @see _.template + **/ + template(settings?: _.TemplateSettings): (...data: any[]) => _Chain; + + /************* * + * Array proxy * + ************** */ + + /** + * Returns a new array comprised of the array on which it is called + * joined with the array(s) and/or value(s) provided as arguments. + * @param arr Arrays and/or values to concatenate into a new array. See the discussion below for details. + * @return A new array comprised of the array on which it is called + **/ + concat(...arr: Array): _Chain; + + /** + * Join all elements of an array into a string. + * @param separator Optional. Specifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma. + * @return The string conversions of all array elements joined into one string. + **/ + join(separator?: any): _ChainSingle; + + /** + * Removes the last element from an array and returns that element. + * @return Returns the popped element. + **/ + pop(): _ChainSingle; + + /** + * Adds one or more elements to the end of an array and returns the new length of the array. + * @param item The elements to add to the end of the array. + * @return The array with the element added to the end. + **/ + push(...item: Array): _Chain; + + /** + * Reverses an array in place. The first array element becomes the last and the last becomes the first. + * @return The reversed array. + **/ + reverse(): _Chain; + + /** + * Removes the first element from an array and returns that element. This method changes the length of the array. + * @return The shifted element. + **/ + shift(): _ChainSingle; + + /** + * Returns a shallow copy of a portion of an array into a new array object. + * @param start Zero-based index at which to begin extraction. + * @param end Optional. Zero-based index at which to end extraction. slice extracts up to but not including end. + * @return A shallow copy of a portion of an array into a new array object. + **/ + slice(start: number, end?: number): _Chain; + + /** + * Sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points. + * @param compareFn Optional. Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element. + * @return The sorted array. + **/ + sort(compareFn?: (a: T, b: T) => boolean): _Chain; + + /** + * Changes the content of an array by removing existing elements and/or adding new elements. + * @param index Index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end. + * @param quantity An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at index, then all of the elements through the end of the array will be deleted. + * @param items The element to add to the array. If you don't specify any elements, splice will only remove elements from the array. + * @return An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. + **/ + splice(index: number, quantity: number, ...items: Array): _Chain; + + /** + * A string representing the specified array and its elements. + * @return A string representing the specified array and its elements. + **/ + toString(): _ChainSingle; + + /** + * Adds one or more elements to the beginning of an array and returns the new length of the array. + * @param items The elements to add to the front of the array. + * @return The array with the element added to the beginning. + **/ + unshift(...items: Array): _Chain; + + /********** * + * Chaining * + *********** */ + + /** + * Wrapped type `any`. + * @see _.chain + **/ + chain(): _Chain; + + /** + * Wrapped type `any`. + * @see _.value + **/ + value(): T[]; + } + interface _ChainSingle { + value(): T; + } + interface _ChainOfArrays extends _Chain { + flatten(shallow?: boolean): _Chain; + } +} diff --git a/node_modules/graphql/LICENSE b/node_modules/graphql/LICENSE new file mode 100644 index 0000000..9e05101 --- /dev/null +++ b/node_modules/graphql/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2015-present, Facebook, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/graphql/README.md b/node_modules/graphql/README.md new file mode 100644 index 0000000..0148a8c --- /dev/null +++ b/node_modules/graphql/README.md @@ -0,0 +1,145 @@ +# 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)](http://badge.fury.io/js/graphql) +[![Build Status](https://travis-ci.org/graphql/graphql-js.svg?branch=master)](https://travis-ci.org/graphql/graphql-js?branch=master) +[![Coverage Status](https://coveralls.io/repos/graphql/graphql-js/badge.svg?branch=master)](https://coveralls.io/r/graphql/graphql-js?branch=master) + +See more complete documentation at http://graphql.org/ and +http://graphql.org/graphql-js/. + +Looking for help? Find resources [from the community](http://graphql.org/community/). + + +## Getting Started + +An overview of GraphQL in general is available in the +[README](https://github.com/facebook/graphql/blob/master/README.md) for the +[Specification for GraphQL](https://github.com/facebook/graphql). 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 yarn: + +```sh +yarn add graphql +``` + +or alternatively using npm: + +```sh +npm install --save 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 code base. + +```js +import { + graphql, + GraphQLSchema, + GraphQLObjectType, + GraphQLString +} from 'graphql'; + +var schema = new GraphQLSchema({ + query: new GraphQLObjectType({ + name: 'RootQueryType', + fields: { + hello: { + type: GraphQLString, + resolve() { + return 'world'; + } + } + } + }) +}); +``` + +This defines a simple schema with one type and one field, that resolves +to a fixed value. The `resolve` function can return a value, a promise, +or an array of promises. A more complex example is included in the top +level [tests](src/__tests__) directory. + +Then, serve the result of a query against that type schema. + +```js +var query = '{ hello }'; + +graphql(schema, query).then(result => { + + // Prints + // { + // data: { hello: "world" } + // } + console.log(result); + +}); +``` + +This runs a query fetching the one field defined. The `graphql` function will +first ensure the query is syntactically and semantically valid before executing +it, reporting errors otherwise. + +```js +var query = '{ boyhowdy }'; + +graphql(schema, query).then(result => { + + // Prints + // { + // errors: [ + // { message: 'Cannot query field boyhowdy on RootQueryType', + // locations: [ { line: 1, column: 3 } ] } + // ] + // } + console.log(result); + +}); +``` + +### Want to ride the bleeding edge? + +The `npm` branch in this repository is automatically maintained to be the last +commit to `master` to pass all tests, in the same form found on npm. It is +recommended to use builds deployed to npm for many reasons, but if you want to use +the latest not-yet-released version of graphql-js, you can do so by depending +directly on this branch: + +``` +npm install graphql@git://github.com/graphql/graphql-js.git#npm +``` + +### 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](https://github.com/graphql/graphql-js/blob/master/.github/CONTRIBUTING.md). + +### Changelog + +Changes are tracked as [GitHub releases](https://github.com/graphql/graphql-js/releases). + +### License + +GraphQL.js is [MIT-licensed](https://github.com/graphql/graphql-js/blob/master/LICENSE). diff --git a/node_modules/graphql/error/GraphQLError.js b/node_modules/graphql/error/GraphQLError.js new file mode 100644 index 0000000..f9d5347 --- /dev/null +++ b/node_modules/graphql/error/GraphQLError.js @@ -0,0 +1,146 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GraphQLError = GraphQLError; + +var _printError = require("./printError"); + +var _location = require("../language/location"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function GraphQLError( // eslint-disable-line no-redeclare +message, nodes, source, positions, path, originalError, extensions) { + // Compute list of blame nodes. + var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions. + + + var _source = source; + + if (!_source && _nodes) { + var node = _nodes[0]; + _source = node && node.loc && node.loc.source; + } + + var _positions = positions; + + if (!_positions && _nodes) { + _positions = _nodes.reduce(function (list, node) { + if (node.loc) { + list.push(node.loc.start); + } + + return list; + }, []); + } + + if (_positions && _positions.length === 0) { + _positions = undefined; + } + + var _locations; + + if (positions && source) { + _locations = positions.map(function (pos) { + return (0, _location.getLocation)(source, pos); + }); + } else if (_nodes) { + _locations = _nodes.reduce(function (list, node) { + if (node.loc) { + list.push((0, _location.getLocation)(node.loc.source, node.loc.start)); + } + + return list; + }, []); + } + + var _extensions = extensions || originalError && originalError.extensions; + + Object.defineProperties(this, { + message: { + value: message, + // By being enumerable, JSON.stringify will include `message` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: true, + writable: true + }, + locations: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _locations || undefined, + // By being enumerable, JSON.stringify will include `locations` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_locations) + }, + path: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: path || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(path) + }, + nodes: { + value: _nodes || undefined + }, + source: { + value: _source || undefined + }, + positions: { + value: _positions || undefined + }, + originalError: { + value: originalError + }, + extensions: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _extensions || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_extensions) + } + }); // Include (non-enumerable) stack trace. + + if (originalError && 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 + }); + } +} + +GraphQLError.prototype = Object.create(Error.prototype, { + constructor: { + value: GraphQLError + }, + name: { + value: 'GraphQLError' + }, + toString: { + value: function toString() { + return (0, _printError.printError)(this); + } + } +}); \ No newline at end of file diff --git a/node_modules/graphql/error/GraphQLError.js.flow b/node_modules/graphql/error/GraphQLError.js.flow new file mode 100644 index 0000000..89e540e --- /dev/null +++ b/node_modules/graphql/error/GraphQLError.js.flow @@ -0,0 +1,220 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { printError } from './printError'; +import { getLocation } from '../language/location'; +import type { SourceLocation } from '../language/location'; +import type { ASTNode } from '../language/ast'; +import type { Source } from '../language/source'; + +/** + * 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. + */ +declare class GraphQLError extends Error { + constructor( + message: string, + nodes?: $ReadOnlyArray | ASTNode | void, + source?: ?Source, + positions?: ?$ReadOnlyArray, + path?: ?$ReadOnlyArray, + originalError?: ?Error, + extensions?: ?{ [key: string]: mixed }, + ): void; + + /** + * A message describing the Error for debugging purposes. + * + * Enumerable, and appears in the result of JSON.stringify(). + * + * Note: should be treated as readonly, despite invariant usage. + */ + message: string; + + /** + * An array of { line, column } locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + +locations: $ReadOnlyArray | void; + + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + +path: $ReadOnlyArray | void; + + /** + * An array of GraphQL AST Nodes corresponding to this error. + */ + +nodes: $ReadOnlyArray | void; + + /** + * The source GraphQL document for the first location of this error. + * + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. + */ + +source: Source | void; + + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + +positions: $ReadOnlyArray | void; + + /** + * The original error thrown from a field resolver during execution. + */ + +originalError: ?Error; + + /** + * Extension fields to add to the formatted error. + */ + +extensions: { [key: string]: mixed } | void; +} + +export function GraphQLError( // eslint-disable-line no-redeclare + message: string, + nodes?: $ReadOnlyArray | ASTNode | void, + source?: ?Source, + positions?: ?$ReadOnlyArray, + path?: ?$ReadOnlyArray, + originalError?: ?Error & { +extensions: mixed }, + extensions?: ?{ [key: string]: mixed }, +) { + // Compute list of blame nodes. + const _nodes = Array.isArray(nodes) + ? nodes.length !== 0 + ? nodes + : undefined + : nodes + ? [nodes] + : undefined; + + // Compute locations in the source for the given nodes/positions. + let _source = source; + if (!_source && _nodes) { + const node = _nodes[0]; + _source = node && node.loc && node.loc.source; + } + + let _positions = positions; + if (!_positions && _nodes) { + _positions = _nodes.reduce((list, node) => { + if (node.loc) { + list.push(node.loc.start); + } + return list; + }, []); + } + if (_positions && _positions.length === 0) { + _positions = undefined; + } + + let _locations; + if (positions && source) { + _locations = positions.map(pos => getLocation(source, pos)); + } else if (_nodes) { + _locations = _nodes.reduce((list, node) => { + if (node.loc) { + list.push(getLocation(node.loc.source, node.loc.start)); + } + return list; + }, []); + } + + const _extensions = extensions || (originalError && originalError.extensions); + + Object.defineProperties(this, { + message: { + value: message, + // By being enumerable, JSON.stringify will include `message` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: true, + writable: true, + }, + locations: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _locations || undefined, + // By being enumerable, JSON.stringify will include `locations` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_locations), + }, + path: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: path || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(path), + }, + nodes: { + value: _nodes || undefined, + }, + source: { + value: _source || undefined, + }, + positions: { + value: _positions || undefined, + }, + originalError: { + value: originalError, + }, + extensions: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _extensions || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_extensions), + }, + }); + + // Include (non-enumerable) stack trace. + if (originalError && 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, + }); + } +} + +(GraphQLError: any).prototype = Object.create(Error.prototype, { + constructor: { value: GraphQLError }, + name: { value: 'GraphQLError' }, + toString: { + value: function toString() { + return printError(this); + }, + }, +}); diff --git a/node_modules/graphql/error/GraphQLError.mjs b/node_modules/graphql/error/GraphQLError.mjs new file mode 100644 index 0000000..ac55ab1 --- /dev/null +++ b/node_modules/graphql/error/GraphQLError.mjs @@ -0,0 +1,136 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { printError } from './printError'; +import { getLocation } from '../language/location'; +export function GraphQLError( // eslint-disable-line no-redeclare +message, nodes, source, positions, path, originalError, extensions) { + // Compute list of blame nodes. + var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions. + + + var _source = source; + + if (!_source && _nodes) { + var node = _nodes[0]; + _source = node && node.loc && node.loc.source; + } + + var _positions = positions; + + if (!_positions && _nodes) { + _positions = _nodes.reduce(function (list, node) { + if (node.loc) { + list.push(node.loc.start); + } + + return list; + }, []); + } + + if (_positions && _positions.length === 0) { + _positions = undefined; + } + + var _locations; + + if (positions && source) { + _locations = positions.map(function (pos) { + return getLocation(source, pos); + }); + } else if (_nodes) { + _locations = _nodes.reduce(function (list, node) { + if (node.loc) { + list.push(getLocation(node.loc.source, node.loc.start)); + } + + return list; + }, []); + } + + var _extensions = extensions || originalError && originalError.extensions; + + Object.defineProperties(this, { + message: { + value: message, + // By being enumerable, JSON.stringify will include `message` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: true, + writable: true + }, + locations: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _locations || undefined, + // By being enumerable, JSON.stringify will include `locations` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_locations) + }, + path: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: path || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(path) + }, + nodes: { + value: _nodes || undefined + }, + source: { + value: _source || undefined + }, + positions: { + value: _positions || undefined + }, + originalError: { + value: originalError + }, + extensions: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _extensions || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_extensions) + } + }); // Include (non-enumerable) stack trace. + + if (originalError && 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 + }); + } +} +GraphQLError.prototype = Object.create(Error.prototype, { + constructor: { + value: GraphQLError + }, + name: { + value: 'GraphQLError' + }, + toString: { + value: function toString() { + return printError(this); + } + } +}); \ No newline at end of file diff --git a/node_modules/graphql/error/formatError.js b/node_modules/graphql/error/formatError.js new file mode 100644 index 0000000..1ccb5ad --- /dev/null +++ b/node_modules/graphql/error/formatError.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.formatError = formatError; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +function formatError(error) { + !error ? (0, _invariant.default)(0, 'Received null or undefined error.') : void 0; + var message = error.message || 'An unknown error occurred.'; + var locations = error.locations; + var path = error.path; + var extensions = error.extensions; + return extensions ? { + message: message, + locations: locations, + path: path, + extensions: extensions + } : { + message: message, + locations: locations, + path: path + }; +} \ No newline at end of file diff --git a/node_modules/graphql/error/formatError.js.flow b/node_modules/graphql/error/formatError.js.flow new file mode 100644 index 0000000..a671812 --- /dev/null +++ b/node_modules/graphql/error/formatError.js.flow @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import type { GraphQLError } from './GraphQLError'; +import type { SourceLocation } from '../language/location'; + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +export function formatError(error: GraphQLError): GraphQLFormattedError { + invariant(error, 'Received null or undefined error.'); + const message = error.message || 'An unknown error occurred.'; + const locations = error.locations; + const path = error.path; + const extensions = error.extensions; + + return extensions + ? { message, locations, path, extensions } + : { message, locations, path }; +} + +export type GraphQLFormattedError = {| + +message: string, + +locations: $ReadOnlyArray | void, + +path: $ReadOnlyArray | void, + +extensions?: { [key: string]: mixed }, +|}; diff --git a/node_modules/graphql/error/formatError.mjs b/node_modules/graphql/error/formatError.mjs new file mode 100644 index 0000000..a83bea6 --- /dev/null +++ b/node_modules/graphql/error/formatError.mjs @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +export function formatError(error) { + !error ? invariant(0, 'Received null or undefined error.') : void 0; + var message = error.message || 'An unknown error occurred.'; + var locations = error.locations; + var path = error.path; + var extensions = error.extensions; + return extensions ? { + message: message, + locations: locations, + path: path, + extensions: extensions + } : { + message: message, + locations: locations, + path: path + }; +} \ No newline at end of file diff --git a/node_modules/graphql/error/index.js b/node_modules/graphql/error/index.js new file mode 100644 index 0000000..94939e8 --- /dev/null +++ b/node_modules/graphql/error/index.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "GraphQLError", { + enumerable: true, + get: function get() { + return _GraphQLError.GraphQLError; + } +}); +Object.defineProperty(exports, "syntaxError", { + enumerable: true, + get: function get() { + return _syntaxError.syntaxError; + } +}); +Object.defineProperty(exports, "locatedError", { + enumerable: true, + get: function get() { + return _locatedError.locatedError; + } +}); +Object.defineProperty(exports, "printError", { + enumerable: true, + get: function get() { + return _printError.printError; + } +}); +Object.defineProperty(exports, "formatError", { + enumerable: true, + get: function get() { + return _formatError.formatError; + } +}); + +var _GraphQLError = require("./GraphQLError"); + +var _syntaxError = require("./syntaxError"); + +var _locatedError = require("./locatedError"); + +var _printError = require("./printError"); + +var _formatError = require("./formatError"); \ No newline at end of file diff --git a/node_modules/graphql/error/index.js.flow b/node_modules/graphql/error/index.js.flow new file mode 100644 index 0000000..3ca6fdb --- /dev/null +++ b/node_modules/graphql/error/index.js.flow @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { GraphQLError } from './GraphQLError'; +export { syntaxError } from './syntaxError'; +export { locatedError } from './locatedError'; +export { printError } from './printError'; +export { formatError } from './formatError'; + +export type { GraphQLFormattedError } from './formatError'; diff --git a/node_modules/graphql/error/index.mjs b/node_modules/graphql/error/index.mjs new file mode 100644 index 0000000..2a23479 --- /dev/null +++ b/node_modules/graphql/error/index.mjs @@ -0,0 +1,13 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { GraphQLError } from './GraphQLError'; +export { syntaxError } from './syntaxError'; +export { locatedError } from './locatedError'; +export { printError } from './printError'; +export { formatError } from './formatError'; \ No newline at end of file diff --git a/node_modules/graphql/error/locatedError.js b/node_modules/graphql/error/locatedError.js new file mode 100644 index 0000000..07a0b8f --- /dev/null +++ b/node_modules/graphql/error/locatedError.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.locatedError = locatedError; + +var _GraphQLError = require("./GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given an arbitrary Error, 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(originalError, nodes, path) { + // Note: this uses a brand-check to support GraphQL errors originating from + // other contexts. + if (originalError && Array.isArray(originalError.path)) { + return originalError; + } + + return new _GraphQLError.GraphQLError(originalError && originalError.message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError); +} \ No newline at end of file diff --git a/node_modules/graphql/error/locatedError.js.flow b/node_modules/graphql/error/locatedError.js.flow new file mode 100644 index 0000000..0f49516 --- /dev/null +++ b/node_modules/graphql/error/locatedError.js.flow @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { GraphQLError } from './GraphQLError'; +import type { ASTNode } from '../language/ast'; + +/** + * Given an arbitrary Error, 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( + originalError: Error | GraphQLError, + nodes: $ReadOnlyArray, + path: $ReadOnlyArray, +): GraphQLError { + // Note: this uses a brand-check to support GraphQL errors originating from + // other contexts. + if (originalError && Array.isArray(originalError.path)) { + return (originalError: any); + } + + return new GraphQLError( + originalError && originalError.message, + (originalError && (originalError: any).nodes) || nodes, + originalError && (originalError: any).source, + originalError && (originalError: any).positions, + path, + originalError, + ); +} diff --git a/node_modules/graphql/error/locatedError.mjs b/node_modules/graphql/error/locatedError.mjs new file mode 100644 index 0000000..67a0a3f --- /dev/null +++ b/node_modules/graphql/error/locatedError.mjs @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from './GraphQLError'; + +/** + * Given an arbitrary Error, 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(originalError, nodes, path) { + // Note: this uses a brand-check to support GraphQL errors originating from + // other contexts. + if (originalError && Array.isArray(originalError.path)) { + return originalError; + } + + return new GraphQLError(originalError && originalError.message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError); +} \ No newline at end of file diff --git a/node_modules/graphql/error/printError.js b/node_modules/graphql/error/printError.js new file mode 100644 index 0000000..80b7ed8 --- /dev/null +++ b/node_modules/graphql/error/printError.js @@ -0,0 +1,146 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.printError = printError; + +var _location = require("../language/location"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + */ +function printError(error) { + var printedLocations = []; + + if (error.nodes) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = error.nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var node = _step.value; + + if (node.loc) { + printedLocations.push(highlightSourceAtLocation(node.loc.source, (0, _location.getLocation)(node.loc.source, node.loc.start))); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else if (error.source && error.locations) { + var source = error.source; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = error.locations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var location = _step2.value; + printedLocations.push(highlightSourceAtLocation(source, location)); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + return printedLocations.length === 0 ? error.message : [error.message].concat(printedLocations).join('\n\n') + '\n'; +} +/** + * Render a helpful description of the location of the error in the GraphQL + * Source document. + */ + + +function highlightSourceAtLocation(source, location) { + var firstLineColumnOffset = source.locationOffset.column - 1; + var body = whitespace(firstLineColumnOffset) + source.body; + var lineIndex = location.line - 1; + var lineOffset = source.locationOffset.line - 1; + var lineNum = location.line + lineOffset; + var columnOffset = location.line === 1 ? firstLineColumnOffset : 0; + var columnNum = location.column + columnOffset; + var lines = body.split(/\r\n|[\n\r]/g); + return "".concat(source.name, " (").concat(lineNum, ":").concat(columnNum, ")\n") + printPrefixedLines([// Lines specified like this: ["prefix", "string"], + ["".concat(lineNum - 1, ": "), lines[lineIndex - 1]], ["".concat(lineNum, ": "), lines[lineIndex]], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1, ": "), lines[lineIndex + 1]]]); +} + +function printPrefixedLines(lines) { + var existingLines = lines.filter(function (_ref) { + var _ = _ref[0], + line = _ref[1]; + return line !== undefined; + }); + var padLen = 0; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = existingLines[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _ref4 = _step3.value; + var prefix = _ref4[0]; + padLen = Math.max(padLen, prefix.length); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return existingLines.map(function (_ref3) { + var prefix = _ref3[0], + line = _ref3[1]; + return lpad(padLen, prefix) + line; + }).join('\n'); +} + +function whitespace(len) { + return Array(len + 1).join(' '); +} + +function lpad(len, str) { + return whitespace(len - str.length) + str; +} \ No newline at end of file diff --git a/node_modules/graphql/error/printError.js.flow b/node_modules/graphql/error/printError.js.flow new file mode 100644 index 0000000..9012640 --- /dev/null +++ b/node_modules/graphql/error/printError.js.flow @@ -0,0 +1,93 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { getLocation } from '../language/location'; +import type { SourceLocation } from '../language/location'; +import type { Source } from '../language/source'; +import type { GraphQLError } from './GraphQLError'; + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + */ +export function printError(error: GraphQLError): string { + const printedLocations = []; + if (error.nodes) { + for (const node of error.nodes) { + if (node.loc) { + printedLocations.push( + highlightSourceAtLocation( + node.loc.source, + getLocation(node.loc.source, node.loc.start), + ), + ); + } + } + } else if (error.source && error.locations) { + const source = error.source; + for (const location of error.locations) { + printedLocations.push(highlightSourceAtLocation(source, location)); + } + } + return printedLocations.length === 0 + ? error.message + : [error.message, ...printedLocations].join('\n\n') + '\n'; +} + +/** + * Render a helpful description of the location of the error in the GraphQL + * Source document. + */ +function highlightSourceAtLocation( + source: Source, + location: SourceLocation, +): string { + const firstLineColumnOffset = source.locationOffset.column - 1; + const body = whitespace(firstLineColumnOffset) + source.body; + + const lineIndex = location.line - 1; + const lineOffset = source.locationOffset.line - 1; + const lineNum = location.line + lineOffset; + + const columnOffset = location.line === 1 ? firstLineColumnOffset : 0; + const columnNum = location.column + columnOffset; + + const lines = body.split(/\r\n|[\n\r]/g); + return ( + `${source.name} (${lineNum}:${columnNum})\n` + + printPrefixedLines([ + // Lines specified like this: ["prefix", "string"], + [`${lineNum - 1}: `, lines[lineIndex - 1]], + [`${lineNum}: `, lines[lineIndex]], + ['', whitespace(columnNum - 1) + '^'], + [`${lineNum + 1}: `, lines[lineIndex + 1]], + ]) + ); +} + +function printPrefixedLines(lines: Array<[string, string]>): string { + const existingLines = lines.filter(([_, line]) => line !== undefined); + + let padLen = 0; + for (const [prefix] of existingLines) { + padLen = Math.max(padLen, prefix.length); + } + + return existingLines + .map(([prefix, line]) => lpad(padLen, prefix) + line) + .join('\n'); +} + +function whitespace(len: number): string { + return Array(len + 1).join(' '); +} + +function lpad(len: number, str: string): string { + return whitespace(len - str.length) + str; +} diff --git a/node_modules/graphql/error/printError.mjs b/node_modules/graphql/error/printError.mjs new file mode 100644 index 0000000..a65d873 --- /dev/null +++ b/node_modules/graphql/error/printError.mjs @@ -0,0 +1,137 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { getLocation } from '../language/location'; + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + */ +export function printError(error) { + var printedLocations = []; + + if (error.nodes) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = error.nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var node = _step.value; + + if (node.loc) { + printedLocations.push(highlightSourceAtLocation(node.loc.source, getLocation(node.loc.source, node.loc.start))); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else if (error.source && error.locations) { + var source = error.source; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = error.locations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var location = _step2.value; + printedLocations.push(highlightSourceAtLocation(source, location)); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + return printedLocations.length === 0 ? error.message : [error.message].concat(printedLocations).join('\n\n') + '\n'; +} +/** + * Render a helpful description of the location of the error in the GraphQL + * Source document. + */ + +function highlightSourceAtLocation(source, location) { + var firstLineColumnOffset = source.locationOffset.column - 1; + var body = whitespace(firstLineColumnOffset) + source.body; + var lineIndex = location.line - 1; + var lineOffset = source.locationOffset.line - 1; + var lineNum = location.line + lineOffset; + var columnOffset = location.line === 1 ? firstLineColumnOffset : 0; + var columnNum = location.column + columnOffset; + var lines = body.split(/\r\n|[\n\r]/g); + return "".concat(source.name, " (").concat(lineNum, ":").concat(columnNum, ")\n") + printPrefixedLines([// Lines specified like this: ["prefix", "string"], + ["".concat(lineNum - 1, ": "), lines[lineIndex - 1]], ["".concat(lineNum, ": "), lines[lineIndex]], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1, ": "), lines[lineIndex + 1]]]); +} + +function printPrefixedLines(lines) { + var existingLines = lines.filter(function (_ref) { + var _ = _ref[0], + line = _ref[1]; + return line !== undefined; + }); + var padLen = 0; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = existingLines[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _ref4 = _step3.value; + var prefix = _ref4[0]; + padLen = Math.max(padLen, prefix.length); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return existingLines.map(function (_ref3) { + var prefix = _ref3[0], + line = _ref3[1]; + return lpad(padLen, prefix) + line; + }).join('\n'); +} + +function whitespace(len) { + return Array(len + 1).join(' '); +} + +function lpad(len, str) { + return whitespace(len - str.length) + str; +} \ No newline at end of file diff --git a/node_modules/graphql/error/syntaxError.js b/node_modules/graphql/error/syntaxError.js new file mode 100644 index 0000000..412f6d3 --- /dev/null +++ b/node_modules/graphql/error/syntaxError.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.syntaxError = syntaxError; + +var _GraphQLError = require("./GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ +function syntaxError(source, position, description) { + return new _GraphQLError.GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]); +} \ No newline at end of file diff --git a/node_modules/graphql/error/syntaxError.js.flow b/node_modules/graphql/error/syntaxError.js.flow new file mode 100644 index 0000000..6409f40 --- /dev/null +++ b/node_modules/graphql/error/syntaxError.js.flow @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { Source } from '../language/source'; +import { GraphQLError } from './GraphQLError'; + +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ +export function syntaxError( + source: Source, + position: number, + description: string, +): GraphQLError { + return new GraphQLError(`Syntax Error: ${description}`, undefined, source, [ + position, + ]); +} diff --git a/node_modules/graphql/error/syntaxError.mjs b/node_modules/graphql/error/syntaxError.mjs new file mode 100644 index 0000000..c7fe5dc --- /dev/null +++ b/node_modules/graphql/error/syntaxError.mjs @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from './GraphQLError'; +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ + +export function syntaxError(source, position, description) { + return new GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]); +} \ No newline at end of file diff --git a/node_modules/graphql/execution/execute.js b/node_modules/graphql/execution/execute.js new file mode 100644 index 0000000..e333064 --- /dev/null +++ b/node_modules/graphql/execution/execute.js @@ -0,0 +1,831 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.execute = execute; +exports.responsePathAsArray = responsePathAsArray; +exports.addPath = addPath; +exports.assertValidExecutionArguments = assertValidExecutionArguments; +exports.buildExecutionContext = buildExecutionContext; +exports.collectFields = collectFields; +exports.buildResolveInfo = buildResolveInfo; +exports.resolveFieldValueOrError = resolveFieldValueOrError; +exports.getFieldDef = getFieldDef; +exports.defaultFieldResolver = void 0; + +var _iterall = require("iterall"); + +var _GraphQLError = require("../error/GraphQLError"); + +var _locatedError = require("../error/locatedError"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _isNullish = _interopRequireDefault(require("../jsutils/isNullish")); + +var _isPromise = _interopRequireDefault(require("../jsutils/isPromise")); + +var _memoize = _interopRequireDefault(require("../jsutils/memoize3")); + +var _promiseForObject = _interopRequireDefault(require("../jsutils/promiseForObject")); + +var _promiseReduce = _interopRequireDefault(require("../jsutils/promiseReduce")); + +var _getOperationRootType = require("../utilities/getOperationRootType"); + +var _typeFromAST = require("../utilities/typeFromAST"); + +var _kinds = require("../language/kinds"); + +var _values = require("./values"); + +var _definition = require("../type/definition"); + +var _introspection = require("../type/introspection"); + +var _directives = require("../type/directives"); + +var _validate = require("../type/validate"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? executeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : executeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); +} + +function executeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // If arguments are missing or incorrect, throw an error. + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed. + + if (Array.isArray(exeContext)) { + return { + errors: exeContext + }; + } // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + + + var data = executeOperation(exeContext, exeContext.operation, rootValue); + return buildResponse(exeContext, data); +} +/** + * Given a completed execution context and data, build the { errors, data } + * response defined by the "Response" section of the GraphQL specification. + */ + + +function buildResponse(exeContext, data) { + if ((0, _isPromise.default)(data)) { + return data.then(function (resolved) { + return buildResponse(exeContext, resolved); + }); + } + + return exeContext.errors.length === 0 ? { + data: data + } : { + errors: exeContext.errors, + data: data + }; +} +/** + * Given a ResponsePath (found in the `path` entry in the information provided + * as the last argument to a field resolver), return an Array of the path keys. + */ + + +function responsePathAsArray(path) { + var flattened = []; + var curr = path; + + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + + return flattened.reverse(); +} +/** + * Given a ResponsePath and a key, return a new ResponsePath containing the + * new key. + */ + + +function addPath(prev, key) { + return { + prev: prev, + key: key + }; +} +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + */ + + +function assertValidExecutionArguments(schema, document, rawVariableValues) { + !document ? (0, _invariant.default)(0, 'Must provide document') : void 0; // If the schema used for execution is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object. + + !(!rawVariableValues || _typeof(rawVariableValues) === 'object') ? (0, _invariant.default)(0, 'Variables must be provided as an Object where each property is a ' + 'variable value. Perhaps look to see if an unparsed JSON string ' + 'was provided.') : void 0; +} +/** + * 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. + */ + + +function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver) { + var errors = []; + var operation; + var hasMultipleAssumedOperations = false; + var fragments = Object.create(null); + + for (var i = 0; i < document.definitions.length; i++) { + var definition = document.definitions[i]; + + switch (definition.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + if (!operationName && operation) { + hasMultipleAssumedOperations = true; + } else if (!operationName || definition.name && definition.name.value === operationName) { + operation = definition; + } + + break; + + case _kinds.Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + } + } + + if (!operation) { + if (operationName) { + errors.push(new _GraphQLError.GraphQLError("Unknown operation named \"".concat(operationName, "\"."))); + } else { + errors.push(new _GraphQLError.GraphQLError('Must provide an operation.')); + } + } else if (hasMultipleAssumedOperations) { + errors.push(new _GraphQLError.GraphQLError('Must provide operation name if query contains multiple operations.')); + } + + var variableValues; + + if (operation) { + var coercedVariableValues = (0, _values.getVariableValues)(schema, operation.variableDefinitions || [], rawVariableValues || {}); + + if (coercedVariableValues.errors) { + errors.push.apply(errors, coercedVariableValues.errors); + } else { + variableValues = coercedVariableValues.coerced; + } + } + + if (errors.length !== 0) { + return errors; + } + + !operation ? (0, _invariant.default)(0, 'Has operation if no errors.') : void 0; + !variableValues ? (0, _invariant.default)(0, 'Has variables if no errors.') : void 0; + return { + schema: schema, + fragments: fragments, + rootValue: rootValue, + contextValue: contextValue, + operation: operation, + variableValues: variableValues, + fieldResolver: fieldResolver || defaultFieldResolver, + errors: errors + }; +} +/** + * Implements the "Evaluating operations" section of the spec. + */ + + +function executeOperation(exeContext, operation, rootValue) { + var type = (0, _getOperationRootType.getOperationRootType)(exeContext.schema, operation); + var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null)); + var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. + // + // Similar to completeValueCatchingError. + + try { + var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields); + + if ((0, _isPromise.default)(result)) { + return result.then(undefined, function (error) { + exeContext.errors.push(error); + return Promise.resolve(null); + }); + } + + return result; + } catch (error) { + exeContext.errors.push(error); + return null; + } +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "write" mode. + */ + + +function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { + return (0, _promiseReduce.default)(Object.keys(fields), function (results, responseName) { + var fieldNodes = fields[responseName]; + var fieldPath = addPath(path, responseName); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result === undefined) { + return results; + } + + if ((0, _isPromise.default)(result)) { + return result.then(function (resolvedResult) { + results[responseName] = resolvedResult; + return results; + }); + } + + results[responseName] = result; + return results; + }, Object.create(null)); +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "read" mode. + */ + + +function executeFields(exeContext, parentType, sourceValue, path, fields) { + var results = Object.create(null); + var containsPromise = false; + + for (var i = 0, keys = Object.keys(fields); i < keys.length; ++i) { + var responseName = keys[i]; + var fieldNodes = fields[responseName]; + var fieldPath = addPath(path, responseName); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result !== undefined) { + results[responseName] = result; + + if (!containsPromise && (0, _isPromise.default)(result)) { + containsPromise = true; + } + } + } // If there are no promises, we can just return the object + + + if (!containsPromise) { + return results; + } // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + + + return (0, _promiseForObject.default)(results); +} +/** + * Given a selectionSet, adds all of the fields in that selection to + * the passed in map of fields, and returns it at the end. + * + * CollectFields requires the "runtime type" of an object. For a field which + * returns an Interface or Union type, the "runtime type" will be the actual + * Object type returned by that field. + */ + + +function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) { + for (var i = 0; i < selectionSet.selections.length; i++) { + var selection = selectionSet.selections[i]; + + switch (selection.kind) { + case _kinds.Kind.FIELD: + if (!shouldIncludeNode(exeContext, selection)) { + continue; + } + + var name = getFieldEntryKey(selection); + + if (!fields[name]) { + fields[name] = []; + } + + fields[name].push(selection); + break; + + case _kinds.Kind.INLINE_FRAGMENT: + if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames); + break; + + case _kinds.Kind.FRAGMENT_SPREAD: + var fragName = selection.name.value; + + if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) { + continue; + } + + visitedFragmentNames[fragName] = true; + var fragment = exeContext.fragments[fragName]; + + if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames); + break; + } + } + + return fields; +} +/** + * Determines if a field should be included based on the @include and @skip + * directives, where @skip has higher precedence than @include. + */ + + +function shouldIncludeNode(exeContext, node) { + var skip = (0, _values.getDirectiveValues)(_directives.GraphQLSkipDirective, node, exeContext.variableValues); + + if (skip && skip.if === true) { + return false; + } + + var include = (0, _values.getDirectiveValues)(_directives.GraphQLIncludeDirective, node, exeContext.variableValues); + + if (include && include.if === false) { + return false; + } + + return true; +} +/** + * Determines if a fragment is applicable to the given type. + */ + + +function doesFragmentConditionMatch(exeContext, fragment, type) { + var typeConditionNode = fragment.typeCondition; + + if (!typeConditionNode) { + return true; + } + + var conditionalType = (0, _typeFromAST.typeFromAST)(exeContext.schema, typeConditionNode); + + if (conditionalType === type) { + return true; + } + + if ((0, _definition.isAbstractType)(conditionalType)) { + return exeContext.schema.isPossibleType(conditionalType, type); + } + + return false; +} +/** + * Implements the logic to compute the key of a given field's entry + */ + + +function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; +} +/** + * Resolves the field on the given source object. In particular, this + * figures out the value that the field returns by calling its resolve function, + * then calls completeValue to complete promises, serialize scalars, or execute + * the sub-selection-set for objects. + */ + + +function resolveField(exeContext, parentType, source, fieldNodes, path) { + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName); + + if (!fieldDef) { + return; + } + + var resolveFn = fieldDef.resolve || exeContext.fieldResolver; + var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal + // or abrupt (error). + + var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info); + return completeValueCatchingError(exeContext, fieldDef.type, fieldNodes, info, path, result); +} + +function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes: fieldNodes, + returnType: fieldDef.type, + parentType: parentType, + path: path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues + }; +} // Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField` +// function. Returns the result of resolveFn or the abrupt-return Error object. + + +function resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info) { + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + var args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + var _contextValue = exeContext.contextValue; + var result = resolveFn(source, args, _contextValue, info); + return (0, _isPromise.default)(result) ? result.then(undefined, asErrorInstance) : result; + } catch (error) { + return asErrorInstance(error); + } +} // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a +// consistent Error interface. + + +function asErrorInstance(error) { + return error instanceof Error ? error : new Error(error || undefined); +} // This is a small wrapper around completeValue which detects and logs errors +// in the execution context. + + +function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) { + try { + var completed; + + if ((0, _isPromise.default)(result)) { + completed = result.then(function (resolved) { + return completeValue(exeContext, returnType, fieldNodes, info, path, resolved); + }); + } else { + completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); + } + + if ((0, _isPromise.default)(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, function (error) { + return handleFieldError(error, fieldNodes, path, returnType, exeContext); + }); + } + + return completed; + } catch (error) { + return handleFieldError(error, fieldNodes, path, returnType, exeContext); + } +} + +function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) { + var error = (0, _locatedError.locatedError)(asErrorInstance(rawError), fieldNodes, responsePathAsArray(path)); // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + + if ((0, _definition.isNonNullType)(returnType)) { + throw error; + } // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + + + exeContext.errors.push(error); + return null; +} +/** + * Implements the instructions for completeValue as defined in the + * "Field entries" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by evaluating all sub-selections. + */ + + +function completeValue(exeContext, returnType, fieldNodes, info, path, result) { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + + + if ((0, _definition.isNonNullType)(returnType)) { + var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); + + if (completed === null) { + throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")); + } + + return completed; + } // If result value is null-ish (null, undefined, or NaN) then return null. + + + if ((0, _isNullish.default)(result)) { + return null; + } // If field type is List, complete each item in the list with the inner type + + + if ((0, _definition.isListType)(returnType)) { + return completeListValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + + + if ((0, _definition.isLeafType)(returnType)) { + return completeLeafValue(returnType, result); + } // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + + + if ((0, _definition.isAbstractType)(returnType)) { + return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is Object, execute and complete all sub-selections. + + + if ((0, _definition.isObjectType)(returnType)) { + return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); + } // Not reachable. All possible output types have been considered. + + /* istanbul ignore next */ + + + throw new Error("Cannot complete value of unexpected type \"".concat((0, _inspect.default)(returnType), "\".")); +} +/** + * Complete a list value by completing each item in the list with the + * inner type + */ + + +function completeListValue(exeContext, returnType, fieldNodes, info, path, result) { + !(0, _iterall.isCollection)(result) ? (0, _invariant.default)(0, "Expected Iterable, but did not find one for field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")) : void 0; // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + + var itemType = returnType.ofType; + var containsPromise = false; + var completedResults = []; + (0, _iterall.forEach)(result, function (item, index) { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + var fieldPath = addPath(path, index); + var completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item); + + if (!containsPromise && (0, _isPromise.default)(completedItem)) { + containsPromise = true; + } + + completedResults.push(completedItem); + }); + return containsPromise ? Promise.all(completedResults) : completedResults; +} +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ + + +function completeLeafValue(returnType, result) { + !returnType.serialize ? (0, _invariant.default)(0, 'Missing serialize method on type') : void 0; + var serializedResult = returnType.serialize(result); + + if ((0, _isInvalid.default)(serializedResult)) { + throw new Error("Expected a value of type \"".concat((0, _inspect.default)(returnType), "\" but ") + "received: ".concat((0, _inspect.default)(result))); + } + + return serializedResult; +} +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ + + +function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) { + var runtimeType = returnType.resolveType ? returnType.resolveType(result, exeContext.contextValue, info) : defaultResolveTypeFn(result, exeContext.contextValue, info, returnType); + + if ((0, _isPromise.default)(runtimeType)) { + return runtimeType.then(function (resolvedRuntimeType) { + return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); + }); + } + + return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); +} + +function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) { + var runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName; + + if (!(0, _definition.isObjectType)(runtimeType)) { + throw new _GraphQLError.GraphQLError("Abstract type ".concat(returnType.name, " must resolve to an Object type at ") + "runtime for field ".concat(info.parentType.name, ".").concat(info.fieldName, " with ") + "value ".concat((0, _inspect.default)(result), ", received \"").concat((0, _inspect.default)(runtimeType), "\". ") + "Either the ".concat(returnType.name, " type should provide a \"resolveType\" ") + 'function or each possible type should provide an "isTypeOf" function.', fieldNodes); + } + + if (!exeContext.schema.isPossibleType(returnType, runtimeType)) { + throw new _GraphQLError.GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type ") + "for \"".concat(returnType.name, "\"."), fieldNodes); + } + + return runtimeType; +} +/** + * Complete an Object value by executing all sub-selections. + */ + + +function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) { + // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + if (returnType.isTypeOf) { + var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + + if ((0, _isPromise.default)(isTypeOf)) { + return isTypeOf.then(function (resolvedIsTypeOf) { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); +} + +function invalidReturnTypeError(returnType, result, fieldNodes) { + return new _GraphQLError.GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat((0, _inspect.default)(result), "."), fieldNodes); +} + +function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) { + // Collect sub-fields to execute to complete this value. + var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ + + +var collectSubfields = (0, _memoize.default)(_collectSubfields); + +function _collectSubfields(exeContext, returnType, fieldNodes) { + var subFieldNodes = Object.create(null); + var visitedFragmentNames = Object.create(null); + + for (var i = 0; i < fieldNodes.length; i++) { + var selectionSet = fieldNodes[i].selectionSet; + + if (selectionSet) { + subFieldNodes = collectFields(exeContext, returnType, selectionSet, subFieldNodes, visitedFragmentNames); + } + } + + return subFieldNodes; +} +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ + + +function defaultResolveTypeFn(value, contextValue, info, abstractType) { + // First, look for `__typename`. + if (value !== null && _typeof(value) === 'object' && typeof value.__typename === 'string') { + return value.__typename; + } // Otherwise, test each possible type. + + + var possibleTypes = info.schema.getPossibleTypes(abstractType); + var promisedIsTypeOfResults = []; + + for (var i = 0; i < possibleTypes.length; i++) { + var type = possibleTypes[i]; + + if (type.isTypeOf) { + var isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if ((0, _isPromise.default)(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type; + } + } + } + + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) { + for (var _i = 0; _i < isTypeOfResults.length; _i++) { + if (isTypeOfResults[_i]) { + return possibleTypes[_i]; + } + } + }); + } +} +/** + * 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. + */ + + +var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) { + // ensure source is a value for which property access is acceptable. + if (_typeof(source) === 'object' || typeof source === 'function') { + var property = source[info.fieldName]; + + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + + return property; + } +}; +/** + * This method looks up the field on the given type definition. + * It has special casing for the two introspection fields, __schema + * and __typename. __typename is special because it can always be + * queried as a field, even in situations where no other fields + * are allowed, like on a Union. __schema could get automatically + * added to the query type, but that would require mutating type + * definitions, which would cause issues. + */ + + +exports.defaultFieldResolver = defaultFieldResolver; + +function getFieldDef(schema, parentType, fieldName) { + if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.SchemaMetaFieldDef; + } else if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.TypeMetaFieldDef; + } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) { + return _introspection.TypeNameMetaFieldDef; + } + + return parentType.getFields()[fieldName]; +} \ No newline at end of file diff --git a/node_modules/graphql/execution/execute.js.flow b/node_modules/graphql/execution/execute.js.flow new file mode 100644 index 0000000..f6f6144 --- /dev/null +++ b/node_modules/graphql/execution/execute.js.flow @@ -0,0 +1,1268 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { forEach, isCollection } from 'iterall'; +import { GraphQLError } from '../error/GraphQLError'; +import { locatedError } from '../error/locatedError'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import isInvalid from '../jsutils/isInvalid'; +import isNullish from '../jsutils/isNullish'; +import isPromise from '../jsutils/isPromise'; +import memoize3 from '../jsutils/memoize3'; +import promiseForObject from '../jsutils/promiseForObject'; +import promiseReduce from '../jsutils/promiseReduce'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { MaybePromise } from '../jsutils/MaybePromise'; + +import { getOperationRootType } from '../utilities/getOperationRootType'; +import { typeFromAST } from '../utilities/typeFromAST'; +import { Kind } from '../language/kinds'; +import { + getVariableValues, + getArgumentValues, + getDirectiveValues, +} from './values'; +import { + isObjectType, + isAbstractType, + isLeafType, + isListType, + isNonNullType, +} from '../type/definition'; +import type { + GraphQLObjectType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLAbstractType, + GraphQLField, + GraphQLFieldResolver, + GraphQLResolveInfo, + ResponsePath, + GraphQLList, +} from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; +import { + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from '../type/introspection'; +import { + GraphQLIncludeDirective, + GraphQLSkipDirective, +} from '../type/directives'; +import { assertValidSchema } from '../type/validate'; +import type { + DocumentNode, + OperationDefinitionNode, + SelectionSetNode, + FieldNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, +} from '../language/ast'; + +/** + * Terminology + * + * "Definitions" are the generic name for top-level statements in the document. + * Examples of this include: + * 1) Operations (such as a query) + * 2) Fragments + * + * "Operations" are a generic name for requests in the document. + * Examples of this include: + * 1) query, + * 2) mutation + * + * "Selections" are the definitions that can appear legally and at + * single level of the query. These include: + * 1) field references e.g "a" + * 2) fragment "spreads" e.g. "...c" + * 3) inline fragment "spreads" e.g. "...on Type { a }" + */ + +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + */ +export type ExecutionContext = {| + schema: GraphQLSchema, + fragments: ObjMap, + rootValue: mixed, + contextValue: mixed, + operation: OperationDefinitionNode, + variableValues: { [variable: string]: mixed }, + fieldResolver: GraphQLFieldResolver, + errors: Array, +|}; + +/** + * 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. + */ +export type ExecutionResult = { + errors?: $ReadOnlyArray, + data?: ObjMap, +}; + +export type ExecutionArgs = {| + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ [variable: string]: mixed }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +|}; + +/** + * Implements the "Evaluating requests" section of the GraphQL specification. + * + * Returns either a synchronous ExecutionResult (if all encountered resolvers + * are synchronous), or a Promise of an ExecutionResult that will eventually be + * resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + * + * Accepts either an object with named arguments, or individual arguments. + */ +declare function execute( + ExecutionArgs, + ..._: [] +): MaybePromise; +/* eslint-disable no-redeclare */ +declare function execute( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ [variable: string]: mixed }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +): MaybePromise; +export function execute( + argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, +) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 + ? executeImpl( + argsOrSchema.schema, + argsOrSchema.document, + argsOrSchema.rootValue, + argsOrSchema.contextValue, + argsOrSchema.variableValues, + argsOrSchema.operationName, + argsOrSchema.fieldResolver, + ) + : executeImpl( + argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ); +} + +function executeImpl( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, +) { + // If arguments are missing or incorrect, throw an error. + assertValidExecutionArguments(schema, document, variableValues); + + // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + const exeContext = buildExecutionContext( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ); + + // Return early errors if execution context failed. + if (Array.isArray(exeContext)) { + return { errors: exeContext }; + } + + // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + const data = executeOperation(exeContext, exeContext.operation, rootValue); + return buildResponse(exeContext, data); +} + +/** + * Given a completed execution context and data, build the { errors, data } + * response defined by the "Response" section of the GraphQL specification. + */ +function buildResponse( + exeContext: ExecutionContext, + data: MaybePromise | null>, +) { + if (isPromise(data)) { + return data.then(resolved => buildResponse(exeContext, resolved)); + } + return exeContext.errors.length === 0 + ? { data } + : { errors: exeContext.errors, data }; +} + +/** + * Given a ResponsePath (found in the `path` entry in the information provided + * as the last argument to a field resolver), return an Array of the path keys. + */ +export function responsePathAsArray( + path: ResponsePath, +): $ReadOnlyArray { + const flattened = []; + let curr = path; + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + return flattened.reverse(); +} + +/** + * Given a ResponsePath and a key, return a new ResponsePath containing the + * new key. + */ +export function addPath(prev: ResponsePath | void, key: string | number) { + return { prev, key }; +} + +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + */ +export function assertValidExecutionArguments( + schema: GraphQLSchema, + document: DocumentNode, + rawVariableValues: ?ObjMap, +): void { + invariant(document, 'Must provide document'); + + // If the schema used for execution is invalid, throw an error. + assertValidSchema(schema); + + // Variables, if provided, must be an object. + invariant( + !rawVariableValues || typeof rawVariableValues === 'object', + 'Variables must be provided as an Object where each property is a ' + + 'variable value. Perhaps look to see if an unparsed JSON string ' + + 'was provided.', + ); +} + +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + */ +export function buildExecutionContext( + schema: GraphQLSchema, + document: DocumentNode, + rootValue: mixed, + contextValue: mixed, + rawVariableValues: ?ObjMap, + operationName: ?string, + fieldResolver: ?GraphQLFieldResolver, +): $ReadOnlyArray | ExecutionContext { + const errors: Array = []; + let operation: OperationDefinitionNode | void; + let hasMultipleAssumedOperations = false; + const fragments: ObjMap = Object.create(null); + for (let i = 0; i < document.definitions.length; i++) { + const definition = document.definitions[i]; + switch (definition.kind) { + case Kind.OPERATION_DEFINITION: + if (!operationName && operation) { + hasMultipleAssumedOperations = true; + } else if ( + !operationName || + (definition.name && definition.name.value === operationName) + ) { + operation = definition; + } + break; + case Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + } + } + + if (!operation) { + if (operationName) { + errors.push( + new GraphQLError(`Unknown operation named "${operationName}".`), + ); + } else { + errors.push(new GraphQLError('Must provide an operation.')); + } + } else if (hasMultipleAssumedOperations) { + errors.push( + new GraphQLError( + 'Must provide operation name if query contains multiple operations.', + ), + ); + } + + let variableValues; + if (operation) { + const coercedVariableValues = getVariableValues( + schema, + operation.variableDefinitions || [], + rawVariableValues || {}, + ); + + if (coercedVariableValues.errors) { + errors.push(...coercedVariableValues.errors); + } else { + variableValues = coercedVariableValues.coerced; + } + } + + if (errors.length !== 0) { + return errors; + } + + invariant(operation, 'Has operation if no errors.'); + invariant(variableValues, 'Has variables if no errors.'); + + return { + schema, + fragments, + rootValue, + contextValue, + operation, + variableValues, + fieldResolver: fieldResolver || defaultFieldResolver, + errors, + }; +} + +/** + * Implements the "Evaluating operations" section of the spec. + */ +function executeOperation( + exeContext: ExecutionContext, + operation: OperationDefinitionNode, + rootValue: mixed, +): MaybePromise | null> { + const type = getOperationRootType(exeContext.schema, operation); + const fields = collectFields( + exeContext, + type, + operation.selectionSet, + Object.create(null), + Object.create(null), + ); + + const path = undefined; + + // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. + // + // Similar to completeValueCatchingError. + try { + const result = + operation.operation === 'mutation' + ? executeFieldsSerially(exeContext, type, rootValue, path, fields) + : executeFields(exeContext, type, rootValue, path, fields); + if (isPromise(result)) { + return result.then(undefined, error => { + exeContext.errors.push(error); + return Promise.resolve(null); + }); + } + return result; + } catch (error) { + exeContext.errors.push(error); + return null; + } +} + +/** + * Implements the "Evaluating selection sets" section of the spec + * for "write" mode. + */ +function executeFieldsSerially( + exeContext: ExecutionContext, + parentType: GraphQLObjectType, + sourceValue: mixed, + path: ResponsePath | void, + fields: ObjMap>, +): MaybePromise> { + return promiseReduce( + Object.keys(fields), + (results, responseName) => { + const fieldNodes = fields[responseName]; + const fieldPath = addPath(path, responseName); + const result = resolveField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); + if (result === undefined) { + return results; + } + if (isPromise(result)) { + return result.then(resolvedResult => { + results[responseName] = resolvedResult; + return results; + }); + } + results[responseName] = result; + return results; + }, + Object.create(null), + ); +} + +/** + * Implements the "Evaluating selection sets" section of the spec + * for "read" mode. + */ +function executeFields( + exeContext: ExecutionContext, + parentType: GraphQLObjectType, + sourceValue: mixed, + path: ResponsePath | void, + fields: ObjMap>, +): MaybePromise> { + const results = Object.create(null); + let containsPromise = false; + + for (let i = 0, keys = Object.keys(fields); i < keys.length; ++i) { + const responseName = keys[i]; + const fieldNodes = fields[responseName]; + const fieldPath = addPath(path, responseName); + const result = resolveField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); + + if (result !== undefined) { + results[responseName] = result; + if (!containsPromise && isPromise(result)) { + containsPromise = true; + } + } + } + + // If there are no promises, we can just return the object + if (!containsPromise) { + return results; + } + + // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + return promiseForObject(results); +} + +/** + * Given a selectionSet, adds all of the fields in that selection to + * the passed in map of fields, and returns it at the end. + * + * CollectFields requires the "runtime type" of an object. For a field which + * returns an Interface or Union type, the "runtime type" will be the actual + * Object type returned by that field. + */ +export function collectFields( + exeContext: ExecutionContext, + runtimeType: GraphQLObjectType, + selectionSet: SelectionSetNode, + fields: ObjMap>, + visitedFragmentNames: ObjMap, +): ObjMap> { + for (let i = 0; i < selectionSet.selections.length; i++) { + const selection = selectionSet.selections[i]; + switch (selection.kind) { + case Kind.FIELD: + if (!shouldIncludeNode(exeContext, selection)) { + continue; + } + const name = getFieldEntryKey(selection); + if (!fields[name]) { + fields[name] = []; + } + fields[name].push(selection); + break; + case Kind.INLINE_FRAGMENT: + if ( + !shouldIncludeNode(exeContext, selection) || + !doesFragmentConditionMatch(exeContext, selection, runtimeType) + ) { + continue; + } + collectFields( + exeContext, + runtimeType, + selection.selectionSet, + fields, + visitedFragmentNames, + ); + break; + case Kind.FRAGMENT_SPREAD: + const fragName = selection.name.value; + if ( + visitedFragmentNames[fragName] || + !shouldIncludeNode(exeContext, selection) + ) { + continue; + } + visitedFragmentNames[fragName] = true; + const fragment = exeContext.fragments[fragName]; + if ( + !fragment || + !doesFragmentConditionMatch(exeContext, fragment, runtimeType) + ) { + continue; + } + collectFields( + exeContext, + runtimeType, + fragment.selectionSet, + fields, + visitedFragmentNames, + ); + break; + } + } + return fields; +} + +/** + * Determines if a field should be included based on the @include and @skip + * directives, where @skip has higher precedence than @include. + */ +function shouldIncludeNode( + exeContext: ExecutionContext, + node: FragmentSpreadNode | FieldNode | InlineFragmentNode, +): boolean { + const skip = getDirectiveValues( + GraphQLSkipDirective, + node, + exeContext.variableValues, + ); + if (skip && skip.if === true) { + return false; + } + + const include = getDirectiveValues( + GraphQLIncludeDirective, + node, + exeContext.variableValues, + ); + if (include && include.if === false) { + return false; + } + return true; +} + +/** + * Determines if a fragment is applicable to the given type. + */ +function doesFragmentConditionMatch( + exeContext: ExecutionContext, + fragment: FragmentDefinitionNode | InlineFragmentNode, + type: GraphQLObjectType, +): boolean { + const typeConditionNode = fragment.typeCondition; + if (!typeConditionNode) { + return true; + } + const conditionalType = typeFromAST(exeContext.schema, typeConditionNode); + if (conditionalType === type) { + return true; + } + if (isAbstractType(conditionalType)) { + return exeContext.schema.isPossibleType(conditionalType, type); + } + return false; +} + +/** + * Implements the logic to compute the key of a given field's entry + */ +function getFieldEntryKey(node: FieldNode): string { + return node.alias ? node.alias.value : node.name.value; +} + +/** + * Resolves the field on the given source object. In particular, this + * figures out the value that the field returns by calling its resolve function, + * then calls completeValue to complete promises, serialize scalars, or execute + * the sub-selection-set for objects. + */ +function resolveField( + exeContext: ExecutionContext, + parentType: GraphQLObjectType, + source: mixed, + fieldNodes: $ReadOnlyArray, + path: ResponsePath, +): MaybePromise { + const fieldNode = fieldNodes[0]; + const fieldName = fieldNode.name.value; + + const fieldDef = getFieldDef(exeContext.schema, parentType, fieldName); + if (!fieldDef) { + return; + } + + const resolveFn = fieldDef.resolve || exeContext.fieldResolver; + + const info = buildResolveInfo( + exeContext, + fieldDef, + fieldNodes, + parentType, + path, + ); + + // Get the resolve function, regardless of if its result is normal + // or abrupt (error). + const result = resolveFieldValueOrError( + exeContext, + fieldDef, + fieldNodes, + resolveFn, + source, + info, + ); + + return completeValueCatchingError( + exeContext, + fieldDef.type, + fieldNodes, + info, + path, + result, + ); +} + +export function buildResolveInfo( + exeContext: ExecutionContext, + fieldDef: GraphQLField<*, *>, + fieldNodes: $ReadOnlyArray, + parentType: GraphQLObjectType, + path: ResponsePath, +): GraphQLResolveInfo { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes, + returnType: fieldDef.type, + parentType, + path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues, + }; +} + +// Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField` +// function. Returns the result of resolveFn or the abrupt-return Error object. +export function resolveFieldValueOrError( + exeContext: ExecutionContext, + fieldDef: GraphQLField, + fieldNodes: $ReadOnlyArray, + resolveFn: GraphQLFieldResolver, + source: TSource, + info: GraphQLResolveInfo, +): Error | mixed { + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + const args = getArgumentValues( + fieldDef, + fieldNodes[0], + exeContext.variableValues, + ); + + // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + const contextValue = exeContext.contextValue; + + const result = resolveFn(source, args, contextValue, info); + return isPromise(result) ? result.then(undefined, asErrorInstance) : result; + } catch (error) { + return asErrorInstance(error); + } +} + +// Sometimes a non-error is thrown, wrap it as an Error instance to ensure a +// consistent Error interface. +function asErrorInstance(error: mixed): Error { + return error instanceof Error ? error : new Error(error || undefined); +} + +// This is a small wrapper around completeValue which detects and logs errors +// in the execution context. +function completeValueCatchingError( + exeContext: ExecutionContext, + returnType: GraphQLOutputType, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + path: ResponsePath, + result: mixed, +): MaybePromise { + try { + let completed; + if (isPromise(result)) { + completed = result.then(resolved => + completeValue(exeContext, returnType, fieldNodes, info, path, resolved), + ); + } else { + completed = completeValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + if (isPromise(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, error => + handleFieldError(error, fieldNodes, path, returnType, exeContext), + ); + } + return completed; + } catch (error) { + return handleFieldError(error, fieldNodes, path, returnType, exeContext); + } +} + +function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) { + const error = locatedError( + asErrorInstance(rawError), + fieldNodes, + responsePathAsArray(path), + ); + + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if (isNonNullType(returnType)) { + throw error; + } + + // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + exeContext.errors.push(error); + return null; +} + +/** + * Implements the instructions for completeValue as defined in the + * "Field entries" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by evaluating all sub-selections. + */ +function completeValue( + exeContext: ExecutionContext, + returnType: GraphQLOutputType, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + path: ResponsePath, + result: mixed, +): MaybePromise { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } + + // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + if (isNonNullType(returnType)) { + const completed = completeValue( + exeContext, + returnType.ofType, + fieldNodes, + info, + path, + result, + ); + if (completed === null) { + throw new Error( + `Cannot return null for non-nullable field ${info.parentType.name}.${ + info.fieldName + }.`, + ); + } + return completed; + } + + // If result value is null-ish (null, undefined, or NaN) then return null. + if (isNullish(result)) { + return null; + } + + // If field type is List, complete each item in the list with the inner type + if (isListType(returnType)) { + return completeListValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + if (isLeafType(returnType)) { + return completeLeafValue(returnType, result); + } + + // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + if (isAbstractType(returnType)) { + return completeAbstractValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + // If field type is Object, execute and complete all sub-selections. + if (isObjectType(returnType)) { + return completeObjectValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + // Not reachable. All possible output types have been considered. + /* istanbul ignore next */ + throw new Error( + `Cannot complete value of unexpected type "${inspect( + (returnType: empty), + )}".`, + ); +} + +/** + * Complete a list value by completing each item in the list with the + * inner type + */ +function completeListValue( + exeContext: ExecutionContext, + returnType: GraphQLList, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + path: ResponsePath, + result: mixed, +): MaybePromise<$ReadOnlyArray> { + invariant( + isCollection(result), + `Expected Iterable, but did not find one for field ${ + info.parentType.name + }.${info.fieldName}.`, + ); + + // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + const itemType = returnType.ofType; + let containsPromise = false; + const completedResults = []; + forEach((result: any), (item, index) => { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + const fieldPath = addPath(path, index); + const completedItem = completeValueCatchingError( + exeContext, + itemType, + fieldNodes, + info, + fieldPath, + item, + ); + + if (!containsPromise && isPromise(completedItem)) { + containsPromise = true; + } + completedResults.push(completedItem); + }); + + return containsPromise ? Promise.all(completedResults) : completedResults; +} + +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ +function completeLeafValue(returnType: GraphQLLeafType, result: mixed): mixed { + invariant(returnType.serialize, 'Missing serialize method on type'); + const serializedResult = returnType.serialize(result); + if (isInvalid(serializedResult)) { + throw new Error( + `Expected a value of type "${inspect(returnType)}" but ` + + `received: ${inspect(result)}`, + ); + } + return serializedResult; +} + +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ +function completeAbstractValue( + exeContext: ExecutionContext, + returnType: GraphQLAbstractType, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + path: ResponsePath, + result: mixed, +): MaybePromise> { + const runtimeType = returnType.resolveType + ? returnType.resolveType(result, exeContext.contextValue, info) + : defaultResolveTypeFn(result, exeContext.contextValue, info, returnType); + + if (isPromise(runtimeType)) { + return runtimeType.then(resolvedRuntimeType => + completeObjectValue( + exeContext, + ensureValidRuntimeType( + resolvedRuntimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ), + ); + } + + return completeObjectValue( + exeContext, + ensureValidRuntimeType( + runtimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ); +} + +function ensureValidRuntimeType( + runtimeTypeOrName: ?GraphQLObjectType | string, + exeContext: ExecutionContext, + returnType: GraphQLAbstractType, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + result: mixed, +): GraphQLObjectType { + const runtimeType = + typeof runtimeTypeOrName === 'string' + ? exeContext.schema.getType(runtimeTypeOrName) + : runtimeTypeOrName; + + if (!isObjectType(runtimeType)) { + throw new GraphQLError( + `Abstract type ${returnType.name} must resolve to an Object type at ` + + `runtime for field ${info.parentType.name}.${info.fieldName} with ` + + `value ${inspect(result)}, received "${inspect(runtimeType)}". ` + + `Either the ${returnType.name} type should provide a "resolveType" ` + + 'function or each possible type should provide an "isTypeOf" function.', + fieldNodes, + ); + } + + if (!exeContext.schema.isPossibleType(returnType, runtimeType)) { + throw new GraphQLError( + `Runtime Object type "${runtimeType.name}" is not a possible type ` + + `for "${returnType.name}".`, + fieldNodes, + ); + } + + return runtimeType; +} + +/** + * Complete an Object value by executing all sub-selections. + */ +function completeObjectValue( + exeContext: ExecutionContext, + returnType: GraphQLObjectType, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + path: ResponsePath, + result: mixed, +): MaybePromise> { + // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + if (returnType.isTypeOf) { + const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + + if (isPromise(isTypeOf)) { + return isTypeOf.then(resolvedIsTypeOf => { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + return collectAndExecuteSubfields( + exeContext, + returnType, + fieldNodes, + path, + result, + ); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return collectAndExecuteSubfields( + exeContext, + returnType, + fieldNodes, + path, + result, + ); +} + +function invalidReturnTypeError( + returnType: GraphQLObjectType, + result: mixed, + fieldNodes: $ReadOnlyArray, +): GraphQLError { + return new GraphQLError( + `Expected value of type "${returnType.name}" but got: ${inspect(result)}.`, + fieldNodes, + ); +} + +function collectAndExecuteSubfields( + exeContext: ExecutionContext, + returnType: GraphQLObjectType, + fieldNodes: $ReadOnlyArray, + path: ResponsePath, + result: mixed, +): MaybePromise> { + // Collect sub-fields to execute to complete this value. + const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} + +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ +const collectSubfields = memoize3(_collectSubfields); +function _collectSubfields( + exeContext: ExecutionContext, + returnType: GraphQLObjectType, + fieldNodes: $ReadOnlyArray, +): ObjMap> { + let subFieldNodes = Object.create(null); + const visitedFragmentNames = Object.create(null); + for (let i = 0; i < fieldNodes.length; i++) { + const selectionSet = fieldNodes[i].selectionSet; + if (selectionSet) { + subFieldNodes = collectFields( + exeContext, + returnType, + selectionSet, + subFieldNodes, + visitedFragmentNames, + ); + } + } + return subFieldNodes; +} + +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ +function defaultResolveTypeFn( + value: mixed, + contextValue: mixed, + info: GraphQLResolveInfo, + abstractType: GraphQLAbstractType, +): MaybePromise { + // First, look for `__typename`. + if ( + value !== null && + typeof value === 'object' && + typeof value.__typename === 'string' + ) { + return value.__typename; + } + + // Otherwise, test each possible type. + const possibleTypes = info.schema.getPossibleTypes(abstractType); + const promisedIsTypeOfResults = []; + + for (let i = 0; i < possibleTypes.length; i++) { + const type = possibleTypes[i]; + + if (type.isTypeOf) { + const isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if (isPromise(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type; + } + } + } + + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then(isTypeOfResults => { + for (let i = 0; i < isTypeOfResults.length; i++) { + if (isTypeOfResults[i]) { + return possibleTypes[i]; + } + } + }); + } +} + +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ +export const defaultFieldResolver: GraphQLFieldResolver = function( + source, + args, + contextValue, + info, +) { + // ensure source is a value for which property access is acceptable. + if (typeof source === 'object' || typeof source === 'function') { + const property = source[info.fieldName]; + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + return property; + } +}; + +/** + * This method looks up the field on the given type definition. + * It has special casing for the two introspection fields, __schema + * and __typename. __typename is special because it can always be + * queried as a field, even in situations where no other fields + * are allowed, like on a Union. __schema could get automatically + * added to the query type, but that would require mutating type + * definitions, which would cause issues. + */ +export function getFieldDef( + schema: GraphQLSchema, + parentType: GraphQLObjectType, + fieldName: string, +): ?GraphQLField<*, *> { + if ( + fieldName === SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return SchemaMetaFieldDef; + } else if ( + fieldName === TypeMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return TypeMetaFieldDef; + } else if (fieldName === TypeNameMetaFieldDef.name) { + return TypeNameMetaFieldDef; + } + return parentType.getFields()[fieldName]; +} diff --git a/node_modules/graphql/execution/execute.mjs b/node_modules/graphql/execution/execute.mjs new file mode 100644 index 0000000..0c962b9 --- /dev/null +++ b/node_modules/graphql/execution/execute.mjs @@ -0,0 +1,792 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { forEach, isCollection } from 'iterall'; +import { GraphQLError } from '../error/GraphQLError'; +import { locatedError } from '../error/locatedError'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import isInvalid from '../jsutils/isInvalid'; +import isNullish from '../jsutils/isNullish'; +import isPromise from '../jsutils/isPromise'; +import memoize3 from '../jsutils/memoize3'; +import promiseForObject from '../jsutils/promiseForObject'; +import promiseReduce from '../jsutils/promiseReduce'; +import { getOperationRootType } from '../utilities/getOperationRootType'; +import { typeFromAST } from '../utilities/typeFromAST'; +import { Kind } from '../language/kinds'; +import { getVariableValues, getArgumentValues, getDirectiveValues } from './values'; +import { isObjectType, isAbstractType, isLeafType, isListType, isNonNullType } from '../type/definition'; +import { SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from '../type/introspection'; +import { GraphQLIncludeDirective, GraphQLSkipDirective } from '../type/directives'; +import { assertValidSchema } from '../type/validate'; +export function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? executeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : executeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); +} + +function executeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // If arguments are missing or incorrect, throw an error. + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed. + + if (Array.isArray(exeContext)) { + return { + errors: exeContext + }; + } // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + + + var data = executeOperation(exeContext, exeContext.operation, rootValue); + return buildResponse(exeContext, data); +} +/** + * Given a completed execution context and data, build the { errors, data } + * response defined by the "Response" section of the GraphQL specification. + */ + + +function buildResponse(exeContext, data) { + if (isPromise(data)) { + return data.then(function (resolved) { + return buildResponse(exeContext, resolved); + }); + } + + return exeContext.errors.length === 0 ? { + data: data + } : { + errors: exeContext.errors, + data: data + }; +} +/** + * Given a ResponsePath (found in the `path` entry in the information provided + * as the last argument to a field resolver), return an Array of the path keys. + */ + + +export function responsePathAsArray(path) { + var flattened = []; + var curr = path; + + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + + return flattened.reverse(); +} +/** + * Given a ResponsePath and a key, return a new ResponsePath containing the + * new key. + */ + +export function addPath(prev, key) { + return { + prev: prev, + key: key + }; +} +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + */ + +export function assertValidExecutionArguments(schema, document, rawVariableValues) { + !document ? invariant(0, 'Must provide document') : void 0; // If the schema used for execution is invalid, throw an error. + + assertValidSchema(schema); // Variables, if provided, must be an object. + + !(!rawVariableValues || _typeof(rawVariableValues) === 'object') ? invariant(0, 'Variables must be provided as an Object where each property is a ' + 'variable value. Perhaps look to see if an unparsed JSON string ' + 'was provided.') : void 0; +} +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + */ + +export function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver) { + var errors = []; + var operation; + var hasMultipleAssumedOperations = false; + var fragments = Object.create(null); + + for (var i = 0; i < document.definitions.length; i++) { + var definition = document.definitions[i]; + + switch (definition.kind) { + case Kind.OPERATION_DEFINITION: + if (!operationName && operation) { + hasMultipleAssumedOperations = true; + } else if (!operationName || definition.name && definition.name.value === operationName) { + operation = definition; + } + + break; + + case Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + } + } + + if (!operation) { + if (operationName) { + errors.push(new GraphQLError("Unknown operation named \"".concat(operationName, "\"."))); + } else { + errors.push(new GraphQLError('Must provide an operation.')); + } + } else if (hasMultipleAssumedOperations) { + errors.push(new GraphQLError('Must provide operation name if query contains multiple operations.')); + } + + var variableValues; + + if (operation) { + var coercedVariableValues = getVariableValues(schema, operation.variableDefinitions || [], rawVariableValues || {}); + + if (coercedVariableValues.errors) { + errors.push.apply(errors, coercedVariableValues.errors); + } else { + variableValues = coercedVariableValues.coerced; + } + } + + if (errors.length !== 0) { + return errors; + } + + !operation ? invariant(0, 'Has operation if no errors.') : void 0; + !variableValues ? invariant(0, 'Has variables if no errors.') : void 0; + return { + schema: schema, + fragments: fragments, + rootValue: rootValue, + contextValue: contextValue, + operation: operation, + variableValues: variableValues, + fieldResolver: fieldResolver || defaultFieldResolver, + errors: errors + }; +} +/** + * Implements the "Evaluating operations" section of the spec. + */ + +function executeOperation(exeContext, operation, rootValue) { + var type = getOperationRootType(exeContext.schema, operation); + var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null)); + var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. + // + // Similar to completeValueCatchingError. + + try { + var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields); + + if (isPromise(result)) { + return result.then(undefined, function (error) { + exeContext.errors.push(error); + return Promise.resolve(null); + }); + } + + return result; + } catch (error) { + exeContext.errors.push(error); + return null; + } +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "write" mode. + */ + + +function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { + return promiseReduce(Object.keys(fields), function (results, responseName) { + var fieldNodes = fields[responseName]; + var fieldPath = addPath(path, responseName); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result === undefined) { + return results; + } + + if (isPromise(result)) { + return result.then(function (resolvedResult) { + results[responseName] = resolvedResult; + return results; + }); + } + + results[responseName] = result; + return results; + }, Object.create(null)); +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "read" mode. + */ + + +function executeFields(exeContext, parentType, sourceValue, path, fields) { + var results = Object.create(null); + var containsPromise = false; + + for (var i = 0, keys = Object.keys(fields); i < keys.length; ++i) { + var responseName = keys[i]; + var fieldNodes = fields[responseName]; + var fieldPath = addPath(path, responseName); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result !== undefined) { + results[responseName] = result; + + if (!containsPromise && isPromise(result)) { + containsPromise = true; + } + } + } // If there are no promises, we can just return the object + + + if (!containsPromise) { + return results; + } // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + + + return promiseForObject(results); +} +/** + * Given a selectionSet, adds all of the fields in that selection to + * the passed in map of fields, and returns it at the end. + * + * CollectFields requires the "runtime type" of an object. For a field which + * returns an Interface or Union type, the "runtime type" will be the actual + * Object type returned by that field. + */ + + +export function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) { + for (var i = 0; i < selectionSet.selections.length; i++) { + var selection = selectionSet.selections[i]; + + switch (selection.kind) { + case Kind.FIELD: + if (!shouldIncludeNode(exeContext, selection)) { + continue; + } + + var name = getFieldEntryKey(selection); + + if (!fields[name]) { + fields[name] = []; + } + + fields[name].push(selection); + break; + + case Kind.INLINE_FRAGMENT: + if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames); + break; + + case Kind.FRAGMENT_SPREAD: + var fragName = selection.name.value; + + if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) { + continue; + } + + visitedFragmentNames[fragName] = true; + var fragment = exeContext.fragments[fragName]; + + if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames); + break; + } + } + + return fields; +} +/** + * Determines if a field should be included based on the @include and @skip + * directives, where @skip has higher precedence than @include. + */ + +function shouldIncludeNode(exeContext, node) { + var skip = getDirectiveValues(GraphQLSkipDirective, node, exeContext.variableValues); + + if (skip && skip.if === true) { + return false; + } + + var include = getDirectiveValues(GraphQLIncludeDirective, node, exeContext.variableValues); + + if (include && include.if === false) { + return false; + } + + return true; +} +/** + * Determines if a fragment is applicable to the given type. + */ + + +function doesFragmentConditionMatch(exeContext, fragment, type) { + var typeConditionNode = fragment.typeCondition; + + if (!typeConditionNode) { + return true; + } + + var conditionalType = typeFromAST(exeContext.schema, typeConditionNode); + + if (conditionalType === type) { + return true; + } + + if (isAbstractType(conditionalType)) { + return exeContext.schema.isPossibleType(conditionalType, type); + } + + return false; +} +/** + * Implements the logic to compute the key of a given field's entry + */ + + +function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; +} +/** + * Resolves the field on the given source object. In particular, this + * figures out the value that the field returns by calling its resolve function, + * then calls completeValue to complete promises, serialize scalars, or execute + * the sub-selection-set for objects. + */ + + +function resolveField(exeContext, parentType, source, fieldNodes, path) { + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName); + + if (!fieldDef) { + return; + } + + var resolveFn = fieldDef.resolve || exeContext.fieldResolver; + var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal + // or abrupt (error). + + var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info); + return completeValueCatchingError(exeContext, fieldDef.type, fieldNodes, info, path, result); +} + +export function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes: fieldNodes, + returnType: fieldDef.type, + parentType: parentType, + path: path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues + }; +} // Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField` +// function. Returns the result of resolveFn or the abrupt-return Error object. + +export function resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info) { + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + var args = getArgumentValues(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + var _contextValue = exeContext.contextValue; + var result = resolveFn(source, args, _contextValue, info); + return isPromise(result) ? result.then(undefined, asErrorInstance) : result; + } catch (error) { + return asErrorInstance(error); + } +} // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a +// consistent Error interface. + +function asErrorInstance(error) { + return error instanceof Error ? error : new Error(error || undefined); +} // This is a small wrapper around completeValue which detects and logs errors +// in the execution context. + + +function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) { + try { + var completed; + + if (isPromise(result)) { + completed = result.then(function (resolved) { + return completeValue(exeContext, returnType, fieldNodes, info, path, resolved); + }); + } else { + completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); + } + + if (isPromise(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, function (error) { + return handleFieldError(error, fieldNodes, path, returnType, exeContext); + }); + } + + return completed; + } catch (error) { + return handleFieldError(error, fieldNodes, path, returnType, exeContext); + } +} + +function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) { + var error = locatedError(asErrorInstance(rawError), fieldNodes, responsePathAsArray(path)); // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + + if (isNonNullType(returnType)) { + throw error; + } // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + + + exeContext.errors.push(error); + return null; +} +/** + * Implements the instructions for completeValue as defined in the + * "Field entries" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by evaluating all sub-selections. + */ + + +function completeValue(exeContext, returnType, fieldNodes, info, path, result) { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + + + if (isNonNullType(returnType)) { + var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); + + if (completed === null) { + throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")); + } + + return completed; + } // If result value is null-ish (null, undefined, or NaN) then return null. + + + if (isNullish(result)) { + return null; + } // If field type is List, complete each item in the list with the inner type + + + if (isListType(returnType)) { + return completeListValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + + + if (isLeafType(returnType)) { + return completeLeafValue(returnType, result); + } // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + + + if (isAbstractType(returnType)) { + return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is Object, execute and complete all sub-selections. + + + if (isObjectType(returnType)) { + return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); + } // Not reachable. All possible output types have been considered. + + /* istanbul ignore next */ + + + throw new Error("Cannot complete value of unexpected type \"".concat(inspect(returnType), "\".")); +} +/** + * Complete a list value by completing each item in the list with the + * inner type + */ + + +function completeListValue(exeContext, returnType, fieldNodes, info, path, result) { + !isCollection(result) ? invariant(0, "Expected Iterable, but did not find one for field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")) : void 0; // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + + var itemType = returnType.ofType; + var containsPromise = false; + var completedResults = []; + forEach(result, function (item, index) { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + var fieldPath = addPath(path, index); + var completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item); + + if (!containsPromise && isPromise(completedItem)) { + containsPromise = true; + } + + completedResults.push(completedItem); + }); + return containsPromise ? Promise.all(completedResults) : completedResults; +} +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ + + +function completeLeafValue(returnType, result) { + !returnType.serialize ? invariant(0, 'Missing serialize method on type') : void 0; + var serializedResult = returnType.serialize(result); + + if (isInvalid(serializedResult)) { + throw new Error("Expected a value of type \"".concat(inspect(returnType), "\" but ") + "received: ".concat(inspect(result))); + } + + return serializedResult; +} +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ + + +function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) { + var runtimeType = returnType.resolveType ? returnType.resolveType(result, exeContext.contextValue, info) : defaultResolveTypeFn(result, exeContext.contextValue, info, returnType); + + if (isPromise(runtimeType)) { + return runtimeType.then(function (resolvedRuntimeType) { + return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); + }); + } + + return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); +} + +function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) { + var runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName; + + if (!isObjectType(runtimeType)) { + throw new GraphQLError("Abstract type ".concat(returnType.name, " must resolve to an Object type at ") + "runtime for field ".concat(info.parentType.name, ".").concat(info.fieldName, " with ") + "value ".concat(inspect(result), ", received \"").concat(inspect(runtimeType), "\". ") + "Either the ".concat(returnType.name, " type should provide a \"resolveType\" ") + 'function or each possible type should provide an "isTypeOf" function.', fieldNodes); + } + + if (!exeContext.schema.isPossibleType(returnType, runtimeType)) { + throw new GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type ") + "for \"".concat(returnType.name, "\"."), fieldNodes); + } + + return runtimeType; +} +/** + * Complete an Object value by executing all sub-selections. + */ + + +function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) { + // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + if (returnType.isTypeOf) { + var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + + if (isPromise(isTypeOf)) { + return isTypeOf.then(function (resolvedIsTypeOf) { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); +} + +function invalidReturnTypeError(returnType, result, fieldNodes) { + return new GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat(inspect(result), "."), fieldNodes); +} + +function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) { + // Collect sub-fields to execute to complete this value. + var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ + + +var collectSubfields = memoize3(_collectSubfields); + +function _collectSubfields(exeContext, returnType, fieldNodes) { + var subFieldNodes = Object.create(null); + var visitedFragmentNames = Object.create(null); + + for (var i = 0; i < fieldNodes.length; i++) { + var selectionSet = fieldNodes[i].selectionSet; + + if (selectionSet) { + subFieldNodes = collectFields(exeContext, returnType, selectionSet, subFieldNodes, visitedFragmentNames); + } + } + + return subFieldNodes; +} +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ + + +function defaultResolveTypeFn(value, contextValue, info, abstractType) { + // First, look for `__typename`. + if (value !== null && _typeof(value) === 'object' && typeof value.__typename === 'string') { + return value.__typename; + } // Otherwise, test each possible type. + + + var possibleTypes = info.schema.getPossibleTypes(abstractType); + var promisedIsTypeOfResults = []; + + for (var i = 0; i < possibleTypes.length; i++) { + var type = possibleTypes[i]; + + if (type.isTypeOf) { + var isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if (isPromise(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type; + } + } + } + + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) { + for (var _i = 0; _i < isTypeOfResults.length; _i++) { + if (isTypeOfResults[_i]) { + return possibleTypes[_i]; + } + } + }); + } +} +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ + + +export var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) { + // ensure source is a value for which property access is acceptable. + if (_typeof(source) === 'object' || typeof source === 'function') { + var property = source[info.fieldName]; + + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + + return property; + } +}; +/** + * This method looks up the field on the given type definition. + * It has special casing for the two introspection fields, __schema + * and __typename. __typename is special because it can always be + * queried as a field, even in situations where no other fields + * are allowed, like on a Union. __schema could get automatically + * added to the query type, but that would require mutating type + * definitions, which would cause issues. + */ + +export function getFieldDef(schema, parentType, fieldName) { + if (fieldName === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return SchemaMetaFieldDef; + } else if (fieldName === TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return TypeMetaFieldDef; + } else if (fieldName === TypeNameMetaFieldDef.name) { + return TypeNameMetaFieldDef; + } + + return parentType.getFields()[fieldName]; +} \ No newline at end of file diff --git a/node_modules/graphql/execution/index.js b/node_modules/graphql/execution/index.js new file mode 100644 index 0000000..77f1274 --- /dev/null +++ b/node_modules/graphql/execution/index.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "execute", { + enumerable: true, + get: function get() { + return _execute.execute; + } +}); +Object.defineProperty(exports, "defaultFieldResolver", { + enumerable: true, + get: function get() { + return _execute.defaultFieldResolver; + } +}); +Object.defineProperty(exports, "responsePathAsArray", { + enumerable: true, + get: function get() { + return _execute.responsePathAsArray; + } +}); +Object.defineProperty(exports, "getDirectiveValues", { + enumerable: true, + get: function get() { + return _values.getDirectiveValues; + } +}); + +var _execute = require("./execute"); + +var _values = require("./values"); \ No newline at end of file diff --git a/node_modules/graphql/execution/index.js.flow b/node_modules/graphql/execution/index.js.flow new file mode 100644 index 0000000..d793e26 --- /dev/null +++ b/node_modules/graphql/execution/index.js.flow @@ -0,0 +1,13 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { execute, defaultFieldResolver, responsePathAsArray } from './execute'; +export { getDirectiveValues } from './values'; + +export type { ExecutionArgs, ExecutionResult } from './execute'; diff --git a/node_modules/graphql/execution/index.mjs b/node_modules/graphql/execution/index.mjs new file mode 100644 index 0000000..66db93a --- /dev/null +++ b/node_modules/graphql/execution/index.mjs @@ -0,0 +1,10 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { execute, defaultFieldResolver, responsePathAsArray } from './execute'; +export { getDirectiveValues } from './values'; \ No newline at end of file diff --git a/node_modules/graphql/execution/values.js b/node_modules/graphql/execution/values.js new file mode 100644 index 0000000..d9d9d7d --- /dev/null +++ b/node_modules/graphql/execution/values.js @@ -0,0 +1,240 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getVariableValues = getVariableValues; +exports.getArgumentValues = getArgumentValues; +exports.getDirectiveValues = getDirectiveValues; + +var _GraphQLError = require("../error/GraphQLError"); + +var _find = _interopRequireDefault(require("../jsutils/find")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _coerceValue = require("../utilities/coerceValue"); + +var _typeFromAST = require("../utilities/typeFromAST"); + +var _valueFromAST = require("../utilities/valueFromAST"); + +var _kinds = require("../language/kinds"); + +var _printer = require("../language/printer"); + +var _definition = require("../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * 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) { + var errors = []; + var coercedValues = {}; + + for (var i = 0; i < varDefNodes.length; i++) { + var varDefNode = varDefNodes[i]; + var varName = varDefNode.variable.name.value; + var varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type); + + if (!(0, _definition.isInputType)(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + errors.push(new _GraphQLError.GraphQLError("Variable \"$".concat(varName, "\" expected value of type ") + "\"".concat((0, _printer.print)(varDefNode.type), "\" which cannot be used as an input type."), [varDefNode.type])); + } else { + var hasValue = hasOwnProperty(inputs, varName); + var value = hasValue ? inputs[varName] : undefined; + + if (!hasValue && varDefNode.defaultValue) { + // If no value was provided to a variable with a default value, + // use the default value. + coercedValues[varName] = (0, _valueFromAST.valueFromAST)(varDefNode.defaultValue, varType); + } else if ((!hasValue || value === null) && (0, _definition.isNonNullType)(varType)) { + // If no value or a nullish value was provided to a variable with a + // non-null type (required), produce an error. + errors.push(new _GraphQLError.GraphQLError(hasValue ? "Variable \"$".concat(varName, "\" of non-null type ") + "\"".concat((0, _inspect.default)(varType), "\" must not be null.") : "Variable \"$".concat(varName, "\" of required type ") + "\"".concat((0, _inspect.default)(varType), "\" was not provided."), [varDefNode])); + } else if (hasValue) { + if (value === null) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[varName] = null; + } else { + // Otherwise, a non-null value was provided, coerce it to the expected + // type or report an error if coercion fails. + var coerced = (0, _coerceValue.coerceValue)(value, varType, varDefNode); + var coercionErrors = coerced.errors; + + if (coercionErrors) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = coercionErrors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var error = _step.value; + error.message = "Variable \"$".concat(varName, "\" got invalid value ").concat((0, _inspect.default)(value), "; ") + error.message; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + errors.push.apply(errors, coercionErrors); + } else { + coercedValues[varName] = coerced.value; + } + } + } + } + } + + return errors.length === 0 ? { + errors: undefined, + coerced: coercedValues + } : { + errors: errors, + coerced: undefined + }; +} +/** + * 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 coercedValues = {}; + var argDefs = def.args; + var argNodes = node.arguments; + + if (!argDefs || !argNodes) { + return coercedValues; + } + + var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) { + return arg.name.value; + }); + + for (var i = 0; i < argDefs.length; i++) { + var argDef = argDefs[i]; + var name = argDef.name; + var argType = argDef.type; + var argumentNode = argNodeMap[name]; + var hasValue = void 0; + var isNull = void 0; + + if (argumentNode && argumentNode.value.kind === _kinds.Kind.VARIABLE) { + var variableName = argumentNode.value.name.value; + hasValue = variableValues && hasOwnProperty(variableValues, variableName); + isNull = variableValues && variableValues[variableName] === null; + } else { + hasValue = argumentNode != null; + isNull = argumentNode && argumentNode.value.kind === _kinds.Kind.NULL; + } + + if (!hasValue && argDef.defaultValue !== undefined) { + // If no argument was provided where the definition has a default value, + // use the default value. + coercedValues[name] = argDef.defaultValue; + } else if ((!hasValue || isNull) && (0, _definition.isNonNullType)(argType)) { + // If no argument or a null value was provided to an argument with a + // non-null type (required), produce a field error. + if (isNull) { + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat((0, _inspect.default)(argType), "\" ") + 'must not be null.', [argumentNode.value]); + } else if (argumentNode && argumentNode.value.kind === _kinds.Kind.VARIABLE) { + var _variableName = argumentNode.value.name.value; + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + "was provided the variable \"$".concat(_variableName, "\" ") + 'which was not provided a runtime value.', [argumentNode.value]); + } else { + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + 'was not provided.', [node]); + } + } else if (hasValue) { + if (argumentNode.value.kind === _kinds.Kind.NULL) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[name] = null; + } else if (argumentNode.value.kind === _kinds.Kind.VARIABLE) { + var _variableName2 = argumentNode.value.name.value; + !variableValues ? (0, _invariant.default)(0, 'Must exist for hasValue to be true.') : void 0; // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + coercedValues[name] = variableValues[_variableName2]; + } else { + var valueNode = argumentNode.value; + var coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues); + + if (coercedValue === undefined) { + // Note: ValuesOfCorrectType validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat((0, _printer.print)(valueNode), "."), [argumentNode.value]); + } + + coercedValues[name] = coercedValue; + } + } + } + + return coercedValues; +} +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + + +function getDirectiveValues(directiveDef, node, variableValues) { + var directiveNode = node.directives && (0, _find.default)(node.directives, function (directive) { + return directive.name.value === directiveDef.name; + }); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} \ No newline at end of file diff --git a/node_modules/graphql/execution/values.js.flow b/node_modules/graphql/execution/values.js.flow new file mode 100644 index 0000000..db9bef6 --- /dev/null +++ b/node_modules/graphql/execution/values.js.flow @@ -0,0 +1,242 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { GraphQLError } from '../error/GraphQLError'; +import find from '../jsutils/find'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import { coerceValue } from '../utilities/coerceValue'; +import { typeFromAST } from '../utilities/typeFromAST'; +import { valueFromAST } from '../utilities/valueFromAST'; +import { Kind } from '../language/kinds'; +import { print } from '../language/printer'; +import { isInputType, isNonNullType } from '../type/definition'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { GraphQLField } from '../type/definition'; +import type { GraphQLDirective } from '../type/directives'; +import type { GraphQLSchema } from '../type/schema'; +import type { + FieldNode, + DirectiveNode, + VariableDefinitionNode, +} from '../language/ast'; + +type CoercedVariableValues = {| + errors: $ReadOnlyArray | void, + coerced: { [variable: string]: mixed } | void, +|}; + +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getVariableValues( + schema: GraphQLSchema, + varDefNodes: Array, + inputs: ObjMap, +): CoercedVariableValues { + const errors = []; + const coercedValues = {}; + for (let i = 0; i < varDefNodes.length; i++) { + const varDefNode = varDefNodes[i]; + 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. + errors.push( + new GraphQLError( + `Variable "$${varName}" expected value of type ` + + `"${print( + varDefNode.type, + )}" which cannot be used as an input type.`, + [varDefNode.type], + ), + ); + } else { + const hasValue = hasOwnProperty(inputs, varName); + const value = hasValue ? inputs[varName] : undefined; + if (!hasValue && varDefNode.defaultValue) { + // If no value was provided to a variable with a default value, + // use the default value. + coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType); + } else if ((!hasValue || value === null) && isNonNullType(varType)) { + // If no value or a nullish value was provided to a variable with a + // non-null type (required), produce an error. + errors.push( + new GraphQLError( + hasValue + ? `Variable "$${varName}" of non-null type ` + + `"${inspect(varType)}" must not be null.` + : `Variable "$${varName}" of required type ` + + `"${inspect(varType)}" was not provided.`, + [varDefNode], + ), + ); + } else if (hasValue) { + if (value === null) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[varName] = null; + } else { + // Otherwise, a non-null value was provided, coerce it to the expected + // type or report an error if coercion fails. + const coerced = coerceValue(value, varType, varDefNode); + const coercionErrors = coerced.errors; + if (coercionErrors) { + for (const error of coercionErrors) { + error.message = + `Variable "$${varName}" got invalid value ${inspect(value)}; ` + + error.message; + } + errors.push(...coercionErrors); + } else { + coercedValues[varName] = coerced.value; + } + } + } + } + } + return errors.length === 0 + ? { errors: undefined, coerced: coercedValues } + : { errors, coerced: undefined }; +} + +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getArgumentValues( + def: GraphQLField<*, *> | GraphQLDirective, + node: FieldNode | DirectiveNode, + variableValues?: ?ObjMap, +): { [argument: string]: mixed } { + const coercedValues = {}; + const argDefs = def.args; + const argNodes = node.arguments; + if (!argDefs || !argNodes) { + return coercedValues; + } + const argNodeMap = keyMap(argNodes, arg => arg.name.value); + for (let i = 0; i < argDefs.length; i++) { + const argDef = argDefs[i]; + const name = argDef.name; + const argType = argDef.type; + const argumentNode = argNodeMap[name]; + let hasValue; + let isNull; + if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) { + const variableName = argumentNode.value.name.value; + hasValue = variableValues && hasOwnProperty(variableValues, variableName); + isNull = variableValues && variableValues[variableName] === null; + } else { + hasValue = argumentNode != null; + isNull = argumentNode && argumentNode.value.kind === Kind.NULL; + } + + if (!hasValue && argDef.defaultValue !== undefined) { + // If no argument was provided where the definition has a default value, + // use the default value. + coercedValues[name] = argDef.defaultValue; + } else if ((!hasValue || isNull) && isNonNullType(argType)) { + // If no argument or a null value was provided to an argument with a + // non-null type (required), produce a field error. + if (isNull) { + throw new GraphQLError( + `Argument "${name}" of non-null type "${inspect(argType)}" ` + + 'must not be null.', + [argumentNode.value], + ); + } else if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) { + const variableName = argumentNode.value.name.value; + throw new GraphQLError( + `Argument "${name}" of required type "${inspect(argType)}" ` + + `was provided the variable "$${variableName}" ` + + 'which was not provided a runtime value.', + [argumentNode.value], + ); + } else { + throw new GraphQLError( + `Argument "${name}" of required type "${inspect(argType)}" ` + + 'was not provided.', + [node], + ); + } + } else if (hasValue) { + if (argumentNode.value.kind === Kind.NULL) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[name] = null; + } else if (argumentNode.value.kind === Kind.VARIABLE) { + const variableName = argumentNode.value.name.value; + invariant(variableValues, 'Must exist for hasValue to be true.'); + // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + coercedValues[name] = variableValues[variableName]; + } else { + const valueNode = argumentNode.value; + const coercedValue = valueFromAST(valueNode, argType, variableValues); + if (coercedValue === undefined) { + // Note: ValuesOfCorrectType 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)}.`, + [argumentNode.value], + ); + } + coercedValues[name] = coercedValue; + } + } + } + return coercedValues; +} + +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getDirectiveValues( + directiveDef: GraphQLDirective, + node: { +directives?: $ReadOnlyArray }, + variableValues?: ?ObjMap, +): void | { [argument: string]: mixed } { + const directiveNode = + node.directives && + find( + node.directives, + directive => directive.name.value === directiveDef.name, + ); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +function hasOwnProperty(obj: mixed, prop: string): boolean { + return Object.prototype.hasOwnProperty.call(obj, prop); +} diff --git a/node_modules/graphql/execution/values.mjs b/node_modules/graphql/execution/values.mjs new file mode 100644 index 0000000..b87623c --- /dev/null +++ b/node_modules/graphql/execution/values.mjs @@ -0,0 +1,216 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../error/GraphQLError'; +import find from '../jsutils/find'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import { coerceValue } from '../utilities/coerceValue'; +import { typeFromAST } from '../utilities/typeFromAST'; +import { valueFromAST } from '../utilities/valueFromAST'; +import { Kind } from '../language/kinds'; +import { print } from '../language/printer'; +import { isInputType, isNonNullType } from '../type/definition'; + +/** + * 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) { + var errors = []; + var coercedValues = {}; + + for (var i = 0; i < varDefNodes.length; i++) { + var varDefNode = varDefNodes[i]; + var varName = varDefNode.variable.name.value; + var varType = typeFromAST(schema, varDefNode.type); + + if (!isInputType(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + errors.push(new GraphQLError("Variable \"$".concat(varName, "\" expected value of type ") + "\"".concat(print(varDefNode.type), "\" which cannot be used as an input type."), [varDefNode.type])); + } else { + var hasValue = hasOwnProperty(inputs, varName); + var value = hasValue ? inputs[varName] : undefined; + + if (!hasValue && varDefNode.defaultValue) { + // If no value was provided to a variable with a default value, + // use the default value. + coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType); + } else if ((!hasValue || value === null) && isNonNullType(varType)) { + // If no value or a nullish value was provided to a variable with a + // non-null type (required), produce an error. + errors.push(new GraphQLError(hasValue ? "Variable \"$".concat(varName, "\" of non-null type ") + "\"".concat(inspect(varType), "\" must not be null.") : "Variable \"$".concat(varName, "\" of required type ") + "\"".concat(inspect(varType), "\" was not provided."), [varDefNode])); + } else if (hasValue) { + if (value === null) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[varName] = null; + } else { + // Otherwise, a non-null value was provided, coerce it to the expected + // type or report an error if coercion fails. + var coerced = coerceValue(value, varType, varDefNode); + var coercionErrors = coerced.errors; + + if (coercionErrors) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = coercionErrors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var error = _step.value; + error.message = "Variable \"$".concat(varName, "\" got invalid value ").concat(inspect(value), "; ") + error.message; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + errors.push.apply(errors, coercionErrors); + } else { + coercedValues[varName] = coerced.value; + } + } + } + } + } + + return errors.length === 0 ? { + errors: undefined, + coerced: coercedValues + } : { + errors: errors, + coerced: undefined + }; +} +/** + * 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 coercedValues = {}; + var argDefs = def.args; + var argNodes = node.arguments; + + if (!argDefs || !argNodes) { + return coercedValues; + } + + var argNodeMap = keyMap(argNodes, function (arg) { + return arg.name.value; + }); + + for (var i = 0; i < argDefs.length; i++) { + var argDef = argDefs[i]; + var name = argDef.name; + var argType = argDef.type; + var argumentNode = argNodeMap[name]; + var hasValue = void 0; + var isNull = void 0; + + if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) { + var variableName = argumentNode.value.name.value; + hasValue = variableValues && hasOwnProperty(variableValues, variableName); + isNull = variableValues && variableValues[variableName] === null; + } else { + hasValue = argumentNode != null; + isNull = argumentNode && argumentNode.value.kind === Kind.NULL; + } + + if (!hasValue && argDef.defaultValue !== undefined) { + // If no argument was provided where the definition has a default value, + // use the default value. + coercedValues[name] = argDef.defaultValue; + } else if ((!hasValue || isNull) && isNonNullType(argType)) { + // If no argument or a null value was provided to an argument with a + // non-null type (required), produce a field error. + if (isNull) { + throw new GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat(inspect(argType), "\" ") + 'must not be null.', [argumentNode.value]); + } else if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) { + var _variableName = argumentNode.value.name.value; + throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + "was provided the variable \"$".concat(_variableName, "\" ") + 'which was not provided a runtime value.', [argumentNode.value]); + } else { + throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + 'was not provided.', [node]); + } + } else if (hasValue) { + if (argumentNode.value.kind === Kind.NULL) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[name] = null; + } else if (argumentNode.value.kind === Kind.VARIABLE) { + var _variableName2 = argumentNode.value.name.value; + !variableValues ? invariant(0, 'Must exist for hasValue to be true.') : void 0; // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + coercedValues[name] = variableValues[_variableName2]; + } else { + var valueNode = argumentNode.value; + var coercedValue = valueFromAST(valueNode, argType, variableValues); + + if (coercedValue === undefined) { + // Note: ValuesOfCorrectType validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat(print(valueNode), "."), [argumentNode.value]); + } + + coercedValues[name] = coercedValue; + } + } + } + + return coercedValues; +} +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + +export function getDirectiveValues(directiveDef, node, variableValues) { + var directiveNode = node.directives && find(node.directives, function (directive) { + return directive.name.value === directiveDef.name; + }); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} \ No newline at end of file diff --git a/node_modules/graphql/graphql.js b/node_modules/graphql/graphql.js new file mode 100644 index 0000000..42992f0 --- /dev/null +++ b/node_modules/graphql/graphql.js @@ -0,0 +1,87 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.graphql = graphql; +exports.graphqlSync = graphqlSync; + +var _validate = require("./type/validate"); + +var _parser = require("./language/parser"); + +var _validate2 = require("./validation/validate"); + +var _execute = require("./execution/execute"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + var _arguments = arguments; + + /* eslint-enable no-redeclare */ + // Always return a Promise for a consistent API. + return new Promise(function (resolve) { + return resolve( // Extract arguments from object args if provided. + _arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver)); + }); +} +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + + +function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + var result = arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver); // Assert that the execution was synchronous. + + if (result.then) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function graphqlImpl(schema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // Validate Schema + var schemaValidationErrors = (0, _validate.validateSchema)(schema); + + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors + }; + } // Parse + + + var document; + + try { + document = (0, _parser.parse)(source); + } catch (syntaxError) { + return { + errors: [syntaxError] + }; + } // Validate + + + var validationErrors = (0, _validate2.validate)(schema, document); + + if (validationErrors.length > 0) { + return { + errors: validationErrors + }; + } // Execute + + + return (0, _execute.execute)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); +} \ No newline at end of file diff --git a/node_modules/graphql/graphql.js.flow b/node_modules/graphql/graphql.js.flow new file mode 100644 index 0000000..ab93016 --- /dev/null +++ b/node_modules/graphql/graphql.js.flow @@ -0,0 +1,209 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { validateSchema } from './type/validate'; +import { parse } from './language/parser'; +import { validate } from './validation/validate'; +import { execute } from './execution/execute'; +import type { ObjMap } from './jsutils/ObjMap'; +import type { Source } from './language/source'; +import type { GraphQLFieldResolver } from './type/definition'; +import type { GraphQLSchema } from './type/schema'; +import type { ExecutionResult } from './execution/execute'; +import type { MaybePromise } from './jsutils/MaybePromise'; + +/** + * This is the primary entry point function for fulfilling GraphQL operations + * by parsing, validating, and executing a GraphQL document along side a + * GraphQL schema. + * + * More sophisticated GraphQL servers, such as those which persist queries, + * may wish to separate the validation and execution phases to a static time + * tooling step, and a server runtime step. + * + * Accepts either an object with named arguments, or individual arguments: + * + * schema: + * The GraphQL type system to use when validating and executing a query. + * source: + * A GraphQL language formatted string representing the requested operation. + * rootValue: + * The value provided as the first argument to resolver functions on the top + * level type (e.g. the query object type). + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. + * variableValues: + * A mapping of variable name to runtime value to use for all variables + * defined in the requestString. + * operationName: + * The name of the operation to use if requestString contains multiple + * possible operations. Can be omitted if requestString contains only + * one operation. + * fieldResolver: + * A resolver function to use when one is not provided by the schema. + * If not provided, the default field resolver is used (which looks for a + * value or method on the source value with the field's name). + */ +export type GraphQLArgs = {| + schema: GraphQLSchema, + source: string | Source, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +|}; +declare function graphql(GraphQLArgs, ..._: []): Promise; +/* eslint-disable no-redeclare */ +declare function graphql( + schema: GraphQLSchema, + source: Source | string, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +): Promise; +export function graphql( + argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, +) { + /* eslint-enable no-redeclare */ + // Always return a Promise for a consistent API. + return new Promise(resolve => + resolve( + // Extract arguments from object args if provided. + arguments.length === 1 + ? graphqlImpl( + argsOrSchema.schema, + argsOrSchema.source, + argsOrSchema.rootValue, + argsOrSchema.contextValue, + argsOrSchema.variableValues, + argsOrSchema.operationName, + argsOrSchema.fieldResolver, + ) + : graphqlImpl( + argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ), + ), + ); +} + +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ +declare function graphqlSync(GraphQLArgs, ..._: []): ExecutionResult; +/* eslint-disable no-redeclare */ +declare function graphqlSync( + schema: GraphQLSchema, + source: Source | string, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +): ExecutionResult; +export function graphqlSync( + argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, +) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + const result = + arguments.length === 1 + ? graphqlImpl( + argsOrSchema.schema, + argsOrSchema.source, + argsOrSchema.rootValue, + argsOrSchema.contextValue, + argsOrSchema.variableValues, + argsOrSchema.operationName, + argsOrSchema.fieldResolver, + ) + : graphqlImpl( + argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ); + + // Assert that the execution was synchronous. + if (result.then) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function graphqlImpl( + schema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, +): MaybePromise { + // 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, + ); +} diff --git a/node_modules/graphql/graphql.mjs b/node_modules/graphql/graphql.mjs new file mode 100644 index 0000000..af7509a --- /dev/null +++ b/node_modules/graphql/graphql.mjs @@ -0,0 +1,74 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { validateSchema } from './type/validate'; +import { parse } from './language/parser'; +import { validate } from './validation/validate'; +import { execute } from './execution/execute'; +export function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + var _arguments = arguments; + + /* eslint-enable no-redeclare */ + // Always return a Promise for a consistent API. + return new Promise(function (resolve) { + return resolve( // Extract arguments from object args if provided. + _arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver)); + }); +} +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + +export function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + var result = arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver); // Assert that the execution was synchronous. + + if (result.then) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function graphqlImpl(schema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // Validate Schema + var schemaValidationErrors = validateSchema(schema); + + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors + }; + } // Parse + + + var document; + + try { + document = parse(source); + } catch (syntaxError) { + return { + errors: [syntaxError] + }; + } // Validate + + + var validationErrors = validate(schema, document); + + if (validationErrors.length > 0) { + return { + errors: validationErrors + }; + } // Execute + + + return execute(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); +} \ No newline at end of file diff --git a/node_modules/graphql/index.js b/node_modules/graphql/index.js new file mode 100644 index 0000000..c6e8f0c --- /dev/null +++ b/node_modules/graphql/index.js @@ -0,0 +1,1071 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "graphql", { + enumerable: true, + get: function get() { + return _graphql.graphql; + } +}); +Object.defineProperty(exports, "graphqlSync", { + enumerable: true, + get: function get() { + return _graphql.graphqlSync; + } +}); +Object.defineProperty(exports, "GraphQLSchema", { + enumerable: true, + get: function get() { + return _type.GraphQLSchema; + } +}); +Object.defineProperty(exports, "GraphQLScalarType", { + enumerable: true, + get: function get() { + return _type.GraphQLScalarType; + } +}); +Object.defineProperty(exports, "GraphQLObjectType", { + enumerable: true, + get: function get() { + return _type.GraphQLObjectType; + } +}); +Object.defineProperty(exports, "GraphQLInterfaceType", { + enumerable: true, + get: function get() { + return _type.GraphQLInterfaceType; + } +}); +Object.defineProperty(exports, "GraphQLUnionType", { + enumerable: true, + get: function get() { + return _type.GraphQLUnionType; + } +}); +Object.defineProperty(exports, "GraphQLEnumType", { + enumerable: true, + get: function get() { + return _type.GraphQLEnumType; + } +}); +Object.defineProperty(exports, "GraphQLInputObjectType", { + enumerable: true, + get: function get() { + return _type.GraphQLInputObjectType; + } +}); +Object.defineProperty(exports, "GraphQLList", { + enumerable: true, + get: function get() { + return _type.GraphQLList; + } +}); +Object.defineProperty(exports, "GraphQLNonNull", { + enumerable: true, + get: function get() { + return _type.GraphQLNonNull; + } +}); +Object.defineProperty(exports, "GraphQLDirective", { + enumerable: true, + get: function get() { + return _type.GraphQLDirective; + } +}); +Object.defineProperty(exports, "TypeKind", { + enumerable: true, + get: function get() { + return _type.TypeKind; + } +}); +Object.defineProperty(exports, "specifiedScalarTypes", { + enumerable: true, + get: function get() { + return _type.specifiedScalarTypes; + } +}); +Object.defineProperty(exports, "GraphQLInt", { + enumerable: true, + get: function get() { + return _type.GraphQLInt; + } +}); +Object.defineProperty(exports, "GraphQLFloat", { + enumerable: true, + get: function get() { + return _type.GraphQLFloat; + } +}); +Object.defineProperty(exports, "GraphQLString", { + enumerable: true, + get: function get() { + return _type.GraphQLString; + } +}); +Object.defineProperty(exports, "GraphQLBoolean", { + enumerable: true, + get: function get() { + return _type.GraphQLBoolean; + } +}); +Object.defineProperty(exports, "GraphQLID", { + enumerable: true, + get: function get() { + return _type.GraphQLID; + } +}); +Object.defineProperty(exports, "specifiedDirectives", { + enumerable: true, + get: function get() { + return _type.specifiedDirectives; + } +}); +Object.defineProperty(exports, "GraphQLIncludeDirective", { + enumerable: true, + get: function get() { + return _type.GraphQLIncludeDirective; + } +}); +Object.defineProperty(exports, "GraphQLSkipDirective", { + enumerable: true, + get: function get() { + return _type.GraphQLSkipDirective; + } +}); +Object.defineProperty(exports, "GraphQLDeprecatedDirective", { + enumerable: true, + get: function get() { + return _type.GraphQLDeprecatedDirective; + } +}); +Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", { + enumerable: true, + get: function get() { + return _type.DEFAULT_DEPRECATION_REASON; + } +}); +Object.defineProperty(exports, "SchemaMetaFieldDef", { + enumerable: true, + get: function get() { + return _type.SchemaMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeMetaFieldDef", { + enumerable: true, + get: function get() { + return _type.TypeMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeNameMetaFieldDef", { + enumerable: true, + get: function get() { + return _type.TypeNameMetaFieldDef; + } +}); +Object.defineProperty(exports, "introspectionTypes", { + enumerable: true, + get: function get() { + return _type.introspectionTypes; + } +}); +Object.defineProperty(exports, "__Schema", { + enumerable: true, + get: function get() { + return _type.__Schema; + } +}); +Object.defineProperty(exports, "__Directive", { + enumerable: true, + get: function get() { + return _type.__Directive; + } +}); +Object.defineProperty(exports, "__DirectiveLocation", { + enumerable: true, + get: function get() { + return _type.__DirectiveLocation; + } +}); +Object.defineProperty(exports, "__Type", { + enumerable: true, + get: function get() { + return _type.__Type; + } +}); +Object.defineProperty(exports, "__Field", { + enumerable: true, + get: function get() { + return _type.__Field; + } +}); +Object.defineProperty(exports, "__InputValue", { + enumerable: true, + get: function get() { + return _type.__InputValue; + } +}); +Object.defineProperty(exports, "__EnumValue", { + enumerable: true, + get: function get() { + return _type.__EnumValue; + } +}); +Object.defineProperty(exports, "__TypeKind", { + enumerable: true, + get: function get() { + return _type.__TypeKind; + } +}); +Object.defineProperty(exports, "isSchema", { + enumerable: true, + get: function get() { + return _type.isSchema; + } +}); +Object.defineProperty(exports, "isDirective", { + enumerable: true, + get: function get() { + return _type.isDirective; + } +}); +Object.defineProperty(exports, "isType", { + enumerable: true, + get: function get() { + return _type.isType; + } +}); +Object.defineProperty(exports, "isScalarType", { + enumerable: true, + get: function get() { + return _type.isScalarType; + } +}); +Object.defineProperty(exports, "isObjectType", { + enumerable: true, + get: function get() { + return _type.isObjectType; + } +}); +Object.defineProperty(exports, "isInterfaceType", { + enumerable: true, + get: function get() { + return _type.isInterfaceType; + } +}); +Object.defineProperty(exports, "isUnionType", { + enumerable: true, + get: function get() { + return _type.isUnionType; + } +}); +Object.defineProperty(exports, "isEnumType", { + enumerable: true, + get: function get() { + return _type.isEnumType; + } +}); +Object.defineProperty(exports, "isInputObjectType", { + enumerable: true, + get: function get() { + return _type.isInputObjectType; + } +}); +Object.defineProperty(exports, "isListType", { + enumerable: true, + get: function get() { + return _type.isListType; + } +}); +Object.defineProperty(exports, "isNonNullType", { + enumerable: true, + get: function get() { + return _type.isNonNullType; + } +}); +Object.defineProperty(exports, "isInputType", { + enumerable: true, + get: function get() { + return _type.isInputType; + } +}); +Object.defineProperty(exports, "isOutputType", { + enumerable: true, + get: function get() { + return _type.isOutputType; + } +}); +Object.defineProperty(exports, "isLeafType", { + enumerable: true, + get: function get() { + return _type.isLeafType; + } +}); +Object.defineProperty(exports, "isCompositeType", { + enumerable: true, + get: function get() { + return _type.isCompositeType; + } +}); +Object.defineProperty(exports, "isAbstractType", { + enumerable: true, + get: function get() { + return _type.isAbstractType; + } +}); +Object.defineProperty(exports, "isWrappingType", { + enumerable: true, + get: function get() { + return _type.isWrappingType; + } +}); +Object.defineProperty(exports, "isNullableType", { + enumerable: true, + get: function get() { + return _type.isNullableType; + } +}); +Object.defineProperty(exports, "isNamedType", { + enumerable: true, + get: function get() { + return _type.isNamedType; + } +}); +Object.defineProperty(exports, "isRequiredArgument", { + enumerable: true, + get: function get() { + return _type.isRequiredArgument; + } +}); +Object.defineProperty(exports, "isRequiredInputField", { + enumerable: true, + get: function get() { + return _type.isRequiredInputField; + } +}); +Object.defineProperty(exports, "isSpecifiedScalarType", { + enumerable: true, + get: function get() { + return _type.isSpecifiedScalarType; + } +}); +Object.defineProperty(exports, "isIntrospectionType", { + enumerable: true, + get: function get() { + return _type.isIntrospectionType; + } +}); +Object.defineProperty(exports, "isSpecifiedDirective", { + enumerable: true, + get: function get() { + return _type.isSpecifiedDirective; + } +}); +Object.defineProperty(exports, "assertType", { + enumerable: true, + get: function get() { + return _type.assertType; + } +}); +Object.defineProperty(exports, "assertScalarType", { + enumerable: true, + get: function get() { + return _type.assertScalarType; + } +}); +Object.defineProperty(exports, "assertObjectType", { + enumerable: true, + get: function get() { + return _type.assertObjectType; + } +}); +Object.defineProperty(exports, "assertInterfaceType", { + enumerable: true, + get: function get() { + return _type.assertInterfaceType; + } +}); +Object.defineProperty(exports, "assertUnionType", { + enumerable: true, + get: function get() { + return _type.assertUnionType; + } +}); +Object.defineProperty(exports, "assertEnumType", { + enumerable: true, + get: function get() { + return _type.assertEnumType; + } +}); +Object.defineProperty(exports, "assertInputObjectType", { + enumerable: true, + get: function get() { + return _type.assertInputObjectType; + } +}); +Object.defineProperty(exports, "assertListType", { + enumerable: true, + get: function get() { + return _type.assertListType; + } +}); +Object.defineProperty(exports, "assertNonNullType", { + enumerable: true, + get: function get() { + return _type.assertNonNullType; + } +}); +Object.defineProperty(exports, "assertInputType", { + enumerable: true, + get: function get() { + return _type.assertInputType; + } +}); +Object.defineProperty(exports, "assertOutputType", { + enumerable: true, + get: function get() { + return _type.assertOutputType; + } +}); +Object.defineProperty(exports, "assertLeafType", { + enumerable: true, + get: function get() { + return _type.assertLeafType; + } +}); +Object.defineProperty(exports, "assertCompositeType", { + enumerable: true, + get: function get() { + return _type.assertCompositeType; + } +}); +Object.defineProperty(exports, "assertAbstractType", { + enumerable: true, + get: function get() { + return _type.assertAbstractType; + } +}); +Object.defineProperty(exports, "assertWrappingType", { + enumerable: true, + get: function get() { + return _type.assertWrappingType; + } +}); +Object.defineProperty(exports, "assertNullableType", { + enumerable: true, + get: function get() { + return _type.assertNullableType; + } +}); +Object.defineProperty(exports, "assertNamedType", { + enumerable: true, + get: function get() { + return _type.assertNamedType; + } +}); +Object.defineProperty(exports, "getNullableType", { + enumerable: true, + get: function get() { + return _type.getNullableType; + } +}); +Object.defineProperty(exports, "getNamedType", { + enumerable: true, + get: function get() { + return _type.getNamedType; + } +}); +Object.defineProperty(exports, "validateSchema", { + enumerable: true, + get: function get() { + return _type.validateSchema; + } +}); +Object.defineProperty(exports, "assertValidSchema", { + enumerable: true, + get: function get() { + return _type.assertValidSchema; + } +}); +Object.defineProperty(exports, "Source", { + enumerable: true, + get: function get() { + return _language.Source; + } +}); +Object.defineProperty(exports, "getLocation", { + enumerable: true, + get: function get() { + return _language.getLocation; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _language.parse; + } +}); +Object.defineProperty(exports, "parseValue", { + enumerable: true, + get: function get() { + return _language.parseValue; + } +}); +Object.defineProperty(exports, "parseType", { + enumerable: true, + get: function get() { + return _language.parseType; + } +}); +Object.defineProperty(exports, "print", { + enumerable: true, + get: function get() { + return _language.print; + } +}); +Object.defineProperty(exports, "visit", { + enumerable: true, + get: function get() { + return _language.visit; + } +}); +Object.defineProperty(exports, "visitInParallel", { + enumerable: true, + get: function get() { + return _language.visitInParallel; + } +}); +Object.defineProperty(exports, "visitWithTypeInfo", { + enumerable: true, + get: function get() { + return _language.visitWithTypeInfo; + } +}); +Object.defineProperty(exports, "getVisitFn", { + enumerable: true, + get: function get() { + return _language.getVisitFn; + } +}); +Object.defineProperty(exports, "Kind", { + enumerable: true, + get: function get() { + return _language.Kind; + } +}); +Object.defineProperty(exports, "TokenKind", { + enumerable: true, + get: function get() { + return _language.TokenKind; + } +}); +Object.defineProperty(exports, "DirectiveLocation", { + enumerable: true, + get: function get() { + return _language.DirectiveLocation; + } +}); +Object.defineProperty(exports, "BREAK", { + enumerable: true, + get: function get() { + return _language.BREAK; + } +}); +Object.defineProperty(exports, "isDefinitionNode", { + enumerable: true, + get: function get() { + return _language.isDefinitionNode; + } +}); +Object.defineProperty(exports, "isExecutableDefinitionNode", { + enumerable: true, + get: function get() { + return _language.isExecutableDefinitionNode; + } +}); +Object.defineProperty(exports, "isSelectionNode", { + enumerable: true, + get: function get() { + return _language.isSelectionNode; + } +}); +Object.defineProperty(exports, "isValueNode", { + enumerable: true, + get: function get() { + return _language.isValueNode; + } +}); +Object.defineProperty(exports, "isTypeNode", { + enumerable: true, + get: function get() { + return _language.isTypeNode; + } +}); +Object.defineProperty(exports, "isTypeSystemDefinitionNode", { + enumerable: true, + get: function get() { + return _language.isTypeSystemDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeDefinitionNode", { + enumerable: true, + get: function get() { + return _language.isTypeDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeSystemExtensionNode", { + enumerable: true, + get: function get() { + return _language.isTypeSystemExtensionNode; + } +}); +Object.defineProperty(exports, "isTypeExtensionNode", { + enumerable: true, + get: function get() { + return _language.isTypeExtensionNode; + } +}); +Object.defineProperty(exports, "execute", { + enumerable: true, + get: function get() { + return _execution.execute; + } +}); +Object.defineProperty(exports, "defaultFieldResolver", { + enumerable: true, + get: function get() { + return _execution.defaultFieldResolver; + } +}); +Object.defineProperty(exports, "responsePathAsArray", { + enumerable: true, + get: function get() { + return _execution.responsePathAsArray; + } +}); +Object.defineProperty(exports, "getDirectiveValues", { + enumerable: true, + get: function get() { + return _execution.getDirectiveValues; + } +}); +Object.defineProperty(exports, "subscribe", { + enumerable: true, + get: function get() { + return _subscription.subscribe; + } +}); +Object.defineProperty(exports, "createSourceEventStream", { + enumerable: true, + get: function get() { + return _subscription.createSourceEventStream; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function get() { + return _validation.validate; + } +}); +Object.defineProperty(exports, "ValidationContext", { + enumerable: true, + get: function get() { + return _validation.ValidationContext; + } +}); +Object.defineProperty(exports, "specifiedRules", { + enumerable: true, + get: function get() { + return _validation.specifiedRules; + } +}); +Object.defineProperty(exports, "FieldsOnCorrectTypeRule", { + enumerable: true, + get: function get() { + return _validation.FieldsOnCorrectTypeRule; + } +}); +Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", { + enumerable: true, + get: function get() { + return _validation.FragmentsOnCompositeTypesRule; + } +}); +Object.defineProperty(exports, "KnownArgumentNamesRule", { + enumerable: true, + get: function get() { + return _validation.KnownArgumentNamesRule; + } +}); +Object.defineProperty(exports, "KnownDirectivesRule", { + enumerable: true, + get: function get() { + return _validation.KnownDirectivesRule; + } +}); +Object.defineProperty(exports, "KnownFragmentNamesRule", { + enumerable: true, + get: function get() { + return _validation.KnownFragmentNamesRule; + } +}); +Object.defineProperty(exports, "KnownTypeNamesRule", { + enumerable: true, + get: function get() { + return _validation.KnownTypeNamesRule; + } +}); +Object.defineProperty(exports, "LoneAnonymousOperationRule", { + enumerable: true, + get: function get() { + return _validation.LoneAnonymousOperationRule; + } +}); +Object.defineProperty(exports, "NoFragmentCyclesRule", { + enumerable: true, + get: function get() { + return _validation.NoFragmentCyclesRule; + } +}); +Object.defineProperty(exports, "NoUndefinedVariablesRule", { + enumerable: true, + get: function get() { + return _validation.NoUndefinedVariablesRule; + } +}); +Object.defineProperty(exports, "NoUnusedFragmentsRule", { + enumerable: true, + get: function get() { + return _validation.NoUnusedFragmentsRule; + } +}); +Object.defineProperty(exports, "NoUnusedVariablesRule", { + enumerable: true, + get: function get() { + return _validation.NoUnusedVariablesRule; + } +}); +Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", { + enumerable: true, + get: function get() { + return _validation.OverlappingFieldsCanBeMergedRule; + } +}); +Object.defineProperty(exports, "PossibleFragmentSpreadsRule", { + enumerable: true, + get: function get() { + return _validation.PossibleFragmentSpreadsRule; + } +}); +Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", { + enumerable: true, + get: function get() { + return _validation.ProvidedRequiredArgumentsRule; + } +}); +Object.defineProperty(exports, "ScalarLeafsRule", { + enumerable: true, + get: function get() { + return _validation.ScalarLeafsRule; + } +}); +Object.defineProperty(exports, "SingleFieldSubscriptionsRule", { + enumerable: true, + get: function get() { + return _validation.SingleFieldSubscriptionsRule; + } +}); +Object.defineProperty(exports, "UniqueArgumentNamesRule", { + enumerable: true, + get: function get() { + return _validation.UniqueArgumentNamesRule; + } +}); +Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", { + enumerable: true, + get: function get() { + return _validation.UniqueDirectivesPerLocationRule; + } +}); +Object.defineProperty(exports, "UniqueFragmentNamesRule", { + enumerable: true, + get: function get() { + return _validation.UniqueFragmentNamesRule; + } +}); +Object.defineProperty(exports, "UniqueInputFieldNamesRule", { + enumerable: true, + get: function get() { + return _validation.UniqueInputFieldNamesRule; + } +}); +Object.defineProperty(exports, "UniqueOperationNamesRule", { + enumerable: true, + get: function get() { + return _validation.UniqueOperationNamesRule; + } +}); +Object.defineProperty(exports, "UniqueVariableNamesRule", { + enumerable: true, + get: function get() { + return _validation.UniqueVariableNamesRule; + } +}); +Object.defineProperty(exports, "ValuesOfCorrectTypeRule", { + enumerable: true, + get: function get() { + return _validation.ValuesOfCorrectTypeRule; + } +}); +Object.defineProperty(exports, "VariablesAreInputTypesRule", { + enumerable: true, + get: function get() { + return _validation.VariablesAreInputTypesRule; + } +}); +Object.defineProperty(exports, "VariablesInAllowedPositionRule", { + enumerable: true, + get: function get() { + return _validation.VariablesInAllowedPositionRule; + } +}); +Object.defineProperty(exports, "GraphQLError", { + enumerable: true, + get: function get() { + return _error.GraphQLError; + } +}); +Object.defineProperty(exports, "formatError", { + enumerable: true, + get: function get() { + return _error.formatError; + } +}); +Object.defineProperty(exports, "printError", { + enumerable: true, + get: function get() { + return _error.printError; + } +}); +Object.defineProperty(exports, "getIntrospectionQuery", { + enumerable: true, + get: function get() { + return _utilities.getIntrospectionQuery; + } +}); +Object.defineProperty(exports, "introspectionQuery", { + enumerable: true, + get: function get() { + return _utilities.introspectionQuery; + } +}); +Object.defineProperty(exports, "getOperationAST", { + enumerable: true, + get: function get() { + return _utilities.getOperationAST; + } +}); +Object.defineProperty(exports, "getOperationRootType", { + enumerable: true, + get: function get() { + return _utilities.getOperationRootType; + } +}); +Object.defineProperty(exports, "introspectionFromSchema", { + enumerable: true, + get: function get() { + return _utilities.introspectionFromSchema; + } +}); +Object.defineProperty(exports, "buildClientSchema", { + enumerable: true, + get: function get() { + return _utilities.buildClientSchema; + } +}); +Object.defineProperty(exports, "buildASTSchema", { + enumerable: true, + get: function get() { + return _utilities.buildASTSchema; + } +}); +Object.defineProperty(exports, "buildSchema", { + enumerable: true, + get: function get() { + return _utilities.buildSchema; + } +}); +Object.defineProperty(exports, "getDescription", { + enumerable: true, + get: function get() { + return _utilities.getDescription; + } +}); +Object.defineProperty(exports, "extendSchema", { + enumerable: true, + get: function get() { + return _utilities.extendSchema; + } +}); +Object.defineProperty(exports, "lexicographicSortSchema", { + enumerable: true, + get: function get() { + return _utilities.lexicographicSortSchema; + } +}); +Object.defineProperty(exports, "printSchema", { + enumerable: true, + get: function get() { + return _utilities.printSchema; + } +}); +Object.defineProperty(exports, "printIntrospectionSchema", { + enumerable: true, + get: function get() { + return _utilities.printIntrospectionSchema; + } +}); +Object.defineProperty(exports, "printType", { + enumerable: true, + get: function get() { + return _utilities.printType; + } +}); +Object.defineProperty(exports, "typeFromAST", { + enumerable: true, + get: function get() { + return _utilities.typeFromAST; + } +}); +Object.defineProperty(exports, "valueFromAST", { + enumerable: true, + get: function get() { + return _utilities.valueFromAST; + } +}); +Object.defineProperty(exports, "valueFromASTUntyped", { + enumerable: true, + get: function get() { + return _utilities.valueFromASTUntyped; + } +}); +Object.defineProperty(exports, "astFromValue", { + enumerable: true, + get: function get() { + return _utilities.astFromValue; + } +}); +Object.defineProperty(exports, "TypeInfo", { + enumerable: true, + get: function get() { + return _utilities.TypeInfo; + } +}); +Object.defineProperty(exports, "coerceValue", { + enumerable: true, + get: function get() { + return _utilities.coerceValue; + } +}); +Object.defineProperty(exports, "isValidJSValue", { + enumerable: true, + get: function get() { + return _utilities.isValidJSValue; + } +}); +Object.defineProperty(exports, "isValidLiteralValue", { + enumerable: true, + get: function get() { + return _utilities.isValidLiteralValue; + } +}); +Object.defineProperty(exports, "concatAST", { + enumerable: true, + get: function get() { + return _utilities.concatAST; + } +}); +Object.defineProperty(exports, "separateOperations", { + enumerable: true, + get: function get() { + return _utilities.separateOperations; + } +}); +Object.defineProperty(exports, "isEqualType", { + enumerable: true, + get: function get() { + return _utilities.isEqualType; + } +}); +Object.defineProperty(exports, "isTypeSubTypeOf", { + enumerable: true, + get: function get() { + return _utilities.isTypeSubTypeOf; + } +}); +Object.defineProperty(exports, "doTypesOverlap", { + enumerable: true, + get: function get() { + return _utilities.doTypesOverlap; + } +}); +Object.defineProperty(exports, "assertValidName", { + enumerable: true, + get: function get() { + return _utilities.assertValidName; + } +}); +Object.defineProperty(exports, "isValidNameError", { + enumerable: true, + get: function get() { + return _utilities.isValidNameError; + } +}); +Object.defineProperty(exports, "findBreakingChanges", { + enumerable: true, + get: function get() { + return _utilities.findBreakingChanges; + } +}); +Object.defineProperty(exports, "findDangerousChanges", { + enumerable: true, + get: function get() { + return _utilities.findDangerousChanges; + } +}); +Object.defineProperty(exports, "BreakingChangeType", { + enumerable: true, + get: function get() { + return _utilities.BreakingChangeType; + } +}); +Object.defineProperty(exports, "DangerousChangeType", { + enumerable: true, + get: function get() { + return _utilities.DangerousChangeType; + } +}); +Object.defineProperty(exports, "findDeprecatedUsages", { + enumerable: true, + get: function get() { + return _utilities.findDeprecatedUsages; + } +}); + +var _graphql = require("./graphql"); + +var _type = require("./type"); + +var _language = require("./language"); + +var _execution = require("./execution"); + +var _subscription = require("./subscription"); + +var _validation = require("./validation"); + +var _error = require("./error"); + +var _utilities = require("./utilities"); \ No newline at end of file diff --git a/node_modules/graphql/index.js.flow b/node_modules/graphql/index.js.flow new file mode 100644 index 0000000..3c4ee54 --- /dev/null +++ b/node_modules/graphql/index.js.flow @@ -0,0 +1,429 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * GraphQL.js provides a reference implementation for the GraphQL specification + * but is also a useful utility for operating on GraphQL files and building + * sophisticated tools. + * + * This primary module exports a general purpose function for fulfilling all + * steps of the GraphQL specification in a single operation, but also includes + * utilities for every part of the GraphQL specification: + * + * - Parsing the GraphQL language. + * - Building a GraphQL type schema. + * - Validating a GraphQL request against a type schema. + * - Executing a GraphQL request against a type schema. + * + * This also includes utility functions for operating on GraphQL types and + * GraphQL documents to facilitate building tools. + * + * You may also import from each sub-directory directly. For example, the + * following two import statements are equivalent: + * + * import { parse } from 'graphql'; + * import { parse } from 'graphql/language'; + */ + +// The primary entry point into fulfilling a GraphQL request. +export type { GraphQLArgs } from './graphql'; +export { graphql, graphqlSync } from './graphql'; + +// Create and operate on GraphQL type definitions and schema. +export { + GraphQLSchema, + // Definitions + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, + GraphQLDirective, + // "Enum" of Type Kinds + TypeKind, + // Scalars + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, + // Built-in Directives defined by the Spec + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, + // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, + // GraphQL Types for introspection. + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + // 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 + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, + // Un-modifiers + getNullableType, + getNamedType, + // Validate GraphQL schema. + validateSchema, + assertValidSchema, +} from './type'; + +export type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + Thunk, + GraphQLSchemaConfig, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLEnumTypeConfig, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueConfigMap, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldConfigMap, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInterfaceTypeConfig, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLResolveInfo, + ResponsePath, + GraphQLScalarTypeConfig, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLDirectiveConfig, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from './type'; + +// Parse and operate on GraphQL language source files. +export { + Source, + getLocation, + // Parse + parse, + parseValue, + parseType, + // Print + print, + // Visit + visit, + visitInParallel, + visitWithTypeInfo, + getVisitFn, + Kind, + TokenKind, + DirectiveLocation, + BREAK, + // Predicates + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, +} from './language'; + +export type { + Lexer, + ParseOptions, + SourceLocation, + // Visitor utilities + ASTVisitor, + Visitor, + VisitFn, + VisitorKeyMap, + // AST nodes + Location, + Token, + ASTNode, + ASTKindToNode, + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, + KindEnum, + TokenKindEnum, + DirectiveLocationEnum, +} from './language'; + +// Execute GraphQL queries. +export { + execute, + defaultFieldResolver, + responsePathAsArray, + getDirectiveValues, +} from './execution'; + +export type { ExecutionArgs, ExecutionResult } from './execution'; + +export { subscribe, createSourceEventStream } from './subscription'; + +// Validate GraphQL queries. +export { + validate, + ValidationContext, + // All validation rules in the GraphQL Specification. + specifiedRules, + // Individual validation rules. + 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, +} from './validation'; + +export type { ValidationRule } from './validation'; + +// Create, format, and print GraphQL errors. +export { GraphQLError, formatError, printError } from './error'; + +export type { GraphQLFormattedError } from './error'; + +// 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, + // @deprecated: use getIntrospectionQuery - will be removed in v15 + introspectionQuery, + // Gets the target Operation from a Document + getOperationAST, + // Gets the Type for the target Operation AST. + getOperationRootType, + // Convert a GraphQLSchema to an IntrospectionQuery + introspectionFromSchema, + // Build a GraphQLSchema from an introspection result. + buildClientSchema, + // Build a GraphQLSchema from a parsed GraphQL Schema language AST. + buildASTSchema, + // Build a GraphQLSchema from a GraphQL schema language document. + buildSchema, + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16 + getDescription, + // Extends an existing GraphQLSchema from a parsed GraphQL Schema + // language AST. + extendSchema, + // Sort a GraphQLSchema. + lexicographicSortSchema, + // Print a GraphQLSchema to GraphQL Schema language. + printSchema, + // Prints the built-in introspection schema in the Schema Language + // format. + printIntrospectionSchema, + // Print a GraphQLType to GraphQL Schema language. + printType, + // 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, + // Coerces a JavaScript value to a GraphQL type, or produces errors. + coerceValue, + // @deprecated use coerceValue - will be removed in v15 + isValidJSValue, + // @deprecated use validation - will be removed in v15 + isValidLiteralValue, + // Concatenates multiple AST together. + concatAST, + // Separates an AST into an AST per Operation. + separateOperations, + // 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. + findBreakingChanges, + findDangerousChanges, + BreakingChangeType, + DangerousChangeType, + // Report all deprecated usage within a GraphQL document. + findDeprecatedUsages, +} from './utilities'; + +export type { + BuildSchemaOptions, + BreakingChange, + DangerousChange, + IntrospectionOptions, + IntrospectionDirective, + IntrospectionEnumType, + IntrospectionEnumValue, + IntrospectionField, + IntrospectionInputObjectType, + IntrospectionInputType, + IntrospectionInputTypeRef, + IntrospectionInputValue, + IntrospectionInterfaceType, + IntrospectionListTypeRef, + IntrospectionNamedTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionObjectType, + IntrospectionOutputType, + IntrospectionOutputTypeRef, + IntrospectionQuery, + IntrospectionScalarType, + IntrospectionSchema, + IntrospectionType, + IntrospectionTypeRef, + IntrospectionUnionType, +} from './utilities'; diff --git a/node_modules/graphql/index.mjs b/node_modules/graphql/index.mjs new file mode 100644 index 0000000..35f72d2 --- /dev/null +++ b/node_modules/graphql/index.mjs @@ -0,0 +1,98 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * GraphQL.js provides a reference implementation for the GraphQL specification + * but is also a useful utility for operating on GraphQL files and building + * sophisticated tools. + * + * This primary module exports a general purpose function for fulfilling all + * steps of the GraphQL specification in a single operation, but also includes + * utilities for every part of the GraphQL specification: + * + * - Parsing the GraphQL language. + * - Building a GraphQL type schema. + * - Validating a GraphQL request against a type schema. + * - Executing a GraphQL request against a type schema. + * + * This also includes utility functions for operating on GraphQL types and + * GraphQL documents to facilitate building tools. + * + * You may also import from each sub-directory directly. For example, the + * following two import statements are equivalent: + * + * import { parse } from 'graphql'; + * import { parse } from 'graphql/language'; + */ +// The primary entry point into fulfilling a GraphQL request. +export { graphql, graphqlSync } from './graphql'; // Create and operate on GraphQL type definitions and schema. + +export { GraphQLSchema, // Definitions +GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLDirective, // "Enum" of Type Kinds +TypeKind, // Scalars +specifiedScalarTypes, GraphQLInt, GraphQLFloat, GraphQLString, GraphQLBoolean, GraphQLID, // Built-in Directives defined by the Spec +specifiedDirectives, GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, // Constant Deprecation Reason +DEFAULT_DEPRECATION_REASON, // Meta-field definitions. +SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef, // GraphQL Types for introspection. +introspectionTypes, __Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind, // 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 +assertType, assertScalarType, assertObjectType, assertInterfaceType, assertUnionType, assertEnumType, assertInputObjectType, assertListType, assertNonNullType, assertInputType, assertOutputType, assertLeafType, assertCompositeType, assertAbstractType, assertWrappingType, assertNullableType, assertNamedType, // Un-modifiers +getNullableType, getNamedType, // Validate GraphQL schema. +validateSchema, assertValidSchema } from './type'; +// Parse and operate on GraphQL language source files. +export { Source, getLocation, // Parse +parse, parseValue, parseType, // Print +print, // Visit +visit, visitInParallel, visitWithTypeInfo, getVisitFn, Kind, TokenKind, DirectiveLocation, BREAK, // Predicates +isDefinitionNode, isExecutableDefinitionNode, isSelectionNode, isValueNode, isTypeNode, isTypeSystemDefinitionNode, isTypeDefinitionNode, isTypeSystemExtensionNode, isTypeExtensionNode } from './language'; +// Execute GraphQL queries. +export { execute, defaultFieldResolver, responsePathAsArray, getDirectiveValues } from './execution'; +export { subscribe, createSourceEventStream } from './subscription'; // Validate GraphQL queries. + +export { validate, ValidationContext, // All validation rules in the GraphQL Specification. +specifiedRules, // Individual validation rules. +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 } from './validation'; +// Create, format, and print GraphQL errors. +export { GraphQLError, formatError, printError } from './error'; +// 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, // @deprecated: use getIntrospectionQuery - will be removed in v15 +introspectionQuery, // Gets the target Operation from a Document +getOperationAST, // Gets the Type for the target Operation AST. +getOperationRootType, // Convert a GraphQLSchema to an IntrospectionQuery +introspectionFromSchema, // Build a GraphQLSchema from an introspection result. +buildClientSchema, // Build a GraphQLSchema from a parsed GraphQL Schema language AST. +buildASTSchema, // Build a GraphQLSchema from a GraphQL schema language document. +buildSchema, // @deprecated: Get the description from a schema AST node and supports legacy +// syntax for specifying descriptions - will be removed in v16 +getDescription, // Extends an existing GraphQLSchema from a parsed GraphQL Schema +// language AST. +extendSchema, // Sort a GraphQLSchema. +lexicographicSortSchema, // Print a GraphQLSchema to GraphQL Schema language. +printSchema, // Prints the built-in introspection schema in the Schema Language +// format. +printIntrospectionSchema, // Print a GraphQLType to GraphQL Schema language. +printType, // 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, // Coerces a JavaScript value to a GraphQL type, or produces errors. +coerceValue, // @deprecated use coerceValue - will be removed in v15 +isValidJSValue, // @deprecated use validation - will be removed in v15 +isValidLiteralValue, // Concatenates multiple AST together. +concatAST, // Separates an AST into an AST per Operation. +separateOperations, // 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. +findBreakingChanges, findDangerousChanges, BreakingChangeType, DangerousChangeType, // Report all deprecated usage within a GraphQL document. +findDeprecatedUsages } from './utilities'; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/MaybePromise.js b/node_modules/graphql/jsutils/MaybePromise.js new file mode 100644 index 0000000..9a390c3 --- /dev/null +++ b/node_modules/graphql/jsutils/MaybePromise.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/MaybePromise.js.flow b/node_modules/graphql/jsutils/MaybePromise.js.flow new file mode 100644 index 0000000..c4b6b6e --- /dev/null +++ b/node_modules/graphql/jsutils/MaybePromise.js.flow @@ -0,0 +1,10 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export type MaybePromise<+T> = Promise | T; diff --git a/node_modules/graphql/jsutils/MaybePromise.mjs b/node_modules/graphql/jsutils/MaybePromise.mjs new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/graphql/jsutils/ObjMap.js b/node_modules/graphql/jsutils/ObjMap.js new file mode 100644 index 0000000..9a390c3 --- /dev/null +++ b/node_modules/graphql/jsutils/ObjMap.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/ObjMap.js.flow b/node_modules/graphql/jsutils/ObjMap.js.flow new file mode 100644 index 0000000..140e60f --- /dev/null +++ b/node_modules/graphql/jsutils/ObjMap.js.flow @@ -0,0 +1,10 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export type ObjMap = { [key: string]: T, __proto__: null }; diff --git a/node_modules/graphql/jsutils/ObjMap.mjs b/node_modules/graphql/jsutils/ObjMap.mjs new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/graphql/jsutils/dedent.js b/node_modules/graphql/jsutils/dedent.js new file mode 100644 index 0000000..cf31056 --- /dev/null +++ b/node_modules/graphql/jsutils/dedent.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = dedent; + +var _invariant = _interopRequireDefault(require("./invariant")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * fixes indentation by removing leading spaces and tabs from each line + */ +function fixIndent(str) { + var trimmedStr = str.replace(/^\n*/m, '') // remove leading newline + .replace(/[ \t]*$/, ''); // remove trailing spaces and tabs + + var indentMatch = /^[ \t]*/.exec(trimmedStr); + !Array.isArray(indentMatch) ? (0, _invariant.default)(0) : void 0; + var indent = indentMatch[0]; // figure out indent + + return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent +} +/** + * An ES6 string tag that fixes indentation. Also removes leading newlines + * and trailing spaces and tabs, but keeps trailing newlines. + * + * Example usage: + * const str = dedent` + * { + * test + * } + * `; + * str === "{\n test\n}\n"; + */ + + +function dedent(strings) { + for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + values[_key - 1] = arguments[_key]; + } + + // when used as an ordinary function, allow passing a singleton string + var strArray = typeof strings === 'string' ? [strings] : strings; + var numValues = values.length; + var str = strArray.reduce(function (prev, cur, index) { + var next = prev + cur; + + if (index < numValues) { + next += values[index]; // interpolation + } + + return next; + }, ''); + return fixIndent(str); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/dedent.js.flow b/node_modules/graphql/jsutils/dedent.js.flow new file mode 100644 index 0000000..540f65e --- /dev/null +++ b/node_modules/graphql/jsutils/dedent.js.flow @@ -0,0 +1,54 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from './invariant'; + +/** + * fixes indentation by removing leading spaces and tabs from each line + */ +function fixIndent(str: string): string { + const trimmedStr = str + .replace(/^\n*/m, '') // remove leading newline + .replace(/[ \t]*$/, ''); // remove trailing spaces and tabs + const indentMatch = /^[ \t]*/.exec(trimmedStr); + invariant(Array.isArray(indentMatch)); + const indent = indentMatch[0]; // figure out indent + return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent +} + +/** + * An ES6 string tag that fixes indentation. Also removes leading newlines + * and trailing spaces and tabs, but keeps trailing newlines. + * + * Example usage: + * const str = dedent` + * { + * test + * } + * `; + * str === "{\n test\n}\n"; + */ +export default function dedent( + strings: string | Array, + ...values: Array +): string { + // when used as an ordinary function, allow passing a singleton string + const strArray = typeof strings === 'string' ? [strings] : strings; + const numValues = values.length; + + const str = strArray.reduce((prev, cur, index) => { + let next = prev + cur; + if (index < numValues) { + next += values[index]; // interpolation + } + return next; + }, ''); + + return fixIndent(str); +} diff --git a/node_modules/graphql/jsutils/dedent.mjs b/node_modules/graphql/jsutils/dedent.mjs new file mode 100644 index 0000000..87eb3c9 --- /dev/null +++ b/node_modules/graphql/jsutils/dedent.mjs @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from './invariant'; +/** + * fixes indentation by removing leading spaces and tabs from each line + */ + +function fixIndent(str) { + var trimmedStr = str.replace(/^\n*/m, '') // remove leading newline + .replace(/[ \t]*$/, ''); // remove trailing spaces and tabs + + var indentMatch = /^[ \t]*/.exec(trimmedStr); + !Array.isArray(indentMatch) ? invariant(0) : void 0; + var indent = indentMatch[0]; // figure out indent + + return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent +} +/** + * An ES6 string tag that fixes indentation. Also removes leading newlines + * and trailing spaces and tabs, but keeps trailing newlines. + * + * Example usage: + * const str = dedent` + * { + * test + * } + * `; + * str === "{\n test\n}\n"; + */ + + +export default function dedent(strings) { + for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + values[_key - 1] = arguments[_key]; + } + + // when used as an ordinary function, allow passing a singleton string + var strArray = typeof strings === 'string' ? [strings] : strings; + var numValues = values.length; + var str = strArray.reduce(function (prev, cur, index) { + var next = prev + cur; + + if (index < numValues) { + next += values[index]; // interpolation + } + + return next; + }, ''); + return fixIndent(str); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/defineToJSON.js b/node_modules/graphql/jsutils/defineToJSON.js new file mode 100644 index 0000000..b5a2513 --- /dev/null +++ b/node_modules/graphql/jsutils/defineToJSON.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = applyToJSON; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The `applyToJSON()` function defines toJSON() and inspect() prototype + * methods which are aliases for toString(). + */ +function applyToJSON(classObject) { + classObject.prototype.toJSON = classObject.prototype.inspect = classObject.prototype.toString; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/defineToJSON.js.flow b/node_modules/graphql/jsutils/defineToJSON.js.flow new file mode 100644 index 0000000..fde3f6c --- /dev/null +++ b/node_modules/graphql/jsutils/defineToJSON.js.flow @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * The `applyToJSON()` function defines toJSON() and inspect() prototype + * methods which are aliases for toString(). + */ +export default function applyToJSON(classObject: Class): void { + classObject.prototype.toJSON = classObject.prototype.inspect = + classObject.prototype.toString; +} diff --git a/node_modules/graphql/jsutils/defineToJSON.mjs b/node_modules/graphql/jsutils/defineToJSON.mjs new file mode 100644 index 0000000..ba22494 --- /dev/null +++ b/node_modules/graphql/jsutils/defineToJSON.mjs @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The `applyToJSON()` function defines toJSON() and inspect() prototype + * methods which are aliases for toString(). + */ +export default function applyToJSON(classObject) { + classObject.prototype.toJSON = classObject.prototype.inspect = classObject.prototype.toString; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/defineToStringTag.js b/node_modules/graphql/jsutils/defineToStringTag.js new file mode 100644 index 0000000..fedef31 --- /dev/null +++ b/node_modules/graphql/jsutils/defineToStringTag.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = applyToStringTag; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The `applyToStringTag()` function checks first to see if the runtime + * supports the `Symbol` class and then if the `Symbol.toStringTag` constant + * is defined as a `Symbol` instance. If both conditions are met, the + * Symbol.toStringTag property is defined as a getter that returns the + * supplied class constructor's name. + * + * @method applyToStringTag + * + * @param {Class} classObject a class such as Object, String, Number but + * typically one of your own creation through the class keyword; `class A {}`, + * for example. + */ +function applyToStringTag(classObject) { + if (typeof Symbol === 'function' && Symbol.toStringTag) { + Object.defineProperty(classObject.prototype, Symbol.toStringTag, { + get: function get() { + return this.constructor.name; + } + }); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/defineToStringTag.js.flow b/node_modules/graphql/jsutils/defineToStringTag.js.flow new file mode 100644 index 0000000..f539cde --- /dev/null +++ b/node_modules/graphql/jsutils/defineToStringTag.js.flow @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * The `applyToStringTag()` function checks first to see if the runtime + * supports the `Symbol` class and then if the `Symbol.toStringTag` constant + * is defined as a `Symbol` instance. If both conditions are met, the + * Symbol.toStringTag property is defined as a getter that returns the + * supplied class constructor's name. + * + * @method applyToStringTag + * + * @param {Class} classObject a class such as Object, String, Number but + * typically one of your own creation through the class keyword; `class A {}`, + * for example. + */ +export default function applyToStringTag(classObject: Class): void { + if (typeof Symbol === 'function' && Symbol.toStringTag) { + Object.defineProperty(classObject.prototype, Symbol.toStringTag, { + get() { + return this.constructor.name; + }, + }); + } +} diff --git a/node_modules/graphql/jsutils/defineToStringTag.mjs b/node_modules/graphql/jsutils/defineToStringTag.mjs new file mode 100644 index 0000000..ed0d728 --- /dev/null +++ b/node_modules/graphql/jsutils/defineToStringTag.mjs @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The `applyToStringTag()` function checks first to see if the runtime + * supports the `Symbol` class and then if the `Symbol.toStringTag` constant + * is defined as a `Symbol` instance. If both conditions are met, the + * Symbol.toStringTag property is defined as a getter that returns the + * supplied class constructor's name. + * + * @method applyToStringTag + * + * @param {Class} classObject a class such as Object, String, Number but + * typically one of your own creation through the class keyword; `class A {}`, + * for example. + */ +export default function applyToStringTag(classObject) { + if (typeof Symbol === 'function' && Symbol.toStringTag) { + Object.defineProperty(classObject.prototype, Symbol.toStringTag, { + get: function get() { + return this.constructor.name; + } + }); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/find.js b/node_modules/graphql/jsutils/find.js new file mode 100644 index 0000000..78b0877 --- /dev/null +++ b/node_modules/graphql/jsutils/find.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = find; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function find(list, predicate) { + for (var i = 0; i < list.length; i++) { + if (predicate(list[i])) { + return list[i]; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/find.js.flow b/node_modules/graphql/jsutils/find.js.flow new file mode 100644 index 0000000..ba608d9 --- /dev/null +++ b/node_modules/graphql/jsutils/find.js.flow @@ -0,0 +1,19 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export default function find( + list: $ReadOnlyArray, + predicate: (item: T) => boolean, +): ?T { + for (let i = 0; i < list.length; i++) { + if (predicate(list[i])) { + return list[i]; + } + } +} diff --git a/node_modules/graphql/jsutils/find.mjs b/node_modules/graphql/jsutils/find.mjs new file mode 100644 index 0000000..965b53f --- /dev/null +++ b/node_modules/graphql/jsutils/find.mjs @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export default function find(list, predicate) { + for (var i = 0; i < list.length; i++) { + if (predicate(list[i])) { + return list[i]; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/inspect.js b/node_modules/graphql/jsutils/inspect.js new file mode 100644 index 0000000..ef08c44 --- /dev/null +++ b/node_modules/graphql/jsutils/inspect.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = inspect; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Used to print values in error messages. + */ +function inspect(value) { + switch (_typeof(value)) { + case 'string': + return JSON.stringify(value); + + case 'function': + return value.name ? "[function ".concat(value.name, "]") : '[function]'; + + case 'object': + if (value) { + if (typeof value.inspect === 'function') { + return value.inspect(); + } else if (Array.isArray(value)) { + return '[' + value.map(inspect).join(', ') + ']'; + } + + var properties = Object.keys(value).map(function (k) { + return "".concat(k, ": ").concat(inspect(value[k])); + }).join(', '); + return properties ? '{ ' + properties + ' }' : '{}'; + } + + return String(value); + + default: + return String(value); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/inspect.js.flow b/node_modules/graphql/jsutils/inspect.js.flow new file mode 100644 index 0000000..f2c32d8 --- /dev/null +++ b/node_modules/graphql/jsutils/inspect.js.flow @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Used to print values in error messages. + */ +export default function inspect(value: mixed): string { + switch (typeof value) { + case 'string': + return JSON.stringify(value); + case 'function': + return value.name ? `[function ${value.name}]` : '[function]'; + case 'object': + if (value) { + if (typeof value.inspect === 'function') { + return value.inspect(); + } else if (Array.isArray(value)) { + return '[' + value.map(inspect).join(', ') + ']'; + } + + const properties = Object.keys(value) + .map(k => `${k}: ${inspect(value[k])}`) + .join(', '); + return properties ? '{ ' + properties + ' }' : '{}'; + } + return String(value); + default: + return String(value); + } +} diff --git a/node_modules/graphql/jsutils/inspect.mjs b/node_modules/graphql/jsutils/inspect.mjs new file mode 100644 index 0000000..e6dcecc --- /dev/null +++ b/node_modules/graphql/jsutils/inspect.mjs @@ -0,0 +1,42 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Used to print values in error messages. + */ +export default function inspect(value) { + switch (_typeof(value)) { + case 'string': + return JSON.stringify(value); + + case 'function': + return value.name ? "[function ".concat(value.name, "]") : '[function]'; + + case 'object': + if (value) { + if (typeof value.inspect === 'function') { + return value.inspect(); + } else if (Array.isArray(value)) { + return '[' + value.map(inspect).join(', ') + ']'; + } + + var properties = Object.keys(value).map(function (k) { + return "".concat(k, ": ").concat(inspect(value[k])); + }).join(', '); + return properties ? '{ ' + properties + ' }' : '{}'; + } + + return String(value); + + default: + return String(value); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/instanceOf.js b/node_modules/graphql/jsutils/instanceOf.js new file mode 100644 index 0000000..497147a --- /dev/null +++ b/node_modules/graphql/jsutils/instanceOf.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * 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/ +var _default = process.env.NODE_ENV === 'production' ? // eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + return value instanceof constructor; +} : // eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; + } + + if (value) { + var valueClass = value.constructor; + var className = constructor.name; + + if (className && valueClass && valueClass.name === className) { + throw new Error("Cannot use ".concat(className, " \"").concat(value, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.")); + } + } + + return false; +}; + +exports.default = _default; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/instanceOf.js.flow b/node_modules/graphql/jsutils/instanceOf.js.flow new file mode 100644 index 0000000..1cb4d2a --- /dev/null +++ b/node_modules/graphql/jsutils/instanceOf.js.flow @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + */ +declare function instanceOf( + value: mixed, + constructor: mixed, +): boolean %checks(value instanceof constructor); + +// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production +// See: https://webpack.js.org/guides/production/ +export default (process.env.NODE_ENV === 'production' + ? // eslint-disable-next-line no-shadow + function instanceOf(value: mixed, constructor: mixed) { + return value instanceof constructor; + } + : // eslint-disable-next-line no-shadow + function instanceOf(value: any, constructor: any) { + if (value instanceof constructor) { + return true; + } + if (value) { + const valueClass = value.constructor; + const className = constructor.name; + if (className && valueClass && valueClass.name === className) { + throw new Error( + `Cannot use ${className} "${value}" from another module or realm. + +Ensure that there is only one instance of "graphql" in the node_modules +directory. If different versions of "graphql" are the dependencies of other +relied on modules, use "resolutions" to ensure only one version is installed. + +https://yarnpkg.com/en/docs/selective-version-resolutions + +Duplicate "graphql" modules cannot be used at the same time since different +versions may have different capabilities and behavior. The data from one +version used in the function from another could produce confusing and +spurious results.`, + ); + } + } + return false; + }); diff --git a/node_modules/graphql/jsutils/instanceOf.mjs b/node_modules/graphql/jsutils/instanceOf.mjs new file mode 100644 index 0000000..f8ad237 --- /dev/null +++ b/node_modules/graphql/jsutils/instanceOf.mjs @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + */ +// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production +// See: https://webpack.js.org/guides/production/ +export default process.env.NODE_ENV === 'production' ? // eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + return value instanceof constructor; +} : // eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; + } + + if (value) { + var valueClass = value.constructor; + var className = constructor.name; + + if (className && valueClass && valueClass.name === className) { + throw new Error("Cannot use ".concat(className, " \"").concat(value, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.")); + } + } + + return false; +}; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/invariant.js b/node_modules/graphql/jsutils/invariant.js new file mode 100644 index 0000000..f62b28e --- /dev/null +++ b/node_modules/graphql/jsutils/invariant.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = invariant; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function invariant(condition, message) { + /* istanbul ignore else */ + if (!condition) { + throw new Error(message); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/invariant.js.flow b/node_modules/graphql/jsutils/invariant.js.flow new file mode 100644 index 0000000..f4a51ef --- /dev/null +++ b/node_modules/graphql/jsutils/invariant.js.flow @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export default function invariant(condition: mixed, message: string) { + /* istanbul ignore else */ + if (!condition) { + throw new Error(message); + } +} diff --git a/node_modules/graphql/jsutils/invariant.mjs b/node_modules/graphql/jsutils/invariant.mjs new file mode 100644 index 0000000..a5b5ace --- /dev/null +++ b/node_modules/graphql/jsutils/invariant.mjs @@ -0,0 +1,14 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export default function invariant(condition, message) { + /* istanbul ignore else */ + if (!condition) { + throw new Error(message); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isFinite.js b/node_modules/graphql/jsutils/isFinite.js new file mode 100644 index 0000000..5e5aa0c --- /dev/null +++ b/node_modules/graphql/jsutils/isFinite.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +var isFinite = Number.isFinite || function (value) { + return typeof value === 'number' && isFinite(value); +}; + +var _default = isFinite; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isFinite.js.flow b/node_modules/graphql/jsutils/isFinite.js.flow new file mode 100644 index 0000000..a874a2d --- /dev/null +++ b/node_modules/graphql/jsutils/isFinite.js.flow @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +declare function isFinite(value: mixed): boolean %checks(typeof value === + 'number'); + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +const isFinite = + Number.isFinite || + function(value) { + return typeof value === 'number' && isFinite(value); + }; +export default isFinite; diff --git a/node_modules/graphql/jsutils/isFinite.mjs b/node_modules/graphql/jsutils/isFinite.mjs new file mode 100644 index 0000000..f6e317b --- /dev/null +++ b/node_modules/graphql/jsutils/isFinite.mjs @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +var isFinite = Number.isFinite || function (value) { + return typeof value === 'number' && isFinite(value); +}; + +export default isFinite; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isInteger.js b/node_modules/graphql/jsutils/isInteger.js new file mode 100644 index 0000000..6628bd1 --- /dev/null +++ b/node_modules/graphql/jsutils/isInteger.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +var isInteger = Number.isInteger || function (value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; +}; + +var _default = isInteger; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isInteger.js.flow b/node_modules/graphql/jsutils/isInteger.js.flow new file mode 100644 index 0000000..3e897d6 --- /dev/null +++ b/node_modules/graphql/jsutils/isInteger.js.flow @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +declare function isInteger(value: mixed): boolean %checks(typeof value === + 'number'); + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +const isInteger = + Number.isInteger || + function(value) { + return ( + typeof value === 'number' && + isFinite(value) && + Math.floor(value) === value + ); + }; +export default isInteger; diff --git a/node_modules/graphql/jsutils/isInteger.mjs b/node_modules/graphql/jsutils/isInteger.mjs new file mode 100644 index 0000000..b4a324b --- /dev/null +++ b/node_modules/graphql/jsutils/isInteger.mjs @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +var isInteger = Number.isInteger || function (value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; +}; + +export default isInteger; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isInvalid.js b/node_modules/graphql/jsutils/isInvalid.js new file mode 100644 index 0000000..0025c6a --- /dev/null +++ b/node_modules/graphql/jsutils/isInvalid.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isInvalid; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if a value is undefined, or NaN. + */ +function isInvalid(value) { + return value === undefined || value !== value; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isInvalid.js.flow b/node_modules/graphql/jsutils/isInvalid.js.flow new file mode 100644 index 0000000..9ddbfed --- /dev/null +++ b/node_modules/graphql/jsutils/isInvalid.js.flow @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Returns true if a value is undefined, or NaN. + */ +export default function isInvalid(value: mixed): boolean %checks { + return value === undefined || value !== value; +} diff --git a/node_modules/graphql/jsutils/isInvalid.mjs b/node_modules/graphql/jsutils/isInvalid.mjs new file mode 100644 index 0000000..af36e07 --- /dev/null +++ b/node_modules/graphql/jsutils/isInvalid.mjs @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if a value is undefined, or NaN. + */ +export default function isInvalid(value) { + return value === undefined || value !== value; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isNullish.js b/node_modules/graphql/jsutils/isNullish.js new file mode 100644 index 0000000..d7cf030 --- /dev/null +++ b/node_modules/graphql/jsutils/isNullish.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isNullish; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if a value is null, undefined, or NaN. + */ +function isNullish(value) { + return value === null || value === undefined || value !== value; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isNullish.js.flow b/node_modules/graphql/jsutils/isNullish.js.flow new file mode 100644 index 0000000..aedd6c8 --- /dev/null +++ b/node_modules/graphql/jsutils/isNullish.js.flow @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Returns true if a value is null, undefined, or NaN. + */ +export default function isNullish(value: mixed): boolean %checks { + return value === null || value === undefined || value !== value; +} diff --git a/node_modules/graphql/jsutils/isNullish.mjs b/node_modules/graphql/jsutils/isNullish.mjs new file mode 100644 index 0000000..7a2e92d --- /dev/null +++ b/node_modules/graphql/jsutils/isNullish.mjs @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if a value is null, undefined, or NaN. + */ +export default function isNullish(value) { + return value === null || value === undefined || value !== value; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isPromise.js b/node_modules/graphql/jsutils/isPromise.js new file mode 100644 index 0000000..0feb12b --- /dev/null +++ b/node_modules/graphql/jsutils/isPromise.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isPromise; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ +// eslint-disable-next-line no-redeclare +function isPromise(value) { + return Boolean(value && typeof value.then === 'function'); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isPromise.js.flow b/node_modules/graphql/jsutils/isPromise.js.flow new file mode 100644 index 0000000..d53c9ee --- /dev/null +++ b/node_modules/graphql/jsutils/isPromise.js.flow @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ +declare function isPromise(value: mixed): boolean %checks(value instanceof + Promise); + +// eslint-disable-next-line no-redeclare +export default function isPromise(value) { + return Boolean(value && typeof value.then === 'function'); +} diff --git a/node_modules/graphql/jsutils/isPromise.mjs b/node_modules/graphql/jsutils/isPromise.mjs new file mode 100644 index 0000000..9705fcb --- /dev/null +++ b/node_modules/graphql/jsutils/isPromise.mjs @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ +// eslint-disable-next-line no-redeclare +export default function isPromise(value) { + return Boolean(value && typeof value.then === 'function'); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/keyMap.js b/node_modules/graphql/jsutils/keyMap.js new file mode 100644 index 0000000..6d4250f --- /dev/null +++ b/node_modules/graphql/jsutils/keyMap.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = keyMap; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } } + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { name: 'Jenny', num: '857-6309' } + * const jennyEntry = entriesByName['Jenny'] + * + */ +function keyMap(list, keyFn) { + return list.reduce(function (map, item) { + return map[keyFn(item)] = item, map; + }, Object.create(null)); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/keyMap.js.flow b/node_modules/graphql/jsutils/keyMap.js.flow new file mode 100644 index 0000000..58fce2f --- /dev/null +++ b/node_modules/graphql/jsutils/keyMap.js.flow @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from './ObjMap'; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } } + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { name: 'Jenny', num: '857-6309' } + * const jennyEntry = entriesByName['Jenny'] + * + */ +export default function keyMap( + list: $ReadOnlyArray, + keyFn: (item: T) => string, +): ObjMap { + return list.reduce( + (map, item) => ((map[keyFn(item)] = item), map), + Object.create(null), + ); +} diff --git a/node_modules/graphql/jsutils/keyMap.mjs b/node_modules/graphql/jsutils/keyMap.mjs new file mode 100644 index 0000000..9df8eb0 --- /dev/null +++ b/node_modules/graphql/jsutils/keyMap.mjs @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } } + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { name: 'Jenny', num: '857-6309' } + * const jennyEntry = entriesByName['Jenny'] + * + */ +export default function keyMap(list, keyFn) { + return list.reduce(function (map, item) { + return map[keyFn(item)] = item, map; + }, Object.create(null)); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/keyValMap.js b/node_modules/graphql/jsutils/keyValMap.js new file mode 100644 index 0000000..d12801d --- /dev/null +++ b/node_modules/graphql/jsutils/keyValMap.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = keyValMap; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * + */ +function keyValMap(list, keyFn, valFn) { + return list.reduce(function (map, item) { + return map[keyFn(item)] = valFn(item), map; + }, Object.create(null)); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/keyValMap.js.flow b/node_modules/graphql/jsutils/keyValMap.js.flow new file mode 100644 index 0000000..7917f3c --- /dev/null +++ b/node_modules/graphql/jsutils/keyValMap.js.flow @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from './ObjMap'; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * + */ +export default function keyValMap( + list: $ReadOnlyArray, + keyFn: (item: T) => string, + valFn: (item: T) => V, +): ObjMap { + return list.reduce( + (map, item) => ((map[keyFn(item)] = valFn(item)), map), + Object.create(null), + ); +} diff --git a/node_modules/graphql/jsutils/keyValMap.mjs b/node_modules/graphql/jsutils/keyValMap.mjs new file mode 100644 index 0000000..eae73e8 --- /dev/null +++ b/node_modules/graphql/jsutils/keyValMap.mjs @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * + */ +export default function keyValMap(list, keyFn, valFn) { + return list.reduce(function (map, item) { + return map[keyFn(item)] = valFn(item), map; + }, Object.create(null)); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/memoize3.js b/node_modules/graphql/jsutils/memoize3.js new file mode 100644 index 0000000..e079629 --- /dev/null +++ b/node_modules/graphql/jsutils/memoize3.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = memoize3; + +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Memoizes the provided three-argument function. + */ +function memoize3(fn) { + var cache0; + + function memoized(a1, a2, a3) { + if (!cache0) { + cache0 = new WeakMap(); + } + + var cache1 = cache0.get(a1); + var cache2; + + if (cache1) { + cache2 = cache1.get(a2); + + if (cache2) { + var cachedValue = cache2.get(a3); + + if (cachedValue !== undefined) { + return cachedValue; + } + } + } else { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + + if (!cache2) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + + var newValue = fn.apply(this, arguments); + cache2.set(a3, newValue); + return newValue; + } + + return memoized; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/memoize3.js.flow b/node_modules/graphql/jsutils/memoize3.js.flow new file mode 100644 index 0000000..37e3951 --- /dev/null +++ b/node_modules/graphql/jsutils/memoize3.js.flow @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Memoizes the provided three-argument function. + */ +export default function memoize3 any>( + fn: T, +): T { + let cache0; + function memoized(a1, a2, a3) { + if (!cache0) { + cache0 = new WeakMap(); + } + let cache1 = cache0.get(a1); + let cache2; + if (cache1) { + cache2 = cache1.get(a2); + if (cache2) { + const cachedValue = cache2.get(a3); + if (cachedValue !== undefined) { + return cachedValue; + } + } + } else { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + if (!cache2) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + const newValue = fn.apply(this, arguments); + cache2.set(a3, newValue); + return newValue; + } + return (memoized: any); +} diff --git a/node_modules/graphql/jsutils/memoize3.mjs b/node_modules/graphql/jsutils/memoize3.mjs new file mode 100644 index 0000000..c82432b --- /dev/null +++ b/node_modules/graphql/jsutils/memoize3.mjs @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Memoizes the provided three-argument function. + */ +export default function memoize3(fn) { + var cache0; + + function memoized(a1, a2, a3) { + if (!cache0) { + cache0 = new WeakMap(); + } + + var cache1 = cache0.get(a1); + var cache2; + + if (cache1) { + cache2 = cache1.get(a2); + + if (cache2) { + var cachedValue = cache2.get(a3); + + if (cachedValue !== undefined) { + return cachedValue; + } + } + } else { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + + if (!cache2) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + + var newValue = fn.apply(this, arguments); + cache2.set(a3, newValue); + return newValue; + } + + return memoized; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/objectValues.js b/node_modules/graphql/jsutils/objectValues.js new file mode 100644 index 0000000..c43e389 --- /dev/null +++ b/node_modules/graphql/jsutils/objectValues.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221 +var objectValues = Object.values || function (obj) { + return Object.keys(obj).map(function (key) { + return obj[key]; + }); +}; + +var _default = objectValues; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/objectValues.js.flow b/node_modules/graphql/jsutils/objectValues.js.flow new file mode 100644 index 0000000..d6bab48 --- /dev/null +++ b/node_modules/graphql/jsutils/objectValues.js.flow @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from './ObjMap'; + +declare function objectValues(obj: ObjMap): Array; + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221 +const objectValues = + Object.values || (obj => Object.keys(obj).map(key => obj[key])); +export default objectValues; diff --git a/node_modules/graphql/jsutils/objectValues.mjs b/node_modules/graphql/jsutils/objectValues.mjs new file mode 100644 index 0000000..8a08ca3 --- /dev/null +++ b/node_modules/graphql/jsutils/objectValues.mjs @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221 +var objectValues = Object.values || function (obj) { + return Object.keys(obj).map(function (key) { + return obj[key]; + }); +}; + +export default objectValues; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/orList.js b/node_modules/graphql/jsutils/orList.js new file mode 100644 index 0000000..d52df38 --- /dev/null +++ b/node_modules/graphql/jsutils/orList.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = orList; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var MAX_LENGTH = 5; +/** + * Given [ A, B, C ] return 'A, B, or C'. + */ + +function orList(items) { + var selected = items.slice(0, MAX_LENGTH); + return selected.reduce(function (list, quoted, index) { + return list + (selected.length > 2 ? ', ' : ' ') + (index === selected.length - 1 ? 'or ' : '') + quoted; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/orList.js.flow b/node_modules/graphql/jsutils/orList.js.flow new file mode 100644 index 0000000..dc63e0d --- /dev/null +++ b/node_modules/graphql/jsutils/orList.js.flow @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +const MAX_LENGTH = 5; + +/** + * Given [ A, B, C ] return 'A, B, or C'. + */ +export default function orList(items: $ReadOnlyArray): string { + const selected = items.slice(0, MAX_LENGTH); + return selected.reduce( + (list, quoted, index) => + list + + (selected.length > 2 ? ', ' : ' ') + + (index === selected.length - 1 ? 'or ' : '') + + quoted, + ); +} diff --git a/node_modules/graphql/jsutils/orList.mjs b/node_modules/graphql/jsutils/orList.mjs new file mode 100644 index 0000000..3c68746 --- /dev/null +++ b/node_modules/graphql/jsutils/orList.mjs @@ -0,0 +1,19 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var MAX_LENGTH = 5; +/** + * Given [ A, B, C ] return 'A, B, or C'. + */ + +export default function orList(items) { + var selected = items.slice(0, MAX_LENGTH); + return selected.reduce(function (list, quoted, index) { + return list + (selected.length > 2 ? ', ' : ' ') + (index === selected.length - 1 ? 'or ' : '') + quoted; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/promiseForObject.js b/node_modules/graphql/jsutils/promiseForObject.js new file mode 100644 index 0000000..55328b2 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseForObject.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = promiseForObject; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ +function promiseForObject(object) { + var keys = Object.keys(object); + var valuesAndPromises = keys.map(function (name) { + return object[name]; + }); + return Promise.all(valuesAndPromises).then(function (values) { + return values.reduce(function (resolvedObject, value, i) { + resolvedObject[keys[i]] = value; + return resolvedObject; + }, Object.create(null)); + }); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/promiseForObject.js.flow b/node_modules/graphql/jsutils/promiseForObject.js.flow new file mode 100644 index 0000000..74d1787 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseForObject.js.flow @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from './ObjMap'; + +/** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ +export default function promiseForObject( + object: ObjMap>, +): Promise> { + const keys = Object.keys(object); + const valuesAndPromises = keys.map(name => object[name]); + return Promise.all(valuesAndPromises).then(values => + values.reduce((resolvedObject, value, i) => { + resolvedObject[keys[i]] = value; + return resolvedObject; + }, Object.create(null)), + ); +} diff --git a/node_modules/graphql/jsutils/promiseForObject.mjs b/node_modules/graphql/jsutils/promiseForObject.mjs new file mode 100644 index 0000000..356ede3 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseForObject.mjs @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ +export default function promiseForObject(object) { + var keys = Object.keys(object); + var valuesAndPromises = keys.map(function (name) { + return object[name]; + }); + return Promise.all(valuesAndPromises).then(function (values) { + return values.reduce(function (resolvedObject, value, i) { + resolvedObject[keys[i]] = value; + return resolvedObject; + }, Object.create(null)); + }); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/promiseReduce.js b/node_modules/graphql/jsutils/promiseReduce.js new file mode 100644 index 0000000..9ed206a --- /dev/null +++ b/node_modules/graphql/jsutils/promiseReduce.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = promiseReduce; + +var _isPromise = _interopRequireDefault(require("./isPromise")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ +function promiseReduce(values, callback, initialValue) { + return values.reduce(function (previous, value) { + return (0, _isPromise.default)(previous) ? previous.then(function (resolved) { + return callback(resolved, value); + }) : callback(previous, value); + }, initialValue); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/promiseReduce.js.flow b/node_modules/graphql/jsutils/promiseReduce.js.flow new file mode 100644 index 0000000..a09837b --- /dev/null +++ b/node_modules/graphql/jsutils/promiseReduce.js.flow @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import isPromise from './isPromise'; +import type { MaybePromise } from './MaybePromise'; + +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ +export default function promiseReduce( + values: $ReadOnlyArray, + callback: (U, T) => MaybePromise, + initialValue: MaybePromise, +): MaybePromise { + return values.reduce( + (previous, value) => + isPromise(previous) + ? previous.then(resolved => callback(resolved, value)) + : callback(previous, value), + initialValue, + ); +} diff --git a/node_modules/graphql/jsutils/promiseReduce.mjs b/node_modules/graphql/jsutils/promiseReduce.mjs new file mode 100644 index 0000000..8fb7919 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseReduce.mjs @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import isPromise from './isPromise'; + +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ +export default function promiseReduce(values, callback, initialValue) { + return values.reduce(function (previous, value) { + return isPromise(previous) ? previous.then(function (resolved) { + return callback(resolved, value); + }) : callback(previous, value); + }, initialValue); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/quotedOrList.js b/node_modules/graphql/jsutils/quotedOrList.js new file mode 100644 index 0000000..826fc02 --- /dev/null +++ b/node_modules/graphql/jsutils/quotedOrList.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = quotedOrList; + +var _orList = _interopRequireDefault(require("./orList")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given [ A, B, C ] return '"A", "B", or "C"'. + */ +function quotedOrList(items) { + return (0, _orList.default)(items.map(function (item) { + return "\"".concat(item, "\""); + })); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/quotedOrList.js.flow b/node_modules/graphql/jsutils/quotedOrList.js.flow new file mode 100644 index 0000000..f567038 --- /dev/null +++ b/node_modules/graphql/jsutils/quotedOrList.js.flow @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import orList from './orList'; + +/** + * Given [ A, B, C ] return '"A", "B", or "C"'. + */ +export default function quotedOrList(items: $ReadOnlyArray): string { + return orList(items.map(item => `"${item}"`)); +} diff --git a/node_modules/graphql/jsutils/quotedOrList.mjs b/node_modules/graphql/jsutils/quotedOrList.mjs new file mode 100644 index 0000000..6cff780 --- /dev/null +++ b/node_modules/graphql/jsutils/quotedOrList.mjs @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import orList from './orList'; +/** + * Given [ A, B, C ] return '"A", "B", or "C"'. + */ + +export default function quotedOrList(items) { + return orList(items.map(function (item) { + return "\"".concat(item, "\""); + })); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/suggestionList.js b/node_modules/graphql/jsutils/suggestionList.js new file mode 100644 index 0000000..42072b3 --- /dev/null +++ b/node_modules/graphql/jsutils/suggestionList.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = suggestionList; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ +function suggestionList(input, options) { + var optionsByDistance = Object.create(null); + var oLength = options.length; + var inputThreshold = input.length / 2; + + for (var i = 0; i < oLength; i++) { + var distance = lexicalDistance(input, options[i]); + var threshold = Math.max(inputThreshold, options[i].length / 2, 1); + + if (distance <= threshold) { + optionsByDistance[options[i]] = distance; + } + } + + return Object.keys(optionsByDistance).sort(function (a, b) { + return optionsByDistance[a] - optionsByDistance[b]; + }); +} +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + * + * @param {string} a + * @param {string} b + * @return {int} distance in number of edits + */ + + +function lexicalDistance(aStr, bStr) { + if (aStr === bStr) { + return 0; + } + + var i; + var j; + var d = []; + var a = aStr.toLowerCase(); + var b = bStr.toLowerCase(); + var aLength = a.length; + var bLength = b.length; // Any case change counts as a single edit + + if (a === b) { + return 1; + } + + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + var cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); + + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); + } + } + } + + return d[aLength][bLength]; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/suggestionList.js.flow b/node_modules/graphql/jsutils/suggestionList.js.flow new file mode 100644 index 0000000..e800d03 --- /dev/null +++ b/node_modules/graphql/jsutils/suggestionList.js.flow @@ -0,0 +1,94 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ +export default function suggestionList( + input: string, + options: $ReadOnlyArray, +): Array { + const optionsByDistance = Object.create(null); + const oLength = options.length; + const inputThreshold = input.length / 2; + for (let i = 0; i < oLength; i++) { + const distance = lexicalDistance(input, options[i]); + const threshold = Math.max(inputThreshold, options[i].length / 2, 1); + if (distance <= threshold) { + optionsByDistance[options[i]] = distance; + } + } + return Object.keys(optionsByDistance).sort( + (a, b) => optionsByDistance[a] - optionsByDistance[b], + ); +} + +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + * + * @param {string} a + * @param {string} b + * @return {int} distance in number of edits + */ +function lexicalDistance(aStr, bStr) { + if (aStr === bStr) { + return 0; + } + + let i; + let j; + const d = []; + const a = aStr.toLowerCase(); + const b = bStr.toLowerCase(); + const aLength = a.length; + const bLength = b.length; + + // Any case change counts as a single edit + if (a === b) { + return 1; + } + + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + + d[i][j] = Math.min( + d[i - 1][j] + 1, + d[i][j - 1] + 1, + d[i - 1][j - 1] + cost, + ); + + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); + } + } + } + + return d[aLength][bLength]; +} diff --git a/node_modules/graphql/jsutils/suggestionList.mjs b/node_modules/graphql/jsutils/suggestionList.mjs new file mode 100644 index 0000000..229d557 --- /dev/null +++ b/node_modules/graphql/jsutils/suggestionList.mjs @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ +export default function suggestionList(input, options) { + var optionsByDistance = Object.create(null); + var oLength = options.length; + var inputThreshold = input.length / 2; + + for (var i = 0; i < oLength; i++) { + var distance = lexicalDistance(input, options[i]); + var threshold = Math.max(inputThreshold, options[i].length / 2, 1); + + if (distance <= threshold) { + optionsByDistance[options[i]] = distance; + } + } + + return Object.keys(optionsByDistance).sort(function (a, b) { + return optionsByDistance[a] - optionsByDistance[b]; + }); +} +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + * + * @param {string} a + * @param {string} b + * @return {int} distance in number of edits + */ + +function lexicalDistance(aStr, bStr) { + if (aStr === bStr) { + return 0; + } + + var i; + var j; + var d = []; + var a = aStr.toLowerCase(); + var b = bStr.toLowerCase(); + var aLength = a.length; + var bLength = b.length; // Any case change counts as a single edit + + if (a === b) { + return 1; + } + + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + var cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); + + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); + } + } + } + + return d[aLength][bLength]; +} \ No newline at end of file diff --git a/node_modules/graphql/language/ast.js b/node_modules/graphql/language/ast.js new file mode 100644 index 0000000..9a390c3 --- /dev/null +++ b/node_modules/graphql/language/ast.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/node_modules/graphql/language/ast.js.flow b/node_modules/graphql/language/ast.js.flow new file mode 100644 index 0000000..22169c3 --- /dev/null +++ b/node_modules/graphql/language/ast.js.flow @@ -0,0 +1,581 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { Source } from './source'; +import type { TokenKindEnum } from './lexer'; + +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +export type Location = { + /** + * The character offset at which this Node begins. + */ + +start: number, + + /** + * The character offset at which this Node ends. + */ + +end: number, + + /** + * The Token at which this Node begins. + */ + +startToken: Token, + + /** + * The Token at which this Node ends. + */ + +endToken: Token, + + /** + * The Source document the AST represents. + */ + +source: Source, +}; + +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ +export type Token = { + /** + * The kind of Token. + */ + +kind: TokenKindEnum, + + /** + * The character offset at which this Node begins. + */ + +start: number, + + /** + * The character offset at which this Node ends. + */ + +end: number, + + /** + * The 1-indexed line number on which this Token appears. + */ + +line: number, + + /** + * The 1-indexed column number at which this Token begins. + */ + +column: number, + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + */ + +value: string | void, + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. is always the first node and + * the last. + */ + +prev: Token | null, + +next: Token | null, +}; + +/** + * The list of all possible AST node types. + */ +export type ASTNode = + | NameNode + | DocumentNode + | OperationDefinitionNode + | VariableDefinitionNode + | VariableNode + | SelectionSetNode + | FieldNode + | ArgumentNode + | FragmentSpreadNode + | InlineFragmentNode + | FragmentDefinitionNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode + | ObjectFieldNode + | DirectiveNode + | NamedTypeNode + | ListTypeNode + | NonNullTypeNode + | SchemaDefinitionNode + | OperationTypeDefinitionNode + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | FieldDefinitionNode + | InputValueDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | EnumValueDefinitionNode + | InputObjectTypeDefinitionNode + | DirectiveDefinitionNode + | SchemaExtensionNode + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode; + +/** + * Utility type listing all nodes indexed by their kind. + */ +export type ASTKindToNode = {| + Name: NameNode, + Document: DocumentNode, + OperationDefinition: OperationDefinitionNode, + VariableDefinition: VariableDefinitionNode, + Variable: VariableNode, + SelectionSet: SelectionSetNode, + Field: FieldNode, + Argument: ArgumentNode, + FragmentSpread: FragmentSpreadNode, + InlineFragment: InlineFragmentNode, + FragmentDefinition: FragmentDefinitionNode, + IntValue: IntValueNode, + FloatValue: FloatValueNode, + StringValue: StringValueNode, + BooleanValue: BooleanValueNode, + NullValue: NullValueNode, + EnumValue: EnumValueNode, + ListValue: ListValueNode, + ObjectValue: ObjectValueNode, + ObjectField: ObjectFieldNode, + Directive: DirectiveNode, + NamedType: NamedTypeNode, + ListType: ListTypeNode, + NonNullType: NonNullTypeNode, + SchemaDefinition: SchemaDefinitionNode, + OperationTypeDefinition: OperationTypeDefinitionNode, + ScalarTypeDefinition: ScalarTypeDefinitionNode, + ObjectTypeDefinition: ObjectTypeDefinitionNode, + FieldDefinition: FieldDefinitionNode, + InputValueDefinition: InputValueDefinitionNode, + InterfaceTypeDefinition: InterfaceTypeDefinitionNode, + UnionTypeDefinition: UnionTypeDefinitionNode, + EnumTypeDefinition: EnumTypeDefinitionNode, + EnumValueDefinition: EnumValueDefinitionNode, + InputObjectTypeDefinition: InputObjectTypeDefinitionNode, + DirectiveDefinition: DirectiveDefinitionNode, + SchemaExtension: SchemaExtensionNode, + ScalarTypeExtension: ScalarTypeExtensionNode, + ObjectTypeExtension: ObjectTypeExtensionNode, + InterfaceTypeExtension: InterfaceTypeExtensionNode, + UnionTypeExtension: UnionTypeExtensionNode, + EnumTypeExtension: EnumTypeExtensionNode, + InputObjectTypeExtension: InputObjectTypeExtensionNode, +|}; + +// Name + +export type NameNode = { + +kind: 'Name', + +loc?: Location, + +value: string, +}; + +// Document + +export type DocumentNode = { + +kind: 'Document', + +loc?: Location, + +definitions: $ReadOnlyArray, +}; + +export type DefinitionNode = + | ExecutableDefinitionNode + | TypeSystemDefinitionNode + | TypeSystemExtensionNode; + +export type ExecutableDefinitionNode = + | OperationDefinitionNode + | FragmentDefinitionNode; + +export type OperationDefinitionNode = { + +kind: 'OperationDefinition', + +loc?: Location, + +operation: OperationTypeNode, + +name?: NameNode, + +variableDefinitions?: $ReadOnlyArray, + +directives?: $ReadOnlyArray, + +selectionSet: SelectionSetNode, +}; + +export type OperationTypeNode = 'query' | 'mutation' | 'subscription'; + +export type VariableDefinitionNode = { + +kind: 'VariableDefinition', + +loc?: Location, + +variable: VariableNode, + +type: TypeNode, + +defaultValue?: ValueNode, + +directives?: $ReadOnlyArray, +}; + +export type VariableNode = { + +kind: 'Variable', + +loc?: Location, + +name: NameNode, +}; + +export type SelectionSetNode = { + kind: 'SelectionSet', + loc?: Location, + selections: $ReadOnlyArray, +}; + +export type SelectionNode = FieldNode | FragmentSpreadNode | InlineFragmentNode; + +export type FieldNode = { + +kind: 'Field', + +loc?: Location, + +alias?: NameNode, + +name: NameNode, + +arguments?: $ReadOnlyArray, + +directives?: $ReadOnlyArray, + +selectionSet?: SelectionSetNode, +}; + +export type ArgumentNode = { + +kind: 'Argument', + +loc?: Location, + +name: NameNode, + +value: ValueNode, +}; + +// Fragments + +export type FragmentSpreadNode = { + +kind: 'FragmentSpread', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, +}; + +export type InlineFragmentNode = { + +kind: 'InlineFragment', + +loc?: Location, + +typeCondition?: NamedTypeNode, + +directives?: $ReadOnlyArray, + +selectionSet: SelectionSetNode, +}; + +export type FragmentDefinitionNode = { + +kind: 'FragmentDefinition', + +loc?: Location, + +name: NameNode, + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + +variableDefinitions?: $ReadOnlyArray, + +typeCondition: NamedTypeNode, + +directives?: $ReadOnlyArray, + +selectionSet: SelectionSetNode, +}; + +// Values + +export type ValueNode = + | VariableNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode; + +export type IntValueNode = { + +kind: 'IntValue', + +loc?: Location, + +value: string, +}; + +export type FloatValueNode = { + +kind: 'FloatValue', + +loc?: Location, + +value: string, +}; + +export type StringValueNode = { + +kind: 'StringValue', + +loc?: Location, + +value: string, + +block?: boolean, +}; + +export type BooleanValueNode = { + +kind: 'BooleanValue', + +loc?: Location, + +value: boolean, +}; + +export type NullValueNode = { + +kind: 'NullValue', + +loc?: Location, +}; + +export type EnumValueNode = { + +kind: 'EnumValue', + +loc?: Location, + +value: string, +}; + +export type ListValueNode = { + +kind: 'ListValue', + +loc?: Location, + +values: $ReadOnlyArray, +}; + +export type ObjectValueNode = { + +kind: 'ObjectValue', + +loc?: Location, + +fields: $ReadOnlyArray, +}; + +export type ObjectFieldNode = { + +kind: 'ObjectField', + +loc?: Location, + +name: NameNode, + +value: ValueNode, +}; + +// Directives + +export type DirectiveNode = { + +kind: 'Directive', + +loc?: Location, + +name: NameNode, + +arguments?: $ReadOnlyArray, +}; + +// Type Reference + +export type TypeNode = NamedTypeNode | ListTypeNode | NonNullTypeNode; + +export type NamedTypeNode = { + +kind: 'NamedType', + +loc?: Location, + +name: NameNode, +}; + +export type ListTypeNode = { + +kind: 'ListType', + +loc?: Location, + +type: TypeNode, +}; + +export type NonNullTypeNode = { + +kind: 'NonNullType', + +loc?: Location, + +type: NamedTypeNode | ListTypeNode, +}; + +// Type System Definition + +export type TypeSystemDefinitionNode = + | SchemaDefinitionNode + | TypeDefinitionNode + | DirectiveDefinitionNode; + +export type SchemaDefinitionNode = { + +kind: 'SchemaDefinition', + +loc?: Location, + +directives?: $ReadOnlyArray, + +operationTypes: $ReadOnlyArray, +}; + +export type OperationTypeDefinitionNode = { + +kind: 'OperationTypeDefinition', + +loc?: Location, + +operation: OperationTypeNode, + +type: NamedTypeNode, +}; + +// Type Definition + +export type TypeDefinitionNode = + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | InputObjectTypeDefinitionNode; + +export type ScalarTypeDefinitionNode = { + +kind: 'ScalarTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, +}; + +export type ObjectTypeDefinitionNode = { + +kind: 'ObjectTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +interfaces?: $ReadOnlyArray, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; + +export type FieldDefinitionNode = { + +kind: 'FieldDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +arguments?: $ReadOnlyArray, + +type: TypeNode, + +directives?: $ReadOnlyArray, +}; + +export type InputValueDefinitionNode = { + +kind: 'InputValueDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +type: TypeNode, + +defaultValue?: ValueNode, + +directives?: $ReadOnlyArray, +}; + +export type InterfaceTypeDefinitionNode = { + +kind: 'InterfaceTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; + +export type UnionTypeDefinitionNode = { + +kind: 'UnionTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, + +types?: $ReadOnlyArray, +}; + +export type EnumTypeDefinitionNode = { + +kind: 'EnumTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, + +values?: $ReadOnlyArray, +}; + +export type EnumValueDefinitionNode = { + +kind: 'EnumValueDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, +}; + +export type InputObjectTypeDefinitionNode = { + +kind: 'InputObjectTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; + +// Directive Definitions + +export type DirectiveDefinitionNode = { + +kind: 'DirectiveDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +arguments?: $ReadOnlyArray, + +locations: $ReadOnlyArray, +}; + +// Type System Extensions + +export type TypeSystemExtensionNode = SchemaExtensionNode | TypeExtensionNode; + +export type SchemaExtensionNode = { + +kind: 'SchemaExtension', + +loc?: Location, + +directives?: $ReadOnlyArray, + +operationTypes?: $ReadOnlyArray, +}; + +// Type Extensions + +export type TypeExtensionNode = + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode; + +export type ScalarTypeExtensionNode = { + +kind: 'ScalarTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, +}; + +export type ObjectTypeExtensionNode = { + +kind: 'ObjectTypeExtension', + +loc?: Location, + +name: NameNode, + +interfaces?: $ReadOnlyArray, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; + +export type InterfaceTypeExtensionNode = { + +kind: 'InterfaceTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; + +export type UnionTypeExtensionNode = { + +kind: 'UnionTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, + +types?: $ReadOnlyArray, +}; + +export type EnumTypeExtensionNode = { + +kind: 'EnumTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, + +values?: $ReadOnlyArray, +}; + +export type InputObjectTypeExtensionNode = { + +kind: 'InputObjectTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; diff --git a/node_modules/graphql/language/ast.mjs b/node_modules/graphql/language/ast.mjs new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/graphql/language/blockStringValue.js b/node_modules/graphql/language/blockStringValue.js new file mode 100644 index 0000000..d68146b --- /dev/null +++ b/node_modules/graphql/language/blockStringValue.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = blockStringValue; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + */ +function blockStringValue(rawString) { + // Expand a block string's raw value into independent lines. + var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first. + + var commonIndent = null; + + for (var i = 1; i < lines.length; i++) { + var line = lines[i]; + var indent = leadingWhitespace(line); + + if (indent < line.length && (commonIndent === null || indent < commonIndent)) { + commonIndent = indent; + + if (commonIndent === 0) { + break; + } + } + } + + if (commonIndent) { + for (var _i = 1; _i < lines.length; _i++) { + lines[_i] = lines[_i].slice(commonIndent); + } + } // Remove leading and trailing blank lines. + + + while (lines.length > 0 && isBlank(lines[0])) { + lines.shift(); + } + + while (lines.length > 0 && isBlank(lines[lines.length - 1])) { + lines.pop(); + } // Return a string of the lines joined with U+000A. + + + return lines.join('\n'); +} + +function leadingWhitespace(str) { + var i = 0; + + while (i < str.length && (str[i] === ' ' || str[i] === '\t')) { + i++; + } + + return i; +} + +function isBlank(str) { + return leadingWhitespace(str) === str.length; +} \ No newline at end of file diff --git a/node_modules/graphql/language/blockStringValue.js.flow b/node_modules/graphql/language/blockStringValue.js.flow new file mode 100644 index 0000000..5b90bc0 --- /dev/null +++ b/node_modules/graphql/language/blockStringValue.js.flow @@ -0,0 +1,64 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + */ +export default function blockStringValue(rawString: string): string { + // Expand a block string's raw value into independent lines. + const lines = rawString.split(/\r\n|[\n\r]/g); + + // Remove common indentation from all lines but first. + let commonIndent = null; + for (let i = 1; i < lines.length; i++) { + const line = lines[i]; + const indent = leadingWhitespace(line); + if ( + indent < line.length && + (commonIndent === null || indent < commonIndent) + ) { + commonIndent = indent; + if (commonIndent === 0) { + break; + } + } + } + + if (commonIndent) { + for (let i = 1; i < lines.length; i++) { + lines[i] = lines[i].slice(commonIndent); + } + } + + // Remove leading and trailing blank lines. + while (lines.length > 0 && isBlank(lines[0])) { + lines.shift(); + } + while (lines.length > 0 && isBlank(lines[lines.length - 1])) { + lines.pop(); + } + + // Return a string of the lines joined with U+000A. + return lines.join('\n'); +} + +function leadingWhitespace(str) { + let i = 0; + while (i < str.length && (str[i] === ' ' || str[i] === '\t')) { + i++; + } + return i; +} + +function isBlank(str) { + return leadingWhitespace(str) === str.length; +} diff --git a/node_modules/graphql/language/blockStringValue.mjs b/node_modules/graphql/language/blockStringValue.mjs new file mode 100644 index 0000000..d28e619 --- /dev/null +++ b/node_modules/graphql/language/blockStringValue.mjs @@ -0,0 +1,66 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + */ +export default function blockStringValue(rawString) { + // Expand a block string's raw value into independent lines. + var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first. + + var commonIndent = null; + + for (var i = 1; i < lines.length; i++) { + var line = lines[i]; + var indent = leadingWhitespace(line); + + if (indent < line.length && (commonIndent === null || indent < commonIndent)) { + commonIndent = indent; + + if (commonIndent === 0) { + break; + } + } + } + + if (commonIndent) { + for (var _i = 1; _i < lines.length; _i++) { + lines[_i] = lines[_i].slice(commonIndent); + } + } // Remove leading and trailing blank lines. + + + while (lines.length > 0 && isBlank(lines[0])) { + lines.shift(); + } + + while (lines.length > 0 && isBlank(lines[lines.length - 1])) { + lines.pop(); + } // Return a string of the lines joined with U+000A. + + + return lines.join('\n'); +} + +function leadingWhitespace(str) { + var i = 0; + + while (i < str.length && (str[i] === ' ' || str[i] === '\t')) { + i++; + } + + return i; +} + +function isBlank(str) { + return leadingWhitespace(str) === str.length; +} \ No newline at end of file diff --git a/node_modules/graphql/language/directiveLocation.js b/node_modules/graphql/language/directiveLocation.js new file mode 100644 index 0000000..3221e97 --- /dev/null +++ b/node_modules/graphql/language/directiveLocation.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.DirectiveLocation = void 0; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The set of allowed directive location values. + */ +var DirectiveLocation = Object.freeze({ + // Request Definitions + QUERY: 'QUERY', + MUTATION: 'MUTATION', + SUBSCRIPTION: 'SUBSCRIPTION', + FIELD: 'FIELD', + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', + INLINE_FRAGMENT: 'INLINE_FRAGMENT', + VARIABLE_DEFINITION: 'VARIABLE_DEFINITION', + // Type System Definitions + SCHEMA: 'SCHEMA', + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + FIELD_DEFINITION: 'FIELD_DEFINITION', + ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + ENUM_VALUE: 'ENUM_VALUE', + INPUT_OBJECT: 'INPUT_OBJECT', + INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION' +}); +/** + * The enum type representing the directive location values. + */ + +exports.DirectiveLocation = DirectiveLocation; \ No newline at end of file diff --git a/node_modules/graphql/language/directiveLocation.js.flow b/node_modules/graphql/language/directiveLocation.js.flow new file mode 100644 index 0000000..e63ec67 --- /dev/null +++ b/node_modules/graphql/language/directiveLocation.js.flow @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * The set of allowed directive location values. + */ +export const DirectiveLocation = Object.freeze({ + // Request Definitions + QUERY: 'QUERY', + MUTATION: 'MUTATION', + SUBSCRIPTION: 'SUBSCRIPTION', + FIELD: 'FIELD', + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', + INLINE_FRAGMENT: 'INLINE_FRAGMENT', + VARIABLE_DEFINITION: 'VARIABLE_DEFINITION', + // Type System Definitions + SCHEMA: 'SCHEMA', + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + FIELD_DEFINITION: 'FIELD_DEFINITION', + ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + ENUM_VALUE: 'ENUM_VALUE', + INPUT_OBJECT: 'INPUT_OBJECT', + INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION', +}); + +/** + * The enum type representing the directive location values. + */ +export type DirectiveLocationEnum = $Values; diff --git a/node_modules/graphql/language/directiveLocation.mjs b/node_modules/graphql/language/directiveLocation.mjs new file mode 100644 index 0000000..45d897f --- /dev/null +++ b/node_modules/graphql/language/directiveLocation.mjs @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The set of allowed directive location values. + */ +export var DirectiveLocation = Object.freeze({ + // Request Definitions + QUERY: 'QUERY', + MUTATION: 'MUTATION', + SUBSCRIPTION: 'SUBSCRIPTION', + FIELD: 'FIELD', + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', + INLINE_FRAGMENT: 'INLINE_FRAGMENT', + VARIABLE_DEFINITION: 'VARIABLE_DEFINITION', + // Type System Definitions + SCHEMA: 'SCHEMA', + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + FIELD_DEFINITION: 'FIELD_DEFINITION', + ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + ENUM_VALUE: 'ENUM_VALUE', + INPUT_OBJECT: 'INPUT_OBJECT', + INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION' +}); +/** + * The enum type representing the directive location values. + */ \ No newline at end of file diff --git a/node_modules/graphql/language/index.js b/node_modules/graphql/language/index.js new file mode 100644 index 0000000..e698cd1 --- /dev/null +++ b/node_modules/graphql/language/index.js @@ -0,0 +1,167 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getLocation", { + enumerable: true, + get: function get() { + return _location.getLocation; + } +}); +Object.defineProperty(exports, "Kind", { + enumerable: true, + get: function get() { + return _kinds.Kind; + } +}); +Object.defineProperty(exports, "createLexer", { + enumerable: true, + get: function get() { + return _lexer.createLexer; + } +}); +Object.defineProperty(exports, "TokenKind", { + enumerable: true, + get: function get() { + return _lexer.TokenKind; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _parser.parse; + } +}); +Object.defineProperty(exports, "parseValue", { + enumerable: true, + get: function get() { + return _parser.parseValue; + } +}); +Object.defineProperty(exports, "parseType", { + enumerable: true, + get: function get() { + return _parser.parseType; + } +}); +Object.defineProperty(exports, "print", { + enumerable: true, + get: function get() { + return _printer.print; + } +}); +Object.defineProperty(exports, "Source", { + enumerable: true, + get: function get() { + return _source.Source; + } +}); +Object.defineProperty(exports, "visit", { + enumerable: true, + get: function get() { + return _visitor.visit; + } +}); +Object.defineProperty(exports, "visitInParallel", { + enumerable: true, + get: function get() { + return _visitor.visitInParallel; + } +}); +Object.defineProperty(exports, "visitWithTypeInfo", { + enumerable: true, + get: function get() { + return _visitor.visitWithTypeInfo; + } +}); +Object.defineProperty(exports, "getVisitFn", { + enumerable: true, + get: function get() { + return _visitor.getVisitFn; + } +}); +Object.defineProperty(exports, "BREAK", { + enumerable: true, + get: function get() { + return _visitor.BREAK; + } +}); +Object.defineProperty(exports, "isDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isDefinitionNode; + } +}); +Object.defineProperty(exports, "isExecutableDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isExecutableDefinitionNode; + } +}); +Object.defineProperty(exports, "isSelectionNode", { + enumerable: true, + get: function get() { + return _predicates.isSelectionNode; + } +}); +Object.defineProperty(exports, "isValueNode", { + enumerable: true, + get: function get() { + return _predicates.isValueNode; + } +}); +Object.defineProperty(exports, "isTypeNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeNode; + } +}); +Object.defineProperty(exports, "isTypeSystemDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeSystemDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeSystemExtensionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeSystemExtensionNode; + } +}); +Object.defineProperty(exports, "isTypeExtensionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeExtensionNode; + } +}); +Object.defineProperty(exports, "DirectiveLocation", { + enumerable: true, + get: function get() { + return _directiveLocation.DirectiveLocation; + } +}); + +var _location = require("./location"); + +var _kinds = require("./kinds"); + +var _lexer = require("./lexer"); + +var _parser = require("./parser"); + +var _printer = require("./printer"); + +var _source = require("./source"); + +var _visitor = require("./visitor"); + +var _predicates = require("./predicates"); + +var _directiveLocation = require("./directiveLocation"); \ No newline at end of file diff --git a/node_modules/graphql/language/index.js.flow b/node_modules/graphql/language/index.js.flow new file mode 100644 index 0000000..8054718 --- /dev/null +++ b/node_modules/graphql/language/index.js.flow @@ -0,0 +1,104 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { getLocation } from './location'; +export type { SourceLocation } from './location'; +export { Kind } from './kinds'; +export type { KindEnum } from './kinds'; +export { createLexer, TokenKind } from './lexer'; +export { parse, parseValue, parseType } from './parser'; +export { print } from './printer'; +export { Source } from './source'; +export { + visit, + visitInParallel, + visitWithTypeInfo, + getVisitFn, + BREAK, +} from './visitor'; +export type { ASTVisitor, Visitor, VisitFn, VisitorKeyMap } from './visitor'; + +export type { Lexer, TokenKindEnum } from './lexer'; +export type { ParseOptions } from './parser'; + +export type { + Location, + Token, + ASTNode, + ASTKindToNode, + // Each kind of AST node + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from './ast'; + +export { + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, +} from './predicates'; + +export { DirectiveLocation } from './directiveLocation'; +export type { DirectiveLocationEnum } from './directiveLocation'; diff --git a/node_modules/graphql/language/index.mjs b/node_modules/graphql/language/index.mjs new file mode 100644 index 0000000..a2940e2 --- /dev/null +++ b/node_modules/graphql/language/index.mjs @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { getLocation } from './location'; +export { Kind } from './kinds'; +export { createLexer, TokenKind } from './lexer'; +export { parse, parseValue, parseType } from './parser'; +export { print } from './printer'; +export { Source } from './source'; +export { visit, visitInParallel, visitWithTypeInfo, getVisitFn, BREAK } from './visitor'; +export { isDefinitionNode, isExecutableDefinitionNode, isSelectionNode, isValueNode, isTypeNode, isTypeSystemDefinitionNode, isTypeDefinitionNode, isTypeSystemExtensionNode, isTypeExtensionNode } from './predicates'; +export { DirectiveLocation } from './directiveLocation'; \ No newline at end of file diff --git a/node_modules/graphql/language/kinds.js b/node_modules/graphql/language/kinds.js new file mode 100644 index 0000000..7eded7a --- /dev/null +++ b/node_modules/graphql/language/kinds.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Kind = void 0; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The set of allowed kind values for AST nodes. + */ +var Kind = Object.freeze({ + // Name + NAME: 'Name', + // Document + DOCUMENT: 'Document', + OPERATION_DEFINITION: 'OperationDefinition', + VARIABLE_DEFINITION: 'VariableDefinition', + SELECTION_SET: 'SelectionSet', + FIELD: 'Field', + ARGUMENT: 'Argument', + // Fragments + FRAGMENT_SPREAD: 'FragmentSpread', + INLINE_FRAGMENT: 'InlineFragment', + FRAGMENT_DEFINITION: 'FragmentDefinition', + // Values + VARIABLE: 'Variable', + INT: 'IntValue', + FLOAT: 'FloatValue', + STRING: 'StringValue', + BOOLEAN: 'BooleanValue', + NULL: 'NullValue', + ENUM: 'EnumValue', + LIST: 'ListValue', + OBJECT: 'ObjectValue', + OBJECT_FIELD: 'ObjectField', + // Directives + DIRECTIVE: 'Directive', + // Types + NAMED_TYPE: 'NamedType', + LIST_TYPE: 'ListType', + NON_NULL_TYPE: 'NonNullType', + // Type System Definitions + SCHEMA_DEFINITION: 'SchemaDefinition', + OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition', + // Type Definitions + SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition', + OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition', + FIELD_DEFINITION: 'FieldDefinition', + INPUT_VALUE_DEFINITION: 'InputValueDefinition', + INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition', + UNION_TYPE_DEFINITION: 'UnionTypeDefinition', + ENUM_TYPE_DEFINITION: 'EnumTypeDefinition', + ENUM_VALUE_DEFINITION: 'EnumValueDefinition', + INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition', + // Directive Definitions + DIRECTIVE_DEFINITION: 'DirectiveDefinition', + // Type System Extensions + SCHEMA_EXTENSION: 'SchemaExtension', + // Type Extensions + SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension', + OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension', + INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension', + UNION_TYPE_EXTENSION: 'UnionTypeExtension', + ENUM_TYPE_EXTENSION: 'EnumTypeExtension', + INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension' +}); +/** + * The enum type representing the possible kind values of AST nodes. + */ + +exports.Kind = Kind; \ No newline at end of file diff --git a/node_modules/graphql/language/kinds.js.flow b/node_modules/graphql/language/kinds.js.flow new file mode 100644 index 0000000..ad46306 --- /dev/null +++ b/node_modules/graphql/language/kinds.js.flow @@ -0,0 +1,83 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * The set of allowed kind values for AST nodes. + */ +export const Kind = Object.freeze({ + // Name + NAME: 'Name', + + // Document + DOCUMENT: 'Document', + OPERATION_DEFINITION: 'OperationDefinition', + VARIABLE_DEFINITION: 'VariableDefinition', + SELECTION_SET: 'SelectionSet', + FIELD: 'Field', + ARGUMENT: 'Argument', + + // Fragments + FRAGMENT_SPREAD: 'FragmentSpread', + INLINE_FRAGMENT: 'InlineFragment', + FRAGMENT_DEFINITION: 'FragmentDefinition', + + // Values + VARIABLE: 'Variable', + INT: 'IntValue', + FLOAT: 'FloatValue', + STRING: 'StringValue', + BOOLEAN: 'BooleanValue', + NULL: 'NullValue', + ENUM: 'EnumValue', + LIST: 'ListValue', + OBJECT: 'ObjectValue', + OBJECT_FIELD: 'ObjectField', + + // Directives + DIRECTIVE: 'Directive', + + // Types + NAMED_TYPE: 'NamedType', + LIST_TYPE: 'ListType', + NON_NULL_TYPE: 'NonNullType', + + // Type System Definitions + SCHEMA_DEFINITION: 'SchemaDefinition', + OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition', + + // Type Definitions + SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition', + OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition', + FIELD_DEFINITION: 'FieldDefinition', + INPUT_VALUE_DEFINITION: 'InputValueDefinition', + INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition', + UNION_TYPE_DEFINITION: 'UnionTypeDefinition', + ENUM_TYPE_DEFINITION: 'EnumTypeDefinition', + ENUM_VALUE_DEFINITION: 'EnumValueDefinition', + INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition', + + // Directive Definitions + DIRECTIVE_DEFINITION: 'DirectiveDefinition', + + // Type System Extensions + SCHEMA_EXTENSION: 'SchemaExtension', + + // Type Extensions + SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension', + OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension', + INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension', + UNION_TYPE_EXTENSION: 'UnionTypeExtension', + ENUM_TYPE_EXTENSION: 'EnumTypeExtension', + INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension', +}); + +/** + * The enum type representing the possible kind values of AST nodes. + */ +export type KindEnum = $Values; diff --git a/node_modules/graphql/language/kinds.mjs b/node_modules/graphql/language/kinds.mjs new file mode 100644 index 0000000..a973e66 --- /dev/null +++ b/node_modules/graphql/language/kinds.mjs @@ -0,0 +1,71 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The set of allowed kind values for AST nodes. + */ +export var Kind = Object.freeze({ + // Name + NAME: 'Name', + // Document + DOCUMENT: 'Document', + OPERATION_DEFINITION: 'OperationDefinition', + VARIABLE_DEFINITION: 'VariableDefinition', + SELECTION_SET: 'SelectionSet', + FIELD: 'Field', + ARGUMENT: 'Argument', + // Fragments + FRAGMENT_SPREAD: 'FragmentSpread', + INLINE_FRAGMENT: 'InlineFragment', + FRAGMENT_DEFINITION: 'FragmentDefinition', + // Values + VARIABLE: 'Variable', + INT: 'IntValue', + FLOAT: 'FloatValue', + STRING: 'StringValue', + BOOLEAN: 'BooleanValue', + NULL: 'NullValue', + ENUM: 'EnumValue', + LIST: 'ListValue', + OBJECT: 'ObjectValue', + OBJECT_FIELD: 'ObjectField', + // Directives + DIRECTIVE: 'Directive', + // Types + NAMED_TYPE: 'NamedType', + LIST_TYPE: 'ListType', + NON_NULL_TYPE: 'NonNullType', + // Type System Definitions + SCHEMA_DEFINITION: 'SchemaDefinition', + OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition', + // Type Definitions + SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition', + OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition', + FIELD_DEFINITION: 'FieldDefinition', + INPUT_VALUE_DEFINITION: 'InputValueDefinition', + INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition', + UNION_TYPE_DEFINITION: 'UnionTypeDefinition', + ENUM_TYPE_DEFINITION: 'EnumTypeDefinition', + ENUM_VALUE_DEFINITION: 'EnumValueDefinition', + INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition', + // Directive Definitions + DIRECTIVE_DEFINITION: 'DirectiveDefinition', + // Type System Extensions + SCHEMA_EXTENSION: 'SchemaExtension', + // Type Extensions + SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension', + OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension', + INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension', + UNION_TYPE_EXTENSION: 'UnionTypeExtension', + ENUM_TYPE_EXTENSION: 'EnumTypeExtension', + INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension' +}); +/** + * The enum type representing the possible kind values of AST nodes. + */ \ No newline at end of file diff --git a/node_modules/graphql/language/lexer.js b/node_modules/graphql/language/lexer.js new file mode 100644 index 0000000..1678775 --- /dev/null +++ b/node_modules/graphql/language/lexer.js @@ -0,0 +1,648 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createLexer = createLexer; +exports.getTokenDesc = getTokenDesc; +exports.TokenKind = void 0; + +var _error = require("../error"); + +var _blockStringValue = _interopRequireDefault(require("./blockStringValue")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given a Source object, this returns a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +function createLexer(source, options) { + var startOfFileToken = new Tok(TokenKind.SOF, 0, 0, 0, 0, null); + var lexer = { + source: source, + options: options, + lastToken: startOfFileToken, + token: startOfFileToken, + line: 1, + lineStart: 0, + advance: advanceLexer, + lookahead: lookahead + }; + return lexer; +} + +function advanceLexer() { + this.lastToken = this.token; + var token = this.token = this.lookahead(); + return token; +} + +function lookahead() { + var token = this.token; + + if (token.kind !== TokenKind.EOF) { + do { + // Note: next is only mutable during parsing, so we cast to allow this. + token = token.next || (token.next = readToken(this, token)); + } while (token.kind === TokenKind.COMMENT); + } + + return token; +} +/** + * The return type of createLexer. + */ + + +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +var TokenKind = Object.freeze({ + SOF: '', + EOF: '', + BANG: '!', + DOLLAR: '$', + AMP: '&', + PAREN_L: '(', + PAREN_R: ')', + SPREAD: '...', + COLON: ':', + EQUALS: '=', + AT: '@', + BRACKET_L: '[', + BRACKET_R: ']', + BRACE_L: '{', + PIPE: '|', + BRACE_R: '}', + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment' +}); +/** + * The enum type representing the token kinds values. + */ + +exports.TokenKind = TokenKind; + +/** + * A helper function to describe a token as a string for debugging + */ +function getTokenDesc(token) { + var value = token.value; + return value ? "".concat(token.kind, " \"").concat(value, "\"") : token.kind; +} + +var charCodeAt = String.prototype.charCodeAt; +var slice = String.prototype.slice; +/** + * Helper function for constructing the Token object. + */ + +function Tok(kind, start, end, line, column, prev, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; + this.value = value; + this.prev = prev; + this.next = null; +} // Print a simplified form when appearing in JSON/util.inspect. + + +Tok.prototype.toJSON = Tok.prototype.inspect = function toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column + }; +}; + +function printCharCode(code) { + return (// NaN/undefined represents access beyond the end of the file. + isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII. + code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form. + "\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"") + ); +} +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace and comments until it finds the next lexable + * token, then lexes punctuators immediately or calls the appropriate helper + * function for more complicated tokens. + */ + + +function readToken(lexer, prev) { + var source = lexer.source; + var body = source.body; + var bodyLength = body.length; + var pos = positionAfterWhitespace(body, prev.end, lexer); + var line = lexer.line; + var col = 1 + pos - lexer.lineStart; + + if (pos >= bodyLength) { + return new Tok(TokenKind.EOF, bodyLength, bodyLength, line, col, prev); + } + + var code = charCodeAt.call(body, pos); // SourceCharacter + + switch (code) { + // ! + case 33: + return new Tok(TokenKind.BANG, pos, pos + 1, line, col, prev); + // # + + case 35: + return readComment(source, pos, line, col, prev); + // $ + + case 36: + return new Tok(TokenKind.DOLLAR, pos, pos + 1, line, col, prev); + // & + + case 38: + return new Tok(TokenKind.AMP, pos, pos + 1, line, col, prev); + // ( + + case 40: + return new Tok(TokenKind.PAREN_L, pos, pos + 1, line, col, prev); + // ) + + case 41: + return new Tok(TokenKind.PAREN_R, pos, pos + 1, line, col, prev); + // . + + case 46: + if (charCodeAt.call(body, pos + 1) === 46 && charCodeAt.call(body, pos + 2) === 46) { + return new Tok(TokenKind.SPREAD, pos, pos + 3, line, col, prev); + } + + break; + // : + + case 58: + return new Tok(TokenKind.COLON, pos, pos + 1, line, col, prev); + // = + + case 61: + return new Tok(TokenKind.EQUALS, pos, pos + 1, line, col, prev); + // @ + + case 64: + return new Tok(TokenKind.AT, pos, pos + 1, line, col, prev); + // [ + + case 91: + return new Tok(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev); + // ] + + case 93: + return new Tok(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev); + // { + + case 123: + return new Tok(TokenKind.BRACE_L, pos, pos + 1, line, col, prev); + // | + + case 124: + return new Tok(TokenKind.PIPE, pos, pos + 1, line, col, prev); + // } + + case 125: + return new Tok(TokenKind.BRACE_R, pos, pos + 1, line, col, prev); + // A-Z _ a-z + + case 65: + case 66: + case 67: + case 68: + case 69: + case 70: + case 71: + case 72: + case 73: + case 74: + case 75: + case 76: + case 77: + case 78: + case 79: + case 80: + case 81: + case 82: + case 83: + case 84: + case 85: + case 86: + case 87: + case 88: + case 89: + case 90: + case 95: + case 97: + case 98: + case 99: + case 100: + case 101: + case 102: + case 103: + case 104: + case 105: + case 106: + case 107: + case 108: + case 109: + case 110: + case 111: + case 112: + case 113: + case 114: + case 115: + case 116: + case 117: + case 118: + case 119: + case 120: + case 121: + case 122: + return readName(source, pos, line, col, prev); + // - 0-9 + + case 45: + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + return readNumber(source, pos, code, line, col, prev); + // " + + case 34: + if (charCodeAt.call(body, pos + 1) === 34 && charCodeAt.call(body, pos + 2) === 34) { + return readBlockString(source, pos, line, col, prev); + } + + return readString(source, pos, line, col, prev); + } + + throw (0, _error.syntaxError)(source, pos, unexpectedCharacterMessage(code)); +} +/** + * Report a message that an unexpected character was encountered. + */ + + +function unexpectedCharacterMessage(code) { + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + return "Cannot contain the invalid character ".concat(printCharCode(code), "."); + } + + if (code === 39) { + // ' + return "Unexpected single quote character ('), did you mean to use " + 'a double quote (")?'; + } + + return "Cannot parse the unexpected character ".concat(printCharCode(code), "."); +} +/** + * Reads from body starting at startPosition until it finds a non-whitespace + * or commented character, then returns the position of that character for + * lexing. + */ + + +function positionAfterWhitespace(body, startPosition, lexer) { + var bodyLength = body.length; + var position = startPosition; + + while (position < bodyLength) { + var code = charCodeAt.call(body, position); // tab | space | comma | BOM + + if (code === 9 || code === 32 || code === 44 || code === 0xfeff) { + ++position; + } else if (code === 10) { + // new line + ++position; + ++lexer.line; + lexer.lineStart = position; + } else if (code === 13) { + // carriage return + if (charCodeAt.call(body, position + 1) === 10) { + position += 2; + } else { + ++position; + } + + ++lexer.line; + lexer.lineStart = position; + } else { + break; + } + } + + return position; +} +/** + * Reads a comment token from the source file. + * + * #[\u0009\u0020-\uFFFF]* + */ + + +function readComment(source, start, line, col, prev) { + var body = source.body; + var code; + var position = start; + + do { + code = charCodeAt.call(body, ++position); + } while (code !== null && ( // SourceCharacter but not LineTerminator + code > 0x001f || code === 0x0009)); + + return new Tok(TokenKind.COMMENT, start, position, line, col, prev, slice.call(body, start + 1, position)); +} +/** + * Reads a number token from the source file, either a float + * or an int depending on whether a decimal point appears. + * + * Int: -?(0|[1-9][0-9]*) + * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? + */ + + +function readNumber(source, start, firstCode, line, col, prev) { + var body = source.body; + var code = firstCode; + var position = start; + var isFloat = false; + + if (code === 45) { + // - + code = charCodeAt.call(body, ++position); + } + + if (code === 48) { + // 0 + code = charCodeAt.call(body, ++position); + + if (code >= 48 && code <= 57) { + throw (0, _error.syntaxError)(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), ".")); + } + } else { + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 46) { + // . + isFloat = true; + code = charCodeAt.call(body, ++position); + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 69 || code === 101) { + // E e + isFloat = true; + code = charCodeAt.call(body, ++position); + + if (code === 43 || code === 45) { + // + - + code = charCodeAt.call(body, ++position); + } + + position = readDigits(source, position, code); + } + + return new Tok(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, slice.call(body, start, position)); +} +/** + * Returns the new position in the source after reading digits. + */ + + +function readDigits(source, start, firstCode) { + var body = source.body; + var position = start; + var code = firstCode; + + if (code >= 48 && code <= 57) { + // 0 - 9 + do { + code = charCodeAt.call(body, ++position); + } while (code >= 48 && code <= 57); // 0 - 9 + + + return position; + } + + throw (0, _error.syntaxError)(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), ".")); +} +/** + * Reads a string token from the source file. + * + * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*" + */ + + +function readString(source, start, line, col, prev) { + var body = source.body; + var position = start + 1; + var chunkStart = position; + var code = 0; + var value = ''; + + while (position < body.length && (code = charCodeAt.call(body, position)) !== null && // not LineTerminator + code !== 0x000a && code !== 0x000d) { + // Closing Quote (") + if (code === 34) { + value += slice.call(body, chunkStart, position); + return new Tok(TokenKind.STRING, start, position + 1, line, col, prev, value); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009) { + throw (0, _error.syntaxError)(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } + + ++position; + + if (code === 92) { + // \ + value += slice.call(body, chunkStart, position - 1); + code = charCodeAt.call(body, position); + + switch (code) { + case 34: + value += '"'; + break; + + case 47: + value += '/'; + break; + + case 92: + value += '\\'; + break; + + case 98: + value += '\b'; + break; + + case 102: + value += '\f'; + break; + + case 110: + value += '\n'; + break; + + case 114: + value += '\r'; + break; + + case 116: + value += '\t'; + break; + + case 117: + // u + var charCode = uniCharCode(charCodeAt.call(body, position + 1), charCodeAt.call(body, position + 2), charCodeAt.call(body, position + 3), charCodeAt.call(body, position + 4)); + + if (charCode < 0) { + throw (0, _error.syntaxError)(source, position, 'Invalid character escape sequence: ' + "\\u".concat(body.slice(position + 1, position + 5), ".")); + } + + value += String.fromCharCode(charCode); + position += 4; + break; + + default: + throw (0, _error.syntaxError)(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), ".")); + } + + ++position; + chunkStart = position; + } + } + + throw (0, _error.syntaxError)(source, position, 'Unterminated string.'); +} +/** + * Reads a block string token from the source file. + * + * """("?"?(\\"""|\\(?!=""")|[^"\\]))*""" + */ + + +function readBlockString(source, start, line, col, prev) { + var body = source.body; + var position = start + 3; + var chunkStart = position; + var code = 0; + var rawValue = ''; + + while (position < body.length && (code = charCodeAt.call(body, position)) !== null) { + // Closing Triple-Quote (""") + if (code === 34 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34) { + rawValue += slice.call(body, chunkStart, position); + return new Tok(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, (0, _blockStringValue.default)(rawValue)); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + throw (0, _error.syntaxError)(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } // Escape Triple-Quote (\""") + + + if (code === 92 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34 && charCodeAt.call(body, position + 3) === 34) { + rawValue += slice.call(body, chunkStart, position) + '"""'; + position += 4; + chunkStart = position; + } else { + ++position; + } + } + + throw (0, _error.syntaxError)(source, position, 'Unterminated string.'); +} +/** + * Converts four hexadecimal chars to the integer that the + * string represents. For example, uniCharCode('0','0','0','f') + * will return 15, and uniCharCode('0','0','f','f') returns 255. + * + * Returns a negative number on error, if a char was invalid. + * + * This is implemented by noting that char2hex() returns -1 on error, + * which means the result of ORing the char2hex() will also be negative. + */ + + +function uniCharCode(a, b, c, d) { + return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d); +} +/** + * Converts a hex character to its integer value. + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 on error. + */ + + +function char2hex(a) { + return a >= 48 && a <= 57 ? a - 48 // 0-9 + : a >= 65 && a <= 70 ? a - 55 // A-F + : a >= 97 && a <= 102 ? a - 87 // a-f + : -1; +} +/** + * Reads an alphanumeric + underscore name from the source. + * + * [_A-Za-z][_0-9A-Za-z]* + */ + + +function readName(source, start, line, col, prev) { + var body = source.body; + var bodyLength = body.length; + var position = start + 1; + var code = 0; + + while (position !== bodyLength && (code = charCodeAt.call(body, position)) !== null && (code === 95 || // _ + code >= 48 && code <= 57 || // 0-9 + code >= 65 && code <= 90 || // A-Z + code >= 97 && code <= 122) // a-z + ) { + ++position; + } + + return new Tok(TokenKind.NAME, start, position, line, col, prev, slice.call(body, start, position)); +} \ No newline at end of file diff --git a/node_modules/graphql/language/lexer.js.flow b/node_modules/graphql/language/lexer.js.flow new file mode 100644 index 0000000..9eff1c2 --- /dev/null +++ b/node_modules/graphql/language/lexer.js.flow @@ -0,0 +1,752 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { Token } from './ast'; +import type { Source } from './source'; +import { syntaxError } from '../error'; +import blockStringValue from './blockStringValue'; + +/** + * Given a Source object, this returns a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +export function createLexer( + source: Source, + options: TOptions, +): Lexer { + const startOfFileToken = new Tok(TokenKind.SOF, 0, 0, 0, 0, null); + const lexer: Lexer = { + source, + options, + lastToken: startOfFileToken, + token: startOfFileToken, + line: 1, + lineStart: 0, + advance: advanceLexer, + lookahead, + }; + return lexer; +} + +function advanceLexer() { + this.lastToken = this.token; + const token = (this.token = this.lookahead()); + return token; +} + +function lookahead() { + let token = this.token; + if (token.kind !== TokenKind.EOF) { + do { + // Note: next is only mutable during parsing, so we cast to allow this. + token = token.next || ((token: any).next = readToken(this, token)); + } while (token.kind === TokenKind.COMMENT); + } + return token; +} + +/** + * The return type of createLexer. + */ +export type Lexer = { + source: Source, + options: TOptions, + + /** + * The previously focused non-ignored token. + */ + lastToken: Token, + + /** + * The currently focused non-ignored token. + */ + token: Token, + + /** + * The (1-indexed) line containing the current token. + */ + line: number, + + /** + * The character offset at which the current line begins. + */ + lineStart: number, + + /** + * Advances the token stream to the next non-ignored token. + */ + advance(): Token, + + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the Lexer's state. + */ + lookahead(): Token, +}; + +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +export const TokenKind = Object.freeze({ + SOF: '', + EOF: '', + BANG: '!', + DOLLAR: '$', + AMP: '&', + PAREN_L: '(', + PAREN_R: ')', + SPREAD: '...', + COLON: ':', + EQUALS: '=', + AT: '@', + BRACKET_L: '[', + BRACKET_R: ']', + BRACE_L: '{', + PIPE: '|', + BRACE_R: '}', + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment', +}); + +/** + * The enum type representing the token kinds values. + */ +export type TokenKindEnum = $Values; + +/** + * A helper function to describe a token as a string for debugging + */ +export function getTokenDesc(token: Token): string { + const value = token.value; + return value ? `${token.kind} "${value}"` : token.kind; +} + +const charCodeAt = String.prototype.charCodeAt; +const slice = String.prototype.slice; + +/** + * Helper function for constructing the Token object. + */ +function Tok( + kind: TokenKindEnum, + start: number, + end: number, + line: number, + column: number, + prev: Token | null, + value?: string, +) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; + this.value = value; + this.prev = prev; + this.next = null; +} + +// Print a simplified form when appearing in JSON/util.inspect. +Tok.prototype.toJSON = Tok.prototype.inspect = function toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column, + }; +}; + +function printCharCode(code) { + return ( + // NaN/undefined represents access beyond the end of the file. + isNaN(code) + ? TokenKind.EOF + : // Trust JSON for ASCII. + code < 0x007f + ? JSON.stringify(String.fromCharCode(code)) + : // Otherwise print the escaped form. + `"\\u${('00' + code.toString(16).toUpperCase()).slice(-4)}"` + ); +} + +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace and comments until it finds the next lexable + * token, then lexes punctuators immediately or calls the appropriate helper + * function for more complicated tokens. + */ +function readToken(lexer: Lexer<*>, prev: Token): Token { + const source = lexer.source; + const body = source.body; + const bodyLength = body.length; + + const pos = positionAfterWhitespace(body, prev.end, lexer); + const line = lexer.line; + const col = 1 + pos - lexer.lineStart; + + if (pos >= bodyLength) { + return new Tok(TokenKind.EOF, bodyLength, bodyLength, line, col, prev); + } + + const code = charCodeAt.call(body, pos); + + // SourceCharacter + switch (code) { + // ! + case 33: + return new Tok(TokenKind.BANG, pos, pos + 1, line, col, prev); + // # + case 35: + return readComment(source, pos, line, col, prev); + // $ + case 36: + return new Tok(TokenKind.DOLLAR, pos, pos + 1, line, col, prev); + // & + case 38: + return new Tok(TokenKind.AMP, pos, pos + 1, line, col, prev); + // ( + case 40: + return new Tok(TokenKind.PAREN_L, pos, pos + 1, line, col, prev); + // ) + case 41: + return new Tok(TokenKind.PAREN_R, pos, pos + 1, line, col, prev); + // . + case 46: + if ( + charCodeAt.call(body, pos + 1) === 46 && + charCodeAt.call(body, pos + 2) === 46 + ) { + return new Tok(TokenKind.SPREAD, pos, pos + 3, line, col, prev); + } + break; + // : + case 58: + return new Tok(TokenKind.COLON, pos, pos + 1, line, col, prev); + // = + case 61: + return new Tok(TokenKind.EQUALS, pos, pos + 1, line, col, prev); + // @ + case 64: + return new Tok(TokenKind.AT, pos, pos + 1, line, col, prev); + // [ + case 91: + return new Tok(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev); + // ] + case 93: + return new Tok(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev); + // { + case 123: + return new Tok(TokenKind.BRACE_L, pos, pos + 1, line, col, prev); + // | + case 124: + return new Tok(TokenKind.PIPE, pos, pos + 1, line, col, prev); + // } + case 125: + return new Tok(TokenKind.BRACE_R, pos, pos + 1, line, col, prev); + // A-Z _ a-z + case 65: + case 66: + case 67: + case 68: + case 69: + case 70: + case 71: + case 72: + case 73: + case 74: + case 75: + case 76: + case 77: + case 78: + case 79: + case 80: + case 81: + case 82: + case 83: + case 84: + case 85: + case 86: + case 87: + case 88: + case 89: + case 90: + case 95: + case 97: + case 98: + case 99: + case 100: + case 101: + case 102: + case 103: + case 104: + case 105: + case 106: + case 107: + case 108: + case 109: + case 110: + case 111: + case 112: + case 113: + case 114: + case 115: + case 116: + case 117: + case 118: + case 119: + case 120: + case 121: + case 122: + return readName(source, pos, line, col, prev); + // - 0-9 + case 45: + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + return readNumber(source, pos, code, line, col, prev); + // " + case 34: + if ( + charCodeAt.call(body, pos + 1) === 34 && + charCodeAt.call(body, pos + 2) === 34 + ) { + return readBlockString(source, pos, line, col, prev); + } + return readString(source, pos, line, col, prev); + } + + throw syntaxError(source, pos, unexpectedCharacterMessage(code)); +} + +/** + * Report a message that an unexpected character was encountered. + */ +function unexpectedCharacterMessage(code) { + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + return `Cannot contain the invalid character ${printCharCode(code)}.`; + } + + if (code === 39) { + // ' + return ( + "Unexpected single quote character ('), did you mean to use " + + 'a double quote (")?' + ); + } + + return `Cannot parse the unexpected character ${printCharCode(code)}.`; +} + +/** + * Reads from body starting at startPosition until it finds a non-whitespace + * or commented character, then returns the position of that character for + * lexing. + */ +function positionAfterWhitespace( + body: string, + startPosition: number, + lexer: Lexer<*>, +): number { + const bodyLength = body.length; + let position = startPosition; + while (position < bodyLength) { + const code = charCodeAt.call(body, position); + // tab | space | comma | BOM + if (code === 9 || code === 32 || code === 44 || code === 0xfeff) { + ++position; + } else if (code === 10) { + // new line + ++position; + ++lexer.line; + lexer.lineStart = position; + } else if (code === 13) { + // carriage return + if (charCodeAt.call(body, position + 1) === 10) { + position += 2; + } else { + ++position; + } + ++lexer.line; + lexer.lineStart = position; + } else { + break; + } + } + return position; +} + +/** + * Reads a comment token from the source file. + * + * #[\u0009\u0020-\uFFFF]* + */ +function readComment(source, start, line, col, prev): Token { + const body = source.body; + let code; + let position = start; + + do { + code = charCodeAt.call(body, ++position); + } while ( + code !== null && + // SourceCharacter but not LineTerminator + (code > 0x001f || code === 0x0009) + ); + + return new Tok( + TokenKind.COMMENT, + start, + position, + line, + col, + prev, + slice.call(body, start + 1, position), + ); +} + +/** + * Reads a number token from the source file, either a float + * or an int depending on whether a decimal point appears. + * + * Int: -?(0|[1-9][0-9]*) + * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? + */ +function readNumber(source, start, firstCode, line, col, prev): Token { + const body = source.body; + let code = firstCode; + let position = start; + let isFloat = false; + + if (code === 45) { + // - + code = charCodeAt.call(body, ++position); + } + + if (code === 48) { + // 0 + code = charCodeAt.call(body, ++position); + if (code >= 48 && code <= 57) { + throw syntaxError( + source, + position, + `Invalid number, unexpected digit after 0: ${printCharCode(code)}.`, + ); + } + } else { + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 46) { + // . + isFloat = true; + + code = charCodeAt.call(body, ++position); + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 69 || code === 101) { + // E e + isFloat = true; + + code = charCodeAt.call(body, ++position); + if (code === 43 || code === 45) { + // + - + code = charCodeAt.call(body, ++position); + } + position = readDigits(source, position, code); + } + + return new Tok( + isFloat ? TokenKind.FLOAT : TokenKind.INT, + start, + position, + line, + col, + prev, + slice.call(body, start, position), + ); +} + +/** + * Returns the new position in the source after reading digits. + */ +function readDigits(source, start, firstCode) { + const body = source.body; + let position = start; + let code = firstCode; + if (code >= 48 && code <= 57) { + // 0 - 9 + do { + code = charCodeAt.call(body, ++position); + } while (code >= 48 && code <= 57); // 0 - 9 + return position; + } + throw syntaxError( + source, + position, + `Invalid number, expected digit but got: ${printCharCode(code)}.`, + ); +} + +/** + * Reads a string token from the source file. + * + * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*" + */ +function readString(source, start, line, col, prev): Token { + const body = source.body; + let position = start + 1; + let chunkStart = position; + let code = 0; + let value = ''; + + while ( + position < body.length && + (code = charCodeAt.call(body, position)) !== null && + // not LineTerminator + code !== 0x000a && + code !== 0x000d + ) { + // Closing Quote (") + if (code === 34) { + value += slice.call(body, chunkStart, position); + return new Tok( + TokenKind.STRING, + start, + position + 1, + line, + col, + prev, + value, + ); + } + + // SourceCharacter + if (code < 0x0020 && code !== 0x0009) { + throw syntaxError( + source, + position, + `Invalid character within String: ${printCharCode(code)}.`, + ); + } + + ++position; + if (code === 92) { + // \ + value += slice.call(body, chunkStart, position - 1); + code = charCodeAt.call(body, position); + switch (code) { + case 34: + value += '"'; + break; + case 47: + value += '/'; + break; + case 92: + value += '\\'; + break; + case 98: + value += '\b'; + break; + case 102: + value += '\f'; + break; + case 110: + value += '\n'; + break; + case 114: + value += '\r'; + break; + case 116: + value += '\t'; + break; + case 117: // u + const charCode = uniCharCode( + charCodeAt.call(body, position + 1), + charCodeAt.call(body, position + 2), + charCodeAt.call(body, position + 3), + charCodeAt.call(body, position + 4), + ); + if (charCode < 0) { + throw syntaxError( + source, + position, + 'Invalid character escape sequence: ' + + `\\u${body.slice(position + 1, position + 5)}.`, + ); + } + value += String.fromCharCode(charCode); + position += 4; + break; + default: + throw syntaxError( + source, + position, + `Invalid character escape sequence: \\${String.fromCharCode( + code, + )}.`, + ); + } + ++position; + chunkStart = position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} + +/** + * Reads a block string token from the source file. + * + * """("?"?(\\"""|\\(?!=""")|[^"\\]))*""" + */ +function readBlockString(source, start, line, col, prev): Token { + const body = source.body; + let position = start + 3; + let chunkStart = position; + let code = 0; + let rawValue = ''; + + while ( + position < body.length && + (code = charCodeAt.call(body, position)) !== null + ) { + // Closing Triple-Quote (""") + if ( + code === 34 && + charCodeAt.call(body, position + 1) === 34 && + charCodeAt.call(body, position + 2) === 34 + ) { + rawValue += slice.call(body, chunkStart, position); + return new Tok( + TokenKind.BLOCK_STRING, + start, + position + 3, + line, + col, + prev, + blockStringValue(rawValue), + ); + } + + // SourceCharacter + if ( + code < 0x0020 && + code !== 0x0009 && + code !== 0x000a && + code !== 0x000d + ) { + throw syntaxError( + source, + position, + `Invalid character within String: ${printCharCode(code)}.`, + ); + } + + // Escape Triple-Quote (\""") + if ( + code === 92 && + charCodeAt.call(body, position + 1) === 34 && + charCodeAt.call(body, position + 2) === 34 && + charCodeAt.call(body, position + 3) === 34 + ) { + rawValue += slice.call(body, chunkStart, position) + '"""'; + position += 4; + chunkStart = position; + } else { + ++position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} + +/** + * Converts four hexadecimal chars to the integer that the + * string represents. For example, uniCharCode('0','0','0','f') + * will return 15, and uniCharCode('0','0','f','f') returns 255. + * + * Returns a negative number on error, if a char was invalid. + * + * This is implemented by noting that char2hex() returns -1 on error, + * which means the result of ORing the char2hex() will also be negative. + */ +function uniCharCode(a, b, c, d) { + return ( + (char2hex(a) << 12) | (char2hex(b) << 8) | (char2hex(c) << 4) | char2hex(d) + ); +} + +/** + * Converts a hex character to its integer value. + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 on error. + */ +function char2hex(a) { + return a >= 48 && a <= 57 + ? a - 48 // 0-9 + : a >= 65 && a <= 70 + ? a - 55 // A-F + : a >= 97 && a <= 102 + ? a - 87 // a-f + : -1; +} + +/** + * Reads an alphanumeric + underscore name from the source. + * + * [_A-Za-z][_0-9A-Za-z]* + */ +function readName(source, start, line, col, prev): Token { + const body = source.body; + const bodyLength = body.length; + let position = start + 1; + let code = 0; + while ( + position !== bodyLength && + (code = charCodeAt.call(body, position)) !== null && + (code === 95 || // _ + (code >= 48 && code <= 57) || // 0-9 + (code >= 65 && code <= 90) || // A-Z + (code >= 97 && code <= 122)) // a-z + ) { + ++position; + } + return new Tok( + TokenKind.NAME, + start, + position, + line, + col, + prev, + slice.call(body, start, position), + ); +} diff --git a/node_modules/graphql/language/lexer.mjs b/node_modules/graphql/language/lexer.mjs new file mode 100644 index 0000000..31a438a --- /dev/null +++ b/node_modules/graphql/language/lexer.mjs @@ -0,0 +1,632 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { syntaxError } from '../error'; +import blockStringValue from './blockStringValue'; +/** + * Given a Source object, this returns a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ + +export function createLexer(source, options) { + var startOfFileToken = new Tok(TokenKind.SOF, 0, 0, 0, 0, null); + var lexer = { + source: source, + options: options, + lastToken: startOfFileToken, + token: startOfFileToken, + line: 1, + lineStart: 0, + advance: advanceLexer, + lookahead: lookahead + }; + return lexer; +} + +function advanceLexer() { + this.lastToken = this.token; + var token = this.token = this.lookahead(); + return token; +} + +function lookahead() { + var token = this.token; + + if (token.kind !== TokenKind.EOF) { + do { + // Note: next is only mutable during parsing, so we cast to allow this. + token = token.next || (token.next = readToken(this, token)); + } while (token.kind === TokenKind.COMMENT); + } + + return token; +} +/** + * The return type of createLexer. + */ + + +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +export var TokenKind = Object.freeze({ + SOF: '', + EOF: '', + BANG: '!', + DOLLAR: '$', + AMP: '&', + PAREN_L: '(', + PAREN_R: ')', + SPREAD: '...', + COLON: ':', + EQUALS: '=', + AT: '@', + BRACKET_L: '[', + BRACKET_R: ']', + BRACE_L: '{', + PIPE: '|', + BRACE_R: '}', + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment' +}); +/** + * The enum type representing the token kinds values. + */ + +/** + * A helper function to describe a token as a string for debugging + */ +export function getTokenDesc(token) { + var value = token.value; + return value ? "".concat(token.kind, " \"").concat(value, "\"") : token.kind; +} +var charCodeAt = String.prototype.charCodeAt; +var slice = String.prototype.slice; +/** + * Helper function for constructing the Token object. + */ + +function Tok(kind, start, end, line, column, prev, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; + this.value = value; + this.prev = prev; + this.next = null; +} // Print a simplified form when appearing in JSON/util.inspect. + + +Tok.prototype.toJSON = Tok.prototype.inspect = function toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column + }; +}; + +function printCharCode(code) { + return (// NaN/undefined represents access beyond the end of the file. + isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII. + code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form. + "\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"") + ); +} +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace and comments until it finds the next lexable + * token, then lexes punctuators immediately or calls the appropriate helper + * function for more complicated tokens. + */ + + +function readToken(lexer, prev) { + var source = lexer.source; + var body = source.body; + var bodyLength = body.length; + var pos = positionAfterWhitespace(body, prev.end, lexer); + var line = lexer.line; + var col = 1 + pos - lexer.lineStart; + + if (pos >= bodyLength) { + return new Tok(TokenKind.EOF, bodyLength, bodyLength, line, col, prev); + } + + var code = charCodeAt.call(body, pos); // SourceCharacter + + switch (code) { + // ! + case 33: + return new Tok(TokenKind.BANG, pos, pos + 1, line, col, prev); + // # + + case 35: + return readComment(source, pos, line, col, prev); + // $ + + case 36: + return new Tok(TokenKind.DOLLAR, pos, pos + 1, line, col, prev); + // & + + case 38: + return new Tok(TokenKind.AMP, pos, pos + 1, line, col, prev); + // ( + + case 40: + return new Tok(TokenKind.PAREN_L, pos, pos + 1, line, col, prev); + // ) + + case 41: + return new Tok(TokenKind.PAREN_R, pos, pos + 1, line, col, prev); + // . + + case 46: + if (charCodeAt.call(body, pos + 1) === 46 && charCodeAt.call(body, pos + 2) === 46) { + return new Tok(TokenKind.SPREAD, pos, pos + 3, line, col, prev); + } + + break; + // : + + case 58: + return new Tok(TokenKind.COLON, pos, pos + 1, line, col, prev); + // = + + case 61: + return new Tok(TokenKind.EQUALS, pos, pos + 1, line, col, prev); + // @ + + case 64: + return new Tok(TokenKind.AT, pos, pos + 1, line, col, prev); + // [ + + case 91: + return new Tok(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev); + // ] + + case 93: + return new Tok(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev); + // { + + case 123: + return new Tok(TokenKind.BRACE_L, pos, pos + 1, line, col, prev); + // | + + case 124: + return new Tok(TokenKind.PIPE, pos, pos + 1, line, col, prev); + // } + + case 125: + return new Tok(TokenKind.BRACE_R, pos, pos + 1, line, col, prev); + // A-Z _ a-z + + case 65: + case 66: + case 67: + case 68: + case 69: + case 70: + case 71: + case 72: + case 73: + case 74: + case 75: + case 76: + case 77: + case 78: + case 79: + case 80: + case 81: + case 82: + case 83: + case 84: + case 85: + case 86: + case 87: + case 88: + case 89: + case 90: + case 95: + case 97: + case 98: + case 99: + case 100: + case 101: + case 102: + case 103: + case 104: + case 105: + case 106: + case 107: + case 108: + case 109: + case 110: + case 111: + case 112: + case 113: + case 114: + case 115: + case 116: + case 117: + case 118: + case 119: + case 120: + case 121: + case 122: + return readName(source, pos, line, col, prev); + // - 0-9 + + case 45: + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + return readNumber(source, pos, code, line, col, prev); + // " + + case 34: + if (charCodeAt.call(body, pos + 1) === 34 && charCodeAt.call(body, pos + 2) === 34) { + return readBlockString(source, pos, line, col, prev); + } + + return readString(source, pos, line, col, prev); + } + + throw syntaxError(source, pos, unexpectedCharacterMessage(code)); +} +/** + * Report a message that an unexpected character was encountered. + */ + + +function unexpectedCharacterMessage(code) { + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + return "Cannot contain the invalid character ".concat(printCharCode(code), "."); + } + + if (code === 39) { + // ' + return "Unexpected single quote character ('), did you mean to use " + 'a double quote (")?'; + } + + return "Cannot parse the unexpected character ".concat(printCharCode(code), "."); +} +/** + * Reads from body starting at startPosition until it finds a non-whitespace + * or commented character, then returns the position of that character for + * lexing. + */ + + +function positionAfterWhitespace(body, startPosition, lexer) { + var bodyLength = body.length; + var position = startPosition; + + while (position < bodyLength) { + var code = charCodeAt.call(body, position); // tab | space | comma | BOM + + if (code === 9 || code === 32 || code === 44 || code === 0xfeff) { + ++position; + } else if (code === 10) { + // new line + ++position; + ++lexer.line; + lexer.lineStart = position; + } else if (code === 13) { + // carriage return + if (charCodeAt.call(body, position + 1) === 10) { + position += 2; + } else { + ++position; + } + + ++lexer.line; + lexer.lineStart = position; + } else { + break; + } + } + + return position; +} +/** + * Reads a comment token from the source file. + * + * #[\u0009\u0020-\uFFFF]* + */ + + +function readComment(source, start, line, col, prev) { + var body = source.body; + var code; + var position = start; + + do { + code = charCodeAt.call(body, ++position); + } while (code !== null && ( // SourceCharacter but not LineTerminator + code > 0x001f || code === 0x0009)); + + return new Tok(TokenKind.COMMENT, start, position, line, col, prev, slice.call(body, start + 1, position)); +} +/** + * Reads a number token from the source file, either a float + * or an int depending on whether a decimal point appears. + * + * Int: -?(0|[1-9][0-9]*) + * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? + */ + + +function readNumber(source, start, firstCode, line, col, prev) { + var body = source.body; + var code = firstCode; + var position = start; + var isFloat = false; + + if (code === 45) { + // - + code = charCodeAt.call(body, ++position); + } + + if (code === 48) { + // 0 + code = charCodeAt.call(body, ++position); + + if (code >= 48 && code <= 57) { + throw syntaxError(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), ".")); + } + } else { + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 46) { + // . + isFloat = true; + code = charCodeAt.call(body, ++position); + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 69 || code === 101) { + // E e + isFloat = true; + code = charCodeAt.call(body, ++position); + + if (code === 43 || code === 45) { + // + - + code = charCodeAt.call(body, ++position); + } + + position = readDigits(source, position, code); + } + + return new Tok(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, slice.call(body, start, position)); +} +/** + * Returns the new position in the source after reading digits. + */ + + +function readDigits(source, start, firstCode) { + var body = source.body; + var position = start; + var code = firstCode; + + if (code >= 48 && code <= 57) { + // 0 - 9 + do { + code = charCodeAt.call(body, ++position); + } while (code >= 48 && code <= 57); // 0 - 9 + + + return position; + } + + throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), ".")); +} +/** + * Reads a string token from the source file. + * + * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*" + */ + + +function readString(source, start, line, col, prev) { + var body = source.body; + var position = start + 1; + var chunkStart = position; + var code = 0; + var value = ''; + + while (position < body.length && (code = charCodeAt.call(body, position)) !== null && // not LineTerminator + code !== 0x000a && code !== 0x000d) { + // Closing Quote (") + if (code === 34) { + value += slice.call(body, chunkStart, position); + return new Tok(TokenKind.STRING, start, position + 1, line, col, prev, value); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009) { + throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } + + ++position; + + if (code === 92) { + // \ + value += slice.call(body, chunkStart, position - 1); + code = charCodeAt.call(body, position); + + switch (code) { + case 34: + value += '"'; + break; + + case 47: + value += '/'; + break; + + case 92: + value += '\\'; + break; + + case 98: + value += '\b'; + break; + + case 102: + value += '\f'; + break; + + case 110: + value += '\n'; + break; + + case 114: + value += '\r'; + break; + + case 116: + value += '\t'; + break; + + case 117: + // u + var charCode = uniCharCode(charCodeAt.call(body, position + 1), charCodeAt.call(body, position + 2), charCodeAt.call(body, position + 3), charCodeAt.call(body, position + 4)); + + if (charCode < 0) { + throw syntaxError(source, position, 'Invalid character escape sequence: ' + "\\u".concat(body.slice(position + 1, position + 5), ".")); + } + + value += String.fromCharCode(charCode); + position += 4; + break; + + default: + throw syntaxError(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), ".")); + } + + ++position; + chunkStart = position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} +/** + * Reads a block string token from the source file. + * + * """("?"?(\\"""|\\(?!=""")|[^"\\]))*""" + */ + + +function readBlockString(source, start, line, col, prev) { + var body = source.body; + var position = start + 3; + var chunkStart = position; + var code = 0; + var rawValue = ''; + + while (position < body.length && (code = charCodeAt.call(body, position)) !== null) { + // Closing Triple-Quote (""") + if (code === 34 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34) { + rawValue += slice.call(body, chunkStart, position); + return new Tok(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, blockStringValue(rawValue)); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } // Escape Triple-Quote (\""") + + + if (code === 92 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34 && charCodeAt.call(body, position + 3) === 34) { + rawValue += slice.call(body, chunkStart, position) + '"""'; + position += 4; + chunkStart = position; + } else { + ++position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} +/** + * Converts four hexadecimal chars to the integer that the + * string represents. For example, uniCharCode('0','0','0','f') + * will return 15, and uniCharCode('0','0','f','f') returns 255. + * + * Returns a negative number on error, if a char was invalid. + * + * This is implemented by noting that char2hex() returns -1 on error, + * which means the result of ORing the char2hex() will also be negative. + */ + + +function uniCharCode(a, b, c, d) { + return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d); +} +/** + * Converts a hex character to its integer value. + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 on error. + */ + + +function char2hex(a) { + return a >= 48 && a <= 57 ? a - 48 // 0-9 + : a >= 65 && a <= 70 ? a - 55 // A-F + : a >= 97 && a <= 102 ? a - 87 // a-f + : -1; +} +/** + * Reads an alphanumeric + underscore name from the source. + * + * [_A-Za-z][_0-9A-Za-z]* + */ + + +function readName(source, start, line, col, prev) { + var body = source.body; + var bodyLength = body.length; + var position = start + 1; + var code = 0; + + while (position !== bodyLength && (code = charCodeAt.call(body, position)) !== null && (code === 95 || // _ + code >= 48 && code <= 57 || // 0-9 + code >= 65 && code <= 90 || // A-Z + code >= 97 && code <= 122) // a-z + ) { + ++position; + } + + return new Tok(TokenKind.NAME, start, position, line, col, prev, slice.call(body, start, position)); +} \ No newline at end of file diff --git a/node_modules/graphql/language/location.js b/node_modules/graphql/language/location.js new file mode 100644 index 0000000..1257b2f --- /dev/null +++ b/node_modules/graphql/language/location.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getLocation = getLocation; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Represents a location in a Source. + */ + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +function getLocation(source, position) { + var lineRegexp = /\r\n|[\n\r]/g; + var line = 1; + var column = position + 1; + var match; + + while ((match = lineRegexp.exec(source.body)) && match.index < position) { + line += 1; + column = position + 1 - (match.index + match[0].length); + } + + return { + line: line, + column: column + }; +} \ No newline at end of file diff --git a/node_modules/graphql/language/location.js.flow b/node_modules/graphql/language/location.js.flow new file mode 100644 index 0000000..8029d5b --- /dev/null +++ b/node_modules/graphql/language/location.js.flow @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { Source } from './source'; + +/** + * Represents a location in a Source. + */ +export type SourceLocation = {| + +line: number, + +column: number, +|}; + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +export function getLocation(source: Source, position: number): SourceLocation { + const lineRegexp = /\r\n|[\n\r]/g; + let line = 1; + let column = position + 1; + let match; + while ((match = lineRegexp.exec(source.body)) && match.index < position) { + line += 1; + column = position + 1 - (match.index + match[0].length); + } + return { line, column }; +} diff --git a/node_modules/graphql/language/location.mjs b/node_modules/graphql/language/location.mjs new file mode 100644 index 0000000..023d5dc --- /dev/null +++ b/node_modules/graphql/language/location.mjs @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Represents a location in a Source. + */ + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +export function getLocation(source, position) { + var lineRegexp = /\r\n|[\n\r]/g; + var line = 1; + var column = position + 1; + var match; + + while ((match = lineRegexp.exec(source.body)) && match.index < position) { + line += 1; + column = position + 1 - (match.index + match[0].length); + } + + return { + line: line, + column: column + }; +} \ No newline at end of file diff --git a/node_modules/graphql/language/parser.js b/node_modules/graphql/language/parser.js new file mode 100644 index 0000000..9cda8d7 --- /dev/null +++ b/node_modules/graphql/language/parser.js @@ -0,0 +1,1527 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parse = parse; +exports.parseValue = parseValue; +exports.parseType = parseType; +exports.parseConstValue = parseConstValue; +exports.parseTypeReference = parseTypeReference; +exports.parseNamedType = parseNamedType; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _source = require("./source"); + +var _error = require("../error"); + +var _lexer = require("./lexer"); + +var _kinds = require("./kinds"); + +var _directiveLocation = require("./directiveLocation"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +function parse(source, options) { + var sourceObj = typeof source === 'string' ? new _source.Source(source) : source; + + if (!(sourceObj instanceof _source.Source)) { + throw new TypeError("Must provide Source. Received: ".concat((0, _inspect.default)(sourceObj))); + } + + var lexer = (0, _lexer.createLexer)(sourceObj, options || {}); + return parseDocument(lexer); +} +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ + + +function parseValue(source, options) { + var sourceObj = typeof source === 'string' ? new _source.Source(source) : source; + var lexer = (0, _lexer.createLexer)(sourceObj, options || {}); + expect(lexer, _lexer.TokenKind.SOF); + var value = parseValueLiteral(lexer, false); + expect(lexer, _lexer.TokenKind.EOF); + return value; +} +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ + + +function parseType(source, options) { + var sourceObj = typeof source === 'string' ? new _source.Source(source) : source; + var lexer = (0, _lexer.createLexer)(sourceObj, options || {}); + expect(lexer, _lexer.TokenKind.SOF); + var type = parseTypeReference(lexer); + expect(lexer, _lexer.TokenKind.EOF); + return type; +} +/** + * Converts a name lex token into a name parse node. + */ + + +function parseName(lexer) { + var token = expect(lexer, _lexer.TokenKind.NAME); + return { + kind: _kinds.Kind.NAME, + value: token.value, + loc: loc(lexer, token) + }; +} // Implements the parsing rules in the Document section. + +/** + * Document : Definition+ + */ + + +function parseDocument(lexer) { + var start = lexer.token; + return { + kind: _kinds.Kind.DOCUMENT, + definitions: many(lexer, _lexer.TokenKind.SOF, parseDefinition, _lexer.TokenKind.EOF), + loc: loc(lexer, start) + }; +} +/** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + */ + + +function parseDefinition(lexer) { + if (peek(lexer, _lexer.TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + case 'fragment': + return parseExecutableDefinition(lexer); + + case 'schema': + case 'scalar': + case 'type': + case 'interface': + case 'union': + case 'enum': + case 'input': + case 'directive': + return parseTypeSystemDefinition(lexer); + + case 'extend': + return parseTypeSystemExtension(lexer); + } + } else if (peek(lexer, _lexer.TokenKind.BRACE_L)) { + return parseExecutableDefinition(lexer); + } else if (peekDescription(lexer)) { + return parseTypeSystemDefinition(lexer); + } + + throw unexpected(lexer); +} +/** + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + */ + + +function parseExecutableDefinition(lexer) { + if (peek(lexer, _lexer.TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + return parseOperationDefinition(lexer); + + case 'fragment': + return parseFragmentDefinition(lexer); + } + } else if (peek(lexer, _lexer.TokenKind.BRACE_L)) { + return parseOperationDefinition(lexer); + } + + throw unexpected(lexer); +} // Implements the parsing rules in the Operations section. + +/** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ + + +function parseOperationDefinition(lexer) { + var start = lexer.token; + + if (peek(lexer, _lexer.TokenKind.BRACE_L)) { + return { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation: 'query', + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; + } + + var operation = parseOperationType(lexer); + var name; + + if (peek(lexer, _lexer.TokenKind.NAME)) { + name = parseName(lexer); + } + + return { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation: operation, + name: name, + variableDefinitions: parseVariableDefinitions(lexer), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * OperationType : one of query mutation subscription + */ + + +function parseOperationType(lexer) { + var operationToken = expect(lexer, _lexer.TokenKind.NAME); + + switch (operationToken.value) { + case 'query': + return 'query'; + + case 'mutation': + return 'mutation'; + + case 'subscription': + return 'subscription'; + } + + throw unexpected(lexer, operationToken); +} +/** + * VariableDefinitions : ( VariableDefinition+ ) + */ + + +function parseVariableDefinitions(lexer) { + return peek(lexer, _lexer.TokenKind.PAREN_L) ? many(lexer, _lexer.TokenKind.PAREN_L, parseVariableDefinition, _lexer.TokenKind.PAREN_R) : []; +} +/** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ + + +function parseVariableDefinition(lexer) { + var start = lexer.token; + + if (lexer.options.experimentalVariableDefinitionDirectives) { + return { + kind: _kinds.Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, _lexer.TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, _lexer.TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : undefined, + directives: parseDirectives(lexer, true), + loc: loc(lexer, start) + }; + } + + return { + kind: _kinds.Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, _lexer.TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, _lexer.TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : undefined, + loc: loc(lexer, start) + }; +} +/** + * Variable : $ Name + */ + + +function parseVariable(lexer) { + var start = lexer.token; + expect(lexer, _lexer.TokenKind.DOLLAR); + return { + kind: _kinds.Kind.VARIABLE, + name: parseName(lexer), + loc: loc(lexer, start) + }; +} +/** + * SelectionSet : { Selection+ } + */ + + +function parseSelectionSet(lexer) { + var start = lexer.token; + return { + kind: _kinds.Kind.SELECTION_SET, + selections: many(lexer, _lexer.TokenKind.BRACE_L, parseSelection, _lexer.TokenKind.BRACE_R), + loc: loc(lexer, start) + }; +} +/** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ + + +function parseSelection(lexer) { + return peek(lexer, _lexer.TokenKind.SPREAD) ? parseFragment(lexer) : parseField(lexer); +} +/** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ + + +function parseField(lexer) { + var start = lexer.token; + var nameOrAlias = parseName(lexer); + var alias; + var name; + + if (skip(lexer, _lexer.TokenKind.COLON)) { + alias = nameOrAlias; + name = parseName(lexer); + } else { + name = nameOrAlias; + } + + return { + kind: _kinds.Kind.FIELD, + alias: alias, + name: name, + arguments: parseArguments(lexer, false), + directives: parseDirectives(lexer, false), + selectionSet: peek(lexer, _lexer.TokenKind.BRACE_L) ? parseSelectionSet(lexer) : undefined, + loc: loc(lexer, start) + }; +} +/** + * Arguments[Const] : ( Argument[?Const]+ ) + */ + + +function parseArguments(lexer, isConst) { + var item = isConst ? parseConstArgument : parseArgument; + return peek(lexer, _lexer.TokenKind.PAREN_L) ? many(lexer, _lexer.TokenKind.PAREN_L, item, _lexer.TokenKind.PAREN_R) : []; +} +/** + * Argument[Const] : Name : Value[?Const] + */ + + +function parseArgument(lexer) { + var start = lexer.token; + return { + kind: _kinds.Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, _lexer.TokenKind.COLON), parseValueLiteral(lexer, false)), + loc: loc(lexer, start) + }; +} + +function parseConstArgument(lexer) { + var start = lexer.token; + return { + kind: _kinds.Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, _lexer.TokenKind.COLON), parseConstValue(lexer)), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Fragments section. + +/** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ + + +function parseFragment(lexer) { + var start = lexer.token; + expect(lexer, _lexer.TokenKind.SPREAD); + + if (peek(lexer, _lexer.TokenKind.NAME) && lexer.token.value !== 'on') { + return { + kind: _kinds.Kind.FRAGMENT_SPREAD, + name: parseFragmentName(lexer), + directives: parseDirectives(lexer, false), + loc: loc(lexer, start) + }; + } + + var typeCondition; + + if (lexer.token.value === 'on') { + lexer.advance(); + typeCondition = parseNamedType(lexer); + } + + return { + kind: _kinds.Kind.INLINE_FRAGMENT, + typeCondition: typeCondition, + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ + + +function parseFragmentDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'fragment'); // Experimental support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + + if (lexer.options.experimentalFragmentVariables) { + return { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + variableDefinitions: parseVariableDefinitions(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; + } + + return { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * FragmentName : Name but not `on` + */ + + +function parseFragmentName(lexer) { + if (lexer.token.value === 'on') { + throw unexpected(lexer); + } + + return parseName(lexer); +} // Implements the parsing rules in the Values section. + +/** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ + + +function parseValueLiteral(lexer, isConst) { + var token = lexer.token; + + switch (token.kind) { + case _lexer.TokenKind.BRACKET_L: + return parseList(lexer, isConst); + + case _lexer.TokenKind.BRACE_L: + return parseObject(lexer, isConst); + + case _lexer.TokenKind.INT: + lexer.advance(); + return { + kind: _kinds.Kind.INT, + value: token.value, + loc: loc(lexer, token) + }; + + case _lexer.TokenKind.FLOAT: + lexer.advance(); + return { + kind: _kinds.Kind.FLOAT, + value: token.value, + loc: loc(lexer, token) + }; + + case _lexer.TokenKind.STRING: + case _lexer.TokenKind.BLOCK_STRING: + return parseStringLiteral(lexer); + + case _lexer.TokenKind.NAME: + if (token.value === 'true' || token.value === 'false') { + lexer.advance(); + return { + kind: _kinds.Kind.BOOLEAN, + value: token.value === 'true', + loc: loc(lexer, token) + }; + } else if (token.value === 'null') { + lexer.advance(); + return { + kind: _kinds.Kind.NULL, + loc: loc(lexer, token) + }; + } + + lexer.advance(); + return { + kind: _kinds.Kind.ENUM, + value: token.value, + loc: loc(lexer, token) + }; + + case _lexer.TokenKind.DOLLAR: + if (!isConst) { + return parseVariable(lexer); + } + + break; + } + + throw unexpected(lexer); +} + +function parseStringLiteral(lexer) { + var token = lexer.token; + lexer.advance(); + return { + kind: _kinds.Kind.STRING, + value: token.value, + block: token.kind === _lexer.TokenKind.BLOCK_STRING, + loc: loc(lexer, token) + }; +} + +function parseConstValue(lexer) { + return parseValueLiteral(lexer, true); +} + +function parseValueValue(lexer) { + return parseValueLiteral(lexer, false); +} +/** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ + + +function parseList(lexer, isConst) { + var start = lexer.token; + var item = isConst ? parseConstValue : parseValueValue; + return { + kind: _kinds.Kind.LIST, + values: any(lexer, _lexer.TokenKind.BRACKET_L, item, _lexer.TokenKind.BRACKET_R), + loc: loc(lexer, start) + }; +} +/** + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + */ + + +function parseObject(lexer, isConst) { + var start = lexer.token; + expect(lexer, _lexer.TokenKind.BRACE_L); + var fields = []; + + while (!skip(lexer, _lexer.TokenKind.BRACE_R)) { + fields.push(parseObjectField(lexer, isConst)); + } + + return { + kind: _kinds.Kind.OBJECT, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * ObjectField[Const] : Name : Value[?Const] + */ + + +function parseObjectField(lexer, isConst) { + var start = lexer.token; + return { + kind: _kinds.Kind.OBJECT_FIELD, + name: parseName(lexer), + value: (expect(lexer, _lexer.TokenKind.COLON), parseValueLiteral(lexer, isConst)), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Directives section. + +/** + * Directives[Const] : Directive[?Const]+ + */ + + +function parseDirectives(lexer, isConst) { + var directives = []; + + while (peek(lexer, _lexer.TokenKind.AT)) { + directives.push(parseDirective(lexer, isConst)); + } + + return directives; +} +/** + * Directive[Const] : @ Name Arguments[?Const]? + */ + + +function parseDirective(lexer, isConst) { + var start = lexer.token; + expect(lexer, _lexer.TokenKind.AT); + return { + kind: _kinds.Kind.DIRECTIVE, + name: parseName(lexer), + arguments: parseArguments(lexer, isConst), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Types section. + +/** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + + +function parseTypeReference(lexer) { + var start = lexer.token; + var type; + + if (skip(lexer, _lexer.TokenKind.BRACKET_L)) { + type = parseTypeReference(lexer); + expect(lexer, _lexer.TokenKind.BRACKET_R); + type = { + kind: _kinds.Kind.LIST_TYPE, + type: type, + loc: loc(lexer, start) + }; + } else { + type = parseNamedType(lexer); + } + + if (skip(lexer, _lexer.TokenKind.BANG)) { + return { + kind: _kinds.Kind.NON_NULL_TYPE, + type: type, + loc: loc(lexer, start) + }; + } + + return type; +} +/** + * NamedType : Name + */ + + +function parseNamedType(lexer) { + var start = lexer.token; + return { + kind: _kinds.Kind.NAMED_TYPE, + name: parseName(lexer), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Type Definition section. + +/** + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ + + +function parseTypeSystemDefinition(lexer) { + // Many definitions begin with a description and require a lookahead. + var keywordToken = peekDescription(lexer) ? lexer.lookahead() : lexer.token; + + if (keywordToken.kind === _lexer.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaDefinition(lexer); + + case 'scalar': + return parseScalarTypeDefinition(lexer); + + case 'type': + return parseObjectTypeDefinition(lexer); + + case 'interface': + return parseInterfaceTypeDefinition(lexer); + + case 'union': + return parseUnionTypeDefinition(lexer); + + case 'enum': + return parseEnumTypeDefinition(lexer); + + case 'input': + return parseInputObjectTypeDefinition(lexer); + + case 'directive': + return parseDirectiveDefinition(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} + +function peekDescription(lexer) { + return peek(lexer, _lexer.TokenKind.STRING) || peek(lexer, _lexer.TokenKind.BLOCK_STRING); +} +/** + * Description : StringValue + */ + + +function parseDescription(lexer) { + if (peekDescription(lexer)) { + return parseStringLiteral(lexer); + } +} +/** + * SchemaDefinition : schema Directives[Const]? { OperationTypeDefinition+ } + */ + + +function parseSchemaDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'schema'); + var directives = parseDirectives(lexer, true); + var operationTypes = many(lexer, _lexer.TokenKind.BRACE_L, parseOperationTypeDefinition, _lexer.TokenKind.BRACE_R); + return { + kind: _kinds.Kind.SCHEMA_DEFINITION, + directives: directives, + operationTypes: operationTypes, + loc: loc(lexer, start) + }; +} +/** + * OperationTypeDefinition : OperationType : NamedType + */ + + +function parseOperationTypeDefinition(lexer) { + var start = lexer.token; + var operation = parseOperationType(lexer); + expect(lexer, _lexer.TokenKind.COLON); + var type = parseNamedType(lexer); + return { + kind: _kinds.Kind.OPERATION_TYPE_DEFINITION, + operation: operation, + type: type, + loc: loc(lexer, start) + }; +} +/** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ + + +function parseScalarTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'scalar'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: _kinds.Kind.SCALAR_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ + + +function parseObjectTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'type'); + var name = parseName(lexer); + var interfaces = parseImplementsInterfaces(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + return { + kind: _kinds.Kind.OBJECT_TYPE_DEFINITION, + description: description, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ + + +function parseImplementsInterfaces(lexer) { + var types = []; + + if (lexer.token.value === 'implements') { + lexer.advance(); // Optional leading ampersand + + skip(lexer, _lexer.TokenKind.AMP); + + do { + types.push(parseNamedType(lexer)); + } while (skip(lexer, _lexer.TokenKind.AMP) || // Legacy support for the SDL? + lexer.options.allowLegacySDLImplementsInterfaces && peek(lexer, _lexer.TokenKind.NAME)); + } + + return types; +} +/** + * FieldsDefinition : { FieldDefinition+ } + */ + + +function parseFieldsDefinition(lexer) { + // Legacy support for the SDL? + if (lexer.options.allowLegacySDLEmptyFields && peek(lexer, _lexer.TokenKind.BRACE_L) && lexer.lookahead().kind === _lexer.TokenKind.BRACE_R) { + lexer.advance(); + lexer.advance(); + return []; + } + + return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseFieldDefinition, _lexer.TokenKind.BRACE_R) : []; +} +/** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ + + +function parseFieldDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + var args = parseArgumentDefs(lexer); + expect(lexer, _lexer.TokenKind.COLON); + var type = parseTypeReference(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: _kinds.Kind.FIELD_DEFINITION, + description: description, + name: name, + arguments: args, + type: type, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ + + +function parseArgumentDefs(lexer) { + if (!peek(lexer, _lexer.TokenKind.PAREN_L)) { + return []; + } + + return many(lexer, _lexer.TokenKind.PAREN_L, parseInputValueDef, _lexer.TokenKind.PAREN_R); +} +/** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ + + +function parseInputValueDef(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + expect(lexer, _lexer.TokenKind.COLON); + var type = parseTypeReference(lexer); + var defaultValue; + + if (skip(lexer, _lexer.TokenKind.EQUALS)) { + defaultValue = parseConstValue(lexer); + } + + var directives = parseDirectives(lexer, true); + return { + kind: _kinds.Kind.INPUT_VALUE_DEFINITION, + description: description, + name: name, + type: type, + defaultValue: defaultValue, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ + + +function parseInterfaceTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'interface'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + return { + kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ + + +function parseUnionTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'union'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var types = parseUnionMemberTypes(lexer); + return { + kind: _kinds.Kind.UNION_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + types: types, + loc: loc(lexer, start) + }; +} +/** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ + + +function parseUnionMemberTypes(lexer) { + var types = []; + + if (skip(lexer, _lexer.TokenKind.EQUALS)) { + // Optional leading pipe + skip(lexer, _lexer.TokenKind.PIPE); + + do { + types.push(parseNamedType(lexer)); + } while (skip(lexer, _lexer.TokenKind.PIPE)); + } + + return types; +} +/** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ + + +function parseEnumTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'enum'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var values = parseEnumValuesDefinition(lexer); + return { + kind: _kinds.Kind.ENUM_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + values: values, + loc: loc(lexer, start) + }; +} +/** + * EnumValuesDefinition : { EnumValueDefinition+ } + */ + + +function parseEnumValuesDefinition(lexer) { + return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseEnumValueDefinition, _lexer.TokenKind.BRACE_R) : []; +} +/** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * EnumValue : Name + */ + + +function parseEnumValueDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: _kinds.Kind.ENUM_VALUE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ + + +function parseInputObjectTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'input'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseInputFieldsDefinition(lexer); + return { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * InputFieldsDefinition : { InputValueDefinition+ } + */ + + +function parseInputFieldsDefinition(lexer) { + return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseInputValueDef, _lexer.TokenKind.BRACE_R) : []; +} +/** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ + + +function parseTypeSystemExtension(lexer) { + var keywordToken = lexer.lookahead(); + + if (keywordToken.kind === _lexer.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaExtension(lexer); + + case 'scalar': + return parseScalarTypeExtension(lexer); + + case 'type': + return parseObjectTypeExtension(lexer); + + case 'interface': + return parseInterfaceTypeExtension(lexer); + + case 'union': + return parseUnionTypeExtension(lexer); + + case 'enum': + return parseEnumTypeExtension(lexer); + + case 'input': + return parseInputObjectTypeExtension(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} +/** + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + */ + + +function parseSchemaExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'schema'); + var directives = parseDirectives(lexer, true); + var operationTypes = peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseOperationTypeDefinition, _lexer.TokenKind.BRACE_R) : []; + + if (directives.length === 0 && operationTypes.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.SCHEMA_EXTENSION, + directives: directives, + operationTypes: operationTypes, + loc: loc(lexer, start) + }; +} +/** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ + + +function parseScalarTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'scalar'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + + if (directives.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.SCALAR_TYPE_EXTENSION, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ + + +function parseObjectTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'type'); + var name = parseName(lexer); + var interfaces = parseImplementsInterfaces(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.OBJECT_TYPE_EXTENSION, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * InterfaceTypeExtension : + * - extend interface Name Directives[Const]? FieldsDefinition + * - extend interface Name Directives[Const] + */ + + +function parseInterfaceTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'interface'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ + + +function parseUnionTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'union'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var types = parseUnionMemberTypes(lexer); + + if (directives.length === 0 && types.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.UNION_TYPE_EXTENSION, + name: name, + directives: directives, + types: types, + loc: loc(lexer, start) + }; +} +/** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ + + +function parseEnumTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'enum'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var values = parseEnumValuesDefinition(lexer); + + if (directives.length === 0 && values.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.ENUM_TYPE_EXTENSION, + name: name, + directives: directives, + values: values, + loc: loc(lexer, start) + }; +} +/** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ + + +function parseInputObjectTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'input'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseInputFieldsDefinition(lexer); + + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? on DirectiveLocations + */ + + +function parseDirectiveDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'directive'); + expect(lexer, _lexer.TokenKind.AT); + var name = parseName(lexer); + var args = parseArgumentDefs(lexer); + expectKeyword(lexer, 'on'); + var locations = parseDirectiveLocations(lexer); + return { + kind: _kinds.Kind.DIRECTIVE_DEFINITION, + description: description, + name: name, + arguments: args, + locations: locations, + loc: loc(lexer, start) + }; +} +/** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ + + +function parseDirectiveLocations(lexer) { + // Optional leading pipe + skip(lexer, _lexer.TokenKind.PIPE); + var locations = []; + + do { + locations.push(parseDirectiveLocation(lexer)); + } while (skip(lexer, _lexer.TokenKind.PIPE)); + + return locations; +} +/* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ + + +function parseDirectiveLocation(lexer) { + var start = lexer.token; + var name = parseName(lexer); + + if (_directiveLocation.DirectiveLocation.hasOwnProperty(name.value)) { + return name; + } + + throw unexpected(lexer, start); +} // Core parsing utility functions + +/** + * Returns a location object, used to identify the place in + * the source that created a given parsed object. + */ + + +function loc(lexer, startToken) { + if (!lexer.options.noLocation) { + return new Loc(startToken, lexer.lastToken, lexer.source); + } +} + +function Loc(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; +} // Print a simplified form when appearing in JSON/util.inspect. + + +Loc.prototype.toJSON = Loc.prototype.inspect = function toJSON() { + return { + start: this.start, + end: this.end + }; +}; +/** + * Determines if the next token is of a given kind + */ + + +function peek(lexer, kind) { + return lexer.token.kind === kind; +} +/** + * If the next token is of the given kind, return true after advancing + * the lexer. Otherwise, do not change the parser state and return false. + */ + + +function skip(lexer, kind) { + var match = lexer.token.kind === kind; + + if (match) { + lexer.advance(); + } + + return match; +} +/** + * If the next token is of the given kind, return that token after advancing + * the lexer. Otherwise, do not change the parser state and throw an error. + */ + + +function expect(lexer, kind) { + var token = lexer.token; + + if (token.kind === kind) { + lexer.advance(); + return token; + } + + throw (0, _error.syntaxError)(lexer.source, token.start, "Expected ".concat(kind, ", found ").concat((0, _lexer.getTokenDesc)(token))); +} +/** + * If the next token is a keyword with the given value, return that token after + * advancing the lexer. Otherwise, do not change the parser state and return + * false. + */ + + +function expectKeyword(lexer, value) { + var token = lexer.token; + + if (token.kind === _lexer.TokenKind.NAME && token.value === value) { + lexer.advance(); + return token; + } + + throw (0, _error.syntaxError)(lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat((0, _lexer.getTokenDesc)(token))); +} +/** + * Helper function for creating an error when an unexpected lexed token + * is encountered. + */ + + +function unexpected(lexer, atToken) { + var token = atToken || lexer.token; + return (0, _error.syntaxError)(lexer.source, token.start, "Unexpected ".concat((0, _lexer.getTokenDesc)(token))); +} +/** + * Returns a possibly empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ + + +function any(lexer, openKind, parseFn, closeKind) { + expect(lexer, openKind); + var nodes = []; + + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + + return nodes; +} +/** + * Returns a non-empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ + + +function many(lexer, openKind, parseFn, closeKind) { + expect(lexer, openKind); + var nodes = [parseFn(lexer)]; + + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + + return nodes; +} \ No newline at end of file diff --git a/node_modules/graphql/language/parser.js.flow b/node_modules/graphql/language/parser.js.flow new file mode 100644 index 0000000..37ba2e1 --- /dev/null +++ b/node_modules/graphql/language/parser.js.flow @@ -0,0 +1,1583 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../jsutils/inspect'; +import { Source } from './source'; +import { syntaxError } from '../error'; +import type { GraphQLError } from '../error'; +import { createLexer, TokenKind, getTokenDesc } from './lexer'; +import type { Lexer, TokenKindEnum } from './lexer'; +import type { + Location, + Token, + NameNode, + VariableNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + StringValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from './ast'; + +import { Kind } from './kinds'; +import { DirectiveLocation } from './directiveLocation'; + +/** + * Configuration options to control parser behavior + */ +export type ParseOptions = { + /** + * By default, the parser creates AST nodes that know the location + * in the source that they correspond to. This configuration flag + * disables that behavior for performance or testing. + */ + noLocation?: boolean, + + /** + * If enabled, the parser will parse empty fields sets in the Schema + * Definition Language. Otherwise, the parser will follow the current + * specification. + * + * This option is provided to ease adoption of the final SDL specification + * and will be removed in v16. + */ + allowLegacySDLEmptyFields?: boolean, + + /** + * If enabled, the parser will parse implemented interfaces with no `&` + * character between each interface. Otherwise, the parser will follow the + * current specification. + * + * This option is provided to ease adoption of the final SDL specification + * and will be removed in v16. + */ + allowLegacySDLImplementsInterfaces?: boolean, + + /** + * EXPERIMENTAL: + * + * If enabled, the parser will understand and parse variable definitions + * contained in a fragment definition. They'll be represented in the + * `variableDefinitions` field of the FragmentDefinitionNode. + * + * The syntax is identical to normal, query-defined variables. For example: + * + * fragment A($var: Boolean = false) on T { + * ... + * } + * + * Note: this feature is experimental and may change or be removed in the + * future. + */ + experimentalFragmentVariables?: boolean, + + /** + * EXPERIMENTAL: + * + * If enabled, the parser understands directives on variable definitions: + * + * query Foo($var: String = "abc" @variable_definition_directive) { + * ... + * } + */ + experimentalVariableDefinitionDirectives?: boolean, +}; + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +export function parse( + source: string | Source, + options?: ParseOptions, +): DocumentNode { + const sourceObj = typeof source === 'string' ? new Source(source) : source; + if (!(sourceObj instanceof Source)) { + throw new TypeError(`Must provide Source. Received: ${inspect(sourceObj)}`); + } + const lexer = createLexer(sourceObj, options || {}); + return parseDocument(lexer); +} + +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ +export function parseValue( + source: string | Source, + options?: ParseOptions, +): ValueNode { + const sourceObj = typeof source === 'string' ? new Source(source) : source; + const lexer = createLexer(sourceObj, options || {}); + expect(lexer, TokenKind.SOF); + const value = parseValueLiteral(lexer, false); + expect(lexer, TokenKind.EOF); + return value; +} + +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ +export function parseType( + source: string | Source, + options?: ParseOptions, +): TypeNode { + const sourceObj = typeof source === 'string' ? new Source(source) : source; + const lexer = createLexer(sourceObj, options || {}); + expect(lexer, TokenKind.SOF); + const type = parseTypeReference(lexer); + expect(lexer, TokenKind.EOF); + return type; +} + +/** + * Converts a name lex token into a name parse node. + */ +function parseName(lexer: Lexer<*>): NameNode { + const token = expect(lexer, TokenKind.NAME); + return { + kind: Kind.NAME, + value: ((token.value: any): string), + loc: loc(lexer, token), + }; +} + +// Implements the parsing rules in the Document section. + +/** + * Document : Definition+ + */ +function parseDocument(lexer: Lexer<*>): DocumentNode { + const start = lexer.token; + return { + kind: Kind.DOCUMENT, + definitions: many(lexer, TokenKind.SOF, parseDefinition, TokenKind.EOF), + loc: loc(lexer, start), + }; +} + +/** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + */ +function parseDefinition(lexer: Lexer<*>): DefinitionNode { + if (peek(lexer, TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + case 'fragment': + return parseExecutableDefinition(lexer); + case 'schema': + case 'scalar': + case 'type': + case 'interface': + case 'union': + case 'enum': + case 'input': + case 'directive': + return parseTypeSystemDefinition(lexer); + case 'extend': + return parseTypeSystemExtension(lexer); + } + } else if (peek(lexer, TokenKind.BRACE_L)) { + return parseExecutableDefinition(lexer); + } else if (peekDescription(lexer)) { + return parseTypeSystemDefinition(lexer); + } + + throw unexpected(lexer); +} + +/** + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + */ +function parseExecutableDefinition(lexer: Lexer<*>): ExecutableDefinitionNode { + if (peek(lexer, TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + return parseOperationDefinition(lexer); + + case 'fragment': + return parseFragmentDefinition(lexer); + } + } else if (peek(lexer, TokenKind.BRACE_L)) { + return parseOperationDefinition(lexer); + } + + throw unexpected(lexer); +} + +// Implements the parsing rules in the Operations section. + +/** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ +function parseOperationDefinition(lexer: Lexer<*>): OperationDefinitionNode { + const start = lexer.token; + if (peek(lexer, TokenKind.BRACE_L)) { + return { + kind: Kind.OPERATION_DEFINITION, + operation: 'query', + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start), + }; + } + const operation = parseOperationType(lexer); + let name; + if (peek(lexer, TokenKind.NAME)) { + name = parseName(lexer); + } + return { + kind: Kind.OPERATION_DEFINITION, + operation, + name, + variableDefinitions: parseVariableDefinitions(lexer), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start), + }; +} + +/** + * OperationType : one of query mutation subscription + */ +function parseOperationType(lexer: Lexer<*>): OperationTypeNode { + const operationToken = expect(lexer, TokenKind.NAME); + switch (operationToken.value) { + case 'query': + return 'query'; + case 'mutation': + return 'mutation'; + case 'subscription': + return 'subscription'; + } + + throw unexpected(lexer, operationToken); +} + +/** + * VariableDefinitions : ( VariableDefinition+ ) + */ +function parseVariableDefinitions( + lexer: Lexer<*>, +): Array { + return peek(lexer, TokenKind.PAREN_L) + ? many(lexer, TokenKind.PAREN_L, parseVariableDefinition, TokenKind.PAREN_R) + : []; +} + +/** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ +function parseVariableDefinition(lexer: Lexer<*>): VariableDefinitionNode { + const start = lexer.token; + if (lexer.options.experimentalVariableDefinitionDirectives) { + return { + kind: Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, TokenKind.EQUALS) + ? parseValueLiteral(lexer, true) + : undefined, + directives: parseDirectives(lexer, true), + loc: loc(lexer, start), + }; + } + + return { + kind: Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, TokenKind.EQUALS) + ? parseValueLiteral(lexer, true) + : undefined, + loc: loc(lexer, start), + }; +} + +/** + * Variable : $ Name + */ +function parseVariable(lexer: Lexer<*>): VariableNode { + const start = lexer.token; + expect(lexer, TokenKind.DOLLAR); + return { + kind: Kind.VARIABLE, + name: parseName(lexer), + loc: loc(lexer, start), + }; +} + +/** + * SelectionSet : { Selection+ } + */ +function parseSelectionSet(lexer: Lexer<*>): SelectionSetNode { + const start = lexer.token; + return { + kind: Kind.SELECTION_SET, + selections: many( + lexer, + TokenKind.BRACE_L, + parseSelection, + TokenKind.BRACE_R, + ), + loc: loc(lexer, start), + }; +} + +/** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ +function parseSelection(lexer: Lexer<*>): SelectionNode { + return peek(lexer, TokenKind.SPREAD) + ? parseFragment(lexer) + : parseField(lexer); +} + +/** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ +function parseField(lexer: Lexer<*>): FieldNode { + const start = lexer.token; + + const nameOrAlias = parseName(lexer); + let alias; + let name; + if (skip(lexer, TokenKind.COLON)) { + alias = nameOrAlias; + name = parseName(lexer); + } else { + name = nameOrAlias; + } + + return { + kind: Kind.FIELD, + alias, + name, + arguments: parseArguments(lexer, false), + directives: parseDirectives(lexer, false), + selectionSet: peek(lexer, TokenKind.BRACE_L) + ? parseSelectionSet(lexer) + : undefined, + loc: loc(lexer, start), + }; +} + +/** + * Arguments[Const] : ( Argument[?Const]+ ) + */ +function parseArguments( + lexer: Lexer<*>, + isConst: boolean, +): Array { + const item = isConst ? parseConstArgument : parseArgument; + return peek(lexer, TokenKind.PAREN_L) + ? many(lexer, TokenKind.PAREN_L, item, TokenKind.PAREN_R) + : []; +} + +/** + * Argument[Const] : Name : Value[?Const] + */ +function parseArgument(lexer: Lexer<*>): ArgumentNode { + const start = lexer.token; + return { + kind: Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseValueLiteral(lexer, false)), + loc: loc(lexer, start), + }; +} + +function parseConstArgument(lexer: Lexer<*>): ArgumentNode { + const start = lexer.token; + return { + kind: Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseConstValue(lexer)), + loc: loc(lexer, start), + }; +} + +// Implements the parsing rules in the Fragments section. + +/** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ +function parseFragment( + lexer: Lexer<*>, +): FragmentSpreadNode | InlineFragmentNode { + const start = lexer.token; + expect(lexer, TokenKind.SPREAD); + if (peek(lexer, TokenKind.NAME) && lexer.token.value !== 'on') { + return { + kind: Kind.FRAGMENT_SPREAD, + name: parseFragmentName(lexer), + directives: parseDirectives(lexer, false), + loc: loc(lexer, start), + }; + } + let typeCondition; + if (lexer.token.value === 'on') { + lexer.advance(); + typeCondition = parseNamedType(lexer); + } + return { + kind: Kind.INLINE_FRAGMENT, + typeCondition, + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start), + }; +} + +/** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ +function parseFragmentDefinition(lexer: Lexer<*>): FragmentDefinitionNode { + const start = lexer.token; + expectKeyword(lexer, 'fragment'); + // Experimental support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + if (lexer.options.experimentalFragmentVariables) { + return { + kind: Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + variableDefinitions: parseVariableDefinitions(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start), + }; + } + return { + kind: Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start), + }; +} + +/** + * FragmentName : Name but not `on` + */ +function parseFragmentName(lexer: Lexer<*>): NameNode { + if (lexer.token.value === 'on') { + throw unexpected(lexer); + } + return parseName(lexer); +} + +// Implements the parsing rules in the Values section. + +/** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ +function parseValueLiteral(lexer: Lexer<*>, isConst: boolean): ValueNode { + const token = lexer.token; + switch (token.kind) { + case TokenKind.BRACKET_L: + return parseList(lexer, isConst); + case TokenKind.BRACE_L: + return parseObject(lexer, isConst); + case TokenKind.INT: + lexer.advance(); + return { + kind: Kind.INT, + value: ((token.value: any): string), + loc: loc(lexer, token), + }; + case TokenKind.FLOAT: + lexer.advance(); + return { + kind: Kind.FLOAT, + value: ((token.value: any): string), + loc: loc(lexer, token), + }; + case TokenKind.STRING: + case TokenKind.BLOCK_STRING: + return parseStringLiteral(lexer); + case TokenKind.NAME: + if (token.value === 'true' || token.value === 'false') { + lexer.advance(); + return { + kind: Kind.BOOLEAN, + value: token.value === 'true', + loc: loc(lexer, token), + }; + } else if (token.value === 'null') { + lexer.advance(); + return { + kind: Kind.NULL, + loc: loc(lexer, token), + }; + } + lexer.advance(); + return { + kind: Kind.ENUM, + value: ((token.value: any): string), + loc: loc(lexer, token), + }; + case TokenKind.DOLLAR: + if (!isConst) { + return parseVariable(lexer); + } + break; + } + throw unexpected(lexer); +} + +function parseStringLiteral(lexer: Lexer<*>): StringValueNode { + const token = lexer.token; + lexer.advance(); + return { + kind: Kind.STRING, + value: ((token.value: any): string), + block: token.kind === TokenKind.BLOCK_STRING, + loc: loc(lexer, token), + }; +} + +export function parseConstValue(lexer: Lexer<*>): ValueNode { + return parseValueLiteral(lexer, true); +} + +function parseValueValue(lexer: Lexer<*>): ValueNode { + return parseValueLiteral(lexer, false); +} + +/** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ +function parseList(lexer: Lexer<*>, isConst: boolean): ListValueNode { + const start = lexer.token; + const item = isConst ? parseConstValue : parseValueValue; + return { + kind: Kind.LIST, + values: any(lexer, TokenKind.BRACKET_L, item, TokenKind.BRACKET_R), + loc: loc(lexer, start), + }; +} + +/** + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + */ +function parseObject(lexer: Lexer<*>, isConst: boolean): ObjectValueNode { + const start = lexer.token; + expect(lexer, TokenKind.BRACE_L); + const fields = []; + while (!skip(lexer, TokenKind.BRACE_R)) { + fields.push(parseObjectField(lexer, isConst)); + } + return { + kind: Kind.OBJECT, + fields, + loc: loc(lexer, start), + }; +} + +/** + * ObjectField[Const] : Name : Value[?Const] + */ +function parseObjectField(lexer: Lexer<*>, isConst: boolean): ObjectFieldNode { + const start = lexer.token; + return { + kind: Kind.OBJECT_FIELD, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseValueLiteral(lexer, isConst)), + loc: loc(lexer, start), + }; +} + +// Implements the parsing rules in the Directives section. + +/** + * Directives[Const] : Directive[?Const]+ + */ +function parseDirectives( + lexer: Lexer<*>, + isConst: boolean, +): Array { + const directives = []; + while (peek(lexer, TokenKind.AT)) { + directives.push(parseDirective(lexer, isConst)); + } + return directives; +} + +/** + * Directive[Const] : @ Name Arguments[?Const]? + */ +function parseDirective(lexer: Lexer<*>, isConst: boolean): DirectiveNode { + const start = lexer.token; + expect(lexer, TokenKind.AT); + return { + kind: Kind.DIRECTIVE, + name: parseName(lexer), + arguments: parseArguments(lexer, isConst), + loc: loc(lexer, start), + }; +} + +// Implements the parsing rules in the Types section. + +/** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ +export function parseTypeReference(lexer: Lexer<*>): TypeNode { + const start = lexer.token; + let type; + if (skip(lexer, TokenKind.BRACKET_L)) { + type = parseTypeReference(lexer); + expect(lexer, TokenKind.BRACKET_R); + type = ({ + kind: Kind.LIST_TYPE, + type, + loc: loc(lexer, start), + }: ListTypeNode); + } else { + type = parseNamedType(lexer); + } + if (skip(lexer, TokenKind.BANG)) { + return ({ + kind: Kind.NON_NULL_TYPE, + type, + loc: loc(lexer, start), + }: NonNullTypeNode); + } + return type; +} + +/** + * NamedType : Name + */ +export function parseNamedType(lexer: Lexer<*>): NamedTypeNode { + const start = lexer.token; + return { + kind: Kind.NAMED_TYPE, + name: parseName(lexer), + loc: loc(lexer, start), + }; +} + +// Implements the parsing rules in the Type Definition section. + +/** + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ +function parseTypeSystemDefinition(lexer: Lexer<*>): TypeSystemDefinitionNode { + // Many definitions begin with a description and require a lookahead. + const keywordToken = peekDescription(lexer) ? lexer.lookahead() : lexer.token; + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaDefinition(lexer); + case 'scalar': + return parseScalarTypeDefinition(lexer); + case 'type': + return parseObjectTypeDefinition(lexer); + case 'interface': + return parseInterfaceTypeDefinition(lexer); + case 'union': + return parseUnionTypeDefinition(lexer); + case 'enum': + return parseEnumTypeDefinition(lexer); + case 'input': + return parseInputObjectTypeDefinition(lexer); + case 'directive': + return parseDirectiveDefinition(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} + +function peekDescription(lexer: Lexer<*>): boolean { + return peek(lexer, TokenKind.STRING) || peek(lexer, TokenKind.BLOCK_STRING); +} + +/** + * Description : StringValue + */ +function parseDescription(lexer: Lexer<*>): void | StringValueNode { + if (peekDescription(lexer)) { + return parseStringLiteral(lexer); + } +} + +/** + * SchemaDefinition : schema Directives[Const]? { OperationTypeDefinition+ } + */ +function parseSchemaDefinition(lexer: Lexer<*>): SchemaDefinitionNode { + const start = lexer.token; + expectKeyword(lexer, 'schema'); + const directives = parseDirectives(lexer, true); + const operationTypes = many( + lexer, + TokenKind.BRACE_L, + parseOperationTypeDefinition, + TokenKind.BRACE_R, + ); + return { + kind: Kind.SCHEMA_DEFINITION, + directives, + operationTypes, + loc: loc(lexer, start), + }; +} + +/** + * OperationTypeDefinition : OperationType : NamedType + */ +function parseOperationTypeDefinition( + lexer: Lexer<*>, +): OperationTypeDefinitionNode { + const start = lexer.token; + const operation = parseOperationType(lexer); + expect(lexer, TokenKind.COLON); + const type = parseNamedType(lexer); + return { + kind: Kind.OPERATION_TYPE_DEFINITION, + operation, + type, + loc: loc(lexer, start), + }; +} + +/** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ +function parseScalarTypeDefinition(lexer: Lexer<*>): ScalarTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'scalar'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + return { + kind: Kind.SCALAR_TYPE_DEFINITION, + description, + name, + directives, + loc: loc(lexer, start), + }; +} + +/** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ +function parseObjectTypeDefinition(lexer: Lexer<*>): ObjectTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'type'); + const name = parseName(lexer); + const interfaces = parseImplementsInterfaces(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseFieldsDefinition(lexer); + return { + kind: Kind.OBJECT_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ +function parseImplementsInterfaces(lexer: Lexer<*>): Array { + const types = []; + if (lexer.token.value === 'implements') { + lexer.advance(); + // Optional leading ampersand + skip(lexer, TokenKind.AMP); + do { + types.push(parseNamedType(lexer)); + } while ( + skip(lexer, TokenKind.AMP) || + // Legacy support for the SDL? + (lexer.options.allowLegacySDLImplementsInterfaces && + peek(lexer, TokenKind.NAME)) + ); + } + return types; +} + +/** + * FieldsDefinition : { FieldDefinition+ } + */ +function parseFieldsDefinition(lexer: Lexer<*>): Array { + // Legacy support for the SDL? + if ( + lexer.options.allowLegacySDLEmptyFields && + peek(lexer, TokenKind.BRACE_L) && + lexer.lookahead().kind === TokenKind.BRACE_R + ) { + lexer.advance(); + lexer.advance(); + return []; + } + return peek(lexer, TokenKind.BRACE_L) + ? many(lexer, TokenKind.BRACE_L, parseFieldDefinition, TokenKind.BRACE_R) + : []; +} + +/** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ +function parseFieldDefinition(lexer: Lexer<*>): FieldDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + const name = parseName(lexer); + const args = parseArgumentDefs(lexer); + expect(lexer, TokenKind.COLON); + const type = parseTypeReference(lexer); + const directives = parseDirectives(lexer, true); + return { + kind: Kind.FIELD_DEFINITION, + description, + name, + arguments: args, + type, + directives, + loc: loc(lexer, start), + }; +} + +/** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ +function parseArgumentDefs(lexer: Lexer<*>): Array { + if (!peek(lexer, TokenKind.PAREN_L)) { + return []; + } + return many(lexer, TokenKind.PAREN_L, parseInputValueDef, TokenKind.PAREN_R); +} + +/** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ +function parseInputValueDef(lexer: Lexer<*>): InputValueDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + const name = parseName(lexer); + expect(lexer, TokenKind.COLON); + const type = parseTypeReference(lexer); + let defaultValue; + if (skip(lexer, TokenKind.EQUALS)) { + defaultValue = parseConstValue(lexer); + } + const directives = parseDirectives(lexer, true); + return { + kind: Kind.INPUT_VALUE_DEFINITION, + description, + name, + type, + defaultValue, + directives, + loc: loc(lexer, start), + }; +} + +/** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ +function parseInterfaceTypeDefinition( + lexer: Lexer<*>, +): InterfaceTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'interface'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseFieldsDefinition(lexer); + return { + kind: Kind.INTERFACE_TYPE_DEFINITION, + description, + name, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ +function parseUnionTypeDefinition(lexer: Lexer<*>): UnionTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'union'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const types = parseUnionMemberTypes(lexer); + return { + kind: Kind.UNION_TYPE_DEFINITION, + description, + name, + directives, + types, + loc: loc(lexer, start), + }; +} + +/** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ +function parseUnionMemberTypes(lexer: Lexer<*>): Array { + const types = []; + if (skip(lexer, TokenKind.EQUALS)) { + // Optional leading pipe + skip(lexer, TokenKind.PIPE); + do { + types.push(parseNamedType(lexer)); + } while (skip(lexer, TokenKind.PIPE)); + } + return types; +} + +/** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ +function parseEnumTypeDefinition(lexer: Lexer<*>): EnumTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'enum'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const values = parseEnumValuesDefinition(lexer); + return { + kind: Kind.ENUM_TYPE_DEFINITION, + description, + name, + directives, + values, + loc: loc(lexer, start), + }; +} + +/** + * EnumValuesDefinition : { EnumValueDefinition+ } + */ +function parseEnumValuesDefinition( + lexer: Lexer<*>, +): Array { + return peek(lexer, TokenKind.BRACE_L) + ? many( + lexer, + TokenKind.BRACE_L, + parseEnumValueDefinition, + TokenKind.BRACE_R, + ) + : []; +} + +/** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * EnumValue : Name + */ +function parseEnumValueDefinition(lexer: Lexer<*>): EnumValueDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + return { + kind: Kind.ENUM_VALUE_DEFINITION, + description, + name, + directives, + loc: loc(lexer, start), + }; +} + +/** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ +function parseInputObjectTypeDefinition( + lexer: Lexer<*>, +): InputObjectTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'input'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseInputFieldsDefinition(lexer); + return { + kind: Kind.INPUT_OBJECT_TYPE_DEFINITION, + description, + name, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * InputFieldsDefinition : { InputValueDefinition+ } + */ +function parseInputFieldsDefinition( + lexer: Lexer<*>, +): Array { + return peek(lexer, TokenKind.BRACE_L) + ? many(lexer, TokenKind.BRACE_L, parseInputValueDef, TokenKind.BRACE_R) + : []; +} + +/** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ +function parseTypeSystemExtension(lexer: Lexer<*>): TypeSystemExtensionNode { + const keywordToken = lexer.lookahead(); + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaExtension(lexer); + case 'scalar': + return parseScalarTypeExtension(lexer); + case 'type': + return parseObjectTypeExtension(lexer); + case 'interface': + return parseInterfaceTypeExtension(lexer); + case 'union': + return parseUnionTypeExtension(lexer); + case 'enum': + return parseEnumTypeExtension(lexer); + case 'input': + return parseInputObjectTypeExtension(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} + +/** + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + */ +function parseSchemaExtension(lexer: Lexer<*>): SchemaExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'schema'); + const directives = parseDirectives(lexer, true); + const operationTypes = peek(lexer, TokenKind.BRACE_L) + ? many( + lexer, + TokenKind.BRACE_L, + parseOperationTypeDefinition, + TokenKind.BRACE_R, + ) + : []; + if (directives.length === 0 && operationTypes.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.SCHEMA_EXTENSION, + directives, + operationTypes, + loc: loc(lexer, start), + }; +} + +/** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ +function parseScalarTypeExtension(lexer: Lexer<*>): ScalarTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'scalar'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + if (directives.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.SCALAR_TYPE_EXTENSION, + name, + directives, + loc: loc(lexer, start), + }; +} + +/** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ +function parseObjectTypeExtension(lexer: Lexer<*>): ObjectTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'type'); + const name = parseName(lexer); + const interfaces = parseImplementsInterfaces(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseFieldsDefinition(lexer); + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw unexpected(lexer); + } + return { + kind: Kind.OBJECT_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * InterfaceTypeExtension : + * - extend interface Name Directives[Const]? FieldsDefinition + * - extend interface Name Directives[Const] + */ +function parseInterfaceTypeExtension( + lexer: Lexer<*>, +): InterfaceTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'interface'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseFieldsDefinition(lexer); + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.INTERFACE_TYPE_EXTENSION, + name, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ +function parseUnionTypeExtension(lexer: Lexer<*>): UnionTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'union'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const types = parseUnionMemberTypes(lexer); + if (directives.length === 0 && types.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.UNION_TYPE_EXTENSION, + name, + directives, + types, + loc: loc(lexer, start), + }; +} + +/** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ +function parseEnumTypeExtension(lexer: Lexer<*>): EnumTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'enum'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const values = parseEnumValuesDefinition(lexer); + if (directives.length === 0 && values.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.ENUM_TYPE_EXTENSION, + name, + directives, + values, + loc: loc(lexer, start), + }; +} + +/** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ +function parseInputObjectTypeExtension( + lexer: Lexer<*>, +): InputObjectTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'input'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseInputFieldsDefinition(lexer); + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.INPUT_OBJECT_TYPE_EXTENSION, + name, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? on DirectiveLocations + */ +function parseDirectiveDefinition(lexer: Lexer<*>): DirectiveDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'directive'); + expect(lexer, TokenKind.AT); + const name = parseName(lexer); + const args = parseArgumentDefs(lexer); + expectKeyword(lexer, 'on'); + const locations = parseDirectiveLocations(lexer); + return { + kind: Kind.DIRECTIVE_DEFINITION, + description, + name, + arguments: args, + locations, + loc: loc(lexer, start), + }; +} + +/** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ +function parseDirectiveLocations(lexer: Lexer<*>): Array { + // Optional leading pipe + skip(lexer, TokenKind.PIPE); + const locations = []; + do { + locations.push(parseDirectiveLocation(lexer)); + } while (skip(lexer, TokenKind.PIPE)); + return locations; +} + +/* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ +function parseDirectiveLocation(lexer: Lexer<*>): NameNode { + const start = lexer.token; + const name = parseName(lexer); + if (DirectiveLocation.hasOwnProperty(name.value)) { + return name; + } + throw unexpected(lexer, start); +} + +// Core parsing utility functions + +/** + * Returns a location object, used to identify the place in + * the source that created a given parsed object. + */ +function loc(lexer: Lexer<*>, startToken: Token): Location | void { + if (!lexer.options.noLocation) { + return new Loc(startToken, lexer.lastToken, lexer.source); + } +} + +function Loc(startToken: Token, endToken: Token, source: Source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; +} + +// Print a simplified form when appearing in JSON/util.inspect. +Loc.prototype.toJSON = Loc.prototype.inspect = function toJSON() { + return { start: this.start, end: this.end }; +}; + +/** + * Determines if the next token is of a given kind + */ +function peek(lexer: Lexer<*>, kind: TokenKindEnum): boolean { + return lexer.token.kind === kind; +} + +/** + * If the next token is of the given kind, return true after advancing + * the lexer. Otherwise, do not change the parser state and return false. + */ +function skip(lexer: Lexer<*>, kind: TokenKindEnum): boolean { + const match = lexer.token.kind === kind; + if (match) { + lexer.advance(); + } + return match; +} + +/** + * If the next token is of the given kind, return that token after advancing + * the lexer. Otherwise, do not change the parser state and throw an error. + */ +function expect(lexer: Lexer<*>, kind: TokenKindEnum): Token { + const token = lexer.token; + if (token.kind === kind) { + lexer.advance(); + return token; + } + throw syntaxError( + lexer.source, + token.start, + `Expected ${kind}, found ${getTokenDesc(token)}`, + ); +} + +/** + * If the next token is a keyword with the given value, return that token after + * advancing the lexer. Otherwise, do not change the parser state and return + * false. + */ +function expectKeyword(lexer: Lexer<*>, value: string): Token { + const token = lexer.token; + if (token.kind === TokenKind.NAME && token.value === value) { + lexer.advance(); + return token; + } + throw syntaxError( + lexer.source, + token.start, + `Expected "${value}", found ${getTokenDesc(token)}`, + ); +} + +/** + * Helper function for creating an error when an unexpected lexed token + * is encountered. + */ +function unexpected(lexer: Lexer<*>, atToken?: ?Token): GraphQLError { + const token = atToken || lexer.token; + return syntaxError( + lexer.source, + token.start, + `Unexpected ${getTokenDesc(token)}`, + ); +} + +/** + * Returns a possibly empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ +function any( + lexer: Lexer<*>, + openKind: TokenKindEnum, + parseFn: (lexer: Lexer<*>) => T, + closeKind: TokenKindEnum, +): Array { + expect(lexer, openKind); + const nodes = []; + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + return nodes; +} + +/** + * Returns a non-empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ +function many( + lexer: Lexer<*>, + openKind: TokenKindEnum, + parseFn: (lexer: Lexer<*>) => T, + closeKind: TokenKindEnum, +): Array { + expect(lexer, openKind); + const nodes = [parseFn(lexer)]; + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + return nodes; +} diff --git a/node_modules/graphql/language/parser.mjs b/node_modules/graphql/language/parser.mjs new file mode 100644 index 0000000..ed07115 --- /dev/null +++ b/node_modules/graphql/language/parser.mjs @@ -0,0 +1,1505 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../jsutils/inspect'; +import { Source } from './source'; +import { syntaxError } from '../error'; +import { createLexer, TokenKind, getTokenDesc } from './lexer'; +import { Kind } from './kinds'; +import { DirectiveLocation } from './directiveLocation'; +/** + * Configuration options to control parser behavior + */ + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +export function parse(source, options) { + var sourceObj = typeof source === 'string' ? new Source(source) : source; + + if (!(sourceObj instanceof Source)) { + throw new TypeError("Must provide Source. Received: ".concat(inspect(sourceObj))); + } + + var lexer = createLexer(sourceObj, options || {}); + return parseDocument(lexer); +} +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ + +export function parseValue(source, options) { + var sourceObj = typeof source === 'string' ? new Source(source) : source; + var lexer = createLexer(sourceObj, options || {}); + expect(lexer, TokenKind.SOF); + var value = parseValueLiteral(lexer, false); + expect(lexer, TokenKind.EOF); + return value; +} +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ + +export function parseType(source, options) { + var sourceObj = typeof source === 'string' ? new Source(source) : source; + var lexer = createLexer(sourceObj, options || {}); + expect(lexer, TokenKind.SOF); + var type = parseTypeReference(lexer); + expect(lexer, TokenKind.EOF); + return type; +} +/** + * Converts a name lex token into a name parse node. + */ + +function parseName(lexer) { + var token = expect(lexer, TokenKind.NAME); + return { + kind: Kind.NAME, + value: token.value, + loc: loc(lexer, token) + }; +} // Implements the parsing rules in the Document section. + +/** + * Document : Definition+ + */ + + +function parseDocument(lexer) { + var start = lexer.token; + return { + kind: Kind.DOCUMENT, + definitions: many(lexer, TokenKind.SOF, parseDefinition, TokenKind.EOF), + loc: loc(lexer, start) + }; +} +/** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + */ + + +function parseDefinition(lexer) { + if (peek(lexer, TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + case 'fragment': + return parseExecutableDefinition(lexer); + + case 'schema': + case 'scalar': + case 'type': + case 'interface': + case 'union': + case 'enum': + case 'input': + case 'directive': + return parseTypeSystemDefinition(lexer); + + case 'extend': + return parseTypeSystemExtension(lexer); + } + } else if (peek(lexer, TokenKind.BRACE_L)) { + return parseExecutableDefinition(lexer); + } else if (peekDescription(lexer)) { + return parseTypeSystemDefinition(lexer); + } + + throw unexpected(lexer); +} +/** + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + */ + + +function parseExecutableDefinition(lexer) { + if (peek(lexer, TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + return parseOperationDefinition(lexer); + + case 'fragment': + return parseFragmentDefinition(lexer); + } + } else if (peek(lexer, TokenKind.BRACE_L)) { + return parseOperationDefinition(lexer); + } + + throw unexpected(lexer); +} // Implements the parsing rules in the Operations section. + +/** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ + + +function parseOperationDefinition(lexer) { + var start = lexer.token; + + if (peek(lexer, TokenKind.BRACE_L)) { + return { + kind: Kind.OPERATION_DEFINITION, + operation: 'query', + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; + } + + var operation = parseOperationType(lexer); + var name; + + if (peek(lexer, TokenKind.NAME)) { + name = parseName(lexer); + } + + return { + kind: Kind.OPERATION_DEFINITION, + operation: operation, + name: name, + variableDefinitions: parseVariableDefinitions(lexer), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * OperationType : one of query mutation subscription + */ + + +function parseOperationType(lexer) { + var operationToken = expect(lexer, TokenKind.NAME); + + switch (operationToken.value) { + case 'query': + return 'query'; + + case 'mutation': + return 'mutation'; + + case 'subscription': + return 'subscription'; + } + + throw unexpected(lexer, operationToken); +} +/** + * VariableDefinitions : ( VariableDefinition+ ) + */ + + +function parseVariableDefinitions(lexer) { + return peek(lexer, TokenKind.PAREN_L) ? many(lexer, TokenKind.PAREN_L, parseVariableDefinition, TokenKind.PAREN_R) : []; +} +/** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ + + +function parseVariableDefinition(lexer) { + var start = lexer.token; + + if (lexer.options.experimentalVariableDefinitionDirectives) { + return { + kind: Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : undefined, + directives: parseDirectives(lexer, true), + loc: loc(lexer, start) + }; + } + + return { + kind: Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : undefined, + loc: loc(lexer, start) + }; +} +/** + * Variable : $ Name + */ + + +function parseVariable(lexer) { + var start = lexer.token; + expect(lexer, TokenKind.DOLLAR); + return { + kind: Kind.VARIABLE, + name: parseName(lexer), + loc: loc(lexer, start) + }; +} +/** + * SelectionSet : { Selection+ } + */ + + +function parseSelectionSet(lexer) { + var start = lexer.token; + return { + kind: Kind.SELECTION_SET, + selections: many(lexer, TokenKind.BRACE_L, parseSelection, TokenKind.BRACE_R), + loc: loc(lexer, start) + }; +} +/** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ + + +function parseSelection(lexer) { + return peek(lexer, TokenKind.SPREAD) ? parseFragment(lexer) : parseField(lexer); +} +/** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ + + +function parseField(lexer) { + var start = lexer.token; + var nameOrAlias = parseName(lexer); + var alias; + var name; + + if (skip(lexer, TokenKind.COLON)) { + alias = nameOrAlias; + name = parseName(lexer); + } else { + name = nameOrAlias; + } + + return { + kind: Kind.FIELD, + alias: alias, + name: name, + arguments: parseArguments(lexer, false), + directives: parseDirectives(lexer, false), + selectionSet: peek(lexer, TokenKind.BRACE_L) ? parseSelectionSet(lexer) : undefined, + loc: loc(lexer, start) + }; +} +/** + * Arguments[Const] : ( Argument[?Const]+ ) + */ + + +function parseArguments(lexer, isConst) { + var item = isConst ? parseConstArgument : parseArgument; + return peek(lexer, TokenKind.PAREN_L) ? many(lexer, TokenKind.PAREN_L, item, TokenKind.PAREN_R) : []; +} +/** + * Argument[Const] : Name : Value[?Const] + */ + + +function parseArgument(lexer) { + var start = lexer.token; + return { + kind: Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseValueLiteral(lexer, false)), + loc: loc(lexer, start) + }; +} + +function parseConstArgument(lexer) { + var start = lexer.token; + return { + kind: Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseConstValue(lexer)), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Fragments section. + +/** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ + + +function parseFragment(lexer) { + var start = lexer.token; + expect(lexer, TokenKind.SPREAD); + + if (peek(lexer, TokenKind.NAME) && lexer.token.value !== 'on') { + return { + kind: Kind.FRAGMENT_SPREAD, + name: parseFragmentName(lexer), + directives: parseDirectives(lexer, false), + loc: loc(lexer, start) + }; + } + + var typeCondition; + + if (lexer.token.value === 'on') { + lexer.advance(); + typeCondition = parseNamedType(lexer); + } + + return { + kind: Kind.INLINE_FRAGMENT, + typeCondition: typeCondition, + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ + + +function parseFragmentDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'fragment'); // Experimental support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + + if (lexer.options.experimentalFragmentVariables) { + return { + kind: Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + variableDefinitions: parseVariableDefinitions(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; + } + + return { + kind: Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * FragmentName : Name but not `on` + */ + + +function parseFragmentName(lexer) { + if (lexer.token.value === 'on') { + throw unexpected(lexer); + } + + return parseName(lexer); +} // Implements the parsing rules in the Values section. + +/** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ + + +function parseValueLiteral(lexer, isConst) { + var token = lexer.token; + + switch (token.kind) { + case TokenKind.BRACKET_L: + return parseList(lexer, isConst); + + case TokenKind.BRACE_L: + return parseObject(lexer, isConst); + + case TokenKind.INT: + lexer.advance(); + return { + kind: Kind.INT, + value: token.value, + loc: loc(lexer, token) + }; + + case TokenKind.FLOAT: + lexer.advance(); + return { + kind: Kind.FLOAT, + value: token.value, + loc: loc(lexer, token) + }; + + case TokenKind.STRING: + case TokenKind.BLOCK_STRING: + return parseStringLiteral(lexer); + + case TokenKind.NAME: + if (token.value === 'true' || token.value === 'false') { + lexer.advance(); + return { + kind: Kind.BOOLEAN, + value: token.value === 'true', + loc: loc(lexer, token) + }; + } else if (token.value === 'null') { + lexer.advance(); + return { + kind: Kind.NULL, + loc: loc(lexer, token) + }; + } + + lexer.advance(); + return { + kind: Kind.ENUM, + value: token.value, + loc: loc(lexer, token) + }; + + case TokenKind.DOLLAR: + if (!isConst) { + return parseVariable(lexer); + } + + break; + } + + throw unexpected(lexer); +} + +function parseStringLiteral(lexer) { + var token = lexer.token; + lexer.advance(); + return { + kind: Kind.STRING, + value: token.value, + block: token.kind === TokenKind.BLOCK_STRING, + loc: loc(lexer, token) + }; +} + +export function parseConstValue(lexer) { + return parseValueLiteral(lexer, true); +} + +function parseValueValue(lexer) { + return parseValueLiteral(lexer, false); +} +/** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ + + +function parseList(lexer, isConst) { + var start = lexer.token; + var item = isConst ? parseConstValue : parseValueValue; + return { + kind: Kind.LIST, + values: any(lexer, TokenKind.BRACKET_L, item, TokenKind.BRACKET_R), + loc: loc(lexer, start) + }; +} +/** + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + */ + + +function parseObject(lexer, isConst) { + var start = lexer.token; + expect(lexer, TokenKind.BRACE_L); + var fields = []; + + while (!skip(lexer, TokenKind.BRACE_R)) { + fields.push(parseObjectField(lexer, isConst)); + } + + return { + kind: Kind.OBJECT, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * ObjectField[Const] : Name : Value[?Const] + */ + + +function parseObjectField(lexer, isConst) { + var start = lexer.token; + return { + kind: Kind.OBJECT_FIELD, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseValueLiteral(lexer, isConst)), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Directives section. + +/** + * Directives[Const] : Directive[?Const]+ + */ + + +function parseDirectives(lexer, isConst) { + var directives = []; + + while (peek(lexer, TokenKind.AT)) { + directives.push(parseDirective(lexer, isConst)); + } + + return directives; +} +/** + * Directive[Const] : @ Name Arguments[?Const]? + */ + + +function parseDirective(lexer, isConst) { + var start = lexer.token; + expect(lexer, TokenKind.AT); + return { + kind: Kind.DIRECTIVE, + name: parseName(lexer), + arguments: parseArguments(lexer, isConst), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Types section. + +/** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + + +export function parseTypeReference(lexer) { + var start = lexer.token; + var type; + + if (skip(lexer, TokenKind.BRACKET_L)) { + type = parseTypeReference(lexer); + expect(lexer, TokenKind.BRACKET_R); + type = { + kind: Kind.LIST_TYPE, + type: type, + loc: loc(lexer, start) + }; + } else { + type = parseNamedType(lexer); + } + + if (skip(lexer, TokenKind.BANG)) { + return { + kind: Kind.NON_NULL_TYPE, + type: type, + loc: loc(lexer, start) + }; + } + + return type; +} +/** + * NamedType : Name + */ + +export function parseNamedType(lexer) { + var start = lexer.token; + return { + kind: Kind.NAMED_TYPE, + name: parseName(lexer), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Type Definition section. + +/** + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ + +function parseTypeSystemDefinition(lexer) { + // Many definitions begin with a description and require a lookahead. + var keywordToken = peekDescription(lexer) ? lexer.lookahead() : lexer.token; + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaDefinition(lexer); + + case 'scalar': + return parseScalarTypeDefinition(lexer); + + case 'type': + return parseObjectTypeDefinition(lexer); + + case 'interface': + return parseInterfaceTypeDefinition(lexer); + + case 'union': + return parseUnionTypeDefinition(lexer); + + case 'enum': + return parseEnumTypeDefinition(lexer); + + case 'input': + return parseInputObjectTypeDefinition(lexer); + + case 'directive': + return parseDirectiveDefinition(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} + +function peekDescription(lexer) { + return peek(lexer, TokenKind.STRING) || peek(lexer, TokenKind.BLOCK_STRING); +} +/** + * Description : StringValue + */ + + +function parseDescription(lexer) { + if (peekDescription(lexer)) { + return parseStringLiteral(lexer); + } +} +/** + * SchemaDefinition : schema Directives[Const]? { OperationTypeDefinition+ } + */ + + +function parseSchemaDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'schema'); + var directives = parseDirectives(lexer, true); + var operationTypes = many(lexer, TokenKind.BRACE_L, parseOperationTypeDefinition, TokenKind.BRACE_R); + return { + kind: Kind.SCHEMA_DEFINITION, + directives: directives, + operationTypes: operationTypes, + loc: loc(lexer, start) + }; +} +/** + * OperationTypeDefinition : OperationType : NamedType + */ + + +function parseOperationTypeDefinition(lexer) { + var start = lexer.token; + var operation = parseOperationType(lexer); + expect(lexer, TokenKind.COLON); + var type = parseNamedType(lexer); + return { + kind: Kind.OPERATION_TYPE_DEFINITION, + operation: operation, + type: type, + loc: loc(lexer, start) + }; +} +/** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ + + +function parseScalarTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'scalar'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: Kind.SCALAR_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ + + +function parseObjectTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'type'); + var name = parseName(lexer); + var interfaces = parseImplementsInterfaces(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + return { + kind: Kind.OBJECT_TYPE_DEFINITION, + description: description, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ + + +function parseImplementsInterfaces(lexer) { + var types = []; + + if (lexer.token.value === 'implements') { + lexer.advance(); // Optional leading ampersand + + skip(lexer, TokenKind.AMP); + + do { + types.push(parseNamedType(lexer)); + } while (skip(lexer, TokenKind.AMP) || // Legacy support for the SDL? + lexer.options.allowLegacySDLImplementsInterfaces && peek(lexer, TokenKind.NAME)); + } + + return types; +} +/** + * FieldsDefinition : { FieldDefinition+ } + */ + + +function parseFieldsDefinition(lexer) { + // Legacy support for the SDL? + if (lexer.options.allowLegacySDLEmptyFields && peek(lexer, TokenKind.BRACE_L) && lexer.lookahead().kind === TokenKind.BRACE_R) { + lexer.advance(); + lexer.advance(); + return []; + } + + return peek(lexer, TokenKind.BRACE_L) ? many(lexer, TokenKind.BRACE_L, parseFieldDefinition, TokenKind.BRACE_R) : []; +} +/** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ + + +function parseFieldDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + var args = parseArgumentDefs(lexer); + expect(lexer, TokenKind.COLON); + var type = parseTypeReference(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: Kind.FIELD_DEFINITION, + description: description, + name: name, + arguments: args, + type: type, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ + + +function parseArgumentDefs(lexer) { + if (!peek(lexer, TokenKind.PAREN_L)) { + return []; + } + + return many(lexer, TokenKind.PAREN_L, parseInputValueDef, TokenKind.PAREN_R); +} +/** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ + + +function parseInputValueDef(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + expect(lexer, TokenKind.COLON); + var type = parseTypeReference(lexer); + var defaultValue; + + if (skip(lexer, TokenKind.EQUALS)) { + defaultValue = parseConstValue(lexer); + } + + var directives = parseDirectives(lexer, true); + return { + kind: Kind.INPUT_VALUE_DEFINITION, + description: description, + name: name, + type: type, + defaultValue: defaultValue, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ + + +function parseInterfaceTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'interface'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + return { + kind: Kind.INTERFACE_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ + + +function parseUnionTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'union'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var types = parseUnionMemberTypes(lexer); + return { + kind: Kind.UNION_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + types: types, + loc: loc(lexer, start) + }; +} +/** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ + + +function parseUnionMemberTypes(lexer) { + var types = []; + + if (skip(lexer, TokenKind.EQUALS)) { + // Optional leading pipe + skip(lexer, TokenKind.PIPE); + + do { + types.push(parseNamedType(lexer)); + } while (skip(lexer, TokenKind.PIPE)); + } + + return types; +} +/** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ + + +function parseEnumTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'enum'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var values = parseEnumValuesDefinition(lexer); + return { + kind: Kind.ENUM_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + values: values, + loc: loc(lexer, start) + }; +} +/** + * EnumValuesDefinition : { EnumValueDefinition+ } + */ + + +function parseEnumValuesDefinition(lexer) { + return peek(lexer, TokenKind.BRACE_L) ? many(lexer, TokenKind.BRACE_L, parseEnumValueDefinition, TokenKind.BRACE_R) : []; +} +/** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * EnumValue : Name + */ + + +function parseEnumValueDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: Kind.ENUM_VALUE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ + + +function parseInputObjectTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'input'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseInputFieldsDefinition(lexer); + return { + kind: Kind.INPUT_OBJECT_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * InputFieldsDefinition : { InputValueDefinition+ } + */ + + +function parseInputFieldsDefinition(lexer) { + return peek(lexer, TokenKind.BRACE_L) ? many(lexer, TokenKind.BRACE_L, parseInputValueDef, TokenKind.BRACE_R) : []; +} +/** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ + + +function parseTypeSystemExtension(lexer) { + var keywordToken = lexer.lookahead(); + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaExtension(lexer); + + case 'scalar': + return parseScalarTypeExtension(lexer); + + case 'type': + return parseObjectTypeExtension(lexer); + + case 'interface': + return parseInterfaceTypeExtension(lexer); + + case 'union': + return parseUnionTypeExtension(lexer); + + case 'enum': + return parseEnumTypeExtension(lexer); + + case 'input': + return parseInputObjectTypeExtension(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} +/** + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + */ + + +function parseSchemaExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'schema'); + var directives = parseDirectives(lexer, true); + var operationTypes = peek(lexer, TokenKind.BRACE_L) ? many(lexer, TokenKind.BRACE_L, parseOperationTypeDefinition, TokenKind.BRACE_R) : []; + + if (directives.length === 0 && operationTypes.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.SCHEMA_EXTENSION, + directives: directives, + operationTypes: operationTypes, + loc: loc(lexer, start) + }; +} +/** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ + + +function parseScalarTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'scalar'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + + if (directives.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.SCALAR_TYPE_EXTENSION, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ + + +function parseObjectTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'type'); + var name = parseName(lexer); + var interfaces = parseImplementsInterfaces(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.OBJECT_TYPE_EXTENSION, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * InterfaceTypeExtension : + * - extend interface Name Directives[Const]? FieldsDefinition + * - extend interface Name Directives[Const] + */ + + +function parseInterfaceTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'interface'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.INTERFACE_TYPE_EXTENSION, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ + + +function parseUnionTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'union'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var types = parseUnionMemberTypes(lexer); + + if (directives.length === 0 && types.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.UNION_TYPE_EXTENSION, + name: name, + directives: directives, + types: types, + loc: loc(lexer, start) + }; +} +/** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ + + +function parseEnumTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'enum'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var values = parseEnumValuesDefinition(lexer); + + if (directives.length === 0 && values.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.ENUM_TYPE_EXTENSION, + name: name, + directives: directives, + values: values, + loc: loc(lexer, start) + }; +} +/** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ + + +function parseInputObjectTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'input'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseInputFieldsDefinition(lexer); + + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.INPUT_OBJECT_TYPE_EXTENSION, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? on DirectiveLocations + */ + + +function parseDirectiveDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'directive'); + expect(lexer, TokenKind.AT); + var name = parseName(lexer); + var args = parseArgumentDefs(lexer); + expectKeyword(lexer, 'on'); + var locations = parseDirectiveLocations(lexer); + return { + kind: Kind.DIRECTIVE_DEFINITION, + description: description, + name: name, + arguments: args, + locations: locations, + loc: loc(lexer, start) + }; +} +/** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ + + +function parseDirectiveLocations(lexer) { + // Optional leading pipe + skip(lexer, TokenKind.PIPE); + var locations = []; + + do { + locations.push(parseDirectiveLocation(lexer)); + } while (skip(lexer, TokenKind.PIPE)); + + return locations; +} +/* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ + + +function parseDirectiveLocation(lexer) { + var start = lexer.token; + var name = parseName(lexer); + + if (DirectiveLocation.hasOwnProperty(name.value)) { + return name; + } + + throw unexpected(lexer, start); +} // Core parsing utility functions + +/** + * Returns a location object, used to identify the place in + * the source that created a given parsed object. + */ + + +function loc(lexer, startToken) { + if (!lexer.options.noLocation) { + return new Loc(startToken, lexer.lastToken, lexer.source); + } +} + +function Loc(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; +} // Print a simplified form when appearing in JSON/util.inspect. + + +Loc.prototype.toJSON = Loc.prototype.inspect = function toJSON() { + return { + start: this.start, + end: this.end + }; +}; +/** + * Determines if the next token is of a given kind + */ + + +function peek(lexer, kind) { + return lexer.token.kind === kind; +} +/** + * If the next token is of the given kind, return true after advancing + * the lexer. Otherwise, do not change the parser state and return false. + */ + + +function skip(lexer, kind) { + var match = lexer.token.kind === kind; + + if (match) { + lexer.advance(); + } + + return match; +} +/** + * If the next token is of the given kind, return that token after advancing + * the lexer. Otherwise, do not change the parser state and throw an error. + */ + + +function expect(lexer, kind) { + var token = lexer.token; + + if (token.kind === kind) { + lexer.advance(); + return token; + } + + throw syntaxError(lexer.source, token.start, "Expected ".concat(kind, ", found ").concat(getTokenDesc(token))); +} +/** + * If the next token is a keyword with the given value, return that token after + * advancing the lexer. Otherwise, do not change the parser state and return + * false. + */ + + +function expectKeyword(lexer, value) { + var token = lexer.token; + + if (token.kind === TokenKind.NAME && token.value === value) { + lexer.advance(); + return token; + } + + throw syntaxError(lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat(getTokenDesc(token))); +} +/** + * Helper function for creating an error when an unexpected lexed token + * is encountered. + */ + + +function unexpected(lexer, atToken) { + var token = atToken || lexer.token; + return syntaxError(lexer.source, token.start, "Unexpected ".concat(getTokenDesc(token))); +} +/** + * Returns a possibly empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ + + +function any(lexer, openKind, parseFn, closeKind) { + expect(lexer, openKind); + var nodes = []; + + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + + return nodes; +} +/** + * Returns a non-empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ + + +function many(lexer, openKind, parseFn, closeKind) { + expect(lexer, openKind); + var nodes = [parseFn(lexer)]; + + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + + return nodes; +} \ No newline at end of file diff --git a/node_modules/graphql/language/predicates.js b/node_modules/graphql/language/predicates.js new file mode 100644 index 0000000..f06ed8d --- /dev/null +++ b/node_modules/graphql/language/predicates.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isDefinitionNode = isDefinitionNode; +exports.isExecutableDefinitionNode = isExecutableDefinitionNode; +exports.isSelectionNode = isSelectionNode; +exports.isValueNode = isValueNode; +exports.isTypeNode = isTypeNode; +exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; +exports.isTypeDefinitionNode = isTypeDefinitionNode; +exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; +exports.isTypeExtensionNode = isTypeExtensionNode; + +var _kinds = require("./kinds"); + +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function isDefinitionNode(node) { + return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node); +} + +function isExecutableDefinitionNode(node) { + return node.kind === _kinds.Kind.OPERATION_DEFINITION || node.kind === _kinds.Kind.FRAGMENT_DEFINITION; +} + +function isSelectionNode(node) { + return node.kind === _kinds.Kind.FIELD || node.kind === _kinds.Kind.FRAGMENT_SPREAD || node.kind === _kinds.Kind.INLINE_FRAGMENT; +} + +function isValueNode(node) { + return node.kind === _kinds.Kind.VARIABLE || node.kind === _kinds.Kind.INT || node.kind === _kinds.Kind.FLOAT || node.kind === _kinds.Kind.STRING || node.kind === _kinds.Kind.BOOLEAN || node.kind === _kinds.Kind.NULL || node.kind === _kinds.Kind.ENUM || node.kind === _kinds.Kind.LIST || node.kind === _kinds.Kind.OBJECT; +} + +function isTypeNode(node) { + return node.kind === _kinds.Kind.NAMED_TYPE || node.kind === _kinds.Kind.LIST_TYPE || node.kind === _kinds.Kind.NON_NULL_TYPE; +} + +function isTypeSystemDefinitionNode(node) { + return node.kind === _kinds.Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === _kinds.Kind.DIRECTIVE_DEFINITION; +} + +function isTypeDefinitionNode(node) { + return node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION; +} + +function isTypeSystemExtensionNode(node) { + return node.kind === _kinds.Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); +} + +function isTypeExtensionNode(node) { + return node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; +} \ No newline at end of file diff --git a/node_modules/graphql/language/predicates.js.flow b/node_modules/graphql/language/predicates.js.flow new file mode 100644 index 0000000..bde7b3a --- /dev/null +++ b/node_modules/graphql/language/predicates.js.flow @@ -0,0 +1,90 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTNode } from './ast'; +import { Kind } from './kinds'; + +export function isDefinitionNode(node: ASTNode): boolean %checks { + return ( + isExecutableDefinitionNode(node) || + isTypeSystemDefinitionNode(node) || + isTypeSystemExtensionNode(node) + ); +} + +export function isExecutableDefinitionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.OPERATION_DEFINITION || + node.kind === Kind.FRAGMENT_DEFINITION + ); +} + +export function isSelectionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.FIELD || + node.kind === Kind.FRAGMENT_SPREAD || + node.kind === Kind.INLINE_FRAGMENT + ); +} + +export function isValueNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.VARIABLE || + node.kind === Kind.INT || + node.kind === Kind.FLOAT || + node.kind === Kind.STRING || + node.kind === Kind.BOOLEAN || + node.kind === Kind.NULL || + node.kind === Kind.ENUM || + node.kind === Kind.LIST || + node.kind === Kind.OBJECT + ); +} + +export function isTypeNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.NAMED_TYPE || + node.kind === Kind.LIST_TYPE || + node.kind === Kind.NON_NULL_TYPE + ); +} + +export function isTypeSystemDefinitionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.SCHEMA_DEFINITION || + isTypeDefinitionNode(node) || + node.kind === Kind.DIRECTIVE_DEFINITION + ); +} + +export function isTypeDefinitionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.SCALAR_TYPE_DEFINITION || + node.kind === Kind.OBJECT_TYPE_DEFINITION || + node.kind === Kind.INTERFACE_TYPE_DEFINITION || + node.kind === Kind.UNION_TYPE_DEFINITION || + node.kind === Kind.ENUM_TYPE_DEFINITION || + node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION + ); +} + +export function isTypeSystemExtensionNode(node: ASTNode): boolean %checks { + return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); +} + +export function isTypeExtensionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.SCALAR_TYPE_EXTENSION || + node.kind === Kind.OBJECT_TYPE_EXTENSION || + node.kind === Kind.INTERFACE_TYPE_EXTENSION || + node.kind === Kind.UNION_TYPE_EXTENSION || + node.kind === Kind.ENUM_TYPE_EXTENSION || + node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION + ); +} diff --git a/node_modules/graphql/language/predicates.mjs b/node_modules/graphql/language/predicates.mjs new file mode 100644 index 0000000..3d8af90 --- /dev/null +++ b/node_modules/graphql/language/predicates.mjs @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { Kind } from './kinds'; +export function isDefinitionNode(node) { + return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node); +} +export function isExecutableDefinitionNode(node) { + return node.kind === Kind.OPERATION_DEFINITION || node.kind === Kind.FRAGMENT_DEFINITION; +} +export function isSelectionNode(node) { + return node.kind === Kind.FIELD || node.kind === Kind.FRAGMENT_SPREAD || node.kind === Kind.INLINE_FRAGMENT; +} +export function isValueNode(node) { + return node.kind === Kind.VARIABLE || node.kind === Kind.INT || node.kind === Kind.FLOAT || node.kind === Kind.STRING || node.kind === Kind.BOOLEAN || node.kind === Kind.NULL || node.kind === Kind.ENUM || node.kind === Kind.LIST || node.kind === Kind.OBJECT; +} +export function isTypeNode(node) { + return node.kind === Kind.NAMED_TYPE || node.kind === Kind.LIST_TYPE || node.kind === Kind.NON_NULL_TYPE; +} +export function isTypeSystemDefinitionNode(node) { + return node.kind === Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === Kind.DIRECTIVE_DEFINITION; +} +export function isTypeDefinitionNode(node) { + return node.kind === Kind.SCALAR_TYPE_DEFINITION || node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.INTERFACE_TYPE_DEFINITION || node.kind === Kind.UNION_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION; +} +export function isTypeSystemExtensionNode(node) { + return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); +} +export function isTypeExtensionNode(node) { + return node.kind === Kind.SCALAR_TYPE_EXTENSION || node.kind === Kind.OBJECT_TYPE_EXTENSION || node.kind === Kind.INTERFACE_TYPE_EXTENSION || node.kind === Kind.UNION_TYPE_EXTENSION || node.kind === Kind.ENUM_TYPE_EXTENSION || node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION; +} \ No newline at end of file diff --git a/node_modules/graphql/language/printer.js b/node_modules/graphql/language/printer.js new file mode 100644 index 0000000..18e3340 --- /dev/null +++ b/node_modules/graphql/language/printer.js @@ -0,0 +1,319 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.print = print; + +var _visitor = require("./visitor"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ +function print(ast) { + return (0, _visitor.visit)(ast, { + leave: printDocASTReducer + }); +} + +var printDocASTReducer = { + Name: function Name(node) { + return node.value; + }, + Variable: function Variable(node) { + return '$' + node.name; + }, + // Document + Document: function Document(node) { + return join(node.definitions, '\n\n') + '\n'; + }, + OperationDefinition: function OperationDefinition(node) { + var op = node.operation; + var name = node.name; + var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + var directives = join(node.directives, ' '); + var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' '); + }, + VariableDefinition: function VariableDefinition(_ref) { + var variable = _ref.variable, + type = _ref.type, + defaultValue = _ref.defaultValue, + directives = _ref.directives; + return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')); + }, + SelectionSet: function SelectionSet(_ref2) { + var selections = _ref2.selections; + return block(selections); + }, + Field: function Field(_ref3) { + var alias = _ref3.alias, + name = _ref3.name, + args = _ref3.arguments, + directives = _ref3.directives, + selectionSet = _ref3.selectionSet; + return join([wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), join(directives, ' '), selectionSet], ' '); + }, + Argument: function Argument(_ref4) { + var name = _ref4.name, + value = _ref4.value; + return name + ': ' + value; + }, + // Fragments + FragmentSpread: function FragmentSpread(_ref5) { + var name = _ref5.name, + directives = _ref5.directives; + return '...' + name + wrap(' ', join(directives, ' ')); + }, + InlineFragment: function InlineFragment(_ref6) { + var typeCondition = _ref6.typeCondition, + directives = _ref6.directives, + selectionSet = _ref6.selectionSet; + return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' '); + }, + FragmentDefinition: function FragmentDefinition(_ref7) { + var name = _ref7.name, + typeCondition = _ref7.typeCondition, + variableDefinitions = _ref7.variableDefinitions, + directives = _ref7.directives, + selectionSet = _ref7.selectionSet; + return (// Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + "fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet + ); + }, + // Value + IntValue: function IntValue(_ref8) { + var value = _ref8.value; + return value; + }, + FloatValue: function FloatValue(_ref9) { + var value = _ref9.value; + return value; + }, + StringValue: function StringValue(_ref10, key) { + var value = _ref10.value, + isBlockString = _ref10.block; + return isBlockString ? printBlockString(value, key === 'description') : JSON.stringify(value); + }, + BooleanValue: function BooleanValue(_ref11) { + var value = _ref11.value; + return value ? 'true' : 'false'; + }, + NullValue: function NullValue() { + return 'null'; + }, + EnumValue: function EnumValue(_ref12) { + var value = _ref12.value; + return value; + }, + ListValue: function ListValue(_ref13) { + var values = _ref13.values; + return '[' + join(values, ', ') + ']'; + }, + ObjectValue: function ObjectValue(_ref14) { + var fields = _ref14.fields; + return '{' + join(fields, ', ') + '}'; + }, + ObjectField: function ObjectField(_ref15) { + var name = _ref15.name, + value = _ref15.value; + return name + ': ' + value; + }, + // Directive + Directive: function Directive(_ref16) { + var name = _ref16.name, + args = _ref16.arguments; + return '@' + name + wrap('(', join(args, ', '), ')'); + }, + // Type + NamedType: function NamedType(_ref17) { + var name = _ref17.name; + return name; + }, + ListType: function ListType(_ref18) { + var type = _ref18.type; + return '[' + type + ']'; + }, + NonNullType: function NonNullType(_ref19) { + var type = _ref19.type; + return type + '!'; + }, + // Type System Definitions + SchemaDefinition: function SchemaDefinition(_ref20) { + var directives = _ref20.directives, + operationTypes = _ref20.operationTypes; + return join(['schema', join(directives, ' '), block(operationTypes)], ' '); + }, + OperationTypeDefinition: function OperationTypeDefinition(_ref21) { + var operation = _ref21.operation, + type = _ref21.type; + return operation + ': ' + type; + }, + ScalarTypeDefinition: addDescription(function (_ref22) { + var name = _ref22.name, + directives = _ref22.directives; + return join(['scalar', name, join(directives, ' ')], ' '); + }), + ObjectTypeDefinition: addDescription(function (_ref23) { + var name = _ref23.name, + interfaces = _ref23.interfaces, + directives = _ref23.directives, + fields = _ref23.fields; + return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }), + FieldDefinition: addDescription(function (_ref24) { + var name = _ref24.name, + args = _ref24.arguments, + type = _ref24.type, + directives = _ref24.directives; + return name + (args.every(function (arg) { + return arg.indexOf('\n') === -1; + }) ? wrap('(', join(args, ', '), ')') : wrap('(\n', indent(join(args, '\n')), '\n)')) + ': ' + type + wrap(' ', join(directives, ' ')); + }), + InputValueDefinition: addDescription(function (_ref25) { + var name = _ref25.name, + type = _ref25.type, + defaultValue = _ref25.defaultValue, + directives = _ref25.directives; + return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' '); + }), + InterfaceTypeDefinition: addDescription(function (_ref26) { + var name = _ref26.name, + directives = _ref26.directives, + fields = _ref26.fields; + return join(['interface', name, join(directives, ' '), block(fields)], ' '); + }), + UnionTypeDefinition: addDescription(function (_ref27) { + var name = _ref27.name, + directives = _ref27.directives, + types = _ref27.types; + return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }), + EnumTypeDefinition: addDescription(function (_ref28) { + var name = _ref28.name, + directives = _ref28.directives, + values = _ref28.values; + return join(['enum', name, join(directives, ' '), block(values)], ' '); + }), + EnumValueDefinition: addDescription(function (_ref29) { + var name = _ref29.name, + directives = _ref29.directives; + return join([name, join(directives, ' ')], ' '); + }), + InputObjectTypeDefinition: addDescription(function (_ref30) { + var name = _ref30.name, + directives = _ref30.directives, + fields = _ref30.fields; + return join(['input', name, join(directives, ' '), block(fields)], ' '); + }), + DirectiveDefinition: addDescription(function (_ref31) { + var name = _ref31.name, + args = _ref31.arguments, + locations = _ref31.locations; + return 'directive @' + name + (args.every(function (arg) { + return arg.indexOf('\n') === -1; + }) ? wrap('(', join(args, ', '), ')') : wrap('(\n', indent(join(args, '\n')), '\n)')) + ' on ' + join(locations, ' | '); + }), + SchemaExtension: function SchemaExtension(_ref32) { + var directives = _ref32.directives, + operationTypes = _ref32.operationTypes; + return join(['extend schema', join(directives, ' '), block(operationTypes)], ' '); + }, + ScalarTypeExtension: function ScalarTypeExtension(_ref33) { + var name = _ref33.name, + directives = _ref33.directives; + return join(['extend scalar', name, join(directives, ' ')], ' '); + }, + ObjectTypeExtension: function ObjectTypeExtension(_ref34) { + var name = _ref34.name, + interfaces = _ref34.interfaces, + directives = _ref34.directives, + fields = _ref34.fields; + return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }, + InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) { + var name = _ref35.name, + directives = _ref35.directives, + fields = _ref35.fields; + return join(['extend interface', name, join(directives, ' '), block(fields)], ' '); + }, + UnionTypeExtension: function UnionTypeExtension(_ref36) { + var name = _ref36.name, + directives = _ref36.directives, + types = _ref36.types; + return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }, + EnumTypeExtension: function EnumTypeExtension(_ref37) { + var name = _ref37.name, + directives = _ref37.directives, + values = _ref37.values; + return join(['extend enum', name, join(directives, ' '), block(values)], ' '); + }, + InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) { + var name = _ref38.name, + directives = _ref38.directives, + fields = _ref38.fields; + return join(['extend input', name, join(directives, ' '), block(fields)], ' '); + } +}; + +function addDescription(cb) { + return function (node) { + return join([node.description, cb(node)], '\n'); + }; +} +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ + + +function join(maybeArray, separator) { + return maybeArray ? maybeArray.filter(function (x) { + return x; + }).join(separator || '') : ''; +} +/** + * Given array, print each item on its own line, wrapped in an + * indented "{ }" block. + */ + + +function block(array) { + return array && array.length !== 0 ? '{\n' + indent(join(array, '\n')) + '\n}' : ''; +} +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise + * print an empty string. + */ + + +function wrap(start, maybeString, end) { + return maybeString ? start + maybeString + (end || '') : ''; +} + +function indent(maybeString) { + return maybeString && ' ' + maybeString.replace(/\n/g, '\n '); +} +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + */ + + +function printBlockString(value, isDescription) { + var escaped = value.replace(/"""/g, '\\"""'); + return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1 ? "\"\"\"".concat(escaped.replace(/"$/, '"\n'), "\"\"\"") : "\"\"\"\n".concat(isDescription ? escaped : indent(escaped), "\n\"\"\""); +} \ No newline at end of file diff --git a/node_modules/graphql/language/printer.js.flow b/node_modules/graphql/language/printer.js.flow new file mode 100644 index 0000000..5254f46 --- /dev/null +++ b/node_modules/graphql/language/printer.js.flow @@ -0,0 +1,275 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { visit } from './visitor'; + +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ +export function print(ast) { + return visit(ast, { leave: printDocASTReducer }); +} + +const printDocASTReducer = { + Name: node => node.value, + Variable: node => '$' + node.name, + + // Document + + Document: node => join(node.definitions, '\n\n') + '\n', + + OperationDefinition(node) { + const op = node.operation; + const name = node.name; + const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + const directives = join(node.directives, ' '); + const selectionSet = node.selectionSet; + // Anonymous queries with no directives or variable definitions can use + // the query short form. + return !name && !directives && !varDefs && op === 'query' + ? selectionSet + : join([op, join([name, varDefs]), directives, selectionSet], ' '); + }, + + VariableDefinition: ({ variable, type, defaultValue, directives }) => + variable + + ': ' + + type + + wrap(' = ', defaultValue) + + wrap(' ', join(directives, ' ')), + SelectionSet: ({ selections }) => block(selections), + + Field: ({ alias, name, arguments: args, directives, selectionSet }) => + join( + [ + wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), + join(directives, ' '), + selectionSet, + ], + ' ', + ), + + Argument: ({ name, value }) => name + ': ' + value, + + // Fragments + + FragmentSpread: ({ name, directives }) => + '...' + name + wrap(' ', join(directives, ' ')), + + InlineFragment: ({ typeCondition, directives, selectionSet }) => + join( + ['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], + ' ', + ), + + FragmentDefinition: ({ + name, + typeCondition, + variableDefinitions, + directives, + selectionSet, + }) => + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` + + `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` + + selectionSet, + + // Value + + IntValue: ({ value }) => value, + FloatValue: ({ value }) => value, + StringValue: ({ value, block: isBlockString }, key) => + isBlockString + ? printBlockString(value, key === 'description') + : JSON.stringify(value), + BooleanValue: ({ value }) => (value ? 'true' : 'false'), + NullValue: () => 'null', + EnumValue: ({ value }) => value, + ListValue: ({ values }) => '[' + join(values, ', ') + ']', + ObjectValue: ({ fields }) => '{' + join(fields, ', ') + '}', + ObjectField: ({ name, value }) => name + ': ' + value, + + // Directive + + Directive: ({ name, arguments: args }) => + '@' + name + wrap('(', join(args, ', '), ')'), + + // Type + + NamedType: ({ name }) => name, + ListType: ({ type }) => '[' + type + ']', + NonNullType: ({ type }) => type + '!', + + // Type System Definitions + + SchemaDefinition: ({ directives, operationTypes }) => + join(['schema', join(directives, ' '), block(operationTypes)], ' '), + + OperationTypeDefinition: ({ operation, type }) => operation + ': ' + type, + + ScalarTypeDefinition: addDescription(({ name, directives }) => + join(['scalar', name, join(directives, ' ')], ' '), + ), + + ObjectTypeDefinition: addDescription( + ({ name, interfaces, directives, fields }) => + join( + [ + 'type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + ), + + FieldDefinition: addDescription( + ({ name, arguments: args, type, directives }) => + name + + (args.every(arg => arg.indexOf('\n') === -1) + ? wrap('(', join(args, ', '), ')') + : wrap('(\n', indent(join(args, '\n')), '\n)')) + + ': ' + + type + + wrap(' ', join(directives, ' ')), + ), + + InputValueDefinition: addDescription( + ({ name, type, defaultValue, directives }) => + join( + [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], + ' ', + ), + ), + + InterfaceTypeDefinition: addDescription(({ name, directives, fields }) => + join(['interface', name, join(directives, ' '), block(fields)], ' '), + ), + + UnionTypeDefinition: addDescription(({ name, directives, types }) => + join( + [ + 'union', + name, + join(directives, ' '), + types && types.length !== 0 ? '= ' + join(types, ' | ') : '', + ], + ' ', + ), + ), + + EnumTypeDefinition: addDescription(({ name, directives, values }) => + join(['enum', name, join(directives, ' '), block(values)], ' '), + ), + + EnumValueDefinition: addDescription(({ name, directives }) => + join([name, join(directives, ' ')], ' '), + ), + + InputObjectTypeDefinition: addDescription(({ name, directives, fields }) => + join(['input', name, join(directives, ' '), block(fields)], ' '), + ), + + DirectiveDefinition: addDescription( + ({ name, arguments: args, locations }) => + 'directive @' + + name + + (args.every(arg => arg.indexOf('\n') === -1) + ? wrap('(', join(args, ', '), ')') + : wrap('(\n', indent(join(args, '\n')), '\n)')) + + ' on ' + + join(locations, ' | '), + ), + + SchemaExtension: ({ directives, operationTypes }) => + join(['extend schema', join(directives, ' '), block(operationTypes)], ' '), + + ScalarTypeExtension: ({ name, directives }) => + join(['extend scalar', name, join(directives, ' ')], ' '), + + ObjectTypeExtension: ({ name, interfaces, directives, fields }) => + join( + [ + 'extend type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + + InterfaceTypeExtension: ({ name, directives, fields }) => + join(['extend interface', name, join(directives, ' '), block(fields)], ' '), + + UnionTypeExtension: ({ name, directives, types }) => + join( + [ + 'extend union', + name, + join(directives, ' '), + types && types.length !== 0 ? '= ' + join(types, ' | ') : '', + ], + ' ', + ), + + EnumTypeExtension: ({ name, directives, values }) => + join(['extend enum', name, join(directives, ' '), block(values)], ' '), + + InputObjectTypeExtension: ({ name, directives, fields }) => + join(['extend input', name, join(directives, ' '), block(fields)], ' '), +}; + +function addDescription(cb) { + return node => join([node.description, cb(node)], '\n'); +} + +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ +function join(maybeArray, separator) { + return maybeArray ? maybeArray.filter(x => x).join(separator || '') : ''; +} + +/** + * Given array, print each item on its own line, wrapped in an + * indented "{ }" block. + */ +function block(array) { + return array && array.length !== 0 + ? '{\n' + indent(join(array, '\n')) + '\n}' + : ''; +} + +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise + * print an empty string. + */ +function wrap(start, maybeString, end) { + return maybeString ? start + maybeString + (end || '') : ''; +} + +function indent(maybeString) { + return maybeString && ' ' + maybeString.replace(/\n/g, '\n '); +} + +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + */ +function printBlockString(value, isDescription) { + const escaped = value.replace(/"""/g, '\\"""'); + return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1 + ? `"""${escaped.replace(/"$/, '"\n')}"""` + : `"""\n${isDescription ? escaped : indent(escaped)}\n"""`; +} diff --git a/node_modules/graphql/language/printer.mjs b/node_modules/graphql/language/printer.mjs new file mode 100644 index 0000000..b6d56f1 --- /dev/null +++ b/node_modules/graphql/language/printer.mjs @@ -0,0 +1,310 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { visit } from './visitor'; +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ + +export function print(ast) { + return visit(ast, { + leave: printDocASTReducer + }); +} +var printDocASTReducer = { + Name: function Name(node) { + return node.value; + }, + Variable: function Variable(node) { + return '$' + node.name; + }, + // Document + Document: function Document(node) { + return join(node.definitions, '\n\n') + '\n'; + }, + OperationDefinition: function OperationDefinition(node) { + var op = node.operation; + var name = node.name; + var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + var directives = join(node.directives, ' '); + var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' '); + }, + VariableDefinition: function VariableDefinition(_ref) { + var variable = _ref.variable, + type = _ref.type, + defaultValue = _ref.defaultValue, + directives = _ref.directives; + return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')); + }, + SelectionSet: function SelectionSet(_ref2) { + var selections = _ref2.selections; + return block(selections); + }, + Field: function Field(_ref3) { + var alias = _ref3.alias, + name = _ref3.name, + args = _ref3.arguments, + directives = _ref3.directives, + selectionSet = _ref3.selectionSet; + return join([wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), join(directives, ' '), selectionSet], ' '); + }, + Argument: function Argument(_ref4) { + var name = _ref4.name, + value = _ref4.value; + return name + ': ' + value; + }, + // Fragments + FragmentSpread: function FragmentSpread(_ref5) { + var name = _ref5.name, + directives = _ref5.directives; + return '...' + name + wrap(' ', join(directives, ' ')); + }, + InlineFragment: function InlineFragment(_ref6) { + var typeCondition = _ref6.typeCondition, + directives = _ref6.directives, + selectionSet = _ref6.selectionSet; + return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' '); + }, + FragmentDefinition: function FragmentDefinition(_ref7) { + var name = _ref7.name, + typeCondition = _ref7.typeCondition, + variableDefinitions = _ref7.variableDefinitions, + directives = _ref7.directives, + selectionSet = _ref7.selectionSet; + return (// Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + "fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet + ); + }, + // Value + IntValue: function IntValue(_ref8) { + var value = _ref8.value; + return value; + }, + FloatValue: function FloatValue(_ref9) { + var value = _ref9.value; + return value; + }, + StringValue: function StringValue(_ref10, key) { + var value = _ref10.value, + isBlockString = _ref10.block; + return isBlockString ? printBlockString(value, key === 'description') : JSON.stringify(value); + }, + BooleanValue: function BooleanValue(_ref11) { + var value = _ref11.value; + return value ? 'true' : 'false'; + }, + NullValue: function NullValue() { + return 'null'; + }, + EnumValue: function EnumValue(_ref12) { + var value = _ref12.value; + return value; + }, + ListValue: function ListValue(_ref13) { + var values = _ref13.values; + return '[' + join(values, ', ') + ']'; + }, + ObjectValue: function ObjectValue(_ref14) { + var fields = _ref14.fields; + return '{' + join(fields, ', ') + '}'; + }, + ObjectField: function ObjectField(_ref15) { + var name = _ref15.name, + value = _ref15.value; + return name + ': ' + value; + }, + // Directive + Directive: function Directive(_ref16) { + var name = _ref16.name, + args = _ref16.arguments; + return '@' + name + wrap('(', join(args, ', '), ')'); + }, + // Type + NamedType: function NamedType(_ref17) { + var name = _ref17.name; + return name; + }, + ListType: function ListType(_ref18) { + var type = _ref18.type; + return '[' + type + ']'; + }, + NonNullType: function NonNullType(_ref19) { + var type = _ref19.type; + return type + '!'; + }, + // Type System Definitions + SchemaDefinition: function SchemaDefinition(_ref20) { + var directives = _ref20.directives, + operationTypes = _ref20.operationTypes; + return join(['schema', join(directives, ' '), block(operationTypes)], ' '); + }, + OperationTypeDefinition: function OperationTypeDefinition(_ref21) { + var operation = _ref21.operation, + type = _ref21.type; + return operation + ': ' + type; + }, + ScalarTypeDefinition: addDescription(function (_ref22) { + var name = _ref22.name, + directives = _ref22.directives; + return join(['scalar', name, join(directives, ' ')], ' '); + }), + ObjectTypeDefinition: addDescription(function (_ref23) { + var name = _ref23.name, + interfaces = _ref23.interfaces, + directives = _ref23.directives, + fields = _ref23.fields; + return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }), + FieldDefinition: addDescription(function (_ref24) { + var name = _ref24.name, + args = _ref24.arguments, + type = _ref24.type, + directives = _ref24.directives; + return name + (args.every(function (arg) { + return arg.indexOf('\n') === -1; + }) ? wrap('(', join(args, ', '), ')') : wrap('(\n', indent(join(args, '\n')), '\n)')) + ': ' + type + wrap(' ', join(directives, ' ')); + }), + InputValueDefinition: addDescription(function (_ref25) { + var name = _ref25.name, + type = _ref25.type, + defaultValue = _ref25.defaultValue, + directives = _ref25.directives; + return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' '); + }), + InterfaceTypeDefinition: addDescription(function (_ref26) { + var name = _ref26.name, + directives = _ref26.directives, + fields = _ref26.fields; + return join(['interface', name, join(directives, ' '), block(fields)], ' '); + }), + UnionTypeDefinition: addDescription(function (_ref27) { + var name = _ref27.name, + directives = _ref27.directives, + types = _ref27.types; + return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }), + EnumTypeDefinition: addDescription(function (_ref28) { + var name = _ref28.name, + directives = _ref28.directives, + values = _ref28.values; + return join(['enum', name, join(directives, ' '), block(values)], ' '); + }), + EnumValueDefinition: addDescription(function (_ref29) { + var name = _ref29.name, + directives = _ref29.directives; + return join([name, join(directives, ' ')], ' '); + }), + InputObjectTypeDefinition: addDescription(function (_ref30) { + var name = _ref30.name, + directives = _ref30.directives, + fields = _ref30.fields; + return join(['input', name, join(directives, ' '), block(fields)], ' '); + }), + DirectiveDefinition: addDescription(function (_ref31) { + var name = _ref31.name, + args = _ref31.arguments, + locations = _ref31.locations; + return 'directive @' + name + (args.every(function (arg) { + return arg.indexOf('\n') === -1; + }) ? wrap('(', join(args, ', '), ')') : wrap('(\n', indent(join(args, '\n')), '\n)')) + ' on ' + join(locations, ' | '); + }), + SchemaExtension: function SchemaExtension(_ref32) { + var directives = _ref32.directives, + operationTypes = _ref32.operationTypes; + return join(['extend schema', join(directives, ' '), block(operationTypes)], ' '); + }, + ScalarTypeExtension: function ScalarTypeExtension(_ref33) { + var name = _ref33.name, + directives = _ref33.directives; + return join(['extend scalar', name, join(directives, ' ')], ' '); + }, + ObjectTypeExtension: function ObjectTypeExtension(_ref34) { + var name = _ref34.name, + interfaces = _ref34.interfaces, + directives = _ref34.directives, + fields = _ref34.fields; + return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }, + InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) { + var name = _ref35.name, + directives = _ref35.directives, + fields = _ref35.fields; + return join(['extend interface', name, join(directives, ' '), block(fields)], ' '); + }, + UnionTypeExtension: function UnionTypeExtension(_ref36) { + var name = _ref36.name, + directives = _ref36.directives, + types = _ref36.types; + return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }, + EnumTypeExtension: function EnumTypeExtension(_ref37) { + var name = _ref37.name, + directives = _ref37.directives, + values = _ref37.values; + return join(['extend enum', name, join(directives, ' '), block(values)], ' '); + }, + InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) { + var name = _ref38.name, + directives = _ref38.directives, + fields = _ref38.fields; + return join(['extend input', name, join(directives, ' '), block(fields)], ' '); + } +}; + +function addDescription(cb) { + return function (node) { + return join([node.description, cb(node)], '\n'); + }; +} +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ + + +function join(maybeArray, separator) { + return maybeArray ? maybeArray.filter(function (x) { + return x; + }).join(separator || '') : ''; +} +/** + * Given array, print each item on its own line, wrapped in an + * indented "{ }" block. + */ + + +function block(array) { + return array && array.length !== 0 ? '{\n' + indent(join(array, '\n')) + '\n}' : ''; +} +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise + * print an empty string. + */ + + +function wrap(start, maybeString, end) { + return maybeString ? start + maybeString + (end || '') : ''; +} + +function indent(maybeString) { + return maybeString && ' ' + maybeString.replace(/\n/g, '\n '); +} +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + */ + + +function printBlockString(value, isDescription) { + var escaped = value.replace(/"""/g, '\\"""'); + return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1 ? "\"\"\"".concat(escaped.replace(/"$/, '"\n'), "\"\"\"") : "\"\"\"\n".concat(isDescription ? escaped : indent(escaped), "\n\"\"\""); +} \ No newline at end of file diff --git a/node_modules/graphql/language/source.js b/node_modules/graphql/language/source.js new file mode 100644 index 0000000..388bc90 --- /dev/null +++ b/node_modules/graphql/language/source.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Source = void 0; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * A representation of source input to GraphQL. + * `name` and `locationOffset` are optional. They are useful for clients who + * store GraphQL documents in source files; for example, if the GraphQL input + * starts at line 40 in a file named Foo.graphql, it might be useful for name to + * be "Foo.graphql" and location to be `{ line: 40, column: 0 }`. + * line and column in locationOffset are 1-indexed + */ +var Source = function Source(body, name, locationOffset) { + _defineProperty(this, "body", void 0); + + _defineProperty(this, "name", void 0); + + _defineProperty(this, "locationOffset", void 0); + + this.body = body; + this.name = name || 'GraphQL request'; + this.locationOffset = locationOffset || { + line: 1, + column: 1 + }; + !(this.locationOffset.line > 0) ? (0, _invariant.default)(0, 'line in locationOffset is 1-indexed and must be positive') : void 0; + !(this.locationOffset.column > 0) ? (0, _invariant.default)(0, 'column in locationOffset is 1-indexed and must be positive') : void 0; +}; // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.Source = Source; +(0, _defineToStringTag.default)(Source); \ No newline at end of file diff --git a/node_modules/graphql/language/source.js.flow b/node_modules/graphql/language/source.js.flow new file mode 100644 index 0000000..94a875f --- /dev/null +++ b/node_modules/graphql/language/source.js.flow @@ -0,0 +1,47 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import defineToStringTag from '../jsutils/defineToStringTag'; + +type Location = {| + line: number, + column: number, +|}; + +/** + * A representation of source input to GraphQL. + * `name` and `locationOffset` are optional. They are useful for clients who + * store GraphQL documents in source files; for example, if the GraphQL input + * starts at line 40 in a file named Foo.graphql, it might be useful for name to + * be "Foo.graphql" and location to be `{ line: 40, column: 0 }`. + * line and column in locationOffset are 1-indexed + */ +export class Source { + body: string; + name: string; + locationOffset: Location; + + constructor(body: string, name?: string, locationOffset?: Location): void { + this.body = body; + this.name = name || 'GraphQL request'; + this.locationOffset = locationOffset || { line: 1, column: 1 }; + invariant( + this.locationOffset.line > 0, + 'line in locationOffset is 1-indexed and must be positive', + ); + invariant( + this.locationOffset.column > 0, + 'column in locationOffset is 1-indexed and must be positive', + ); + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(Source); diff --git a/node_modules/graphql/language/source.mjs b/node_modules/graphql/language/source.mjs new file mode 100644 index 0000000..fd1425e --- /dev/null +++ b/node_modules/graphql/language/source.mjs @@ -0,0 +1,39 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; +import defineToStringTag from '../jsutils/defineToStringTag'; + +/** + * A representation of source input to GraphQL. + * `name` and `locationOffset` are optional. They are useful for clients who + * store GraphQL documents in source files; for example, if the GraphQL input + * starts at line 40 in a file named Foo.graphql, it might be useful for name to + * be "Foo.graphql" and location to be `{ line: 40, column: 0 }`. + * line and column in locationOffset are 1-indexed + */ +export var Source = function Source(body, name, locationOffset) { + _defineProperty(this, "body", void 0); + + _defineProperty(this, "name", void 0); + + _defineProperty(this, "locationOffset", void 0); + + this.body = body; + this.name = name || 'GraphQL request'; + this.locationOffset = locationOffset || { + line: 1, + column: 1 + }; + !(this.locationOffset.line > 0) ? invariant(0, 'line in locationOffset is 1-indexed and must be positive') : void 0; + !(this.locationOffset.column > 0) ? invariant(0, 'column in locationOffset is 1-indexed and must be positive') : void 0; +}; // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(Source); \ No newline at end of file diff --git a/node_modules/graphql/language/visitor.js b/node_modules/graphql/language/visitor.js new file mode 100644 index 0000000..3da1fb6 --- /dev/null +++ b/node_modules/graphql/language/visitor.js @@ -0,0 +1,450 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.visit = visit; +exports.visitInParallel = visitInParallel; +exports.visitWithTypeInfo = visitWithTypeInfo; +exports.getVisitFn = getVisitFn; +exports.BREAK = exports.QueryDocumentKeys = void 0; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var QueryDocumentKeys = { + Name: [], + Document: ['definitions'], + OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + Directive: ['name', 'arguments'], + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + SchemaDefinition: ['directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], + InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + SchemaExtension: ['directives', 'operationTypes'], + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'] +}; +exports.QueryDocumentKeys = QueryDocumentKeys; +var BREAK = {}; +/** + * visit() will walk through an AST using a depth first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to four permutations of + * visitor API: + * + * 1) Named visitors triggered when entering a node a specific kind. + * + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * + * 2) Named visitors that trigger upon entering and leaving a node of + * a specific kind. + * + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * + * 4) Parallel visitors for entering and leaving nodes of a specific kind. + * + * visit(ast, { + * enter: { + * Kind(node) { + * // enter the "Kind" node + * } + * }, + * leave: { + * Kind(node) { + * // leave the "Kind" node + * } + * } + * }) + */ + +exports.BREAK = BREAK; + +function visit(root, visitor) { + var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys; + + /* eslint-disable no-undef-init */ + var stack = undefined; + var inArray = Array.isArray(root); + var keys = [root]; + var index = -1; + var edits = []; + var node = undefined; + var key = undefined; + var parent = undefined; + var path = []; + var ancestors = []; + var newRoot = root; + /* eslint-enable no-undef-init */ + + do { + index++; + var isLeaving = index === keys.length; + var isEdited = isLeaving && edits.length !== 0; + + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + + if (isEdited) { + if (inArray) { + node = node.slice(); + } else { + var clone = {}; + + for (var k in node) { + if (node.hasOwnProperty(k)) { + clone[k] = node[k]; + } + } + + node = clone; + } + + var editOffset = 0; + + for (var ii = 0; ii < edits.length; ii++) { + var editKey = edits[ii][0]; + var editValue = edits[ii][1]; + + if (inArray) { + editKey -= editOffset; + } + + if (inArray && editValue === null) { + node.splice(editKey, 1); + editOffset++; + } else { + node[editKey] = editValue; + } + } + } + + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else { + key = parent ? inArray ? index : keys[index] : undefined; + node = parent ? parent[key] : newRoot; + + if (node === null || node === undefined) { + continue; + } + + if (parent) { + path.push(key); + } + } + + var result = void 0; + + if (!Array.isArray(node)) { + if (!isNode(node)) { + throw new Error('Invalid AST Node: ' + (0, _inspect.default)(node)); + } + + var visitFn = getVisitFn(visitor, node.kind, isLeaving); + + if (visitFn) { + result = visitFn.call(visitor, node, key, parent, path, ancestors); + + if (result === BREAK) { + break; + } + + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + + if (!isLeaving) { + if (isNode(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + } + + if (result === undefined && isEdited) { + edits.push([key, node]); + } + + if (isLeaving) { + path.pop(); + } else { + stack = { + inArray: inArray, + index: index, + keys: keys, + edits: edits, + prev: stack + }; + inArray = Array.isArray(node); + keys = inArray ? node : visitorKeys[node.kind] || []; + index = -1; + edits = []; + + if (parent) { + ancestors.push(parent); + } + + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + newRoot = edits[edits.length - 1][1]; + } + + return newRoot; +} + +function isNode(maybeNode) { + return Boolean(maybeNode && typeof maybeNode.kind === 'string'); +} +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ + + +function visitInParallel(visitors) { + var skipping = new Array(visitors.length); + return { + enter: function enter(node) { + for (var i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + } + }, + leave: function leave(node) { + for (var i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + true); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + } + }; +} +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ + + +function visitWithTypeInfo(typeInfo, visitor) { + return { + enter: function enter(node) { + typeInfo.enter(node); + var fn = getVisitFn(visitor, node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitor, arguments); + + if (result !== undefined) { + typeInfo.leave(node); + + if (isNode(result)) { + typeInfo.enter(result); + } + } + + return result; + } + }, + leave: function leave(node) { + var fn = getVisitFn(visitor, node.kind, + /* isLeaving */ + true); + var result; + + if (fn) { + result = fn.apply(visitor, arguments); + } + + typeInfo.leave(node); + return result; + } + }; +} +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + */ + + +function getVisitFn(visitor, kind, isLeaving) { + var kindVisitor = visitor[kind]; + + if (kindVisitor) { + if (!isLeaving && typeof kindVisitor === 'function') { + // { Kind() {} } + return kindVisitor; + } + + var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter; + + if (typeof kindSpecificVisitor === 'function') { + // { Kind: { enter() {}, leave() {} } } + return kindSpecificVisitor; + } + } else { + var specificVisitor = isLeaving ? visitor.leave : visitor.enter; + + if (specificVisitor) { + if (typeof specificVisitor === 'function') { + // { enter() {}, leave() {} } + return specificVisitor; + } + + var specificKindVisitor = specificVisitor[kind]; + + if (typeof specificKindVisitor === 'function') { + // { enter: { Kind() {} }, leave: { Kind() {} } } + return specificKindVisitor; + } + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/language/visitor.js.flow b/node_modules/graphql/language/visitor.js.flow new file mode 100644 index 0000000..ab5839a --- /dev/null +++ b/node_modules/graphql/language/visitor.js.flow @@ -0,0 +1,479 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../jsutils/inspect'; +import type { ASTNode, ASTKindToNode } from './ast'; +import type { TypeInfo } from '../utilities/TypeInfo'; + +/** + * A visitor is provided to visit, it contains the collection of + * relevant functions to be called during the visitor's traversal. + */ +export type ASTVisitor = Visitor; +export type Visitor> = + | EnterLeave< + | VisitFn + | ShapeMap(Node) => VisitFn>, + > + | ShapeMap< + KindToNode, + (Node) => VisitFn | EnterLeave>, + >; +type EnterLeave = {| +enter?: T, +leave?: T |}; +type ShapeMap = $Shape<$ObjMap>; + +/** + * A visitor is comprised of visit functions, which are called on each node + * during the visitor's traversal. + */ +export type VisitFn = ( + // The current node being visiting. + node: TVisitedNode, + // The index or key to this node from the parent node or Array. + key: string | number | void, + // The parent immediately above this node, which may be an Array. + parent: TAnyNode | $ReadOnlyArray | void, + // The key path to get to this node from the root node. + path: $ReadOnlyArray, + // All nodes and Arrays visited before reaching parent of this node. + // These correspond to array indices in `path`. + // Note: ancestors includes arrays which contain the parent of visited node. + ancestors: $ReadOnlyArray>, +) => any; + +/** + * A KeyMap describes each the traversable properties of each kind of node. + */ +export type VisitorKeyMap = $ObjMap< + KindToNode, + (T) => $ReadOnlyArray<$Keys>, +>; + +export const QueryDocumentKeys = { + Name: [], + + Document: ['definitions'], + OperationDefinition: [ + 'name', + 'variableDefinitions', + 'directives', + 'selectionSet', + ], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: [ + 'name', + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + 'variableDefinitions', + 'typeCondition', + 'directives', + 'selectionSet', + ], + + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + + Directive: ['name', 'arguments'], + + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + + SchemaDefinition: ['directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields', + ], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: [ + 'description', + 'name', + 'type', + 'defaultValue', + 'directives', + ], + InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + + SchemaExtension: ['directives', 'operationTypes'], + + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'], +}; + +export const BREAK = {}; + +/** + * visit() will walk through an AST using a depth first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to four permutations of + * visitor API: + * + * 1) Named visitors triggered when entering a node a specific kind. + * + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * + * 2) Named visitors that trigger upon entering and leaving a node of + * a specific kind. + * + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * + * 4) Parallel visitors for entering and leaving nodes of a specific kind. + * + * visit(ast, { + * enter: { + * Kind(node) { + * // enter the "Kind" node + * } + * }, + * leave: { + * Kind(node) { + * // leave the "Kind" node + * } + * } + * }) + */ +export function visit( + root: ASTNode, + visitor: Visitor, + visitorKeys: VisitorKeyMap = QueryDocumentKeys, +): any { + /* eslint-disable no-undef-init */ + let stack: any = undefined; + let inArray = Array.isArray(root); + let keys: any = [root]; + let index = -1; + let edits = []; + let node: any = undefined; + let key: any = undefined; + let parent: any = undefined; + const path: any = []; + const ancestors = []; + let newRoot = root; + /* eslint-enable no-undef-init */ + + do { + index++; + const isLeaving = index === keys.length; + const isEdited = isLeaving && edits.length !== 0; + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + if (isEdited) { + if (inArray) { + node = node.slice(); + } else { + const clone = {}; + for (const k in node) { + if (node.hasOwnProperty(k)) { + clone[k] = node[k]; + } + } + node = clone; + } + let editOffset = 0; + for (let ii = 0; ii < edits.length; ii++) { + let editKey: any = edits[ii][0]; + const editValue = edits[ii][1]; + if (inArray) { + editKey -= editOffset; + } + if (inArray && editValue === null) { + node.splice(editKey, 1); + editOffset++; + } else { + node[editKey] = editValue; + } + } + } + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else { + key = parent ? (inArray ? index : keys[index]) : undefined; + node = parent ? parent[key] : newRoot; + if (node === null || node === undefined) { + continue; + } + if (parent) { + path.push(key); + } + } + + let result; + if (!Array.isArray(node)) { + if (!isNode(node)) { + throw new Error('Invalid AST Node: ' + inspect(node)); + } + const visitFn = getVisitFn(visitor, node.kind, isLeaving); + if (visitFn) { + result = visitFn.call(visitor, node, key, parent, path, ancestors); + + if (result === BREAK) { + break; + } + + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + if (!isLeaving) { + if (isNode(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + } + + if (result === undefined && isEdited) { + edits.push([key, node]); + } + + if (isLeaving) { + path.pop(); + } else { + stack = { inArray, index, keys, edits, prev: stack }; + inArray = Array.isArray(node); + keys = inArray ? node : visitorKeys[node.kind] || []; + index = -1; + edits = []; + if (parent) { + ancestors.push(parent); + } + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + newRoot = edits[edits.length - 1][1]; + } + + return newRoot; +} + +function isNode(maybeNode): boolean %checks { + return Boolean(maybeNode && typeof maybeNode.kind === 'string'); +} + +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ +export function visitInParallel( + visitors: Array>, +): Visitor { + const skipping = new Array(visitors.length); + + return { + enter(node) { + for (let i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + const fn = getVisitFn(visitors[i], node.kind, /* isLeaving */ false); + if (fn) { + const result = fn.apply(visitors[i], arguments); + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + } + }, + leave(node) { + for (let i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + const fn = getVisitFn(visitors[i], node.kind, /* isLeaving */ true); + if (fn) { + const result = fn.apply(visitors[i], arguments); + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + }, + }; +} + +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ +export function visitWithTypeInfo( + typeInfo: TypeInfo, + visitor: Visitor, +): Visitor { + return { + enter(node) { + typeInfo.enter(node); + const fn = getVisitFn(visitor, node.kind, /* isLeaving */ false); + if (fn) { + const result = fn.apply(visitor, arguments); + if (result !== undefined) { + typeInfo.leave(node); + if (isNode(result)) { + typeInfo.enter(result); + } + } + return result; + } + }, + leave(node) { + const fn = getVisitFn(visitor, node.kind, /* isLeaving */ true); + let result; + if (fn) { + result = fn.apply(visitor, arguments); + } + typeInfo.leave(node); + return result; + }, + }; +} + +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + */ +export function getVisitFn( + visitor: Visitor, + kind: string, + isLeaving: boolean, +): ?VisitFn { + const kindVisitor = visitor[kind]; + if (kindVisitor) { + if (!isLeaving && typeof kindVisitor === 'function') { + // { Kind() {} } + return kindVisitor; + } + const kindSpecificVisitor = isLeaving + ? kindVisitor.leave + : kindVisitor.enter; + if (typeof kindSpecificVisitor === 'function') { + // { Kind: { enter() {}, leave() {} } } + return kindSpecificVisitor; + } + } else { + const specificVisitor = isLeaving ? visitor.leave : visitor.enter; + if (specificVisitor) { + if (typeof specificVisitor === 'function') { + // { enter() {}, leave() {} } + return specificVisitor; + } + const specificKindVisitor = specificVisitor[kind]; + if (typeof specificKindVisitor === 'function') { + // { enter: { Kind() {} }, leave: { Kind() {} } } + return specificKindVisitor; + } + } + } +} diff --git a/node_modules/graphql/language/visitor.mjs b/node_modules/graphql/language/visitor.mjs new file mode 100644 index 0000000..01cc258 --- /dev/null +++ b/node_modules/graphql/language/visitor.mjs @@ -0,0 +1,431 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../jsutils/inspect'; +export var QueryDocumentKeys = { + Name: [], + Document: ['definitions'], + OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + Directive: ['name', 'arguments'], + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + SchemaDefinition: ['directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], + InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + SchemaExtension: ['directives', 'operationTypes'], + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'] +}; +export var BREAK = {}; +/** + * visit() will walk through an AST using a depth first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to four permutations of + * visitor API: + * + * 1) Named visitors triggered when entering a node a specific kind. + * + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * + * 2) Named visitors that trigger upon entering and leaving a node of + * a specific kind. + * + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * + * 4) Parallel visitors for entering and leaving nodes of a specific kind. + * + * visit(ast, { + * enter: { + * Kind(node) { + * // enter the "Kind" node + * } + * }, + * leave: { + * Kind(node) { + * // leave the "Kind" node + * } + * } + * }) + */ + +export function visit(root, visitor) { + var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys; + + /* eslint-disable no-undef-init */ + var stack = undefined; + var inArray = Array.isArray(root); + var keys = [root]; + var index = -1; + var edits = []; + var node = undefined; + var key = undefined; + var parent = undefined; + var path = []; + var ancestors = []; + var newRoot = root; + /* eslint-enable no-undef-init */ + + do { + index++; + var isLeaving = index === keys.length; + var isEdited = isLeaving && edits.length !== 0; + + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + + if (isEdited) { + if (inArray) { + node = node.slice(); + } else { + var clone = {}; + + for (var k in node) { + if (node.hasOwnProperty(k)) { + clone[k] = node[k]; + } + } + + node = clone; + } + + var editOffset = 0; + + for (var ii = 0; ii < edits.length; ii++) { + var editKey = edits[ii][0]; + var editValue = edits[ii][1]; + + if (inArray) { + editKey -= editOffset; + } + + if (inArray && editValue === null) { + node.splice(editKey, 1); + editOffset++; + } else { + node[editKey] = editValue; + } + } + } + + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else { + key = parent ? inArray ? index : keys[index] : undefined; + node = parent ? parent[key] : newRoot; + + if (node === null || node === undefined) { + continue; + } + + if (parent) { + path.push(key); + } + } + + var result = void 0; + + if (!Array.isArray(node)) { + if (!isNode(node)) { + throw new Error('Invalid AST Node: ' + inspect(node)); + } + + var visitFn = getVisitFn(visitor, node.kind, isLeaving); + + if (visitFn) { + result = visitFn.call(visitor, node, key, parent, path, ancestors); + + if (result === BREAK) { + break; + } + + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + + if (!isLeaving) { + if (isNode(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + } + + if (result === undefined && isEdited) { + edits.push([key, node]); + } + + if (isLeaving) { + path.pop(); + } else { + stack = { + inArray: inArray, + index: index, + keys: keys, + edits: edits, + prev: stack + }; + inArray = Array.isArray(node); + keys = inArray ? node : visitorKeys[node.kind] || []; + index = -1; + edits = []; + + if (parent) { + ancestors.push(parent); + } + + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + newRoot = edits[edits.length - 1][1]; + } + + return newRoot; +} + +function isNode(maybeNode) { + return Boolean(maybeNode && typeof maybeNode.kind === 'string'); +} +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ + + +export function visitInParallel(visitors) { + var skipping = new Array(visitors.length); + return { + enter: function enter(node) { + for (var i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + } + }, + leave: function leave(node) { + for (var i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + true); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + } + }; +} +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ + +export function visitWithTypeInfo(typeInfo, visitor) { + return { + enter: function enter(node) { + typeInfo.enter(node); + var fn = getVisitFn(visitor, node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitor, arguments); + + if (result !== undefined) { + typeInfo.leave(node); + + if (isNode(result)) { + typeInfo.enter(result); + } + } + + return result; + } + }, + leave: function leave(node) { + var fn = getVisitFn(visitor, node.kind, + /* isLeaving */ + true); + var result; + + if (fn) { + result = fn.apply(visitor, arguments); + } + + typeInfo.leave(node); + return result; + } + }; +} +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + */ + +export function getVisitFn(visitor, kind, isLeaving) { + var kindVisitor = visitor[kind]; + + if (kindVisitor) { + if (!isLeaving && typeof kindVisitor === 'function') { + // { Kind() {} } + return kindVisitor; + } + + var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter; + + if (typeof kindSpecificVisitor === 'function') { + // { Kind: { enter() {}, leave() {} } } + return kindSpecificVisitor; + } + } else { + var specificVisitor = isLeaving ? visitor.leave : visitor.enter; + + if (specificVisitor) { + if (typeof specificVisitor === 'function') { + // { enter() {}, leave() {} } + return specificVisitor; + } + + var specificKindVisitor = specificVisitor[kind]; + + if (typeof specificKindVisitor === 'function') { + // { enter: { Kind() {} }, leave: { Kind() {} } } + return specificKindVisitor; + } + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/subscription/asyncIteratorReject.js b/node_modules/graphql/subscription/asyncIteratorReject.js new file mode 100644 index 0000000..8e06da3 --- /dev/null +++ b/node_modules/graphql/subscription/asyncIteratorReject.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncIteratorReject; + +var _iterall = require("iterall"); + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Given an error, returns an AsyncIterable which will fail with that error. + * + * Similar to Promise.reject(error) + */ +function asyncIteratorReject(error) { + var isComplete = false; + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + + return _defineProperty({ + next: function next() { + var result = isComplete ? Promise.resolve({ + value: undefined, + done: true + }) : Promise.reject(error); + isComplete = true; + return result; + }, + return: function _return() { + isComplete = true; + return Promise.resolve({ + value: undefined, + done: true + }); + }, + throw: function _throw() { + isComplete = true; + return Promise.reject(error); + } + }, _iterall.$$asyncIterator, function () { + return this; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/subscription/asyncIteratorReject.js.flow b/node_modules/graphql/subscription/asyncIteratorReject.js.flow new file mode 100644 index 0000000..7992dc6 --- /dev/null +++ b/node_modules/graphql/subscription/asyncIteratorReject.js.flow @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { $$asyncIterator } from 'iterall'; + +/** + * Given an error, returns an AsyncIterable which will fail with that error. + * + * Similar to Promise.reject(error) + */ +export default function asyncIteratorReject(error: Error): AsyncIterator { + let isComplete = false; + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + return ({ + next() { + const result = isComplete + ? Promise.resolve({ value: undefined, done: true }) + : Promise.reject(error); + isComplete = true; + return result; + }, + return() { + isComplete = true; + return Promise.resolve({ value: undefined, done: true }); + }, + throw() { + isComplete = true; + return Promise.reject(error); + }, + [$$asyncIterator]() { + return this; + }, + }: any); +} diff --git a/node_modules/graphql/subscription/asyncIteratorReject.mjs b/node_modules/graphql/subscription/asyncIteratorReject.mjs new file mode 100644 index 0000000..e2612cf --- /dev/null +++ b/node_modules/graphql/subscription/asyncIteratorReject.mjs @@ -0,0 +1,46 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { $$asyncIterator } from 'iterall'; +/** + * Given an error, returns an AsyncIterable which will fail with that error. + * + * Similar to Promise.reject(error) + */ + +export default function asyncIteratorReject(error) { + var isComplete = false; + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + + return _defineProperty({ + next: function next() { + var result = isComplete ? Promise.resolve({ + value: undefined, + done: true + }) : Promise.reject(error); + isComplete = true; + return result; + }, + return: function _return() { + isComplete = true; + return Promise.resolve({ + value: undefined, + done: true + }); + }, + throw: function _throw() { + isComplete = true; + return Promise.reject(error); + } + }, $$asyncIterator, function () { + return this; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/subscription/index.js b/node_modules/graphql/subscription/index.js new file mode 100644 index 0000000..0b45f00 --- /dev/null +++ b/node_modules/graphql/subscription/index.js @@ -0,0 +1,19 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "subscribe", { + enumerable: true, + get: function get() { + return _subscribe.subscribe; + } +}); +Object.defineProperty(exports, "createSourceEventStream", { + enumerable: true, + get: function get() { + return _subscribe.createSourceEventStream; + } +}); + +var _subscribe = require("./subscribe"); \ No newline at end of file diff --git a/node_modules/graphql/subscription/index.js.flow b/node_modules/graphql/subscription/index.js.flow new file mode 100644 index 0000000..1883165 --- /dev/null +++ b/node_modules/graphql/subscription/index.js.flow @@ -0,0 +1,10 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { subscribe, createSourceEventStream } from './subscribe'; diff --git a/node_modules/graphql/subscription/index.mjs b/node_modules/graphql/subscription/index.mjs new file mode 100644 index 0000000..a0e3646 --- /dev/null +++ b/node_modules/graphql/subscription/index.mjs @@ -0,0 +1,9 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { subscribe, createSourceEventStream } from './subscribe'; \ No newline at end of file diff --git a/node_modules/graphql/subscription/mapAsyncIterator.js b/node_modules/graphql/subscription/mapAsyncIterator.js new file mode 100644 index 0000000..eec4f90 --- /dev/null +++ b/node_modules/graphql/subscription/mapAsyncIterator.js @@ -0,0 +1,85 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapAsyncIterator; + +var _iterall = require("iterall"); + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +function mapAsyncIterator(iterable, callback, rejectCallback) { + var iterator = (0, _iterall.getAsyncIterator)(iterable); + var $return; + var abruptClose; // $FlowFixMe(>=0.68.0) + + if (typeof iterator.return === 'function') { + $return = iterator.return; + + abruptClose = function abruptClose(error) { + var rethrow = function rethrow() { + return Promise.reject(error); + }; + + return $return.call(iterator).then(rethrow, rethrow); + }; + } + + function mapResult(result) { + return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose); + } + + var mapReject; + + if (rejectCallback) { + // Capture rejectCallback to ensure it cannot be null. + var reject = rejectCallback; + + mapReject = function mapReject(error) { + return asyncMapValue(error, reject).then(iteratorResult, abruptClose); + }; + } + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + + + return _defineProperty({ + next: function next() { + return iterator.next().then(mapResult, mapReject); + }, + return: function _return() { + return $return ? $return.call(iterator).then(mapResult, mapReject) : Promise.resolve({ + value: undefined, + done: true + }); + }, + throw: function _throw(error) { + // $FlowFixMe(>=0.68.0) + if (typeof iterator.throw === 'function') { + return iterator.throw(error).then(mapResult, mapReject); + } + + return Promise.reject(error).catch(abruptClose); + } + }, _iterall.$$asyncIterator, function () { + return this; + }); +} + +function asyncMapValue(value, callback) { + return new Promise(function (resolve) { + return resolve(callback(value)); + }); +} + +function iteratorResult(value) { + return { + value: value, + done: false + }; +} \ No newline at end of file diff --git a/node_modules/graphql/subscription/mapAsyncIterator.js.flow b/node_modules/graphql/subscription/mapAsyncIterator.js.flow new file mode 100644 index 0000000..c7a7e23 --- /dev/null +++ b/node_modules/graphql/subscription/mapAsyncIterator.js.flow @@ -0,0 +1,81 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { $$asyncIterator, getAsyncIterator } from 'iterall'; +import type { MaybePromise } from '../jsutils/MaybePromise'; + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +export default function mapAsyncIterator( + iterable: AsyncIterable, + callback: T => MaybePromise, + rejectCallback?: any => MaybePromise, +): AsyncGenerator { + const iterator = getAsyncIterator(iterable); + let $return; + let abruptClose; + // $FlowFixMe(>=0.68.0) + if (typeof iterator.return === 'function') { + $return = iterator.return; + abruptClose = error => { + const rethrow = () => Promise.reject(error); + return $return.call(iterator).then(rethrow, rethrow); + }; + } + + function mapResult(result) { + return result.done + ? result + : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose); + } + + let mapReject; + if (rejectCallback) { + // Capture rejectCallback to ensure it cannot be null. + const reject = rejectCallback; + mapReject = error => + asyncMapValue(error, reject).then(iteratorResult, abruptClose); + } + + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + return ({ + next() { + return iterator.next().then(mapResult, mapReject); + }, + return() { + return $return + ? $return.call(iterator).then(mapResult, mapReject) + : Promise.resolve({ value: undefined, done: true }); + }, + throw(error) { + // $FlowFixMe(>=0.68.0) + if (typeof iterator.throw === 'function') { + return iterator.throw(error).then(mapResult, mapReject); + } + return Promise.reject(error).catch(abruptClose); + }, + [$$asyncIterator]() { + return this; + }, + }: any); +} + +function asyncMapValue( + value: T, + callback: T => MaybePromise, +): Promise { + return new Promise(resolve => resolve(callback(value))); +} + +function iteratorResult(value: T): IteratorResult { + return { value, done: false }; +} diff --git a/node_modules/graphql/subscription/mapAsyncIterator.mjs b/node_modules/graphql/subscription/mapAsyncIterator.mjs new file mode 100644 index 0000000..fe20bb1 --- /dev/null +++ b/node_modules/graphql/subscription/mapAsyncIterator.mjs @@ -0,0 +1,86 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { $$asyncIterator, getAsyncIterator } from 'iterall'; + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +export default function mapAsyncIterator(iterable, callback, rejectCallback) { + var iterator = getAsyncIterator(iterable); + var $return; + var abruptClose; // $FlowFixMe(>=0.68.0) + + if (typeof iterator.return === 'function') { + $return = iterator.return; + + abruptClose = function abruptClose(error) { + var rethrow = function rethrow() { + return Promise.reject(error); + }; + + return $return.call(iterator).then(rethrow, rethrow); + }; + } + + function mapResult(result) { + return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose); + } + + var mapReject; + + if (rejectCallback) { + // Capture rejectCallback to ensure it cannot be null. + var reject = rejectCallback; + + mapReject = function mapReject(error) { + return asyncMapValue(error, reject).then(iteratorResult, abruptClose); + }; + } + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + + + return _defineProperty({ + next: function next() { + return iterator.next().then(mapResult, mapReject); + }, + return: function _return() { + return $return ? $return.call(iterator).then(mapResult, mapReject) : Promise.resolve({ + value: undefined, + done: true + }); + }, + throw: function _throw(error) { + // $FlowFixMe(>=0.68.0) + if (typeof iterator.throw === 'function') { + return iterator.throw(error).then(mapResult, mapReject); + } + + return Promise.reject(error).catch(abruptClose); + } + }, $$asyncIterator, function () { + return this; + }); +} + +function asyncMapValue(value, callback) { + return new Promise(function (resolve) { + return resolve(callback(value)); + }); +} + +function iteratorResult(value) { + return { + value: value, + done: false + }; +} \ No newline at end of file diff --git a/node_modules/graphql/subscription/subscribe.js b/node_modules/graphql/subscription/subscribe.js new file mode 100644 index 0000000..c0134cd --- /dev/null +++ b/node_modules/graphql/subscription/subscribe.js @@ -0,0 +1,151 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.subscribe = subscribe; +exports.createSourceEventStream = createSourceEventStream; + +var _iterall = require("iterall"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _GraphQLError = require("../error/GraphQLError"); + +var _locatedError = require("../error/locatedError"); + +var _execute = require("../execution/execute"); + +var _mapAsyncIterator = _interopRequireDefault(require("./mapAsyncIterator")); + +var _getOperationRootType = require("../utilities/getOperationRootType"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? subscribeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver, argsOrSchema.subscribeFieldResolver) : subscribeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver); +} +/** + * This function checks if the error is a GraphQLError. If it is, report it as + * an ExecutionResult, containing only errors and no data. Otherwise treat the + * error as a system-class error and re-throw it. + */ + + +function reportGraphQLError(error) { + if (error instanceof _GraphQLError.GraphQLError) { + return { + errors: [error] + }; + } + + throw error; +} + +function subscribeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + var sourcePromise = createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver); // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. + + var mapSourceToResponse = function mapSourceToResponse(payload) { + return (0, _execute.execute)(schema, document, payload, contextValue, variableValues, operationName, fieldResolver); + }; // Resolve the Source Stream, then map every source value to a + // ExecutionResult value as described above. + + + return sourcePromise.then(function (resultOrStream) { + return (// Note: Flow can't refine isAsyncIterable, so explicit casts are used. + (0, _iterall.isAsyncIterable)(resultOrStream) ? (0, _mapAsyncIterator.default)(resultOrStream, mapSourceToResponse, reportGraphQLError) : resultOrStream + ); + }, reportGraphQLError); +} +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise. + * + * If the client-provided invalid arguments, the source stream could not be + * created, or the resolver did not return an AsyncIterable, this function will + * will throw an error, which should be caught and handled by the caller. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ + + +function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + (0, _execute.assertValidExecutionArguments)(schema, document, variableValues); + + try { + // If a valid context cannot be created due to incorrect arguments, + // this will throw an error. + var exeContext = (0, _execute.buildExecutionContext)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed. + + if (Array.isArray(exeContext)) { + return Promise.resolve({ + errors: exeContext + }); + } + + var type = (0, _getOperationRootType.getOperationRootType)(schema, exeContext.operation); + var fields = (0, _execute.collectFields)(exeContext, type, exeContext.operation.selectionSet, Object.create(null), Object.create(null)); + var responseNames = Object.keys(fields); + var responseName = responseNames[0]; + var fieldNodes = fields[responseName]; + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = (0, _execute.getFieldDef)(schema, type, fieldName); + + if (!fieldDef) { + throw new _GraphQLError.GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes); + } // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + + + var resolveFn = fieldDef.subscribe || exeContext.fieldResolver; + var path = (0, _execute.addPath)(undefined, responseName); + var info = (0, _execute.buildResolveInfo)(exeContext, fieldDef, fieldNodes, type, path); // resolveFieldValueOrError implements the "ResolveFieldEventStream" + // algorithm from GraphQL specification. It differs from + // "ResolveFieldValue" due to providing a different `resolveFn`. + + var result = (0, _execute.resolveFieldValueOrError)(exeContext, fieldDef, fieldNodes, resolveFn, rootValue, info); // Coerce to Promise for easier error handling and consistent return type. + + return Promise.resolve(result).then(function (eventStream) { + // If eventStream is an Error, rethrow a located error. + if (eventStream instanceof Error) { + throw (0, _locatedError.locatedError)(eventStream, fieldNodes, (0, _execute.responsePathAsArray)(path)); + } // Assert field returned an event stream, otherwise yield an error. + + + if ((0, _iterall.isAsyncIterable)(eventStream)) { + // Note: isAsyncIterable above ensures this will be correct. + return eventStream; + } + + throw new Error('Subscription field must return Async Iterable. Received: ' + (0, _inspect.default)(eventStream)); + }); + } catch (error) { + return Promise.reject(error); + } +} \ No newline at end of file diff --git a/node_modules/graphql/subscription/subscribe.js.flow b/node_modules/graphql/subscription/subscribe.js.flow new file mode 100644 index 0000000..4b2e74a --- /dev/null +++ b/node_modules/graphql/subscription/subscribe.js.flow @@ -0,0 +1,289 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { isAsyncIterable } from 'iterall'; +import inspect from '../jsutils/inspect'; +import { GraphQLError } from '../error/GraphQLError'; +import { locatedError } from '../error/locatedError'; +import { + addPath, + assertValidExecutionArguments, + buildExecutionContext, + buildResolveInfo, + collectFields, + execute, + getFieldDef, + resolveFieldValueOrError, + responsePathAsArray, +} from '../execution/execute'; +import type { GraphQLSchema } from '../type/schema'; +import mapAsyncIterator from './mapAsyncIterator'; + +import type { ObjMap } from '../jsutils/ObjMap'; +import type { ExecutionResult } from '../execution/execute'; +import type { DocumentNode } from '../language/ast'; +import type { GraphQLFieldResolver } from '../type/definition'; +import { getOperationRootType } from '../utilities/getOperationRootType'; + +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise which resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (client error). The promise will be rejected if a + * server error occurs. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Accepts either an object with named arguments, or individual arguments. + */ +declare function subscribe( + {| + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, + subscribeFieldResolver?: ?GraphQLFieldResolver, + |}, + ..._: [] +): Promise | ExecutionResult>; +/* eslint-disable no-redeclare */ +declare function subscribe( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, + subscribeFieldResolver?: ?GraphQLFieldResolver, +): Promise | ExecutionResult>; +export function subscribe( + argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + subscribeFieldResolver, +) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 + ? subscribeImpl( + argsOrSchema.schema, + argsOrSchema.document, + argsOrSchema.rootValue, + argsOrSchema.contextValue, + argsOrSchema.variableValues, + argsOrSchema.operationName, + argsOrSchema.fieldResolver, + argsOrSchema.subscribeFieldResolver, + ) + : subscribeImpl( + argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + subscribeFieldResolver, + ); +} + +/** + * This function checks if the error is a GraphQLError. If it is, report it as + * an ExecutionResult, containing only errors and no data. Otherwise treat the + * error as a system-class error and re-throw it. + */ +function reportGraphQLError(error) { + if (error instanceof GraphQLError) { + return { errors: [error] }; + } + throw error; +} + +function subscribeImpl( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + subscribeFieldResolver, +) { + const sourcePromise = createSourceEventStream( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + subscribeFieldResolver, + ); + + // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. + const mapSourceToResponse = payload => + execute( + schema, + document, + payload, + contextValue, + variableValues, + operationName, + fieldResolver, + ); + + // Resolve the Source Stream, then map every source value to a + // ExecutionResult value as described above. + return sourcePromise.then( + resultOrStream => + // Note: Flow can't refine isAsyncIterable, so explicit casts are used. + isAsyncIterable(resultOrStream) + ? mapAsyncIterator( + ((resultOrStream: any): AsyncIterable), + mapSourceToResponse, + reportGraphQLError, + ) + : ((resultOrStream: any): ExecutionResult), + reportGraphQLError, + ); +} + +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise. + * + * If the client-provided invalid arguments, the source stream could not be + * created, or the resolver did not return an AsyncIterable, this function will + * will throw an error, which should be caught and handled by the caller. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ +export function createSourceEventStream( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +): Promise | ExecutionResult> { + // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + assertValidExecutionArguments(schema, document, variableValues); + + try { + // If a valid context cannot be created due to incorrect arguments, + // this will throw an error. + const exeContext = buildExecutionContext( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ); + + // Return early errors if execution context failed. + if (Array.isArray(exeContext)) { + return Promise.resolve({ errors: exeContext }); + } + + const type = getOperationRootType(schema, exeContext.operation); + const fields = collectFields( + exeContext, + type, + exeContext.operation.selectionSet, + Object.create(null), + Object.create(null), + ); + const responseNames = Object.keys(fields); + const responseName = responseNames[0]; + const fieldNodes = fields[responseName]; + const fieldNode = fieldNodes[0]; + const fieldName = fieldNode.name.value; + const fieldDef = getFieldDef(schema, type, fieldName); + + if (!fieldDef) { + throw new GraphQLError( + `The subscription field "${fieldName}" is not defined.`, + fieldNodes, + ); + } + + // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + const resolveFn = fieldDef.subscribe || exeContext.fieldResolver; + + const path = addPath(undefined, responseName); + + const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, type, path); + + // resolveFieldValueOrError implements the "ResolveFieldEventStream" + // algorithm from GraphQL specification. It differs from + // "ResolveFieldValue" due to providing a different `resolveFn`. + const result = resolveFieldValueOrError( + exeContext, + fieldDef, + fieldNodes, + resolveFn, + rootValue, + info, + ); + + // Coerce to Promise for easier error handling and consistent return type. + return Promise.resolve(result).then(eventStream => { + // If eventStream is an Error, rethrow a located error. + if (eventStream instanceof Error) { + throw locatedError(eventStream, fieldNodes, responsePathAsArray(path)); + } + + // Assert field returned an event stream, otherwise yield an error. + if (isAsyncIterable(eventStream)) { + // Note: isAsyncIterable above ensures this will be correct. + return ((eventStream: any): AsyncIterable); + } + throw new Error( + 'Subscription field must return Async Iterable. Received: ' + + inspect(eventStream), + ); + }); + } catch (error) { + return Promise.reject(error); + } +} diff --git a/node_modules/graphql/subscription/subscribe.mjs b/node_modules/graphql/subscription/subscribe.mjs new file mode 100644 index 0000000..e2e65ca --- /dev/null +++ b/node_modules/graphql/subscription/subscribe.mjs @@ -0,0 +1,154 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { isAsyncIterable } from 'iterall'; +import inspect from '../jsutils/inspect'; +import { GraphQLError } from '../error/GraphQLError'; +import { locatedError } from '../error/locatedError'; +import { addPath, assertValidExecutionArguments, buildExecutionContext, buildResolveInfo, collectFields, execute, getFieldDef, resolveFieldValueOrError, responsePathAsArray } from '../execution/execute'; +import mapAsyncIterator from './mapAsyncIterator'; +import { getOperationRootType } from '../utilities/getOperationRootType'; +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise which resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (client error). The promise will be rejected if a + * server error occurs. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Accepts either an object with named arguments, or individual arguments. + */ + +export function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? subscribeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver, argsOrSchema.subscribeFieldResolver) : subscribeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver); +} +/** + * This function checks if the error is a GraphQLError. If it is, report it as + * an ExecutionResult, containing only errors and no data. Otherwise treat the + * error as a system-class error and re-throw it. + */ + +function reportGraphQLError(error) { + if (error instanceof GraphQLError) { + return { + errors: [error] + }; + } + + throw error; +} + +function subscribeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + var sourcePromise = createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver); // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. + + var mapSourceToResponse = function mapSourceToResponse(payload) { + return execute(schema, document, payload, contextValue, variableValues, operationName, fieldResolver); + }; // Resolve the Source Stream, then map every source value to a + // ExecutionResult value as described above. + + + return sourcePromise.then(function (resultOrStream) { + return (// Note: Flow can't refine isAsyncIterable, so explicit casts are used. + isAsyncIterable(resultOrStream) ? mapAsyncIterator(resultOrStream, mapSourceToResponse, reportGraphQLError) : resultOrStream + ); + }, reportGraphQLError); +} +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise. + * + * If the client-provided invalid arguments, the source stream could not be + * created, or the resolver did not return an AsyncIterable, this function will + * will throw an error, which should be caught and handled by the caller. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ + + +export function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + assertValidExecutionArguments(schema, document, variableValues); + + try { + // If a valid context cannot be created due to incorrect arguments, + // this will throw an error. + var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed. + + if (Array.isArray(exeContext)) { + return Promise.resolve({ + errors: exeContext + }); + } + + var type = getOperationRootType(schema, exeContext.operation); + var fields = collectFields(exeContext, type, exeContext.operation.selectionSet, Object.create(null), Object.create(null)); + var responseNames = Object.keys(fields); + var responseName = responseNames[0]; + var fieldNodes = fields[responseName]; + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = getFieldDef(schema, type, fieldName); + + if (!fieldDef) { + throw new GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes); + } // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + + + var resolveFn = fieldDef.subscribe || exeContext.fieldResolver; + var path = addPath(undefined, responseName); + var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, type, path); // resolveFieldValueOrError implements the "ResolveFieldEventStream" + // algorithm from GraphQL specification. It differs from + // "ResolveFieldValue" due to providing a different `resolveFn`. + + var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, rootValue, info); // Coerce to Promise for easier error handling and consistent return type. + + return Promise.resolve(result).then(function (eventStream) { + // If eventStream is an Error, rethrow a located error. + if (eventStream instanceof Error) { + throw locatedError(eventStream, fieldNodes, responsePathAsArray(path)); + } // Assert field returned an event stream, otherwise yield an error. + + + if (isAsyncIterable(eventStream)) { + // Note: isAsyncIterable above ensures this will be correct. + return eventStream; + } + + throw new Error('Subscription field must return Async Iterable. Received: ' + inspect(eventStream)); + }); + } catch (error) { + return Promise.reject(error); + } +} \ No newline at end of file diff --git a/node_modules/graphql/type/definition.js b/node_modules/graphql/type/definition.js new file mode 100644 index 0000000..99ff4a5 --- /dev/null +++ b/node_modules/graphql/type/definition.js @@ -0,0 +1,968 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isType = isType; +exports.assertType = assertType; +exports.isScalarType = isScalarType; +exports.assertScalarType = assertScalarType; +exports.isObjectType = isObjectType; +exports.assertObjectType = assertObjectType; +exports.isInterfaceType = isInterfaceType; +exports.assertInterfaceType = assertInterfaceType; +exports.isUnionType = isUnionType; +exports.assertUnionType = assertUnionType; +exports.isEnumType = isEnumType; +exports.assertEnumType = assertEnumType; +exports.isInputObjectType = isInputObjectType; +exports.assertInputObjectType = assertInputObjectType; +exports.isListType = isListType; +exports.assertListType = assertListType; +exports.isNonNullType = isNonNullType; +exports.assertNonNullType = assertNonNullType; +exports.isInputType = isInputType; +exports.assertInputType = assertInputType; +exports.isOutputType = isOutputType; +exports.assertOutputType = assertOutputType; +exports.isLeafType = isLeafType; +exports.assertLeafType = assertLeafType; +exports.isCompositeType = isCompositeType; +exports.assertCompositeType = assertCompositeType; +exports.isAbstractType = isAbstractType; +exports.assertAbstractType = assertAbstractType; +exports.GraphQLList = GraphQLList; +exports.GraphQLNonNull = GraphQLNonNull; +exports.isWrappingType = isWrappingType; +exports.assertWrappingType = assertWrappingType; +exports.isNullableType = isNullableType; +exports.assertNullableType = assertNullableType; +exports.getNullableType = getNullableType; +exports.isNamedType = isNamedType; +exports.assertNamedType = assertNamedType; +exports.getNamedType = getNamedType; +exports.isRequiredArgument = isRequiredArgument; +exports.isRequiredInputField = isRequiredInputField; +exports.GraphQLInputObjectType = exports.GraphQLEnumType = exports.GraphQLUnionType = exports.GraphQLInterfaceType = exports.GraphQLObjectType = exports.GraphQLScalarType = void 0; + +var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON")); + +var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag")); + +var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _kinds = require("../language/kinds"); + +var _valueFromASTUntyped = require("../utilities/valueFromASTUntyped"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function isType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type); +} + +function assertType(type) { + !isType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL type.")) : void 0; + return type; +} +/** + * There are predicates for each kind of GraphQL type. + */ + + +// eslint-disable-next-line no-redeclare +function isScalarType(type) { + return (0, _instanceOf.default)(type, GraphQLScalarType); +} + +function assertScalarType(type) { + !isScalarType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Scalar type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isObjectType(type) { + return (0, _instanceOf.default)(type, GraphQLObjectType); +} + +function assertObjectType(type) { + !isObjectType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Object type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isInterfaceType(type) { + return (0, _instanceOf.default)(type, GraphQLInterfaceType); +} + +function assertInterfaceType(type) { + !isInterfaceType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Interface type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isUnionType(type) { + return (0, _instanceOf.default)(type, GraphQLUnionType); +} + +function assertUnionType(type) { + !isUnionType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Union type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isEnumType(type) { + return (0, _instanceOf.default)(type, GraphQLEnumType); +} + +function assertEnumType(type) { + !isEnumType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Enum type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isInputObjectType(type) { + return (0, _instanceOf.default)(type, GraphQLInputObjectType); +} + +function assertInputObjectType(type) { + !isInputObjectType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Input Object type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isListType(type) { + return (0, _instanceOf.default)(type, GraphQLList); +} + +function assertListType(type) { + !isListType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL List type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isNonNullType(type) { + return (0, _instanceOf.default)(type, GraphQLNonNull); +} + +function assertNonNullType(type) { + !isNonNullType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Non-Null type.")) : void 0; + return type; +} +/** + * These types may be used as input types for arguments and directives. + */ + + +function isInputType(type) { + return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType); +} + +function assertInputType(type) { + !isInputType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL input type.")) : void 0; + return type; +} +/** + * These types may be used as output types as the result of fields. + */ + + +function isOutputType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType); +} + +function assertOutputType(type) { + !isOutputType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL output type.")) : void 0; + return type; +} +/** + * These types may describe types which may be leaf values. + */ + + +function isLeafType(type) { + return isScalarType(type) || isEnumType(type); +} + +function assertLeafType(type) { + !isLeafType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL leaf type.")) : void 0; + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + + +function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} + +function assertCompositeType(type) { + !isCompositeType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL composite type.")) : void 0; + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + + +function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); +} + +function assertAbstractType(type) { + !isAbstractType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL abstract type.")) : void 0; + return type; +} +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: GraphQLList(PersonType) }, + * children: { type: GraphQLList(PersonType) }, + * }) + * }) + * + */ + + +// eslint-disable-next-line no-redeclare +function GraphQLList(ofType) { + if (this instanceof GraphQLList) { + this.ofType = assertType(ofType); + } else { + return new GraphQLList(ofType); + } +} // Need to cast through any to alter the prototype. + + +GraphQLList.prototype.toString = function toString() { + return '[' + String(this.ofType) + ']'; +}; + +(0, _defineToJSON.default)(GraphQLList); +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ + +// eslint-disable-next-line no-redeclare +function GraphQLNonNull(ofType) { + if (this instanceof GraphQLNonNull) { + this.ofType = assertNullableType(ofType); + } else { + return new GraphQLNonNull(ofType); + } +} // Need to cast through any to alter the prototype. + + +GraphQLNonNull.prototype.toString = function toString() { + return String(this.ofType) + '!'; +}; + +(0, _defineToJSON.default)(GraphQLNonNull); +/** + * These types wrap and modify other types + */ + +function isWrappingType(type) { + return isListType(type) || isNonNullType(type); +} + +function assertWrappingType(type) { + !isWrappingType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL wrapping type.")) : void 0; + return type; +} +/** + * These types can all accept null as a value. + */ + + +function isNullableType(type) { + return isType(type) && !isNonNullType(type); +} + +function assertNullableType(type) { + !isNullableType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL nullable type.")) : void 0; + return type; +} +/* eslint-disable no-redeclare */ + + +function getNullableType(type) { + /* eslint-enable no-redeclare */ + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} +/** + * These named types do not include modifiers like List or NonNull. + */ + + +function isNamedType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type); +} + +function assertNamedType(type) { + !isNamedType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL named type.")) : void 0; + return type; +} +/* eslint-disable no-redeclare */ + + +function getNamedType(type) { + /* eslint-enable no-redeclare */ + if (type) { + var unwrappedType = type; + + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + + return unwrappedType; + } +} +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ + + +function resolveThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function does not return a value (i.e. it returns + * `undefined`) then an error will be raised and a `null` value will be returned + * in the response. If the serialize function returns `null`, then no error will + * be included in the response. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (value % 2 === 1) { + * return value; + * } + * } + * }); + * + */ + + +var GraphQLScalarType = +/*#__PURE__*/ +function () { + function GraphQLScalarType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "serialize", void 0); + + _defineProperty(this, "parseValue", void 0); + + _defineProperty(this, "parseLiteral", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + this.name = config.name; + this.description = config.description; + this.serialize = config.serialize; + + this.parseValue = config.parseValue || function (value) { + return value; + }; + + this.parseLiteral = config.parseLiteral || _valueFromASTUntyped.valueFromASTUntyped; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + !(typeof config.serialize === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"serialize\" function. If this custom Scalar ") + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.') : void 0; + + if (config.parseValue || config.parseLiteral) { + !(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide both \"parseValue\" and \"parseLiteral\" ") + 'functions.') : void 0; + } + } + + var _proto = GraphQLScalarType.prototype; + + _proto.toString = function toString() { + return this.name; + }; + + return GraphQLScalarType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLScalarType = GraphQLScalarType; +(0, _defineToStringTag.default)(GraphQLScalarType); +(0, _defineToJSON.default)(GraphQLScalarType); + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * + */ +var GraphQLObjectType = +/*#__PURE__*/ +function () { + function GraphQLObjectType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "isTypeOf", void 0); + + _defineProperty(this, "_fields", void 0); + + _defineProperty(this, "_interfaces", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.isTypeOf = config.isTypeOf; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + !(config.isTypeOf == null || typeof config.isTypeOf === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"isTypeOf\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.isTypeOf), ".")) : void 0; + } + + var _proto2 = GraphQLObjectType.prototype; + + _proto2.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto2.getInterfaces = function getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + }; + + _proto2.toString = function toString() { + return this.name; + }; + + return GraphQLObjectType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLObjectType = GraphQLObjectType; +(0, _defineToStringTag.default)(GraphQLObjectType); +(0, _defineToJSON.default)(GraphQLObjectType); + +function defineInterfaces(config) { + var interfaces = resolveThunk(config.interfaces) || []; + !Array.isArray(interfaces) ? (0, _invariant.default)(0, "".concat(config.name, " interfaces must be an Array or a function which returns ") + 'an Array.') : void 0; + return interfaces; +} + +function defineFieldMap(config) { + var fieldMap = resolveThunk(config.fields) || {}; + !isPlainObj(fieldMap) ? (0, _invariant.default)(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0; + var resultFieldMap = Object.create(null); + + var _arr = Object.keys(fieldMap); + + var _loop = function _loop() { + var fieldName = _arr[_i]; + var fieldConfig = fieldMap[fieldName]; + !isPlainObj(fieldConfig) ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field config must be an object")) : void 0; + !!fieldConfig.hasOwnProperty('isDeprecated') ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " should provide \"deprecationReason\" ") + 'instead of "isDeprecated".') : void 0; + + var field = _objectSpread({}, fieldConfig, { + isDeprecated: Boolean(fieldConfig.deprecationReason), + name: fieldName + }); + + !(field.resolve == null || typeof field.resolve === 'function') ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field resolver must be a function if ") + "provided, but got: ".concat((0, _inspect.default)(field.resolve), ".")) : void 0; + var argsConfig = fieldConfig.args; + + if (!argsConfig) { + field.args = []; + } else { + !isPlainObj(argsConfig) ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " args must be an object with argument ") + 'names as keys.') : void 0; + field.args = Object.keys(argsConfig).map(function (argName) { + var arg = argsConfig[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode + }; + }); + } + + resultFieldMap[fieldName] = field; + }; + + for (var _i = 0; _i < _arr.length; _i++) { + _loop(); + } + + return resultFieldMap; +} + +function isPlainObj(obj) { + return obj && _typeof(obj) === 'object' && !Array.isArray(obj); +} + +function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * + */ +var GraphQLInterfaceType = +/*#__PURE__*/ +function () { + function GraphQLInterfaceType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "resolveType", void 0); + + _defineProperty(this, "_fields", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._fields = defineFieldMap.bind(undefined, config); + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + !(config.resolveType == null || typeof config.resolveType === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.resolveType), ".")) : void 0; + } + + var _proto3 = GraphQLInterfaceType.prototype; + + _proto3.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto3.toString = function toString() { + return this.name; + }; + + return GraphQLInterfaceType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLInterfaceType = GraphQLInterfaceType; +(0, _defineToStringTag.default)(GraphQLInterfaceType); +(0, _defineToJSON.default)(GraphQLInterfaceType); + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * + */ +var GraphQLUnionType = +/*#__PURE__*/ +function () { + function GraphQLUnionType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "resolveType", void 0); + + _defineProperty(this, "_types", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._types = defineTypes.bind(undefined, config); + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + !(config.resolveType == null || typeof config.resolveType === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.resolveType), ".")) : void 0; + } + + var _proto4 = GraphQLUnionType.prototype; + + _proto4.getTypes = function getTypes() { + if (typeof this._types === 'function') { + this._types = this._types(); + } + + return this._types; + }; + + _proto4.toString = function toString() { + return this.name; + }; + + return GraphQLUnionType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLUnionType = GraphQLUnionType; +(0, _defineToStringTag.default)(GraphQLUnionType); +(0, _defineToJSON.default)(GraphQLUnionType); + +function defineTypes(config) { + var types = resolveThunk(config.types) || []; + !Array.isArray(types) ? (0, _invariant.default)(0, 'Must provide Array of types or a function which returns ' + "such an array for Union ".concat(config.name, ".")) : void 0; + return types; +} + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +var GraphQLEnumType +/* */ += +/*#__PURE__*/ +function () { + function GraphQLEnumType(config + /* */ + ) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_values", void 0); + + _defineProperty(this, "_valueLookup", void 0); + + _defineProperty(this, "_nameLookup", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._values = defineEnumValues(this, config.values); + this._valueLookup = new Map(this._values.map(function (enumValue) { + return [enumValue.value, enumValue]; + })); + this._nameLookup = (0, _keyMap.default)(this._values, function (value) { + return value.name; + }); + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + } + + var _proto5 = GraphQLEnumType.prototype; + + _proto5.getValues = function getValues() { + return this._values; + }; + + _proto5.getValue = function getValue(name) { + return this._nameLookup[name]; + }; + + _proto5.serialize = function serialize(value + /* T */ + ) { + var enumValue = this._valueLookup.get(value); + + if (enumValue) { + return enumValue.name; + } + }; + + _proto5.parseValue = function parseValue(value) + /* T */ + { + if (typeof value === 'string') { + var enumValue = this.getValue(value); + + if (enumValue) { + return enumValue.value; + } + } + }; + + _proto5.parseLiteral = function parseLiteral(valueNode, _variables) + /* T */ + { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind === _kinds.Kind.ENUM) { + var enumValue = this.getValue(valueNode.value); + + if (enumValue) { + return enumValue.value; + } + } + }; + + _proto5.toString = function toString() { + return this.name; + }; + + return GraphQLEnumType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLEnumType = GraphQLEnumType; +(0, _defineToStringTag.default)(GraphQLEnumType); +(0, _defineToJSON.default)(GraphQLEnumType); + +function defineEnumValues(type, valueMap +/* */ +) { + !isPlainObj(valueMap) ? (0, _invariant.default)(0, "".concat(type.name, " values must be an object with value names as keys.")) : void 0; + return Object.keys(valueMap).map(function (valueName) { + var value = valueMap[valueName]; + !isPlainObj(value) ? (0, _invariant.default)(0, "".concat(type.name, ".").concat(valueName, " must refer to an object with a \"value\" key ") + "representing an internal value but got: ".concat((0, _inspect.default)(value), ".")) : void 0; + !!value.hasOwnProperty('isDeprecated') ? (0, _invariant.default)(0, "".concat(type.name, ".").concat(valueName, " should provide \"deprecationReason\" instead ") + 'of "isDeprecated".') : void 0; + return { + name: valueName, + description: value.description, + isDeprecated: Boolean(value.deprecationReason), + deprecationReason: value.deprecationReason, + astNode: value.astNode, + value: value.hasOwnProperty('value') ? value.value : valueName + }; + }); +} + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: GraphQLNonNull(GraphQLFloat) }, + * lon: { type: GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +var GraphQLInputObjectType = +/*#__PURE__*/ +function () { + function GraphQLInputObjectType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_fields", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._fields = defineInputFieldMap.bind(undefined, config); + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + } + + var _proto6 = GraphQLInputObjectType.prototype; + + _proto6.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto6.toString = function toString() { + return this.name; + }; + + return GraphQLInputObjectType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLInputObjectType = GraphQLInputObjectType; +(0, _defineToStringTag.default)(GraphQLInputObjectType); +(0, _defineToJSON.default)(GraphQLInputObjectType); + +function defineInputFieldMap(config) { + var fieldMap = resolveThunk(config.fields) || {}; + !isPlainObj(fieldMap) ? (0, _invariant.default)(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0; + var resultFieldMap = Object.create(null); + + var _arr2 = Object.keys(fieldMap); + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var fieldName = _arr2[_i2]; + + var field = _objectSpread({}, fieldMap[fieldName], { + name: fieldName + }); + + !!field.hasOwnProperty('resolve') ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field has a resolve property, but ") + 'Input Types cannot define resolvers.') : void 0; + resultFieldMap[fieldName] = field; + } + + return resultFieldMap; +} + +function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; +} \ No newline at end of file diff --git a/node_modules/graphql/type/definition.js.flow b/node_modules/graphql/type/definition.js.flow new file mode 100644 index 0000000..675092d --- /dev/null +++ b/node_modules/graphql/type/definition.js.flow @@ -0,0 +1,1286 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import defineToJSON from '../jsutils/defineToJSON'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import instanceOf from '../jsutils/instanceOf'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import type { ObjMap } from '../jsutils/ObjMap'; +import { Kind } from '../language/kinds'; +import { valueFromASTUntyped } from '../utilities/valueFromASTUntyped'; +import type { + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, + OperationDefinitionNode, + FieldNode, + FragmentDefinitionNode, + ValueNode, +} from '../language/ast'; +import type { GraphQLSchema } from './schema'; +import type { MaybePromise } from '../jsutils/MaybePromise'; + +// Predicates & Assertions + +/** + * These are all of the possible kinds of types. + */ +export type GraphQLType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull; + +export function isType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) || + isListType(type) || + isNonNullType(type) + ); +} + +export function assertType(type: mixed): GraphQLType { + invariant(isType(type), `Expected ${inspect(type)} to be a GraphQL type.`); + return type; +} + +/** + * There are predicates for each kind of GraphQL type. + */ + +declare function isScalarType(type: mixed): boolean %checks(type instanceof + GraphQLScalarType); +// eslint-disable-next-line no-redeclare +export function isScalarType(type) { + return instanceOf(type, GraphQLScalarType); +} + +export function assertScalarType(type: mixed): GraphQLScalarType { + invariant( + isScalarType(type), + `Expected ${inspect(type)} to be a GraphQL Scalar type.`, + ); + return type; +} + +declare function isObjectType(type: mixed): boolean %checks(type instanceof + GraphQLObjectType); +// eslint-disable-next-line no-redeclare +export function isObjectType(type) { + return instanceOf(type, GraphQLObjectType); +} + +export function assertObjectType(type: mixed): GraphQLObjectType { + invariant( + isObjectType(type), + `Expected ${inspect(type)} to be a GraphQL Object type.`, + ); + return type; +} + +declare function isInterfaceType(type: mixed): boolean %checks(type instanceof + GraphQLInterfaceType); +// eslint-disable-next-line no-redeclare +export function isInterfaceType(type) { + return instanceOf(type, GraphQLInterfaceType); +} + +export function assertInterfaceType(type: mixed): GraphQLInterfaceType { + invariant( + isInterfaceType(type), + `Expected ${inspect(type)} to be a GraphQL Interface type.`, + ); + return type; +} + +declare function isUnionType(type: mixed): boolean %checks(type instanceof + GraphQLUnionType); +// eslint-disable-next-line no-redeclare +export function isUnionType(type) { + return instanceOf(type, GraphQLUnionType); +} + +export function assertUnionType(type: mixed): GraphQLUnionType { + invariant( + isUnionType(type), + `Expected ${inspect(type)} to be a GraphQL Union type.`, + ); + return type; +} + +declare function isEnumType(type: mixed): boolean %checks(type instanceof + GraphQLEnumType); +// eslint-disable-next-line no-redeclare +export function isEnumType(type) { + return instanceOf(type, GraphQLEnumType); +} + +export function assertEnumType(type: mixed): GraphQLEnumType { + invariant( + isEnumType(type), + `Expected ${inspect(type)} to be a GraphQL Enum type.`, + ); + return type; +} + +declare function isInputObjectType(type: mixed): boolean %checks(type instanceof + GraphQLInputObjectType); +// eslint-disable-next-line no-redeclare +export function isInputObjectType(type) { + return instanceOf(type, GraphQLInputObjectType); +} + +export function assertInputObjectType(type: mixed): GraphQLInputObjectType { + invariant( + isInputObjectType(type), + `Expected ${inspect(type)} to be a GraphQL Input Object type.`, + ); + return type; +} + +declare function isListType(type: mixed): boolean %checks(type instanceof + GraphQLList); +// eslint-disable-next-line no-redeclare +export function isListType(type) { + return instanceOf(type, GraphQLList); +} + +export function assertListType(type: mixed): GraphQLList { + invariant( + isListType(type), + `Expected ${inspect(type)} to be a GraphQL List type.`, + ); + return type; +} + +declare function isNonNullType(type: mixed): boolean %checks(type instanceof + GraphQLNonNull); +// eslint-disable-next-line no-redeclare +export function isNonNullType(type) { + return instanceOf(type, GraphQLNonNull); +} + +export function assertNonNullType(type: mixed): GraphQLNonNull { + invariant( + isNonNullType(type), + `Expected ${inspect(type)} to be a GraphQL Non-Null type.`, + ); + return type; +} + +/** + * These types may be used as input types for arguments and directives. + */ +export type GraphQLInputType = + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList, + >; + +export function isInputType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isEnumType(type) || + isInputObjectType(type) || + (isWrappingType(type) && isInputType(type.ofType)) + ); +} + +export function assertInputType(type: mixed): GraphQLInputType { + invariant( + isInputType(type), + `Expected ${inspect(type)} to be a GraphQL input type.`, + ); + return type; +} + +/** + * These types may be used as output types as the result of fields. + */ +export type GraphQLOutputType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList, + >; + +export function isOutputType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + (isWrappingType(type) && isOutputType(type.ofType)) + ); +} + +export function assertOutputType(type: mixed): GraphQLOutputType { + invariant( + isOutputType(type), + `Expected ${inspect(type)} to be a GraphQL output type.`, + ); + return type; +} + +/** + * These types may describe types which may be leaf values. + */ +export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; + +export function isLeafType(type: mixed): boolean %checks { + return isScalarType(type) || isEnumType(type); +} + +export function assertLeafType(type: mixed): GraphQLLeafType { + invariant( + isLeafType(type), + `Expected ${inspect(type)} to be a GraphQL leaf type.`, + ); + return type; +} + +/** + * These types may describe the parent context of a selection set. + */ +export type GraphQLCompositeType = + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType; + +export function isCompositeType(type: mixed): boolean %checks { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} + +export function assertCompositeType(type: mixed): GraphQLCompositeType { + invariant( + isCompositeType(type), + `Expected ${inspect(type)} to be a GraphQL composite type.`, + ); + return type; +} + +/** + * These types may describe the parent context of a selection set. + */ +export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; + +export function isAbstractType(type: mixed): boolean %checks { + return isInterfaceType(type) || isUnionType(type); +} + +export function assertAbstractType(type: mixed): GraphQLAbstractType { + invariant( + isAbstractType(type), + `Expected ${inspect(type)} to be a GraphQL abstract type.`, + ); + return type; +} + +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: GraphQLList(PersonType) }, + * children: { type: GraphQLList(PersonType) }, + * }) + * }) + * + */ +declare class GraphQLList<+T: GraphQLType> { + +ofType: T; + static (ofType: T): GraphQLList; + // Note: constructors cannot be used for covariant types. Drop the "new". + constructor(ofType: GraphQLType): void; +} +// eslint-disable-next-line no-redeclare +export function GraphQLList(ofType) { + if (this instanceof GraphQLList) { + this.ofType = assertType(ofType); + } else { + return new GraphQLList(ofType); + } +} + +// Need to cast through any to alter the prototype. +(GraphQLList.prototype: any).toString = function toString() { + return '[' + String(this.ofType) + ']'; +}; +defineToJSON(GraphQLList); + +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ +declare class GraphQLNonNull<+T: GraphQLNullableType> { + +ofType: T; + static (ofType: T): GraphQLNonNull; + // Note: constructors cannot be used for covariant types. Drop the "new". + constructor(ofType: GraphQLType): void; +} +// eslint-disable-next-line no-redeclare +export function GraphQLNonNull(ofType) { + if (this instanceof GraphQLNonNull) { + this.ofType = assertNullableType(ofType); + } else { + return new GraphQLNonNull(ofType); + } +} + +// Need to cast through any to alter the prototype. +(GraphQLNonNull.prototype: any).toString = function toString() { + return String(this.ofType) + '!'; +}; +defineToJSON(GraphQLNonNull); + +/** + * These types wrap and modify other types + */ + +export type GraphQLWrappingType = GraphQLList | GraphQLNonNull; + +export function isWrappingType(type: mixed): boolean %checks { + return isListType(type) || isNonNullType(type); +} + +export function assertWrappingType(type: mixed): GraphQLWrappingType { + invariant( + isWrappingType(type), + `Expected ${inspect(type)} to be a GraphQL wrapping type.`, + ); + return type; +} + +/** + * These types can all accept null as a value. + */ +export type GraphQLNullableType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList; + +export function isNullableType(type: mixed): boolean %checks { + return isType(type) && !isNonNullType(type); +} + +export function assertNullableType(type: mixed): GraphQLNullableType { + invariant( + isNullableType(type), + `Expected ${inspect(type)} to be a GraphQL nullable type.`, + ); + return type; +} + +/* eslint-disable no-redeclare */ +declare function getNullableType(type: void | null): void; +declare function getNullableType(type: T): T; +declare function getNullableType(type: GraphQLNonNull): T; +export function getNullableType(type) { + /* eslint-enable no-redeclare */ + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} + +/** + * These named types do not include modifiers like List or NonNull. + */ +export type GraphQLNamedType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType; + +export function isNamedType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) + ); +} + +export function assertNamedType(type: mixed): GraphQLNamedType { + invariant( + isNamedType(type), + `Expected ${inspect(type)} to be a GraphQL named type.`, + ); + return type; +} + +/* eslint-disable no-redeclare */ +declare function getNamedType(type: void | null): void; +declare function getNamedType(type: GraphQLType): GraphQLNamedType; +export function getNamedType(type) { + /* eslint-enable no-redeclare */ + if (type) { + let unwrappedType = type; + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + return unwrappedType; + } +} + +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ +export type Thunk<+T> = (() => T) | T; + +function resolveThunk<+T>(thunk: Thunk): T { + return typeof thunk === 'function' ? thunk() : thunk; +} + +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function does not return a value (i.e. it returns + * `undefined`) then an error will be raised and a `null` value will be returned + * in the response. If the serialize function returns `null`, then no error will + * be included in the response. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (value % 2 === 1) { + * return value; + * } + * } + * }); + * + */ +export class GraphQLScalarType { + name: string; + description: ?string; + serialize: GraphQLScalarSerializer<*>; + parseValue: GraphQLScalarValueParser<*>; + parseLiteral: GraphQLScalarLiteralParser<*>; + astNode: ?ScalarTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + + constructor(config: GraphQLScalarTypeConfig<*, *>): void { + this.name = config.name; + this.description = config.description; + this.serialize = config.serialize; + this.parseValue = config.parseValue || (value => value); + this.parseLiteral = config.parseLiteral || valueFromASTUntyped; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + invariant(typeof config.name === 'string', 'Must provide name.'); + invariant( + typeof config.serialize === 'function', + `${this.name} must provide "serialize" function. If this custom Scalar ` + + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + + 'functions are also provided.', + ); + if (config.parseValue || config.parseLiteral) { + invariant( + typeof config.parseValue === 'function' && + typeof config.parseLiteral === 'function', + `${this.name} must provide both "parseValue" and "parseLiteral" ` + + 'functions.', + ); + } + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLScalarType); +defineToJSON(GraphQLScalarType); + +export type GraphQLScalarSerializer = (value: mixed) => ?TExternal; +export type GraphQLScalarValueParser = (value: mixed) => ?TInternal; +export type GraphQLScalarLiteralParser = ( + valueNode: ValueNode, + variables: ?ObjMap, +) => ?TInternal; + +export type GraphQLScalarTypeConfig = {| + name: string, + description?: ?string, + // Serializes an internal value to include in a response. + serialize: GraphQLScalarSerializer, + // Parses an externally provided value to use as an input. + parseValue?: GraphQLScalarValueParser, + // Parses an externally provided literal value to use as an input. + parseLiteral?: GraphQLScalarLiteralParser, + astNode?: ?ScalarTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * + */ +export class GraphQLObjectType { + name: string; + description: ?string; + astNode: ?ObjectTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + isTypeOf: ?GraphQLIsTypeOfFn<*, *>; + + _fields: Thunk>; + _interfaces: Thunk>; + + constructor(config: GraphQLObjectTypeConfig<*, *>): void { + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.isTypeOf = config.isTypeOf; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + invariant(typeof config.name === 'string', 'Must provide name.'); + invariant( + config.isTypeOf == null || typeof config.isTypeOf === 'function', + `${this.name} must provide "isTypeOf" as a function, ` + + `but got: ${inspect(config.isTypeOf)}.`, + ); + } + + getFields(): GraphQLFieldMap<*, *> { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + + getInterfaces(): Array { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLObjectType); +defineToJSON(GraphQLObjectType); + +function defineInterfaces( + config: GraphQLObjectTypeConfig<*, *>, +): Array { + const interfaces = resolveThunk(config.interfaces) || []; + invariant( + Array.isArray(interfaces), + `${config.name} interfaces must be an Array or a function which returns ` + + 'an Array.', + ); + return interfaces; +} + +function defineFieldMap( + config: + | GraphQLObjectTypeConfig + | GraphQLInterfaceTypeConfig, +): GraphQLFieldMap { + const fieldMap = resolveThunk(config.fields) || {}; + invariant( + isPlainObj(fieldMap), + `${config.name} fields must be an object with field names as keys or a ` + + 'function which returns such an object.', + ); + + const resultFieldMap = Object.create(null); + for (const fieldName of Object.keys(fieldMap)) { + const fieldConfig = fieldMap[fieldName]; + invariant( + isPlainObj(fieldConfig), + `${config.name}.${fieldName} field config must be an object`, + ); + invariant( + !fieldConfig.hasOwnProperty('isDeprecated'), + `${config.name}.${fieldName} should provide "deprecationReason" ` + + 'instead of "isDeprecated".', + ); + const field = { + ...fieldConfig, + isDeprecated: Boolean(fieldConfig.deprecationReason), + name: fieldName, + }; + invariant( + field.resolve == null || typeof field.resolve === 'function', + `${config.name}.${fieldName} field resolver must be a function if ` + + `provided, but got: ${inspect(field.resolve)}.`, + ); + const argsConfig = fieldConfig.args; + if (!argsConfig) { + field.args = []; + } else { + invariant( + isPlainObj(argsConfig), + `${config.name}.${fieldName} args must be an object with argument ` + + 'names as keys.', + ); + field.args = Object.keys(argsConfig).map(argName => { + const arg = argsConfig[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode, + }; + }); + } + resultFieldMap[fieldName] = field; + } + return resultFieldMap; +} + +function isPlainObj(obj) { + return obj && typeof obj === 'object' && !Array.isArray(obj); +} + +export type GraphQLObjectTypeConfig = {| + name: string, + interfaces?: Thunk>, + fields: Thunk>, + isTypeOf?: ?GraphQLIsTypeOfFn, + description?: ?string, + astNode?: ?ObjectTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +export type GraphQLTypeResolver = ( + value: TSource, + context: TContext, + info: GraphQLResolveInfo, +) => MaybePromise; + +export type GraphQLIsTypeOfFn = ( + source: TSource, + context: TContext, + info: GraphQLResolveInfo, +) => MaybePromise; + +export type GraphQLFieldResolver< + TSource, + TContext, + TArgs = { [argument: string]: any }, +> = ( + source: TSource, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo, +) => mixed; + +export type GraphQLResolveInfo = {| + +fieldName: string, + +fieldNodes: $ReadOnlyArray, + +returnType: GraphQLOutputType, + +parentType: GraphQLObjectType, + +path: ResponsePath, + +schema: GraphQLSchema, + +fragments: ObjMap, + +rootValue: mixed, + +operation: OperationDefinitionNode, + +variableValues: { [variable: string]: mixed }, +|}; + +export type ResponsePath = {| + +prev: ResponsePath | void, + +key: string | number, +|}; + +export type GraphQLFieldConfig< + TSource, + TContext, + TArgs = { [argument: string]: any }, +> = {| + type: GraphQLOutputType, + args?: GraphQLFieldConfigArgumentMap, + resolve?: GraphQLFieldResolver, + subscribe?: GraphQLFieldResolver, + deprecationReason?: ?string, + description?: ?string, + astNode?: ?FieldDefinitionNode, +|}; + +export type GraphQLFieldConfigArgumentMap = ObjMap; + +export type GraphQLArgumentConfig = {| + type: GraphQLInputType, + defaultValue?: mixed, + description?: ?string, + astNode?: ?InputValueDefinitionNode, +|}; + +export type GraphQLFieldConfigMap = ObjMap< + GraphQLFieldConfig, +>; + +export type GraphQLField< + TSource, + TContext, + TArgs = { [argument: string]: any }, +> = { + name: string, + description: ?string, + type: GraphQLOutputType, + args: Array, + resolve?: GraphQLFieldResolver, + subscribe?: GraphQLFieldResolver, + isDeprecated?: boolean, + deprecationReason?: ?string, + astNode?: ?FieldDefinitionNode, +}; + +export type GraphQLArgument = { + name: string, + type: GraphQLInputType, + defaultValue?: mixed, + description?: ?string, + astNode?: ?InputValueDefinitionNode, +}; + +export function isRequiredArgument(arg: GraphQLArgument): boolean %checks { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} + +export type GraphQLFieldMap = ObjMap< + GraphQLField, +>; + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * + */ +export class GraphQLInterfaceType { + name: string; + description: ?string; + astNode: ?InterfaceTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + resolveType: ?GraphQLTypeResolver<*, *>; + + _fields: Thunk>; + + constructor(config: GraphQLInterfaceTypeConfig<*, *>): void { + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._fields = defineFieldMap.bind(undefined, config); + invariant(typeof config.name === 'string', 'Must provide name.'); + invariant( + config.resolveType == null || typeof config.resolveType === 'function', + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${inspect(config.resolveType)}.`, + ); + } + + getFields(): GraphQLFieldMap<*, *> { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLInterfaceType); +defineToJSON(GraphQLInterfaceType); + +export type GraphQLInterfaceTypeConfig = {| + name: string, + fields: Thunk>, + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: ?GraphQLTypeResolver, + description?: ?string, + astNode?: ?InterfaceTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * + */ +export class GraphQLUnionType { + name: string; + description: ?string; + astNode: ?UnionTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + resolveType: ?GraphQLTypeResolver<*, *>; + + _types: Thunk>; + + constructor(config: GraphQLUnionTypeConfig<*, *>): void { + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._types = defineTypes.bind(undefined, config); + invariant(typeof config.name === 'string', 'Must provide name.'); + invariant( + config.resolveType == null || typeof config.resolveType === 'function', + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${inspect(config.resolveType)}.`, + ); + } + + getTypes(): Array { + if (typeof this._types === 'function') { + this._types = this._types(); + } + return this._types; + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLUnionType); +defineToJSON(GraphQLUnionType); + +function defineTypes( + config: GraphQLUnionTypeConfig<*, *>, +): Array { + const types = resolveThunk(config.types) || []; + invariant( + Array.isArray(types), + 'Must provide Array of types or a function which returns ' + + `such an array for Union ${config.name}.`, + ); + return types; +} + +export type GraphQLUnionTypeConfig = {| + name: string, + types: Thunk>, + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: ?GraphQLTypeResolver, + description?: ?string, + astNode?: ?UnionTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +export class GraphQLEnumType /* */ { + name: string; + description: ?string; + astNode: ?EnumTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + + _values: Array */>; + _valueLookup: Map; + _nameLookup: ObjMap; + + constructor(config: GraphQLEnumTypeConfig /* */): void { + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._values = defineEnumValues(this, config.values); + this._valueLookup = new Map( + this._values.map(enumValue => [enumValue.value, enumValue]), + ); + this._nameLookup = keyMap(this._values, value => value.name); + + invariant(typeof config.name === 'string', 'Must provide name.'); + } + + getValues(): Array */> { + return this._values; + } + + getValue(name: string): ?GraphQLEnumValue { + return this._nameLookup[name]; + } + + serialize(value: mixed /* T */): ?string { + const enumValue = this._valueLookup.get(value); + if (enumValue) { + return enumValue.name; + } + } + + parseValue(value: mixed): ?any /* T */ { + if (typeof value === 'string') { + const enumValue = this.getValue(value); + if (enumValue) { + return enumValue.value; + } + } + } + + parseLiteral(valueNode: ValueNode, _variables: ?ObjMap): ?any /* T */ { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind === Kind.ENUM) { + const enumValue = this.getValue(valueNode.value); + if (enumValue) { + return enumValue.value; + } + } + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLEnumType); +defineToJSON(GraphQLEnumType); + +function defineEnumValues( + type: GraphQLEnumType, + valueMap: GraphQLEnumValueConfigMap /* */, +): Array */> { + invariant( + isPlainObj(valueMap), + `${type.name} values must be an object with value names as keys.`, + ); + return Object.keys(valueMap).map(valueName => { + const value = valueMap[valueName]; + invariant( + isPlainObj(value), + `${type.name}.${valueName} must refer to an object with a "value" key ` + + `representing an internal value but got: ${inspect(value)}.`, + ); + invariant( + !value.hasOwnProperty('isDeprecated'), + `${type.name}.${valueName} should provide "deprecationReason" instead ` + + 'of "isDeprecated".', + ); + return { + name: valueName, + description: value.description, + isDeprecated: Boolean(value.deprecationReason), + deprecationReason: value.deprecationReason, + astNode: value.astNode, + value: value.hasOwnProperty('value') ? value.value : valueName, + }; + }); +} + +export type GraphQLEnumTypeConfig /* */ = {| + name: string, + values: GraphQLEnumValueConfigMap /* */, + description?: ?string, + astNode?: ?EnumTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +export type GraphQLEnumValueConfigMap /* */ = ObjMap< + GraphQLEnumValueConfig /* */, +>; + +export type GraphQLEnumValueConfig /* */ = {| + value?: any /* T */, + deprecationReason?: ?string, + description?: ?string, + astNode?: ?EnumValueDefinitionNode, +|}; + +export type GraphQLEnumValue /* */ = { + name: string, + description: ?string, + isDeprecated?: boolean, + deprecationReason: ?string, + astNode?: ?EnumValueDefinitionNode, + value: any /* T */, +}; + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: GraphQLNonNull(GraphQLFloat) }, + * lon: { type: GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +export class GraphQLInputObjectType { + name: string; + description: ?string; + astNode: ?InputObjectTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + + _fields: Thunk; + + constructor(config: GraphQLInputObjectTypeConfig): void { + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._fields = defineInputFieldMap.bind(undefined, config); + invariant(typeof config.name === 'string', 'Must provide name.'); + } + + getFields(): GraphQLInputFieldMap { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLInputObjectType); +defineToJSON(GraphQLInputObjectType); + +function defineInputFieldMap( + config: GraphQLInputObjectTypeConfig, +): GraphQLInputFieldMap { + const fieldMap = resolveThunk(config.fields) || {}; + invariant( + isPlainObj(fieldMap), + `${config.name} fields must be an object with field names as keys or a ` + + 'function which returns such an object.', + ); + const resultFieldMap = Object.create(null); + for (const fieldName of Object.keys(fieldMap)) { + const field = { + ...fieldMap[fieldName], + name: fieldName, + }; + invariant( + !field.hasOwnProperty('resolve'), + `${config.name}.${fieldName} field has a resolve property, but ` + + 'Input Types cannot define resolvers.', + ); + resultFieldMap[fieldName] = field; + } + return resultFieldMap; +} + +export type GraphQLInputObjectTypeConfig = {| + name: string, + fields: Thunk, + description?: ?string, + astNode?: ?InputObjectTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +export type GraphQLInputFieldConfig = {| + type: GraphQLInputType, + defaultValue?: mixed, + description?: ?string, + astNode?: ?InputValueDefinitionNode, +|}; + +export type GraphQLInputFieldConfigMap = ObjMap; + +export type GraphQLInputField = { + name: string, + type: GraphQLInputType, + defaultValue?: mixed, + description?: ?string, + astNode?: ?InputValueDefinitionNode, +}; + +export function isRequiredInputField( + field: GraphQLInputField, +): boolean %checks { + return isNonNullType(field.type) && field.defaultValue === undefined; +} + +export type GraphQLInputFieldMap = ObjMap; diff --git a/node_modules/graphql/type/definition.mjs b/node_modules/graphql/type/definition.mjs new file mode 100644 index 0000000..b37bf3e --- /dev/null +++ b/node_modules/graphql/type/definition.mjs @@ -0,0 +1,869 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import defineToJSON from '../jsutils/defineToJSON'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import instanceOf from '../jsutils/instanceOf'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import { Kind } from '../language/kinds'; +import { valueFromASTUntyped } from '../utilities/valueFromASTUntyped'; +export function isType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type); +} +export function assertType(type) { + !isType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL type.")) : void 0; + return type; +} +/** + * There are predicates for each kind of GraphQL type. + */ + +// eslint-disable-next-line no-redeclare +export function isScalarType(type) { + return instanceOf(type, GraphQLScalarType); +} +export function assertScalarType(type) { + !isScalarType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Scalar type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isObjectType(type) { + return instanceOf(type, GraphQLObjectType); +} +export function assertObjectType(type) { + !isObjectType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Object type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isInterfaceType(type) { + return instanceOf(type, GraphQLInterfaceType); +} +export function assertInterfaceType(type) { + !isInterfaceType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Interface type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isUnionType(type) { + return instanceOf(type, GraphQLUnionType); +} +export function assertUnionType(type) { + !isUnionType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Union type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isEnumType(type) { + return instanceOf(type, GraphQLEnumType); +} +export function assertEnumType(type) { + !isEnumType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Enum type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isInputObjectType(type) { + return instanceOf(type, GraphQLInputObjectType); +} +export function assertInputObjectType(type) { + !isInputObjectType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Input Object type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isListType(type) { + return instanceOf(type, GraphQLList); +} +export function assertListType(type) { + !isListType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL List type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isNonNullType(type) { + return instanceOf(type, GraphQLNonNull); +} +export function assertNonNullType(type) { + !isNonNullType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Non-Null type.")) : void 0; + return type; +} +/** + * These types may be used as input types for arguments and directives. + */ + +export function isInputType(type) { + return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType); +} +export function assertInputType(type) { + !isInputType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL input type.")) : void 0; + return type; +} +/** + * These types may be used as output types as the result of fields. + */ + +export function isOutputType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType); +} +export function assertOutputType(type) { + !isOutputType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL output type.")) : void 0; + return type; +} +/** + * These types may describe types which may be leaf values. + */ + +export function isLeafType(type) { + return isScalarType(type) || isEnumType(type); +} +export function assertLeafType(type) { + !isLeafType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL leaf type.")) : void 0; + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + +export function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} +export function assertCompositeType(type) { + !isCompositeType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL composite type.")) : void 0; + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + +export function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); +} +export function assertAbstractType(type) { + !isAbstractType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL abstract type.")) : void 0; + return type; +} +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: GraphQLList(PersonType) }, + * children: { type: GraphQLList(PersonType) }, + * }) + * }) + * + */ + +// eslint-disable-next-line no-redeclare +export function GraphQLList(ofType) { + if (this instanceof GraphQLList) { + this.ofType = assertType(ofType); + } else { + return new GraphQLList(ofType); + } +} // Need to cast through any to alter the prototype. + +GraphQLList.prototype.toString = function toString() { + return '[' + String(this.ofType) + ']'; +}; + +defineToJSON(GraphQLList); +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ + +// eslint-disable-next-line no-redeclare +export function GraphQLNonNull(ofType) { + if (this instanceof GraphQLNonNull) { + this.ofType = assertNullableType(ofType); + } else { + return new GraphQLNonNull(ofType); + } +} // Need to cast through any to alter the prototype. + +GraphQLNonNull.prototype.toString = function toString() { + return String(this.ofType) + '!'; +}; + +defineToJSON(GraphQLNonNull); +/** + * These types wrap and modify other types + */ + +export function isWrappingType(type) { + return isListType(type) || isNonNullType(type); +} +export function assertWrappingType(type) { + !isWrappingType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL wrapping type.")) : void 0; + return type; +} +/** + * These types can all accept null as a value. + */ + +export function isNullableType(type) { + return isType(type) && !isNonNullType(type); +} +export function assertNullableType(type) { + !isNullableType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL nullable type.")) : void 0; + return type; +} +/* eslint-disable no-redeclare */ + +export function getNullableType(type) { + /* eslint-enable no-redeclare */ + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} +/** + * These named types do not include modifiers like List or NonNull. + */ + +export function isNamedType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type); +} +export function assertNamedType(type) { + !isNamedType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL named type.")) : void 0; + return type; +} +/* eslint-disable no-redeclare */ + +export function getNamedType(type) { + /* eslint-enable no-redeclare */ + if (type) { + var unwrappedType = type; + + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + + return unwrappedType; + } +} +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ + +function resolveThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function does not return a value (i.e. it returns + * `undefined`) then an error will be raised and a `null` value will be returned + * in the response. If the serialize function returns `null`, then no error will + * be included in the response. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (value % 2 === 1) { + * return value; + * } + * } + * }); + * + */ + + +export var GraphQLScalarType = +/*#__PURE__*/ +function () { + function GraphQLScalarType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "serialize", void 0); + + _defineProperty(this, "parseValue", void 0); + + _defineProperty(this, "parseLiteral", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + this.name = config.name; + this.description = config.description; + this.serialize = config.serialize; + + this.parseValue = config.parseValue || function (value) { + return value; + }; + + this.parseLiteral = config.parseLiteral || valueFromASTUntyped; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + !(typeof config.serialize === 'function') ? invariant(0, "".concat(this.name, " must provide \"serialize\" function. If this custom Scalar ") + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.') : void 0; + + if (config.parseValue || config.parseLiteral) { + !(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function') ? invariant(0, "".concat(this.name, " must provide both \"parseValue\" and \"parseLiteral\" ") + 'functions.') : void 0; + } + } + + var _proto = GraphQLScalarType.prototype; + + _proto.toString = function toString() { + return this.name; + }; + + return GraphQLScalarType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLScalarType); +defineToJSON(GraphQLScalarType); + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * + */ +export var GraphQLObjectType = +/*#__PURE__*/ +function () { + function GraphQLObjectType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "isTypeOf", void 0); + + _defineProperty(this, "_fields", void 0); + + _defineProperty(this, "_interfaces", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.isTypeOf = config.isTypeOf; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + !(config.isTypeOf == null || typeof config.isTypeOf === 'function') ? invariant(0, "".concat(this.name, " must provide \"isTypeOf\" as a function, ") + "but got: ".concat(inspect(config.isTypeOf), ".")) : void 0; + } + + var _proto2 = GraphQLObjectType.prototype; + + _proto2.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto2.getInterfaces = function getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + }; + + _proto2.toString = function toString() { + return this.name; + }; + + return GraphQLObjectType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLObjectType); +defineToJSON(GraphQLObjectType); + +function defineInterfaces(config) { + var interfaces = resolveThunk(config.interfaces) || []; + !Array.isArray(interfaces) ? invariant(0, "".concat(config.name, " interfaces must be an Array or a function which returns ") + 'an Array.') : void 0; + return interfaces; +} + +function defineFieldMap(config) { + var fieldMap = resolveThunk(config.fields) || {}; + !isPlainObj(fieldMap) ? invariant(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0; + var resultFieldMap = Object.create(null); + + var _arr = Object.keys(fieldMap); + + var _loop = function _loop() { + var fieldName = _arr[_i]; + var fieldConfig = fieldMap[fieldName]; + !isPlainObj(fieldConfig) ? invariant(0, "".concat(config.name, ".").concat(fieldName, " field config must be an object")) : void 0; + !!fieldConfig.hasOwnProperty('isDeprecated') ? invariant(0, "".concat(config.name, ".").concat(fieldName, " should provide \"deprecationReason\" ") + 'instead of "isDeprecated".') : void 0; + + var field = _objectSpread({}, fieldConfig, { + isDeprecated: Boolean(fieldConfig.deprecationReason), + name: fieldName + }); + + !(field.resolve == null || typeof field.resolve === 'function') ? invariant(0, "".concat(config.name, ".").concat(fieldName, " field resolver must be a function if ") + "provided, but got: ".concat(inspect(field.resolve), ".")) : void 0; + var argsConfig = fieldConfig.args; + + if (!argsConfig) { + field.args = []; + } else { + !isPlainObj(argsConfig) ? invariant(0, "".concat(config.name, ".").concat(fieldName, " args must be an object with argument ") + 'names as keys.') : void 0; + field.args = Object.keys(argsConfig).map(function (argName) { + var arg = argsConfig[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode + }; + }); + } + + resultFieldMap[fieldName] = field; + }; + + for (var _i = 0; _i < _arr.length; _i++) { + _loop(); + } + + return resultFieldMap; +} + +function isPlainObj(obj) { + return obj && _typeof(obj) === 'object' && !Array.isArray(obj); +} + +export function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * + */ +export var GraphQLInterfaceType = +/*#__PURE__*/ +function () { + function GraphQLInterfaceType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "resolveType", void 0); + + _defineProperty(this, "_fields", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._fields = defineFieldMap.bind(undefined, config); + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + !(config.resolveType == null || typeof config.resolveType === 'function') ? invariant(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), ".")) : void 0; + } + + var _proto3 = GraphQLInterfaceType.prototype; + + _proto3.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto3.toString = function toString() { + return this.name; + }; + + return GraphQLInterfaceType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLInterfaceType); +defineToJSON(GraphQLInterfaceType); + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * + */ +export var GraphQLUnionType = +/*#__PURE__*/ +function () { + function GraphQLUnionType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "resolveType", void 0); + + _defineProperty(this, "_types", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._types = defineTypes.bind(undefined, config); + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + !(config.resolveType == null || typeof config.resolveType === 'function') ? invariant(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), ".")) : void 0; + } + + var _proto4 = GraphQLUnionType.prototype; + + _proto4.getTypes = function getTypes() { + if (typeof this._types === 'function') { + this._types = this._types(); + } + + return this._types; + }; + + _proto4.toString = function toString() { + return this.name; + }; + + return GraphQLUnionType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLUnionType); +defineToJSON(GraphQLUnionType); + +function defineTypes(config) { + var types = resolveThunk(config.types) || []; + !Array.isArray(types) ? invariant(0, 'Must provide Array of types or a function which returns ' + "such an array for Union ".concat(config.name, ".")) : void 0; + return types; +} + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +export var GraphQLEnumType +/* */ += +/*#__PURE__*/ +function () { + function GraphQLEnumType(config + /* */ + ) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_values", void 0); + + _defineProperty(this, "_valueLookup", void 0); + + _defineProperty(this, "_nameLookup", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._values = defineEnumValues(this, config.values); + this._valueLookup = new Map(this._values.map(function (enumValue) { + return [enumValue.value, enumValue]; + })); + this._nameLookup = keyMap(this._values, function (value) { + return value.name; + }); + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + } + + var _proto5 = GraphQLEnumType.prototype; + + _proto5.getValues = function getValues() { + return this._values; + }; + + _proto5.getValue = function getValue(name) { + return this._nameLookup[name]; + }; + + _proto5.serialize = function serialize(value + /* T */ + ) { + var enumValue = this._valueLookup.get(value); + + if (enumValue) { + return enumValue.name; + } + }; + + _proto5.parseValue = function parseValue(value) + /* T */ + { + if (typeof value === 'string') { + var enumValue = this.getValue(value); + + if (enumValue) { + return enumValue.value; + } + } + }; + + _proto5.parseLiteral = function parseLiteral(valueNode, _variables) + /* T */ + { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind === Kind.ENUM) { + var enumValue = this.getValue(valueNode.value); + + if (enumValue) { + return enumValue.value; + } + } + }; + + _proto5.toString = function toString() { + return this.name; + }; + + return GraphQLEnumType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLEnumType); +defineToJSON(GraphQLEnumType); + +function defineEnumValues(type, valueMap +/* */ +) { + !isPlainObj(valueMap) ? invariant(0, "".concat(type.name, " values must be an object with value names as keys.")) : void 0; + return Object.keys(valueMap).map(function (valueName) { + var value = valueMap[valueName]; + !isPlainObj(value) ? invariant(0, "".concat(type.name, ".").concat(valueName, " must refer to an object with a \"value\" key ") + "representing an internal value but got: ".concat(inspect(value), ".")) : void 0; + !!value.hasOwnProperty('isDeprecated') ? invariant(0, "".concat(type.name, ".").concat(valueName, " should provide \"deprecationReason\" instead ") + 'of "isDeprecated".') : void 0; + return { + name: valueName, + description: value.description, + isDeprecated: Boolean(value.deprecationReason), + deprecationReason: value.deprecationReason, + astNode: value.astNode, + value: value.hasOwnProperty('value') ? value.value : valueName + }; + }); +} + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: GraphQLNonNull(GraphQLFloat) }, + * lon: { type: GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +export var GraphQLInputObjectType = +/*#__PURE__*/ +function () { + function GraphQLInputObjectType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_fields", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._fields = defineInputFieldMap.bind(undefined, config); + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + } + + var _proto6 = GraphQLInputObjectType.prototype; + + _proto6.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto6.toString = function toString() { + return this.name; + }; + + return GraphQLInputObjectType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLInputObjectType); +defineToJSON(GraphQLInputObjectType); + +function defineInputFieldMap(config) { + var fieldMap = resolveThunk(config.fields) || {}; + !isPlainObj(fieldMap) ? invariant(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0; + var resultFieldMap = Object.create(null); + + var _arr2 = Object.keys(fieldMap); + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var fieldName = _arr2[_i2]; + + var field = _objectSpread({}, fieldMap[fieldName], { + name: fieldName + }); + + !!field.hasOwnProperty('resolve') ? invariant(0, "".concat(config.name, ".").concat(fieldName, " field has a resolve property, but ") + 'Input Types cannot define resolvers.') : void 0; + resultFieldMap[fieldName] = field; + } + + return resultFieldMap; +} + +export function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; +} \ No newline at end of file diff --git a/node_modules/graphql/type/directives.js b/node_modules/graphql/type/directives.js new file mode 100644 index 0000000..eecadc9 --- /dev/null +++ b/node_modules/graphql/type/directives.js @@ -0,0 +1,156 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isDirective = isDirective; +exports.isSpecifiedDirective = isSpecifiedDirective; +exports.specifiedDirectives = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = void 0; + +var _definition = require("./definition"); + +var _scalars = require("./scalars"); + +var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag")); + +var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON")); + +var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _directiveLocation = require("../language/directiveLocation"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +// eslint-disable-next-line no-redeclare +function isDirective(directive) { + return (0, _instanceOf.default)(directive, GraphQLDirective); +} +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ + + +var GraphQLDirective = +/*#__PURE__*/ +function () { + function GraphQLDirective(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "locations", void 0); + + _defineProperty(this, "args", void 0); + + _defineProperty(this, "astNode", void 0); + + this.name = config.name; + this.description = config.description; + this.locations = config.locations; + this.astNode = config.astNode; + !config.name ? (0, _invariant.default)(0, 'Directive must be named.') : void 0; + !Array.isArray(config.locations) ? (0, _invariant.default)(0, 'Must provide locations for directive.') : void 0; + var args = config.args; + + if (!args) { + this.args = []; + } else { + !!Array.isArray(args) ? (0, _invariant.default)(0, "@".concat(config.name, " args must be an object with argument names as keys.")) : void 0; + this.args = Object.keys(args).map(function (argName) { + var arg = args[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode + }; + }); + } + } + + var _proto = GraphQLDirective.prototype; + + _proto.toString = function toString() { + return '@' + this.name; + }; + + return GraphQLDirective; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLDirective = GraphQLDirective; +(0, _defineToStringTag.default)(GraphQLDirective); +(0, _defineToJSON.default)(GraphQLDirective); + +/** + * Used to conditionally include fields or fragments. + */ +var GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: 'Directs the executor to include this field or fragment only when ' + 'the `if` argument is true.', + locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean), + description: 'Included when true.' + } + } +}); +/** + * Used to conditionally skip (exclude) fields or fragments. + */ + +exports.GraphQLIncludeDirective = GraphQLIncludeDirective; +var GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: 'Directs the executor to skip this field or fragment when the `if` ' + 'argument is true.', + locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean), + description: 'Skipped when true.' + } + } +}); +/** + * Constant string used for default reason for a deprecation. + */ + +exports.GraphQLSkipDirective = GraphQLSkipDirective; +var DEFAULT_DEPRECATION_REASON = 'No longer supported'; +/** + * Used to declare element of a GraphQL schema as deprecated. + */ + +exports.DEFAULT_DEPRECATION_REASON = DEFAULT_DEPRECATION_REASON; +var GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [_directiveLocation.DirectiveLocation.FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ENUM_VALUE], + args: { + reason: { + type: _scalars.GraphQLString, + description: 'Explains why this element was deprecated, usually also including a ' + 'suggestion for how to access supported similar data. Formatted using ' + 'the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON + } + } +}); +/** + * The full list of specified directives. + */ + +exports.GraphQLDeprecatedDirective = GraphQLDeprecatedDirective; +var specifiedDirectives = [GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective]; +exports.specifiedDirectives = specifiedDirectives; + +function isSpecifiedDirective(directive) { + return specifiedDirectives.some(function (specifiedDirective) { + return specifiedDirective.name === directive.name; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/type/directives.js.flow b/node_modules/graphql/type/directives.js.flow new file mode 100644 index 0000000..e8a7b74 --- /dev/null +++ b/node_modules/graphql/type/directives.js.flow @@ -0,0 +1,178 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { + GraphQLFieldConfigArgumentMap, + GraphQLArgument, +} from './definition'; +import { GraphQLNonNull } from './definition'; +import { GraphQLString, GraphQLBoolean } from './scalars'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import defineToJSON from '../jsutils/defineToJSON'; +import instanceOf from '../jsutils/instanceOf'; +import invariant from '../jsutils/invariant'; +import type { DirectiveDefinitionNode } from '../language/ast'; +import { + DirectiveLocation, + type DirectiveLocationEnum, +} from '../language/directiveLocation'; + +/** + * Test if the given value is a GraphQL directive. + */ +declare function isDirective( + directive: mixed, +): boolean %checks(directive instanceof GraphQLDirective); +// eslint-disable-next-line no-redeclare +export function isDirective(directive) { + return instanceOf(directive, GraphQLDirective); +} + +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ +export class GraphQLDirective { + name: string; + description: ?string; + locations: Array; + args: Array; + astNode: ?DirectiveDefinitionNode; + + constructor(config: GraphQLDirectiveConfig): void { + this.name = config.name; + this.description = config.description; + this.locations = config.locations; + this.astNode = config.astNode; + invariant(config.name, 'Directive must be named.'); + invariant( + Array.isArray(config.locations), + 'Must provide locations for directive.', + ); + + const args = config.args; + if (!args) { + this.args = []; + } else { + invariant( + !Array.isArray(args), + `@${config.name} args must be an object with argument names as keys.`, + ); + this.args = Object.keys(args).map(argName => { + const arg = args[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode, + }; + }); + } + } + + toString(): string { + return '@' + this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLDirective); +defineToJSON(GraphQLDirective); + +export type GraphQLDirectiveConfig = {| + name: string, + description?: ?string, + locations: Array, + args?: ?GraphQLFieldConfigArgumentMap, + astNode?: ?DirectiveDefinitionNode, +|}; + +/** + * Used to conditionally include fields or fragments. + */ +export const GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: + 'Directs the executor to include this field or fragment only when ' + + 'the `if` argument is true.', + locations: [ + DirectiveLocation.FIELD, + DirectiveLocation.FRAGMENT_SPREAD, + DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: GraphQLNonNull(GraphQLBoolean), + description: 'Included when true.', + }, + }, +}); + +/** + * Used to conditionally skip (exclude) fields or fragments. + */ +export const GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: + 'Directs the executor to skip this field or fragment when the `if` ' + + 'argument is true.', + locations: [ + DirectiveLocation.FIELD, + DirectiveLocation.FRAGMENT_SPREAD, + DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: GraphQLNonNull(GraphQLBoolean), + description: 'Skipped when true.', + }, + }, +}); + +/** + * Constant string used for default reason for a deprecation. + */ +export const DEFAULT_DEPRECATION_REASON = 'No longer supported'; + +/** + * Used to declare element of a GraphQL schema as deprecated. + */ +export const GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.ENUM_VALUE], + args: { + reason: { + type: GraphQLString, + description: + 'Explains why this element was deprecated, usually also including a ' + + 'suggestion for how to access supported similar data. Formatted using ' + + 'the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON, + }, + }, +}); + +/** + * The full list of specified directives. + */ +export const specifiedDirectives: $ReadOnlyArray<*> = [ + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, +]; + +export function isSpecifiedDirective( + directive: GraphQLDirective, +): boolean %checks { + return specifiedDirectives.some( + specifiedDirective => specifiedDirective.name === directive.name, + ); +} diff --git a/node_modules/graphql/type/directives.mjs b/node_modules/graphql/type/directives.mjs new file mode 100644 index 0000000..b0629e5 --- /dev/null +++ b/node_modules/graphql/type/directives.mjs @@ -0,0 +1,141 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLNonNull } from './definition'; +import { GraphQLString, GraphQLBoolean } from './scalars'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import defineToJSON from '../jsutils/defineToJSON'; +import instanceOf from '../jsutils/instanceOf'; +import invariant from '../jsutils/invariant'; +import { DirectiveLocation } from '../language/directiveLocation'; +/** + * Test if the given value is a GraphQL directive. + */ + +// eslint-disable-next-line no-redeclare +export function isDirective(directive) { + return instanceOf(directive, GraphQLDirective); +} +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ + +export var GraphQLDirective = +/*#__PURE__*/ +function () { + function GraphQLDirective(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "locations", void 0); + + _defineProperty(this, "args", void 0); + + _defineProperty(this, "astNode", void 0); + + this.name = config.name; + this.description = config.description; + this.locations = config.locations; + this.astNode = config.astNode; + !config.name ? invariant(0, 'Directive must be named.') : void 0; + !Array.isArray(config.locations) ? invariant(0, 'Must provide locations for directive.') : void 0; + var args = config.args; + + if (!args) { + this.args = []; + } else { + !!Array.isArray(args) ? invariant(0, "@".concat(config.name, " args must be an object with argument names as keys.")) : void 0; + this.args = Object.keys(args).map(function (argName) { + var arg = args[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode + }; + }); + } + } + + var _proto = GraphQLDirective.prototype; + + _proto.toString = function toString() { + return '@' + this.name; + }; + + return GraphQLDirective; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLDirective); +defineToJSON(GraphQLDirective); + +/** + * Used to conditionally include fields or fragments. + */ +export var GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: 'Directs the executor to include this field or fragment only when ' + 'the `if` argument is true.', + locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: GraphQLNonNull(GraphQLBoolean), + description: 'Included when true.' + } + } +}); +/** + * Used to conditionally skip (exclude) fields or fragments. + */ + +export var GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: 'Directs the executor to skip this field or fragment when the `if` ' + 'argument is true.', + locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: GraphQLNonNull(GraphQLBoolean), + description: 'Skipped when true.' + } + } +}); +/** + * Constant string used for default reason for a deprecation. + */ + +export var DEFAULT_DEPRECATION_REASON = 'No longer supported'; +/** + * Used to declare element of a GraphQL schema as deprecated. + */ + +export var GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.ENUM_VALUE], + args: { + reason: { + type: GraphQLString, + description: 'Explains why this element was deprecated, usually also including a ' + 'suggestion for how to access supported similar data. Formatted using ' + 'the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON + } + } +}); +/** + * The full list of specified directives. + */ + +export var specifiedDirectives = [GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective]; +export function isSpecifiedDirective(directive) { + return specifiedDirectives.some(function (specifiedDirective) { + return specifiedDirective.name === directive.name; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/type/index.js b/node_modules/graphql/type/index.js new file mode 100644 index 0000000..d758984 --- /dev/null +++ b/node_modules/graphql/type/index.js @@ -0,0 +1,491 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isSchema", { + enumerable: true, + get: function get() { + return _schema.isSchema; + } +}); +Object.defineProperty(exports, "GraphQLSchema", { + enumerable: true, + get: function get() { + return _schema.GraphQLSchema; + } +}); +Object.defineProperty(exports, "isType", { + enumerable: true, + get: function get() { + return _definition.isType; + } +}); +Object.defineProperty(exports, "isScalarType", { + enumerable: true, + get: function get() { + return _definition.isScalarType; + } +}); +Object.defineProperty(exports, "isObjectType", { + enumerable: true, + get: function get() { + return _definition.isObjectType; + } +}); +Object.defineProperty(exports, "isInterfaceType", { + enumerable: true, + get: function get() { + return _definition.isInterfaceType; + } +}); +Object.defineProperty(exports, "isUnionType", { + enumerable: true, + get: function get() { + return _definition.isUnionType; + } +}); +Object.defineProperty(exports, "isEnumType", { + enumerable: true, + get: function get() { + return _definition.isEnumType; + } +}); +Object.defineProperty(exports, "isInputObjectType", { + enumerable: true, + get: function get() { + return _definition.isInputObjectType; + } +}); +Object.defineProperty(exports, "isListType", { + enumerable: true, + get: function get() { + return _definition.isListType; + } +}); +Object.defineProperty(exports, "isNonNullType", { + enumerable: true, + get: function get() { + return _definition.isNonNullType; + } +}); +Object.defineProperty(exports, "isInputType", { + enumerable: true, + get: function get() { + return _definition.isInputType; + } +}); +Object.defineProperty(exports, "isOutputType", { + enumerable: true, + get: function get() { + return _definition.isOutputType; + } +}); +Object.defineProperty(exports, "isLeafType", { + enumerable: true, + get: function get() { + return _definition.isLeafType; + } +}); +Object.defineProperty(exports, "isCompositeType", { + enumerable: true, + get: function get() { + return _definition.isCompositeType; + } +}); +Object.defineProperty(exports, "isAbstractType", { + enumerable: true, + get: function get() { + return _definition.isAbstractType; + } +}); +Object.defineProperty(exports, "isWrappingType", { + enumerable: true, + get: function get() { + return _definition.isWrappingType; + } +}); +Object.defineProperty(exports, "isNullableType", { + enumerable: true, + get: function get() { + return _definition.isNullableType; + } +}); +Object.defineProperty(exports, "isNamedType", { + enumerable: true, + get: function get() { + return _definition.isNamedType; + } +}); +Object.defineProperty(exports, "isRequiredArgument", { + enumerable: true, + get: function get() { + return _definition.isRequiredArgument; + } +}); +Object.defineProperty(exports, "isRequiredInputField", { + enumerable: true, + get: function get() { + return _definition.isRequiredInputField; + } +}); +Object.defineProperty(exports, "assertType", { + enumerable: true, + get: function get() { + return _definition.assertType; + } +}); +Object.defineProperty(exports, "assertScalarType", { + enumerable: true, + get: function get() { + return _definition.assertScalarType; + } +}); +Object.defineProperty(exports, "assertObjectType", { + enumerable: true, + get: function get() { + return _definition.assertObjectType; + } +}); +Object.defineProperty(exports, "assertInterfaceType", { + enumerable: true, + get: function get() { + return _definition.assertInterfaceType; + } +}); +Object.defineProperty(exports, "assertUnionType", { + enumerable: true, + get: function get() { + return _definition.assertUnionType; + } +}); +Object.defineProperty(exports, "assertEnumType", { + enumerable: true, + get: function get() { + return _definition.assertEnumType; + } +}); +Object.defineProperty(exports, "assertInputObjectType", { + enumerable: true, + get: function get() { + return _definition.assertInputObjectType; + } +}); +Object.defineProperty(exports, "assertListType", { + enumerable: true, + get: function get() { + return _definition.assertListType; + } +}); +Object.defineProperty(exports, "assertNonNullType", { + enumerable: true, + get: function get() { + return _definition.assertNonNullType; + } +}); +Object.defineProperty(exports, "assertInputType", { + enumerable: true, + get: function get() { + return _definition.assertInputType; + } +}); +Object.defineProperty(exports, "assertOutputType", { + enumerable: true, + get: function get() { + return _definition.assertOutputType; + } +}); +Object.defineProperty(exports, "assertLeafType", { + enumerable: true, + get: function get() { + return _definition.assertLeafType; + } +}); +Object.defineProperty(exports, "assertCompositeType", { + enumerable: true, + get: function get() { + return _definition.assertCompositeType; + } +}); +Object.defineProperty(exports, "assertAbstractType", { + enumerable: true, + get: function get() { + return _definition.assertAbstractType; + } +}); +Object.defineProperty(exports, "assertWrappingType", { + enumerable: true, + get: function get() { + return _definition.assertWrappingType; + } +}); +Object.defineProperty(exports, "assertNullableType", { + enumerable: true, + get: function get() { + return _definition.assertNullableType; + } +}); +Object.defineProperty(exports, "assertNamedType", { + enumerable: true, + get: function get() { + return _definition.assertNamedType; + } +}); +Object.defineProperty(exports, "getNullableType", { + enumerable: true, + get: function get() { + return _definition.getNullableType; + } +}); +Object.defineProperty(exports, "getNamedType", { + enumerable: true, + get: function get() { + return _definition.getNamedType; + } +}); +Object.defineProperty(exports, "GraphQLScalarType", { + enumerable: true, + get: function get() { + return _definition.GraphQLScalarType; + } +}); +Object.defineProperty(exports, "GraphQLObjectType", { + enumerable: true, + get: function get() { + return _definition.GraphQLObjectType; + } +}); +Object.defineProperty(exports, "GraphQLInterfaceType", { + enumerable: true, + get: function get() { + return _definition.GraphQLInterfaceType; + } +}); +Object.defineProperty(exports, "GraphQLUnionType", { + enumerable: true, + get: function get() { + return _definition.GraphQLUnionType; + } +}); +Object.defineProperty(exports, "GraphQLEnumType", { + enumerable: true, + get: function get() { + return _definition.GraphQLEnumType; + } +}); +Object.defineProperty(exports, "GraphQLInputObjectType", { + enumerable: true, + get: function get() { + return _definition.GraphQLInputObjectType; + } +}); +Object.defineProperty(exports, "GraphQLList", { + enumerable: true, + get: function get() { + return _definition.GraphQLList; + } +}); +Object.defineProperty(exports, "GraphQLNonNull", { + enumerable: true, + get: function get() { + return _definition.GraphQLNonNull; + } +}); +Object.defineProperty(exports, "isDirective", { + enumerable: true, + get: function get() { + return _directives.isDirective; + } +}); +Object.defineProperty(exports, "GraphQLDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLDirective; + } +}); +Object.defineProperty(exports, "isSpecifiedDirective", { + enumerable: true, + get: function get() { + return _directives.isSpecifiedDirective; + } +}); +Object.defineProperty(exports, "specifiedDirectives", { + enumerable: true, + get: function get() { + return _directives.specifiedDirectives; + } +}); +Object.defineProperty(exports, "GraphQLIncludeDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLIncludeDirective; + } +}); +Object.defineProperty(exports, "GraphQLSkipDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLSkipDirective; + } +}); +Object.defineProperty(exports, "GraphQLDeprecatedDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLDeprecatedDirective; + } +}); +Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", { + enumerable: true, + get: function get() { + return _directives.DEFAULT_DEPRECATION_REASON; + } +}); +Object.defineProperty(exports, "isSpecifiedScalarType", { + enumerable: true, + get: function get() { + return _scalars.isSpecifiedScalarType; + } +}); +Object.defineProperty(exports, "specifiedScalarTypes", { + enumerable: true, + get: function get() { + return _scalars.specifiedScalarTypes; + } +}); +Object.defineProperty(exports, "GraphQLInt", { + enumerable: true, + get: function get() { + return _scalars.GraphQLInt; + } +}); +Object.defineProperty(exports, "GraphQLFloat", { + enumerable: true, + get: function get() { + return _scalars.GraphQLFloat; + } +}); +Object.defineProperty(exports, "GraphQLString", { + enumerable: true, + get: function get() { + return _scalars.GraphQLString; + } +}); +Object.defineProperty(exports, "GraphQLBoolean", { + enumerable: true, + get: function get() { + return _scalars.GraphQLBoolean; + } +}); +Object.defineProperty(exports, "GraphQLID", { + enumerable: true, + get: function get() { + return _scalars.GraphQLID; + } +}); +Object.defineProperty(exports, "TypeKind", { + enumerable: true, + get: function get() { + return _introspection.TypeKind; + } +}); +Object.defineProperty(exports, "isIntrospectionType", { + enumerable: true, + get: function get() { + return _introspection.isIntrospectionType; + } +}); +Object.defineProperty(exports, "introspectionTypes", { + enumerable: true, + get: function get() { + return _introspection.introspectionTypes; + } +}); +Object.defineProperty(exports, "__Schema", { + enumerable: true, + get: function get() { + return _introspection.__Schema; + } +}); +Object.defineProperty(exports, "__Directive", { + enumerable: true, + get: function get() { + return _introspection.__Directive; + } +}); +Object.defineProperty(exports, "__DirectiveLocation", { + enumerable: true, + get: function get() { + return _introspection.__DirectiveLocation; + } +}); +Object.defineProperty(exports, "__Type", { + enumerable: true, + get: function get() { + return _introspection.__Type; + } +}); +Object.defineProperty(exports, "__Field", { + enumerable: true, + get: function get() { + return _introspection.__Field; + } +}); +Object.defineProperty(exports, "__InputValue", { + enumerable: true, + get: function get() { + return _introspection.__InputValue; + } +}); +Object.defineProperty(exports, "__EnumValue", { + enumerable: true, + get: function get() { + return _introspection.__EnumValue; + } +}); +Object.defineProperty(exports, "__TypeKind", { + enumerable: true, + get: function get() { + return _introspection.__TypeKind; + } +}); +Object.defineProperty(exports, "SchemaMetaFieldDef", { + enumerable: true, + get: function get() { + return _introspection.SchemaMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeMetaFieldDef", { + enumerable: true, + get: function get() { + return _introspection.TypeMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeNameMetaFieldDef", { + enumerable: true, + get: function get() { + return _introspection.TypeNameMetaFieldDef; + } +}); +Object.defineProperty(exports, "validateSchema", { + enumerable: true, + get: function get() { + return _validate.validateSchema; + } +}); +Object.defineProperty(exports, "assertValidSchema", { + enumerable: true, + get: function get() { + return _validate.assertValidSchema; + } +}); + +var _schema = require("./schema"); + +var _definition = require("./definition"); + +var _directives = require("./directives"); + +var _scalars = require("./scalars"); + +var _introspection = require("./introspection"); + +var _validate = require("./validate"); \ No newline at end of file diff --git a/node_modules/graphql/type/index.js.flow b/node_modules/graphql/type/index.js.flow new file mode 100644 index 0000000..4868543 --- /dev/null +++ b/node_modules/graphql/type/index.js.flow @@ -0,0 +1,162 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { + // Predicate + isSchema, + // GraphQL Schema definition + GraphQLSchema, +} from './schema'; + +export type { GraphQLSchemaConfig } from './schema'; + +export { + // Predicates + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, + // Assertions + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, + // Un-modifiers + getNullableType, + getNamedType, + // Definitions + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + // Type Wrappers + GraphQLList, + GraphQLNonNull, +} from './definition'; + +export { + // Predicate + isDirective, + // Directives Definition + GraphQLDirective, + // Built-in Directives defined by the Spec + isSpecifiedDirective, + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, +} from './directives'; + +export type { GraphQLDirectiveConfig } from './directives'; + +// Common built-in scalar instances. +export { + isSpecifiedScalarType, + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, +} from './scalars'; + +export { + // "Enum" of Type Kinds + TypeKind, + // GraphQL Types for introspection. + isIntrospectionType, + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from './introspection'; + +export type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + Thunk, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLEnumTypeConfig, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueConfigMap, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldConfigMap, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInterfaceTypeConfig, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLResolveInfo, + ResponsePath, + GraphQLScalarTypeConfig, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from './definition'; + +export { validateSchema, assertValidSchema } from './validate'; diff --git a/node_modules/graphql/type/index.mjs b/node_modules/graphql/type/index.mjs new file mode 100644 index 0000000..47d065a --- /dev/null +++ b/node_modules/graphql/type/index.mjs @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { // Predicate +isSchema, // GraphQL Schema definition +GraphQLSchema } from './schema'; +export { // Predicates +isType, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isListType, isNonNullType, isInputType, isOutputType, isLeafType, isCompositeType, isAbstractType, isWrappingType, isNullableType, isNamedType, isRequiredArgument, isRequiredInputField, // Assertions +assertType, assertScalarType, assertObjectType, assertInterfaceType, assertUnionType, assertEnumType, assertInputObjectType, assertListType, assertNonNullType, assertInputType, assertOutputType, assertLeafType, assertCompositeType, assertAbstractType, assertWrappingType, assertNullableType, assertNamedType, // Un-modifiers +getNullableType, getNamedType, // Definitions +GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, // Type Wrappers +GraphQLList, GraphQLNonNull } from './definition'; +export { // Predicate +isDirective, // Directives Definition +GraphQLDirective, // Built-in Directives defined by the Spec +isSpecifiedDirective, specifiedDirectives, GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, // Constant Deprecation Reason +DEFAULT_DEPRECATION_REASON } from './directives'; +// Common built-in scalar instances. +export { isSpecifiedScalarType, specifiedScalarTypes, GraphQLInt, GraphQLFloat, GraphQLString, GraphQLBoolean, GraphQLID } from './scalars'; +export { // "Enum" of Type Kinds +TypeKind, // GraphQL Types for introspection. +isIntrospectionType, introspectionTypes, __Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind, // Meta-field definitions. +SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from './introspection'; +export { validateSchema, assertValidSchema } from './validate'; \ No newline at end of file diff --git a/node_modules/graphql/type/introspection.js b/node_modules/graphql/type/introspection.js new file mode 100644 index 0000000..a3a1a25 --- /dev/null +++ b/node_modules/graphql/type/introspection.js @@ -0,0 +1,546 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIntrospectionType = isIntrospectionType; +exports.introspectionTypes = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.SchemaMetaFieldDef = exports.__TypeKind = exports.TypeKind = exports.__EnumValue = exports.__InputValue = exports.__Field = exports.__Type = exports.__DirectiveLocation = exports.__Directive = exports.__Schema = void 0; + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _astFromValue = require("../utilities/astFromValue"); + +var _printer = require("../language/printer"); + +var _definition = require("./definition"); + +var _scalars = require("./scalars"); + +var _directiveLocation = require("../language/directiveLocation"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var __Schema = new _definition.GraphQLObjectType({ + name: '__Schema', + description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It ' + 'exposes all available types and directives on the server, as well as ' + 'the entry points for query, mutation, and subscription operations.', + fields: function fields() { + return { + types: { + description: 'A list of all types supported by this server.', + type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type))), + resolve: function resolve(schema) { + return (0, _objectValues.default)(schema.getTypeMap()); + } + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: (0, _definition.GraphQLNonNull)(__Type), + resolve: function resolve(schema) { + return schema.getQueryType(); + } + }, + mutationType: { + description: 'If this server supports mutation, the type that ' + 'mutation operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getMutationType(); + } + }, + subscriptionType: { + description: 'If this server support subscription, the type that ' + 'subscription operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getSubscriptionType(); + } + }, + directives: { + description: 'A list of all directives supported by this server.', + type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Directive))), + resolve: function resolve(schema) { + return schema.getDirectives(); + } + } + }; + } +}); + +exports.__Schema = __Schema; + +var __Directive = new _definition.GraphQLObjectType({ + name: '__Directive', + description: 'A Directive provides a way to describe alternate runtime execution and ' + 'type validation behavior in a GraphQL document.' + "\n\nIn some cases, you need to provide options to alter GraphQL's " + 'execution behavior in ways field arguments will not suffice, such as ' + 'conditionally including or skipping a field. Directives provide this by ' + 'describing additional information to the executor.', + fields: function fields() { + return { + name: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + locations: { + type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__DirectiveLocation))), + resolve: function resolve(obj) { + return obj.locations; + } + }, + args: { + type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue))), + resolve: function resolve(directive) { + return directive.args || []; + } + } + }; + } +}); + +exports.__Directive = __Directive; + +var __DirectiveLocation = new _definition.GraphQLEnumType({ + name: '__DirectiveLocation', + description: 'A Directive can be adjacent to many parts of the GraphQL language, a ' + '__DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: _directiveLocation.DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.' + }, + MUTATION: { + value: _directiveLocation.DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.' + }, + SUBSCRIPTION: { + value: _directiveLocation.DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.' + }, + FIELD: { + value: _directiveLocation.DirectiveLocation.FIELD, + description: 'Location adjacent to a field.' + }, + FRAGMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.' + }, + FRAGMENT_SPREAD: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.' + }, + INLINE_FRAGMENT: { + value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.' + }, + VARIABLE_DEFINITION: { + value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.' + }, + SCHEMA: { + value: _directiveLocation.DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.' + }, + SCALAR: { + value: _directiveLocation.DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.' + }, + OBJECT: { + value: _directiveLocation.DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.' + }, + FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.' + }, + ARGUMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.' + }, + INTERFACE: { + value: _directiveLocation.DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.' + }, + UNION: { + value: _directiveLocation.DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.' + }, + ENUM: { + value: _directiveLocation.DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.' + }, + ENUM_VALUE: { + value: _directiveLocation.DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.' + }, + INPUT_OBJECT: { + value: _directiveLocation.DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.' + }, + INPUT_FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.' + } + } +}); + +exports.__DirectiveLocation = __DirectiveLocation; + +var __Type = new _definition.GraphQLObjectType({ + name: '__Type', + description: 'The fundamental unit of any GraphQL Schema is the type. There are ' + 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' + '\n\nDepending on the kind of a type, certain fields describe ' + 'information about that type. Scalar types provide no information ' + 'beyond a name and description, while Enum types provide their values. ' + 'Object and Interface types provide the fields they describe. Abstract ' + 'types, Union and Interface, provide the Object types possible ' + 'at runtime. List and NonNull types compose other types.', + fields: function fields() { + return { + kind: { + type: (0, _definition.GraphQLNonNull)(__TypeKind), + resolve: function resolve(type) { + if ((0, _definition.isScalarType)(type)) { + return TypeKind.SCALAR; + } else if ((0, _definition.isObjectType)(type)) { + return TypeKind.OBJECT; + } else if ((0, _definition.isInterfaceType)(type)) { + return TypeKind.INTERFACE; + } else if ((0, _definition.isUnionType)(type)) { + return TypeKind.UNION; + } else if ((0, _definition.isEnumType)(type)) { + return TypeKind.ENUM; + } else if ((0, _definition.isInputObjectType)(type)) { + return TypeKind.INPUT_OBJECT; + } else if ((0, _definition.isListType)(type)) { + return TypeKind.LIST; + } else if ((0, _definition.isNonNullType)(type)) { + return TypeKind.NON_NULL; + } + + throw new Error('Unknown kind of type: ' + type); + } + }, + name: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + fields: { + type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Field)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref) { + var includeDeprecated = _ref.includeDeprecated; + + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + var fields = (0, _objectValues.default)(type.getFields()); + + if (!includeDeprecated) { + fields = fields.filter(function (field) { + return !field.deprecationReason; + }); + } + + return fields; + } + + return null; + } + }, + interfaces: { + type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type)), + resolve: function resolve(type) { + if ((0, _definition.isObjectType)(type)) { + return type.getInterfaces(); + } + } + }, + possibleTypes: { + type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type)), + resolve: function resolve(type, args, context, _ref2) { + var schema = _ref2.schema; + + if ((0, _definition.isAbstractType)(type)) { + return schema.getPossibleTypes(type); + } + } + }, + enumValues: { + type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__EnumValue)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref3) { + var includeDeprecated = _ref3.includeDeprecated; + + if ((0, _definition.isEnumType)(type)) { + var values = type.getValues(); + + if (!includeDeprecated) { + values = values.filter(function (value) { + return !value.deprecationReason; + }); + } + + return values; + } + } + }, + inputFields: { + type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue)), + resolve: function resolve(type) { + if ((0, _definition.isInputObjectType)(type)) { + return (0, _objectValues.default)(type.getFields()); + } + } + }, + ofType: { + type: __Type, + resolve: function resolve(obj) { + return obj.ofType; + } + } + }; + } +}); + +exports.__Type = __Type; + +var __Field = new _definition.GraphQLObjectType({ + name: '__Field', + description: 'Object and Interface types are described by a list of Fields, each of ' + 'which has a name, potentially a list of arguments, and a return type.', + fields: function fields() { + return { + name: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + args: { + type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue))), + resolve: function resolve(field) { + return field.args || []; + } + }, + type: { + type: (0, _definition.GraphQLNonNull)(__Type), + resolve: function resolve(obj) { + return obj.type; + } + }, + isDeprecated: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean), + resolve: function resolve(obj) { + return obj.isDeprecated; + } + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.deprecationReason; + } + } + }; + } +}); + +exports.__Field = __Field; + +var __InputValue = new _definition.GraphQLObjectType({ + name: '__InputValue', + description: 'Arguments provided to Fields or Directives and the input fields of an ' + 'InputObject are represented as Input Values which describe their type ' + 'and optionally a default value.', + fields: function fields() { + return { + name: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + type: { + type: (0, _definition.GraphQLNonNull)(__Type), + resolve: function resolve(obj) { + return obj.type; + } + }, + defaultValue: { + type: _scalars.GraphQLString, + description: 'A GraphQL-formatted string representing the default value for this ' + 'input value.', + resolve: function resolve(inputVal) { + return (0, _isInvalid.default)(inputVal.defaultValue) ? null : (0, _printer.print)((0, _astFromValue.astFromValue)(inputVal.defaultValue, inputVal.type)); + } + } + }; + } +}); + +exports.__InputValue = __InputValue; + +var __EnumValue = new _definition.GraphQLObjectType({ + name: '__EnumValue', + description: 'One possible value for a given Enum. Enum values are unique values, not ' + 'a placeholder for a string or numeric value. However an Enum value is ' + 'returned in a JSON response as a string.', + fields: function fields() { + return { + name: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + isDeprecated: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean), + resolve: function resolve(obj) { + return obj.isDeprecated; + } + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.deprecationReason; + } + } + }; + } +}); + +exports.__EnumValue = __EnumValue; +var TypeKind = { + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + INPUT_OBJECT: 'INPUT_OBJECT', + LIST: 'LIST', + NON_NULL: 'NON_NULL' +}; +exports.TypeKind = TypeKind; + +var __TypeKind = new _definition.GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.' + }, + OBJECT: { + value: TypeKind.OBJECT, + description: 'Indicates this type is an object. ' + '`fields` and `interfaces` are valid fields.' + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: 'Indicates this type is an interface. ' + '`fields` and `possibleTypes` are valid fields.' + }, + UNION: { + value: TypeKind.UNION, + description: 'Indicates this type is a union. `possibleTypes` is a valid field.' + }, + ENUM: { + value: TypeKind.ENUM, + description: 'Indicates this type is an enum. `enumValues` is a valid field.' + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: 'Indicates this type is an input object. ' + '`inputFields` is a valid field.' + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.' + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: 'Indicates this type is a non-null. `ofType` is a valid field.' + } + } +}); +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + + +exports.__TypeKind = __TypeKind; +var SchemaMetaFieldDef = { + name: '__schema', + type: (0, _definition.GraphQLNonNull)(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: function resolve(source, args, context, _ref4) { + var schema = _ref4.schema; + return schema; + } +}; +exports.SchemaMetaFieldDef = SchemaMetaFieldDef; +var TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [{ + name: 'name', + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString) + }], + resolve: function resolve(source, _ref5, context, _ref6) { + var name = _ref5.name; + var schema = _ref6.schema; + return schema.getType(name); + } +}; +exports.TypeMetaFieldDef = TypeMetaFieldDef; +var TypeNameMetaFieldDef = { + name: '__typename', + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: function resolve(source, args, context, _ref7) { + var parentType = _ref7.parentType; + return parentType.name; + } +}; +exports.TypeNameMetaFieldDef = TypeNameMetaFieldDef; +var introspectionTypes = [__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]; +exports.introspectionTypes = introspectionTypes; + +function isIntrospectionType(type) { + return (0, _definition.isNamedType)(type) && ( // Would prefer to use introspectionTypes.some(), however %checks needs + // a simple expression. + type.name === __Schema.name || type.name === __Directive.name || type.name === __DirectiveLocation.name || type.name === __Type.name || type.name === __Field.name || type.name === __InputValue.name || type.name === __EnumValue.name || type.name === __TypeKind.name); +} \ No newline at end of file diff --git a/node_modules/graphql/type/introspection.js.flow b/node_modules/graphql/type/introspection.js.flow new file mode 100644 index 0000000..63630d9 --- /dev/null +++ b/node_modules/graphql/type/introspection.js.flow @@ -0,0 +1,498 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { astFromValue } from '../utilities/astFromValue'; +import { print } from '../language/printer'; +import { + GraphQLObjectType, + GraphQLEnumType, + GraphQLList, + GraphQLNonNull, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isAbstractType, + isNamedType, +} from './definition'; +import { GraphQLString, GraphQLBoolean } from './scalars'; +import { DirectiveLocation } from '../language/directiveLocation'; +import type { GraphQLField } from './definition'; + +export const __Schema = new GraphQLObjectType({ + name: '__Schema', + description: + 'A GraphQL Schema defines the capabilities of a GraphQL server. It ' + + 'exposes all available types and directives on the server, as well as ' + + 'the entry points for query, mutation, and subscription operations.', + fields: () => ({ + types: { + description: 'A list of all types supported by this server.', + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Type))), + resolve(schema) { + return objectValues(schema.getTypeMap()); + }, + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: GraphQLNonNull(__Type), + resolve: schema => schema.getQueryType(), + }, + mutationType: { + description: + 'If this server supports mutation, the type that ' + + 'mutation operations will be rooted at.', + type: __Type, + resolve: schema => schema.getMutationType(), + }, + subscriptionType: { + description: + 'If this server support subscription, the type that ' + + 'subscription operations will be rooted at.', + type: __Type, + resolve: schema => schema.getSubscriptionType(), + }, + directives: { + description: 'A list of all directives supported by this server.', + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Directive))), + resolve: schema => schema.getDirectives(), + }, + }), +}); + +export const __Directive = new GraphQLObjectType({ + name: '__Directive', + description: + 'A Directive provides a way to describe alternate runtime execution and ' + + 'type validation behavior in a GraphQL document.' + + "\n\nIn some cases, you need to provide options to alter GraphQL's " + + 'execution behavior in ways field arguments will not suffice, such as ' + + 'conditionally including or skipping a field. Directives provide this by ' + + 'describing additional information to the executor.', + fields: () => ({ + name: { + type: GraphQLNonNull(GraphQLString), + resolve: obj => obj.name, + }, + description: { + type: GraphQLString, + resolve: obj => obj.description, + }, + locations: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__DirectiveLocation))), + resolve: obj => obj.locations, + }, + args: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))), + resolve: directive => directive.args || [], + }, + }), +}); + +export const __DirectiveLocation = new GraphQLEnumType({ + name: '__DirectiveLocation', + description: + 'A Directive can be adjacent to many parts of the GraphQL language, a ' + + '__DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.', + }, + MUTATION: { + value: DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.', + }, + SUBSCRIPTION: { + value: DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.', + }, + FIELD: { + value: DirectiveLocation.FIELD, + description: 'Location adjacent to a field.', + }, + FRAGMENT_DEFINITION: { + value: DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.', + }, + FRAGMENT_SPREAD: { + value: DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.', + }, + INLINE_FRAGMENT: { + value: DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.', + }, + VARIABLE_DEFINITION: { + value: DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.', + }, + SCHEMA: { + value: DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.', + }, + SCALAR: { + value: DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.', + }, + OBJECT: { + value: DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.', + }, + FIELD_DEFINITION: { + value: DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.', + }, + ARGUMENT_DEFINITION: { + value: DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.', + }, + INTERFACE: { + value: DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.', + }, + UNION: { + value: DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.', + }, + ENUM: { + value: DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.', + }, + ENUM_VALUE: { + value: DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.', + }, + INPUT_OBJECT: { + value: DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.', + }, + INPUT_FIELD_DEFINITION: { + value: DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.', + }, + }, +}); + +export const __Type = new GraphQLObjectType({ + name: '__Type', + description: + 'The fundamental unit of any GraphQL Schema is the type. There are ' + + 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' + + '\n\nDepending on the kind of a type, certain fields describe ' + + 'information about that type. Scalar types provide no information ' + + 'beyond a name and description, while Enum types provide their values. ' + + 'Object and Interface types provide the fields they describe. Abstract ' + + 'types, Union and Interface, provide the Object types possible ' + + 'at runtime. List and NonNull types compose other types.', + fields: () => ({ + kind: { + type: GraphQLNonNull(__TypeKind), + resolve(type) { + if (isScalarType(type)) { + return TypeKind.SCALAR; + } else if (isObjectType(type)) { + return TypeKind.OBJECT; + } else if (isInterfaceType(type)) { + return TypeKind.INTERFACE; + } else if (isUnionType(type)) { + return TypeKind.UNION; + } else if (isEnumType(type)) { + return TypeKind.ENUM; + } else if (isInputObjectType(type)) { + return TypeKind.INPUT_OBJECT; + } else if (isListType(type)) { + return TypeKind.LIST; + } else if (isNonNullType(type)) { + return TypeKind.NON_NULL; + } + throw new Error('Unknown kind of type: ' + type); + }, + }, + name: { + type: GraphQLString, + resolve: obj => obj.name, + }, + description: { + type: GraphQLString, + resolve: obj => obj.description, + }, + fields: { + type: GraphQLList(GraphQLNonNull(__Field)), + args: { + includeDeprecated: { type: GraphQLBoolean, defaultValue: false }, + }, + resolve(type, { includeDeprecated }) { + if (isObjectType(type) || isInterfaceType(type)) { + let fields = objectValues(type.getFields()); + if (!includeDeprecated) { + fields = fields.filter(field => !field.deprecationReason); + } + return fields; + } + return null; + }, + }, + interfaces: { + type: GraphQLList(GraphQLNonNull(__Type)), + resolve(type) { + if (isObjectType(type)) { + return type.getInterfaces(); + } + }, + }, + possibleTypes: { + type: GraphQLList(GraphQLNonNull(__Type)), + resolve(type, args, context, { schema }) { + if (isAbstractType(type)) { + return schema.getPossibleTypes(type); + } + }, + }, + enumValues: { + type: GraphQLList(GraphQLNonNull(__EnumValue)), + args: { + includeDeprecated: { type: GraphQLBoolean, defaultValue: false }, + }, + resolve(type, { includeDeprecated }) { + if (isEnumType(type)) { + let values = type.getValues(); + if (!includeDeprecated) { + values = values.filter(value => !value.deprecationReason); + } + return values; + } + }, + }, + inputFields: { + type: GraphQLList(GraphQLNonNull(__InputValue)), + resolve(type) { + if (isInputObjectType(type)) { + return objectValues(type.getFields()); + } + }, + }, + ofType: { + type: __Type, + resolve: obj => obj.ofType, + }, + }), +}); + +export const __Field = new GraphQLObjectType({ + name: '__Field', + description: + 'Object and Interface types are described by a list of Fields, each of ' + + 'which has a name, potentially a list of arguments, and a return type.', + fields: () => ({ + name: { + type: GraphQLNonNull(GraphQLString), + resolve: obj => obj.name, + }, + description: { + type: GraphQLString, + resolve: obj => obj.description, + }, + args: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))), + resolve: field => field.args || [], + }, + type: { + type: GraphQLNonNull(__Type), + resolve: obj => obj.type, + }, + isDeprecated: { + type: GraphQLNonNull(GraphQLBoolean), + resolve: obj => obj.isDeprecated, + }, + deprecationReason: { + type: GraphQLString, + resolve: obj => obj.deprecationReason, + }, + }), +}); + +export const __InputValue = new GraphQLObjectType({ + name: '__InputValue', + description: + 'Arguments provided to Fields or Directives and the input fields of an ' + + 'InputObject are represented as Input Values which describe their type ' + + 'and optionally a default value.', + fields: () => ({ + name: { + type: GraphQLNonNull(GraphQLString), + resolve: obj => obj.name, + }, + description: { + type: GraphQLString, + resolve: obj => obj.description, + }, + type: { + type: GraphQLNonNull(__Type), + resolve: obj => obj.type, + }, + defaultValue: { + type: GraphQLString, + description: + 'A GraphQL-formatted string representing the default value for this ' + + 'input value.', + resolve: inputVal => + isInvalid(inputVal.defaultValue) + ? null + : print(astFromValue(inputVal.defaultValue, inputVal.type)), + }, + }), +}); + +export const __EnumValue = new GraphQLObjectType({ + name: '__EnumValue', + description: + 'One possible value for a given Enum. Enum values are unique values, not ' + + 'a placeholder for a string or numeric value. However an Enum value is ' + + 'returned in a JSON response as a string.', + fields: () => ({ + name: { + type: GraphQLNonNull(GraphQLString), + resolve: obj => obj.name, + }, + description: { + type: GraphQLString, + resolve: obj => obj.description, + }, + isDeprecated: { + type: GraphQLNonNull(GraphQLBoolean), + resolve: obj => obj.isDeprecated, + }, + deprecationReason: { + type: GraphQLString, + resolve: obj => obj.deprecationReason, + }, + }), +}); + +export const TypeKind = { + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + INPUT_OBJECT: 'INPUT_OBJECT', + LIST: 'LIST', + NON_NULL: 'NON_NULL', +}; + +export const __TypeKind = new GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.', + }, + OBJECT: { + value: TypeKind.OBJECT, + description: + 'Indicates this type is an object. ' + + '`fields` and `interfaces` are valid fields.', + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: + 'Indicates this type is an interface. ' + + '`fields` and `possibleTypes` are valid fields.', + }, + UNION: { + value: TypeKind.UNION, + description: + 'Indicates this type is a union. `possibleTypes` is a valid field.', + }, + ENUM: { + value: TypeKind.ENUM, + description: + 'Indicates this type is an enum. `enumValues` is a valid field.', + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: + 'Indicates this type is an input object. ' + + '`inputFields` is a valid field.', + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.', + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: + 'Indicates this type is a non-null. `ofType` is a valid field.', + }, + }, +}); + +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +export const SchemaMetaFieldDef: GraphQLField<*, *> = { + name: '__schema', + type: GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: (source, args, context, { schema }) => schema, +}; + +export const TypeMetaFieldDef: GraphQLField<*, *> = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [{ name: 'name', type: GraphQLNonNull(GraphQLString) }], + resolve: (source, { name }, context, { schema }) => schema.getType(name), +}; + +export const TypeNameMetaFieldDef: GraphQLField<*, *> = { + name: '__typename', + type: GraphQLNonNull(GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: (source, args, context, { parentType }) => parentType.name, +}; + +export const introspectionTypes: $ReadOnlyArray<*> = [ + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, +]; + +export function isIntrospectionType(type: mixed): boolean %checks { + return ( + isNamedType(type) && + // Would prefer to use introspectionTypes.some(), however %checks needs + // a simple expression. + (type.name === __Schema.name || + type.name === __Directive.name || + type.name === __DirectiveLocation.name || + type.name === __Type.name || + type.name === __Field.name || + type.name === __InputValue.name || + type.name === __EnumValue.name || + type.name === __TypeKind.name) + ); +} diff --git a/node_modules/graphql/type/introspection.mjs b/node_modules/graphql/type/introspection.mjs new file mode 100644 index 0000000..6f1bf6e --- /dev/null +++ b/node_modules/graphql/type/introspection.mjs @@ -0,0 +1,500 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { astFromValue } from '../utilities/astFromValue'; +import { print } from '../language/printer'; +import { GraphQLObjectType, GraphQLEnumType, GraphQLList, GraphQLNonNull, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isListType, isNonNullType, isAbstractType, isNamedType } from './definition'; +import { GraphQLString, GraphQLBoolean } from './scalars'; +import { DirectiveLocation } from '../language/directiveLocation'; +export var __Schema = new GraphQLObjectType({ + name: '__Schema', + description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It ' + 'exposes all available types and directives on the server, as well as ' + 'the entry points for query, mutation, and subscription operations.', + fields: function fields() { + return { + types: { + description: 'A list of all types supported by this server.', + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Type))), + resolve: function resolve(schema) { + return objectValues(schema.getTypeMap()); + } + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: GraphQLNonNull(__Type), + resolve: function resolve(schema) { + return schema.getQueryType(); + } + }, + mutationType: { + description: 'If this server supports mutation, the type that ' + 'mutation operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getMutationType(); + } + }, + subscriptionType: { + description: 'If this server support subscription, the type that ' + 'subscription operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getSubscriptionType(); + } + }, + directives: { + description: 'A list of all directives supported by this server.', + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Directive))), + resolve: function resolve(schema) { + return schema.getDirectives(); + } + } + }; + } +}); +export var __Directive = new GraphQLObjectType({ + name: '__Directive', + description: 'A Directive provides a way to describe alternate runtime execution and ' + 'type validation behavior in a GraphQL document.' + "\n\nIn some cases, you need to provide options to alter GraphQL's " + 'execution behavior in ways field arguments will not suffice, such as ' + 'conditionally including or skipping a field. Directives provide this by ' + 'describing additional information to the executor.', + fields: function fields() { + return { + name: { + type: GraphQLNonNull(GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + locations: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__DirectiveLocation))), + resolve: function resolve(obj) { + return obj.locations; + } + }, + args: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))), + resolve: function resolve(directive) { + return directive.args || []; + } + } + }; + } +}); +export var __DirectiveLocation = new GraphQLEnumType({ + name: '__DirectiveLocation', + description: 'A Directive can be adjacent to many parts of the GraphQL language, a ' + '__DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.' + }, + MUTATION: { + value: DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.' + }, + SUBSCRIPTION: { + value: DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.' + }, + FIELD: { + value: DirectiveLocation.FIELD, + description: 'Location adjacent to a field.' + }, + FRAGMENT_DEFINITION: { + value: DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.' + }, + FRAGMENT_SPREAD: { + value: DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.' + }, + INLINE_FRAGMENT: { + value: DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.' + }, + VARIABLE_DEFINITION: { + value: DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.' + }, + SCHEMA: { + value: DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.' + }, + SCALAR: { + value: DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.' + }, + OBJECT: { + value: DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.' + }, + FIELD_DEFINITION: { + value: DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.' + }, + ARGUMENT_DEFINITION: { + value: DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.' + }, + INTERFACE: { + value: DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.' + }, + UNION: { + value: DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.' + }, + ENUM: { + value: DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.' + }, + ENUM_VALUE: { + value: DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.' + }, + INPUT_OBJECT: { + value: DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.' + }, + INPUT_FIELD_DEFINITION: { + value: DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.' + } + } +}); +export var __Type = new GraphQLObjectType({ + name: '__Type', + description: 'The fundamental unit of any GraphQL Schema is the type. There are ' + 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' + '\n\nDepending on the kind of a type, certain fields describe ' + 'information about that type. Scalar types provide no information ' + 'beyond a name and description, while Enum types provide their values. ' + 'Object and Interface types provide the fields they describe. Abstract ' + 'types, Union and Interface, provide the Object types possible ' + 'at runtime. List and NonNull types compose other types.', + fields: function fields() { + return { + kind: { + type: GraphQLNonNull(__TypeKind), + resolve: function resolve(type) { + if (isScalarType(type)) { + return TypeKind.SCALAR; + } else if (isObjectType(type)) { + return TypeKind.OBJECT; + } else if (isInterfaceType(type)) { + return TypeKind.INTERFACE; + } else if (isUnionType(type)) { + return TypeKind.UNION; + } else if (isEnumType(type)) { + return TypeKind.ENUM; + } else if (isInputObjectType(type)) { + return TypeKind.INPUT_OBJECT; + } else if (isListType(type)) { + return TypeKind.LIST; + } else if (isNonNullType(type)) { + return TypeKind.NON_NULL; + } + + throw new Error('Unknown kind of type: ' + type); + } + }, + name: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + fields: { + type: GraphQLList(GraphQLNonNull(__Field)), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref) { + var includeDeprecated = _ref.includeDeprecated; + + if (isObjectType(type) || isInterfaceType(type)) { + var fields = objectValues(type.getFields()); + + if (!includeDeprecated) { + fields = fields.filter(function (field) { + return !field.deprecationReason; + }); + } + + return fields; + } + + return null; + } + }, + interfaces: { + type: GraphQLList(GraphQLNonNull(__Type)), + resolve: function resolve(type) { + if (isObjectType(type)) { + return type.getInterfaces(); + } + } + }, + possibleTypes: { + type: GraphQLList(GraphQLNonNull(__Type)), + resolve: function resolve(type, args, context, _ref2) { + var schema = _ref2.schema; + + if (isAbstractType(type)) { + return schema.getPossibleTypes(type); + } + } + }, + enumValues: { + type: GraphQLList(GraphQLNonNull(__EnumValue)), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref3) { + var includeDeprecated = _ref3.includeDeprecated; + + if (isEnumType(type)) { + var values = type.getValues(); + + if (!includeDeprecated) { + values = values.filter(function (value) { + return !value.deprecationReason; + }); + } + + return values; + } + } + }, + inputFields: { + type: GraphQLList(GraphQLNonNull(__InputValue)), + resolve: function resolve(type) { + if (isInputObjectType(type)) { + return objectValues(type.getFields()); + } + } + }, + ofType: { + type: __Type, + resolve: function resolve(obj) { + return obj.ofType; + } + } + }; + } +}); +export var __Field = new GraphQLObjectType({ + name: '__Field', + description: 'Object and Interface types are described by a list of Fields, each of ' + 'which has a name, potentially a list of arguments, and a return type.', + fields: function fields() { + return { + name: { + type: GraphQLNonNull(GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + args: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))), + resolve: function resolve(field) { + return field.args || []; + } + }, + type: { + type: GraphQLNonNull(__Type), + resolve: function resolve(obj) { + return obj.type; + } + }, + isDeprecated: { + type: GraphQLNonNull(GraphQLBoolean), + resolve: function resolve(obj) { + return obj.isDeprecated; + } + }, + deprecationReason: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.deprecationReason; + } + } + }; + } +}); +export var __InputValue = new GraphQLObjectType({ + name: '__InputValue', + description: 'Arguments provided to Fields or Directives and the input fields of an ' + 'InputObject are represented as Input Values which describe their type ' + 'and optionally a default value.', + fields: function fields() { + return { + name: { + type: GraphQLNonNull(GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + type: { + type: GraphQLNonNull(__Type), + resolve: function resolve(obj) { + return obj.type; + } + }, + defaultValue: { + type: GraphQLString, + description: 'A GraphQL-formatted string representing the default value for this ' + 'input value.', + resolve: function resolve(inputVal) { + return isInvalid(inputVal.defaultValue) ? null : print(astFromValue(inputVal.defaultValue, inputVal.type)); + } + } + }; + } +}); +export var __EnumValue = new GraphQLObjectType({ + name: '__EnumValue', + description: 'One possible value for a given Enum. Enum values are unique values, not ' + 'a placeholder for a string or numeric value. However an Enum value is ' + 'returned in a JSON response as a string.', + fields: function fields() { + return { + name: { + type: GraphQLNonNull(GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + isDeprecated: { + type: GraphQLNonNull(GraphQLBoolean), + resolve: function resolve(obj) { + return obj.isDeprecated; + } + }, + deprecationReason: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.deprecationReason; + } + } + }; + } +}); +export var TypeKind = { + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + INPUT_OBJECT: 'INPUT_OBJECT', + LIST: 'LIST', + NON_NULL: 'NON_NULL' +}; +export var __TypeKind = new GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.' + }, + OBJECT: { + value: TypeKind.OBJECT, + description: 'Indicates this type is an object. ' + '`fields` and `interfaces` are valid fields.' + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: 'Indicates this type is an interface. ' + '`fields` and `possibleTypes` are valid fields.' + }, + UNION: { + value: TypeKind.UNION, + description: 'Indicates this type is a union. `possibleTypes` is a valid field.' + }, + ENUM: { + value: TypeKind.ENUM, + description: 'Indicates this type is an enum. `enumValues` is a valid field.' + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: 'Indicates this type is an input object. ' + '`inputFields` is a valid field.' + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.' + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: 'Indicates this type is a non-null. `ofType` is a valid field.' + } + } +}); +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +export var SchemaMetaFieldDef = { + name: '__schema', + type: GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: function resolve(source, args, context, _ref4) { + var schema = _ref4.schema; + return schema; + } +}; +export var TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [{ + name: 'name', + type: GraphQLNonNull(GraphQLString) + }], + resolve: function resolve(source, _ref5, context, _ref6) { + var name = _ref5.name; + var schema = _ref6.schema; + return schema.getType(name); + } +}; +export var TypeNameMetaFieldDef = { + name: '__typename', + type: GraphQLNonNull(GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: function resolve(source, args, context, _ref7) { + var parentType = _ref7.parentType; + return parentType.name; + } +}; +export var introspectionTypes = [__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]; +export function isIntrospectionType(type) { + return isNamedType(type) && ( // Would prefer to use introspectionTypes.some(), however %checks needs + // a simple expression. + type.name === __Schema.name || type.name === __Directive.name || type.name === __DirectiveLocation.name || type.name === __Type.name || type.name === __Field.name || type.name === __InputValue.name || type.name === __EnumValue.name || type.name === __TypeKind.name); +} \ No newline at end of file diff --git a/node_modules/graphql/type/scalars.js b/node_modules/graphql/type/scalars.js new file mode 100644 index 0000000..ea797bb --- /dev/null +++ b/node_modules/graphql/type/scalars.js @@ -0,0 +1,244 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isSpecifiedScalarType = isSpecifiedScalarType; +exports.specifiedScalarTypes = exports.GraphQLID = exports.GraphQLBoolean = exports.GraphQLString = exports.GraphQLFloat = exports.GraphQLInt = void 0; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _isFinite = _interopRequireDefault(require("../jsutils/isFinite")); + +var _isInteger = _interopRequireDefault(require("../jsutils/isInteger")); + +var _definition = require("./definition"); + +var _kinds = require("../language/kinds"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +// As per the GraphQL Spec, Integers are only treated as valid when a valid +// 32-bit signed integer, providing the broadest support across platforms. +// +// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because +// they are internally represented as IEEE 754 doubles. +var MAX_INT = 2147483647; +var MIN_INT = -2147483648; + +function serializeInt(value) { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + var num = value; + + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + + if (!(0, _isInteger.default)(num)) { + throw new TypeError("Int cannot represent non-integer value: ".concat((0, _inspect.default)(value))); + } + + if (num > MAX_INT || num < MIN_INT) { + throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat((0, _inspect.default)(value))); + } + + return num; +} + +function coerceInt(value) { + if (!(0, _isInteger.default)(value)) { + throw new TypeError("Int cannot represent non-integer value: ".concat((0, _inspect.default)(value))); + } + + if (value > MAX_INT || value < MIN_INT) { + throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat((0, _inspect.default)(value))); + } + + return value; +} + +var GraphQLInt = new _definition.GraphQLScalarType({ + name: 'Int', + description: 'The `Int` scalar type represents non-fractional signed whole numeric ' + 'values. Int can represent values between -(2^31) and 2^31 - 1. ', + serialize: serializeInt, + parseValue: coerceInt, + parseLiteral: function parseLiteral(ast) { + if (ast.kind === _kinds.Kind.INT) { + var num = parseInt(ast.value, 10); + + if (num <= MAX_INT && num >= MIN_INT) { + return num; + } + } + + return undefined; + } +}); +exports.GraphQLInt = GraphQLInt; + +function serializeFloat(value) { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + var num = value; + + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + + if (!(0, _isFinite.default)(num)) { + throw new TypeError("Float cannot represent non numeric value: ".concat((0, _inspect.default)(value))); + } + + return num; +} + +function coerceFloat(value) { + if (!(0, _isFinite.default)(value)) { + throw new TypeError("Float cannot represent non numeric value: ".concat((0, _inspect.default)(value))); + } + + return value; +} + +var GraphQLFloat = new _definition.GraphQLScalarType({ + name: 'Float', + description: 'The `Float` scalar type represents signed double-precision fractional ' + 'values as specified by ' + '[IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ', + serialize: serializeFloat, + parseValue: coerceFloat, + parseLiteral: function parseLiteral(ast) { + return ast.kind === _kinds.Kind.FLOAT || ast.kind === _kinds.Kind.INT ? parseFloat(ast.value) : undefined; + } +}); +exports.GraphQLFloat = GraphQLFloat; + +function serializeString(value) { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an complex value which can be represented as a string + // (ex: MongoDB id objects). + var result = value && typeof value.valueOf === 'function' ? value.valueOf() : value; // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof result === 'string') { + return result; + } + + if (typeof result === 'boolean') { + return result ? 'true' : 'false'; + } + + if ((0, _isFinite.default)(result)) { + return result.toString(); + } + + throw new TypeError("String cannot represent value: ".concat((0, _inspect.default)(value))); +} + +function coerceString(value) { + if (typeof value !== 'string') { + throw new TypeError("String cannot represent a non string value: ".concat((0, _inspect.default)(value))); + } + + return value; +} + +var GraphQLString = new _definition.GraphQLScalarType({ + name: 'String', + description: 'The `String` scalar type represents textual data, represented as UTF-8 ' + 'character sequences. The String type is most often used by GraphQL to ' + 'represent free-form human-readable text.', + serialize: serializeString, + parseValue: coerceString, + parseLiteral: function parseLiteral(ast) { + return ast.kind === _kinds.Kind.STRING ? ast.value : undefined; + } +}); +exports.GraphQLString = GraphQLString; + +function serializeBoolean(value) { + if (typeof value === 'boolean') { + return value; + } + + if ((0, _isFinite.default)(value)) { + return value !== 0; + } + + throw new TypeError("Boolean cannot represent a non boolean value: ".concat((0, _inspect.default)(value))); +} + +function coerceBoolean(value) { + if (typeof value !== 'boolean') { + throw new TypeError("Boolean cannot represent a non boolean value: ".concat((0, _inspect.default)(value))); + } + + return value; +} + +var GraphQLBoolean = new _definition.GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize: serializeBoolean, + parseValue: coerceBoolean, + parseLiteral: function parseLiteral(ast) { + return ast.kind === _kinds.Kind.BOOLEAN ? ast.value : undefined; + } +}); +exports.GraphQLBoolean = GraphQLBoolean; + +function serializeID(value) { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an object identifier (ex. MongoDB). + var result = value && typeof value.valueOf === 'function' ? value.valueOf() : value; + + if (typeof result === 'string') { + return result; + } + + if ((0, _isInteger.default)(result)) { + return String(result); + } + + throw new TypeError("ID cannot represent value: ".concat((0, _inspect.default)(value))); +} + +function coerceID(value) { + if (typeof value === 'string') { + return value; + } + + if ((0, _isInteger.default)(value)) { + return value.toString(); + } + + throw new TypeError("ID cannot represent value: ".concat((0, _inspect.default)(value))); +} + +var GraphQLID = new _definition.GraphQLScalarType({ + name: 'ID', + description: 'The `ID` scalar type represents a unique identifier, often used to ' + 'refetch an object or as key for a cache. The ID type appears in a JSON ' + 'response as a String; however, it is not intended to be human-readable. ' + 'When expected as an input type, any string (such as `"4"`) or integer ' + '(such as `4`) input value will be accepted as an ID.', + serialize: serializeID, + parseValue: coerceID, + parseLiteral: function parseLiteral(ast) { + return ast.kind === _kinds.Kind.STRING || ast.kind === _kinds.Kind.INT ? ast.value : undefined; + } +}); +exports.GraphQLID = GraphQLID; +var specifiedScalarTypes = [GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]; +exports.specifiedScalarTypes = specifiedScalarTypes; + +function isSpecifiedScalarType(type) { + return (0, _definition.isNamedType)(type) && ( // Would prefer to use specifiedScalarTypes.some(), however %checks needs + // a simple expression. + type.name === GraphQLString.name || type.name === GraphQLInt.name || type.name === GraphQLFloat.name || type.name === GraphQLBoolean.name || type.name === GraphQLID.name); +} \ No newline at end of file diff --git a/node_modules/graphql/type/scalars.js.flow b/node_modules/graphql/type/scalars.js.flow new file mode 100644 index 0000000..89f6ed2 --- /dev/null +++ b/node_modules/graphql/type/scalars.js.flow @@ -0,0 +1,253 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../jsutils/inspect'; +import isFinite from '../jsutils/isFinite'; +import isInteger from '../jsutils/isInteger'; +import { GraphQLScalarType, isNamedType } from './definition'; +import { Kind } from '../language/kinds'; + +// As per the GraphQL Spec, Integers are only treated as valid when a valid +// 32-bit signed integer, providing the broadest support across platforms. +// +// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because +// they are internally represented as IEEE 754 doubles. +const MAX_INT = 2147483647; +const MIN_INT = -2147483648; + +function serializeInt(value: mixed): number { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + let num = value; + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + + if (!isInteger(num)) { + throw new TypeError( + `Int cannot represent non-integer value: ${inspect(value)}`, + ); + } + if (num > MAX_INT || num < MIN_INT) { + throw new TypeError( + `Int cannot represent non 32-bit signed integer value: ${inspect(value)}`, + ); + } + return num; +} + +function coerceInt(value: mixed): number { + if (!isInteger(value)) { + throw new TypeError( + `Int cannot represent non-integer value: ${inspect(value)}`, + ); + } + if (value > MAX_INT || value < MIN_INT) { + throw new TypeError( + `Int cannot represent non 32-bit signed integer value: ${inspect(value)}`, + ); + } + return value; +} + +export const GraphQLInt = new GraphQLScalarType({ + name: 'Int', + description: + 'The `Int` scalar type represents non-fractional signed whole numeric ' + + 'values. Int can represent values between -(2^31) and 2^31 - 1. ', + serialize: serializeInt, + parseValue: coerceInt, + parseLiteral(ast) { + if (ast.kind === Kind.INT) { + const num = parseInt(ast.value, 10); + if (num <= MAX_INT && num >= MIN_INT) { + return num; + } + } + return undefined; + }, +}); + +function serializeFloat(value: mixed): number { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + let num = value; + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + if (!isFinite(num)) { + throw new TypeError( + `Float cannot represent non numeric value: ${inspect(value)}`, + ); + } + return num; +} + +function coerceFloat(value: mixed): number { + if (!isFinite(value)) { + throw new TypeError( + `Float cannot represent non numeric value: ${inspect(value)}`, + ); + } + return value; +} + +export const GraphQLFloat = new GraphQLScalarType({ + name: 'Float', + description: + 'The `Float` scalar type represents signed double-precision fractional ' + + 'values as specified by ' + + '[IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ', + serialize: serializeFloat, + parseValue: coerceFloat, + parseLiteral(ast) { + return ast.kind === Kind.FLOAT || ast.kind === Kind.INT + ? parseFloat(ast.value) + : undefined; + }, +}); + +function serializeString(value: mixed): string { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an complex value which can be represented as a string + // (ex: MongoDB id objects). + const result = + value && typeof value.valueOf === 'function' ? value.valueOf() : value; + // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + if (typeof result === 'string') { + return result; + } + if (typeof result === 'boolean') { + return result ? 'true' : 'false'; + } + if (isFinite(result)) { + return result.toString(); + } + throw new TypeError(`String cannot represent value: ${inspect(value)}`); +} + +function coerceString(value: mixed): string { + if (typeof value !== 'string') { + throw new TypeError( + `String cannot represent a non string value: ${inspect(value)}`, + ); + } + return value; +} + +export const GraphQLString = new GraphQLScalarType({ + name: 'String', + description: + 'The `String` scalar type represents textual data, represented as UTF-8 ' + + 'character sequences. The String type is most often used by GraphQL to ' + + 'represent free-form human-readable text.', + serialize: serializeString, + parseValue: coerceString, + parseLiteral(ast) { + return ast.kind === Kind.STRING ? ast.value : undefined; + }, +}); + +function serializeBoolean(value: mixed): boolean { + if (typeof value === 'boolean') { + return value; + } + if (isFinite(value)) { + return value !== 0; + } + throw new TypeError( + `Boolean cannot represent a non boolean value: ${inspect(value)}`, + ); +} + +function coerceBoolean(value: mixed): boolean { + if (typeof value !== 'boolean') { + throw new TypeError( + `Boolean cannot represent a non boolean value: ${inspect(value)}`, + ); + } + return value; +} + +export const GraphQLBoolean = new GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize: serializeBoolean, + parseValue: coerceBoolean, + parseLiteral(ast) { + return ast.kind === Kind.BOOLEAN ? ast.value : undefined; + }, +}); + +function serializeID(value: mixed): string { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an object identifier (ex. MongoDB). + const result = + value && typeof value.valueOf === 'function' ? value.valueOf() : value; + if (typeof result === 'string') { + return result; + } + if (isInteger(result)) { + return String(result); + } + throw new TypeError(`ID cannot represent value: ${inspect(value)}`); +} + +function coerceID(value: mixed): string { + if (typeof value === 'string') { + return value; + } + if (isInteger(value)) { + return value.toString(); + } + throw new TypeError(`ID cannot represent value: ${inspect(value)}`); +} + +export const GraphQLID = new GraphQLScalarType({ + name: 'ID', + description: + 'The `ID` scalar type represents a unique identifier, often used to ' + + 'refetch an object or as key for a cache. The ID type appears in a JSON ' + + 'response as a String; however, it is not intended to be human-readable. ' + + 'When expected as an input type, any string (such as `"4"`) or integer ' + + '(such as `4`) input value will be accepted as an ID.', + serialize: serializeID, + parseValue: coerceID, + parseLiteral(ast) { + return ast.kind === Kind.STRING || ast.kind === Kind.INT + ? ast.value + : undefined; + }, +}); + +export const specifiedScalarTypes: $ReadOnlyArray<*> = [ + GraphQLString, + GraphQLInt, + GraphQLFloat, + GraphQLBoolean, + GraphQLID, +]; + +export function isSpecifiedScalarType(type: mixed): boolean %checks { + return ( + isNamedType(type) && + // Would prefer to use specifiedScalarTypes.some(), however %checks needs + // a simple expression. + (type.name === GraphQLString.name || + type.name === GraphQLInt.name || + type.name === GraphQLFloat.name || + type.name === GraphQLBoolean.name || + type.name === GraphQLID.name) + ); +} diff --git a/node_modules/graphql/type/scalars.mjs b/node_modules/graphql/type/scalars.mjs new file mode 100644 index 0000000..3eec312 --- /dev/null +++ b/node_modules/graphql/type/scalars.mjs @@ -0,0 +1,222 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../jsutils/inspect'; +import isFinite from '../jsutils/isFinite'; +import isInteger from '../jsutils/isInteger'; +import { GraphQLScalarType, isNamedType } from './definition'; +import { Kind } from '../language/kinds'; // As per the GraphQL Spec, Integers are only treated as valid when a valid +// 32-bit signed integer, providing the broadest support across platforms. +// +// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because +// they are internally represented as IEEE 754 doubles. + +var MAX_INT = 2147483647; +var MIN_INT = -2147483648; + +function serializeInt(value) { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + var num = value; + + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + + if (!isInteger(num)) { + throw new TypeError("Int cannot represent non-integer value: ".concat(inspect(value))); + } + + if (num > MAX_INT || num < MIN_INT) { + throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat(inspect(value))); + } + + return num; +} + +function coerceInt(value) { + if (!isInteger(value)) { + throw new TypeError("Int cannot represent non-integer value: ".concat(inspect(value))); + } + + if (value > MAX_INT || value < MIN_INT) { + throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat(inspect(value))); + } + + return value; +} + +export var GraphQLInt = new GraphQLScalarType({ + name: 'Int', + description: 'The `Int` scalar type represents non-fractional signed whole numeric ' + 'values. Int can represent values between -(2^31) and 2^31 - 1. ', + serialize: serializeInt, + parseValue: coerceInt, + parseLiteral: function parseLiteral(ast) { + if (ast.kind === Kind.INT) { + var num = parseInt(ast.value, 10); + + if (num <= MAX_INT && num >= MIN_INT) { + return num; + } + } + + return undefined; + } +}); + +function serializeFloat(value) { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + var num = value; + + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + + if (!isFinite(num)) { + throw new TypeError("Float cannot represent non numeric value: ".concat(inspect(value))); + } + + return num; +} + +function coerceFloat(value) { + if (!isFinite(value)) { + throw new TypeError("Float cannot represent non numeric value: ".concat(inspect(value))); + } + + return value; +} + +export var GraphQLFloat = new GraphQLScalarType({ + name: 'Float', + description: 'The `Float` scalar type represents signed double-precision fractional ' + 'values as specified by ' + '[IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ', + serialize: serializeFloat, + parseValue: coerceFloat, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.FLOAT || ast.kind === Kind.INT ? parseFloat(ast.value) : undefined; + } +}); + +function serializeString(value) { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an complex value which can be represented as a string + // (ex: MongoDB id objects). + var result = value && typeof value.valueOf === 'function' ? value.valueOf() : value; // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof result === 'string') { + return result; + } + + if (typeof result === 'boolean') { + return result ? 'true' : 'false'; + } + + if (isFinite(result)) { + return result.toString(); + } + + throw new TypeError("String cannot represent value: ".concat(inspect(value))); +} + +function coerceString(value) { + if (typeof value !== 'string') { + throw new TypeError("String cannot represent a non string value: ".concat(inspect(value))); + } + + return value; +} + +export var GraphQLString = new GraphQLScalarType({ + name: 'String', + description: 'The `String` scalar type represents textual data, represented as UTF-8 ' + 'character sequences. The String type is most often used by GraphQL to ' + 'represent free-form human-readable text.', + serialize: serializeString, + parseValue: coerceString, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.STRING ? ast.value : undefined; + } +}); + +function serializeBoolean(value) { + if (typeof value === 'boolean') { + return value; + } + + if (isFinite(value)) { + return value !== 0; + } + + throw new TypeError("Boolean cannot represent a non boolean value: ".concat(inspect(value))); +} + +function coerceBoolean(value) { + if (typeof value !== 'boolean') { + throw new TypeError("Boolean cannot represent a non boolean value: ".concat(inspect(value))); + } + + return value; +} + +export var GraphQLBoolean = new GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize: serializeBoolean, + parseValue: coerceBoolean, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.BOOLEAN ? ast.value : undefined; + } +}); + +function serializeID(value) { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an object identifier (ex. MongoDB). + var result = value && typeof value.valueOf === 'function' ? value.valueOf() : value; + + if (typeof result === 'string') { + return result; + } + + if (isInteger(result)) { + return String(result); + } + + throw new TypeError("ID cannot represent value: ".concat(inspect(value))); +} + +function coerceID(value) { + if (typeof value === 'string') { + return value; + } + + if (isInteger(value)) { + return value.toString(); + } + + throw new TypeError("ID cannot represent value: ".concat(inspect(value))); +} + +export var GraphQLID = new GraphQLScalarType({ + name: 'ID', + description: 'The `ID` scalar type represents a unique identifier, often used to ' + 'refetch an object or as key for a cache. The ID type appears in a JSON ' + 'response as a String; however, it is not intended to be human-readable. ' + 'When expected as an input type, any string (such as `"4"`) or integer ' + '(such as `4`) input value will be accepted as an ID.', + serialize: serializeID, + parseValue: coerceID, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.STRING || ast.kind === Kind.INT ? ast.value : undefined; + } +}); +export var specifiedScalarTypes = [GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]; +export function isSpecifiedScalarType(type) { + return isNamedType(type) && ( // Would prefer to use specifiedScalarTypes.some(), however %checks needs + // a simple expression. + type.name === GraphQLString.name || type.name === GraphQLInt.name || type.name === GraphQLFloat.name || type.name === GraphQLBoolean.name || type.name === GraphQLID.name); +} \ No newline at end of file diff --git a/node_modules/graphql/type/schema.js b/node_modules/graphql/type/schema.js new file mode 100644 index 0000000..3b7d32f --- /dev/null +++ b/node_modules/graphql/type/schema.js @@ -0,0 +1,339 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isSchema = isSchema; +exports.GraphQLSchema = void 0; + +var _definition = require("./definition"); + +var _directives = require("./directives"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _introspection = require("./introspection"); + +var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag")); + +var _find = _interopRequireDefault(require("../jsutils/find")); + +var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +// eslint-disable-next-line no-redeclare +function isSchema(schema) { + return (0, _instanceOf.default)(schema, GraphQLSchema); +} +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. @include and + * @skip) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * + */ + + +var GraphQLSchema = +/*#__PURE__*/ +function () { + // Used as a cache for validateSchema(). + // Referenced by validateSchema(). + function GraphQLSchema(config) { + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_queryType", void 0); + + _defineProperty(this, "_mutationType", void 0); + + _defineProperty(this, "_subscriptionType", void 0); + + _defineProperty(this, "_directives", void 0); + + _defineProperty(this, "_typeMap", void 0); + + _defineProperty(this, "_implementations", void 0); + + _defineProperty(this, "_possibleTypeMap", void 0); + + _defineProperty(this, "__validationErrors", void 0); + + _defineProperty(this, "__allowedLegacyNames", void 0); + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + if (config && config.assumeValid) { + this.__validationErrors = []; + } else { + // Otherwise check for common mistakes during construction to produce + // clear and early error messages. + !(_typeof(config) === 'object') ? (0, _invariant.default)(0, 'Must provide configuration object.') : void 0; + !(!config.types || Array.isArray(config.types)) ? (0, _invariant.default)(0, "\"types\" must be Array if provided but got: ".concat((0, _inspect.default)(config.types), ".")) : void 0; + !(!config.directives || Array.isArray(config.directives)) ? (0, _invariant.default)(0, '"directives" must be Array if provided but got: ' + "".concat((0, _inspect.default)(config.directives), ".")) : void 0; + !(!config.allowedLegacyNames || Array.isArray(config.allowedLegacyNames)) ? (0, _invariant.default)(0, '"allowedLegacyNames" must be Array if provided but got: ' + "".concat((0, _inspect.default)(config.allowedLegacyNames), ".")) : void 0; + } + + this.__allowedLegacyNames = config.allowedLegacyNames || []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = config.directives || _directives.specifiedDirectives; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; // Build type map now to detect any errors within this schema. + + var initialTypes = [this.getQueryType(), this.getMutationType(), this.getSubscriptionType(), _introspection.__Schema]; + var types = config.types; + + if (types) { + initialTypes = initialTypes.concat(types); + } // Keep track of all types referenced within the schema. + + + var typeMap = Object.create(null); // First by deeply visiting all initial types. + + typeMap = initialTypes.reduce(typeMapReducer, typeMap); // Then by deeply visiting all directive types. + + typeMap = this._directives.reduce(typeMapDirectiveReducer, typeMap); // Storing the resulting map for reference by the schema. + + this._typeMap = typeMap; // Keep track of all implementations by interface name. + + this._implementations = Object.create(null); + + var _arr = Object.keys(this._typeMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var typeName = _arr[_i]; + var type = this._typeMap[typeName]; + + if ((0, _definition.isObjectType)(type)) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = type.getInterfaces()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var iface = _step.value; + + if ((0, _definition.isInterfaceType)(iface)) { + var impls = this._implementations[iface.name]; + + if (impls) { + impls.push(type); + } else { + this._implementations[iface.name] = [type]; + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else if ((0, _definition.isAbstractType)(type) && !this._implementations[type.name]) { + this._implementations[type.name] = []; + } + } + } + + var _proto = GraphQLSchema.prototype; + + _proto.getQueryType = function getQueryType() { + return this._queryType; + }; + + _proto.getMutationType = function getMutationType() { + return this._mutationType; + }; + + _proto.getSubscriptionType = function getSubscriptionType() { + return this._subscriptionType; + }; + + _proto.getTypeMap = function getTypeMap() { + return this._typeMap; + }; + + _proto.getType = function getType(name) { + return this.getTypeMap()[name]; + }; + + _proto.getPossibleTypes = function getPossibleTypes(abstractType) { + if ((0, _definition.isUnionType)(abstractType)) { + return abstractType.getTypes(); + } + + return this._implementations[abstractType.name]; + }; + + _proto.isPossibleType = function isPossibleType(abstractType, possibleType) { + var possibleTypeMap = this._possibleTypeMap; + + if (!possibleTypeMap) { + this._possibleTypeMap = possibleTypeMap = Object.create(null); + } + + if (!possibleTypeMap[abstractType.name]) { + var possibleTypes = this.getPossibleTypes(abstractType); + possibleTypeMap[abstractType.name] = possibleTypes.reduce(function (map, type) { + return map[type.name] = true, map; + }, Object.create(null)); + } + + return Boolean(possibleTypeMap[abstractType.name][possibleType.name]); + }; + + _proto.getDirectives = function getDirectives() { + return this._directives; + }; + + _proto.getDirective = function getDirective(name) { + return (0, _find.default)(this.getDirectives(), function (directive) { + return directive.name === name; + }); + }; + + return GraphQLSchema; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLSchema = GraphQLSchema; +(0, _defineToStringTag.default)(GraphQLSchema); + +function typeMapReducer(map, type) { + if (!type) { + return map; + } + + if ((0, _definition.isWrappingType)(type)) { + return typeMapReducer(map, type.ofType); + } + + if (map[type.name]) { + !(map[type.name] === type) ? (0, _invariant.default)(0, 'Schema must contain unique named types but contains multiple ' + "types named \"".concat(type.name, "\".")) : void 0; + return map; + } + + map[type.name] = type; + var reducedMap = map; + + if ((0, _definition.isUnionType)(type)) { + reducedMap = type.getTypes().reduce(typeMapReducer, reducedMap); + } + + if ((0, _definition.isObjectType)(type)) { + reducedMap = type.getInterfaces().reduce(typeMapReducer, reducedMap); + } + + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = (0, _objectValues.default)(type.getFields())[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var field = _step2.value; + + if (field.args) { + var fieldArgTypes = field.args.map(function (arg) { + return arg.type; + }); + reducedMap = fieldArgTypes.reduce(typeMapReducer, reducedMap); + } + + reducedMap = typeMapReducer(reducedMap, field.type); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + if ((0, _definition.isInputObjectType)(type)) { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = (0, _objectValues.default)(type.getFields())[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _field = _step3.value; + reducedMap = typeMapReducer(reducedMap, _field.type); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + + return reducedMap; +} + +function typeMapDirectiveReducer(map, directive) { + // Directives are not validated until validateSchema() is called. + if (!(0, _directives.isDirective)(directive)) { + return map; + } + + return directive.args.reduce(function (_map, arg) { + return typeMapReducer(_map, arg.type); + }, map); +} \ No newline at end of file diff --git a/node_modules/graphql/type/schema.js.flow b/node_modules/graphql/type/schema.js.flow new file mode 100644 index 0000000..ad95d34 --- /dev/null +++ b/node_modules/graphql/type/schema.js.flow @@ -0,0 +1,329 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { + isAbstractType, + isObjectType, + isInterfaceType, + isUnionType, + isInputObjectType, + isWrappingType, +} from './definition'; +import type { + GraphQLType, + GraphQLNamedType, + GraphQLAbstractType, + GraphQLObjectType, +} from './definition'; +import type { + SchemaDefinitionNode, + SchemaExtensionNode, +} from '../language/ast'; +import { + GraphQLDirective, + isDirective, + specifiedDirectives, +} from './directives'; +import type { GraphQLError } from '../error/GraphQLError'; +import inspect from '../jsutils/inspect'; +import { __Schema } from './introspection'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import find from '../jsutils/find'; +import instanceOf from '../jsutils/instanceOf'; +import invariant from '../jsutils/invariant'; +import objectValues from '../jsutils/objectValues'; +import type { ObjMap } from '../jsutils/ObjMap'; + +/** + * Test if the given value is a GraphQL schema. + */ +declare function isSchema(schema: mixed): boolean %checks(schema instanceof + GraphQLSchema); +// eslint-disable-next-line no-redeclare +export function isSchema(schema) { + return instanceOf(schema, GraphQLSchema); +} + +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. @include and + * @skip) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * + */ +export class GraphQLSchema { + astNode: ?SchemaDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + _queryType: ?GraphQLObjectType; + _mutationType: ?GraphQLObjectType; + _subscriptionType: ?GraphQLObjectType; + _directives: $ReadOnlyArray; + _typeMap: TypeMap; + _implementations: ObjMap>; + _possibleTypeMap: ?ObjMap>; + // Used as a cache for validateSchema(). + __validationErrors: ?$ReadOnlyArray; + // Referenced by validateSchema(). + __allowedLegacyNames: $ReadOnlyArray; + + constructor(config: GraphQLSchemaConfig): void { + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + if (config && config.assumeValid) { + this.__validationErrors = []; + } else { + // Otherwise check for common mistakes during construction to produce + // clear and early error messages. + invariant( + typeof config === 'object', + 'Must provide configuration object.', + ); + invariant( + !config.types || Array.isArray(config.types), + `"types" must be Array if provided but got: ${inspect(config.types)}.`, + ); + invariant( + !config.directives || Array.isArray(config.directives), + '"directives" must be Array if provided but got: ' + + `${inspect(config.directives)}.`, + ); + invariant( + !config.allowedLegacyNames || Array.isArray(config.allowedLegacyNames), + '"allowedLegacyNames" must be Array if provided but got: ' + + `${inspect(config.allowedLegacyNames)}.`, + ); + } + + this.__allowedLegacyNames = config.allowedLegacyNames || []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; + // Provide specified directives (e.g. @include and @skip) by default. + this._directives = config.directives || specifiedDirectives; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + + // Build type map now to detect any errors within this schema. + let initialTypes: Array = [ + this.getQueryType(), + this.getMutationType(), + this.getSubscriptionType(), + __Schema, + ]; + + const types = config.types; + if (types) { + initialTypes = initialTypes.concat(types); + } + + // Keep track of all types referenced within the schema. + let typeMap: TypeMap = Object.create(null); + + // First by deeply visiting all initial types. + typeMap = initialTypes.reduce(typeMapReducer, typeMap); + + // Then by deeply visiting all directive types. + typeMap = this._directives.reduce(typeMapDirectiveReducer, typeMap); + + // Storing the resulting map for reference by the schema. + this._typeMap = typeMap; + + // Keep track of all implementations by interface name. + this._implementations = Object.create(null); + for (const typeName of Object.keys(this._typeMap)) { + const type = this._typeMap[typeName]; + if (isObjectType(type)) { + for (const iface of type.getInterfaces()) { + if (isInterfaceType(iface)) { + const impls = this._implementations[iface.name]; + if (impls) { + impls.push(type); + } else { + this._implementations[iface.name] = [type]; + } + } + } + } else if (isAbstractType(type) && !this._implementations[type.name]) { + this._implementations[type.name] = []; + } + } + } + + getQueryType(): ?GraphQLObjectType { + return this._queryType; + } + + getMutationType(): ?GraphQLObjectType { + return this._mutationType; + } + + getSubscriptionType(): ?GraphQLObjectType { + return this._subscriptionType; + } + + getTypeMap(): TypeMap { + return this._typeMap; + } + + getType(name: string): ?GraphQLNamedType { + return this.getTypeMap()[name]; + } + + getPossibleTypes( + abstractType: GraphQLAbstractType, + ): $ReadOnlyArray { + if (isUnionType(abstractType)) { + return abstractType.getTypes(); + } + return this._implementations[abstractType.name]; + } + + isPossibleType( + abstractType: GraphQLAbstractType, + possibleType: GraphQLObjectType, + ): boolean { + let possibleTypeMap = this._possibleTypeMap; + if (!possibleTypeMap) { + this._possibleTypeMap = possibleTypeMap = Object.create(null); + } + + if (!possibleTypeMap[abstractType.name]) { + const possibleTypes = this.getPossibleTypes(abstractType); + possibleTypeMap[abstractType.name] = possibleTypes.reduce( + (map, type) => ((map[type.name] = true), map), + Object.create(null), + ); + } + + return Boolean(possibleTypeMap[abstractType.name][possibleType.name]); + } + + getDirectives(): $ReadOnlyArray { + return this._directives; + } + + getDirective(name: string): ?GraphQLDirective { + return find(this.getDirectives(), directive => directive.name === name); + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLSchema); + +type TypeMap = ObjMap; + +export type GraphQLSchemaValidationOptions = {| + /** + * When building a schema from a GraphQL service's introspection result, it + * might be safe to assume the schema is valid. Set to true to assume the + * produced schema is valid. + * + * Default: false + */ + assumeValid?: boolean, + + /** + * If provided, the schema will consider fields or types with names included + * in this list valid, even if they do not adhere to the specification's + * schema validation rules. + * + * This option is provided to ease adoption and will be removed in v15. + */ + allowedLegacyNames?: ?$ReadOnlyArray, +|}; + +export type GraphQLSchemaConfig = {| + query?: ?GraphQLObjectType, + mutation?: ?GraphQLObjectType, + subscription?: ?GraphQLObjectType, + types?: ?Array, + directives?: ?Array, + astNode?: ?SchemaDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, + ...GraphQLSchemaValidationOptions, +|}; + +function typeMapReducer(map: TypeMap, type: ?GraphQLType): TypeMap { + if (!type) { + return map; + } + if (isWrappingType(type)) { + return typeMapReducer(map, type.ofType); + } + if (map[type.name]) { + invariant( + map[type.name] === type, + 'Schema must contain unique named types but contains multiple ' + + `types named "${type.name}".`, + ); + return map; + } + map[type.name] = type; + + let reducedMap = map; + + if (isUnionType(type)) { + reducedMap = type.getTypes().reduce(typeMapReducer, reducedMap); + } + + if (isObjectType(type)) { + reducedMap = type.getInterfaces().reduce(typeMapReducer, reducedMap); + } + + if (isObjectType(type) || isInterfaceType(type)) { + for (const field of objectValues(type.getFields())) { + if (field.args) { + const fieldArgTypes = field.args.map(arg => arg.type); + reducedMap = fieldArgTypes.reduce(typeMapReducer, reducedMap); + } + reducedMap = typeMapReducer(reducedMap, field.type); + } + } + + if (isInputObjectType(type)) { + for (const field of objectValues(type.getFields())) { + reducedMap = typeMapReducer(reducedMap, field.type); + } + } + + return reducedMap; +} + +function typeMapDirectiveReducer( + map: TypeMap, + directive: ?GraphQLDirective, +): TypeMap { + // Directives are not validated until validateSchema() is called. + if (!isDirective(directive)) { + return map; + } + return directive.args.reduce( + (_map, arg) => typeMapReducer(_map, arg.type), + map, + ); +} diff --git a/node_modules/graphql/type/schema.mjs b/node_modules/graphql/type/schema.mjs new file mode 100644 index 0000000..5e3ef73 --- /dev/null +++ b/node_modules/graphql/type/schema.mjs @@ -0,0 +1,325 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { isAbstractType, isObjectType, isInterfaceType, isUnionType, isInputObjectType, isWrappingType } from './definition'; +import { GraphQLDirective, isDirective, specifiedDirectives } from './directives'; +import inspect from '../jsutils/inspect'; +import { __Schema } from './introspection'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import find from '../jsutils/find'; +import instanceOf from '../jsutils/instanceOf'; +import invariant from '../jsutils/invariant'; +import objectValues from '../jsutils/objectValues'; +// eslint-disable-next-line no-redeclare +export function isSchema(schema) { + return instanceOf(schema, GraphQLSchema); +} +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. @include and + * @skip) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * + */ + +export var GraphQLSchema = +/*#__PURE__*/ +function () { + // Used as a cache for validateSchema(). + // Referenced by validateSchema(). + function GraphQLSchema(config) { + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_queryType", void 0); + + _defineProperty(this, "_mutationType", void 0); + + _defineProperty(this, "_subscriptionType", void 0); + + _defineProperty(this, "_directives", void 0); + + _defineProperty(this, "_typeMap", void 0); + + _defineProperty(this, "_implementations", void 0); + + _defineProperty(this, "_possibleTypeMap", void 0); + + _defineProperty(this, "__validationErrors", void 0); + + _defineProperty(this, "__allowedLegacyNames", void 0); + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + if (config && config.assumeValid) { + this.__validationErrors = []; + } else { + // Otherwise check for common mistakes during construction to produce + // clear and early error messages. + !(_typeof(config) === 'object') ? invariant(0, 'Must provide configuration object.') : void 0; + !(!config.types || Array.isArray(config.types)) ? invariant(0, "\"types\" must be Array if provided but got: ".concat(inspect(config.types), ".")) : void 0; + !(!config.directives || Array.isArray(config.directives)) ? invariant(0, '"directives" must be Array if provided but got: ' + "".concat(inspect(config.directives), ".")) : void 0; + !(!config.allowedLegacyNames || Array.isArray(config.allowedLegacyNames)) ? invariant(0, '"allowedLegacyNames" must be Array if provided but got: ' + "".concat(inspect(config.allowedLegacyNames), ".")) : void 0; + } + + this.__allowedLegacyNames = config.allowedLegacyNames || []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = config.directives || specifiedDirectives; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; // Build type map now to detect any errors within this schema. + + var initialTypes = [this.getQueryType(), this.getMutationType(), this.getSubscriptionType(), __Schema]; + var types = config.types; + + if (types) { + initialTypes = initialTypes.concat(types); + } // Keep track of all types referenced within the schema. + + + var typeMap = Object.create(null); // First by deeply visiting all initial types. + + typeMap = initialTypes.reduce(typeMapReducer, typeMap); // Then by deeply visiting all directive types. + + typeMap = this._directives.reduce(typeMapDirectiveReducer, typeMap); // Storing the resulting map for reference by the schema. + + this._typeMap = typeMap; // Keep track of all implementations by interface name. + + this._implementations = Object.create(null); + + var _arr = Object.keys(this._typeMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var typeName = _arr[_i]; + var type = this._typeMap[typeName]; + + if (isObjectType(type)) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = type.getInterfaces()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var iface = _step.value; + + if (isInterfaceType(iface)) { + var impls = this._implementations[iface.name]; + + if (impls) { + impls.push(type); + } else { + this._implementations[iface.name] = [type]; + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else if (isAbstractType(type) && !this._implementations[type.name]) { + this._implementations[type.name] = []; + } + } + } + + var _proto = GraphQLSchema.prototype; + + _proto.getQueryType = function getQueryType() { + return this._queryType; + }; + + _proto.getMutationType = function getMutationType() { + return this._mutationType; + }; + + _proto.getSubscriptionType = function getSubscriptionType() { + return this._subscriptionType; + }; + + _proto.getTypeMap = function getTypeMap() { + return this._typeMap; + }; + + _proto.getType = function getType(name) { + return this.getTypeMap()[name]; + }; + + _proto.getPossibleTypes = function getPossibleTypes(abstractType) { + if (isUnionType(abstractType)) { + return abstractType.getTypes(); + } + + return this._implementations[abstractType.name]; + }; + + _proto.isPossibleType = function isPossibleType(abstractType, possibleType) { + var possibleTypeMap = this._possibleTypeMap; + + if (!possibleTypeMap) { + this._possibleTypeMap = possibleTypeMap = Object.create(null); + } + + if (!possibleTypeMap[abstractType.name]) { + var possibleTypes = this.getPossibleTypes(abstractType); + possibleTypeMap[abstractType.name] = possibleTypes.reduce(function (map, type) { + return map[type.name] = true, map; + }, Object.create(null)); + } + + return Boolean(possibleTypeMap[abstractType.name][possibleType.name]); + }; + + _proto.getDirectives = function getDirectives() { + return this._directives; + }; + + _proto.getDirective = function getDirective(name) { + return find(this.getDirectives(), function (directive) { + return directive.name === name; + }); + }; + + return GraphQLSchema; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLSchema); + +function typeMapReducer(map, type) { + if (!type) { + return map; + } + + if (isWrappingType(type)) { + return typeMapReducer(map, type.ofType); + } + + if (map[type.name]) { + !(map[type.name] === type) ? invariant(0, 'Schema must contain unique named types but contains multiple ' + "types named \"".concat(type.name, "\".")) : void 0; + return map; + } + + map[type.name] = type; + var reducedMap = map; + + if (isUnionType(type)) { + reducedMap = type.getTypes().reduce(typeMapReducer, reducedMap); + } + + if (isObjectType(type)) { + reducedMap = type.getInterfaces().reduce(typeMapReducer, reducedMap); + } + + if (isObjectType(type) || isInterfaceType(type)) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = objectValues(type.getFields())[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var field = _step2.value; + + if (field.args) { + var fieldArgTypes = field.args.map(function (arg) { + return arg.type; + }); + reducedMap = fieldArgTypes.reduce(typeMapReducer, reducedMap); + } + + reducedMap = typeMapReducer(reducedMap, field.type); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + if (isInputObjectType(type)) { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = objectValues(type.getFields())[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _field = _step3.value; + reducedMap = typeMapReducer(reducedMap, _field.type); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + + return reducedMap; +} + +function typeMapDirectiveReducer(map, directive) { + // Directives are not validated until validateSchema() is called. + if (!isDirective(directive)) { + return map; + } + + return directive.args.reduce(function (_map, arg) { + return typeMapReducer(_map, arg.type); + }, map); +} \ No newline at end of file diff --git a/node_modules/graphql/type/validate.js b/node_modules/graphql/type/validate.js new file mode 100644 index 0000000..274ce59 --- /dev/null +++ b/node_modules/graphql/type/validate.js @@ -0,0 +1,808 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validateSchema = validateSchema; +exports.assertValidSchema = assertValidSchema; + +var _definition = require("./definition"); + +var _directives = require("./directives"); + +var _introspection = require("./introspection"); + +var _schema = require("./schema"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _find = _interopRequireDefault(require("../jsutils/find")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _GraphQLError = require("../error/GraphQLError"); + +var _assertValidName = require("../utilities/assertValidName"); + +var _typeComparators = require("../utilities/typeComparators"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ +function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + !(0, _schema.isSchema)(schema) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(schema), " to be a GraphQL schema.")) : void 0; // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + + var context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + var errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ + + +function assertValidSchema(schema) { + var errors = validateSchema(schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} + +var SchemaValidationContext = +/*#__PURE__*/ +function () { + function SchemaValidationContext(schema) { + _defineProperty(this, "_errors", void 0); + + _defineProperty(this, "schema", void 0); + + this._errors = []; + this.schema = schema; + } + + var _proto = SchemaValidationContext.prototype; + + _proto.reportError = function reportError(message, nodes) { + var _nodes = (Array.isArray(nodes) ? nodes : [nodes]).filter(Boolean); + + this.addError(new _GraphQLError.GraphQLError(message, _nodes)); + }; + + _proto.addError = function addError(error) { + this._errors.push(error); + }; + + _proto.getErrors = function getErrors() { + return this._errors; + }; + + return SchemaValidationContext; +}(); + +function validateRootTypes(context) { + var schema = context.schema; + var queryType = schema.getQueryType(); + + if (!queryType) { + context.reportError("Query root type must be provided.", schema.astNode); + } else if (!(0, _definition.isObjectType)(queryType)) { + context.reportError("Query root type must be Object type, it cannot be ".concat((0, _inspect.default)(queryType), "."), getOperationTypeNode(schema, queryType, 'query')); + } + + var mutationType = schema.getMutationType(); + + if (mutationType && !(0, _definition.isObjectType)(mutationType)) { + context.reportError('Mutation root type must be Object type if provided, it cannot be ' + "".concat((0, _inspect.default)(mutationType), "."), getOperationTypeNode(schema, mutationType, 'mutation')); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) { + context.reportError('Subscription root type must be Object type if provided, it cannot be ' + "".concat((0, _inspect.default)(subscriptionType), "."), getOperationTypeNode(schema, subscriptionType, 'subscription')); + } +} + +function getOperationTypeNode(schema, type, operation) { + var operationNodes = getAllSubNodes(schema, function (node) { + return node.operationTypes; + }); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = operationNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var node = _step.value; + + if (node.operation === operation) { + return node.type; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return type.astNode; +} + +function validateDirectives(context) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = context.schema.getDirectives()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var directive = _step2.value; + + // Ensure all directives are in fact GraphQL directives. + if (!(0, _directives.isDirective)(directive)) { + context.reportError("Expected directive but got: ".concat((0, _inspect.default)(directive), "."), directive && directive.astNode); + continue; + } // Ensure they are named correctly. + + + validateName(context, directive); // TODO: Ensure proper locations. + // Ensure the arguments are valid. + + var argNames = Object.create(null); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = directive.args[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var arg = _step3.value; + var argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure they are unique per directive. + + if (argNames[argName]) { + context.reportError("Argument @".concat(directive.name, "(").concat(argName, ":) can only be defined once."), getAllDirectiveArgNodes(directive, argName)); + continue; + } + + argNames[argName] = true; // Ensure the type is an input type. + + if (!(0, _definition.isInputType)(arg.type)) { + context.reportError("The type of @".concat(directive.name, "(").concat(argName, ":) must be Input Type ") + "but got: ".concat((0, _inspect.default)(arg.type), "."), getDirectiveArgTypeNode(directive, argName)); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } +} + +function validateName(context, node) { + // If a schema explicitly allows some legacy name which is no longer valid, + // allow it to be assumed valid. + if (context.schema.__allowedLegacyNames.indexOf(node.name) !== -1) { + return; + } // Ensure names are valid, however introspection types opt out. + + + var error = (0, _assertValidName.isValidNameError)(node.name, node.astNode || undefined); + + if (error) { + context.addError(error); + } +} + +function validateTypes(context) { + var typeMap = context.schema.getTypeMap(); + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = (0, _objectValues.default)(typeMap)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var type = _step4.value; + + // Ensure all provided types are in fact GraphQL type. + if (!(0, _definition.isNamedType)(type)) { + context.reportError("Expected GraphQL named type but got: ".concat((0, _inspect.default)(type), "."), type && type.astNode); + continue; + } // Ensure it is named correctly (excluding introspection types). + + + if (!(0, _introspection.isIntrospectionType)(type)) { + validateName(context, type); + } + + if ((0, _definition.isObjectType)(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateObjectInterfaces(context, type); + } else if ((0, _definition.isInterfaceType)(type)) { + // Ensure fields are valid. + validateFields(context, type); + } else if ((0, _definition.isUnionType)(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if ((0, _definition.isEnumType)(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if ((0, _definition.isInputObjectType)(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } +} + +function validateFields(context, type) { + var fields = (0, _objectValues.default)(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError("Type ".concat(type.name, " must define one or more fields."), getAllNodes(type)); + } + + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = fields[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var field = _step5.value; + // Ensure they are named correctly. + validateName(context, field); // Ensure they were defined at most once. + + var fieldNodes = getAllFieldNodes(type, field.name); + + if (fieldNodes.length > 1) { + context.reportError("Field ".concat(type.name, ".").concat(field.name, " can only be defined once."), fieldNodes); + continue; + } // Ensure the type is an output type + + + if (!(0, _definition.isOutputType)(field.type)) { + context.reportError("The type of ".concat(type.name, ".").concat(field.name, " must be Output Type ") + "but got: ".concat((0, _inspect.default)(field.type), "."), getFieldTypeNode(type, field.name)); + } // Ensure the arguments are valid + + + var argNames = Object.create(null); + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = field.args[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var arg = _step6.value; + var argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure they are unique per field. + + if (argNames[argName]) { + context.reportError("Field argument ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) can only ") + 'be defined once.', getAllFieldArgNodes(type, field.name, argName)); + } + + argNames[argName] = true; // Ensure the type is an input type + + if (!(0, _definition.isInputType)(arg.type)) { + context.reportError("The type of ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) must be Input ") + "Type but got: ".concat((0, _inspect.default)(arg.type), "."), getFieldArgTypeNode(type, field.name, argName)); + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } +} + +function validateObjectInterfaces(context, object) { + var implementedTypeNames = Object.create(null); + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = object.getInterfaces()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var iface = _step7.value; + + if (!(0, _definition.isInterfaceType)(iface)) { + context.reportError("Type ".concat((0, _inspect.default)(object), " must only implement Interface types, ") + "it cannot implement ".concat((0, _inspect.default)(iface), "."), getImplementsInterfaceNode(object, iface)); + continue; + } + + if (implementedTypeNames[iface.name]) { + context.reportError("Type ".concat(object.name, " can only implement ").concat(iface.name, " once."), getAllImplementsInterfaceNodes(object, iface)); + continue; + } + + implementedTypeNames[iface.name] = true; + validateObjectImplementsInterface(context, object, iface); + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } +} + +function validateObjectImplementsInterface(context, object, iface) { + var objectFieldMap = object.getFields(); + var ifaceFieldMap = iface.getFields(); // Assert each interface field is implemented. + + var _arr = Object.keys(ifaceFieldMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var fieldName = _arr[_i]; + var objectField = objectFieldMap[fieldName]; + var ifaceField = ifaceFieldMap[fieldName]; // Assert interface field exists on object. + + if (!objectField) { + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expected but ") + "".concat(object.name, " does not provide it."), [getFieldNode(iface, fieldName)].concat(getAllNodes(object))); + continue; + } // Assert interface field type is satisfied by object field type, by being + // a valid subtype. (covariant) + + + if (!(0, _typeComparators.isTypeSubTypeOf)(context.schema, objectField.type, ifaceField.type)) { + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expects type ") + "".concat((0, _inspect.default)(ifaceField.type), " but ").concat(object.name, ".").concat(fieldName, " ") + "is type ".concat((0, _inspect.default)(objectField.type), "."), [getFieldTypeNode(iface, fieldName), getFieldTypeNode(object, fieldName)]); + } // Assert each interface field arg is implemented. + + + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + var _loop = function _loop() { + var ifaceArg = _step8.value; + var argName = ifaceArg.name; + var objectArg = (0, _find.default)(objectField.args, function (arg) { + return arg.name === argName; + }); // Assert interface field arg exists on object field. + + if (!objectArg) { + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expected but ".concat(object.name, ".").concat(fieldName, " does not provide it."), [getFieldArgNode(iface, fieldName, argName), getFieldNode(object, fieldName)]); + return "continue"; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + + if (!(0, _typeComparators.isEqualType)(ifaceArg.type, objectArg.type)) { + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expects type ".concat((0, _inspect.default)(ifaceArg.type), " but ") + "".concat(object.name, ".").concat(fieldName, "(").concat(argName, ":) is type ") + "".concat((0, _inspect.default)(objectArg.type), "."), [getFieldArgTypeNode(iface, fieldName, argName), getFieldArgTypeNode(object, fieldName, argName)]); + } // TODO: validate default values? + + }; + + for (var _iterator8 = ifaceField.args[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var _ret = _loop(); + + if (_ret === "continue") continue; + } // Assert additional arguments must not be required. + + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + var _loop2 = function _loop2() { + var objectArg = _step9.value; + var argName = objectArg.name; + var ifaceArg = (0, _find.default)(ifaceField.args, function (arg) { + return arg.name === argName; + }); + + if (!ifaceArg && (0, _definition.isRequiredArgument)(objectArg)) { + context.reportError("Object field ".concat(object.name, ".").concat(fieldName, " includes required ") + "argument ".concat(argName, " that is missing from the Interface field ") + "".concat(iface.name, ".").concat(fieldName, "."), [getFieldArgNode(object, fieldName, argName), getFieldNode(iface, fieldName)]); + } + }; + + for (var _iterator9 = objectField.args[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + _loop2(); + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + } +} + +function validateUnionMembers(context, union) { + var memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError("Union type ".concat(union.name, " must define one or more member types."), getAllNodes(union)); + } + + var includedTypeNames = Object.create(null); + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = memberTypes[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var memberType = _step10.value; + + if (includedTypeNames[memberType.name]) { + context.reportError("Union type ".concat(union.name, " can only include type ") + "".concat(memberType.name, " once."), getUnionMemberTypeNodes(union, memberType.name)); + continue; + } + + includedTypeNames[memberType.name] = true; + + if (!(0, _definition.isObjectType)(memberType)) { + context.reportError("Union type ".concat(union.name, " can only include Object types, ") + "it cannot include ".concat((0, _inspect.default)(memberType), "."), getUnionMemberTypeNodes(union, String(memberType))); + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } +} + +function validateEnumValues(context, enumType) { + var enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError("Enum type ".concat(enumType.name, " must define one or more values."), getAllNodes(enumType)); + } + + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + for (var _iterator11 = enumValues[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + var enumValue = _step11.value; + var valueName = enumValue.name; // Ensure no duplicates. + + var allNodes = getEnumValueNodes(enumType, valueName); + + if (allNodes && allNodes.length > 1) { + context.reportError("Enum type ".concat(enumType.name, " can include value ").concat(valueName, " only once."), allNodes); + } // Ensure valid name. + + + validateName(context, enumValue); + + if (valueName === 'true' || valueName === 'false' || valueName === 'null') { + context.reportError("Enum type ".concat(enumType.name, " cannot include value: ").concat(valueName, "."), enumValue.astNode); + } + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } +} + +function validateInputFields(context, inputObj) { + var fields = (0, _objectValues.default)(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError("Input Object type ".concat(inputObj.name, " must define one or more fields."), getAllNodes(inputObj)); + } // Ensure the arguments are valid + + + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + for (var _iterator12 = fields[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + var field = _step12.value; + // Ensure they are named correctly. + validateName(context, field); // TODO: Ensure they are unique per field. + // Ensure the type is an input type + + if (!(0, _definition.isInputType)(field.type)) { + context.reportError("The type of ".concat(inputObj.name, ".").concat(field.name, " must be Input Type ") + "but got: ".concat((0, _inspect.default)(field.type), "."), field.astNode && field.astNode.type); + } + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } +} + +function getAllNodes(object) { + var astNode = object.astNode, + extensionASTNodes = object.extensionASTNodes; + return astNode ? extensionASTNodes ? [astNode].concat(extensionASTNodes) : [astNode] : extensionASTNodes || []; +} + +function getAllSubNodes(object, getter) { + var result = []; + var _iteratorNormalCompletion13 = true; + var _didIteratorError13 = false; + var _iteratorError13 = undefined; + + try { + for (var _iterator13 = getAllNodes(object)[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) { + var astNode = _step13.value; + + if (astNode) { + var subNodes = getter(astNode); + + if (subNodes) { + result = result.concat(subNodes); + } + } + } + } catch (err) { + _didIteratorError13 = true; + _iteratorError13 = err; + } finally { + try { + if (!_iteratorNormalCompletion13 && _iterator13.return != null) { + _iterator13.return(); + } + } finally { + if (_didIteratorError13) { + throw _iteratorError13; + } + } + } + + return result; +} + +function getImplementsInterfaceNode(type, iface) { + return getAllImplementsInterfaceNodes(type, iface)[0]; +} + +function getAllImplementsInterfaceNodes(type, iface) { + return getAllSubNodes(type, function (typeNode) { + return typeNode.interfaces; + }).filter(function (ifaceNode) { + return ifaceNode.name.value === iface.name; + }); +} + +function getFieldNode(type, fieldName) { + return getAllFieldNodes(type, fieldName)[0]; +} + +function getAllFieldNodes(type, fieldName) { + return getAllSubNodes(type, function (typeNode) { + return typeNode.fields; + }).filter(function (fieldNode) { + return fieldNode.name.value === fieldName; + }); +} + +function getFieldTypeNode(type, fieldName) { + var fieldNode = getFieldNode(type, fieldName); + return fieldNode && fieldNode.type; +} + +function getFieldArgNode(type, fieldName, argName) { + return getAllFieldArgNodes(type, fieldName, argName)[0]; +} + +function getAllFieldArgNodes(type, fieldName, argName) { + var argNodes = []; + var fieldNode = getFieldNode(type, fieldName); + + if (fieldNode && fieldNode.arguments) { + var _iteratorNormalCompletion14 = true; + var _didIteratorError14 = false; + var _iteratorError14 = undefined; + + try { + for (var _iterator14 = fieldNode.arguments[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) { + var node = _step14.value; + + if (node.name.value === argName) { + argNodes.push(node); + } + } + } catch (err) { + _didIteratorError14 = true; + _iteratorError14 = err; + } finally { + try { + if (!_iteratorNormalCompletion14 && _iterator14.return != null) { + _iterator14.return(); + } + } finally { + if (_didIteratorError14) { + throw _iteratorError14; + } + } + } + } + + return argNodes; +} + +function getFieldArgTypeNode(type, fieldName, argName) { + var fieldArgNode = getFieldArgNode(type, fieldName, argName); + return fieldArgNode && fieldArgNode.type; +} + +function getAllDirectiveArgNodes(directive, argName) { + return getAllSubNodes(directive, function (directiveNode) { + return directiveNode.arguments; + }).filter(function (argNode) { + return argNode.name.value === argName; + }); +} + +function getDirectiveArgTypeNode(directive, argName) { + var argNode = getAllDirectiveArgNodes(directive, argName)[0]; + return argNode && argNode.type; +} + +function getUnionMemberTypeNodes(union, typeName) { + return getAllSubNodes(union, function (unionNode) { + return unionNode.types; + }).filter(function (typeNode) { + return typeNode.name.value === typeName; + }); +} + +function getEnumValueNodes(enumType, valueName) { + return getAllSubNodes(enumType, function (enumNode) { + return enumNode.values; + }).filter(function (valueNode) { + return valueNode.name.value === valueName; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/type/validate.js.flow b/node_modules/graphql/type/validate.js.flow new file mode 100644 index 0000000..22f3423 --- /dev/null +++ b/node_modules/graphql/type/validate.js.flow @@ -0,0 +1,697 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isNamedType, + isInputType, + isOutputType, + isRequiredArgument, +} from './definition'; +import type { + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, +} from './definition'; +import { isDirective } from './directives'; +import type { GraphQLDirective } from './directives'; +import { isIntrospectionType } from './introspection'; +import { isSchema } from './schema'; +import type { GraphQLSchema } from './schema'; +import inspect from '../jsutils/inspect'; +import find from '../jsutils/find'; +import invariant from '../jsutils/invariant'; +import objectValues from '../jsutils/objectValues'; +import { GraphQLError } from '../error/GraphQLError'; +import type { + ASTNode, + FieldDefinitionNode, + EnumValueDefinitionNode, + InputValueDefinitionNode, + NamedTypeNode, + TypeNode, +} from '../language/ast'; +import { isValidNameError } from '../utilities/assertValidName'; +import { isEqualType, isTypeSubTypeOf } from '../utilities/typeComparators'; + +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ +export function validateSchema( + schema: GraphQLSchema, +): $ReadOnlyArray { + // First check to ensure the provided value is in fact a GraphQLSchema. + invariant( + isSchema(schema), + `Expected ${inspect(schema)} to be a GraphQL schema.`, + ); + + // If this Schema has already been validated, return the previous results. + if (schema.__validationErrors) { + return schema.__validationErrors; + } + + // Validate the schema, producing a list of errors. + const context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); + + // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + const errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} + +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ +export function assertValidSchema(schema: GraphQLSchema): void { + const errors = validateSchema(schema); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } +} + +class SchemaValidationContext { + +_errors: Array; + +schema: GraphQLSchema; + + constructor(schema) { + this._errors = []; + this.schema = schema; + } + + reportError( + message: string, + nodes?: $ReadOnlyArray | ?ASTNode, + ): void { + const _nodes = (Array.isArray(nodes) ? nodes : [nodes]).filter(Boolean); + this.addError(new GraphQLError(message, _nodes)); + } + + addError(error: GraphQLError): void { + this._errors.push(error); + } + + getErrors(): $ReadOnlyArray { + return this._errors; + } +} + +function validateRootTypes(context) { + const schema = context.schema; + const queryType = schema.getQueryType(); + if (!queryType) { + context.reportError(`Query root type must be provided.`, schema.astNode); + } else if (!isObjectType(queryType)) { + context.reportError( + `Query root type must be Object type, it cannot be ${inspect( + queryType, + )}.`, + getOperationTypeNode(schema, queryType, 'query'), + ); + } + + const mutationType = schema.getMutationType(); + if (mutationType && !isObjectType(mutationType)) { + context.reportError( + 'Mutation root type must be Object type if provided, it cannot be ' + + `${inspect(mutationType)}.`, + getOperationTypeNode(schema, mutationType, 'mutation'), + ); + } + + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType && !isObjectType(subscriptionType)) { + context.reportError( + 'Subscription root type must be Object type if provided, it cannot be ' + + `${inspect(subscriptionType)}.`, + getOperationTypeNode(schema, subscriptionType, 'subscription'), + ); + } +} + +function getOperationTypeNode( + schema: GraphQLSchema, + type: GraphQLObjectType, + operation: string, +): ?ASTNode { + const operationNodes = getAllSubNodes(schema, node => node.operationTypes); + for (const node of operationNodes) { + if (node.operation === operation) { + return node.type; + } + } + + return type.astNode; +} + +function validateDirectives(context: SchemaValidationContext): void { + for (const directive of context.schema.getDirectives()) { + // Ensure all directives are in fact GraphQL directives. + if (!isDirective(directive)) { + context.reportError( + `Expected directive but got: ${inspect(directive)}.`, + directive && directive.astNode, + ); + continue; + } + + // Ensure they are named correctly. + validateName(context, directive); + + // TODO: Ensure proper locations. + + // Ensure the arguments are valid. + const argNames = Object.create(null); + for (const arg of directive.args) { + const argName = arg.name; + + // Ensure they are named correctly. + validateName(context, arg); + + // Ensure they are unique per directive. + if (argNames[argName]) { + context.reportError( + `Argument @${directive.name}(${argName}:) can only be defined once.`, + getAllDirectiveArgNodes(directive, argName), + ); + continue; + } + argNames[argName] = true; + + // Ensure the type is an input type. + if (!isInputType(arg.type)) { + context.reportError( + `The type of @${directive.name}(${argName}:) must be Input Type ` + + `but got: ${inspect(arg.type)}.`, + getDirectiveArgTypeNode(directive, argName), + ); + } + } + } +} + +function validateName( + context: SchemaValidationContext, + node: { +name: string, +astNode: ?ASTNode }, +): void { + // If a schema explicitly allows some legacy name which is no longer valid, + // allow it to be assumed valid. + if (context.schema.__allowedLegacyNames.indexOf(node.name) !== -1) { + return; + } + // Ensure names are valid, however introspection types opt out. + const error = isValidNameError(node.name, node.astNode || undefined); + if (error) { + context.addError(error); + } +} + +function validateTypes(context: SchemaValidationContext): void { + const typeMap = context.schema.getTypeMap(); + for (const type of objectValues(typeMap)) { + // Ensure all provided types are in fact GraphQL type. + if (!isNamedType(type)) { + context.reportError( + `Expected GraphQL named type but got: ${inspect(type)}.`, + type && type.astNode, + ); + continue; + } + + // Ensure it is named correctly (excluding introspection types). + if (!isIntrospectionType(type)) { + validateName(context, type); + } + + if (isObjectType(type)) { + // Ensure fields are valid + validateFields(context, type); + + // Ensure objects implement the interfaces they claim to. + validateObjectInterfaces(context, type); + } else if (isInterfaceType(type)) { + // Ensure fields are valid. + validateFields(context, type); + } else if (isUnionType(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if (isEnumType(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if (isInputObjectType(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); + } + } +} + +function validateFields( + context: SchemaValidationContext, + type: GraphQLObjectType | GraphQLInterfaceType, +): void { + const fields = objectValues(type.getFields()); + + // Objects and Interfaces both must define one or more fields. + if (fields.length === 0) { + context.reportError( + `Type ${type.name} must define one or more fields.`, + getAllNodes(type), + ); + } + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); + + // Ensure they were defined at most once. + const fieldNodes = getAllFieldNodes(type, field.name); + if (fieldNodes.length > 1) { + context.reportError( + `Field ${type.name}.${field.name} can only be defined once.`, + fieldNodes, + ); + continue; + } + + // Ensure the type is an output type + if (!isOutputType(field.type)) { + context.reportError( + `The type of ${type.name}.${field.name} must be Output Type ` + + `but got: ${inspect(field.type)}.`, + getFieldTypeNode(type, field.name), + ); + } + + // Ensure the arguments are valid + const argNames = Object.create(null); + for (const arg of field.args) { + const argName = arg.name; + + // Ensure they are named correctly. + validateName(context, arg); + + // Ensure they are unique per field. + if (argNames[argName]) { + context.reportError( + `Field argument ${type.name}.${field.name}(${argName}:) can only ` + + 'be defined once.', + getAllFieldArgNodes(type, field.name, argName), + ); + } + argNames[argName] = true; + + // Ensure the type is an input type + if (!isInputType(arg.type)) { + context.reportError( + `The type of ${type.name}.${field.name}(${argName}:) must be Input ` + + `Type but got: ${inspect(arg.type)}.`, + getFieldArgTypeNode(type, field.name, argName), + ); + } + } + } +} + +function validateObjectInterfaces( + context: SchemaValidationContext, + object: GraphQLObjectType, +): void { + const implementedTypeNames = Object.create(null); + for (const iface of object.getInterfaces()) { + if (!isInterfaceType(iface)) { + context.reportError( + `Type ${inspect(object)} must only implement Interface types, ` + + `it cannot implement ${inspect(iface)}.`, + getImplementsInterfaceNode(object, iface), + ); + continue; + } + + if (implementedTypeNames[iface.name]) { + context.reportError( + `Type ${object.name} can only implement ${iface.name} once.`, + getAllImplementsInterfaceNodes(object, iface), + ); + continue; + } + implementedTypeNames[iface.name] = true; + validateObjectImplementsInterface(context, object, iface); + } +} + +function validateObjectImplementsInterface( + context: SchemaValidationContext, + object: GraphQLObjectType, + iface: GraphQLInterfaceType, +): void { + const objectFieldMap = object.getFields(); + const ifaceFieldMap = iface.getFields(); + + // Assert each interface field is implemented. + for (const fieldName of Object.keys(ifaceFieldMap)) { + const objectField = objectFieldMap[fieldName]; + const ifaceField = ifaceFieldMap[fieldName]; + + // Assert interface field exists on object. + if (!objectField) { + context.reportError( + `Interface field ${iface.name}.${fieldName} expected but ` + + `${object.name} does not provide it.`, + [getFieldNode(iface, fieldName), ...getAllNodes(object)], + ); + continue; + } + + // Assert interface field type is satisfied by object field type, by being + // a valid subtype. (covariant) + if (!isTypeSubTypeOf(context.schema, objectField.type, ifaceField.type)) { + context.reportError( + `Interface field ${iface.name}.${fieldName} expects type ` + + `${inspect(ifaceField.type)} but ${object.name}.${fieldName} ` + + `is type ${inspect(objectField.type)}.`, + [ + getFieldTypeNode(iface, fieldName), + getFieldTypeNode(object, fieldName), + ], + ); + } + + // Assert each interface field arg is implemented. + for (const ifaceArg of ifaceField.args) { + const argName = ifaceArg.name; + const objectArg = find(objectField.args, arg => arg.name === argName); + + // Assert interface field arg exists on object field. + if (!objectArg) { + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + + `expected but ${object.name}.${fieldName} does not provide it.`, + [ + getFieldArgNode(iface, fieldName, argName), + getFieldNode(object, fieldName), + ], + ); + continue; + } + + // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + if (!isEqualType(ifaceArg.type, objectArg.type)) { + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + + `expects type ${inspect(ifaceArg.type)} but ` + + `${object.name}.${fieldName}(${argName}:) is type ` + + `${inspect(objectArg.type)}.`, + [ + getFieldArgTypeNode(iface, fieldName, argName), + getFieldArgTypeNode(object, fieldName, argName), + ], + ); + } + + // TODO: validate default values? + } + + // Assert additional arguments must not be required. + for (const objectArg of objectField.args) { + const argName = objectArg.name; + const ifaceArg = find(ifaceField.args, arg => arg.name === argName); + if (!ifaceArg && isRequiredArgument(objectArg)) { + context.reportError( + `Object field ${object.name}.${fieldName} includes required ` + + `argument ${argName} that is missing from the Interface field ` + + `${iface.name}.${fieldName}.`, + [ + getFieldArgNode(object, fieldName, argName), + getFieldNode(iface, fieldName), + ], + ); + } + } + } +} + +function validateUnionMembers( + context: SchemaValidationContext, + union: GraphQLUnionType, +): void { + const memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError( + `Union type ${union.name} must define one or more member types.`, + getAllNodes(union), + ); + } + + const includedTypeNames = Object.create(null); + for (const memberType of memberTypes) { + if (includedTypeNames[memberType.name]) { + context.reportError( + `Union type ${union.name} can only include type ` + + `${memberType.name} once.`, + getUnionMemberTypeNodes(union, memberType.name), + ); + continue; + } + includedTypeNames[memberType.name] = true; + if (!isObjectType(memberType)) { + context.reportError( + `Union type ${union.name} can only include Object types, ` + + `it cannot include ${inspect(memberType)}.`, + getUnionMemberTypeNodes(union, String(memberType)), + ); + } + } +} + +function validateEnumValues( + context: SchemaValidationContext, + enumType: GraphQLEnumType, +): void { + const enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError( + `Enum type ${enumType.name} must define one or more values.`, + getAllNodes(enumType), + ); + } + + for (const enumValue of enumValues) { + const valueName = enumValue.name; + + // Ensure no duplicates. + const allNodes = getEnumValueNodes(enumType, valueName); + if (allNodes && allNodes.length > 1) { + context.reportError( + `Enum type ${enumType.name} can include value ${valueName} only once.`, + allNodes, + ); + } + + // Ensure valid name. + validateName(context, enumValue); + if (valueName === 'true' || valueName === 'false' || valueName === 'null') { + context.reportError( + `Enum type ${enumType.name} cannot include value: ${valueName}.`, + enumValue.astNode, + ); + } + } +} + +function validateInputFields( + context: SchemaValidationContext, + inputObj: GraphQLInputObjectType, +): void { + const fields = objectValues(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError( + `Input Object type ${inputObj.name} must define one or more fields.`, + getAllNodes(inputObj), + ); + } + + // Ensure the arguments are valid + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); + + // TODO: Ensure they are unique per field. + + // Ensure the type is an input type + if (!isInputType(field.type)) { + context.reportError( + `The type of ${inputObj.name}.${field.name} must be Input Type ` + + `but got: ${inspect(field.type)}.`, + field.astNode && field.astNode.type, + ); + } + } +} + +type SDLDefinedObject = { + +astNode: ?T, + +extensionASTNodes?: ?$ReadOnlyArray, +}; + +function getAllNodes( + object: SDLDefinedObject, +): $ReadOnlyArray { + const { astNode, extensionASTNodes } = object; + return astNode + ? extensionASTNodes + ? [astNode].concat(extensionASTNodes) + : [astNode] + : extensionASTNodes || []; +} + +function getAllSubNodes( + object: SDLDefinedObject, + getter: (T | K) => ?(L | $ReadOnlyArray), +): $ReadOnlyArray { + let result = []; + for (const astNode of getAllNodes(object)) { + if (astNode) { + const subNodes = getter(astNode); + if (subNodes) { + result = result.concat(subNodes); + } + } + } + return result; +} + +function getImplementsInterfaceNode( + type: GraphQLObjectType, + iface: GraphQLInterfaceType, +): ?NamedTypeNode { + return getAllImplementsInterfaceNodes(type, iface)[0]; +} + +function getAllImplementsInterfaceNodes( + type: GraphQLObjectType, + iface: GraphQLInterfaceType, +): $ReadOnlyArray { + return getAllSubNodes(type, typeNode => typeNode.interfaces).filter( + ifaceNode => ifaceNode.name.value === iface.name, + ); +} + +function getFieldNode( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, +): ?FieldDefinitionNode { + return getAllFieldNodes(type, fieldName)[0]; +} + +function getAllFieldNodes( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, +): $ReadOnlyArray { + return getAllSubNodes(type, typeNode => typeNode.fields).filter( + fieldNode => fieldNode.name.value === fieldName, + ); +} + +function getFieldTypeNode( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, +): ?TypeNode { + const fieldNode = getFieldNode(type, fieldName); + return fieldNode && fieldNode.type; +} + +function getFieldArgNode( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, + argName: string, +): ?InputValueDefinitionNode { + return getAllFieldArgNodes(type, fieldName, argName)[0]; +} + +function getAllFieldArgNodes( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, + argName: string, +): $ReadOnlyArray { + const argNodes = []; + const fieldNode = getFieldNode(type, fieldName); + if (fieldNode && fieldNode.arguments) { + for (const node of fieldNode.arguments) { + if (node.name.value === argName) { + argNodes.push(node); + } + } + } + return argNodes; +} + +function getFieldArgTypeNode( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, + argName: string, +): ?TypeNode { + const fieldArgNode = getFieldArgNode(type, fieldName, argName); + return fieldArgNode && fieldArgNode.type; +} + +function getAllDirectiveArgNodes( + directive: GraphQLDirective, + argName: string, +): $ReadOnlyArray { + return getAllSubNodes( + directive, + directiveNode => directiveNode.arguments, + ).filter(argNode => argNode.name.value === argName); +} + +function getDirectiveArgTypeNode( + directive: GraphQLDirective, + argName: string, +): ?TypeNode { + const argNode = getAllDirectiveArgNodes(directive, argName)[0]; + return argNode && argNode.type; +} + +function getUnionMemberTypeNodes( + union: GraphQLUnionType, + typeName: string, +): ?$ReadOnlyArray { + return getAllSubNodes(union, unionNode => unionNode.types).filter( + typeNode => typeNode.name.value === typeName, + ); +} + +function getEnumValueNodes( + enumType: GraphQLEnumType, + valueName: string, +): ?$ReadOnlyArray { + return getAllSubNodes(enumType, enumNode => enumNode.values).filter( + valueNode => valueNode.name.value === valueName, + ); +} diff --git a/node_modules/graphql/type/validate.mjs b/node_modules/graphql/type/validate.mjs new file mode 100644 index 0000000..10de50d --- /dev/null +++ b/node_modules/graphql/type/validate.mjs @@ -0,0 +1,795 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isNamedType, isInputType, isOutputType, isRequiredArgument } from './definition'; +import { isDirective } from './directives'; +import { isIntrospectionType } from './introspection'; +import { isSchema } from './schema'; +import inspect from '../jsutils/inspect'; +import find from '../jsutils/find'; +import invariant from '../jsutils/invariant'; +import objectValues from '../jsutils/objectValues'; +import { GraphQLError } from '../error/GraphQLError'; +import { isValidNameError } from '../utilities/assertValidName'; +import { isEqualType, isTypeSubTypeOf } from '../utilities/typeComparators'; +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ + +export function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + !isSchema(schema) ? invariant(0, "Expected ".concat(inspect(schema), " to be a GraphQL schema.")) : void 0; // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + + var context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + var errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ + +export function assertValidSchema(schema) { + var errors = validateSchema(schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} + +var SchemaValidationContext = +/*#__PURE__*/ +function () { + function SchemaValidationContext(schema) { + _defineProperty(this, "_errors", void 0); + + _defineProperty(this, "schema", void 0); + + this._errors = []; + this.schema = schema; + } + + var _proto = SchemaValidationContext.prototype; + + _proto.reportError = function reportError(message, nodes) { + var _nodes = (Array.isArray(nodes) ? nodes : [nodes]).filter(Boolean); + + this.addError(new GraphQLError(message, _nodes)); + }; + + _proto.addError = function addError(error) { + this._errors.push(error); + }; + + _proto.getErrors = function getErrors() { + return this._errors; + }; + + return SchemaValidationContext; +}(); + +function validateRootTypes(context) { + var schema = context.schema; + var queryType = schema.getQueryType(); + + if (!queryType) { + context.reportError("Query root type must be provided.", schema.astNode); + } else if (!isObjectType(queryType)) { + context.reportError("Query root type must be Object type, it cannot be ".concat(inspect(queryType), "."), getOperationTypeNode(schema, queryType, 'query')); + } + + var mutationType = schema.getMutationType(); + + if (mutationType && !isObjectType(mutationType)) { + context.reportError('Mutation root type must be Object type if provided, it cannot be ' + "".concat(inspect(mutationType), "."), getOperationTypeNode(schema, mutationType, 'mutation')); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && !isObjectType(subscriptionType)) { + context.reportError('Subscription root type must be Object type if provided, it cannot be ' + "".concat(inspect(subscriptionType), "."), getOperationTypeNode(schema, subscriptionType, 'subscription')); + } +} + +function getOperationTypeNode(schema, type, operation) { + var operationNodes = getAllSubNodes(schema, function (node) { + return node.operationTypes; + }); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = operationNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var node = _step.value; + + if (node.operation === operation) { + return node.type; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return type.astNode; +} + +function validateDirectives(context) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = context.schema.getDirectives()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var directive = _step2.value; + + // Ensure all directives are in fact GraphQL directives. + if (!isDirective(directive)) { + context.reportError("Expected directive but got: ".concat(inspect(directive), "."), directive && directive.astNode); + continue; + } // Ensure they are named correctly. + + + validateName(context, directive); // TODO: Ensure proper locations. + // Ensure the arguments are valid. + + var argNames = Object.create(null); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = directive.args[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var arg = _step3.value; + var argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure they are unique per directive. + + if (argNames[argName]) { + context.reportError("Argument @".concat(directive.name, "(").concat(argName, ":) can only be defined once."), getAllDirectiveArgNodes(directive, argName)); + continue; + } + + argNames[argName] = true; // Ensure the type is an input type. + + if (!isInputType(arg.type)) { + context.reportError("The type of @".concat(directive.name, "(").concat(argName, ":) must be Input Type ") + "but got: ".concat(inspect(arg.type), "."), getDirectiveArgTypeNode(directive, argName)); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } +} + +function validateName(context, node) { + // If a schema explicitly allows some legacy name which is no longer valid, + // allow it to be assumed valid. + if (context.schema.__allowedLegacyNames.indexOf(node.name) !== -1) { + return; + } // Ensure names are valid, however introspection types opt out. + + + var error = isValidNameError(node.name, node.astNode || undefined); + + if (error) { + context.addError(error); + } +} + +function validateTypes(context) { + var typeMap = context.schema.getTypeMap(); + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = objectValues(typeMap)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var type = _step4.value; + + // Ensure all provided types are in fact GraphQL type. + if (!isNamedType(type)) { + context.reportError("Expected GraphQL named type but got: ".concat(inspect(type), "."), type && type.astNode); + continue; + } // Ensure it is named correctly (excluding introspection types). + + + if (!isIntrospectionType(type)) { + validateName(context, type); + } + + if (isObjectType(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateObjectInterfaces(context, type); + } else if (isInterfaceType(type)) { + // Ensure fields are valid. + validateFields(context, type); + } else if (isUnionType(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if (isEnumType(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if (isInputObjectType(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } +} + +function validateFields(context, type) { + var fields = objectValues(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError("Type ".concat(type.name, " must define one or more fields."), getAllNodes(type)); + } + + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = fields[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var field = _step5.value; + // Ensure they are named correctly. + validateName(context, field); // Ensure they were defined at most once. + + var fieldNodes = getAllFieldNodes(type, field.name); + + if (fieldNodes.length > 1) { + context.reportError("Field ".concat(type.name, ".").concat(field.name, " can only be defined once."), fieldNodes); + continue; + } // Ensure the type is an output type + + + if (!isOutputType(field.type)) { + context.reportError("The type of ".concat(type.name, ".").concat(field.name, " must be Output Type ") + "but got: ".concat(inspect(field.type), "."), getFieldTypeNode(type, field.name)); + } // Ensure the arguments are valid + + + var argNames = Object.create(null); + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = field.args[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var arg = _step6.value; + var argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure they are unique per field. + + if (argNames[argName]) { + context.reportError("Field argument ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) can only ") + 'be defined once.', getAllFieldArgNodes(type, field.name, argName)); + } + + argNames[argName] = true; // Ensure the type is an input type + + if (!isInputType(arg.type)) { + context.reportError("The type of ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) must be Input ") + "Type but got: ".concat(inspect(arg.type), "."), getFieldArgTypeNode(type, field.name, argName)); + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } +} + +function validateObjectInterfaces(context, object) { + var implementedTypeNames = Object.create(null); + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = object.getInterfaces()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var iface = _step7.value; + + if (!isInterfaceType(iface)) { + context.reportError("Type ".concat(inspect(object), " must only implement Interface types, ") + "it cannot implement ".concat(inspect(iface), "."), getImplementsInterfaceNode(object, iface)); + continue; + } + + if (implementedTypeNames[iface.name]) { + context.reportError("Type ".concat(object.name, " can only implement ").concat(iface.name, " once."), getAllImplementsInterfaceNodes(object, iface)); + continue; + } + + implementedTypeNames[iface.name] = true; + validateObjectImplementsInterface(context, object, iface); + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } +} + +function validateObjectImplementsInterface(context, object, iface) { + var objectFieldMap = object.getFields(); + var ifaceFieldMap = iface.getFields(); // Assert each interface field is implemented. + + var _arr = Object.keys(ifaceFieldMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var fieldName = _arr[_i]; + var objectField = objectFieldMap[fieldName]; + var ifaceField = ifaceFieldMap[fieldName]; // Assert interface field exists on object. + + if (!objectField) { + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expected but ") + "".concat(object.name, " does not provide it."), [getFieldNode(iface, fieldName)].concat(getAllNodes(object))); + continue; + } // Assert interface field type is satisfied by object field type, by being + // a valid subtype. (covariant) + + + if (!isTypeSubTypeOf(context.schema, objectField.type, ifaceField.type)) { + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expects type ") + "".concat(inspect(ifaceField.type), " but ").concat(object.name, ".").concat(fieldName, " ") + "is type ".concat(inspect(objectField.type), "."), [getFieldTypeNode(iface, fieldName), getFieldTypeNode(object, fieldName)]); + } // Assert each interface field arg is implemented. + + + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + var _loop = function _loop() { + var ifaceArg = _step8.value; + var argName = ifaceArg.name; + var objectArg = find(objectField.args, function (arg) { + return arg.name === argName; + }); // Assert interface field arg exists on object field. + + if (!objectArg) { + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expected but ".concat(object.name, ".").concat(fieldName, " does not provide it."), [getFieldArgNode(iface, fieldName, argName), getFieldNode(object, fieldName)]); + return "continue"; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + + if (!isEqualType(ifaceArg.type, objectArg.type)) { + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expects type ".concat(inspect(ifaceArg.type), " but ") + "".concat(object.name, ".").concat(fieldName, "(").concat(argName, ":) is type ") + "".concat(inspect(objectArg.type), "."), [getFieldArgTypeNode(iface, fieldName, argName), getFieldArgTypeNode(object, fieldName, argName)]); + } // TODO: validate default values? + + }; + + for (var _iterator8 = ifaceField.args[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var _ret = _loop(); + + if (_ret === "continue") continue; + } // Assert additional arguments must not be required. + + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + var _loop2 = function _loop2() { + var objectArg = _step9.value; + var argName = objectArg.name; + var ifaceArg = find(ifaceField.args, function (arg) { + return arg.name === argName; + }); + + if (!ifaceArg && isRequiredArgument(objectArg)) { + context.reportError("Object field ".concat(object.name, ".").concat(fieldName, " includes required ") + "argument ".concat(argName, " that is missing from the Interface field ") + "".concat(iface.name, ".").concat(fieldName, "."), [getFieldArgNode(object, fieldName, argName), getFieldNode(iface, fieldName)]); + } + }; + + for (var _iterator9 = objectField.args[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + _loop2(); + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + } +} + +function validateUnionMembers(context, union) { + var memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError("Union type ".concat(union.name, " must define one or more member types."), getAllNodes(union)); + } + + var includedTypeNames = Object.create(null); + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = memberTypes[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var memberType = _step10.value; + + if (includedTypeNames[memberType.name]) { + context.reportError("Union type ".concat(union.name, " can only include type ") + "".concat(memberType.name, " once."), getUnionMemberTypeNodes(union, memberType.name)); + continue; + } + + includedTypeNames[memberType.name] = true; + + if (!isObjectType(memberType)) { + context.reportError("Union type ".concat(union.name, " can only include Object types, ") + "it cannot include ".concat(inspect(memberType), "."), getUnionMemberTypeNodes(union, String(memberType))); + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } +} + +function validateEnumValues(context, enumType) { + var enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError("Enum type ".concat(enumType.name, " must define one or more values."), getAllNodes(enumType)); + } + + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + for (var _iterator11 = enumValues[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + var enumValue = _step11.value; + var valueName = enumValue.name; // Ensure no duplicates. + + var allNodes = getEnumValueNodes(enumType, valueName); + + if (allNodes && allNodes.length > 1) { + context.reportError("Enum type ".concat(enumType.name, " can include value ").concat(valueName, " only once."), allNodes); + } // Ensure valid name. + + + validateName(context, enumValue); + + if (valueName === 'true' || valueName === 'false' || valueName === 'null') { + context.reportError("Enum type ".concat(enumType.name, " cannot include value: ").concat(valueName, "."), enumValue.astNode); + } + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } +} + +function validateInputFields(context, inputObj) { + var fields = objectValues(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError("Input Object type ".concat(inputObj.name, " must define one or more fields."), getAllNodes(inputObj)); + } // Ensure the arguments are valid + + + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + for (var _iterator12 = fields[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + var field = _step12.value; + // Ensure they are named correctly. + validateName(context, field); // TODO: Ensure they are unique per field. + // Ensure the type is an input type + + if (!isInputType(field.type)) { + context.reportError("The type of ".concat(inputObj.name, ".").concat(field.name, " must be Input Type ") + "but got: ".concat(inspect(field.type), "."), field.astNode && field.astNode.type); + } + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } +} + +function getAllNodes(object) { + var astNode = object.astNode, + extensionASTNodes = object.extensionASTNodes; + return astNode ? extensionASTNodes ? [astNode].concat(extensionASTNodes) : [astNode] : extensionASTNodes || []; +} + +function getAllSubNodes(object, getter) { + var result = []; + var _iteratorNormalCompletion13 = true; + var _didIteratorError13 = false; + var _iteratorError13 = undefined; + + try { + for (var _iterator13 = getAllNodes(object)[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) { + var astNode = _step13.value; + + if (astNode) { + var subNodes = getter(astNode); + + if (subNodes) { + result = result.concat(subNodes); + } + } + } + } catch (err) { + _didIteratorError13 = true; + _iteratorError13 = err; + } finally { + try { + if (!_iteratorNormalCompletion13 && _iterator13.return != null) { + _iterator13.return(); + } + } finally { + if (_didIteratorError13) { + throw _iteratorError13; + } + } + } + + return result; +} + +function getImplementsInterfaceNode(type, iface) { + return getAllImplementsInterfaceNodes(type, iface)[0]; +} + +function getAllImplementsInterfaceNodes(type, iface) { + return getAllSubNodes(type, function (typeNode) { + return typeNode.interfaces; + }).filter(function (ifaceNode) { + return ifaceNode.name.value === iface.name; + }); +} + +function getFieldNode(type, fieldName) { + return getAllFieldNodes(type, fieldName)[0]; +} + +function getAllFieldNodes(type, fieldName) { + return getAllSubNodes(type, function (typeNode) { + return typeNode.fields; + }).filter(function (fieldNode) { + return fieldNode.name.value === fieldName; + }); +} + +function getFieldTypeNode(type, fieldName) { + var fieldNode = getFieldNode(type, fieldName); + return fieldNode && fieldNode.type; +} + +function getFieldArgNode(type, fieldName, argName) { + return getAllFieldArgNodes(type, fieldName, argName)[0]; +} + +function getAllFieldArgNodes(type, fieldName, argName) { + var argNodes = []; + var fieldNode = getFieldNode(type, fieldName); + + if (fieldNode && fieldNode.arguments) { + var _iteratorNormalCompletion14 = true; + var _didIteratorError14 = false; + var _iteratorError14 = undefined; + + try { + for (var _iterator14 = fieldNode.arguments[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) { + var node = _step14.value; + + if (node.name.value === argName) { + argNodes.push(node); + } + } + } catch (err) { + _didIteratorError14 = true; + _iteratorError14 = err; + } finally { + try { + if (!_iteratorNormalCompletion14 && _iterator14.return != null) { + _iterator14.return(); + } + } finally { + if (_didIteratorError14) { + throw _iteratorError14; + } + } + } + } + + return argNodes; +} + +function getFieldArgTypeNode(type, fieldName, argName) { + var fieldArgNode = getFieldArgNode(type, fieldName, argName); + return fieldArgNode && fieldArgNode.type; +} + +function getAllDirectiveArgNodes(directive, argName) { + return getAllSubNodes(directive, function (directiveNode) { + return directiveNode.arguments; + }).filter(function (argNode) { + return argNode.name.value === argName; + }); +} + +function getDirectiveArgTypeNode(directive, argName) { + var argNode = getAllDirectiveArgNodes(directive, argName)[0]; + return argNode && argNode.type; +} + +function getUnionMemberTypeNodes(union, typeName) { + return getAllSubNodes(union, function (unionNode) { + return unionNode.types; + }).filter(function (typeNode) { + return typeNode.name.value === typeName; + }); +} + +function getEnumValueNodes(enumType, valueName) { + return getAllSubNodes(enumType, function (enumNode) { + return enumNode.values; + }).filter(function (valueNode) { + return valueNode.name.value === valueName; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/TypeInfo.js b/node_modules/graphql/utilities/TypeInfo.js new file mode 100644 index 0000000..81813c1 --- /dev/null +++ b/node_modules/graphql/utilities/TypeInfo.js @@ -0,0 +1,345 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TypeInfo = void 0; + +var _kinds = require("../language/kinds"); + +var _definition = require("../type/definition"); + +var _introspection = require("../type/introspection"); + +var _typeFromAST = require("./typeFromAST"); + +var _find = _interopRequireDefault(require("../jsutils/find")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ +var TypeInfo = +/*#__PURE__*/ +function () { + function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant codebases. You should never need to use it. + getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals + initialType) { + _defineProperty(this, "_schema", void 0); + + _defineProperty(this, "_typeStack", void 0); + + _defineProperty(this, "_parentTypeStack", void 0); + + _defineProperty(this, "_inputTypeStack", void 0); + + _defineProperty(this, "_fieldDefStack", void 0); + + _defineProperty(this, "_defaultValueStack", void 0); + + _defineProperty(this, "_directive", void 0); + + _defineProperty(this, "_argument", void 0); + + _defineProperty(this, "_enumValue", void 0); + + _defineProperty(this, "_getFieldDef", void 0); + + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = getFieldDefFn || getFieldDef; + + if (initialType) { + if ((0, _definition.isInputType)(initialType)) { + this._inputTypeStack.push(initialType); + } + + if ((0, _definition.isCompositeType)(initialType)) { + this._parentTypeStack.push(initialType); + } + + if ((0, _definition.isOutputType)(initialType)) { + this._typeStack.push(initialType); + } + } + } + + var _proto = TypeInfo.prototype; + + _proto.getType = function getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + }; + + _proto.getParentType = function getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + }; + + _proto.getInputType = function getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + }; + + _proto.getParentInputType = function getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + }; + + _proto.getFieldDef = function getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + }; + + _proto.getDefaultValue = function getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + }; + + _proto.getDirective = function getDirective() { + return this._directive; + }; + + _proto.getArgument = function getArgument() { + return this._argument; + }; + + _proto.getEnumValue = function getEnumValue() { + return this._enumValue; + }; + + _proto.enter = function enter(node) { + var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: + var namedType = (0, _definition.getNamedType)(this.getType()); + + this._parentTypeStack.push((0, _definition.isCompositeType)(namedType) ? namedType : undefined); + + break; + + case _kinds.Kind.FIELD: + var parentType = this.getParentType(); + var fieldDef; + var fieldType; + + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + + if (fieldDef) { + fieldType = fieldDef.type; + } + } + + this._fieldDefStack.push(fieldDef); + + this._typeStack.push((0, _definition.isOutputType)(fieldType) ? fieldType : undefined); + + break; + + case _kinds.Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + + case _kinds.Kind.OPERATION_DEFINITION: + var type; + + if (node.operation === 'query') { + type = schema.getQueryType(); + } else if (node.operation === 'mutation') { + type = schema.getMutationType(); + } else if (node.operation === 'subscription') { + type = schema.getSubscriptionType(); + } + + this._typeStack.push((0, _definition.isObjectType)(type) ? type : undefined); + + break; + + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + var typeConditionAST = node.typeCondition; + var outputType = typeConditionAST ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) : (0, _definition.getNamedType)(this.getType()); + + this._typeStack.push((0, _definition.isOutputType)(outputType) ? outputType : undefined); + + break; + + case _kinds.Kind.VARIABLE_DEFINITION: + var inputType = (0, _typeFromAST.typeFromAST)(schema, node.type); + + this._inputTypeStack.push((0, _definition.isInputType)(inputType) ? inputType : undefined); + + break; + + case _kinds.Kind.ARGUMENT: + var argDef; + var argType; + var fieldOrDirective = this.getDirective() || this.getFieldDef(); + + if (fieldOrDirective) { + argDef = (0, _find.default)(fieldOrDirective.args, function (arg) { + return arg.name === node.name.value; + }); + + if (argDef) { + argType = argDef.type; + } + } + + this._argument = argDef; + + this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + + this._inputTypeStack.push((0, _definition.isInputType)(argType) ? argType : undefined); + + break; + + case _kinds.Kind.LIST: + var listType = (0, _definition.getNullableType)(this.getInputType()); + var itemType = (0, _definition.isListType)(listType) ? listType.ofType : listType; // List positions never have a default value. + + this._defaultValueStack.push(undefined); + + this._inputTypeStack.push((0, _definition.isInputType)(itemType) ? itemType : undefined); + + break; + + case _kinds.Kind.OBJECT_FIELD: + var objectType = (0, _definition.getNamedType)(this.getInputType()); + var inputFieldType; + var inputField; + + if ((0, _definition.isInputObjectType)(objectType)) { + inputField = objectType.getFields()[node.name.value]; + + if (inputField) { + inputFieldType = inputField.type; + } + } + + this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined); + + this._inputTypeStack.push((0, _definition.isInputType)(inputFieldType) ? inputFieldType : undefined); + + break; + + case _kinds.Kind.ENUM: + var enumType = (0, _definition.getNamedType)(this.getInputType()); + var enumValue; + + if ((0, _definition.isEnumType)(enumType)) { + enumValue = enumType.getValue(node.value); + } + + this._enumValue = enumValue; + break; + } + }; + + _proto.leave = function leave(node) { + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: + this._parentTypeStack.pop(); + + break; + + case _kinds.Kind.FIELD: + this._fieldDefStack.pop(); + + this._typeStack.pop(); + + break; + + case _kinds.Kind.DIRECTIVE: + this._directive = null; + break; + + case _kinds.Kind.OPERATION_DEFINITION: + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + + break; + + case _kinds.Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.ARGUMENT: + this._argument = null; + + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.LIST: + case _kinds.Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.ENUM: + this._enumValue = null; + break; + } + }; + + return TypeInfo; +}(); +/** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + */ + + +exports.TypeInfo = TypeInfo; + +function getFieldDef(schema, parentType, fieldNode) { + var name = fieldNode.name.value; + + if (name === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.SchemaMetaFieldDef; + } + + if (name === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.TypeMetaFieldDef; + } + + if (name === _introspection.TypeNameMetaFieldDef.name && (0, _definition.isCompositeType)(parentType)) { + return _introspection.TypeNameMetaFieldDef; + } + + if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { + return parentType.getFields()[name]; + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/TypeInfo.js.flow b/node_modules/graphql/utilities/TypeInfo.js.flow new file mode 100644 index 0000000..b217131 --- /dev/null +++ b/node_modules/graphql/utilities/TypeInfo.js.flow @@ -0,0 +1,313 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { Kind } from '../language/kinds'; +import { + isObjectType, + isInterfaceType, + isEnumType, + isInputObjectType, + isListType, + isCompositeType, + isInputType, + isOutputType, + getNullableType, + getNamedType, +} from '../type/definition'; +import type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, + GraphQLArgument, + GraphQLInputField, + GraphQLEnumValue, +} from '../type/definition'; +import type { GraphQLDirective } from '../type/directives'; +import { + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from '../type/introspection'; +import type { GraphQLSchema } from '../type/schema'; +import type { ASTNode, FieldNode } from '../language/ast'; +import { typeFromAST } from './typeFromAST'; +import find from '../jsutils/find'; + +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ +export class TypeInfo { + _schema: GraphQLSchema; + _typeStack: Array; + _parentTypeStack: Array; + _inputTypeStack: Array; + _fieldDefStack: Array>; + _defaultValueStack: Array; + _directive: ?GraphQLDirective; + _argument: ?GraphQLArgument; + _enumValue: ?GraphQLEnumValue; + _getFieldDef: typeof getFieldDef; + + constructor( + schema: GraphQLSchema, + // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant codebases. You should never need to use it. + // It may disappear in the future. + getFieldDefFn?: typeof getFieldDef, + // Initial type may be provided in rare cases to facilitate traversals + // beginning somewhere other than documents. + initialType?: GraphQLType, + ): void { + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = getFieldDefFn || getFieldDef; + if (initialType) { + if (isInputType(initialType)) { + this._inputTypeStack.push(initialType); + } + if (isCompositeType(initialType)) { + this._parentTypeStack.push(initialType); + } + if (isOutputType(initialType)) { + this._typeStack.push(initialType); + } + } + } + + getType(): ?GraphQLOutputType { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + } + + getParentType(): ?GraphQLCompositeType { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + } + + getInputType(): ?GraphQLInputType { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + } + + getParentInputType(): ?GraphQLInputType { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + } + + getFieldDef(): ?GraphQLField<*, *> { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + } + + getDefaultValue(): ?mixed { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + } + + getDirective(): ?GraphQLDirective { + return this._directive; + } + + getArgument(): ?GraphQLArgument { + return this._argument; + } + + getEnumValue(): ?GraphQLEnumValue { + return this._enumValue; + } + + enter(node: ASTNode) { + const schema = this._schema; + // Note: many of the types below are explicitly typed as "mixed" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + switch (node.kind) { + case Kind.SELECTION_SET: + const namedType: mixed = getNamedType(this.getType()); + this._parentTypeStack.push( + isCompositeType(namedType) ? namedType : undefined, + ); + break; + case Kind.FIELD: + const parentType = this.getParentType(); + let fieldDef; + let fieldType: mixed; + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + if (fieldDef) { + fieldType = fieldDef.type; + } + } + this._fieldDefStack.push(fieldDef); + this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined); + break; + case Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + case Kind.OPERATION_DEFINITION: + let type: mixed; + if (node.operation === 'query') { + type = schema.getQueryType(); + } else if (node.operation === 'mutation') { + type = schema.getMutationType(); + } else if (node.operation === 'subscription') { + type = schema.getSubscriptionType(); + } + this._typeStack.push(isObjectType(type) ? type : undefined); + break; + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + const typeConditionAST = node.typeCondition; + const outputType: mixed = typeConditionAST + ? typeFromAST(schema, typeConditionAST) + : getNamedType(this.getType()); + this._typeStack.push(isOutputType(outputType) ? outputType : undefined); + break; + case Kind.VARIABLE_DEFINITION: + const inputType: mixed = typeFromAST(schema, node.type); + this._inputTypeStack.push( + isInputType(inputType) ? inputType : undefined, + ); + break; + case Kind.ARGUMENT: + let argDef; + let argType: mixed; + const fieldOrDirective = this.getDirective() || this.getFieldDef(); + if (fieldOrDirective) { + argDef = find( + fieldOrDirective.args, + arg => arg.name === node.name.value, + ); + if (argDef) { + argType = argDef.type; + } + } + this._argument = argDef; + this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + this._inputTypeStack.push(isInputType(argType) ? argType : undefined); + break; + case Kind.LIST: + const listType: mixed = getNullableType(this.getInputType()); + const itemType: mixed = isListType(listType) + ? listType.ofType + : listType; + // List positions never have a default value. + this._defaultValueStack.push(undefined); + this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined); + break; + case Kind.OBJECT_FIELD: + const objectType: mixed = getNamedType(this.getInputType()); + let inputFieldType: GraphQLInputType | void; + let inputField: GraphQLInputField | void; + if (isInputObjectType(objectType)) { + inputField = objectType.getFields()[node.name.value]; + if (inputField) { + inputFieldType = inputField.type; + } + } + this._defaultValueStack.push( + inputField ? inputField.defaultValue : undefined, + ); + this._inputTypeStack.push( + isInputType(inputFieldType) ? inputFieldType : undefined, + ); + break; + case Kind.ENUM: + const enumType: mixed = getNamedType(this.getInputType()); + let enumValue; + if (isEnumType(enumType)) { + enumValue = enumType.getValue(node.value); + } + this._enumValue = enumValue; + break; + } + } + + leave(node: ASTNode) { + switch (node.kind) { + case Kind.SELECTION_SET: + this._parentTypeStack.pop(); + break; + case Kind.FIELD: + this._fieldDefStack.pop(); + this._typeStack.pop(); + break; + case Kind.DIRECTIVE: + this._directive = null; + break; + case Kind.OPERATION_DEFINITION: + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + break; + case Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + break; + case Kind.ARGUMENT: + this._argument = null; + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case Kind.LIST: + case Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case Kind.ENUM: + this._enumValue = null; + break; + } + } +} + +/** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + */ +function getFieldDef( + schema: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode, +): ?GraphQLField<*, *> { + const name = fieldNode.name.value; + if ( + name === SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return SchemaMetaFieldDef; + } + if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return TypeMetaFieldDef; + } + if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) { + return TypeNameMetaFieldDef; + } + if (isObjectType(parentType) || isInterfaceType(parentType)) { + return parentType.getFields()[name]; + } +} diff --git a/node_modules/graphql/utilities/TypeInfo.mjs b/node_modules/graphql/utilities/TypeInfo.mjs new file mode 100644 index 0000000..d74e661 --- /dev/null +++ b/node_modules/graphql/utilities/TypeInfo.mjs @@ -0,0 +1,337 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { Kind } from '../language/kinds'; +import { isObjectType, isInterfaceType, isEnumType, isInputObjectType, isListType, isCompositeType, isInputType, isOutputType, getNullableType, getNamedType } from '../type/definition'; +import { SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from '../type/introspection'; +import { typeFromAST } from './typeFromAST'; +import find from '../jsutils/find'; +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ + +export var TypeInfo = +/*#__PURE__*/ +function () { + function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant codebases. You should never need to use it. + getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals + initialType) { + _defineProperty(this, "_schema", void 0); + + _defineProperty(this, "_typeStack", void 0); + + _defineProperty(this, "_parentTypeStack", void 0); + + _defineProperty(this, "_inputTypeStack", void 0); + + _defineProperty(this, "_fieldDefStack", void 0); + + _defineProperty(this, "_defaultValueStack", void 0); + + _defineProperty(this, "_directive", void 0); + + _defineProperty(this, "_argument", void 0); + + _defineProperty(this, "_enumValue", void 0); + + _defineProperty(this, "_getFieldDef", void 0); + + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = getFieldDefFn || getFieldDef; + + if (initialType) { + if (isInputType(initialType)) { + this._inputTypeStack.push(initialType); + } + + if (isCompositeType(initialType)) { + this._parentTypeStack.push(initialType); + } + + if (isOutputType(initialType)) { + this._typeStack.push(initialType); + } + } + } + + var _proto = TypeInfo.prototype; + + _proto.getType = function getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + }; + + _proto.getParentType = function getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + }; + + _proto.getInputType = function getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + }; + + _proto.getParentInputType = function getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + }; + + _proto.getFieldDef = function getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + }; + + _proto.getDefaultValue = function getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + }; + + _proto.getDirective = function getDirective() { + return this._directive; + }; + + _proto.getArgument = function getArgument() { + return this._argument; + }; + + _proto.getEnumValue = function getEnumValue() { + return this._enumValue; + }; + + _proto.enter = function enter(node) { + var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + + switch (node.kind) { + case Kind.SELECTION_SET: + var namedType = getNamedType(this.getType()); + + this._parentTypeStack.push(isCompositeType(namedType) ? namedType : undefined); + + break; + + case Kind.FIELD: + var parentType = this.getParentType(); + var fieldDef; + var fieldType; + + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + + if (fieldDef) { + fieldType = fieldDef.type; + } + } + + this._fieldDefStack.push(fieldDef); + + this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined); + + break; + + case Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + + case Kind.OPERATION_DEFINITION: + var type; + + if (node.operation === 'query') { + type = schema.getQueryType(); + } else if (node.operation === 'mutation') { + type = schema.getMutationType(); + } else if (node.operation === 'subscription') { + type = schema.getSubscriptionType(); + } + + this._typeStack.push(isObjectType(type) ? type : undefined); + + break; + + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + var typeConditionAST = node.typeCondition; + var outputType = typeConditionAST ? typeFromAST(schema, typeConditionAST) : getNamedType(this.getType()); + + this._typeStack.push(isOutputType(outputType) ? outputType : undefined); + + break; + + case Kind.VARIABLE_DEFINITION: + var inputType = typeFromAST(schema, node.type); + + this._inputTypeStack.push(isInputType(inputType) ? inputType : undefined); + + break; + + case Kind.ARGUMENT: + var argDef; + var argType; + var fieldOrDirective = this.getDirective() || this.getFieldDef(); + + if (fieldOrDirective) { + argDef = find(fieldOrDirective.args, function (arg) { + return arg.name === node.name.value; + }); + + if (argDef) { + argType = argDef.type; + } + } + + this._argument = argDef; + + this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + + this._inputTypeStack.push(isInputType(argType) ? argType : undefined); + + break; + + case Kind.LIST: + var listType = getNullableType(this.getInputType()); + var itemType = isListType(listType) ? listType.ofType : listType; // List positions never have a default value. + + this._defaultValueStack.push(undefined); + + this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined); + + break; + + case Kind.OBJECT_FIELD: + var objectType = getNamedType(this.getInputType()); + var inputFieldType; + var inputField; + + if (isInputObjectType(objectType)) { + inputField = objectType.getFields()[node.name.value]; + + if (inputField) { + inputFieldType = inputField.type; + } + } + + this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined); + + this._inputTypeStack.push(isInputType(inputFieldType) ? inputFieldType : undefined); + + break; + + case Kind.ENUM: + var enumType = getNamedType(this.getInputType()); + var enumValue; + + if (isEnumType(enumType)) { + enumValue = enumType.getValue(node.value); + } + + this._enumValue = enumValue; + break; + } + }; + + _proto.leave = function leave(node) { + switch (node.kind) { + case Kind.SELECTION_SET: + this._parentTypeStack.pop(); + + break; + + case Kind.FIELD: + this._fieldDefStack.pop(); + + this._typeStack.pop(); + + break; + + case Kind.DIRECTIVE: + this._directive = null; + break; + + case Kind.OPERATION_DEFINITION: + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + + break; + + case Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + + break; + + case Kind.ARGUMENT: + this._argument = null; + + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case Kind.LIST: + case Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case Kind.ENUM: + this._enumValue = null; + break; + } + }; + + return TypeInfo; +}(); +/** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + */ + +function getFieldDef(schema, parentType, fieldNode) { + var name = fieldNode.name.value; + + if (name === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return SchemaMetaFieldDef; + } + + if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return TypeMetaFieldDef; + } + + if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) { + return TypeNameMetaFieldDef; + } + + if (isObjectType(parentType) || isInterfaceType(parentType)) { + return parentType.getFields()[name]; + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/assertValidName.js b/node_modules/graphql/utilities/assertValidName.js new file mode 100644 index 0000000..3d20308 --- /dev/null +++ b/node_modules/graphql/utilities/assertValidName.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assertValidName = assertValidName; +exports.isValidNameError = isValidNameError; + +var _GraphQLError = require("../error/GraphQLError"); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * Upholds the spec rules about naming. + */ + +function assertValidName(name) { + var error = isValidNameError(name); + + if (error) { + throw error; + } + + return name; +} +/** + * Returns an Error if a name is invalid. + */ + + +function isValidNameError(name, node) { + !(typeof name === 'string') ? (0, _invariant.default)(0, 'Expected string') : void 0; + + if (name.length > 1 && name[0] === '_' && name[1] === '_') { + return new _GraphQLError.GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by ") + 'GraphQL introspection.', node); + } + + if (!NAME_RX.test(name)) { + return new _GraphQLError.GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not."), node); + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/assertValidName.js.flow b/node_modules/graphql/utilities/assertValidName.js.flow new file mode 100644 index 0000000..cdc20b1 --- /dev/null +++ b/node_modules/graphql/utilities/assertValidName.js.flow @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { GraphQLError } from '../error/GraphQLError'; +import type { ASTNode } from '../language/ast'; +import invariant from '../jsutils/invariant'; + +const NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * Upholds the spec rules about naming. + */ +export function assertValidName(name: string): string { + const error = isValidNameError(name); + if (error) { + throw error; + } + return name; +} + +/** + * Returns an Error if a name is invalid. + */ +export function isValidNameError( + name: string, + node?: ASTNode | void, +): GraphQLError | void { + invariant(typeof name === 'string', 'Expected string'); + if (name.length > 1 && name[0] === '_' && name[1] === '_') { + return new GraphQLError( + `Name "${name}" must not begin with "__", which is reserved by ` + + 'GraphQL introspection.', + node, + ); + } + if (!NAME_RX.test(name)) { + return new GraphQLError( + `Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "${name}" does not.`, + node, + ); + } +} diff --git a/node_modules/graphql/utilities/assertValidName.mjs b/node_modules/graphql/utilities/assertValidName.mjs new file mode 100644 index 0000000..e737529 --- /dev/null +++ b/node_modules/graphql/utilities/assertValidName.mjs @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../error/GraphQLError'; +import invariant from '../jsutils/invariant'; +var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * Upholds the spec rules about naming. + */ + +export function assertValidName(name) { + var error = isValidNameError(name); + + if (error) { + throw error; + } + + return name; +} +/** + * Returns an Error if a name is invalid. + */ + +export function isValidNameError(name, node) { + !(typeof name === 'string') ? invariant(0, 'Expected string') : void 0; + + if (name.length > 1 && name[0] === '_' && name[1] === '_') { + return new GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by ") + 'GraphQL introspection.', node); + } + + if (!NAME_RX.test(name)) { + return new GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not."), node); + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/astFromValue.js b/node_modules/graphql/utilities/astFromValue.js new file mode 100644 index 0000000..bbebca5 --- /dev/null +++ b/node_modules/graphql/utilities/astFromValue.js @@ -0,0 +1,207 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.astFromValue = astFromValue; + +var _iterall = require("iterall"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _isNullish = _interopRequireDefault(require("../jsutils/isNullish")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _kinds = require("../language/kinds"); + +var _definition = require("../type/definition"); + +var _scalars = require("../type/scalars"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Produces a GraphQL Value AST given a JavaScript value. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Mixed | Enum Value | + * | null | NullValue | + * + */ +function astFromValue(value, type) { + if ((0, _definition.isNonNullType)(type)) { + var astValue = astFromValue(value, type.ofType); + + if (astValue && astValue.kind === _kinds.Kind.NULL) { + return null; + } + + return astValue; + } // only explicit null, not undefined, NaN + + + if (value === null) { + return { + kind: _kinds.Kind.NULL + }; + } // undefined, NaN + + + if ((0, _isInvalid.default)(value)) { + return null; + } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + + + if ((0, _definition.isListType)(type)) { + var itemType = type.ofType; + + if ((0, _iterall.isCollection)(value)) { + var valuesNodes = []; + (0, _iterall.forEach)(value, function (item) { + var itemNode = astFromValue(item, itemType); + + if (itemNode) { + valuesNodes.push(itemNode); + } + }); + return { + kind: _kinds.Kind.LIST, + values: valuesNodes + }; + } + + return astFromValue(value, itemType); + } // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + + + if ((0, _definition.isInputObjectType)(type)) { + if (value === null || _typeof(value) !== 'object') { + return null; + } + + var fields = (0, _objectValues.default)(type.getFields()); + var fieldNodes = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var field = _step.value; + var fieldValue = astFromValue(value[field.name], field.type); + + if (fieldValue) { + fieldNodes.push({ + kind: _kinds.Kind.OBJECT_FIELD, + name: { + kind: _kinds.Kind.NAME, + value: field.name + }, + value: fieldValue + }); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return { + kind: _kinds.Kind.OBJECT, + fields: fieldNodes + }; + } + + if ((0, _definition.isScalarType)(type) || (0, _definition.isEnumType)(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + var serialized = type.serialize(value); + + if ((0, _isNullish.default)(serialized)) { + return null; + } // Others serialize based on their corresponding JavaScript scalar types. + + + if (typeof serialized === 'boolean') { + return { + kind: _kinds.Kind.BOOLEAN, + value: serialized + }; + } // JavaScript numbers can be Int or Float values. + + + if (typeof serialized === 'number') { + var stringNum = String(serialized); + return integerStringRegExp.test(stringNum) ? { + kind: _kinds.Kind.INT, + value: stringNum + } : { + kind: _kinds.Kind.FLOAT, + value: stringNum + }; + } + + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if ((0, _definition.isEnumType)(type)) { + return { + kind: _kinds.Kind.ENUM, + value: serialized + }; + } // ID types can use Int literals. + + + if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) { + return { + kind: _kinds.Kind.INT, + value: serialized + }; + } + + return { + kind: _kinds.Kind.STRING, + value: serialized + }; + } + + throw new TypeError("Cannot convert value to AST: ".concat((0, _inspect.default)(serialized))); + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ + + +var integerStringRegExp = /^-?(0|[1-9][0-9]*)$/; \ No newline at end of file diff --git a/node_modules/graphql/utilities/astFromValue.js.flow b/node_modules/graphql/utilities/astFromValue.js.flow new file mode 100644 index 0000000..cf73305 --- /dev/null +++ b/node_modules/graphql/utilities/astFromValue.js.flow @@ -0,0 +1,152 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { forEach, isCollection } from 'iterall'; + +import inspect from '../jsutils/inspect'; +import isNullish from '../jsutils/isNullish'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import type { ValueNode } from '../language/ast'; +import { Kind } from '../language/kinds'; +import type { GraphQLInputType } from '../type/definition'; +import { + isScalarType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, +} from '../type/definition'; +import { GraphQLID } from '../type/scalars'; + +/** + * Produces a GraphQL Value AST given a JavaScript value. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Mixed | Enum Value | + * | null | NullValue | + * + */ +export function astFromValue(value: mixed, type: GraphQLInputType): ?ValueNode { + if (isNonNullType(type)) { + const astValue = astFromValue(value, type.ofType); + if (astValue && astValue.kind === Kind.NULL) { + return null; + } + return astValue; + } + + // only explicit null, not undefined, NaN + if (value === null) { + return { kind: Kind.NULL }; + } + + // undefined, NaN + if (isInvalid(value)) { + return null; + } + + // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + if (isListType(type)) { + const itemType = type.ofType; + if (isCollection(value)) { + const valuesNodes = []; + forEach((value: any), item => { + const itemNode = astFromValue(item, itemType); + if (itemNode) { + valuesNodes.push(itemNode); + } + }); + return { kind: Kind.LIST, values: valuesNodes }; + } + return astFromValue(value, itemType); + } + + // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + if (isInputObjectType(type)) { + if (value === null || typeof value !== 'object') { + return null; + } + const fields = objectValues(type.getFields()); + const fieldNodes = []; + for (const field of fields) { + const fieldValue = astFromValue(value[field.name], field.type); + if (fieldValue) { + fieldNodes.push({ + kind: Kind.OBJECT_FIELD, + name: { kind: Kind.NAME, value: field.name }, + value: fieldValue, + }); + } + } + return { kind: Kind.OBJECT, fields: fieldNodes }; + } + + if (isScalarType(type) || isEnumType(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + const serialized = type.serialize(value); + if (isNullish(serialized)) { + return null; + } + + // Others serialize based on their corresponding JavaScript scalar types. + if (typeof serialized === 'boolean') { + return { kind: Kind.BOOLEAN, value: serialized }; + } + + // JavaScript numbers can be Int or Float values. + if (typeof serialized === 'number') { + const stringNum = String(serialized); + return integerStringRegExp.test(stringNum) + ? { kind: Kind.INT, value: stringNum } + : { kind: Kind.FLOAT, value: stringNum }; + } + + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if (isEnumType(type)) { + return { kind: Kind.ENUM, value: serialized }; + } + + // ID types can use Int literals. + if (type === GraphQLID && integerStringRegExp.test(serialized)) { + return { kind: Kind.INT, value: serialized }; + } + + return { + kind: Kind.STRING, + value: serialized, + }; + } + + throw new TypeError(`Cannot convert value to AST: ${inspect(serialized)}`); + } + + /* istanbul ignore next */ + throw new Error(`Unknown type: ${(type: empty)}.`); +} + +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ +const integerStringRegExp = /^-?(0|[1-9][0-9]*)$/; diff --git a/node_modules/graphql/utilities/astFromValue.mjs b/node_modules/graphql/utilities/astFromValue.mjs new file mode 100644 index 0000000..1403f3d --- /dev/null +++ b/node_modules/graphql/utilities/astFromValue.mjs @@ -0,0 +1,198 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { forEach, isCollection } from 'iterall'; +import inspect from '../jsutils/inspect'; +import isNullish from '../jsutils/isNullish'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { Kind } from '../language/kinds'; +import { isScalarType, isEnumType, isInputObjectType, isListType, isNonNullType } from '../type/definition'; +import { GraphQLID } from '../type/scalars'; +/** + * Produces a GraphQL Value AST given a JavaScript value. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Mixed | Enum Value | + * | null | NullValue | + * + */ + +export function astFromValue(value, type) { + if (isNonNullType(type)) { + var astValue = astFromValue(value, type.ofType); + + if (astValue && astValue.kind === Kind.NULL) { + return null; + } + + return astValue; + } // only explicit null, not undefined, NaN + + + if (value === null) { + return { + kind: Kind.NULL + }; + } // undefined, NaN + + + if (isInvalid(value)) { + return null; + } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + + + if (isListType(type)) { + var itemType = type.ofType; + + if (isCollection(value)) { + var valuesNodes = []; + forEach(value, function (item) { + var itemNode = astFromValue(item, itemType); + + if (itemNode) { + valuesNodes.push(itemNode); + } + }); + return { + kind: Kind.LIST, + values: valuesNodes + }; + } + + return astFromValue(value, itemType); + } // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + + + if (isInputObjectType(type)) { + if (value === null || _typeof(value) !== 'object') { + return null; + } + + var fields = objectValues(type.getFields()); + var fieldNodes = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var field = _step.value; + var fieldValue = astFromValue(value[field.name], field.type); + + if (fieldValue) { + fieldNodes.push({ + kind: Kind.OBJECT_FIELD, + name: { + kind: Kind.NAME, + value: field.name + }, + value: fieldValue + }); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return { + kind: Kind.OBJECT, + fields: fieldNodes + }; + } + + if (isScalarType(type) || isEnumType(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + var serialized = type.serialize(value); + + if (isNullish(serialized)) { + return null; + } // Others serialize based on their corresponding JavaScript scalar types. + + + if (typeof serialized === 'boolean') { + return { + kind: Kind.BOOLEAN, + value: serialized + }; + } // JavaScript numbers can be Int or Float values. + + + if (typeof serialized === 'number') { + var stringNum = String(serialized); + return integerStringRegExp.test(stringNum) ? { + kind: Kind.INT, + value: stringNum + } : { + kind: Kind.FLOAT, + value: stringNum + }; + } + + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if (isEnumType(type)) { + return { + kind: Kind.ENUM, + value: serialized + }; + } // ID types can use Int literals. + + + if (type === GraphQLID && integerStringRegExp.test(serialized)) { + return { + kind: Kind.INT, + value: serialized + }; + } + + return { + kind: Kind.STRING, + value: serialized + }; + } + + throw new TypeError("Cannot convert value to AST: ".concat(inspect(serialized))); + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ + +var integerStringRegExp = /^-?(0|[1-9][0-9]*)$/; \ No newline at end of file diff --git a/node_modules/graphql/utilities/buildASTSchema.js b/node_modules/graphql/utilities/buildASTSchema.js new file mode 100644 index 0000000..39a5cbf --- /dev/null +++ b/node_modules/graphql/utilities/buildASTSchema.js @@ -0,0 +1,487 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildASTSchema = buildASTSchema; +exports.getDescription = getDescription; +exports.buildSchema = buildSchema; +exports.ASTDefinitionBuilder = void 0; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap")); + +var _valueFromAST = require("./valueFromAST"); + +var _validate = require("../validation/validate"); + +var _blockStringValue = _interopRequireDefault(require("../language/blockStringValue")); + +var _lexer = require("../language/lexer"); + +var _parser = require("../language/parser"); + +var _values = require("../execution/values"); + +var _kinds = require("../language/kinds"); + +var _predicates = require("../language/predicates"); + +var _definition = require("../type/definition"); + +var _directives = require("../type/directives"); + +var _introspection = require("../type/introspection"); + +var _scalars = require("../type/scalars"); + +var _schema = require("../type/schema"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +function buildASTSchema(documentAST, options) { + !(documentAST && documentAST.kind === _kinds.Kind.DOCUMENT) ? (0, _invariant.default)(0, 'Must provide valid Document AST') : void 0; + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + (0, _validate.assertValidSDL)(documentAST); + } + + var schemaDef; + var typeDefs = []; + var nodeMap = Object.create(null); + var directiveDefs = []; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var def = documentAST.definitions[i]; + + if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if ((0, _predicates.isTypeDefinitionNode)(def)) { + var typeName = def.name.value; + + if (nodeMap[typeName]) { + throw new Error("Type \"".concat(typeName, "\" was defined more than once.")); + } + + typeDefs.push(def); + nodeMap[typeName] = def; + } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } + } + + var operationTypes = schemaDef ? getOperationTypes(schemaDef) : { + query: nodeMap.Query, + mutation: nodeMap.Mutation, + subscription: nodeMap.Subscription + }; + var definitionBuilder = new ASTDefinitionBuilder(nodeMap, options, function (typeRef) { + throw new Error("Type \"".concat(typeRef.name.value, "\" not found in document.")); + }); + var directives = directiveDefs.map(function (def) { + return definitionBuilder.buildDirective(def); + }); // If specified directives were not explicitly declared, add them. + + if (!directives.some(function (directive) { + return directive.name === 'skip'; + })) { + directives.push(_directives.GraphQLSkipDirective); + } + + if (!directives.some(function (directive) { + return directive.name === 'include'; + })) { + directives.push(_directives.GraphQLIncludeDirective); + } + + if (!directives.some(function (directive) { + return directive.name === 'deprecated'; + })) { + directives.push(_directives.GraphQLDeprecatedDirective); + } // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + return new _schema.GraphQLSchema({ + query: operationTypes.query ? definitionBuilder.buildType(operationTypes.query) : null, + mutation: operationTypes.mutation ? definitionBuilder.buildType(operationTypes.mutation) : null, + subscription: operationTypes.subscription ? definitionBuilder.buildType(operationTypes.subscription) : null, + types: typeDefs.map(function (node) { + return definitionBuilder.buildType(node); + }), + directives: directives, + astNode: schemaDef, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames + }); + + function getOperationTypes(schema) { + var opTypes = {}; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schema.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var operationType = _step.value; + var _typeName = operationType.type.name.value; + var operation = operationType.operation; + + if (opTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } + + if (!nodeMap[_typeName]) { + throw new Error("Specified ".concat(operation, " type \"").concat(_typeName, "\" not found in document.")); + } + + opTypes[operation] = operationType.type; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return opTypes; + } +} + +var ASTDefinitionBuilder = +/*#__PURE__*/ +function () { + function ASTDefinitionBuilder(typeDefinitionsMap, options, resolveType) { + _defineProperty(this, "_typeDefinitionsMap", void 0); + + _defineProperty(this, "_options", void 0); + + _defineProperty(this, "_resolveType", void 0); + + _defineProperty(this, "_cache", void 0); + + this._typeDefinitionsMap = typeDefinitionsMap; + this._options = options; + this._resolveType = resolveType; // Initialize to the GraphQL built in scalars and introspection types. + + this._cache = (0, _keyMap.default)(_scalars.specifiedScalarTypes.concat(_introspection.introspectionTypes), function (type) { + return type.name; + }); + } + + var _proto = ASTDefinitionBuilder.prototype; + + _proto.buildType = function buildType(node) { + var typeName = node.name.value; + + if (!this._cache[typeName]) { + if (node.kind === _kinds.Kind.NAMED_TYPE) { + var defNode = this._typeDefinitionsMap[typeName]; + this._cache[typeName] = defNode ? this._makeSchemaDef(defNode) : this._resolveType(node); + } else { + this._cache[typeName] = this._makeSchemaDef(node); + } + } + + return this._cache[typeName]; + }; + + _proto._buildWrappedType = function _buildWrappedType(typeNode) { + if (typeNode.kind === _kinds.Kind.LIST_TYPE) { + return (0, _definition.GraphQLList)(this._buildWrappedType(typeNode.type)); + } + + if (typeNode.kind === _kinds.Kind.NON_NULL_TYPE) { + return (0, _definition.GraphQLNonNull)( // Note: GraphQLNonNull constructor validates this type + this._buildWrappedType(typeNode.type)); + } + + return this.buildType(typeNode); + }; + + _proto.buildDirective = function buildDirective(directiveNode) { + return new _directives.GraphQLDirective({ + name: directiveNode.name.value, + description: getDescription(directiveNode, this._options), + locations: directiveNode.locations.map(function (node) { + return node.value; + }), + args: directiveNode.arguments && this._makeInputValues(directiveNode.arguments), + astNode: directiveNode + }); + }; + + _proto.buildField = function buildField(field) { + return { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: this._buildWrappedType(field.type), + description: getDescription(field, this._options), + args: field.arguments && this._makeInputValues(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + }; + + _proto.buildInputField = function buildInputField(value) { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + var type = this._buildWrappedType(value.type); + + return { + name: value.name.value, + type: type, + description: getDescription(value, this._options), + defaultValue: (0, _valueFromAST.valueFromAST)(value.defaultValue, type), + astNode: value + }; + }; + + _proto.buildEnumValue = function buildEnumValue(value) { + return { + description: getDescription(value, this._options), + deprecationReason: getDeprecationReason(value), + astNode: value + }; + }; + + _proto._makeSchemaDef = function _makeSchemaDef(def) { + switch (def.kind) { + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + return this._makeTypeDef(def); + + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + return this._makeInterfaceDef(def); + + case _kinds.Kind.ENUM_TYPE_DEFINITION: + return this._makeEnumDef(def); + + case _kinds.Kind.UNION_TYPE_DEFINITION: + return this._makeUnionDef(def); + + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + return this._makeScalarDef(def); + + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + return this._makeInputObjectDef(def); + + default: + throw new Error("Type kind \"".concat(def.kind, "\" not supported.")); + } + }; + + _proto._makeTypeDef = function _makeTypeDef(def) { + var _this = this; + + var interfaces = def.interfaces; + return new _definition.GraphQLObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return _this._makeFieldDefMap(def); + }, + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces: interfaces ? function () { + return interfaces.map(function (ref) { + return _this.buildType(ref); + }); + } : [], + astNode: def + }); + }; + + _proto._makeFieldDefMap = function _makeFieldDefMap(def) { + var _this2 = this; + + return def.fields ? (0, _keyValMap.default)(def.fields, function (field) { + return field.name.value; + }, function (field) { + return _this2.buildField(field); + }) : {}; + }; + + _proto._makeInputValues = function _makeInputValues(values) { + var _this3 = this; + + return (0, _keyValMap.default)(values, function (value) { + return value.name.value; + }, function (value) { + return _this3.buildInputField(value); + }); + }; + + _proto._makeInterfaceDef = function _makeInterfaceDef(def) { + var _this4 = this; + + return new _definition.GraphQLInterfaceType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return _this4._makeFieldDefMap(def); + }, + astNode: def + }); + }; + + _proto._makeEnumDef = function _makeEnumDef(def) { + return new _definition.GraphQLEnumType({ + name: def.name.value, + description: getDescription(def, this._options), + values: this._makeValueDefMap(def), + astNode: def + }); + }; + + _proto._makeValueDefMap = function _makeValueDefMap(def) { + var _this5 = this; + + return def.values ? (0, _keyValMap.default)(def.values, function (enumValue) { + return enumValue.name.value; + }, function (enumValue) { + return _this5.buildEnumValue(enumValue); + }) : {}; + }; + + _proto._makeUnionDef = function _makeUnionDef(def) { + var _this6 = this; + + var types = def.types; + return new _definition.GraphQLUnionType({ + name: def.name.value, + description: getDescription(def, this._options), + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + types: types ? function () { + return types.map(function (ref) { + return _this6.buildType(ref); + }); + } : [], + astNode: def + }); + }; + + _proto._makeScalarDef = function _makeScalarDef(def) { + return new _definition.GraphQLScalarType({ + name: def.name.value, + description: getDescription(def, this._options), + astNode: def, + serialize: function serialize(value) { + return value; + } + }); + }; + + _proto._makeInputObjectDef = function _makeInputObjectDef(def) { + var _this7 = this; + + return new _definition.GraphQLInputObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return def.fields ? _this7._makeInputValues(def.fields) : {}; + }, + astNode: def + }); + }; + + return ASTDefinitionBuilder; +}(); +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ + + +exports.ASTDefinitionBuilder = ASTDefinitionBuilder; + +function getDeprecationReason(node) { + var deprecated = (0, _values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective, node); + return deprecated && deprecated.reason; +} +/** + * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ + + +function getDescription(node, options) { + if (node.description) { + return node.description.value; + } + + if (options && options.commentDescriptions) { + var rawValue = getLeadingCommentBlock(node); + + if (rawValue !== undefined) { + return (0, _blockStringValue.default)('\n' + rawValue); + } + } +} + +function getLeadingCommentBlock(node) { + var loc = node.loc; + + if (!loc) { + return; + } + + var comments = []; + var token = loc.startToken.prev; + + while (token && token.kind === _lexer.TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) { + var value = String(token.value); + comments.push(value); + token = token.prev; + } + + return comments.reverse().join('\n'); +} +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + + +function buildSchema(source, options) { + return buildASTSchema((0, _parser.parse)(source, options), options); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/buildASTSchema.js.flow b/node_modules/graphql/utilities/buildASTSchema.js.flow new file mode 100644 index 0000000..2319e74 --- /dev/null +++ b/node_modules/graphql/utilities/buildASTSchema.js.flow @@ -0,0 +1,506 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import type { ObjMap } from '../jsutils/ObjMap'; +import { valueFromAST } from './valueFromAST'; +import { assertValidSDL } from '../validation/validate'; +import blockStringValue from '../language/blockStringValue'; +import { TokenKind } from '../language/lexer'; +import { parse } from '../language/parser'; +import type { ParseOptions } from '../language/parser'; +import type { Source } from '../language/source'; +import { getDirectiveValues } from '../execution/values'; +import { Kind } from '../language/kinds'; + +import type { + DocumentNode, + TypeNode, + NamedTypeNode, + SchemaDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + StringValueNode, + Location, +} from '../language/ast'; +import { isTypeDefinitionNode } from '../language/predicates'; + +import type { DirectiveLocationEnum } from '../language/directiveLocation'; + +import type { + GraphQLType, + GraphQLNamedType, + GraphQLFieldConfig, + GraphQLEnumValueConfig, + GraphQLInputField, +} from '../type/definition'; + +import { + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, +} from '../type/definition'; + +import { + GraphQLDirective, + GraphQLSkipDirective, + GraphQLIncludeDirective, + GraphQLDeprecatedDirective, +} from '../type/directives'; + +import { introspectionTypes } from '../type/introspection'; + +import { specifiedScalarTypes } from '../type/scalars'; + +import { GraphQLSchema } from '../type/schema'; +import type { GraphQLSchemaValidationOptions } from '../type/schema'; + +export type BuildSchemaOptions = { + ...GraphQLSchemaValidationOptions, + + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean, + + /** + * Set to true to assume the SDL is valid. + * + * Default: false + */ + assumeValidSDL?: boolean, +}; + +/** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function buildASTSchema( + documentAST: DocumentNode, + options?: BuildSchemaOptions, +): GraphQLSchema { + invariant( + documentAST && documentAST.kind === Kind.DOCUMENT, + 'Must provide valid Document AST', + ); + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + assertValidSDL(documentAST); + } + + let schemaDef: ?SchemaDefinitionNode; + + const typeDefs: Array = []; + const nodeMap: ObjMap = Object.create(null); + const directiveDefs: Array = []; + for (let i = 0; i < documentAST.definitions.length; i++) { + const def = documentAST.definitions[i]; + if (def.kind === Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (isTypeDefinitionNode(def)) { + const typeName = def.name.value; + if (nodeMap[typeName]) { + throw new Error(`Type "${typeName}" was defined more than once.`); + } + typeDefs.push(def); + nodeMap[typeName] = def; + } else if (def.kind === Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } + } + + const operationTypes = schemaDef + ? getOperationTypes(schemaDef) + : { + query: nodeMap.Query, + mutation: nodeMap.Mutation, + subscription: nodeMap.Subscription, + }; + + const definitionBuilder = new ASTDefinitionBuilder( + nodeMap, + options, + typeRef => { + throw new Error(`Type "${typeRef.name.value}" not found in document.`); + }, + ); + + const directives = directiveDefs.map(def => + definitionBuilder.buildDirective(def), + ); + + // If specified directives were not explicitly declared, add them. + if (!directives.some(directive => directive.name === 'skip')) { + directives.push(GraphQLSkipDirective); + } + + if (!directives.some(directive => directive.name === 'include')) { + directives.push(GraphQLIncludeDirective); + } + + if (!directives.some(directive => directive.name === 'deprecated')) { + directives.push(GraphQLDeprecatedDirective); + } + + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + return new GraphQLSchema({ + query: operationTypes.query + ? (definitionBuilder.buildType(operationTypes.query): any) + : null, + mutation: operationTypes.mutation + ? (definitionBuilder.buildType(operationTypes.mutation): any) + : null, + subscription: operationTypes.subscription + ? (definitionBuilder.buildType(operationTypes.subscription): any) + : null, + types: typeDefs.map(node => definitionBuilder.buildType(node)), + directives, + astNode: schemaDef, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames, + }); + + function getOperationTypes(schema: SchemaDefinitionNode) { + const opTypes = {}; + for (const operationType of schema.operationTypes) { + const typeName = operationType.type.name.value; + const operation = operationType.operation; + if (opTypes[operation]) { + throw new Error(`Must provide only one ${operation} type in schema.`); + } + if (!nodeMap[typeName]) { + throw new Error( + `Specified ${operation} type "${typeName}" not found in document.`, + ); + } + opTypes[operation] = operationType.type; + } + return opTypes; + } +} + +type TypeDefinitionsMap = ObjMap; +type TypeResolver = (typeRef: NamedTypeNode) => GraphQLNamedType; + +export class ASTDefinitionBuilder { + _typeDefinitionsMap: TypeDefinitionsMap; + _options: ?BuildSchemaOptions; + _resolveType: TypeResolver; + _cache: ObjMap; + + constructor( + typeDefinitionsMap: TypeDefinitionsMap, + options: ?BuildSchemaOptions, + resolveType: TypeResolver, + ) { + this._typeDefinitionsMap = typeDefinitionsMap; + this._options = options; + this._resolveType = resolveType; + // Initialize to the GraphQL built in scalars and introspection types. + this._cache = keyMap( + specifiedScalarTypes.concat(introspectionTypes), + type => type.name, + ); + } + + buildType(node: NamedTypeNode | TypeDefinitionNode): GraphQLNamedType { + const typeName = node.name.value; + if (!this._cache[typeName]) { + if (node.kind === Kind.NAMED_TYPE) { + const defNode = this._typeDefinitionsMap[typeName]; + this._cache[typeName] = defNode + ? this._makeSchemaDef(defNode) + : this._resolveType(node); + } else { + this._cache[typeName] = this._makeSchemaDef(node); + } + } + return this._cache[typeName]; + } + + _buildWrappedType(typeNode: TypeNode): GraphQLType { + if (typeNode.kind === Kind.LIST_TYPE) { + return GraphQLList(this._buildWrappedType(typeNode.type)); + } + if (typeNode.kind === Kind.NON_NULL_TYPE) { + return GraphQLNonNull( + // Note: GraphQLNonNull constructor validates this type + (this._buildWrappedType(typeNode.type): any), + ); + } + return this.buildType(typeNode); + } + + buildDirective(directiveNode: DirectiveDefinitionNode): GraphQLDirective { + return new GraphQLDirective({ + name: directiveNode.name.value, + description: getDescription(directiveNode, this._options), + locations: directiveNode.locations.map( + node => ((node.value: any): DirectiveLocationEnum), + ), + args: + directiveNode.arguments && + this._makeInputValues(directiveNode.arguments), + astNode: directiveNode, + }); + } + + buildField(field: FieldDefinitionNode): GraphQLFieldConfig<*, *> { + return { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: (this._buildWrappedType(field.type): any), + description: getDescription(field, this._options), + args: field.arguments && this._makeInputValues(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + + buildInputField(value: InputValueDefinitionNode): GraphQLInputField { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type: any = this._buildWrappedType(value.type); + return { + name: value.name.value, + type, + description: getDescription(value, this._options), + defaultValue: valueFromAST(value.defaultValue, type), + astNode: value, + }; + } + + buildEnumValue(value: EnumValueDefinitionNode): GraphQLEnumValueConfig { + return { + description: getDescription(value, this._options), + deprecationReason: getDeprecationReason(value), + astNode: value, + }; + } + + _makeSchemaDef(def: TypeDefinitionNode): GraphQLNamedType { + switch (def.kind) { + case Kind.OBJECT_TYPE_DEFINITION: + return this._makeTypeDef(def); + case Kind.INTERFACE_TYPE_DEFINITION: + return this._makeInterfaceDef(def); + case Kind.ENUM_TYPE_DEFINITION: + return this._makeEnumDef(def); + case Kind.UNION_TYPE_DEFINITION: + return this._makeUnionDef(def); + case Kind.SCALAR_TYPE_DEFINITION: + return this._makeScalarDef(def); + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + return this._makeInputObjectDef(def); + default: + throw new Error(`Type kind "${def.kind}" not supported.`); + } + } + + _makeTypeDef(def: ObjectTypeDefinitionNode) { + const interfaces: ?$ReadOnlyArray = def.interfaces; + return new GraphQLObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: () => this._makeFieldDefMap(def), + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces: interfaces + ? () => interfaces.map(ref => (this.buildType(ref): any)) + : [], + astNode: def, + }); + } + + _makeFieldDefMap( + def: ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode, + ) { + return def.fields + ? keyValMap( + def.fields, + field => field.name.value, + field => this.buildField(field), + ) + : {}; + } + + _makeInputValues(values: $ReadOnlyArray) { + return keyValMap( + values, + value => value.name.value, + value => this.buildInputField(value), + ); + } + + _makeInterfaceDef(def: InterfaceTypeDefinitionNode) { + return new GraphQLInterfaceType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: () => this._makeFieldDefMap(def), + astNode: def, + }); + } + + _makeEnumDef(def: EnumTypeDefinitionNode) { + return new GraphQLEnumType({ + name: def.name.value, + description: getDescription(def, this._options), + values: this._makeValueDefMap(def), + astNode: def, + }); + } + + _makeValueDefMap(def: EnumTypeDefinitionNode) { + return def.values + ? keyValMap( + def.values, + enumValue => enumValue.name.value, + enumValue => this.buildEnumValue(enumValue), + ) + : {}; + } + + _makeUnionDef(def: UnionTypeDefinitionNode) { + const types: ?$ReadOnlyArray = def.types; + return new GraphQLUnionType({ + name: def.name.value, + description: getDescription(def, this._options), + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + types: types ? () => types.map(ref => (this.buildType(ref): any)) : [], + astNode: def, + }); + } + + _makeScalarDef(def: ScalarTypeDefinitionNode) { + return new GraphQLScalarType({ + name: def.name.value, + description: getDescription(def, this._options), + astNode: def, + serialize: value => value, + }); + } + + _makeInputObjectDef(def: InputObjectTypeDefinitionNode) { + return new GraphQLInputObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: () => (def.fields ? this._makeInputValues(def.fields) : {}), + astNode: def, + }); + } +} + +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ +function getDeprecationReason( + node: EnumValueDefinitionNode | FieldDefinitionNode, +): ?string { + const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node); + return deprecated && (deprecated.reason: any); +} + +/** + * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function getDescription( + node: { +description?: StringValueNode, +loc?: Location }, + options: ?BuildSchemaOptions, +): void | string { + if (node.description) { + return node.description.value; + } + if (options && options.commentDescriptions) { + const rawValue = getLeadingCommentBlock(node); + if (rawValue !== undefined) { + return blockStringValue('\n' + rawValue); + } + } +} + +function getLeadingCommentBlock(node): void | string { + const loc = node.loc; + if (!loc) { + return; + } + const comments = []; + let token = loc.startToken.prev; + while ( + token && + token.kind === TokenKind.COMMENT && + token.next && + token.prev && + token.line + 1 === token.next.line && + token.line !== token.prev.line + ) { + const value = String(token.value); + comments.push(value); + token = token.prev; + } + return comments.reverse().join('\n'); +} + +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ +export function buildSchema( + source: string | Source, + options?: BuildSchemaOptions & ParseOptions, +): GraphQLSchema { + return buildASTSchema(parse(source, options), options); +} diff --git a/node_modules/graphql/utilities/buildASTSchema.mjs b/node_modules/graphql/utilities/buildASTSchema.mjs new file mode 100644 index 0000000..a57c6d5 --- /dev/null +++ b/node_modules/graphql/utilities/buildASTSchema.mjs @@ -0,0 +1,464 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import { valueFromAST } from './valueFromAST'; +import { assertValidSDL } from '../validation/validate'; +import blockStringValue from '../language/blockStringValue'; +import { TokenKind } from '../language/lexer'; +import { parse } from '../language/parser'; +import { getDirectiveValues } from '../execution/values'; +import { Kind } from '../language/kinds'; +import { isTypeDefinitionNode } from '../language/predicates'; +import { GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull } from '../type/definition'; +import { GraphQLDirective, GraphQLSkipDirective, GraphQLIncludeDirective, GraphQLDeprecatedDirective } from '../type/directives'; +import { introspectionTypes } from '../type/introspection'; +import { specifiedScalarTypes } from '../type/scalars'; +import { GraphQLSchema } from '../type/schema'; + +/** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function buildASTSchema(documentAST, options) { + !(documentAST && documentAST.kind === Kind.DOCUMENT) ? invariant(0, 'Must provide valid Document AST') : void 0; + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + assertValidSDL(documentAST); + } + + var schemaDef; + var typeDefs = []; + var nodeMap = Object.create(null); + var directiveDefs = []; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var def = documentAST.definitions[i]; + + if (def.kind === Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (isTypeDefinitionNode(def)) { + var typeName = def.name.value; + + if (nodeMap[typeName]) { + throw new Error("Type \"".concat(typeName, "\" was defined more than once.")); + } + + typeDefs.push(def); + nodeMap[typeName] = def; + } else if (def.kind === Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } + } + + var operationTypes = schemaDef ? getOperationTypes(schemaDef) : { + query: nodeMap.Query, + mutation: nodeMap.Mutation, + subscription: nodeMap.Subscription + }; + var definitionBuilder = new ASTDefinitionBuilder(nodeMap, options, function (typeRef) { + throw new Error("Type \"".concat(typeRef.name.value, "\" not found in document.")); + }); + var directives = directiveDefs.map(function (def) { + return definitionBuilder.buildDirective(def); + }); // If specified directives were not explicitly declared, add them. + + if (!directives.some(function (directive) { + return directive.name === 'skip'; + })) { + directives.push(GraphQLSkipDirective); + } + + if (!directives.some(function (directive) { + return directive.name === 'include'; + })) { + directives.push(GraphQLIncludeDirective); + } + + if (!directives.some(function (directive) { + return directive.name === 'deprecated'; + })) { + directives.push(GraphQLDeprecatedDirective); + } // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + return new GraphQLSchema({ + query: operationTypes.query ? definitionBuilder.buildType(operationTypes.query) : null, + mutation: operationTypes.mutation ? definitionBuilder.buildType(operationTypes.mutation) : null, + subscription: operationTypes.subscription ? definitionBuilder.buildType(operationTypes.subscription) : null, + types: typeDefs.map(function (node) { + return definitionBuilder.buildType(node); + }), + directives: directives, + astNode: schemaDef, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames + }); + + function getOperationTypes(schema) { + var opTypes = {}; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schema.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var operationType = _step.value; + var _typeName = operationType.type.name.value; + var operation = operationType.operation; + + if (opTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } + + if (!nodeMap[_typeName]) { + throw new Error("Specified ".concat(operation, " type \"").concat(_typeName, "\" not found in document.")); + } + + opTypes[operation] = operationType.type; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return opTypes; + } +} +export var ASTDefinitionBuilder = +/*#__PURE__*/ +function () { + function ASTDefinitionBuilder(typeDefinitionsMap, options, resolveType) { + _defineProperty(this, "_typeDefinitionsMap", void 0); + + _defineProperty(this, "_options", void 0); + + _defineProperty(this, "_resolveType", void 0); + + _defineProperty(this, "_cache", void 0); + + this._typeDefinitionsMap = typeDefinitionsMap; + this._options = options; + this._resolveType = resolveType; // Initialize to the GraphQL built in scalars and introspection types. + + this._cache = keyMap(specifiedScalarTypes.concat(introspectionTypes), function (type) { + return type.name; + }); + } + + var _proto = ASTDefinitionBuilder.prototype; + + _proto.buildType = function buildType(node) { + var typeName = node.name.value; + + if (!this._cache[typeName]) { + if (node.kind === Kind.NAMED_TYPE) { + var defNode = this._typeDefinitionsMap[typeName]; + this._cache[typeName] = defNode ? this._makeSchemaDef(defNode) : this._resolveType(node); + } else { + this._cache[typeName] = this._makeSchemaDef(node); + } + } + + return this._cache[typeName]; + }; + + _proto._buildWrappedType = function _buildWrappedType(typeNode) { + if (typeNode.kind === Kind.LIST_TYPE) { + return GraphQLList(this._buildWrappedType(typeNode.type)); + } + + if (typeNode.kind === Kind.NON_NULL_TYPE) { + return GraphQLNonNull( // Note: GraphQLNonNull constructor validates this type + this._buildWrappedType(typeNode.type)); + } + + return this.buildType(typeNode); + }; + + _proto.buildDirective = function buildDirective(directiveNode) { + return new GraphQLDirective({ + name: directiveNode.name.value, + description: getDescription(directiveNode, this._options), + locations: directiveNode.locations.map(function (node) { + return node.value; + }), + args: directiveNode.arguments && this._makeInputValues(directiveNode.arguments), + astNode: directiveNode + }); + }; + + _proto.buildField = function buildField(field) { + return { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: this._buildWrappedType(field.type), + description: getDescription(field, this._options), + args: field.arguments && this._makeInputValues(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + }; + + _proto.buildInputField = function buildInputField(value) { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + var type = this._buildWrappedType(value.type); + + return { + name: value.name.value, + type: type, + description: getDescription(value, this._options), + defaultValue: valueFromAST(value.defaultValue, type), + astNode: value + }; + }; + + _proto.buildEnumValue = function buildEnumValue(value) { + return { + description: getDescription(value, this._options), + deprecationReason: getDeprecationReason(value), + astNode: value + }; + }; + + _proto._makeSchemaDef = function _makeSchemaDef(def) { + switch (def.kind) { + case Kind.OBJECT_TYPE_DEFINITION: + return this._makeTypeDef(def); + + case Kind.INTERFACE_TYPE_DEFINITION: + return this._makeInterfaceDef(def); + + case Kind.ENUM_TYPE_DEFINITION: + return this._makeEnumDef(def); + + case Kind.UNION_TYPE_DEFINITION: + return this._makeUnionDef(def); + + case Kind.SCALAR_TYPE_DEFINITION: + return this._makeScalarDef(def); + + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + return this._makeInputObjectDef(def); + + default: + throw new Error("Type kind \"".concat(def.kind, "\" not supported.")); + } + }; + + _proto._makeTypeDef = function _makeTypeDef(def) { + var _this = this; + + var interfaces = def.interfaces; + return new GraphQLObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return _this._makeFieldDefMap(def); + }, + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces: interfaces ? function () { + return interfaces.map(function (ref) { + return _this.buildType(ref); + }); + } : [], + astNode: def + }); + }; + + _proto._makeFieldDefMap = function _makeFieldDefMap(def) { + var _this2 = this; + + return def.fields ? keyValMap(def.fields, function (field) { + return field.name.value; + }, function (field) { + return _this2.buildField(field); + }) : {}; + }; + + _proto._makeInputValues = function _makeInputValues(values) { + var _this3 = this; + + return keyValMap(values, function (value) { + return value.name.value; + }, function (value) { + return _this3.buildInputField(value); + }); + }; + + _proto._makeInterfaceDef = function _makeInterfaceDef(def) { + var _this4 = this; + + return new GraphQLInterfaceType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return _this4._makeFieldDefMap(def); + }, + astNode: def + }); + }; + + _proto._makeEnumDef = function _makeEnumDef(def) { + return new GraphQLEnumType({ + name: def.name.value, + description: getDescription(def, this._options), + values: this._makeValueDefMap(def), + astNode: def + }); + }; + + _proto._makeValueDefMap = function _makeValueDefMap(def) { + var _this5 = this; + + return def.values ? keyValMap(def.values, function (enumValue) { + return enumValue.name.value; + }, function (enumValue) { + return _this5.buildEnumValue(enumValue); + }) : {}; + }; + + _proto._makeUnionDef = function _makeUnionDef(def) { + var _this6 = this; + + var types = def.types; + return new GraphQLUnionType({ + name: def.name.value, + description: getDescription(def, this._options), + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + types: types ? function () { + return types.map(function (ref) { + return _this6.buildType(ref); + }); + } : [], + astNode: def + }); + }; + + _proto._makeScalarDef = function _makeScalarDef(def) { + return new GraphQLScalarType({ + name: def.name.value, + description: getDescription(def, this._options), + astNode: def, + serialize: function serialize(value) { + return value; + } + }); + }; + + _proto._makeInputObjectDef = function _makeInputObjectDef(def) { + var _this7 = this; + + return new GraphQLInputObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return def.fields ? _this7._makeInputValues(def.fields) : {}; + }, + astNode: def + }); + }; + + return ASTDefinitionBuilder; +}(); +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ + +function getDeprecationReason(node) { + var deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node); + return deprecated && deprecated.reason; +} +/** + * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ + + +export function getDescription(node, options) { + if (node.description) { + return node.description.value; + } + + if (options && options.commentDescriptions) { + var rawValue = getLeadingCommentBlock(node); + + if (rawValue !== undefined) { + return blockStringValue('\n' + rawValue); + } + } +} + +function getLeadingCommentBlock(node) { + var loc = node.loc; + + if (!loc) { + return; + } + + var comments = []; + var token = loc.startToken.prev; + + while (token && token.kind === TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) { + var value = String(token.value); + comments.push(value); + token = token.prev; + } + + return comments.reverse().join('\n'); +} +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + + +export function buildSchema(source, options) { + return buildASTSchema(parse(source, options), options); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/buildClientSchema.js b/node_modules/graphql/utilities/buildClientSchema.js new file mode 100644 index 0000000..432f844 --- /dev/null +++ b/node_modules/graphql/utilities/buildClientSchema.js @@ -0,0 +1,323 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildClientSchema = buildClientSchema; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap")); + +var _valueFromAST = require("./valueFromAST"); + +var _parser = require("../language/parser"); + +var _schema = require("../type/schema"); + +var _definition = require("../type/definition"); + +var _directives = require("../type/directives"); + +var _introspection = require("../type/introspection"); + +var _scalars = require("../type/scalars"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + */ +function buildClientSchema(introspection, options) { + // Get the schema from the introspection result. + var schemaIntrospection = introspection.__schema; // Converts the list of types into a keyMap based on the type names. + + var typeIntrospectionMap = (0, _keyMap.default)(schemaIntrospection.types, function (type) { + return type.name; + }); // A cache to use to store the actual GraphQLType definition objects by name. + // Initialize to the GraphQL built in scalars. All functions below are inline + // so that this type def cache is within the scope of the closure. + + var typeDefCache = (0, _keyMap.default)(_scalars.specifiedScalarTypes.concat(_introspection.introspectionTypes), function (type) { + return type.name; + }); // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + + function getType(typeRef) { + if (typeRef.kind === _introspection.TypeKind.LIST) { + var itemRef = typeRef.ofType; + + if (!itemRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + return (0, _definition.GraphQLList)(getType(itemRef)); + } + + if (typeRef.kind === _introspection.TypeKind.NON_NULL) { + var nullableRef = typeRef.ofType; + + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + var nullableType = getType(nullableRef); + return (0, _definition.GraphQLNonNull)((0, _definition.assertNullableType)(nullableType)); + } + + if (!typeRef.name) { + throw new Error('Unknown type reference: ' + (0, _inspect.default)(typeRef)); + } + + return getNamedType(typeRef.name); + } + + function getNamedType(typeName) { + if (typeDefCache[typeName]) { + return typeDefCache[typeName]; + } + + var typeIntrospection = typeIntrospectionMap[typeName]; + + if (!typeIntrospection) { + throw new Error("Invalid or incomplete schema, unknown type: ".concat(typeName, ". Ensure ") + 'that a full introspection query is used in order to build a ' + 'client schema.'); + } + + var typeDef = buildType(typeIntrospection); + typeDefCache[typeName] = typeDef; + return typeDef; + } + + function getInputType(typeRef) { + var type = getType(typeRef); + !(0, _definition.isInputType)(type) ? (0, _invariant.default)(0, 'Introspection must provide input type for arguments.') : void 0; + return type; + } + + function getOutputType(typeRef) { + var type = getType(typeRef); + !(0, _definition.isOutputType)(type) ? (0, _invariant.default)(0, 'Introspection must provide output type for fields.') : void 0; + return type; + } + + function getObjectType(typeRef) { + var type = getType(typeRef); + return (0, _definition.assertObjectType)(type); + } + + function getInterfaceType(typeRef) { + var type = getType(typeRef); + return (0, _definition.assertInterfaceType)(type); + } // Given a type's introspection result, construct the correct + // GraphQLType instance. + + + function buildType(type) { + if (type && type.name && type.kind) { + switch (type.kind) { + case _introspection.TypeKind.SCALAR: + return buildScalarDef(type); + + case _introspection.TypeKind.OBJECT: + return buildObjectDef(type); + + case _introspection.TypeKind.INTERFACE: + return buildInterfaceDef(type); + + case _introspection.TypeKind.UNION: + return buildUnionDef(type); + + case _introspection.TypeKind.ENUM: + return buildEnumDef(type); + + case _introspection.TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + + throw new Error('Invalid or incomplete introspection result. Ensure that a full ' + 'introspection query is used in order to build a client schema:' + (0, _inspect.default)(type)); + } + + function buildScalarDef(scalarIntrospection) { + return new _definition.GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + serialize: function serialize(value) { + return value; + } + }); + } + + function buildObjectDef(objectIntrospection) { + if (!objectIntrospection.interfaces) { + throw new Error('Introspection result missing interfaces: ' + (0, _inspect.default)(objectIntrospection)); + } + + return new _definition.GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: function interfaces() { + return objectIntrospection.interfaces.map(getInterfaceType); + }, + fields: function fields() { + return buildFieldDefMap(objectIntrospection); + } + }); + } + + function buildInterfaceDef(interfaceIntrospection) { + return new _definition.GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + fields: function fields() { + return buildFieldDefMap(interfaceIntrospection); + } + }); + } + + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + throw new Error('Introspection result missing possibleTypes: ' + (0, _inspect.default)(unionIntrospection)); + } + + return new _definition.GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: function types() { + return unionIntrospection.possibleTypes.map(getObjectType); + } + }); + } + + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + throw new Error('Introspection result missing enumValues: ' + (0, _inspect.default)(enumIntrospection)); + } + + return new _definition.GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: (0, _keyValMap.default)(enumIntrospection.enumValues, function (valueIntrospection) { + return valueIntrospection.name; + }, function (valueIntrospection) { + return { + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason + }; + }) + }); + } + + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + throw new Error('Introspection result missing inputFields: ' + (0, _inspect.default)(inputObjectIntrospection)); + } + + return new _definition.GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: function fields() { + return buildInputValueDefMap(inputObjectIntrospection.inputFields); + } + }); + } + + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error('Introspection result missing fields: ' + (0, _inspect.default)(typeIntrospection)); + } + + return (0, _keyValMap.default)(typeIntrospection.fields, function (fieldIntrospection) { + return fieldIntrospection.name; + }, function (fieldIntrospection) { + if (!fieldIntrospection.args) { + throw new Error('Introspection result missing field args: ' + (0, _inspect.default)(fieldIntrospection)); + } + + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type: getOutputType(fieldIntrospection.type), + args: buildInputValueDefMap(fieldIntrospection.args) + }; + }); + } + + function buildInputValueDefMap(inputValueIntrospections) { + return (0, _keyValMap.default)(inputValueIntrospections, function (inputValue) { + return inputValue.name; + }, buildInputValue); + } + + function buildInputValue(inputValueIntrospection) { + var type = getInputType(inputValueIntrospection.type); + var defaultValue = inputValueIntrospection.defaultValue ? (0, _valueFromAST.valueFromAST)((0, _parser.parseValue)(inputValueIntrospection.defaultValue), type) : undefined; + return { + description: inputValueIntrospection.description, + type: type, + defaultValue: defaultValue + }; + } + + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + throw new Error('Introspection result missing directive args: ' + (0, _inspect.default)(directiveIntrospection)); + } + + if (!directiveIntrospection.locations) { + throw new Error('Introspection result missing directive locations: ' + (0, _inspect.default)(directiveIntrospection)); + } + + return new _directives.GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args) + }); + } // Iterate through all types, getting the type definition for each, ensuring + // that any type not directly referenced by a field will get created. + + + var types = schemaIntrospection.types.map(function (typeIntrospection) { + return getNamedType(typeIntrospection.name); + }); // Get the root Query, Mutation, and Subscription types. + + var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null; + var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null; + var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + var directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types. + + return new _schema.GraphQLSchema({ + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: types, + directives: directives, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/buildClientSchema.js.flow b/node_modules/graphql/utilities/buildClientSchema.js.flow new file mode 100644 index 0000000..531036d --- /dev/null +++ b/node_modules/graphql/utilities/buildClientSchema.js.flow @@ -0,0 +1,396 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import { valueFromAST } from './valueFromAST'; +import { parseValue } from '../language/parser'; +import { GraphQLSchema } from '../type/schema'; + +import { + isInputType, + isOutputType, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, + assertNullableType, + assertObjectType, + assertInterfaceType, +} from '../type/definition'; + +import type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLNamedType, +} from '../type/definition'; + +import { GraphQLDirective } from '../type/directives'; + +import { introspectionTypes, TypeKind } from '../type/introspection'; + +import { specifiedScalarTypes } from '../type/scalars'; + +import type { + IntrospectionQuery, + IntrospectionType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionInputTypeRef, + IntrospectionOutputTypeRef, + IntrospectionNamedTypeRef, +} from './introspectionQuery'; + +import type { GraphQLSchemaValidationOptions } from '../type/schema'; + +type Options = {| + ...GraphQLSchemaValidationOptions, +|}; + +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + */ +export function buildClientSchema( + introspection: IntrospectionQuery, + options?: Options, +): GraphQLSchema { + // Get the schema from the introspection result. + const schemaIntrospection = introspection.__schema; + + // Converts the list of types into a keyMap based on the type names. + const typeIntrospectionMap = keyMap( + schemaIntrospection.types, + type => type.name, + ); + + // A cache to use to store the actual GraphQLType definition objects by name. + // Initialize to the GraphQL built in scalars. All functions below are inline + // so that this type def cache is within the scope of the closure. + const typeDefCache = keyMap( + specifiedScalarTypes.concat(introspectionTypes), + type => type.name, + ); + + // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + function getType(typeRef: IntrospectionTypeRef): GraphQLType { + if (typeRef.kind === TypeKind.LIST) { + const itemRef = typeRef.ofType; + if (!itemRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + return GraphQLList(getType(itemRef)); + } + if (typeRef.kind === TypeKind.NON_NULL) { + const nullableRef = typeRef.ofType; + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + const nullableType = getType(nullableRef); + return GraphQLNonNull(assertNullableType(nullableType)); + } + if (!typeRef.name) { + throw new Error('Unknown type reference: ' + inspect(typeRef)); + } + return getNamedType(typeRef.name); + } + + function getNamedType(typeName: string): GraphQLNamedType { + if (typeDefCache[typeName]) { + return typeDefCache[typeName]; + } + const typeIntrospection = typeIntrospectionMap[typeName]; + if (!typeIntrospection) { + throw new Error( + `Invalid or incomplete schema, unknown type: ${typeName}. Ensure ` + + 'that a full introspection query is used in order to build a ' + + 'client schema.', + ); + } + const typeDef = buildType(typeIntrospection); + typeDefCache[typeName] = typeDef; + return typeDef; + } + + function getInputType(typeRef: IntrospectionInputTypeRef): GraphQLInputType { + const type = getType(typeRef); + invariant( + isInputType(type), + 'Introspection must provide input type for arguments.', + ); + return type; + } + + function getOutputType( + typeRef: IntrospectionOutputTypeRef, + ): GraphQLOutputType { + const type = getType(typeRef); + invariant( + isOutputType(type), + 'Introspection must provide output type for fields.', + ); + return type; + } + + function getObjectType( + typeRef: IntrospectionNamedTypeRef, + ): GraphQLObjectType { + const type = getType(typeRef); + return assertObjectType(type); + } + + function getInterfaceType( + typeRef: IntrospectionTypeRef, + ): GraphQLInterfaceType { + const type = getType(typeRef); + return assertInterfaceType(type); + } + + // Given a type's introspection result, construct the correct + // GraphQLType instance. + function buildType(type: IntrospectionType): GraphQLNamedType { + if (type && type.name && type.kind) { + switch (type.kind) { + case TypeKind.SCALAR: + return buildScalarDef(type); + case TypeKind.OBJECT: + return buildObjectDef(type); + case TypeKind.INTERFACE: + return buildInterfaceDef(type); + case TypeKind.UNION: + return buildUnionDef(type); + case TypeKind.ENUM: + return buildEnumDef(type); + case TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + throw new Error( + 'Invalid or incomplete introspection result. Ensure that a full ' + + 'introspection query is used in order to build a client schema:' + + inspect(type), + ); + } + + function buildScalarDef( + scalarIntrospection: IntrospectionScalarType, + ): GraphQLScalarType { + return new GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + serialize: value => value, + }); + } + + function buildObjectDef( + objectIntrospection: IntrospectionObjectType, + ): GraphQLObjectType { + if (!objectIntrospection.interfaces) { + throw new Error( + 'Introspection result missing interfaces: ' + + inspect(objectIntrospection), + ); + } + return new GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: () => objectIntrospection.interfaces.map(getInterfaceType), + fields: () => buildFieldDefMap(objectIntrospection), + }); + } + + function buildInterfaceDef( + interfaceIntrospection: IntrospectionInterfaceType, + ): GraphQLInterfaceType { + return new GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + fields: () => buildFieldDefMap(interfaceIntrospection), + }); + } + + function buildUnionDef( + unionIntrospection: IntrospectionUnionType, + ): GraphQLUnionType { + if (!unionIntrospection.possibleTypes) { + throw new Error( + 'Introspection result missing possibleTypes: ' + + inspect(unionIntrospection), + ); + } + return new GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: () => unionIntrospection.possibleTypes.map(getObjectType), + }); + } + + function buildEnumDef( + enumIntrospection: IntrospectionEnumType, + ): GraphQLEnumType { + if (!enumIntrospection.enumValues) { + throw new Error( + 'Introspection result missing enumValues: ' + + inspect(enumIntrospection), + ); + } + return new GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: keyValMap( + enumIntrospection.enumValues, + valueIntrospection => valueIntrospection.name, + valueIntrospection => ({ + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason, + }), + ), + }); + } + + function buildInputObjectDef( + inputObjectIntrospection: IntrospectionInputObjectType, + ): GraphQLInputObjectType { + if (!inputObjectIntrospection.inputFields) { + throw new Error( + 'Introspection result missing inputFields: ' + + inspect(inputObjectIntrospection), + ); + } + return new GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields), + }); + } + + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error( + 'Introspection result missing fields: ' + inspect(typeIntrospection), + ); + } + return keyValMap( + typeIntrospection.fields, + fieldIntrospection => fieldIntrospection.name, + fieldIntrospection => { + if (!fieldIntrospection.args) { + throw new Error( + 'Introspection result missing field args: ' + + inspect(fieldIntrospection), + ); + } + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type: getOutputType(fieldIntrospection.type), + args: buildInputValueDefMap(fieldIntrospection.args), + }; + }, + ); + } + + function buildInputValueDefMap(inputValueIntrospections) { + return keyValMap( + inputValueIntrospections, + inputValue => inputValue.name, + buildInputValue, + ); + } + + function buildInputValue(inputValueIntrospection) { + const type = getInputType(inputValueIntrospection.type); + const defaultValue = inputValueIntrospection.defaultValue + ? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type) + : undefined; + return { + description: inputValueIntrospection.description, + type, + defaultValue, + }; + } + + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + throw new Error( + 'Introspection result missing directive args: ' + + inspect(directiveIntrospection), + ); + } + if (!directiveIntrospection.locations) { + throw new Error( + 'Introspection result missing directive locations: ' + + inspect(directiveIntrospection), + ); + } + return new GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args), + }); + } + + // Iterate through all types, getting the type definition for each, ensuring + // that any type not directly referenced by a field will get created. + const types = schemaIntrospection.types.map(typeIntrospection => + getNamedType(typeIntrospection.name), + ); + + // Get the root Query, Mutation, and Subscription types. + const queryType = schemaIntrospection.queryType + ? getObjectType(schemaIntrospection.queryType) + : null; + + const mutationType = schemaIntrospection.mutationType + ? getObjectType(schemaIntrospection.mutationType) + : null; + + const subscriptionType = schemaIntrospection.subscriptionType + ? getObjectType(schemaIntrospection.subscriptionType) + : null; + + // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + const directives = schemaIntrospection.directives + ? schemaIntrospection.directives.map(buildDirective) + : []; + + // Then produce and return a Schema with these types. + return new GraphQLSchema({ + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types, + directives, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames, + }); +} diff --git a/node_modules/graphql/utilities/buildClientSchema.mjs b/node_modules/graphql/utilities/buildClientSchema.mjs new file mode 100644 index 0000000..8393622 --- /dev/null +++ b/node_modules/graphql/utilities/buildClientSchema.mjs @@ -0,0 +1,303 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import { valueFromAST } from './valueFromAST'; +import { parseValue } from '../language/parser'; +import { GraphQLSchema } from '../type/schema'; +import { isInputType, isOutputType, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, assertNullableType, assertObjectType, assertInterfaceType } from '../type/definition'; +import { GraphQLDirective } from '../type/directives'; +import { introspectionTypes, TypeKind } from '../type/introspection'; +import { specifiedScalarTypes } from '../type/scalars'; + +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + */ +export function buildClientSchema(introspection, options) { + // Get the schema from the introspection result. + var schemaIntrospection = introspection.__schema; // Converts the list of types into a keyMap based on the type names. + + var typeIntrospectionMap = keyMap(schemaIntrospection.types, function (type) { + return type.name; + }); // A cache to use to store the actual GraphQLType definition objects by name. + // Initialize to the GraphQL built in scalars. All functions below are inline + // so that this type def cache is within the scope of the closure. + + var typeDefCache = keyMap(specifiedScalarTypes.concat(introspectionTypes), function (type) { + return type.name; + }); // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + + function getType(typeRef) { + if (typeRef.kind === TypeKind.LIST) { + var itemRef = typeRef.ofType; + + if (!itemRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + return GraphQLList(getType(itemRef)); + } + + if (typeRef.kind === TypeKind.NON_NULL) { + var nullableRef = typeRef.ofType; + + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + var nullableType = getType(nullableRef); + return GraphQLNonNull(assertNullableType(nullableType)); + } + + if (!typeRef.name) { + throw new Error('Unknown type reference: ' + inspect(typeRef)); + } + + return getNamedType(typeRef.name); + } + + function getNamedType(typeName) { + if (typeDefCache[typeName]) { + return typeDefCache[typeName]; + } + + var typeIntrospection = typeIntrospectionMap[typeName]; + + if (!typeIntrospection) { + throw new Error("Invalid or incomplete schema, unknown type: ".concat(typeName, ". Ensure ") + 'that a full introspection query is used in order to build a ' + 'client schema.'); + } + + var typeDef = buildType(typeIntrospection); + typeDefCache[typeName] = typeDef; + return typeDef; + } + + function getInputType(typeRef) { + var type = getType(typeRef); + !isInputType(type) ? invariant(0, 'Introspection must provide input type for arguments.') : void 0; + return type; + } + + function getOutputType(typeRef) { + var type = getType(typeRef); + !isOutputType(type) ? invariant(0, 'Introspection must provide output type for fields.') : void 0; + return type; + } + + function getObjectType(typeRef) { + var type = getType(typeRef); + return assertObjectType(type); + } + + function getInterfaceType(typeRef) { + var type = getType(typeRef); + return assertInterfaceType(type); + } // Given a type's introspection result, construct the correct + // GraphQLType instance. + + + function buildType(type) { + if (type && type.name && type.kind) { + switch (type.kind) { + case TypeKind.SCALAR: + return buildScalarDef(type); + + case TypeKind.OBJECT: + return buildObjectDef(type); + + case TypeKind.INTERFACE: + return buildInterfaceDef(type); + + case TypeKind.UNION: + return buildUnionDef(type); + + case TypeKind.ENUM: + return buildEnumDef(type); + + case TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + + throw new Error('Invalid or incomplete introspection result. Ensure that a full ' + 'introspection query is used in order to build a client schema:' + inspect(type)); + } + + function buildScalarDef(scalarIntrospection) { + return new GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + serialize: function serialize(value) { + return value; + } + }); + } + + function buildObjectDef(objectIntrospection) { + if (!objectIntrospection.interfaces) { + throw new Error('Introspection result missing interfaces: ' + inspect(objectIntrospection)); + } + + return new GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: function interfaces() { + return objectIntrospection.interfaces.map(getInterfaceType); + }, + fields: function fields() { + return buildFieldDefMap(objectIntrospection); + } + }); + } + + function buildInterfaceDef(interfaceIntrospection) { + return new GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + fields: function fields() { + return buildFieldDefMap(interfaceIntrospection); + } + }); + } + + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + throw new Error('Introspection result missing possibleTypes: ' + inspect(unionIntrospection)); + } + + return new GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: function types() { + return unionIntrospection.possibleTypes.map(getObjectType); + } + }); + } + + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + throw new Error('Introspection result missing enumValues: ' + inspect(enumIntrospection)); + } + + return new GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: keyValMap(enumIntrospection.enumValues, function (valueIntrospection) { + return valueIntrospection.name; + }, function (valueIntrospection) { + return { + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason + }; + }) + }); + } + + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + throw new Error('Introspection result missing inputFields: ' + inspect(inputObjectIntrospection)); + } + + return new GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: function fields() { + return buildInputValueDefMap(inputObjectIntrospection.inputFields); + } + }); + } + + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error('Introspection result missing fields: ' + inspect(typeIntrospection)); + } + + return keyValMap(typeIntrospection.fields, function (fieldIntrospection) { + return fieldIntrospection.name; + }, function (fieldIntrospection) { + if (!fieldIntrospection.args) { + throw new Error('Introspection result missing field args: ' + inspect(fieldIntrospection)); + } + + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type: getOutputType(fieldIntrospection.type), + args: buildInputValueDefMap(fieldIntrospection.args) + }; + }); + } + + function buildInputValueDefMap(inputValueIntrospections) { + return keyValMap(inputValueIntrospections, function (inputValue) { + return inputValue.name; + }, buildInputValue); + } + + function buildInputValue(inputValueIntrospection) { + var type = getInputType(inputValueIntrospection.type); + var defaultValue = inputValueIntrospection.defaultValue ? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type) : undefined; + return { + description: inputValueIntrospection.description, + type: type, + defaultValue: defaultValue + }; + } + + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + throw new Error('Introspection result missing directive args: ' + inspect(directiveIntrospection)); + } + + if (!directiveIntrospection.locations) { + throw new Error('Introspection result missing directive locations: ' + inspect(directiveIntrospection)); + } + + return new GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args) + }); + } // Iterate through all types, getting the type definition for each, ensuring + // that any type not directly referenced by a field will get created. + + + var types = schemaIntrospection.types.map(function (typeIntrospection) { + return getNamedType(typeIntrospection.name); + }); // Get the root Query, Mutation, and Subscription types. + + var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null; + var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null; + var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + var directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types. + + return new GraphQLSchema({ + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: types, + directives: directives, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/coerceValue.js b/node_modules/graphql/utilities/coerceValue.js new file mode 100644 index 0000000..17df0ce --- /dev/null +++ b/node_modules/graphql/utilities/coerceValue.js @@ -0,0 +1,202 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.coerceValue = coerceValue; + +var _iterall = require("iterall"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _orList = _interopRequireDefault(require("../jsutils/orList")); + +var _suggestionList = _interopRequireDefault(require("../jsutils/suggestionList")); + +var _GraphQLError = require("../error/GraphQLError"); + +var _definition = require("../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Coerces a JavaScript value given a GraphQL Type. + * + * Returns either a value which is valid for the provided type or a list of + * encountered coercion errors. + * + */ +function coerceValue(value, type, blameNode, path) { + // A value must be provided if the type is non-null. + if ((0, _definition.isNonNullType)(type)) { + if (value == null) { + return ofErrors([coercionError("Expected non-nullable type ".concat((0, _inspect.default)(type), " not to be null"), blameNode, path)]); + } + + return coerceValue(value, type.ofType, blameNode, path); + } + + if (value == null) { + // Explicitly return the value null. + return ofValue(null); + } + + if ((0, _definition.isScalarType)(type)) { + // Scalars determine if a value is valid via parseValue(), which can + // throw to indicate failure. If it throws, maintain a reference to + // the original error. + try { + var parseResult = type.parseValue(value); + + if ((0, _isInvalid.default)(parseResult)) { + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path)]); + } + + return ofValue(parseResult); + } catch (error) { + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, error.message, error)]); + } + } + + if ((0, _definition.isEnumType)(type)) { + if (typeof value === 'string') { + var enumValue = type.getValue(value); + + if (enumValue) { + return ofValue(enumValue.value); + } + } + + var suggestions = (0, _suggestionList.default)(String(value), type.getValues().map(function (enumValue) { + return enumValue.name; + })); + var didYouMean = suggestions.length !== 0 ? "did you mean ".concat((0, _orList.default)(suggestions), "?") : undefined; + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, didYouMean)]); + } + + if ((0, _definition.isListType)(type)) { + var itemType = type.ofType; + + if ((0, _iterall.isCollection)(value)) { + var errors; + var coercedValue = []; + (0, _iterall.forEach)(value, function (itemValue, index) { + var coercedItem = coerceValue(itemValue, itemType, blameNode, atPath(path, index)); + + if (coercedItem.errors) { + errors = add(errors, coercedItem.errors); + } else if (!errors) { + coercedValue.push(coercedItem.value); + } + }); + return errors ? ofErrors(errors) : ofValue(coercedValue); + } // Lists accept a non-list value as a list of one. + + + var coercedItem = coerceValue(value, itemType, blameNode); + return coercedItem.errors ? coercedItem : ofValue([coercedItem.value]); + } + + if ((0, _definition.isInputObjectType)(type)) { + if (_typeof(value) !== 'object') { + return ofErrors([coercionError("Expected type ".concat(type.name, " to be an object"), blameNode, path)]); + } + + var _errors; + + var _coercedValue = {}; + var fields = type.getFields(); // Ensure every defined field is valid. + + for (var fieldName in fields) { + if (hasOwnProperty.call(fields, fieldName)) { + var field = fields[fieldName]; + var fieldValue = value[fieldName]; + + if ((0, _isInvalid.default)(fieldValue)) { + if (!(0, _isInvalid.default)(field.defaultValue)) { + _coercedValue[fieldName] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + _errors = add(_errors, coercionError("Field ".concat(printPath(atPath(path, fieldName)), " of required ") + "type ".concat((0, _inspect.default)(field.type), " was not provided"), blameNode)); + } + } else { + var coercedField = coerceValue(fieldValue, field.type, blameNode, atPath(path, fieldName)); + + if (coercedField.errors) { + _errors = add(_errors, coercedField.errors); + } else if (!_errors) { + _coercedValue[fieldName] = coercedField.value; + } + } + } + } // Ensure every provided field is defined. + + + for (var _fieldName in value) { + if (hasOwnProperty.call(value, _fieldName)) { + if (!fields[_fieldName]) { + var _suggestions = (0, _suggestionList.default)(_fieldName, Object.keys(fields)); + + var _didYouMean = _suggestions.length !== 0 ? "did you mean ".concat((0, _orList.default)(_suggestions), "?") : undefined; + + _errors = add(_errors, coercionError("Field \"".concat(_fieldName, "\" is not defined by type ").concat(type.name), blameNode, path, _didYouMean)); + } + } + } + + return _errors ? ofErrors(_errors) : ofValue(_coercedValue); + } + /* istanbul ignore next */ + + + throw new Error("Unexpected type: ".concat(type, ".")); +} + +function ofValue(value) { + return { + errors: undefined, + value: value + }; +} + +function ofErrors(errors) { + return { + errors: errors, + value: undefined + }; +} + +function add(errors, moreErrors) { + return (errors || []).concat(moreErrors); +} + +function atPath(prev, key) { + return { + prev: prev, + key: key + }; +} + +function coercionError(message, blameNode, path, subMessage, originalError) { + var pathStr = printPath(path); // Return a GraphQLError instance + + return new _GraphQLError.GraphQLError(message + (pathStr ? ' at ' + pathStr : '') + (subMessage ? '; ' + subMessage : '.'), blameNode, undefined, undefined, undefined, originalError); +} // Build a string describing the path into the value where the error was found + + +function printPath(path) { + var pathStr = ''; + var currentPath = path; + + while (currentPath) { + pathStr = (typeof currentPath.key === 'string' ? '.' + currentPath.key : '[' + String(currentPath.key) + ']') + pathStr; + currentPath = currentPath.prev; + } + + return pathStr ? 'value' + pathStr : ''; +} + +var hasOwnProperty = Object.prototype.hasOwnProperty; \ No newline at end of file diff --git a/node_modules/graphql/utilities/coerceValue.js.flow b/node_modules/graphql/utilities/coerceValue.js.flow new file mode 100644 index 0000000..000d19d --- /dev/null +++ b/node_modules/graphql/utilities/coerceValue.js.flow @@ -0,0 +1,257 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { forEach, isCollection } from 'iterall'; +import inspect from '../jsutils/inspect'; +import isInvalid from '../jsutils/isInvalid'; +import orList from '../jsutils/orList'; +import suggestionList from '../jsutils/suggestionList'; +import { GraphQLError } from '../error/GraphQLError'; +import type { ASTNode } from '../language/ast'; +import { + isScalarType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, +} from '../type/definition'; +import type { GraphQLInputType } from '../type/definition'; + +type CoercedValue = {| + +errors: $ReadOnlyArray | void, + +value: mixed, +|}; + +type Path = {| +prev: Path | void, +key: string | number |}; + +/** + * Coerces a JavaScript value given a GraphQL Type. + * + * Returns either a value which is valid for the provided type or a list of + * encountered coercion errors. + * + */ +export function coerceValue( + value: mixed, + type: GraphQLInputType, + blameNode?: ASTNode, + path?: Path, +): CoercedValue { + // A value must be provided if the type is non-null. + if (isNonNullType(type)) { + if (value == null) { + return ofErrors([ + coercionError( + `Expected non-nullable type ${inspect(type)} not to be null`, + blameNode, + path, + ), + ]); + } + return coerceValue(value, type.ofType, blameNode, path); + } + + if (value == null) { + // Explicitly return the value null. + return ofValue(null); + } + + if (isScalarType(type)) { + // Scalars determine if a value is valid via parseValue(), which can + // throw to indicate failure. If it throws, maintain a reference to + // the original error. + try { + const parseResult = type.parseValue(value); + if (isInvalid(parseResult)) { + return ofErrors([ + coercionError(`Expected type ${type.name}`, blameNode, path), + ]); + } + return ofValue(parseResult); + } catch (error) { + return ofErrors([ + coercionError( + `Expected type ${type.name}`, + blameNode, + path, + error.message, + error, + ), + ]); + } + } + + if (isEnumType(type)) { + if (typeof value === 'string') { + const enumValue = type.getValue(value); + if (enumValue) { + return ofValue(enumValue.value); + } + } + const suggestions = suggestionList( + String(value), + type.getValues().map(enumValue => enumValue.name), + ); + const didYouMean = + suggestions.length !== 0 + ? `did you mean ${orList(suggestions)}?` + : undefined; + return ofErrors([ + coercionError(`Expected type ${type.name}`, blameNode, path, didYouMean), + ]); + } + + if (isListType(type)) { + const itemType = type.ofType; + if (isCollection(value)) { + let errors; + const coercedValue = []; + forEach((value: any), (itemValue, index) => { + const coercedItem = coerceValue( + itemValue, + itemType, + blameNode, + atPath(path, index), + ); + if (coercedItem.errors) { + errors = add(errors, coercedItem.errors); + } else if (!errors) { + coercedValue.push(coercedItem.value); + } + }); + return errors ? ofErrors(errors) : ofValue(coercedValue); + } + // Lists accept a non-list value as a list of one. + const coercedItem = coerceValue(value, itemType, blameNode); + return coercedItem.errors ? coercedItem : ofValue([coercedItem.value]); + } + + if (isInputObjectType(type)) { + if (typeof value !== 'object') { + return ofErrors([ + coercionError( + `Expected type ${type.name} to be an object`, + blameNode, + path, + ), + ]); + } + let errors; + const coercedValue = {}; + const fields = type.getFields(); + + // Ensure every defined field is valid. + for (const fieldName in fields) { + if (hasOwnProperty.call(fields, fieldName)) { + const field = fields[fieldName]; + const fieldValue = value[fieldName]; + if (isInvalid(fieldValue)) { + if (!isInvalid(field.defaultValue)) { + coercedValue[fieldName] = field.defaultValue; + } else if (isNonNullType(field.type)) { + errors = add( + errors, + coercionError( + `Field ${printPath(atPath(path, fieldName))} of required ` + + `type ${inspect(field.type)} was not provided`, + blameNode, + ), + ); + } + } else { + const coercedField = coerceValue( + fieldValue, + field.type, + blameNode, + atPath(path, fieldName), + ); + if (coercedField.errors) { + errors = add(errors, coercedField.errors); + } else if (!errors) { + coercedValue[fieldName] = coercedField.value; + } + } + } + } + + // Ensure every provided field is defined. + for (const fieldName in value) { + if (hasOwnProperty.call(value, fieldName)) { + if (!fields[fieldName]) { + const suggestions = suggestionList(fieldName, Object.keys(fields)); + const didYouMean = + suggestions.length !== 0 + ? `did you mean ${orList(suggestions)}?` + : undefined; + errors = add( + errors, + coercionError( + `Field "${fieldName}" is not defined by type ${type.name}`, + blameNode, + path, + didYouMean, + ), + ); + } + } + } + + return errors ? ofErrors(errors) : ofValue(coercedValue); + } + + /* istanbul ignore next */ + throw new Error(`Unexpected type: ${(type: empty)}.`); +} + +function ofValue(value) { + return { errors: undefined, value }; +} + +function ofErrors(errors) { + return { errors, value: undefined }; +} + +function add(errors, moreErrors) { + return (errors || []).concat(moreErrors); +} + +function atPath(prev, key) { + return { prev, key }; +} + +function coercionError(message, blameNode, path, subMessage, originalError) { + const pathStr = printPath(path); + // Return a GraphQLError instance + return new GraphQLError( + message + + (pathStr ? ' at ' + pathStr : '') + + (subMessage ? '; ' + subMessage : '.'), + blameNode, + undefined, + undefined, + undefined, + originalError, + ); +} + +// Build a string describing the path into the value where the error was found +function printPath(path) { + let pathStr = ''; + let currentPath = path; + while (currentPath) { + pathStr = + (typeof currentPath.key === 'string' + ? '.' + currentPath.key + : '[' + String(currentPath.key) + ']') + pathStr; + currentPath = currentPath.prev; + } + return pathStr ? 'value' + pathStr : ''; +} + +const hasOwnProperty = Object.prototype.hasOwnProperty; diff --git a/node_modules/graphql/utilities/coerceValue.mjs b/node_modules/graphql/utilities/coerceValue.mjs new file mode 100644 index 0000000..2fdcd4e --- /dev/null +++ b/node_modules/graphql/utilities/coerceValue.mjs @@ -0,0 +1,195 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { forEach, isCollection } from 'iterall'; +import inspect from '../jsutils/inspect'; +import isInvalid from '../jsutils/isInvalid'; +import orList from '../jsutils/orList'; +import suggestionList from '../jsutils/suggestionList'; +import { GraphQLError } from '../error/GraphQLError'; +import { isScalarType, isEnumType, isInputObjectType, isListType, isNonNullType } from '../type/definition'; + +/** + * Coerces a JavaScript value given a GraphQL Type. + * + * Returns either a value which is valid for the provided type or a list of + * encountered coercion errors. + * + */ +export function coerceValue(value, type, blameNode, path) { + // A value must be provided if the type is non-null. + if (isNonNullType(type)) { + if (value == null) { + return ofErrors([coercionError("Expected non-nullable type ".concat(inspect(type), " not to be null"), blameNode, path)]); + } + + return coerceValue(value, type.ofType, blameNode, path); + } + + if (value == null) { + // Explicitly return the value null. + return ofValue(null); + } + + if (isScalarType(type)) { + // Scalars determine if a value is valid via parseValue(), which can + // throw to indicate failure. If it throws, maintain a reference to + // the original error. + try { + var parseResult = type.parseValue(value); + + if (isInvalid(parseResult)) { + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path)]); + } + + return ofValue(parseResult); + } catch (error) { + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, error.message, error)]); + } + } + + if (isEnumType(type)) { + if (typeof value === 'string') { + var enumValue = type.getValue(value); + + if (enumValue) { + return ofValue(enumValue.value); + } + } + + var suggestions = suggestionList(String(value), type.getValues().map(function (enumValue) { + return enumValue.name; + })); + var didYouMean = suggestions.length !== 0 ? "did you mean ".concat(orList(suggestions), "?") : undefined; + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, didYouMean)]); + } + + if (isListType(type)) { + var itemType = type.ofType; + + if (isCollection(value)) { + var errors; + var coercedValue = []; + forEach(value, function (itemValue, index) { + var coercedItem = coerceValue(itemValue, itemType, blameNode, atPath(path, index)); + + if (coercedItem.errors) { + errors = add(errors, coercedItem.errors); + } else if (!errors) { + coercedValue.push(coercedItem.value); + } + }); + return errors ? ofErrors(errors) : ofValue(coercedValue); + } // Lists accept a non-list value as a list of one. + + + var coercedItem = coerceValue(value, itemType, blameNode); + return coercedItem.errors ? coercedItem : ofValue([coercedItem.value]); + } + + if (isInputObjectType(type)) { + if (_typeof(value) !== 'object') { + return ofErrors([coercionError("Expected type ".concat(type.name, " to be an object"), blameNode, path)]); + } + + var _errors; + + var _coercedValue = {}; + var fields = type.getFields(); // Ensure every defined field is valid. + + for (var fieldName in fields) { + if (hasOwnProperty.call(fields, fieldName)) { + var field = fields[fieldName]; + var fieldValue = value[fieldName]; + + if (isInvalid(fieldValue)) { + if (!isInvalid(field.defaultValue)) { + _coercedValue[fieldName] = field.defaultValue; + } else if (isNonNullType(field.type)) { + _errors = add(_errors, coercionError("Field ".concat(printPath(atPath(path, fieldName)), " of required ") + "type ".concat(inspect(field.type), " was not provided"), blameNode)); + } + } else { + var coercedField = coerceValue(fieldValue, field.type, blameNode, atPath(path, fieldName)); + + if (coercedField.errors) { + _errors = add(_errors, coercedField.errors); + } else if (!_errors) { + _coercedValue[fieldName] = coercedField.value; + } + } + } + } // Ensure every provided field is defined. + + + for (var _fieldName in value) { + if (hasOwnProperty.call(value, _fieldName)) { + if (!fields[_fieldName]) { + var _suggestions = suggestionList(_fieldName, Object.keys(fields)); + + var _didYouMean = _suggestions.length !== 0 ? "did you mean ".concat(orList(_suggestions), "?") : undefined; + + _errors = add(_errors, coercionError("Field \"".concat(_fieldName, "\" is not defined by type ").concat(type.name), blameNode, path, _didYouMean)); + } + } + } + + return _errors ? ofErrors(_errors) : ofValue(_coercedValue); + } + /* istanbul ignore next */ + + + throw new Error("Unexpected type: ".concat(type, ".")); +} + +function ofValue(value) { + return { + errors: undefined, + value: value + }; +} + +function ofErrors(errors) { + return { + errors: errors, + value: undefined + }; +} + +function add(errors, moreErrors) { + return (errors || []).concat(moreErrors); +} + +function atPath(prev, key) { + return { + prev: prev, + key: key + }; +} + +function coercionError(message, blameNode, path, subMessage, originalError) { + var pathStr = printPath(path); // Return a GraphQLError instance + + return new GraphQLError(message + (pathStr ? ' at ' + pathStr : '') + (subMessage ? '; ' + subMessage : '.'), blameNode, undefined, undefined, undefined, originalError); +} // Build a string describing the path into the value where the error was found + + +function printPath(path) { + var pathStr = ''; + var currentPath = path; + + while (currentPath) { + pathStr = (typeof currentPath.key === 'string' ? '.' + currentPath.key : '[' + String(currentPath.key) + ']') + pathStr; + currentPath = currentPath.prev; + } + + return pathStr ? 'value' + pathStr : ''; +} + +var hasOwnProperty = Object.prototype.hasOwnProperty; \ No newline at end of file diff --git a/node_modules/graphql/utilities/concatAST.js b/node_modules/graphql/utilities/concatAST.js new file mode 100644 index 0000000..609185d --- /dev/null +++ b/node_modules/graphql/utilities/concatAST.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.concatAST = concatAST; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ +function concatAST(asts) { + var batchDefinitions = []; + + for (var i = 0; i < asts.length; i++) { + var definitions = asts[i].definitions; + + for (var j = 0; j < definitions.length; j++) { + batchDefinitions.push(definitions[j]); + } + } + + return { + kind: 'Document', + definitions: batchDefinitions + }; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/concatAST.js.flow b/node_modules/graphql/utilities/concatAST.js.flow new file mode 100644 index 0000000..edeaa8f --- /dev/null +++ b/node_modules/graphql/utilities/concatAST.js.flow @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { DocumentNode } from '../language/ast'; + +/** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ +export function concatAST(asts: $ReadOnlyArray): DocumentNode { + const batchDefinitions = []; + for (let i = 0; i < asts.length; i++) { + const definitions = asts[i].definitions; + for (let j = 0; j < definitions.length; j++) { + batchDefinitions.push(definitions[j]); + } + } + return { + kind: 'Document', + definitions: batchDefinitions, + }; +} diff --git a/node_modules/graphql/utilities/concatAST.mjs b/node_modules/graphql/utilities/concatAST.mjs new file mode 100644 index 0000000..6e5ddc4 --- /dev/null +++ b/node_modules/graphql/utilities/concatAST.mjs @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ +export function concatAST(asts) { + var batchDefinitions = []; + + for (var i = 0; i < asts.length; i++) { + var definitions = asts[i].definitions; + + for (var j = 0; j < definitions.length; j++) { + batchDefinitions.push(definitions[j]); + } + } + + return { + kind: 'Document', + definitions: batchDefinitions + }; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/extendSchema.js b/node_modules/graphql/utilities/extendSchema.js new file mode 100644 index 0000000..125d63a --- /dev/null +++ b/node_modules/graphql/utilities/extendSchema.js @@ -0,0 +1,794 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.extendSchema = extendSchema; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _buildASTSchema = require("./buildASTSchema"); + +var _validate = require("../validation/validate"); + +var _GraphQLError = require("../error/GraphQLError"); + +var _schema = require("../type/schema"); + +var _introspection = require("../type/introspection"); + +var _scalars = require("../type/scalars"); + +var _definition = require("../type/definition"); + +var _directives = require("../type/directives"); + +var _kinds = require("../language/kinds"); + +var _predicates = require("../language/predicates"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + * + * Accepts options as a third argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +function extendSchema(schema, documentAST, options) { + !(0, _schema.isSchema)(schema) ? (0, _invariant.default)(0, 'Must provide valid GraphQLSchema') : void 0; + !(documentAST && documentAST.kind === _kinds.Kind.DOCUMENT) ? (0, _invariant.default)(0, 'Must provide valid Document AST') : void 0; + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + (0, _validate.assertValidSDLExtension)(documentAST, schema); + } // Collect the type definitions and extensions found in the document. + + + var typeDefinitionMap = Object.create(null); + var typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + + var directiveDefinitions = []; + var schemaDef; // Schema extensions are collected which may add additional operation types. + + var schemaExtensions = []; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var def = documentAST.definitions[i]; + + if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if ((0, _predicates.isTypeDefinitionNode)(def)) { + // Sanity check that none of the defined types conflict with the + // schema's existing types. + var typeName = def.name.value; + + if (schema.getType(typeName)) { + throw new _GraphQLError.GraphQLError("Type \"".concat(typeName, "\" already exists in the schema. It cannot also ") + 'be defined in this type definition.', [def]); + } + + typeDefinitionMap[typeName] = def; + } else if ((0, _predicates.isTypeExtensionNode)(def)) { + // Sanity check that this type extension exists within the + // schema's existing types. + var extendedTypeName = def.name.value; + var existingType = schema.getType(extendedTypeName); + + if (!existingType) { + throw new _GraphQLError.GraphQLError("Cannot extend type \"".concat(extendedTypeName, "\" because it does not ") + 'exist in the existing schema.', [def]); + } + + checkExtensionNode(existingType, def); + var existingTypeExtensions = typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def]; + } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var directiveName = def.name.value; + var existingDirective = schema.getDirective(directiveName); + + if (existingDirective) { + throw new _GraphQLError.GraphQLError("Directive \"".concat(directiveName, "\" already exists in the schema. It ") + 'cannot be redefined.', [def]); + } + + directiveDefinitions.push(def); + } + } // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + + + if (Object.keys(typeExtensionsMap).length === 0 && Object.keys(typeDefinitionMap).length === 0 && directiveDefinitions.length === 0 && schemaExtensions.length === 0 && !schemaDef) { + return schema; + } + + var astBuilder = new _buildASTSchema.ASTDefinitionBuilder(typeDefinitionMap, options, function (typeRef) { + var typeName = typeRef.name.value; + var existingType = schema.getType(typeName); + + if (existingType) { + return extendNamedType(existingType); + } + + throw new _GraphQLError.GraphQLError("Unknown type: \"".concat(typeName, "\". Ensure that this type exists ") + 'either in the original schema, or is added in a type definition.', [typeRef]); + }); + var extendTypeCache = Object.create(null); // Get the extended root operation types. + + var operationTypes = { + query: extendMaybeNamedType(schema.getQueryType()), + mutation: extendMaybeNamedType(schema.getMutationType()), + subscription: extendMaybeNamedType(schema.getSubscriptionType()) + }; + + if (schemaDef) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schemaDef.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var operation = _ref2.operation, + type = _ref2.type; + + if (operationTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + operationTypes[operation] = astBuilder.buildType(type); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } // Then, incorporate schema definition and all schema extensions. + + + for (var _i = 0; _i < schemaExtensions.length; _i++) { + var schemaExtension = schemaExtensions[_i]; + + if (schemaExtension.operationTypes) { + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + for (var _iterator12 = schemaExtension.operationTypes[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + var _ref4 = _step12.value; + var operation = _ref4.operation, + type = _ref4.type; + + if (operationTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + operationTypes[operation] = astBuilder.buildType(type); + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } + } + } + + var schemaExtensionASTNodes = schemaExtensions ? schema.extensionASTNodes ? schema.extensionASTNodes.concat(schemaExtensions) : schemaExtensions : schema.extensionASTNodes; + var types = (0, _objectValues.default)(schema.getTypeMap()).map(function (type) { + return extendNamedType(type); + }).concat((0, _objectValues.default)(typeDefinitionMap).map(function (type) { + return astBuilder.buildType(type); + })); // Support both original legacy names and extended legacy names. + + var allowedLegacyNames = schema.__allowedLegacyNames.concat(options && options.allowedLegacyNames || []); // Then produce and return a Schema with these types. + + + return new _schema.GraphQLSchema(_objectSpread({}, operationTypes, { + types: types, + directives: getMergedDirectives(), + astNode: schema.astNode, + extensionASTNodes: schemaExtensionASTNodes, + allowedLegacyNames: allowedLegacyNames + })); // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. + + function getMergedDirectives() { + var existingDirectives = schema.getDirectives().map(extendDirective); + !existingDirectives ? (0, _invariant.default)(0, 'schema must have default directives') : void 0; + return existingDirectives.concat(directiveDefinitions.map(function (node) { + return astBuilder.buildDirective(node); + })); + } + + function extendMaybeNamedType(type) { + return type ? extendNamedType(type) : null; + } + + function extendNamedType(type) { + if ((0, _introspection.isIntrospectionType)(type) || (0, _scalars.isSpecifiedScalarType)(type)) { + // Builtin types are not extended. + return type; + } + + var name = type.name; + + if (!extendTypeCache[name]) { + if ((0, _definition.isScalarType)(type)) { + extendTypeCache[name] = extendScalarType(type); + } else if ((0, _definition.isObjectType)(type)) { + extendTypeCache[name] = extendObjectType(type); + } else if ((0, _definition.isInterfaceType)(type)) { + extendTypeCache[name] = extendInterfaceType(type); + } else if ((0, _definition.isUnionType)(type)) { + extendTypeCache[name] = extendUnionType(type); + } else if ((0, _definition.isEnumType)(type)) { + extendTypeCache[name] = extendEnumType(type); + } else if ((0, _definition.isInputObjectType)(type)) { + extendTypeCache[name] = extendInputObjectType(type); + } + } + + return extendTypeCache[name]; + } + + function extendDirective(directive) { + return new _directives.GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: directive.locations, + args: extendArgs(directive.args), + astNode: directive.astNode + }); + } + + function extendInputObjectType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLInputObjectType({ + name: name, + description: type.description, + fields: function fields() { + return extendInputFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes + }); + } + + function extendInputFieldMap(type) { + var newFieldMap = Object.create(null); + var oldFieldMap = type.getFields(); + + var _arr = Object.keys(oldFieldMap); + + for (var _i2 = 0; _i2 < _arr.length; _i2++) { + var _fieldName = _arr[_i2]; + var _field = oldFieldMap[_fieldName]; + newFieldMap[_fieldName] = { + description: _field.description, + type: extendType(_field.type), + defaultValue: _field.defaultValue, + astNode: _field.astNode + }; + } // If there are any extensions to the fields, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = extensions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var extension = _step2.value; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = extension.fields[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var field = _step3.value; + var fieldName = field.name.value; + + if (oldFieldMap[fieldName]) { + throw new _GraphQLError.GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]); + } + + newFieldMap[fieldName] = astBuilder.buildInputField(field); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + return newFieldMap; + } + + function extendEnumType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLEnumType({ + name: name, + description: type.description, + values: extendValueMap(type), + astNode: type.astNode, + extensionASTNodes: extensionASTNodes + }); + } + + function extendValueMap(type) { + var newValueMap = Object.create(null); + var oldValueMap = (0, _keyMap.default)(type.getValues(), function (value) { + return value.name; + }); + + var _arr2 = Object.keys(oldValueMap); + + for (var _i3 = 0; _i3 < _arr2.length; _i3++) { + var _valueName = _arr2[_i3]; + var _value = oldValueMap[_valueName]; + newValueMap[_valueName] = { + name: _value.name, + description: _value.description, + value: _value.value, + deprecationReason: _value.deprecationReason, + astNode: _value.astNode + }; + } // If there are any extensions to the values, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = extensions[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var extension = _step4.value; + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = extension.values[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var value = _step5.value; + var valueName = value.name.value; + + if (oldValueMap[valueName]) { + throw new _GraphQLError.GraphQLError("Enum value \"".concat(type.name, ".").concat(valueName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [value]); + } + + newValueMap[valueName] = astBuilder.buildEnumValue(value); + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + + return newValueMap; + } + + function extendScalarType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLScalarType({ + name: name, + description: type.description, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + serialize: type.serialize, + parseValue: type.parseValue, + parseLiteral: type.parseLiteral + }); + } + + function extendObjectType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLObjectType({ + name: name, + description: type.description, + interfaces: function interfaces() { + return extendImplementedInterfaces(type); + }, + fields: function fields() { + return extendFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + isTypeOf: type.isTypeOf + }); + } + + function extendArgs(args) { + return (0, _keyValMap.default)(args, function (arg) { + return arg.name; + }, function (arg) { + return { + type: extendType(arg.type), + defaultValue: arg.defaultValue, + description: arg.description, + astNode: arg.astNode + }; + }); + } + + function extendInterfaceType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLInterfaceType({ + name: type.name, + description: type.description, + fields: function fields() { + return extendFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + resolveType: type.resolveType + }); + } + + function extendUnionType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLUnionType({ + name: name, + description: type.description, + types: function types() { + return extendPossibleTypes(type); + }, + astNode: type.astNode, + resolveType: type.resolveType, + extensionASTNodes: extensionASTNodes + }); + } + + function extendPossibleTypes(type) { + var possibleTypes = type.getTypes().map(extendNamedType); // If there are any extensions to the union, apply those here. + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = extensions[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var extension = _step6.value; + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = extension.types[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var namedType = _step7.value; + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + possibleTypes.push(astBuilder.buildType(namedType)); + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + + return possibleTypes; + } + + function extendImplementedInterfaces(type) { + var interfaces = type.getInterfaces().map(extendNamedType); // If there are any extensions to the interfaces, apply those here. + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + for (var _iterator8 = extensions[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var extension = _step8.value; + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + for (var _iterator9 = extension.interfaces[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + var namedType = _step9.value; + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces.push(astBuilder.buildType(namedType)); + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + } + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + } + + return interfaces; + } + + function extendFieldMap(type) { + var newFieldMap = Object.create(null); + var oldFieldMap = type.getFields(); + + var _arr3 = Object.keys(oldFieldMap); + + for (var _i4 = 0; _i4 < _arr3.length; _i4++) { + var _fieldName2 = _arr3[_i4]; + var _field2 = oldFieldMap[_fieldName2]; + newFieldMap[_fieldName2] = { + description: _field2.description, + deprecationReason: _field2.deprecationReason, + type: extendType(_field2.type), + args: extendArgs(_field2.args), + astNode: _field2.astNode, + resolve: _field2.resolve + }; + } // If there are any extensions to the fields, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = extensions[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var extension = _step10.value; + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + for (var _iterator11 = extension.fields[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + var field = _step11.value; + var fieldName = field.name.value; + + if (oldFieldMap[fieldName]) { + throw new _GraphQLError.GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]); + } + + newFieldMap[fieldName] = astBuilder.buildField(field); + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } + } + + return newFieldMap; + } + + function extendType(typeDef) { + if ((0, _definition.isListType)(typeDef)) { + return (0, _definition.GraphQLList)(extendType(typeDef.ofType)); + } + + if ((0, _definition.isNonNullType)(typeDef)) { + return (0, _definition.GraphQLNonNull)(extendType(typeDef.ofType)); + } + + return extendNamedType(typeDef); + } +} + +function checkExtensionNode(type, node) { + switch (node.kind) { + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + if (!(0, _definition.isObjectType)(type)) { + throw new _GraphQLError.GraphQLError("Cannot extend non-object type \"".concat(type.name, "\"."), [node]); + } + + break; + + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + if (!(0, _definition.isInterfaceType)(type)) { + throw new _GraphQLError.GraphQLError("Cannot extend non-interface type \"".concat(type.name, "\"."), [node]); + } + + break; + + case _kinds.Kind.ENUM_TYPE_EXTENSION: + if (!(0, _definition.isEnumType)(type)) { + throw new _GraphQLError.GraphQLError("Cannot extend non-enum type \"".concat(type.name, "\"."), [node]); + } + + break; + + case _kinds.Kind.UNION_TYPE_EXTENSION: + if (!(0, _definition.isUnionType)(type)) { + throw new _GraphQLError.GraphQLError("Cannot extend non-union type \"".concat(type.name, "\"."), [node]); + } + + break; + + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + if (!(0, _definition.isInputObjectType)(type)) { + throw new _GraphQLError.GraphQLError("Cannot extend non-input object type \"".concat(type.name, "\"."), [node]); + } + + break; + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/extendSchema.js.flow b/node_modules/graphql/utilities/extendSchema.js.flow new file mode 100644 index 0000000..62b184a --- /dev/null +++ b/node_modules/graphql/utilities/extendSchema.js.flow @@ -0,0 +1,645 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import objectValues from '../jsutils/objectValues'; +import { ASTDefinitionBuilder } from './buildASTSchema'; +import { assertValidSDLExtension } from '../validation/validate'; +import { GraphQLError } from '../error/GraphQLError'; +import { isSchema, GraphQLSchema } from '../type/schema'; +import { isIntrospectionType } from '../type/introspection'; +import { isSpecifiedScalarType } from '../type/scalars'; + +import type { GraphQLSchemaValidationOptions } from '../type/schema'; + +import type { + GraphQLType, + GraphQLNamedType, + GraphQLArgument, + GraphQLFieldConfigArgumentMap, +} from '../type/definition'; + +import { + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isListType, + isNonNullType, + isEnumType, + isInputObjectType, + GraphQLList, + GraphQLNonNull, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, +} from '../type/definition'; + +import { GraphQLDirective } from '../type/directives'; + +import { Kind } from '../language/kinds'; + +import type { + DocumentNode, + DirectiveDefinitionNode, + SchemaExtensionNode, + SchemaDefinitionNode, +} from '../language/ast'; +import { + isTypeDefinitionNode, + isTypeExtensionNode, +} from '../language/predicates'; + +type Options = {| + ...GraphQLSchemaValidationOptions, + + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean, + + /** + * Set to true to assume the SDL is valid. + * + * Default: false + */ + assumeValidSDL?: boolean, +|}; + +/** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + * + * Accepts options as a third argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function extendSchema( + schema: GraphQLSchema, + documentAST: DocumentNode, + options?: Options, +): GraphQLSchema { + invariant(isSchema(schema), 'Must provide valid GraphQLSchema'); + + invariant( + documentAST && documentAST.kind === Kind.DOCUMENT, + 'Must provide valid Document AST', + ); + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + assertValidSDLExtension(documentAST, schema); + } + + // Collect the type definitions and extensions found in the document. + const typeDefinitionMap = Object.create(null); + const typeExtensionsMap = Object.create(null); + + // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + const directiveDefinitions: Array = []; + + let schemaDef: ?SchemaDefinitionNode; + // Schema extensions are collected which may add additional operation types. + const schemaExtensions: Array = []; + + for (let i = 0; i < documentAST.definitions.length; i++) { + const def = documentAST.definitions[i]; + if (def.kind === Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if (isTypeDefinitionNode(def)) { + // Sanity check that none of the defined types conflict with the + // schema's existing types. + const typeName = def.name.value; + if (schema.getType(typeName)) { + throw new GraphQLError( + `Type "${typeName}" already exists in the schema. It cannot also ` + + 'be defined in this type definition.', + [def], + ); + } + typeDefinitionMap[typeName] = def; + } else if (isTypeExtensionNode(def)) { + // Sanity check that this type extension exists within the + // schema's existing types. + const extendedTypeName = def.name.value; + const existingType = schema.getType(extendedTypeName); + if (!existingType) { + throw new GraphQLError( + `Cannot extend type "${extendedTypeName}" because it does not ` + + 'exist in the existing schema.', + [def], + ); + } + checkExtensionNode(existingType, def); + + const existingTypeExtensions = typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions + ? existingTypeExtensions.concat([def]) + : [def]; + } else if (def.kind === Kind.DIRECTIVE_DEFINITION) { + const directiveName = def.name.value; + const existingDirective = schema.getDirective(directiveName); + if (existingDirective) { + throw new GraphQLError( + `Directive "${directiveName}" already exists in the schema. It ` + + 'cannot be redefined.', + [def], + ); + } + directiveDefinitions.push(def); + } + } + + // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + if ( + Object.keys(typeExtensionsMap).length === 0 && + Object.keys(typeDefinitionMap).length === 0 && + directiveDefinitions.length === 0 && + schemaExtensions.length === 0 && + !schemaDef + ) { + return schema; + } + + const astBuilder = new ASTDefinitionBuilder( + typeDefinitionMap, + options, + typeRef => { + const typeName = typeRef.name.value; + const existingType = schema.getType(typeName); + if (existingType) { + return extendNamedType(existingType); + } + + throw new GraphQLError( + `Unknown type: "${typeName}". Ensure that this type exists ` + + 'either in the original schema, or is added in a type definition.', + [typeRef], + ); + }, + ); + + const extendTypeCache = Object.create(null); + + // Get the extended root operation types. + const operationTypes = { + query: extendMaybeNamedType(schema.getQueryType()), + mutation: extendMaybeNamedType(schema.getMutationType()), + subscription: extendMaybeNamedType(schema.getSubscriptionType()), + }; + + if (schemaDef) { + for (const { operation, type } of schemaDef.operationTypes) { + if (operationTypes[operation]) { + throw new Error(`Must provide only one ${operation} type in schema.`); + } + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + operationTypes[operation] = (astBuilder.buildType(type): any); + } + } + // Then, incorporate schema definition and all schema extensions. + for (const schemaExtension of schemaExtensions) { + if (schemaExtension.operationTypes) { + for (const { operation, type } of schemaExtension.operationTypes) { + if (operationTypes[operation]) { + throw new Error(`Must provide only one ${operation} type in schema.`); + } + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + operationTypes[operation] = (astBuilder.buildType(type): any); + } + } + } + + const schemaExtensionASTNodes = schemaExtensions + ? schema.extensionASTNodes + ? schema.extensionASTNodes.concat(schemaExtensions) + : schemaExtensions + : schema.extensionASTNodes; + + const types = [ + // Iterate through all types, getting the type definition for each, ensuring + // that any type not directly referenced by a field will get created. + ...objectValues(schema.getTypeMap()).map(type => extendNamedType(type)), + // Do the same with new types. + ...objectValues(typeDefinitionMap).map(type => astBuilder.buildType(type)), + ]; + + // Support both original legacy names and extended legacy names. + const allowedLegacyNames = schema.__allowedLegacyNames.concat( + (options && options.allowedLegacyNames) || [], + ); + + // Then produce and return a Schema with these types. + return new GraphQLSchema({ + ...operationTypes, + types, + directives: getMergedDirectives(), + astNode: schema.astNode, + extensionASTNodes: schemaExtensionASTNodes, + allowedLegacyNames, + }); + + // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. + + function getMergedDirectives(): Array { + const existingDirectives = schema.getDirectives().map(extendDirective); + invariant(existingDirectives, 'schema must have default directives'); + + return existingDirectives.concat( + directiveDefinitions.map(node => astBuilder.buildDirective(node)), + ); + } + + function extendMaybeNamedType(type: ?T): ?T { + return type ? extendNamedType(type) : null; + } + + function extendNamedType(type: T): T { + if (isIntrospectionType(type) || isSpecifiedScalarType(type)) { + // Builtin types are not extended. + return type; + } + + const name = type.name; + if (!extendTypeCache[name]) { + if (isScalarType(type)) { + extendTypeCache[name] = extendScalarType(type); + } else if (isObjectType(type)) { + extendTypeCache[name] = extendObjectType(type); + } else if (isInterfaceType(type)) { + extendTypeCache[name] = extendInterfaceType(type); + } else if (isUnionType(type)) { + extendTypeCache[name] = extendUnionType(type); + } else if (isEnumType(type)) { + extendTypeCache[name] = extendEnumType(type); + } else if (isInputObjectType(type)) { + extendTypeCache[name] = extendInputObjectType(type); + } + } + return (extendTypeCache[name]: any); + } + + function extendDirective(directive: GraphQLDirective): GraphQLDirective { + return new GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: directive.locations, + args: extendArgs(directive.args), + astNode: directive.astNode, + }); + } + + function extendInputObjectType( + type: GraphQLInputObjectType, + ): GraphQLInputObjectType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLInputObjectType({ + name, + description: type.description, + fields: () => extendInputFieldMap(type), + astNode: type.astNode, + extensionASTNodes, + }); + } + + function extendInputFieldMap(type: GraphQLInputObjectType) { + const newFieldMap = Object.create(null); + const oldFieldMap = type.getFields(); + for (const fieldName of Object.keys(oldFieldMap)) { + const field = oldFieldMap[fieldName]; + newFieldMap[fieldName] = { + description: field.description, + type: extendType(field.type), + defaultValue: field.defaultValue, + astNode: field.astNode, + }; + } + + // If there are any extensions to the fields, apply those here. + const extensions = typeExtensionsMap[type.name]; + if (extensions) { + for (const extension of extensions) { + for (const field of extension.fields) { + const fieldName = field.name.value; + if (oldFieldMap[fieldName]) { + throw new GraphQLError( + `Field "${type.name}.${fieldName}" already exists in the ` + + 'schema. It cannot also be defined in this type extension.', + [field], + ); + } + newFieldMap[fieldName] = astBuilder.buildInputField(field); + } + } + } + + return newFieldMap; + } + + function extendEnumType(type: GraphQLEnumType): GraphQLEnumType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLEnumType({ + name, + description: type.description, + values: extendValueMap(type), + astNode: type.astNode, + extensionASTNodes, + }); + } + + function extendValueMap(type: GraphQLEnumType) { + const newValueMap = Object.create(null); + const oldValueMap = keyMap(type.getValues(), value => value.name); + for (const valueName of Object.keys(oldValueMap)) { + const value = oldValueMap[valueName]; + newValueMap[valueName] = { + name: value.name, + description: value.description, + value: value.value, + deprecationReason: value.deprecationReason, + astNode: value.astNode, + }; + } + + // If there are any extensions to the values, apply those here. + const extensions = typeExtensionsMap[type.name]; + if (extensions) { + for (const extension of extensions) { + for (const value of extension.values) { + const valueName = value.name.value; + if (oldValueMap[valueName]) { + throw new GraphQLError( + `Enum value "${type.name}.${valueName}" already exists in the ` + + 'schema. It cannot also be defined in this type extension.', + [value], + ); + } + newValueMap[valueName] = astBuilder.buildEnumValue(value); + } + } + } + + return newValueMap; + } + + function extendScalarType(type: GraphQLScalarType): GraphQLScalarType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLScalarType({ + name, + description: type.description, + astNode: type.astNode, + extensionASTNodes, + serialize: type.serialize, + parseValue: type.parseValue, + parseLiteral: type.parseLiteral, + }); + } + + function extendObjectType(type: GraphQLObjectType): GraphQLObjectType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLObjectType({ + name, + description: type.description, + interfaces: () => extendImplementedInterfaces(type), + fields: () => extendFieldMap(type), + astNode: type.astNode, + extensionASTNodes, + isTypeOf: type.isTypeOf, + }); + } + + function extendArgs( + args: Array, + ): GraphQLFieldConfigArgumentMap { + return keyValMap( + args, + arg => arg.name, + arg => ({ + type: extendType(arg.type), + defaultValue: arg.defaultValue, + description: arg.description, + astNode: arg.astNode, + }), + ); + } + + function extendInterfaceType( + type: GraphQLInterfaceType, + ): GraphQLInterfaceType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLInterfaceType({ + name: type.name, + description: type.description, + fields: () => extendFieldMap(type), + astNode: type.astNode, + extensionASTNodes, + resolveType: type.resolveType, + }); + } + + function extendUnionType(type: GraphQLUnionType): GraphQLUnionType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLUnionType({ + name, + description: type.description, + types: () => extendPossibleTypes(type), + astNode: type.astNode, + resolveType: type.resolveType, + extensionASTNodes, + }); + } + + function extendPossibleTypes( + type: GraphQLUnionType, + ): Array { + const possibleTypes = type.getTypes().map(extendNamedType); + + // If there are any extensions to the union, apply those here. + const extensions = typeExtensionsMap[type.name]; + if (extensions) { + for (const extension of extensions) { + for (const namedType of extension.types) { + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + possibleTypes.push((astBuilder.buildType(namedType): any)); + } + } + } + return possibleTypes; + } + + function extendImplementedInterfaces( + type: GraphQLObjectType, + ): Array { + const interfaces = type.getInterfaces().map(extendNamedType); + + // If there are any extensions to the interfaces, apply those here. + const extensions = typeExtensionsMap[type.name]; + if (extensions) { + for (const extension of extensions) { + for (const namedType of extension.interfaces) { + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces.push((astBuilder.buildType(namedType): any)); + } + } + } + + return interfaces; + } + + function extendFieldMap(type: GraphQLObjectType | GraphQLInterfaceType) { + const newFieldMap = Object.create(null); + const oldFieldMap = type.getFields(); + for (const fieldName of Object.keys(oldFieldMap)) { + const field = oldFieldMap[fieldName]; + newFieldMap[fieldName] = { + description: field.description, + deprecationReason: field.deprecationReason, + type: extendType(field.type), + args: extendArgs(field.args), + astNode: field.astNode, + resolve: field.resolve, + }; + } + + // If there are any extensions to the fields, apply those here. + const extensions = typeExtensionsMap[type.name]; + if (extensions) { + for (const extension of extensions) { + for (const field of extension.fields) { + const fieldName = field.name.value; + if (oldFieldMap[fieldName]) { + throw new GraphQLError( + `Field "${type.name}.${fieldName}" already exists in the ` + + 'schema. It cannot also be defined in this type extension.', + [field], + ); + } + newFieldMap[fieldName] = astBuilder.buildField(field); + } + } + } + + return newFieldMap; + } + + function extendType(typeDef: T): T { + if (isListType(typeDef)) { + return (GraphQLList(extendType(typeDef.ofType)): any); + } + if (isNonNullType(typeDef)) { + return (GraphQLNonNull(extendType(typeDef.ofType)): any); + } + return extendNamedType(typeDef); + } +} + +function checkExtensionNode(type, node) { + switch (node.kind) { + case Kind.OBJECT_TYPE_EXTENSION: + if (!isObjectType(type)) { + throw new GraphQLError( + `Cannot extend non-object type "${type.name}".`, + [node], + ); + } + break; + case Kind.INTERFACE_TYPE_EXTENSION: + if (!isInterfaceType(type)) { + throw new GraphQLError( + `Cannot extend non-interface type "${type.name}".`, + [node], + ); + } + break; + case Kind.ENUM_TYPE_EXTENSION: + if (!isEnumType(type)) { + throw new GraphQLError(`Cannot extend non-enum type "${type.name}".`, [ + node, + ]); + } + break; + case Kind.UNION_TYPE_EXTENSION: + if (!isUnionType(type)) { + throw new GraphQLError(`Cannot extend non-union type "${type.name}".`, [ + node, + ]); + } + break; + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + if (!isInputObjectType(type)) { + throw new GraphQLError( + `Cannot extend non-input object type "${type.name}".`, + [node], + ); + } + break; + } +} diff --git a/node_modules/graphql/utilities/extendSchema.mjs b/node_modules/graphql/utilities/extendSchema.mjs new file mode 100644 index 0000000..c4a1d99 --- /dev/null +++ b/node_modules/graphql/utilities/extendSchema.mjs @@ -0,0 +1,780 @@ +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import objectValues from '../jsutils/objectValues'; +import { ASTDefinitionBuilder } from './buildASTSchema'; +import { assertValidSDLExtension } from '../validation/validate'; +import { GraphQLError } from '../error/GraphQLError'; +import { isSchema, GraphQLSchema } from '../type/schema'; +import { isIntrospectionType } from '../type/introspection'; +import { isSpecifiedScalarType } from '../type/scalars'; +import { isScalarType, isObjectType, isInterfaceType, isUnionType, isListType, isNonNullType, isEnumType, isInputObjectType, GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType } from '../type/definition'; +import { GraphQLDirective } from '../type/directives'; +import { Kind } from '../language/kinds'; +import { isTypeDefinitionNode, isTypeExtensionNode } from '../language/predicates'; + +/** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + * + * Accepts options as a third argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function extendSchema(schema, documentAST, options) { + !isSchema(schema) ? invariant(0, 'Must provide valid GraphQLSchema') : void 0; + !(documentAST && documentAST.kind === Kind.DOCUMENT) ? invariant(0, 'Must provide valid Document AST') : void 0; + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + assertValidSDLExtension(documentAST, schema); + } // Collect the type definitions and extensions found in the document. + + + var typeDefinitionMap = Object.create(null); + var typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + + var directiveDefinitions = []; + var schemaDef; // Schema extensions are collected which may add additional operation types. + + var schemaExtensions = []; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var def = documentAST.definitions[i]; + + if (def.kind === Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if (isTypeDefinitionNode(def)) { + // Sanity check that none of the defined types conflict with the + // schema's existing types. + var typeName = def.name.value; + + if (schema.getType(typeName)) { + throw new GraphQLError("Type \"".concat(typeName, "\" already exists in the schema. It cannot also ") + 'be defined in this type definition.', [def]); + } + + typeDefinitionMap[typeName] = def; + } else if (isTypeExtensionNode(def)) { + // Sanity check that this type extension exists within the + // schema's existing types. + var extendedTypeName = def.name.value; + var existingType = schema.getType(extendedTypeName); + + if (!existingType) { + throw new GraphQLError("Cannot extend type \"".concat(extendedTypeName, "\" because it does not ") + 'exist in the existing schema.', [def]); + } + + checkExtensionNode(existingType, def); + var existingTypeExtensions = typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def]; + } else if (def.kind === Kind.DIRECTIVE_DEFINITION) { + var directiveName = def.name.value; + var existingDirective = schema.getDirective(directiveName); + + if (existingDirective) { + throw new GraphQLError("Directive \"".concat(directiveName, "\" already exists in the schema. It ") + 'cannot be redefined.', [def]); + } + + directiveDefinitions.push(def); + } + } // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + + + if (Object.keys(typeExtensionsMap).length === 0 && Object.keys(typeDefinitionMap).length === 0 && directiveDefinitions.length === 0 && schemaExtensions.length === 0 && !schemaDef) { + return schema; + } + + var astBuilder = new ASTDefinitionBuilder(typeDefinitionMap, options, function (typeRef) { + var typeName = typeRef.name.value; + var existingType = schema.getType(typeName); + + if (existingType) { + return extendNamedType(existingType); + } + + throw new GraphQLError("Unknown type: \"".concat(typeName, "\". Ensure that this type exists ") + 'either in the original schema, or is added in a type definition.', [typeRef]); + }); + var extendTypeCache = Object.create(null); // Get the extended root operation types. + + var operationTypes = { + query: extendMaybeNamedType(schema.getQueryType()), + mutation: extendMaybeNamedType(schema.getMutationType()), + subscription: extendMaybeNamedType(schema.getSubscriptionType()) + }; + + if (schemaDef) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schemaDef.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var operation = _ref2.operation, + type = _ref2.type; + + if (operationTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + operationTypes[operation] = astBuilder.buildType(type); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } // Then, incorporate schema definition and all schema extensions. + + + for (var _i = 0; _i < schemaExtensions.length; _i++) { + var schemaExtension = schemaExtensions[_i]; + + if (schemaExtension.operationTypes) { + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + for (var _iterator12 = schemaExtension.operationTypes[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + var _ref4 = _step12.value; + var operation = _ref4.operation, + type = _ref4.type; + + if (operationTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + operationTypes[operation] = astBuilder.buildType(type); + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } + } + } + + var schemaExtensionASTNodes = schemaExtensions ? schema.extensionASTNodes ? schema.extensionASTNodes.concat(schemaExtensions) : schemaExtensions : schema.extensionASTNodes; + var types = objectValues(schema.getTypeMap()).map(function (type) { + return extendNamedType(type); + }).concat(objectValues(typeDefinitionMap).map(function (type) { + return astBuilder.buildType(type); + })); // Support both original legacy names and extended legacy names. + + var allowedLegacyNames = schema.__allowedLegacyNames.concat(options && options.allowedLegacyNames || []); // Then produce and return a Schema with these types. + + + return new GraphQLSchema(_objectSpread({}, operationTypes, { + types: types, + directives: getMergedDirectives(), + astNode: schema.astNode, + extensionASTNodes: schemaExtensionASTNodes, + allowedLegacyNames: allowedLegacyNames + })); // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. + + function getMergedDirectives() { + var existingDirectives = schema.getDirectives().map(extendDirective); + !existingDirectives ? invariant(0, 'schema must have default directives') : void 0; + return existingDirectives.concat(directiveDefinitions.map(function (node) { + return astBuilder.buildDirective(node); + })); + } + + function extendMaybeNamedType(type) { + return type ? extendNamedType(type) : null; + } + + function extendNamedType(type) { + if (isIntrospectionType(type) || isSpecifiedScalarType(type)) { + // Builtin types are not extended. + return type; + } + + var name = type.name; + + if (!extendTypeCache[name]) { + if (isScalarType(type)) { + extendTypeCache[name] = extendScalarType(type); + } else if (isObjectType(type)) { + extendTypeCache[name] = extendObjectType(type); + } else if (isInterfaceType(type)) { + extendTypeCache[name] = extendInterfaceType(type); + } else if (isUnionType(type)) { + extendTypeCache[name] = extendUnionType(type); + } else if (isEnumType(type)) { + extendTypeCache[name] = extendEnumType(type); + } else if (isInputObjectType(type)) { + extendTypeCache[name] = extendInputObjectType(type); + } + } + + return extendTypeCache[name]; + } + + function extendDirective(directive) { + return new GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: directive.locations, + args: extendArgs(directive.args), + astNode: directive.astNode + }); + } + + function extendInputObjectType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLInputObjectType({ + name: name, + description: type.description, + fields: function fields() { + return extendInputFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes + }); + } + + function extendInputFieldMap(type) { + var newFieldMap = Object.create(null); + var oldFieldMap = type.getFields(); + + var _arr = Object.keys(oldFieldMap); + + for (var _i2 = 0; _i2 < _arr.length; _i2++) { + var _fieldName = _arr[_i2]; + var _field = oldFieldMap[_fieldName]; + newFieldMap[_fieldName] = { + description: _field.description, + type: extendType(_field.type), + defaultValue: _field.defaultValue, + astNode: _field.astNode + }; + } // If there are any extensions to the fields, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = extensions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var extension = _step2.value; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = extension.fields[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var field = _step3.value; + var fieldName = field.name.value; + + if (oldFieldMap[fieldName]) { + throw new GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]); + } + + newFieldMap[fieldName] = astBuilder.buildInputField(field); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + return newFieldMap; + } + + function extendEnumType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLEnumType({ + name: name, + description: type.description, + values: extendValueMap(type), + astNode: type.astNode, + extensionASTNodes: extensionASTNodes + }); + } + + function extendValueMap(type) { + var newValueMap = Object.create(null); + var oldValueMap = keyMap(type.getValues(), function (value) { + return value.name; + }); + + var _arr2 = Object.keys(oldValueMap); + + for (var _i3 = 0; _i3 < _arr2.length; _i3++) { + var _valueName = _arr2[_i3]; + var _value = oldValueMap[_valueName]; + newValueMap[_valueName] = { + name: _value.name, + description: _value.description, + value: _value.value, + deprecationReason: _value.deprecationReason, + astNode: _value.astNode + }; + } // If there are any extensions to the values, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = extensions[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var extension = _step4.value; + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = extension.values[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var value = _step5.value; + var valueName = value.name.value; + + if (oldValueMap[valueName]) { + throw new GraphQLError("Enum value \"".concat(type.name, ".").concat(valueName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [value]); + } + + newValueMap[valueName] = astBuilder.buildEnumValue(value); + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + + return newValueMap; + } + + function extendScalarType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLScalarType({ + name: name, + description: type.description, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + serialize: type.serialize, + parseValue: type.parseValue, + parseLiteral: type.parseLiteral + }); + } + + function extendObjectType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLObjectType({ + name: name, + description: type.description, + interfaces: function interfaces() { + return extendImplementedInterfaces(type); + }, + fields: function fields() { + return extendFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + isTypeOf: type.isTypeOf + }); + } + + function extendArgs(args) { + return keyValMap(args, function (arg) { + return arg.name; + }, function (arg) { + return { + type: extendType(arg.type), + defaultValue: arg.defaultValue, + description: arg.description, + astNode: arg.astNode + }; + }); + } + + function extendInterfaceType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLInterfaceType({ + name: type.name, + description: type.description, + fields: function fields() { + return extendFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + resolveType: type.resolveType + }); + } + + function extendUnionType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLUnionType({ + name: name, + description: type.description, + types: function types() { + return extendPossibleTypes(type); + }, + astNode: type.astNode, + resolveType: type.resolveType, + extensionASTNodes: extensionASTNodes + }); + } + + function extendPossibleTypes(type) { + var possibleTypes = type.getTypes().map(extendNamedType); // If there are any extensions to the union, apply those here. + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = extensions[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var extension = _step6.value; + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = extension.types[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var namedType = _step7.value; + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + possibleTypes.push(astBuilder.buildType(namedType)); + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + + return possibleTypes; + } + + function extendImplementedInterfaces(type) { + var interfaces = type.getInterfaces().map(extendNamedType); // If there are any extensions to the interfaces, apply those here. + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + for (var _iterator8 = extensions[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var extension = _step8.value; + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + for (var _iterator9 = extension.interfaces[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + var namedType = _step9.value; + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces.push(astBuilder.buildType(namedType)); + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + } + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + } + + return interfaces; + } + + function extendFieldMap(type) { + var newFieldMap = Object.create(null); + var oldFieldMap = type.getFields(); + + var _arr3 = Object.keys(oldFieldMap); + + for (var _i4 = 0; _i4 < _arr3.length; _i4++) { + var _fieldName2 = _arr3[_i4]; + var _field2 = oldFieldMap[_fieldName2]; + newFieldMap[_fieldName2] = { + description: _field2.description, + deprecationReason: _field2.deprecationReason, + type: extendType(_field2.type), + args: extendArgs(_field2.args), + astNode: _field2.astNode, + resolve: _field2.resolve + }; + } // If there are any extensions to the fields, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = extensions[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var extension = _step10.value; + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + for (var _iterator11 = extension.fields[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + var field = _step11.value; + var fieldName = field.name.value; + + if (oldFieldMap[fieldName]) { + throw new GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]); + } + + newFieldMap[fieldName] = astBuilder.buildField(field); + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } + } + + return newFieldMap; + } + + function extendType(typeDef) { + if (isListType(typeDef)) { + return GraphQLList(extendType(typeDef.ofType)); + } + + if (isNonNullType(typeDef)) { + return GraphQLNonNull(extendType(typeDef.ofType)); + } + + return extendNamedType(typeDef); + } +} + +function checkExtensionNode(type, node) { + switch (node.kind) { + case Kind.OBJECT_TYPE_EXTENSION: + if (!isObjectType(type)) { + throw new GraphQLError("Cannot extend non-object type \"".concat(type.name, "\"."), [node]); + } + + break; + + case Kind.INTERFACE_TYPE_EXTENSION: + if (!isInterfaceType(type)) { + throw new GraphQLError("Cannot extend non-interface type \"".concat(type.name, "\"."), [node]); + } + + break; + + case Kind.ENUM_TYPE_EXTENSION: + if (!isEnumType(type)) { + throw new GraphQLError("Cannot extend non-enum type \"".concat(type.name, "\"."), [node]); + } + + break; + + case Kind.UNION_TYPE_EXTENSION: + if (!isUnionType(type)) { + throw new GraphQLError("Cannot extend non-union type \"".concat(type.name, "\"."), [node]); + } + + break; + + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + if (!isInputObjectType(type)) { + throw new GraphQLError("Cannot extend non-input object type \"".concat(type.name, "\"."), [node]); + } + + break; + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/findBreakingChanges.js b/node_modules/graphql/utilities/findBreakingChanges.js new file mode 100644 index 0000000..94f08e4 --- /dev/null +++ b/node_modules/graphql/utilities/findBreakingChanges.js @@ -0,0 +1,1245 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findBreakingChanges = findBreakingChanges; +exports.findDangerousChanges = findDangerousChanges; +exports.findRemovedTypes = findRemovedTypes; +exports.findTypesThatChangedKind = findTypesThatChangedKind; +exports.findArgChanges = findArgChanges; +exports.findFieldsThatChangedTypeOnObjectOrInterfaceTypes = findFieldsThatChangedTypeOnObjectOrInterfaceTypes; +exports.findFieldsThatChangedTypeOnInputObjectTypes = findFieldsThatChangedTypeOnInputObjectTypes; +exports.findTypesRemovedFromUnions = findTypesRemovedFromUnions; +exports.findTypesAddedToUnions = findTypesAddedToUnions; +exports.findValuesRemovedFromEnums = findValuesRemovedFromEnums; +exports.findValuesAddedToEnums = findValuesAddedToEnums; +exports.findInterfacesRemovedFromObjectTypes = findInterfacesRemovedFromObjectTypes; +exports.findInterfacesAddedToObjectTypes = findInterfacesAddedToObjectTypes; +exports.findRemovedDirectives = findRemovedDirectives; +exports.findRemovedDirectiveArgs = findRemovedDirectiveArgs; +exports.findAddedNonNullDirectiveArgs = findAddedNonNullDirectiveArgs; +exports.findRemovedLocationsForDirective = findRemovedLocationsForDirective; +exports.findRemovedDirectiveLocations = findRemovedDirectiveLocations; +exports.DangerousChangeType = exports.BreakingChangeType = void 0; + +var _definition = require("../type/definition"); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2016-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var BreakingChangeType = { + FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', + FIELD_REMOVED: 'FIELD_REMOVED', + TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND', + TYPE_REMOVED: 'TYPE_REMOVED', + TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION', + VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', + ARG_REMOVED: 'ARG_REMOVED', + ARG_CHANGED_KIND: 'ARG_CHANGED_KIND', + REQUIRED_ARG_ADDED: 'REQUIRED_ARG_ADDED', + REQUIRED_INPUT_FIELD_ADDED: 'REQUIRED_INPUT_FIELD_ADDED', + INTERFACE_REMOVED_FROM_OBJECT: 'INTERFACE_REMOVED_FROM_OBJECT', + DIRECTIVE_REMOVED: 'DIRECTIVE_REMOVED', + DIRECTIVE_ARG_REMOVED: 'DIRECTIVE_ARG_REMOVED', + DIRECTIVE_LOCATION_REMOVED: 'DIRECTIVE_LOCATION_REMOVED', + REQUIRED_DIRECTIVE_ARG_ADDED: 'REQUIRED_DIRECTIVE_ARG_ADDED' +}; +exports.BreakingChangeType = BreakingChangeType; +var DangerousChangeType = { + ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE', + VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM', + INTERFACE_ADDED_TO_OBJECT: 'INTERFACE_ADDED_TO_OBJECT', + TYPE_ADDED_TO_UNION: 'TYPE_ADDED_TO_UNION', + OPTIONAL_INPUT_FIELD_ADDED: 'OPTIONAL_INPUT_FIELD_ADDED', + OPTIONAL_ARG_ADDED: 'OPTIONAL_ARG_ADDED' +}; +exports.DangerousChangeType = DangerousChangeType; + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ +function findBreakingChanges(oldSchema, newSchema) { + return findRemovedTypes(oldSchema, newSchema).concat(findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).breakingChanges, findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), findRemovedDirectives(oldSchema, newSchema), findRemovedDirectiveArgs(oldSchema, newSchema), findAddedNonNullDirectiveArgs(oldSchema, newSchema), findRemovedDirectiveLocations(oldSchema, newSchema)); +} +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + */ + + +function findDangerousChanges(oldSchema, newSchema) { + return findArgChanges(oldSchema, newSchema).dangerousChanges.concat(findValuesAddedToEnums(oldSchema, newSchema), findInterfacesAddedToObjectTypes(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).dangerousChanges); +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing an entire type. + */ + + +function findRemovedTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr = Object.keys(oldTypeMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var typeName = _arr[_i]; + + if (!newTypeMap[typeName]) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: "".concat(typeName, " was removed.") + }); + } + } + + return breakingChanges; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to changing the type of a type. + */ + + +function findTypesThatChangedKind(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr2 = Object.keys(oldTypeMap); + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var typeName = _arr2[_i2]; + + if (!newTypeMap[typeName]) { + continue; + } + + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (oldType.constructor !== newType.constructor) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: "".concat(typeName, " changed from ") + "".concat(typeKindName(oldType), " to ").concat(typeKindName(newType), ".") + }); + } + } + + return breakingChanges; +} +/** + * Given two schemas, returns an Array containing descriptions of any + * breaking or dangerous changes in the newSchema related to arguments + * (such as removal or change of type of an argument, or a change in an + * argument's default value). + */ + + +function findArgChanges(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + var dangerousChanges = []; + + var _arr3 = Object.keys(oldTypeMap); + + for (var _i3 = 0; _i3 < _arr3.length; _i3++) { + var typeName = _arr3[_i3]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!((0, _definition.isObjectType)(oldType) || (0, _definition.isInterfaceType)(oldType)) || !((0, _definition.isObjectType)(newType) || (0, _definition.isInterfaceType)(newType)) || newType.constructor !== oldType.constructor) { + continue; + } + + var oldTypeFields = oldType.getFields(); + var newTypeFields = newType.getFields(); + + var _arr4 = Object.keys(oldTypeFields); + + for (var _i4 = 0; _i4 < _arr4.length; _i4++) { + var fieldName = _arr4[_i4]; + + if (!newTypeFields[fieldName]) { + continue; + } + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + var _loop = function _loop() { + var oldArgDef = _step.value; + var newArgs = newTypeFields[fieldName].args; + var newArgDef = newArgs.find(function (arg) { + return arg.name === oldArgDef.name; + }); // Arg not present + + if (!newArgDef) { + breakingChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " was removed") + }); + } else { + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type); + + if (!isSafe) { + breakingChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed type from ") + "".concat(oldArgDef.type.toString(), " to ").concat(newArgDef.type.toString()) + }); + } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) { + dangerousChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed defaultValue") + }); + } + } + }; + + for (var _iterator = oldTypeFields[fieldName].args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + _loop(); + } // Check if arg was added to the field + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + var _loop2 = function _loop2() { + var newArgDef = _step2.value; + var oldArgs = oldTypeFields[fieldName].args; + var oldArgDef = oldArgs.find(function (arg) { + return arg.name === newArgDef.name; + }); + + if (!oldArgDef) { + var argName = newArgDef.name; + + if ((0, _definition.isRequiredArgument)(newArgDef)) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: "A required arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added") + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: "An optional arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added") + }); + } + } + }; + + for (var _iterator2 = newTypeFields[fieldName].args[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + _loop2(); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + } + + return { + breakingChanges: breakingChanges, + dangerousChanges: dangerousChanges + }; +} + +function typeKindName(type) { + if ((0, _definition.isScalarType)(type)) { + return 'a Scalar type'; + } + + if ((0, _definition.isObjectType)(type)) { + return 'an Object type'; + } + + if ((0, _definition.isInterfaceType)(type)) { + return 'an Interface type'; + } + + if ((0, _definition.isUnionType)(type)) { + return 'a Union type'; + } + + if ((0, _definition.isEnumType)(type)) { + return 'an Enum type'; + } + + if ((0, _definition.isInputObjectType)(type)) { + return 'an Input type'; + } + + throw new TypeError('Unknown type ' + type.constructor.name); +} + +function findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr5 = Object.keys(oldTypeMap); + + for (var _i5 = 0; _i5 < _arr5.length; _i5++) { + var typeName = _arr5[_i5]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!((0, _definition.isObjectType)(oldType) || (0, _definition.isInterfaceType)(oldType)) || !((0, _definition.isObjectType)(newType) || (0, _definition.isInterfaceType)(newType)) || newType.constructor !== oldType.constructor) { + continue; + } + + var oldTypeFieldsDef = oldType.getFields(); + var newTypeFieldsDef = newType.getFields(); + + var _arr6 = Object.keys(oldTypeFieldsDef); + + for (var _i6 = 0; _i6 < _arr6.length; _i6++) { + var fieldName = _arr6[_i6]; + + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(typeName, ".").concat(fieldName, " was removed.") + }); + } else { + var oldFieldType = oldTypeFieldsDef[fieldName].type; + var newFieldType = newTypeFieldsDef[fieldName].type; + var isSafe = isChangeSafeForObjectOrInterfaceField(oldFieldType, newFieldType); + + if (!isSafe) { + var oldFieldTypeString = (0, _definition.isNamedType)(oldFieldType) ? oldFieldType.name : oldFieldType.toString(); + var newFieldTypeString = (0, _definition.isNamedType)(newFieldType) ? newFieldType.name : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".") + }); + } + } + } + } + + return breakingChanges; +} + +function findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + var dangerousChanges = []; + + var _arr7 = Object.keys(oldTypeMap); + + for (var _i7 = 0; _i7 < _arr7.length; _i7++) { + var typeName = _arr7[_i7]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isInputObjectType)(oldType) || !(0, _definition.isInputObjectType)(newType)) { + continue; + } + + var oldTypeFieldsDef = oldType.getFields(); + var newTypeFieldsDef = newType.getFields(); + + var _arr8 = Object.keys(oldTypeFieldsDef); + + for (var _i8 = 0; _i8 < _arr8.length; _i8++) { + var fieldName = _arr8[_i8]; + + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(typeName, ".").concat(fieldName, " was removed.") + }); + } else { + var oldFieldType = oldTypeFieldsDef[fieldName].type; + var newFieldType = newTypeFieldsDef[fieldName].type; + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldFieldType, newFieldType); + + if (!isSafe) { + var oldFieldTypeString = (0, _definition.isNamedType)(oldFieldType) ? oldFieldType.name : oldFieldType.toString(); + var newFieldTypeString = (0, _definition.isNamedType)(newFieldType) ? newFieldType.name : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".") + }); + } + } + } // Check if a field was added to the input object type + + + var _arr9 = Object.keys(newTypeFieldsDef); + + for (var _i9 = 0; _i9 < _arr9.length; _i9++) { + var _fieldName = _arr9[_i9]; + + if (!(_fieldName in oldTypeFieldsDef)) { + if ((0, _definition.isRequiredInputField)(newTypeFieldsDef[_fieldName])) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: "A required field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.") + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: "An optional field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.") + }); + } + } + } + } + + return { + breakingChanges: breakingChanges, + dangerousChanges: dangerousChanges + }; +} + +function isChangeSafeForObjectOrInterfaceField(oldType, newType) { + if ((0, _definition.isNamedType)(oldType)) { + return (// if they're both named types, see if their names are equivalent + (0, _definition.isNamedType)(newType) && oldType.name === newType.name || // moving from nullable to non-null of the same underlying type is safe + (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } else if ((0, _definition.isListType)(oldType)) { + return (// if they're both lists, make sure the underlying types are compatible + (0, _definition.isListType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || // moving from nullable to non-null of the same underlying type is safe + (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } else if ((0, _definition.isNonNullType)(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType); + } + + return false; +} + +function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { + if ((0, _definition.isNamedType)(oldType)) { + // if they're both named types, see if their names are equivalent + return (0, _definition.isNamedType)(newType) && oldType.name === newType.name; + } else if ((0, _definition.isListType)(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return (0, _definition.isListType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType); + } else if ((0, _definition.isNonNullType)(oldType)) { + return (// if they're both non-null, make sure the underlying types are + // compatible + (0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || // moving from non-null to nullable of the same underlying type is safe + !(0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType) + ); + } + + return false; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing types from a union type. + */ + + +function findTypesRemovedFromUnions(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var typesRemovedFromUnion = []; + + var _arr10 = Object.keys(oldTypeMap); + + for (var _i10 = 0; _i10 < _arr10.length; _i10++) { + var typeName = _arr10[_i10]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isUnionType)(oldType) || !(0, _definition.isUnionType)(newType)) { + continue; + } + + var typeNamesInNewUnion = Object.create(null); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = newType.getTypes()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var type = _step3.value; + typeNamesInNewUnion[type.name] = true; + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = oldType.getTypes()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var _type = _step4.value; + + if (!typeNamesInNewUnion[_type.name]) { + typesRemovedFromUnion.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: "".concat(_type.name, " was removed from union type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + + return typesRemovedFromUnion; +} +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding types to a union type. + */ + + +function findTypesAddedToUnions(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var typesAddedToUnion = []; + + var _arr11 = Object.keys(newTypeMap); + + for (var _i11 = 0; _i11 < _arr11.length; _i11++) { + var typeName = _arr11[_i11]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isUnionType)(oldType) || !(0, _definition.isUnionType)(newType)) { + continue; + } + + var typeNamesInOldUnion = Object.create(null); + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = oldType.getTypes()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var type = _step5.value; + typeNamesInOldUnion[type.name] = true; + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = newType.getTypes()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var _type2 = _step6.value; + + if (!typeNamesInOldUnion[_type2.name]) { + typesAddedToUnion.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: "".concat(_type2.name, " was added to union type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + + return typesAddedToUnion; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing values from an enum type. + */ + + +function findValuesRemovedFromEnums(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var valuesRemovedFromEnums = []; + + var _arr12 = Object.keys(oldTypeMap); + + for (var _i12 = 0; _i12 < _arr12.length; _i12++) { + var typeName = _arr12[_i12]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isEnumType)(oldType) || !(0, _definition.isEnumType)(newType)) { + continue; + } + + var valuesInNewEnum = Object.create(null); + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = newType.getValues()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var value = _step7.value; + valuesInNewEnum[value.name] = true; + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + for (var _iterator8 = oldType.getValues()[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var _value = _step8.value; + + if (!valuesInNewEnum[_value.name]) { + valuesRemovedFromEnums.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: "".concat(_value.name, " was removed from enum type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + } + + return valuesRemovedFromEnums; +} +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding values to an enum type. + */ + + +function findValuesAddedToEnums(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var valuesAddedToEnums = []; + + var _arr13 = Object.keys(oldTypeMap); + + for (var _i13 = 0; _i13 < _arr13.length; _i13++) { + var typeName = _arr13[_i13]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isEnumType)(oldType) || !(0, _definition.isEnumType)(newType)) { + continue; + } + + var valuesInOldEnum = Object.create(null); + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + for (var _iterator9 = oldType.getValues()[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + var value = _step9.value; + valuesInOldEnum[value.name] = true; + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = newType.getValues()[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var _value2 = _step10.value; + + if (!valuesInOldEnum[_value2.name]) { + valuesAddedToEnums.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: "".concat(_value2.name, " was added to enum type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } + } + + return valuesAddedToEnums; +} + +function findInterfacesRemovedFromObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr14 = Object.keys(oldTypeMap); + + for (var _i14 = 0; _i14 < _arr14.length; _i14++) { + var typeName = _arr14[_i14]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isObjectType)(oldType) || !(0, _definition.isObjectType)(newType)) { + continue; + } + + var oldInterfaces = oldType.getInterfaces(); + var newInterfaces = newType.getInterfaces(); + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + var _loop3 = function _loop3() { + var oldInterface = _step11.value; + + if (!newInterfaces.some(function (int) { + return int.name === oldInterface.name; + })) { + breakingChanges.push({ + type: BreakingChangeType.INTERFACE_REMOVED_FROM_OBJECT, + description: "".concat(typeName, " no longer implements interface ") + "".concat(oldInterface.name, ".") + }); + } + }; + + for (var _iterator11 = oldInterfaces[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + _loop3(); + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } + } + + return breakingChanges; +} + +function findInterfacesAddedToObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var interfacesAddedToObjectTypes = []; + + var _arr15 = Object.keys(newTypeMap); + + for (var _i15 = 0; _i15 < _arr15.length; _i15++) { + var typeName = _arr15[_i15]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isObjectType)(oldType) || !(0, _definition.isObjectType)(newType)) { + continue; + } + + var oldInterfaces = oldType.getInterfaces(); + var newInterfaces = newType.getInterfaces(); + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + var _loop4 = function _loop4() { + var newInterface = _step12.value; + + if (!oldInterfaces.some(function (int) { + return int.name === newInterface.name; + })) { + interfacesAddedToObjectTypes.push({ + type: DangerousChangeType.INTERFACE_ADDED_TO_OBJECT, + description: "".concat(newInterface.name, " added to interfaces implemented ") + "by ".concat(typeName, ".") + }); + } + }; + + for (var _iterator12 = newInterfaces[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + _loop4(); + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } + } + + return interfacesAddedToObjectTypes; +} + +function findRemovedDirectives(oldSchema, newSchema) { + var removedDirectives = []; + var newSchemaDirectiveMap = getDirectiveMapForSchema(newSchema); + var _iteratorNormalCompletion13 = true; + var _didIteratorError13 = false; + var _iteratorError13 = undefined; + + try { + for (var _iterator13 = oldSchema.getDirectives()[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) { + var directive = _step13.value; + + if (!newSchemaDirectiveMap[directive.name]) { + removedDirectives.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: "".concat(directive.name, " was removed") + }); + } + } + } catch (err) { + _didIteratorError13 = true; + _iteratorError13 = err; + } finally { + try { + if (!_iteratorNormalCompletion13 && _iterator13.return != null) { + _iterator13.return(); + } + } finally { + if (_didIteratorError13) { + throw _iteratorError13; + } + } + } + + return removedDirectives; +} + +function findRemovedArgsForDirective(oldDirective, newDirective) { + var removedArgs = []; + var newArgMap = getArgumentMapForDirective(newDirective); + var _iteratorNormalCompletion14 = true; + var _didIteratorError14 = false; + var _iteratorError14 = undefined; + + try { + for (var _iterator14 = oldDirective.args[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) { + var arg = _step14.value; + + if (!newArgMap[arg.name]) { + removedArgs.push(arg); + } + } + } catch (err) { + _didIteratorError14 = true; + _iteratorError14 = err; + } finally { + try { + if (!_iteratorNormalCompletion14 && _iterator14.return != null) { + _iterator14.return(); + } + } finally { + if (_didIteratorError14) { + throw _iteratorError14; + } + } + } + + return removedArgs; +} + +function findRemovedDirectiveArgs(oldSchema, newSchema) { + var removedDirectiveArgs = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion15 = true; + var _didIteratorError15 = false; + var _iteratorError15 = undefined; + + try { + for (var _iterator15 = newSchema.getDirectives()[Symbol.iterator](), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) { + var newDirective = _step15.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion16 = true; + var _didIteratorError16 = false; + var _iteratorError16 = undefined; + + try { + for (var _iterator16 = findRemovedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step16; !(_iteratorNormalCompletion16 = (_step16 = _iterator16.next()).done); _iteratorNormalCompletion16 = true) { + var arg = _step16.value; + removedDirectiveArgs.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: "".concat(arg.name, " was removed from ").concat(newDirective.name) + }); + } + } catch (err) { + _didIteratorError16 = true; + _iteratorError16 = err; + } finally { + try { + if (!_iteratorNormalCompletion16 && _iterator16.return != null) { + _iterator16.return(); + } + } finally { + if (_didIteratorError16) { + throw _iteratorError16; + } + } + } + } + } catch (err) { + _didIteratorError15 = true; + _iteratorError15 = err; + } finally { + try { + if (!_iteratorNormalCompletion15 && _iterator15.return != null) { + _iterator15.return(); + } + } finally { + if (_didIteratorError15) { + throw _iteratorError15; + } + } + } + + return removedDirectiveArgs; +} + +function findAddedArgsForDirective(oldDirective, newDirective) { + var addedArgs = []; + var oldArgMap = getArgumentMapForDirective(oldDirective); + var _iteratorNormalCompletion17 = true; + var _didIteratorError17 = false; + var _iteratorError17 = undefined; + + try { + for (var _iterator17 = newDirective.args[Symbol.iterator](), _step17; !(_iteratorNormalCompletion17 = (_step17 = _iterator17.next()).done); _iteratorNormalCompletion17 = true) { + var arg = _step17.value; + + if (!oldArgMap[arg.name]) { + addedArgs.push(arg); + } + } + } catch (err) { + _didIteratorError17 = true; + _iteratorError17 = err; + } finally { + try { + if (!_iteratorNormalCompletion17 && _iterator17.return != null) { + _iterator17.return(); + } + } finally { + if (_didIteratorError17) { + throw _iteratorError17; + } + } + } + + return addedArgs; +} + +function findAddedNonNullDirectiveArgs(oldSchema, newSchema) { + var addedNonNullableArgs = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion18 = true; + var _didIteratorError18 = false; + var _iteratorError18 = undefined; + + try { + for (var _iterator18 = newSchema.getDirectives()[Symbol.iterator](), _step18; !(_iteratorNormalCompletion18 = (_step18 = _iterator18.next()).done); _iteratorNormalCompletion18 = true) { + var newDirective = _step18.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion19 = true; + var _didIteratorError19 = false; + var _iteratorError19 = undefined; + + try { + for (var _iterator19 = findAddedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step19; !(_iteratorNormalCompletion19 = (_step19 = _iterator19.next()).done); _iteratorNormalCompletion19 = true) { + var arg = _step19.value; + + if ((0, _definition.isRequiredArgument)(arg)) { + addedNonNullableArgs.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: "A required arg ".concat(arg.name, " on directive ") + "".concat(newDirective.name, " was added") + }); + } + } + } catch (err) { + _didIteratorError19 = true; + _iteratorError19 = err; + } finally { + try { + if (!_iteratorNormalCompletion19 && _iterator19.return != null) { + _iterator19.return(); + } + } finally { + if (_didIteratorError19) { + throw _iteratorError19; + } + } + } + } + } catch (err) { + _didIteratorError18 = true; + _iteratorError18 = err; + } finally { + try { + if (!_iteratorNormalCompletion18 && _iterator18.return != null) { + _iterator18.return(); + } + } finally { + if (_didIteratorError18) { + throw _iteratorError18; + } + } + } + + return addedNonNullableArgs; +} + +function findRemovedLocationsForDirective(oldDirective, newDirective) { + var removedLocations = []; + var newLocationSet = new Set(newDirective.locations); + var _iteratorNormalCompletion20 = true; + var _didIteratorError20 = false; + var _iteratorError20 = undefined; + + try { + for (var _iterator20 = oldDirective.locations[Symbol.iterator](), _step20; !(_iteratorNormalCompletion20 = (_step20 = _iterator20.next()).done); _iteratorNormalCompletion20 = true) { + var oldLocation = _step20.value; + + if (!newLocationSet.has(oldLocation)) { + removedLocations.push(oldLocation); + } + } + } catch (err) { + _didIteratorError20 = true; + _iteratorError20 = err; + } finally { + try { + if (!_iteratorNormalCompletion20 && _iterator20.return != null) { + _iterator20.return(); + } + } finally { + if (_didIteratorError20) { + throw _iteratorError20; + } + } + } + + return removedLocations; +} + +function findRemovedDirectiveLocations(oldSchema, newSchema) { + var removedLocations = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion21 = true; + var _didIteratorError21 = false; + var _iteratorError21 = undefined; + + try { + for (var _iterator21 = newSchema.getDirectives()[Symbol.iterator](), _step21; !(_iteratorNormalCompletion21 = (_step21 = _iterator21.next()).done); _iteratorNormalCompletion21 = true) { + var newDirective = _step21.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion22 = true; + var _didIteratorError22 = false; + var _iteratorError22 = undefined; + + try { + for (var _iterator22 = findRemovedLocationsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step22; !(_iteratorNormalCompletion22 = (_step22 = _iterator22.next()).done); _iteratorNormalCompletion22 = true) { + var location = _step22.value; + removedLocations.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: "".concat(location, " was removed from ").concat(newDirective.name) + }); + } + } catch (err) { + _didIteratorError22 = true; + _iteratorError22 = err; + } finally { + try { + if (!_iteratorNormalCompletion22 && _iterator22.return != null) { + _iterator22.return(); + } + } finally { + if (_didIteratorError22) { + throw _iteratorError22; + } + } + } + } + } catch (err) { + _didIteratorError21 = true; + _iteratorError21 = err; + } finally { + try { + if (!_iteratorNormalCompletion21 && _iterator21.return != null) { + _iterator21.return(); + } + } finally { + if (_didIteratorError21) { + throw _iteratorError21; + } + } + } + + return removedLocations; +} + +function getDirectiveMapForSchema(schema) { + return (0, _keyMap.default)(schema.getDirectives(), function (dir) { + return dir.name; + }); +} + +function getArgumentMapForDirective(directive) { + return (0, _keyMap.default)(directive.args, function (arg) { + return arg.name; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/findBreakingChanges.js.flow b/node_modules/graphql/utilities/findBreakingChanges.js.flow new file mode 100644 index 0000000..9f79621 --- /dev/null +++ b/node_modules/graphql/utilities/findBreakingChanges.js.flow @@ -0,0 +1,853 @@ +/** + * Copyright (c) 2016-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isNonNullType, + isListType, + isNamedType, + isRequiredArgument, + isRequiredInputField, +} from '../type/definition'; + +import type { + GraphQLNamedType, + GraphQLFieldMap, + GraphQLType, + GraphQLArgument, +} from '../type/definition'; + +import type { GraphQLDirective } from '../type/directives'; +import type { GraphQLSchema } from '../type/schema'; +import keyMap from '../jsutils/keyMap'; + +import type { ObjMap } from '../jsutils/ObjMap'; +import type { DirectiveLocationEnum } from '../language/directiveLocation'; + +export const BreakingChangeType = { + FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', + FIELD_REMOVED: 'FIELD_REMOVED', + TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND', + TYPE_REMOVED: 'TYPE_REMOVED', + TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION', + VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', + ARG_REMOVED: 'ARG_REMOVED', + ARG_CHANGED_KIND: 'ARG_CHANGED_KIND', + REQUIRED_ARG_ADDED: 'REQUIRED_ARG_ADDED', + REQUIRED_INPUT_FIELD_ADDED: 'REQUIRED_INPUT_FIELD_ADDED', + INTERFACE_REMOVED_FROM_OBJECT: 'INTERFACE_REMOVED_FROM_OBJECT', + DIRECTIVE_REMOVED: 'DIRECTIVE_REMOVED', + DIRECTIVE_ARG_REMOVED: 'DIRECTIVE_ARG_REMOVED', + DIRECTIVE_LOCATION_REMOVED: 'DIRECTIVE_LOCATION_REMOVED', + REQUIRED_DIRECTIVE_ARG_ADDED: 'REQUIRED_DIRECTIVE_ARG_ADDED', +}; + +export const DangerousChangeType = { + ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE', + VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM', + INTERFACE_ADDED_TO_OBJECT: 'INTERFACE_ADDED_TO_OBJECT', + TYPE_ADDED_TO_UNION: 'TYPE_ADDED_TO_UNION', + OPTIONAL_INPUT_FIELD_ADDED: 'OPTIONAL_INPUT_FIELD_ADDED', + OPTIONAL_ARG_ADDED: 'OPTIONAL_ARG_ADDED', +}; + +export type BreakingChange = { + type: $Keys, + description: string, +}; + +export type DangerousChange = { + type: $Keys, + description: string, +}; + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ +export function findBreakingChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + return [ + ...findRemovedTypes(oldSchema, newSchema), + ...findTypesThatChangedKind(oldSchema, newSchema), + ...findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), + ...findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema) + .breakingChanges, + ...findTypesRemovedFromUnions(oldSchema, newSchema), + ...findValuesRemovedFromEnums(oldSchema, newSchema), + ...findArgChanges(oldSchema, newSchema).breakingChanges, + ...findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), + ...findRemovedDirectives(oldSchema, newSchema), + ...findRemovedDirectiveArgs(oldSchema, newSchema), + ...findAddedNonNullDirectiveArgs(oldSchema, newSchema), + ...findRemovedDirectiveLocations(oldSchema, newSchema), + ]; +} + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + */ +export function findDangerousChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + return [ + ...findArgChanges(oldSchema, newSchema).dangerousChanges, + ...findValuesAddedToEnums(oldSchema, newSchema), + ...findInterfacesAddedToObjectTypes(oldSchema, newSchema), + ...findTypesAddedToUnions(oldSchema, newSchema), + ...findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema) + .dangerousChanges, + ]; +} + +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing an entire type. + */ +export function findRemovedTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const breakingChanges = []; + for (const typeName of Object.keys(oldTypeMap)) { + if (!newTypeMap[typeName]) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: `${typeName} was removed.`, + }); + } + } + return breakingChanges; +} + +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to changing the type of a type. + */ +export function findTypesThatChangedKind( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const breakingChanges = []; + for (const typeName of Object.keys(oldTypeMap)) { + if (!newTypeMap[typeName]) { + continue; + } + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (oldType.constructor !== newType.constructor) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: + `${typeName} changed from ` + + `${typeKindName(oldType)} to ${typeKindName(newType)}.`, + }); + } + } + return breakingChanges; +} + +/** + * Given two schemas, returns an Array containing descriptions of any + * breaking or dangerous changes in the newSchema related to arguments + * (such as removal or change of type of an argument, or a change in an + * argument's default value). + */ +export function findArgChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): { + breakingChanges: Array, + dangerousChanges: Array, +} { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const breakingChanges = []; + const dangerousChanges = []; + + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if ( + !(isObjectType(oldType) || isInterfaceType(oldType)) || + !(isObjectType(newType) || isInterfaceType(newType)) || + newType.constructor !== oldType.constructor + ) { + continue; + } + + const oldTypeFields: GraphQLFieldMap<*, *> = oldType.getFields(); + const newTypeFields: GraphQLFieldMap<*, *> = newType.getFields(); + + for (const fieldName of Object.keys(oldTypeFields)) { + if (!newTypeFields[fieldName]) { + continue; + } + + for (const oldArgDef of oldTypeFields[fieldName].args) { + const newArgs = newTypeFields[fieldName].args; + const newArgDef = newArgs.find(arg => arg.name === oldArgDef.name); + + // Arg not present + if (!newArgDef) { + breakingChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: + `${oldType.name}.${fieldName} arg ` + + `${oldArgDef.name} was removed`, + }); + } else { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldArgDef.type, + newArgDef.type, + ); + if (!isSafe) { + breakingChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: + `${oldType.name}.${fieldName} arg ` + + `${oldArgDef.name} has changed type from ` + + `${oldArgDef.type.toString()} to ${newArgDef.type.toString()}`, + }); + } else if ( + oldArgDef.defaultValue !== undefined && + oldArgDef.defaultValue !== newArgDef.defaultValue + ) { + dangerousChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: + `${oldType.name}.${fieldName} arg ` + + `${oldArgDef.name} has changed defaultValue`, + }); + } + } + } + // Check if arg was added to the field + for (const newArgDef of newTypeFields[fieldName].args) { + const oldArgs = oldTypeFields[fieldName].args; + const oldArgDef = oldArgs.find(arg => arg.name === newArgDef.name); + if (!oldArgDef) { + const argName = newArgDef.name; + if (isRequiredArgument(newArgDef)) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: + `A required arg ${argName} on ` + + `${typeName}.${fieldName} was added`, + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: + `An optional arg ${argName} on ` + + `${typeName}.${fieldName} was added`, + }); + } + } + } + } + } + + return { + breakingChanges, + dangerousChanges, + }; +} + +function typeKindName(type: GraphQLNamedType): string { + if (isScalarType(type)) { + return 'a Scalar type'; + } + if (isObjectType(type)) { + return 'an Object type'; + } + if (isInterfaceType(type)) { + return 'an Interface type'; + } + if (isUnionType(type)) { + return 'a Union type'; + } + if (isEnumType(type)) { + return 'an Enum type'; + } + if (isInputObjectType(type)) { + return 'an Input type'; + } + throw new TypeError('Unknown type ' + type.constructor.name); +} + +export function findFieldsThatChangedTypeOnObjectOrInterfaceTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const breakingChanges = []; + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if ( + !(isObjectType(oldType) || isInterfaceType(oldType)) || + !(isObjectType(newType) || isInterfaceType(newType)) || + newType.constructor !== oldType.constructor + ) { + continue; + } + + const oldTypeFieldsDef = oldType.getFields(); + const newTypeFieldsDef = newType.getFields(); + for (const fieldName of Object.keys(oldTypeFieldsDef)) { + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${typeName}.${fieldName} was removed.`, + }); + } else { + const oldFieldType = oldTypeFieldsDef[fieldName].type; + const newFieldType = newTypeFieldsDef[fieldName].type; + const isSafe = isChangeSafeForObjectOrInterfaceField( + oldFieldType, + newFieldType, + ); + if (!isSafe) { + const oldFieldTypeString = isNamedType(oldFieldType) + ? oldFieldType.name + : oldFieldType.toString(); + const newFieldTypeString = isNamedType(newFieldType) + ? newFieldType.name + : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${typeName}.${fieldName} changed type from ` + + `${oldFieldTypeString} to ${newFieldTypeString}.`, + }); + } + } + } + } + return breakingChanges; +} + +export function findFieldsThatChangedTypeOnInputObjectTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): { + breakingChanges: Array, + dangerousChanges: Array, +} { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const breakingChanges = []; + const dangerousChanges = []; + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isInputObjectType(oldType) || !isInputObjectType(newType)) { + continue; + } + + const oldTypeFieldsDef = oldType.getFields(); + const newTypeFieldsDef = newType.getFields(); + for (const fieldName of Object.keys(oldTypeFieldsDef)) { + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${typeName}.${fieldName} was removed.`, + }); + } else { + const oldFieldType = oldTypeFieldsDef[fieldName].type; + const newFieldType = newTypeFieldsDef[fieldName].type; + + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldFieldType, + newFieldType, + ); + if (!isSafe) { + const oldFieldTypeString = isNamedType(oldFieldType) + ? oldFieldType.name + : oldFieldType.toString(); + const newFieldTypeString = isNamedType(newFieldType) + ? newFieldType.name + : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${typeName}.${fieldName} changed type from ` + + `${oldFieldTypeString} to ${newFieldTypeString}.`, + }); + } + } + } + // Check if a field was added to the input object type + for (const fieldName of Object.keys(newTypeFieldsDef)) { + if (!(fieldName in oldTypeFieldsDef)) { + if (isRequiredInputField(newTypeFieldsDef[fieldName])) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: + `A required field ${fieldName} on ` + + `input type ${typeName} was added.`, + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: + `An optional field ${fieldName} on ` + + `input type ${typeName} was added.`, + }); + } + } + } + } + return { + breakingChanges, + dangerousChanges, + }; +} + +function isChangeSafeForObjectOrInterfaceField( + oldType: GraphQLType, + newType: GraphQLType, +): boolean { + if (isNamedType(oldType)) { + return ( + // if they're both named types, see if their names are equivalent + (isNamedType(newType) && oldType.name === newType.name) || + // moving from nullable to non-null of the same underlying type is safe + (isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); + } else if (isListType(oldType)) { + return ( + // if they're both lists, make sure the underlying types are compatible + (isListType(newType) && + isChangeSafeForObjectOrInterfaceField( + oldType.ofType, + newType.ofType, + )) || + // moving from nullable to non-null of the same underlying type is safe + (isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); + } else if (isNonNullType(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return ( + isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) + ); + } + return false; +} + +function isChangeSafeForInputObjectFieldOrFieldArg( + oldType: GraphQLType, + newType: GraphQLType, +): boolean { + if (isNamedType(oldType)) { + // if they're both named types, see if their names are equivalent + return isNamedType(newType) && oldType.name === newType.name; + } else if (isListType(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return ( + isListType(newType) && + isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) + ); + } else if (isNonNullType(oldType)) { + return ( + // if they're both non-null, make sure the underlying types are + // compatible + (isNonNullType(newType) && + isChangeSafeForInputObjectFieldOrFieldArg( + oldType.ofType, + newType.ofType, + )) || + // moving from non-null to nullable of the same underlying type is safe + (!isNonNullType(newType) && + isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType)) + ); + } + return false; +} + +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing types from a union type. + */ +export function findTypesRemovedFromUnions( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const typesRemovedFromUnion = []; + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isUnionType(oldType) || !isUnionType(newType)) { + continue; + } + const typeNamesInNewUnion = Object.create(null); + for (const type of newType.getTypes()) { + typeNamesInNewUnion[type.name] = true; + } + for (const type of oldType.getTypes()) { + if (!typeNamesInNewUnion[type.name]) { + typesRemovedFromUnion.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: `${type.name} was removed from union type ${typeName}.`, + }); + } + } + } + return typesRemovedFromUnion; +} + +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding types to a union type. + */ +export function findTypesAddedToUnions( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const typesAddedToUnion = []; + for (const typeName of Object.keys(newTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isUnionType(oldType) || !isUnionType(newType)) { + continue; + } + const typeNamesInOldUnion = Object.create(null); + for (const type of oldType.getTypes()) { + typeNamesInOldUnion[type.name] = true; + } + for (const type of newType.getTypes()) { + if (!typeNamesInOldUnion[type.name]) { + typesAddedToUnion.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: `${type.name} was added to union type ${typeName}.`, + }); + } + } + } + return typesAddedToUnion; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing values from an enum type. + */ +export function findValuesRemovedFromEnums( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const valuesRemovedFromEnums = []; + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isEnumType(oldType) || !isEnumType(newType)) { + continue; + } + const valuesInNewEnum = Object.create(null); + for (const value of newType.getValues()) { + valuesInNewEnum[value.name] = true; + } + for (const value of oldType.getValues()) { + if (!valuesInNewEnum[value.name]) { + valuesRemovedFromEnums.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: `${value.name} was removed from enum type ${typeName}.`, + }); + } + } + } + return valuesRemovedFromEnums; +} + +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding values to an enum type. + */ +export function findValuesAddedToEnums( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const valuesAddedToEnums = []; + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isEnumType(oldType) || !isEnumType(newType)) { + continue; + } + + const valuesInOldEnum = Object.create(null); + for (const value of oldType.getValues()) { + valuesInOldEnum[value.name] = true; + } + for (const value of newType.getValues()) { + if (!valuesInOldEnum[value.name]) { + valuesAddedToEnums.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: `${value.name} was added to enum type ${typeName}.`, + }); + } + } + } + return valuesAddedToEnums; +} + +export function findInterfacesRemovedFromObjectTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + const breakingChanges = []; + + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isObjectType(oldType) || !isObjectType(newType)) { + continue; + } + + const oldInterfaces = oldType.getInterfaces(); + const newInterfaces = newType.getInterfaces(); + for (const oldInterface of oldInterfaces) { + if (!newInterfaces.some(int => int.name === oldInterface.name)) { + breakingChanges.push({ + type: BreakingChangeType.INTERFACE_REMOVED_FROM_OBJECT, + description: + `${typeName} no longer implements interface ` + + `${oldInterface.name}.`, + }); + } + } + } + return breakingChanges; +} + +export function findInterfacesAddedToObjectTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + const interfacesAddedToObjectTypes = []; + + for (const typeName of Object.keys(newTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isObjectType(oldType) || !isObjectType(newType)) { + continue; + } + + const oldInterfaces = oldType.getInterfaces(); + const newInterfaces = newType.getInterfaces(); + for (const newInterface of newInterfaces) { + if (!oldInterfaces.some(int => int.name === newInterface.name)) { + interfacesAddedToObjectTypes.push({ + type: DangerousChangeType.INTERFACE_ADDED_TO_OBJECT, + description: + `${newInterface.name} added to interfaces implemented ` + + `by ${typeName}.`, + }); + } + } + } + return interfacesAddedToObjectTypes; +} + +export function findRemovedDirectives( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const removedDirectives = []; + + const newSchemaDirectiveMap = getDirectiveMapForSchema(newSchema); + for (const directive of oldSchema.getDirectives()) { + if (!newSchemaDirectiveMap[directive.name]) { + removedDirectives.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: `${directive.name} was removed`, + }); + } + } + + return removedDirectives; +} + +function findRemovedArgsForDirective( + oldDirective: GraphQLDirective, + newDirective: GraphQLDirective, +): Array { + const removedArgs = []; + const newArgMap = getArgumentMapForDirective(newDirective); + + for (const arg of oldDirective.args) { + if (!newArgMap[arg.name]) { + removedArgs.push(arg); + } + } + + return removedArgs; +} + +export function findRemovedDirectiveArgs( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const removedDirectiveArgs = []; + const oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + + for (const newDirective of newSchema.getDirectives()) { + const oldDirective = oldSchemaDirectiveMap[newDirective.name]; + if (!oldDirective) { + continue; + } + + for (const arg of findRemovedArgsForDirective(oldDirective, newDirective)) { + removedDirectiveArgs.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: `${arg.name} was removed from ${newDirective.name}`, + }); + } + } + + return removedDirectiveArgs; +} + +function findAddedArgsForDirective( + oldDirective: GraphQLDirective, + newDirective: GraphQLDirective, +): Array { + const addedArgs = []; + const oldArgMap = getArgumentMapForDirective(oldDirective); + + for (const arg of newDirective.args) { + if (!oldArgMap[arg.name]) { + addedArgs.push(arg); + } + } + + return addedArgs; +} + +export function findAddedNonNullDirectiveArgs( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const addedNonNullableArgs = []; + const oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + + for (const newDirective of newSchema.getDirectives()) { + const oldDirective = oldSchemaDirectiveMap[newDirective.name]; + if (!oldDirective) { + continue; + } + + for (const arg of findAddedArgsForDirective(oldDirective, newDirective)) { + if (isRequiredArgument(arg)) { + addedNonNullableArgs.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: + `A required arg ${arg.name} on directive ` + + `${newDirective.name} was added`, + }); + } + } + } + + return addedNonNullableArgs; +} + +export function findRemovedLocationsForDirective( + oldDirective: GraphQLDirective, + newDirective: GraphQLDirective, +): Array { + const removedLocations = []; + const newLocationSet = new Set(newDirective.locations); + + for (const oldLocation of oldDirective.locations) { + if (!newLocationSet.has(oldLocation)) { + removedLocations.push(oldLocation); + } + } + + return removedLocations; +} + +export function findRemovedDirectiveLocations( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const removedLocations = []; + const oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + + for (const newDirective of newSchema.getDirectives()) { + const oldDirective = oldSchemaDirectiveMap[newDirective.name]; + if (!oldDirective) { + continue; + } + + for (const location of findRemovedLocationsForDirective( + oldDirective, + newDirective, + )) { + removedLocations.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: `${location} was removed from ${newDirective.name}`, + }); + } + } + + return removedLocations; +} + +function getDirectiveMapForSchema( + schema: GraphQLSchema, +): ObjMap { + return keyMap(schema.getDirectives(), dir => dir.name); +} + +function getArgumentMapForDirective( + directive: GraphQLDirective, +): ObjMap { + return keyMap(directive.args, arg => arg.name); +} diff --git a/node_modules/graphql/utilities/findBreakingChanges.mjs b/node_modules/graphql/utilities/findBreakingChanges.mjs new file mode 100644 index 0000000..bec653f --- /dev/null +++ b/node_modules/graphql/utilities/findBreakingChanges.mjs @@ -0,0 +1,1201 @@ +/** + * Copyright (c) 2016-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isNonNullType, isListType, isNamedType, isRequiredArgument, isRequiredInputField } from '../type/definition'; +import keyMap from '../jsutils/keyMap'; +export var BreakingChangeType = { + FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', + FIELD_REMOVED: 'FIELD_REMOVED', + TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND', + TYPE_REMOVED: 'TYPE_REMOVED', + TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION', + VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', + ARG_REMOVED: 'ARG_REMOVED', + ARG_CHANGED_KIND: 'ARG_CHANGED_KIND', + REQUIRED_ARG_ADDED: 'REQUIRED_ARG_ADDED', + REQUIRED_INPUT_FIELD_ADDED: 'REQUIRED_INPUT_FIELD_ADDED', + INTERFACE_REMOVED_FROM_OBJECT: 'INTERFACE_REMOVED_FROM_OBJECT', + DIRECTIVE_REMOVED: 'DIRECTIVE_REMOVED', + DIRECTIVE_ARG_REMOVED: 'DIRECTIVE_ARG_REMOVED', + DIRECTIVE_LOCATION_REMOVED: 'DIRECTIVE_LOCATION_REMOVED', + REQUIRED_DIRECTIVE_ARG_ADDED: 'REQUIRED_DIRECTIVE_ARG_ADDED' +}; +export var DangerousChangeType = { + ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE', + VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM', + INTERFACE_ADDED_TO_OBJECT: 'INTERFACE_ADDED_TO_OBJECT', + TYPE_ADDED_TO_UNION: 'TYPE_ADDED_TO_UNION', + OPTIONAL_INPUT_FIELD_ADDED: 'OPTIONAL_INPUT_FIELD_ADDED', + OPTIONAL_ARG_ADDED: 'OPTIONAL_ARG_ADDED' +}; + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ +export function findBreakingChanges(oldSchema, newSchema) { + return findRemovedTypes(oldSchema, newSchema).concat(findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).breakingChanges, findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), findRemovedDirectives(oldSchema, newSchema), findRemovedDirectiveArgs(oldSchema, newSchema), findAddedNonNullDirectiveArgs(oldSchema, newSchema), findRemovedDirectiveLocations(oldSchema, newSchema)); +} +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + */ + +export function findDangerousChanges(oldSchema, newSchema) { + return findArgChanges(oldSchema, newSchema).dangerousChanges.concat(findValuesAddedToEnums(oldSchema, newSchema), findInterfacesAddedToObjectTypes(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).dangerousChanges); +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing an entire type. + */ + +export function findRemovedTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr = Object.keys(oldTypeMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var typeName = _arr[_i]; + + if (!newTypeMap[typeName]) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: "".concat(typeName, " was removed.") + }); + } + } + + return breakingChanges; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to changing the type of a type. + */ + +export function findTypesThatChangedKind(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr2 = Object.keys(oldTypeMap); + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var typeName = _arr2[_i2]; + + if (!newTypeMap[typeName]) { + continue; + } + + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (oldType.constructor !== newType.constructor) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: "".concat(typeName, " changed from ") + "".concat(typeKindName(oldType), " to ").concat(typeKindName(newType), ".") + }); + } + } + + return breakingChanges; +} +/** + * Given two schemas, returns an Array containing descriptions of any + * breaking or dangerous changes in the newSchema related to arguments + * (such as removal or change of type of an argument, or a change in an + * argument's default value). + */ + +export function findArgChanges(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + var dangerousChanges = []; + + var _arr3 = Object.keys(oldTypeMap); + + for (var _i3 = 0; _i3 < _arr3.length; _i3++) { + var typeName = _arr3[_i3]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(isObjectType(oldType) || isInterfaceType(oldType)) || !(isObjectType(newType) || isInterfaceType(newType)) || newType.constructor !== oldType.constructor) { + continue; + } + + var oldTypeFields = oldType.getFields(); + var newTypeFields = newType.getFields(); + + var _arr4 = Object.keys(oldTypeFields); + + for (var _i4 = 0; _i4 < _arr4.length; _i4++) { + var fieldName = _arr4[_i4]; + + if (!newTypeFields[fieldName]) { + continue; + } + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + var _loop = function _loop() { + var oldArgDef = _step.value; + var newArgs = newTypeFields[fieldName].args; + var newArgDef = newArgs.find(function (arg) { + return arg.name === oldArgDef.name; + }); // Arg not present + + if (!newArgDef) { + breakingChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " was removed") + }); + } else { + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type); + + if (!isSafe) { + breakingChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed type from ") + "".concat(oldArgDef.type.toString(), " to ").concat(newArgDef.type.toString()) + }); + } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) { + dangerousChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed defaultValue") + }); + } + } + }; + + for (var _iterator = oldTypeFields[fieldName].args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + _loop(); + } // Check if arg was added to the field + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + var _loop2 = function _loop2() { + var newArgDef = _step2.value; + var oldArgs = oldTypeFields[fieldName].args; + var oldArgDef = oldArgs.find(function (arg) { + return arg.name === newArgDef.name; + }); + + if (!oldArgDef) { + var argName = newArgDef.name; + + if (isRequiredArgument(newArgDef)) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: "A required arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added") + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: "An optional arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added") + }); + } + } + }; + + for (var _iterator2 = newTypeFields[fieldName].args[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + _loop2(); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + } + + return { + breakingChanges: breakingChanges, + dangerousChanges: dangerousChanges + }; +} + +function typeKindName(type) { + if (isScalarType(type)) { + return 'a Scalar type'; + } + + if (isObjectType(type)) { + return 'an Object type'; + } + + if (isInterfaceType(type)) { + return 'an Interface type'; + } + + if (isUnionType(type)) { + return 'a Union type'; + } + + if (isEnumType(type)) { + return 'an Enum type'; + } + + if (isInputObjectType(type)) { + return 'an Input type'; + } + + throw new TypeError('Unknown type ' + type.constructor.name); +} + +export function findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr5 = Object.keys(oldTypeMap); + + for (var _i5 = 0; _i5 < _arr5.length; _i5++) { + var typeName = _arr5[_i5]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(isObjectType(oldType) || isInterfaceType(oldType)) || !(isObjectType(newType) || isInterfaceType(newType)) || newType.constructor !== oldType.constructor) { + continue; + } + + var oldTypeFieldsDef = oldType.getFields(); + var newTypeFieldsDef = newType.getFields(); + + var _arr6 = Object.keys(oldTypeFieldsDef); + + for (var _i6 = 0; _i6 < _arr6.length; _i6++) { + var fieldName = _arr6[_i6]; + + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(typeName, ".").concat(fieldName, " was removed.") + }); + } else { + var oldFieldType = oldTypeFieldsDef[fieldName].type; + var newFieldType = newTypeFieldsDef[fieldName].type; + var isSafe = isChangeSafeForObjectOrInterfaceField(oldFieldType, newFieldType); + + if (!isSafe) { + var oldFieldTypeString = isNamedType(oldFieldType) ? oldFieldType.name : oldFieldType.toString(); + var newFieldTypeString = isNamedType(newFieldType) ? newFieldType.name : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".") + }); + } + } + } + } + + return breakingChanges; +} +export function findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + var dangerousChanges = []; + + var _arr7 = Object.keys(oldTypeMap); + + for (var _i7 = 0; _i7 < _arr7.length; _i7++) { + var typeName = _arr7[_i7]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isInputObjectType(oldType) || !isInputObjectType(newType)) { + continue; + } + + var oldTypeFieldsDef = oldType.getFields(); + var newTypeFieldsDef = newType.getFields(); + + var _arr8 = Object.keys(oldTypeFieldsDef); + + for (var _i8 = 0; _i8 < _arr8.length; _i8++) { + var fieldName = _arr8[_i8]; + + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(typeName, ".").concat(fieldName, " was removed.") + }); + } else { + var oldFieldType = oldTypeFieldsDef[fieldName].type; + var newFieldType = newTypeFieldsDef[fieldName].type; + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldFieldType, newFieldType); + + if (!isSafe) { + var oldFieldTypeString = isNamedType(oldFieldType) ? oldFieldType.name : oldFieldType.toString(); + var newFieldTypeString = isNamedType(newFieldType) ? newFieldType.name : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".") + }); + } + } + } // Check if a field was added to the input object type + + + var _arr9 = Object.keys(newTypeFieldsDef); + + for (var _i9 = 0; _i9 < _arr9.length; _i9++) { + var _fieldName = _arr9[_i9]; + + if (!(_fieldName in oldTypeFieldsDef)) { + if (isRequiredInputField(newTypeFieldsDef[_fieldName])) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: "A required field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.") + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: "An optional field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.") + }); + } + } + } + } + + return { + breakingChanges: breakingChanges, + dangerousChanges: dangerousChanges + }; +} + +function isChangeSafeForObjectOrInterfaceField(oldType, newType) { + if (isNamedType(oldType)) { + return (// if they're both named types, see if their names are equivalent + isNamedType(newType) && oldType.name === newType.name || // moving from nullable to non-null of the same underlying type is safe + isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } else if (isListType(oldType)) { + return (// if they're both lists, make sure the underlying types are compatible + isListType(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || // moving from nullable to non-null of the same underlying type is safe + isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } else if (isNonNullType(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType); + } + + return false; +} + +function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { + if (isNamedType(oldType)) { + // if they're both named types, see if their names are equivalent + return isNamedType(newType) && oldType.name === newType.name; + } else if (isListType(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return isListType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType); + } else if (isNonNullType(oldType)) { + return (// if they're both non-null, make sure the underlying types are + // compatible + isNonNullType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || // moving from non-null to nullable of the same underlying type is safe + !isNonNullType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType) + ); + } + + return false; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing types from a union type. + */ + + +export function findTypesRemovedFromUnions(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var typesRemovedFromUnion = []; + + var _arr10 = Object.keys(oldTypeMap); + + for (var _i10 = 0; _i10 < _arr10.length; _i10++) { + var typeName = _arr10[_i10]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isUnionType(oldType) || !isUnionType(newType)) { + continue; + } + + var typeNamesInNewUnion = Object.create(null); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = newType.getTypes()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var type = _step3.value; + typeNamesInNewUnion[type.name] = true; + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = oldType.getTypes()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var _type = _step4.value; + + if (!typeNamesInNewUnion[_type.name]) { + typesRemovedFromUnion.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: "".concat(_type.name, " was removed from union type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + + return typesRemovedFromUnion; +} +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding types to a union type. + */ + +export function findTypesAddedToUnions(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var typesAddedToUnion = []; + + var _arr11 = Object.keys(newTypeMap); + + for (var _i11 = 0; _i11 < _arr11.length; _i11++) { + var typeName = _arr11[_i11]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isUnionType(oldType) || !isUnionType(newType)) { + continue; + } + + var typeNamesInOldUnion = Object.create(null); + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = oldType.getTypes()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var type = _step5.value; + typeNamesInOldUnion[type.name] = true; + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = newType.getTypes()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var _type2 = _step6.value; + + if (!typeNamesInOldUnion[_type2.name]) { + typesAddedToUnion.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: "".concat(_type2.name, " was added to union type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + + return typesAddedToUnion; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing values from an enum type. + */ + +export function findValuesRemovedFromEnums(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var valuesRemovedFromEnums = []; + + var _arr12 = Object.keys(oldTypeMap); + + for (var _i12 = 0; _i12 < _arr12.length; _i12++) { + var typeName = _arr12[_i12]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isEnumType(oldType) || !isEnumType(newType)) { + continue; + } + + var valuesInNewEnum = Object.create(null); + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = newType.getValues()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var value = _step7.value; + valuesInNewEnum[value.name] = true; + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + for (var _iterator8 = oldType.getValues()[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var _value = _step8.value; + + if (!valuesInNewEnum[_value.name]) { + valuesRemovedFromEnums.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: "".concat(_value.name, " was removed from enum type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + } + + return valuesRemovedFromEnums; +} +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding values to an enum type. + */ + +export function findValuesAddedToEnums(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var valuesAddedToEnums = []; + + var _arr13 = Object.keys(oldTypeMap); + + for (var _i13 = 0; _i13 < _arr13.length; _i13++) { + var typeName = _arr13[_i13]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isEnumType(oldType) || !isEnumType(newType)) { + continue; + } + + var valuesInOldEnum = Object.create(null); + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + for (var _iterator9 = oldType.getValues()[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + var value = _step9.value; + valuesInOldEnum[value.name] = true; + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = newType.getValues()[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var _value2 = _step10.value; + + if (!valuesInOldEnum[_value2.name]) { + valuesAddedToEnums.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: "".concat(_value2.name, " was added to enum type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } + } + + return valuesAddedToEnums; +} +export function findInterfacesRemovedFromObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr14 = Object.keys(oldTypeMap); + + for (var _i14 = 0; _i14 < _arr14.length; _i14++) { + var typeName = _arr14[_i14]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isObjectType(oldType) || !isObjectType(newType)) { + continue; + } + + var oldInterfaces = oldType.getInterfaces(); + var newInterfaces = newType.getInterfaces(); + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + var _loop3 = function _loop3() { + var oldInterface = _step11.value; + + if (!newInterfaces.some(function (int) { + return int.name === oldInterface.name; + })) { + breakingChanges.push({ + type: BreakingChangeType.INTERFACE_REMOVED_FROM_OBJECT, + description: "".concat(typeName, " no longer implements interface ") + "".concat(oldInterface.name, ".") + }); + } + }; + + for (var _iterator11 = oldInterfaces[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + _loop3(); + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } + } + + return breakingChanges; +} +export function findInterfacesAddedToObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var interfacesAddedToObjectTypes = []; + + var _arr15 = Object.keys(newTypeMap); + + for (var _i15 = 0; _i15 < _arr15.length; _i15++) { + var typeName = _arr15[_i15]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isObjectType(oldType) || !isObjectType(newType)) { + continue; + } + + var oldInterfaces = oldType.getInterfaces(); + var newInterfaces = newType.getInterfaces(); + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + var _loop4 = function _loop4() { + var newInterface = _step12.value; + + if (!oldInterfaces.some(function (int) { + return int.name === newInterface.name; + })) { + interfacesAddedToObjectTypes.push({ + type: DangerousChangeType.INTERFACE_ADDED_TO_OBJECT, + description: "".concat(newInterface.name, " added to interfaces implemented ") + "by ".concat(typeName, ".") + }); + } + }; + + for (var _iterator12 = newInterfaces[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + _loop4(); + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } + } + + return interfacesAddedToObjectTypes; +} +export function findRemovedDirectives(oldSchema, newSchema) { + var removedDirectives = []; + var newSchemaDirectiveMap = getDirectiveMapForSchema(newSchema); + var _iteratorNormalCompletion13 = true; + var _didIteratorError13 = false; + var _iteratorError13 = undefined; + + try { + for (var _iterator13 = oldSchema.getDirectives()[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) { + var directive = _step13.value; + + if (!newSchemaDirectiveMap[directive.name]) { + removedDirectives.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: "".concat(directive.name, " was removed") + }); + } + } + } catch (err) { + _didIteratorError13 = true; + _iteratorError13 = err; + } finally { + try { + if (!_iteratorNormalCompletion13 && _iterator13.return != null) { + _iterator13.return(); + } + } finally { + if (_didIteratorError13) { + throw _iteratorError13; + } + } + } + + return removedDirectives; +} + +function findRemovedArgsForDirective(oldDirective, newDirective) { + var removedArgs = []; + var newArgMap = getArgumentMapForDirective(newDirective); + var _iteratorNormalCompletion14 = true; + var _didIteratorError14 = false; + var _iteratorError14 = undefined; + + try { + for (var _iterator14 = oldDirective.args[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) { + var arg = _step14.value; + + if (!newArgMap[arg.name]) { + removedArgs.push(arg); + } + } + } catch (err) { + _didIteratorError14 = true; + _iteratorError14 = err; + } finally { + try { + if (!_iteratorNormalCompletion14 && _iterator14.return != null) { + _iterator14.return(); + } + } finally { + if (_didIteratorError14) { + throw _iteratorError14; + } + } + } + + return removedArgs; +} + +export function findRemovedDirectiveArgs(oldSchema, newSchema) { + var removedDirectiveArgs = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion15 = true; + var _didIteratorError15 = false; + var _iteratorError15 = undefined; + + try { + for (var _iterator15 = newSchema.getDirectives()[Symbol.iterator](), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) { + var newDirective = _step15.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion16 = true; + var _didIteratorError16 = false; + var _iteratorError16 = undefined; + + try { + for (var _iterator16 = findRemovedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step16; !(_iteratorNormalCompletion16 = (_step16 = _iterator16.next()).done); _iteratorNormalCompletion16 = true) { + var arg = _step16.value; + removedDirectiveArgs.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: "".concat(arg.name, " was removed from ").concat(newDirective.name) + }); + } + } catch (err) { + _didIteratorError16 = true; + _iteratorError16 = err; + } finally { + try { + if (!_iteratorNormalCompletion16 && _iterator16.return != null) { + _iterator16.return(); + } + } finally { + if (_didIteratorError16) { + throw _iteratorError16; + } + } + } + } + } catch (err) { + _didIteratorError15 = true; + _iteratorError15 = err; + } finally { + try { + if (!_iteratorNormalCompletion15 && _iterator15.return != null) { + _iterator15.return(); + } + } finally { + if (_didIteratorError15) { + throw _iteratorError15; + } + } + } + + return removedDirectiveArgs; +} + +function findAddedArgsForDirective(oldDirective, newDirective) { + var addedArgs = []; + var oldArgMap = getArgumentMapForDirective(oldDirective); + var _iteratorNormalCompletion17 = true; + var _didIteratorError17 = false; + var _iteratorError17 = undefined; + + try { + for (var _iterator17 = newDirective.args[Symbol.iterator](), _step17; !(_iteratorNormalCompletion17 = (_step17 = _iterator17.next()).done); _iteratorNormalCompletion17 = true) { + var arg = _step17.value; + + if (!oldArgMap[arg.name]) { + addedArgs.push(arg); + } + } + } catch (err) { + _didIteratorError17 = true; + _iteratorError17 = err; + } finally { + try { + if (!_iteratorNormalCompletion17 && _iterator17.return != null) { + _iterator17.return(); + } + } finally { + if (_didIteratorError17) { + throw _iteratorError17; + } + } + } + + return addedArgs; +} + +export function findAddedNonNullDirectiveArgs(oldSchema, newSchema) { + var addedNonNullableArgs = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion18 = true; + var _didIteratorError18 = false; + var _iteratorError18 = undefined; + + try { + for (var _iterator18 = newSchema.getDirectives()[Symbol.iterator](), _step18; !(_iteratorNormalCompletion18 = (_step18 = _iterator18.next()).done); _iteratorNormalCompletion18 = true) { + var newDirective = _step18.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion19 = true; + var _didIteratorError19 = false; + var _iteratorError19 = undefined; + + try { + for (var _iterator19 = findAddedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step19; !(_iteratorNormalCompletion19 = (_step19 = _iterator19.next()).done); _iteratorNormalCompletion19 = true) { + var arg = _step19.value; + + if (isRequiredArgument(arg)) { + addedNonNullableArgs.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: "A required arg ".concat(arg.name, " on directive ") + "".concat(newDirective.name, " was added") + }); + } + } + } catch (err) { + _didIteratorError19 = true; + _iteratorError19 = err; + } finally { + try { + if (!_iteratorNormalCompletion19 && _iterator19.return != null) { + _iterator19.return(); + } + } finally { + if (_didIteratorError19) { + throw _iteratorError19; + } + } + } + } + } catch (err) { + _didIteratorError18 = true; + _iteratorError18 = err; + } finally { + try { + if (!_iteratorNormalCompletion18 && _iterator18.return != null) { + _iterator18.return(); + } + } finally { + if (_didIteratorError18) { + throw _iteratorError18; + } + } + } + + return addedNonNullableArgs; +} +export function findRemovedLocationsForDirective(oldDirective, newDirective) { + var removedLocations = []; + var newLocationSet = new Set(newDirective.locations); + var _iteratorNormalCompletion20 = true; + var _didIteratorError20 = false; + var _iteratorError20 = undefined; + + try { + for (var _iterator20 = oldDirective.locations[Symbol.iterator](), _step20; !(_iteratorNormalCompletion20 = (_step20 = _iterator20.next()).done); _iteratorNormalCompletion20 = true) { + var oldLocation = _step20.value; + + if (!newLocationSet.has(oldLocation)) { + removedLocations.push(oldLocation); + } + } + } catch (err) { + _didIteratorError20 = true; + _iteratorError20 = err; + } finally { + try { + if (!_iteratorNormalCompletion20 && _iterator20.return != null) { + _iterator20.return(); + } + } finally { + if (_didIteratorError20) { + throw _iteratorError20; + } + } + } + + return removedLocations; +} +export function findRemovedDirectiveLocations(oldSchema, newSchema) { + var removedLocations = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion21 = true; + var _didIteratorError21 = false; + var _iteratorError21 = undefined; + + try { + for (var _iterator21 = newSchema.getDirectives()[Symbol.iterator](), _step21; !(_iteratorNormalCompletion21 = (_step21 = _iterator21.next()).done); _iteratorNormalCompletion21 = true) { + var newDirective = _step21.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion22 = true; + var _didIteratorError22 = false; + var _iteratorError22 = undefined; + + try { + for (var _iterator22 = findRemovedLocationsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step22; !(_iteratorNormalCompletion22 = (_step22 = _iterator22.next()).done); _iteratorNormalCompletion22 = true) { + var location = _step22.value; + removedLocations.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: "".concat(location, " was removed from ").concat(newDirective.name) + }); + } + } catch (err) { + _didIteratorError22 = true; + _iteratorError22 = err; + } finally { + try { + if (!_iteratorNormalCompletion22 && _iterator22.return != null) { + _iterator22.return(); + } + } finally { + if (_didIteratorError22) { + throw _iteratorError22; + } + } + } + } + } catch (err) { + _didIteratorError21 = true; + _iteratorError21 = err; + } finally { + try { + if (!_iteratorNormalCompletion21 && _iterator21.return != null) { + _iterator21.return(); + } + } finally { + if (_didIteratorError21) { + throw _iteratorError21; + } + } + } + + return removedLocations; +} + +function getDirectiveMapForSchema(schema) { + return keyMap(schema.getDirectives(), function (dir) { + return dir.name; + }); +} + +function getArgumentMapForDirective(directive) { + return keyMap(directive.args, function (arg) { + return arg.name; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/findDeprecatedUsages.js b/node_modules/graphql/utilities/findDeprecatedUsages.js new file mode 100644 index 0000000..4906b58 --- /dev/null +++ b/node_modules/graphql/utilities/findDeprecatedUsages.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findDeprecatedUsages = findDeprecatedUsages; + +var _GraphQLError = require("../error/GraphQLError"); + +var _visitor = require("../language/visitor"); + +var _definition = require("../type/definition"); + +var _TypeInfo = require("./TypeInfo"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * A validation rule which reports deprecated usages. + * + * Returns a list of GraphQLError instances describing each deprecated use. + */ +function findDeprecatedUsages(schema, ast) { + var errors = []; + var typeInfo = new _TypeInfo.TypeInfo(schema); + (0, _visitor.visit)(ast, (0, _visitor.visitWithTypeInfo)(typeInfo, { + Field: function Field(node) { + var fieldDef = typeInfo.getFieldDef(); + + if (fieldDef && fieldDef.isDeprecated) { + var parentType = typeInfo.getParentType(); + + if (parentType) { + var reason = fieldDef.deprecationReason; + errors.push(new _GraphQLError.GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node])); + } + } + }, + EnumValue: function EnumValue(node) { + var enumVal = typeInfo.getEnumValue(); + + if (enumVal && enumVal.isDeprecated) { + var type = (0, _definition.getNamedType)(typeInfo.getInputType()); + + if (type) { + var reason = enumVal.deprecationReason; + errors.push(new _GraphQLError.GraphQLError("The enum value ".concat(type.name, ".").concat(enumVal.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node])); + } + } + } + })); + return errors; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/findDeprecatedUsages.js.flow b/node_modules/graphql/utilities/findDeprecatedUsages.js.flow new file mode 100644 index 0000000..d2ad48e --- /dev/null +++ b/node_modules/graphql/utilities/findDeprecatedUsages.js.flow @@ -0,0 +1,68 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { GraphQLError } from '../error/GraphQLError'; +import { visit, visitWithTypeInfo } from '../language/visitor'; +import type { DocumentNode } from '../language/ast'; +import { getNamedType } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; +import { TypeInfo } from './TypeInfo'; + +/** + * A validation rule which reports deprecated usages. + * + * Returns a list of GraphQLError instances describing each deprecated use. + */ +export function findDeprecatedUsages( + schema: GraphQLSchema, + ast: DocumentNode, +): Array { + const errors = []; + const typeInfo = new TypeInfo(schema); + + visit( + ast, + visitWithTypeInfo(typeInfo, { + Field(node) { + const fieldDef = typeInfo.getFieldDef(); + if (fieldDef && fieldDef.isDeprecated) { + const parentType = typeInfo.getParentType(); + if (parentType) { + const reason = fieldDef.deprecationReason; + errors.push( + new GraphQLError( + `The field ${parentType.name}.${fieldDef.name} is deprecated.` + + (reason ? ' ' + reason : ''), + [node], + ), + ); + } + } + }, + EnumValue(node) { + const enumVal = typeInfo.getEnumValue(); + if (enumVal && enumVal.isDeprecated) { + const type = getNamedType(typeInfo.getInputType()); + if (type) { + const reason = enumVal.deprecationReason; + errors.push( + new GraphQLError( + `The enum value ${type.name}.${enumVal.name} is deprecated.` + + (reason ? ' ' + reason : ''), + [node], + ), + ); + } + } + }, + }), + ); + + return errors; +} diff --git a/node_modules/graphql/utilities/findDeprecatedUsages.mjs b/node_modules/graphql/utilities/findDeprecatedUsages.mjs new file mode 100644 index 0000000..9330d0d --- /dev/null +++ b/node_modules/graphql/utilities/findDeprecatedUsages.mjs @@ -0,0 +1,49 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../error/GraphQLError'; +import { visit, visitWithTypeInfo } from '../language/visitor'; +import { getNamedType } from '../type/definition'; +import { TypeInfo } from './TypeInfo'; +/** + * A validation rule which reports deprecated usages. + * + * Returns a list of GraphQLError instances describing each deprecated use. + */ + +export function findDeprecatedUsages(schema, ast) { + var errors = []; + var typeInfo = new TypeInfo(schema); + visit(ast, visitWithTypeInfo(typeInfo, { + Field: function Field(node) { + var fieldDef = typeInfo.getFieldDef(); + + if (fieldDef && fieldDef.isDeprecated) { + var parentType = typeInfo.getParentType(); + + if (parentType) { + var reason = fieldDef.deprecationReason; + errors.push(new GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node])); + } + } + }, + EnumValue: function EnumValue(node) { + var enumVal = typeInfo.getEnumValue(); + + if (enumVal && enumVal.isDeprecated) { + var type = getNamedType(typeInfo.getInputType()); + + if (type) { + var reason = enumVal.deprecationReason; + errors.push(new GraphQLError("The enum value ".concat(type.name, ".").concat(enumVal.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node])); + } + } + } + })); + return errors; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/getOperationAST.js b/node_modules/graphql/utilities/getOperationAST.js new file mode 100644 index 0000000..c3f1c49 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationAST.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getOperationAST = getOperationAST; + +var _kinds = require("../language/kinds"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ +function getOperationAST(documentAST, operationName) { + var operation = null; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var definition = documentAST.definitions[i]; + + if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) { + if (!operationName) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; + } + + operation = definition; + } else if (definition.name && definition.name.value === operationName) { + return definition; + } + } + } + + return operation; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/getOperationAST.js.flow b/node_modules/graphql/utilities/getOperationAST.js.flow new file mode 100644 index 0000000..b4e491a --- /dev/null +++ b/node_modules/graphql/utilities/getOperationAST.js.flow @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { Kind } from '../language/kinds'; +import type { DocumentNode, OperationDefinitionNode } from '../language/ast'; + +/** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ +export function getOperationAST( + documentAST: DocumentNode, + operationName: ?string, +): ?OperationDefinitionNode { + let operation = null; + for (let i = 0; i < documentAST.definitions.length; i++) { + const definition = documentAST.definitions[i]; + if (definition.kind === Kind.OPERATION_DEFINITION) { + if (!operationName) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; + } + operation = definition; + } else if (definition.name && definition.name.value === operationName) { + return definition; + } + } + } + return operation; +} diff --git a/node_modules/graphql/utilities/getOperationAST.mjs b/node_modules/graphql/utilities/getOperationAST.mjs new file mode 100644 index 0000000..d26da10 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationAST.mjs @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { Kind } from '../language/kinds'; + +/** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ +export function getOperationAST(documentAST, operationName) { + var operation = null; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var definition = documentAST.definitions[i]; + + if (definition.kind === Kind.OPERATION_DEFINITION) { + if (!operationName) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; + } + + operation = definition; + } else if (definition.name && definition.name.value === operationName) { + return definition; + } + } + } + + return operation; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/getOperationRootType.js b/node_modules/graphql/utilities/getOperationRootType.js new file mode 100644 index 0000000..dc37be7 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationRootType.js @@ -0,0 +1,54 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getOperationRootType = getOperationRootType; + +var _GraphQLError = require("../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Extracts the root type of the operation from the schema. + */ +function getOperationRootType(schema, operation) { + switch (operation.operation) { + case 'query': + var queryType = schema.getQueryType(); + + if (!queryType) { + throw new _GraphQLError.GraphQLError('Schema does not define the required query root type.', [operation]); + } + + return queryType; + + case 'mutation': + var mutationType = schema.getMutationType(); + + if (!mutationType) { + throw new _GraphQLError.GraphQLError('Schema is not configured for mutations.', [operation]); + } + + return mutationType; + + case 'subscription': + var subscriptionType = schema.getSubscriptionType(); + + if (!subscriptionType) { + throw new _GraphQLError.GraphQLError('Schema is not configured for subscriptions.', [operation]); + } + + return subscriptionType; + + default: + throw new _GraphQLError.GraphQLError('Can only have query, mutation and subscription operations.', [operation]); + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/getOperationRootType.js.flow b/node_modules/graphql/utilities/getOperationRootType.js.flow new file mode 100644 index 0000000..ddc6e99 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationRootType.js.flow @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { GraphQLError } from '../error/GraphQLError'; +import type { + OperationDefinitionNode, + OperationTypeDefinitionNode, +} from '../language/ast'; +import type { GraphQLSchema } from '../type/schema'; +import type { GraphQLObjectType } from '../type/definition'; + +/** + * Extracts the root type of the operation from the schema. + */ +export function getOperationRootType( + schema: GraphQLSchema, + operation: OperationDefinitionNode | OperationTypeDefinitionNode, +): GraphQLObjectType { + switch (operation.operation) { + case 'query': + const queryType = schema.getQueryType(); + if (!queryType) { + throw new GraphQLError( + 'Schema does not define the required query root type.', + [operation], + ); + } + return queryType; + case 'mutation': + const mutationType = schema.getMutationType(); + if (!mutationType) { + throw new GraphQLError('Schema is not configured for mutations.', [ + operation, + ]); + } + return mutationType; + case 'subscription': + const subscriptionType = schema.getSubscriptionType(); + if (!subscriptionType) { + throw new GraphQLError('Schema is not configured for subscriptions.', [ + operation, + ]); + } + return subscriptionType; + default: + throw new GraphQLError( + 'Can only have query, mutation and subscription operations.', + [operation], + ); + } +} diff --git a/node_modules/graphql/utilities/getOperationRootType.mjs b/node_modules/graphql/utilities/getOperationRootType.mjs new file mode 100644 index 0000000..69a9fe3 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationRootType.mjs @@ -0,0 +1,46 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../error/GraphQLError'; + +/** + * Extracts the root type of the operation from the schema. + */ +export function getOperationRootType(schema, operation) { + switch (operation.operation) { + case 'query': + var queryType = schema.getQueryType(); + + if (!queryType) { + throw new GraphQLError('Schema does not define the required query root type.', [operation]); + } + + return queryType; + + case 'mutation': + var mutationType = schema.getMutationType(); + + if (!mutationType) { + throw new GraphQLError('Schema is not configured for mutations.', [operation]); + } + + return mutationType; + + case 'subscription': + var subscriptionType = schema.getSubscriptionType(); + + if (!subscriptionType) { + throw new GraphQLError('Schema is not configured for subscriptions.', [operation]); + } + + return subscriptionType; + + default: + throw new GraphQLError('Can only have query, mutation and subscription operations.', [operation]); + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/index.js b/node_modules/graphql/utilities/index.js new file mode 100644 index 0000000..938e66e --- /dev/null +++ b/node_modules/graphql/utilities/index.js @@ -0,0 +1,255 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getIntrospectionQuery", { + enumerable: true, + get: function get() { + return _introspectionQuery.getIntrospectionQuery; + } +}); +Object.defineProperty(exports, "introspectionQuery", { + enumerable: true, + get: function get() { + return _introspectionQuery.introspectionQuery; + } +}); +Object.defineProperty(exports, "getOperationAST", { + enumerable: true, + get: function get() { + return _getOperationAST.getOperationAST; + } +}); +Object.defineProperty(exports, "getOperationRootType", { + enumerable: true, + get: function get() { + return _getOperationRootType.getOperationRootType; + } +}); +Object.defineProperty(exports, "introspectionFromSchema", { + enumerable: true, + get: function get() { + return _introspectionFromSchema.introspectionFromSchema; + } +}); +Object.defineProperty(exports, "buildClientSchema", { + enumerable: true, + get: function get() { + return _buildClientSchema.buildClientSchema; + } +}); +Object.defineProperty(exports, "buildASTSchema", { + enumerable: true, + get: function get() { + return _buildASTSchema.buildASTSchema; + } +}); +Object.defineProperty(exports, "buildSchema", { + enumerable: true, + get: function get() { + return _buildASTSchema.buildSchema; + } +}); +Object.defineProperty(exports, "getDescription", { + enumerable: true, + get: function get() { + return _buildASTSchema.getDescription; + } +}); +Object.defineProperty(exports, "extendSchema", { + enumerable: true, + get: function get() { + return _extendSchema.extendSchema; + } +}); +Object.defineProperty(exports, "lexicographicSortSchema", { + enumerable: true, + get: function get() { + return _lexicographicSortSchema.lexicographicSortSchema; + } +}); +Object.defineProperty(exports, "printSchema", { + enumerable: true, + get: function get() { + return _schemaPrinter.printSchema; + } +}); +Object.defineProperty(exports, "printType", { + enumerable: true, + get: function get() { + return _schemaPrinter.printType; + } +}); +Object.defineProperty(exports, "printIntrospectionSchema", { + enumerable: true, + get: function get() { + return _schemaPrinter.printIntrospectionSchema; + } +}); +Object.defineProperty(exports, "typeFromAST", { + enumerable: true, + get: function get() { + return _typeFromAST.typeFromAST; + } +}); +Object.defineProperty(exports, "valueFromAST", { + enumerable: true, + get: function get() { + return _valueFromAST.valueFromAST; + } +}); +Object.defineProperty(exports, "valueFromASTUntyped", { + enumerable: true, + get: function get() { + return _valueFromASTUntyped.valueFromASTUntyped; + } +}); +Object.defineProperty(exports, "astFromValue", { + enumerable: true, + get: function get() { + return _astFromValue.astFromValue; + } +}); +Object.defineProperty(exports, "TypeInfo", { + enumerable: true, + get: function get() { + return _TypeInfo.TypeInfo; + } +}); +Object.defineProperty(exports, "coerceValue", { + enumerable: true, + get: function get() { + return _coerceValue.coerceValue; + } +}); +Object.defineProperty(exports, "isValidJSValue", { + enumerable: true, + get: function get() { + return _isValidJSValue.isValidJSValue; + } +}); +Object.defineProperty(exports, "isValidLiteralValue", { + enumerable: true, + get: function get() { + return _isValidLiteralValue.isValidLiteralValue; + } +}); +Object.defineProperty(exports, "concatAST", { + enumerable: true, + get: function get() { + return _concatAST.concatAST; + } +}); +Object.defineProperty(exports, "separateOperations", { + enumerable: true, + get: function get() { + return _separateOperations.separateOperations; + } +}); +Object.defineProperty(exports, "isEqualType", { + enumerable: true, + get: function get() { + return _typeComparators.isEqualType; + } +}); +Object.defineProperty(exports, "isTypeSubTypeOf", { + enumerable: true, + get: function get() { + return _typeComparators.isTypeSubTypeOf; + } +}); +Object.defineProperty(exports, "doTypesOverlap", { + enumerable: true, + get: function get() { + return _typeComparators.doTypesOverlap; + } +}); +Object.defineProperty(exports, "assertValidName", { + enumerable: true, + get: function get() { + return _assertValidName.assertValidName; + } +}); +Object.defineProperty(exports, "isValidNameError", { + enumerable: true, + get: function get() { + return _assertValidName.isValidNameError; + } +}); +Object.defineProperty(exports, "BreakingChangeType", { + enumerable: true, + get: function get() { + return _findBreakingChanges.BreakingChangeType; + } +}); +Object.defineProperty(exports, "DangerousChangeType", { + enumerable: true, + get: function get() { + return _findBreakingChanges.DangerousChangeType; + } +}); +Object.defineProperty(exports, "findBreakingChanges", { + enumerable: true, + get: function get() { + return _findBreakingChanges.findBreakingChanges; + } +}); +Object.defineProperty(exports, "findDangerousChanges", { + enumerable: true, + get: function get() { + return _findBreakingChanges.findDangerousChanges; + } +}); +Object.defineProperty(exports, "findDeprecatedUsages", { + enumerable: true, + get: function get() { + return _findDeprecatedUsages.findDeprecatedUsages; + } +}); + +var _introspectionQuery = require("./introspectionQuery"); + +var _getOperationAST = require("./getOperationAST"); + +var _getOperationRootType = require("./getOperationRootType"); + +var _introspectionFromSchema = require("./introspectionFromSchema"); + +var _buildClientSchema = require("./buildClientSchema"); + +var _buildASTSchema = require("./buildASTSchema"); + +var _extendSchema = require("./extendSchema"); + +var _lexicographicSortSchema = require("./lexicographicSortSchema"); + +var _schemaPrinter = require("./schemaPrinter"); + +var _typeFromAST = require("./typeFromAST"); + +var _valueFromAST = require("./valueFromAST"); + +var _valueFromASTUntyped = require("./valueFromASTUntyped"); + +var _astFromValue = require("./astFromValue"); + +var _TypeInfo = require("./TypeInfo"); + +var _coerceValue = require("./coerceValue"); + +var _isValidJSValue = require("./isValidJSValue"); + +var _isValidLiteralValue = require("./isValidLiteralValue"); + +var _concatAST = require("./concatAST"); + +var _separateOperations = require("./separateOperations"); + +var _typeComparators = require("./typeComparators"); + +var _assertValidName = require("./assertValidName"); + +var _findBreakingChanges = require("./findBreakingChanges"); + +var _findDeprecatedUsages = require("./findDeprecatedUsages"); \ No newline at end of file diff --git a/node_modules/graphql/utilities/index.js.flow b/node_modules/graphql/utilities/index.js.flow new file mode 100644 index 0000000..cf14c71 --- /dev/null +++ b/node_modules/graphql/utilities/index.js.flow @@ -0,0 +1,127 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +// The GraphQL query recommended for a full schema introspection. +export { + getIntrospectionQuery, + // @deprecated, use getIntrospectionQuery() - will be removed in v15 + introspectionQuery, +} from './introspectionQuery'; +export type { + IntrospectionOptions, + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionInputType, + IntrospectionOutputType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionInputTypeRef, + IntrospectionOutputTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, +} from './introspectionQuery'; + +// Gets the target Operation from a Document +export { getOperationAST } from './getOperationAST'; + +// Gets the Type for the target Operation AST. +export { getOperationRootType } from './getOperationRootType'; + +// Convert a GraphQLSchema to an IntrospectionQuery +export { introspectionFromSchema } from './introspectionFromSchema'; + +// Build a GraphQLSchema from an introspection result. +export { buildClientSchema } from './buildClientSchema'; + +// Build a GraphQLSchema from GraphQL Schema language. +export { + buildASTSchema, + buildSchema, + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16 + getDescription, +} from './buildASTSchema'; +export type { BuildSchemaOptions } from './buildASTSchema'; + +// Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. +export { extendSchema } from './extendSchema'; + +// Sort a GraphQLSchema. +export { lexicographicSortSchema } from './lexicographicSortSchema'; + +// Print a GraphQLSchema to GraphQL Schema language. +export { + printSchema, + printType, + printIntrospectionSchema, +} from './schemaPrinter'; + +// Create a GraphQLType from a GraphQL language AST. +export { typeFromAST } from './typeFromAST'; + +// Create a JavaScript value from a GraphQL language AST with a type. +export { valueFromAST } from './valueFromAST'; + +// Create a JavaScript value from a GraphQL language AST without a type. +export { valueFromASTUntyped } from './valueFromASTUntyped'; + +// Create a GraphQL language AST from a JavaScript value. +export { astFromValue } from './astFromValue'; + +// A helper to use within recursive-descent visitors which need to be aware of +// the GraphQL type system. +export { TypeInfo } from './TypeInfo'; + +// Coerces a JavaScript value to a GraphQL type, or produces errors. +export { coerceValue } from './coerceValue'; + +// @deprecated use coerceValue - will be removed in v15 +export { isValidJSValue } from './isValidJSValue'; + +// @deprecated use validation - will be removed in v15 +export { isValidLiteralValue } from './isValidLiteralValue'; + +// Concatenates multiple AST together. +export { concatAST } from './concatAST'; + +// Separates an AST into an AST per Operation. +export { separateOperations } from './separateOperations'; + +// Comparators for types +export { + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, +} from './typeComparators'; + +// Asserts that a string is a valid GraphQL name +export { assertValidName, isValidNameError } from './assertValidName'; + +// Compares two GraphQLSchemas and detects breaking changes. +export { + BreakingChangeType, + DangerousChangeType, + findBreakingChanges, + findDangerousChanges, +} from './findBreakingChanges'; +export type { BreakingChange, DangerousChange } from './findBreakingChanges'; + +// Report all deprecated usage within a GraphQL document. +export { findDeprecatedUsages } from './findDeprecatedUsages'; diff --git a/node_modules/graphql/utilities/index.mjs b/node_modules/graphql/utilities/index.mjs new file mode 100644 index 0000000..4ba9733 --- /dev/null +++ b/node_modules/graphql/utilities/index.mjs @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +// The GraphQL query recommended for a full schema introspection. +export { getIntrospectionQuery, // @deprecated, use getIntrospectionQuery() - will be removed in v15 +introspectionQuery } from './introspectionQuery'; +// Gets the target Operation from a Document +export { getOperationAST } from './getOperationAST'; // Gets the Type for the target Operation AST. + +export { getOperationRootType } from './getOperationRootType'; // Convert a GraphQLSchema to an IntrospectionQuery + +export { introspectionFromSchema } from './introspectionFromSchema'; // Build a GraphQLSchema from an introspection result. + +export { buildClientSchema } from './buildClientSchema'; // Build a GraphQLSchema from GraphQL Schema language. + +export { buildASTSchema, buildSchema, // @deprecated: Get the description from a schema AST node and supports legacy +// syntax for specifying descriptions - will be removed in v16 +getDescription } from './buildASTSchema'; +// Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. +export { extendSchema } from './extendSchema'; // Sort a GraphQLSchema. + +export { lexicographicSortSchema } from './lexicographicSortSchema'; // Print a GraphQLSchema to GraphQL Schema language. + +export { printSchema, printType, printIntrospectionSchema } from './schemaPrinter'; // Create a GraphQLType from a GraphQL language AST. + +export { typeFromAST } from './typeFromAST'; // Create a JavaScript value from a GraphQL language AST with a type. + +export { valueFromAST } from './valueFromAST'; // Create a JavaScript value from a GraphQL language AST without a type. + +export { valueFromASTUntyped } from './valueFromASTUntyped'; // Create a GraphQL language AST from a JavaScript value. + +export { astFromValue } from './astFromValue'; // A helper to use within recursive-descent visitors which need to be aware of +// the GraphQL type system. + +export { TypeInfo } from './TypeInfo'; // Coerces a JavaScript value to a GraphQL type, or produces errors. + +export { coerceValue } from './coerceValue'; // @deprecated use coerceValue - will be removed in v15 + +export { isValidJSValue } from './isValidJSValue'; // @deprecated use validation - will be removed in v15 + +export { isValidLiteralValue } from './isValidLiteralValue'; // Concatenates multiple AST together. + +export { concatAST } from './concatAST'; // Separates an AST into an AST per Operation. + +export { separateOperations } from './separateOperations'; // Comparators for types + +export { isEqualType, isTypeSubTypeOf, doTypesOverlap } from './typeComparators'; // Asserts that a string is a valid GraphQL name + +export { assertValidName, isValidNameError } from './assertValidName'; // Compares two GraphQLSchemas and detects breaking changes. + +export { BreakingChangeType, DangerousChangeType, findBreakingChanges, findDangerousChanges } from './findBreakingChanges'; +// Report all deprecated usage within a GraphQL document. +export { findDeprecatedUsages } from './findDeprecatedUsages'; \ No newline at end of file diff --git a/node_modules/graphql/utilities/introspectionFromSchema.js b/node_modules/graphql/utilities/introspectionFromSchema.js new file mode 100644 index 0000000..5d8fd69 --- /dev/null +++ b/node_modules/graphql/utilities/introspectionFromSchema.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.introspectionFromSchema = introspectionFromSchema; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _introspectionQuery = require("./introspectionQuery"); + +var _execute = require("../execution/execute"); + +var _parser = require("../language/parser"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + */ +function introspectionFromSchema(schema, options) { + var queryAST = (0, _parser.parse)((0, _introspectionQuery.getIntrospectionQuery)(options)); + var result = (0, _execute.execute)(schema, queryAST); + !(!result.then && !result.errors && result.data) ? (0, _invariant.default)(0) : void 0; + return result.data; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/introspectionFromSchema.js.flow b/node_modules/graphql/utilities/introspectionFromSchema.js.flow new file mode 100644 index 0000000..c2690b6 --- /dev/null +++ b/node_modules/graphql/utilities/introspectionFromSchema.js.flow @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import { getIntrospectionQuery } from './introspectionQuery'; +import type { GraphQLSchema } from '../type/schema'; +import { execute } from '../execution/execute'; +import { parse } from '../language/parser'; +import type { + IntrospectionQuery, + IntrospectionOptions, +} from './introspectionQuery'; + +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + */ +export function introspectionFromSchema( + schema: GraphQLSchema, + options?: IntrospectionOptions, +): IntrospectionQuery { + const queryAST = parse(getIntrospectionQuery(options)); + const result = execute(schema, queryAST); + invariant(!result.then && !result.errors && result.data); + return (result.data: any); +} diff --git a/node_modules/graphql/utilities/introspectionFromSchema.mjs b/node_modules/graphql/utilities/introspectionFromSchema.mjs new file mode 100644 index 0000000..88a0bff --- /dev/null +++ b/node_modules/graphql/utilities/introspectionFromSchema.mjs @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; +import { getIntrospectionQuery } from './introspectionQuery'; +import { execute } from '../execution/execute'; +import { parse } from '../language/parser'; + +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + */ +export function introspectionFromSchema(schema, options) { + var queryAST = parse(getIntrospectionQuery(options)); + var result = execute(schema, queryAST); + !(!result.then && !result.errors && result.data) ? invariant(0) : void 0; + return result.data; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/introspectionQuery.js b/node_modules/graphql/utilities/introspectionQuery.js new file mode 100644 index 0000000..b0179d3 --- /dev/null +++ b/node_modules/graphql/utilities/introspectionQuery.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getIntrospectionQuery = getIntrospectionQuery; +exports.introspectionQuery = void 0; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function getIntrospectionQuery(options) { + var descriptions = !(options && options.descriptions === false); + return "\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ".concat(descriptions ? 'description' : '', "\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions ? 'description' : '', "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions ? 'description' : '', "\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n "); +} +/** + * Deprecated, call getIntrospectionQuery directly. + * + * This function will be removed in v15 + */ + + +var introspectionQuery = getIntrospectionQuery(); +exports.introspectionQuery = introspectionQuery; \ No newline at end of file diff --git a/node_modules/graphql/utilities/introspectionQuery.js.flow b/node_modules/graphql/utilities/introspectionQuery.js.flow new file mode 100644 index 0000000..b6ebe58 --- /dev/null +++ b/node_modules/graphql/utilities/introspectionQuery.js.flow @@ -0,0 +1,276 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { DirectiveLocationEnum } from '../language/directiveLocation'; + +export type IntrospectionOptions = {| + // Whether to include descriptions in the introspection result. + // Default: true + descriptions: boolean, +|}; + +export function getIntrospectionQuery(options?: IntrospectionOptions): string { + const descriptions = !(options && options.descriptions === false); + return ` + query IntrospectionQuery { + __schema { + queryType { name } + mutationType { name } + subscriptionType { name } + types { + ...FullType + } + directives { + name + ${descriptions ? 'description' : ''} + locations + args { + ...InputValue + } + } + } + } + + fragment FullType on __Type { + kind + name + ${descriptions ? 'description' : ''} + fields(includeDeprecated: true) { + name + ${descriptions ? 'description' : ''} + args { + ...InputValue + } + type { + ...TypeRef + } + isDeprecated + deprecationReason + } + inputFields { + ...InputValue + } + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + ${descriptions ? 'description' : ''} + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef + } + } + + fragment InputValue on __InputValue { + name + ${descriptions ? 'description' : ''} + type { ...TypeRef } + defaultValue + } + + fragment TypeRef on __Type { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + } + } + } + } + } + } + } + } + `; +} + +/** + * Deprecated, call getIntrospectionQuery directly. + * + * This function will be removed in v15 + */ +export const introspectionQuery = getIntrospectionQuery(); + +export type IntrospectionQuery = {| + +__schema: IntrospectionSchema, +|}; + +export type IntrospectionSchema = {| + +queryType: IntrospectionNamedTypeRef, + +mutationType: ?IntrospectionNamedTypeRef, + +subscriptionType: ?IntrospectionNamedTypeRef, + +types: $ReadOnlyArray, + +directives: $ReadOnlyArray, +|}; + +export type IntrospectionType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType + | IntrospectionInputObjectType; + +export type IntrospectionOutputType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType; + +export type IntrospectionInputType = + | IntrospectionScalarType + | IntrospectionEnumType + | IntrospectionInputObjectType; + +export type IntrospectionScalarType = { + +kind: 'SCALAR', + +name: string, + +description?: ?string, +}; + +export type IntrospectionObjectType = { + +kind: 'OBJECT', + +name: string, + +description?: ?string, + +fields: $ReadOnlyArray, + +interfaces: $ReadOnlyArray< + IntrospectionNamedTypeRef, + >, +}; + +export type IntrospectionInterfaceType = { + +kind: 'INTERFACE', + +name: string, + +description?: ?string, + +fields: $ReadOnlyArray, + +possibleTypes: $ReadOnlyArray< + IntrospectionNamedTypeRef, + >, +}; + +export type IntrospectionUnionType = { + +kind: 'UNION', + +name: string, + +description?: ?string, + +possibleTypes: $ReadOnlyArray< + IntrospectionNamedTypeRef, + >, +}; + +export type IntrospectionEnumType = { + +kind: 'ENUM', + +name: string, + +description?: ?string, + +enumValues: $ReadOnlyArray, +}; + +export type IntrospectionInputObjectType = { + +kind: 'INPUT_OBJECT', + +name: string, + +description?: ?string, + +inputFields: $ReadOnlyArray, +}; + +export type IntrospectionListTypeRef< + T: IntrospectionTypeRef = IntrospectionTypeRef, +> = { + +kind: 'LIST', + +ofType: T, +}; + +export type IntrospectionNonNullTypeRef< + T: IntrospectionTypeRef = IntrospectionTypeRef, +> = { + +kind: 'NON_NULL', + +ofType: T, +}; + +export type IntrospectionTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef, + >; + +export type IntrospectionOutputTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef, + >; + +export type IntrospectionInputTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef, + >; + +export type IntrospectionNamedTypeRef< + T: IntrospectionType = IntrospectionType, +> = { + +kind: $PropertyType, + +name: string, +}; + +export type IntrospectionField = {| + +name: string, + +description?: ?string, + +args: $ReadOnlyArray, + +type: IntrospectionOutputTypeRef, + +isDeprecated: boolean, + +deprecationReason: ?string, +|}; + +export type IntrospectionInputValue = {| + +name: string, + +description?: ?string, + +type: IntrospectionInputTypeRef, + +defaultValue: ?string, +|}; + +export type IntrospectionEnumValue = {| + +name: string, + +description?: ?string, + +isDeprecated: boolean, + +deprecationReason: ?string, +|}; + +export type IntrospectionDirective = {| + +name: string, + +description?: ?string, + +locations: $ReadOnlyArray, + +args: $ReadOnlyArray, +|}; diff --git a/node_modules/graphql/utilities/introspectionQuery.mjs b/node_modules/graphql/utilities/introspectionQuery.mjs new file mode 100644 index 0000000..8eec21d --- /dev/null +++ b/node_modules/graphql/utilities/introspectionQuery.mjs @@ -0,0 +1,19 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export function getIntrospectionQuery(options) { + var descriptions = !(options && options.descriptions === false); + return "\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ".concat(descriptions ? 'description' : '', "\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions ? 'description' : '', "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions ? 'description' : '', "\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n "); +} +/** + * Deprecated, call getIntrospectionQuery directly. + * + * This function will be removed in v15 + */ + +export var introspectionQuery = getIntrospectionQuery(); \ No newline at end of file diff --git a/node_modules/graphql/utilities/isValidJSValue.js b/node_modules/graphql/utilities/isValidJSValue.js new file mode 100644 index 0000000..d1fa12f --- /dev/null +++ b/node_modules/graphql/utilities/isValidJSValue.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isValidJSValue = isValidJSValue; + +var _coerceValue = require("./coerceValue"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Deprecated. Use coerceValue() directly for richer information. + * + * This function will be removed in v15 + */ +function isValidJSValue(value, type) { + var errors = (0, _coerceValue.coerceValue)(value, type).errors; + return errors ? errors.map(function (error) { + return error.message; + }) : []; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/isValidJSValue.js.flow b/node_modules/graphql/utilities/isValidJSValue.js.flow new file mode 100644 index 0000000..815476b --- /dev/null +++ b/node_modules/graphql/utilities/isValidJSValue.js.flow @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { coerceValue } from './coerceValue'; +import type { GraphQLInputType } from '../type/definition'; + +/** + * Deprecated. Use coerceValue() directly for richer information. + * + * This function will be removed in v15 + */ +export function isValidJSValue( + value: mixed, + type: GraphQLInputType, +): Array { + const errors = coerceValue(value, type).errors; + return errors ? errors.map(error => error.message) : []; +} diff --git a/node_modules/graphql/utilities/isValidJSValue.mjs b/node_modules/graphql/utilities/isValidJSValue.mjs new file mode 100644 index 0000000..59c38fa --- /dev/null +++ b/node_modules/graphql/utilities/isValidJSValue.mjs @@ -0,0 +1,21 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { coerceValue } from './coerceValue'; + +/** + * Deprecated. Use coerceValue() directly for richer information. + * + * This function will be removed in v15 + */ +export function isValidJSValue(value, type) { + var errors = coerceValue(value, type).errors; + return errors ? errors.map(function (error) { + return error.message; + }) : []; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/isValidLiteralValue.js b/node_modules/graphql/utilities/isValidLiteralValue.js new file mode 100644 index 0000000..c518c0e --- /dev/null +++ b/node_modules/graphql/utilities/isValidLiteralValue.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isValidLiteralValue = isValidLiteralValue; + +var _TypeInfo = require("./TypeInfo"); + +var _kinds = require("../language/kinds"); + +var _visitor = require("../language/visitor"); + +var _schema = require("../type/schema"); + +var _ValuesOfCorrectType = require("../validation/rules/ValuesOfCorrectType"); + +var _ValidationContext = require("../validation/ValidationContext"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Utility which determines if a value literal node is valid for an input type. + * + * Deprecated. Rely on validation for documents containing literal values. + * + * This function will be removed in v15 + */ +function isValidLiteralValue(type, valueNode) { + var emptySchema = new _schema.GraphQLSchema({}); + var emptyDoc = { + kind: _kinds.Kind.DOCUMENT, + definitions: [] + }; + var typeInfo = new _TypeInfo.TypeInfo(emptySchema, undefined, type); + var context = new _ValidationContext.ValidationContext(emptySchema, emptyDoc, typeInfo); + var visitor = (0, _ValuesOfCorrectType.ValuesOfCorrectType)(context); + (0, _visitor.visit)(valueNode, (0, _visitor.visitWithTypeInfo)(typeInfo, visitor)); + return context.getErrors(); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/isValidLiteralValue.js.flow b/node_modules/graphql/utilities/isValidLiteralValue.js.flow new file mode 100644 index 0000000..1b7806c --- /dev/null +++ b/node_modules/graphql/utilities/isValidLiteralValue.js.flow @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { TypeInfo } from './TypeInfo'; +import type { GraphQLError } from '../error/GraphQLError'; +import type { ValueNode } from '../language/ast'; +import { Kind } from '../language/kinds'; +import { visit, visitWithTypeInfo } from '../language/visitor'; +import type { GraphQLInputType } from '../type/definition'; +import { GraphQLSchema } from '../type/schema'; +import { ValuesOfCorrectType } from '../validation/rules/ValuesOfCorrectType'; +import { ValidationContext } from '../validation/ValidationContext'; + +/** + * Utility which determines if a value literal node is valid for an input type. + * + * Deprecated. Rely on validation for documents containing literal values. + * + * This function will be removed in v15 + */ +export function isValidLiteralValue( + type: GraphQLInputType, + valueNode: ValueNode, +): $ReadOnlyArray { + const emptySchema = new GraphQLSchema({}); + const emptyDoc = { kind: Kind.DOCUMENT, definitions: [] }; + const typeInfo = new TypeInfo(emptySchema, undefined, type); + const context = new ValidationContext(emptySchema, emptyDoc, typeInfo); + const visitor = ValuesOfCorrectType(context); + visit(valueNode, visitWithTypeInfo(typeInfo, visitor)); + return context.getErrors(); +} diff --git a/node_modules/graphql/utilities/isValidLiteralValue.mjs b/node_modules/graphql/utilities/isValidLiteralValue.mjs new file mode 100644 index 0000000..103c20c --- /dev/null +++ b/node_modules/graphql/utilities/isValidLiteralValue.mjs @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { TypeInfo } from './TypeInfo'; +import { Kind } from '../language/kinds'; +import { visit, visitWithTypeInfo } from '../language/visitor'; +import { GraphQLSchema } from '../type/schema'; +import { ValuesOfCorrectType } from '../validation/rules/ValuesOfCorrectType'; +import { ValidationContext } from '../validation/ValidationContext'; +/** + * Utility which determines if a value literal node is valid for an input type. + * + * Deprecated. Rely on validation for documents containing literal values. + * + * This function will be removed in v15 + */ + +export function isValidLiteralValue(type, valueNode) { + var emptySchema = new GraphQLSchema({}); + var emptyDoc = { + kind: Kind.DOCUMENT, + definitions: [] + }; + var typeInfo = new TypeInfo(emptySchema, undefined, type); + var context = new ValidationContext(emptySchema, emptyDoc, typeInfo); + var visitor = ValuesOfCorrectType(context); + visit(valueNode, visitWithTypeInfo(typeInfo, visitor)); + return context.getErrors(); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/lexicographicSortSchema.js b/node_modules/graphql/utilities/lexicographicSortSchema.js new file mode 100644 index 0000000..09f56d7 --- /dev/null +++ b/node_modules/graphql/utilities/lexicographicSortSchema.js @@ -0,0 +1,219 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.lexicographicSortSchema = lexicographicSortSchema; + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _schema = require("../type/schema"); + +var _directives = require("../type/directives"); + +var _definition = require("../type/definition"); + +var _scalars = require("../type/scalars"); + +var _introspection = require("../type/introspection"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Sort GraphQLSchema. + */ +function lexicographicSortSchema(schema) { + var cache = Object.create(null); + + var sortMaybeType = function sortMaybeType(maybeType) { + return maybeType && sortNamedType(maybeType); + }; + + return new _schema.GraphQLSchema({ + types: sortTypes((0, _objectValues.default)(schema.getTypeMap())), + directives: sortByName(schema.getDirectives()).map(sortDirective), + query: sortMaybeType(schema.getQueryType()), + mutation: sortMaybeType(schema.getMutationType()), + subscription: sortMaybeType(schema.getSubscriptionType()), + astNode: schema.astNode + }); + + function sortDirective(directive) { + return new _directives.GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: sortBy(directive.locations, function (x) { + return x; + }), + args: sortArgs(directive.args), + astNode: directive.astNode + }); + } + + function sortArgs(args) { + return (0, _keyValMap.default)(sortByName(args), function (arg) { + return arg.name; + }, function (arg) { + return _objectSpread({}, arg, { + type: sortType(arg.type) + }); + }); + } + + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return { + type: sortType(field.type), + args: sortArgs(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + description: field.description, + astNode: field.astNode + }; + }); + } + + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return { + type: sortType(field.type), + defaultValue: field.defaultValue, + description: field.description, + astNode: field.astNode + }; + }); + } + + function sortType(type) { + if ((0, _definition.isListType)(type)) { + return new _definition.GraphQLList(sortType(type.ofType)); + } else if ((0, _definition.isNonNullType)(type)) { + return new _definition.GraphQLNonNull(sortType(type.ofType)); + } + + return sortNamedType(type); + } + + function sortTypes(arr) { + return sortByName(arr).map(sortNamedType); + } + + function sortNamedType(type) { + if ((0, _scalars.isSpecifiedScalarType)(type) || (0, _introspection.isIntrospectionType)(type)) { + return type; + } + + var sortedType = cache[type.name]; + + if (!sortedType) { + sortedType = sortNamedTypeImpl(type); + cache[type.name] = sortedType; + } + + return sortedType; + } + + function sortNamedTypeImpl(type) { + if ((0, _definition.isScalarType)(type)) { + return type; + } else if ((0, _definition.isObjectType)(type)) { + return new _definition.GraphQLObjectType({ + name: type.name, + interfaces: function interfaces() { + return sortTypes(type.getInterfaces()); + }, + fields: function fields() { + return sortFields(type.getFields()); + }, + isTypeOf: type.isTypeOf, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes + }); + } else if ((0, _definition.isInterfaceType)(type)) { + return new _definition.GraphQLInterfaceType({ + name: type.name, + fields: function fields() { + return sortFields(type.getFields()); + }, + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes + }); + } else if ((0, _definition.isUnionType)(type)) { + return new _definition.GraphQLUnionType({ + name: type.name, + types: function types() { + return sortTypes(type.getTypes()); + }, + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode + }); + } else if ((0, _definition.isEnumType)(type)) { + return new _definition.GraphQLEnumType({ + name: type.name, + values: (0, _keyValMap.default)(sortByName(type.getValues()), function (val) { + return val.name; + }, function (val) { + return { + value: val.value, + deprecationReason: val.deprecationReason, + description: val.description, + astNode: val.astNode + }; + }), + description: type.description, + astNode: type.astNode + }); + } else if ((0, _definition.isInputObjectType)(type)) { + return new _definition.GraphQLInputObjectType({ + name: type.name, + fields: function fields() { + return sortInputFields(type.getFields()); + }, + description: type.description, + astNode: type.astNode + }); + } + + throw new Error("Unknown type: \"".concat(type, "\"")); + } +} + +function sortObjMap(map, sortValueFn) { + var sortedMap = Object.create(null); + var sortedKeys = sortBy(Object.keys(map), function (x) { + return x; + }); + + for (var _i = 0; _i < sortedKeys.length; _i++) { + var key = sortedKeys[_i]; + var value = map[key]; + sortedMap[key] = sortValueFn ? sortValueFn(value) : value; + } + + return sortedMap; +} + +function sortByName(array) { + return sortBy(array, function (obj) { + return obj.name; + }); +} + +function sortBy(array, mapToKey) { + return array.slice().sort(function (obj1, obj2) { + var key1 = mapToKey(obj1); + var key2 = mapToKey(obj2); + return key1.localeCompare(key2); + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/lexicographicSortSchema.js.flow b/node_modules/graphql/utilities/lexicographicSortSchema.js.flow new file mode 100644 index 0000000..570d3e4 --- /dev/null +++ b/node_modules/graphql/utilities/lexicographicSortSchema.js.flow @@ -0,0 +1,198 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from '../jsutils/ObjMap'; +import keyValMap from '../jsutils/keyValMap'; +import objectValues from '../jsutils/objectValues'; +import { GraphQLSchema } from '../type/schema'; +import { GraphQLDirective } from '../type/directives'; +import type { GraphQLNamedType } from '../type/definition'; +import { + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, + isListType, + isNonNullType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, +} from '../type/definition'; +import { isSpecifiedScalarType } from '../type/scalars'; +import { isIntrospectionType } from '../type/introspection'; + +/** + * Sort GraphQLSchema. + */ +export function lexicographicSortSchema(schema: GraphQLSchema): GraphQLSchema { + const cache = Object.create(null); + + const sortMaybeType = maybeType => maybeType && sortNamedType(maybeType); + return new GraphQLSchema({ + types: sortTypes(objectValues(schema.getTypeMap())), + directives: sortByName(schema.getDirectives()).map(sortDirective), + query: sortMaybeType(schema.getQueryType()), + mutation: sortMaybeType(schema.getMutationType()), + subscription: sortMaybeType(schema.getSubscriptionType()), + astNode: schema.astNode, + }); + + function sortDirective(directive) { + return new GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: sortBy(directive.locations, x => x), + args: sortArgs(directive.args), + astNode: directive.astNode, + }); + } + + function sortArgs(args) { + return keyValMap( + sortByName(args), + arg => arg.name, + arg => ({ + ...arg, + type: sortType(arg.type), + }), + ); + } + + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, field => ({ + type: sortType(field.type), + args: sortArgs(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + description: field.description, + astNode: field.astNode, + })); + } + + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, field => ({ + type: sortType(field.type), + defaultValue: field.defaultValue, + description: field.description, + astNode: field.astNode, + })); + } + + function sortType(type) { + if (isListType(type)) { + return new GraphQLList(sortType(type.ofType)); + } else if (isNonNullType(type)) { + return new GraphQLNonNull(sortType(type.ofType)); + } + return sortNamedType(type); + } + + function sortTypes(arr: Array): Array { + return sortByName(arr).map(sortNamedType); + } + + function sortNamedType(type: T): T { + if (isSpecifiedScalarType(type) || isIntrospectionType(type)) { + return type; + } + + let sortedType = cache[type.name]; + if (!sortedType) { + sortedType = sortNamedTypeImpl(type); + cache[type.name] = sortedType; + } + return ((sortedType: any): T); + } + + function sortNamedTypeImpl(type) { + if (isScalarType(type)) { + return type; + } else if (isObjectType(type)) { + return new GraphQLObjectType({ + name: type.name, + interfaces: () => sortTypes(type.getInterfaces()), + fields: () => sortFields(type.getFields()), + isTypeOf: type.isTypeOf, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes, + }); + } else if (isInterfaceType(type)) { + return new GraphQLInterfaceType({ + name: type.name, + fields: () => sortFields(type.getFields()), + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes, + }); + } else if (isUnionType(type)) { + return new GraphQLUnionType({ + name: type.name, + types: () => sortTypes(type.getTypes()), + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode, + }); + } else if (isEnumType(type)) { + return new GraphQLEnumType({ + name: type.name, + values: keyValMap( + sortByName(type.getValues()), + val => val.name, + val => ({ + value: val.value, + deprecationReason: val.deprecationReason, + description: val.description, + astNode: val.astNode, + }), + ), + description: type.description, + astNode: type.astNode, + }); + } else if (isInputObjectType(type)) { + return new GraphQLInputObjectType({ + name: type.name, + fields: () => sortInputFields(type.getFields()), + description: type.description, + astNode: type.astNode, + }); + } + throw new Error(`Unknown type: "${type}"`); + } +} + +function sortObjMap(map: ObjMap, sortValueFn?: T => R): ObjMap { + const sortedMap = Object.create(null); + const sortedKeys = sortBy(Object.keys(map), x => x); + for (const key of sortedKeys) { + const value = map[key]; + sortedMap[key] = sortValueFn ? sortValueFn(value) : value; + } + return sortedMap; +} + +function sortByName(array: $ReadOnlyArray): Array { + return sortBy(array, obj => obj.name); +} + +function sortBy(array: $ReadOnlyArray, mapToKey: T => string): Array { + return array.slice().sort((obj1, obj2) => { + const key1 = mapToKey(obj1); + const key2 = mapToKey(obj2); + return key1.localeCompare(key2); + }); +} diff --git a/node_modules/graphql/utilities/lexicographicSortSchema.mjs b/node_modules/graphql/utilities/lexicographicSortSchema.mjs new file mode 100644 index 0000000..fc0841a --- /dev/null +++ b/node_modules/graphql/utilities/lexicographicSortSchema.mjs @@ -0,0 +1,212 @@ +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import keyValMap from '../jsutils/keyValMap'; +import objectValues from '../jsutils/objectValues'; +import { GraphQLSchema } from '../type/schema'; +import { GraphQLDirective } from '../type/directives'; +import { GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, isListType, isNonNullType, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType } from '../type/definition'; +import { isSpecifiedScalarType } from '../type/scalars'; +import { isIntrospectionType } from '../type/introspection'; +/** + * Sort GraphQLSchema. + */ + +export function lexicographicSortSchema(schema) { + var cache = Object.create(null); + + var sortMaybeType = function sortMaybeType(maybeType) { + return maybeType && sortNamedType(maybeType); + }; + + return new GraphQLSchema({ + types: sortTypes(objectValues(schema.getTypeMap())), + directives: sortByName(schema.getDirectives()).map(sortDirective), + query: sortMaybeType(schema.getQueryType()), + mutation: sortMaybeType(schema.getMutationType()), + subscription: sortMaybeType(schema.getSubscriptionType()), + astNode: schema.astNode + }); + + function sortDirective(directive) { + return new GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: sortBy(directive.locations, function (x) { + return x; + }), + args: sortArgs(directive.args), + astNode: directive.astNode + }); + } + + function sortArgs(args) { + return keyValMap(sortByName(args), function (arg) { + return arg.name; + }, function (arg) { + return _objectSpread({}, arg, { + type: sortType(arg.type) + }); + }); + } + + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return { + type: sortType(field.type), + args: sortArgs(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + description: field.description, + astNode: field.astNode + }; + }); + } + + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return { + type: sortType(field.type), + defaultValue: field.defaultValue, + description: field.description, + astNode: field.astNode + }; + }); + } + + function sortType(type) { + if (isListType(type)) { + return new GraphQLList(sortType(type.ofType)); + } else if (isNonNullType(type)) { + return new GraphQLNonNull(sortType(type.ofType)); + } + + return sortNamedType(type); + } + + function sortTypes(arr) { + return sortByName(arr).map(sortNamedType); + } + + function sortNamedType(type) { + if (isSpecifiedScalarType(type) || isIntrospectionType(type)) { + return type; + } + + var sortedType = cache[type.name]; + + if (!sortedType) { + sortedType = sortNamedTypeImpl(type); + cache[type.name] = sortedType; + } + + return sortedType; + } + + function sortNamedTypeImpl(type) { + if (isScalarType(type)) { + return type; + } else if (isObjectType(type)) { + return new GraphQLObjectType({ + name: type.name, + interfaces: function interfaces() { + return sortTypes(type.getInterfaces()); + }, + fields: function fields() { + return sortFields(type.getFields()); + }, + isTypeOf: type.isTypeOf, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes + }); + } else if (isInterfaceType(type)) { + return new GraphQLInterfaceType({ + name: type.name, + fields: function fields() { + return sortFields(type.getFields()); + }, + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes + }); + } else if (isUnionType(type)) { + return new GraphQLUnionType({ + name: type.name, + types: function types() { + return sortTypes(type.getTypes()); + }, + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode + }); + } else if (isEnumType(type)) { + return new GraphQLEnumType({ + name: type.name, + values: keyValMap(sortByName(type.getValues()), function (val) { + return val.name; + }, function (val) { + return { + value: val.value, + deprecationReason: val.deprecationReason, + description: val.description, + astNode: val.astNode + }; + }), + description: type.description, + astNode: type.astNode + }); + } else if (isInputObjectType(type)) { + return new GraphQLInputObjectType({ + name: type.name, + fields: function fields() { + return sortInputFields(type.getFields()); + }, + description: type.description, + astNode: type.astNode + }); + } + + throw new Error("Unknown type: \"".concat(type, "\"")); + } +} + +function sortObjMap(map, sortValueFn) { + var sortedMap = Object.create(null); + var sortedKeys = sortBy(Object.keys(map), function (x) { + return x; + }); + + for (var _i = 0; _i < sortedKeys.length; _i++) { + var key = sortedKeys[_i]; + var value = map[key]; + sortedMap[key] = sortValueFn ? sortValueFn(value) : value; + } + + return sortedMap; +} + +function sortByName(array) { + return sortBy(array, function (obj) { + return obj.name; + }); +} + +function sortBy(array, mapToKey) { + return array.slice().sort(function (obj1, obj2) { + var key1 = mapToKey(obj1); + var key2 = mapToKey(obj2); + return key1.localeCompare(key2); + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/schemaPrinter.js b/node_modules/graphql/utilities/schemaPrinter.js new file mode 100644 index 0000000..3355b22 --- /dev/null +++ b/node_modules/graphql/utilities/schemaPrinter.js @@ -0,0 +1,342 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.printSchema = printSchema; +exports.printIntrospectionSchema = printIntrospectionSchema; +exports.printType = printType; + +var _isNullish = _interopRequireDefault(require("../jsutils/isNullish")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _astFromValue = require("../utilities/astFromValue"); + +var _printer = require("../language/printer"); + +var _definition = require("../type/definition"); + +var _scalars = require("../type/scalars"); + +var _directives = require("../type/directives"); + +var _introspection = require("../type/introspection"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +function printSchema(schema, options) { + return printFilteredSchema(schema, function (n) { + return !(0, _directives.isSpecifiedDirective)(n); + }, isDefinedType, options); +} + +function printIntrospectionSchema(schema, options) { + return printFilteredSchema(schema, _directives.isSpecifiedDirective, _introspection.isIntrospectionType, options); +} + +function isDefinedType(type) { + return !(0, _scalars.isSpecifiedScalarType)(type) && !(0, _introspection.isIntrospectionType)(type); +} + +function printFilteredSchema(schema, directiveFilter, typeFilter, options) { + var directives = schema.getDirectives().filter(directiveFilter); + var typeMap = schema.getTypeMap(); + var types = (0, _objectValues.default)(typeMap).sort(function (type1, type2) { + return type1.name.localeCompare(type2.name); + }).filter(typeFilter); + return [printSchemaDefinition(schema)].concat(directives.map(function (directive) { + return printDirective(directive, options); + }), types.map(function (type) { + return printType(type, options); + })).filter(Boolean).join('\n\n') + '\n'; +} + +function printSchemaDefinition(schema) { + if (isSchemaOfCommonNames(schema)) { + return; + } + + var operationTypes = []; + var queryType = schema.getQueryType(); + + if (queryType) { + operationTypes.push(" query: ".concat(queryType.name)); + } + + var mutationType = schema.getMutationType(); + + if (mutationType) { + operationTypes.push(" mutation: ".concat(mutationType.name)); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType) { + operationTypes.push(" subscription: ".concat(subscriptionType.name)); + } + + return "schema {\n".concat(operationTypes.join('\n'), "\n}"); +} +/** + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * schema { + * query: Query + * mutation: Mutation + * } + * + * When using this naming convention, the schema description can be omitted. + */ + + +function isSchemaOfCommonNames(schema) { + var queryType = schema.getQueryType(); + + if (queryType && queryType.name !== 'Query') { + return false; + } + + var mutationType = schema.getMutationType(); + + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + + return true; +} + +function printType(type, options) { + if ((0, _definition.isScalarType)(type)) { + return printScalar(type, options); + } else if ((0, _definition.isObjectType)(type)) { + return printObject(type, options); + } else if ((0, _definition.isInterfaceType)(type)) { + return printInterface(type, options); + } else if ((0, _definition.isUnionType)(type)) { + return printUnion(type, options); + } else if ((0, _definition.isEnumType)(type)) { + return printEnum(type, options); + } else if ((0, _definition.isInputObjectType)(type)) { + return printInputObject(type, options); + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} + +function printScalar(type, options) { + return printDescription(options, type) + "scalar ".concat(type.name); +} + +function printObject(type, options) { + var interfaces = type.getInterfaces(); + var implementedInterfaces = interfaces.length ? ' implements ' + interfaces.map(function (i) { + return i.name; + }).join(' & ') : ''; + return printDescription(options, type) + "type ".concat(type.name).concat(implementedInterfaces, " {\n") + printFields(options, type) + '\n' + '}'; +} + +function printInterface(type, options) { + return printDescription(options, type) + "interface ".concat(type.name, " {\n") + printFields(options, type) + '\n' + '}'; +} + +function printUnion(type, options) { + return printDescription(options, type) + "union ".concat(type.name, " = ").concat(type.getTypes().join(' | ')); +} + +function printEnum(type, options) { + return printDescription(options, type) + "enum ".concat(type.name, " {\n") + printEnumValues(type.getValues(), options) + '\n' + '}'; +} + +function printEnumValues(values, options) { + return values.map(function (value, i) { + return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value); + }).join('\n'); +} + +function printInputObject(type, options) { + var fields = (0, _objectValues.default)(type.getFields()); + return printDescription(options, type) + "input ".concat(type.name, " {\n") + fields.map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f); + }).join('\n') + '\n' + '}'; +} + +function printFields(options, type) { + var fields = (0, _objectValues.default)(type.getFields()); + return fields.map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, f.args, ' ') + ': ' + String(f.type) + printDeprecated(f); + }).join('\n'); +} + +function printArgs(options, args) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + + if (args.length === 0) { + return ''; + } // If every arg does not have a description, print them on one line. + + + if (args.every(function (arg) { + return !arg.description; + })) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + + return '(\n' + args.map(function (arg, i) { + return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg); + }).join('\n') + '\n' + indentation + ')'; +} + +function printInputValue(arg) { + var argDecl = arg.name + ': ' + String(arg.type); + + if (!(0, _isInvalid.default)(arg.defaultValue)) { + argDecl += " = ".concat((0, _printer.print)((0, _astFromValue.astFromValue)(arg.defaultValue, arg.type))); + } + + return argDecl; +} + +function printDirective(directive, options) { + return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + ' on ' + directive.locations.join(' | '); +} + +function printDeprecated(fieldOrEnumVal) { + if (!fieldOrEnumVal.isDeprecated) { + return ''; + } + + var reason = fieldOrEnumVal.deprecationReason; + + if ((0, _isNullish.default)(reason) || reason === '' || reason === _directives.DEFAULT_DEPRECATION_REASON) { + return ' @deprecated'; + } + + return ' @deprecated(reason: ' + (0, _printer.print)((0, _astFromValue.astFromValue)(reason, _scalars.GraphQLString)) + ')'; +} + +function printDescription(options, def) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + + if (!def.description) { + return ''; + } + + var lines = descriptionLines(def.description, 120 - indentation.length); + + if (options && options.commentDescriptions) { + return printDescriptionWithComments(lines, indentation, firstInBlock); + } + + var description = indentation && !firstInBlock ? '\n' + indentation + '"""' : indentation + '"""'; // In some circumstances, a single line can be used for the description. + + if (lines.length === 1 && lines[0].length < 70 && lines[0][lines[0].length - 1] !== '"') { + return description + escapeQuote(lines[0]) + '"""\n'; + } // Format a multi-line block quote to account for leading space. + + + var hasLeadingSpace = lines[0][0] === ' ' || lines[0][0] === '\t'; + + if (!hasLeadingSpace) { + description += '\n'; + } + + for (var i = 0; i < lines.length; i++) { + if (i !== 0 || !hasLeadingSpace) { + description += indentation; + } + + description += escapeQuote(lines[i]) + '\n'; + } + + description += indentation + '"""\n'; + return description; +} + +function escapeQuote(line) { + return line.replace(/"""/g, '\\"""'); +} + +function printDescriptionWithComments(lines, indentation, firstInBlock) { + var description = indentation && !firstInBlock ? '\n' : ''; + + for (var i = 0; i < lines.length; i++) { + if (lines[i] === '') { + description += indentation + '#\n'; + } else { + description += indentation + '# ' + lines[i] + '\n'; + } + } + + return description; +} + +function descriptionLines(description, maxLen) { + var lines = []; + var rawLines = description.split('\n'); + + for (var i = 0; i < rawLines.length; i++) { + if (rawLines[i] === '') { + lines.push(rawLines[i]); + } else { + // For > 120 character long lines, cut at space boundaries into sublines + // of ~80 chars. + var sublines = breakLine(rawLines[i], maxLen); + + for (var j = 0; j < sublines.length; j++) { + lines.push(sublines[j]); + } + } + } + + return lines; +} + +function breakLine(line, maxLen) { + if (line.length < maxLen + 5) { + return [line]; + } + + var parts = line.split(new RegExp("((?: |^).{15,".concat(maxLen - 40, "}(?= |$))"))); + + if (parts.length < 4) { + return [line]; + } + + var sublines = [parts[0] + parts[1] + parts[2]]; + + for (var i = 3; i < parts.length; i += 2) { + sublines.push(parts[i].slice(1) + parts[i + 1]); + } + + return sublines; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/schemaPrinter.js.flow b/node_modules/graphql/utilities/schemaPrinter.js.flow new file mode 100644 index 0000000..aa9b01c --- /dev/null +++ b/node_modules/graphql/utilities/schemaPrinter.js.flow @@ -0,0 +1,425 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import isNullish from '../jsutils/isNullish'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { astFromValue } from '../utilities/astFromValue'; +import { print } from '../language/printer'; +import type { GraphQLSchema } from '../type/schema'; +import { + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, +} from '../type/definition'; +import type { + GraphQLNamedType, + GraphQLScalarType, + GraphQLEnumType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLInputObjectType, +} from '../type/definition'; +import { GraphQLString, isSpecifiedScalarType } from '../type/scalars'; +import { + GraphQLDirective, + DEFAULT_DEPRECATION_REASON, + isSpecifiedDirective, +} from '../type/directives'; +import { isIntrospectionType } from '../type/introspection'; + +type Options = {| + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean, +|}; + +/** + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function printSchema(schema: GraphQLSchema, options?: Options): string { + return printFilteredSchema( + schema, + n => !isSpecifiedDirective(n), + isDefinedType, + options, + ); +} + +export function printIntrospectionSchema( + schema: GraphQLSchema, + options?: Options, +): string { + return printFilteredSchema( + schema, + isSpecifiedDirective, + isIntrospectionType, + options, + ); +} + +function isDefinedType(type: GraphQLNamedType): boolean { + return !isSpecifiedScalarType(type) && !isIntrospectionType(type); +} + +function printFilteredSchema( + schema: GraphQLSchema, + directiveFilter: (type: GraphQLDirective) => boolean, + typeFilter: (type: GraphQLNamedType) => boolean, + options, +): string { + const directives = schema.getDirectives().filter(directiveFilter); + const typeMap = schema.getTypeMap(); + const types = objectValues(typeMap) + .sort((type1, type2) => type1.name.localeCompare(type2.name)) + .filter(typeFilter); + + return ( + [printSchemaDefinition(schema)] + .concat( + directives.map(directive => printDirective(directive, options)), + types.map(type => printType(type, options)), + ) + .filter(Boolean) + .join('\n\n') + '\n' + ); +} + +function printSchemaDefinition(schema: GraphQLSchema): ?string { + if (isSchemaOfCommonNames(schema)) { + return; + } + + const operationTypes = []; + + const queryType = schema.getQueryType(); + if (queryType) { + operationTypes.push(` query: ${queryType.name}`); + } + + const mutationType = schema.getMutationType(); + if (mutationType) { + operationTypes.push(` mutation: ${mutationType.name}`); + } + + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType) { + operationTypes.push(` subscription: ${subscriptionType.name}`); + } + + return `schema {\n${operationTypes.join('\n')}\n}`; +} + +/** + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * schema { + * query: Query + * mutation: Mutation + * } + * + * When using this naming convention, the schema description can be omitted. + */ +function isSchemaOfCommonNames(schema: GraphQLSchema): boolean { + const queryType = schema.getQueryType(); + if (queryType && queryType.name !== 'Query') { + return false; + } + + const mutationType = schema.getMutationType(); + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + + return true; +} + +export function printType(type: GraphQLNamedType, options?: Options): string { + if (isScalarType(type)) { + return printScalar(type, options); + } else if (isObjectType(type)) { + return printObject(type, options); + } else if (isInterfaceType(type)) { + return printInterface(type, options); + } else if (isUnionType(type)) { + return printUnion(type, options); + } else if (isEnumType(type)) { + return printEnum(type, options); + } else if (isInputObjectType(type)) { + return printInputObject(type, options); + } + /* istanbul ignore next */ + throw new Error(`Unknown type: ${(type: empty)}.`); +} + +function printScalar(type: GraphQLScalarType, options): string { + return printDescription(options, type) + `scalar ${type.name}`; +} + +function printObject(type: GraphQLObjectType, options): string { + const interfaces = type.getInterfaces(); + const implementedInterfaces = interfaces.length + ? ' implements ' + interfaces.map(i => i.name).join(' & ') + : ''; + return ( + printDescription(options, type) + + `type ${type.name}${implementedInterfaces} {\n` + + printFields(options, type) + + '\n' + + '}' + ); +} + +function printInterface(type: GraphQLInterfaceType, options): string { + return ( + printDescription(options, type) + + `interface ${type.name} {\n` + + printFields(options, type) + + '\n' + + '}' + ); +} + +function printUnion(type: GraphQLUnionType, options): string { + return ( + printDescription(options, type) + + `union ${type.name} = ${type.getTypes().join(' | ')}` + ); +} + +function printEnum(type: GraphQLEnumType, options): string { + return ( + printDescription(options, type) + + `enum ${type.name} {\n` + + printEnumValues(type.getValues(), options) + + '\n' + + '}' + ); +} + +function printEnumValues(values, options): string { + return values + .map( + (value, i) => + printDescription(options, value, ' ', !i) + + ' ' + + value.name + + printDeprecated(value), + ) + .join('\n'); +} + +function printInputObject(type: GraphQLInputObjectType, options): string { + const fields = objectValues(type.getFields()); + return ( + printDescription(options, type) + + `input ${type.name} {\n` + + fields + .map( + (f, i) => + printDescription(options, f, ' ', !i) + ' ' + printInputValue(f), + ) + .join('\n') + + '\n' + + '}' + ); +} + +function printFields(options, type) { + const fields = objectValues(type.getFields()); + return fields + .map( + (f, i) => + printDescription(options, f, ' ', !i) + + ' ' + + f.name + + printArgs(options, f.args, ' ') + + ': ' + + String(f.type) + + printDeprecated(f), + ) + .join('\n'); +} + +function printArgs(options, args, indentation = '') { + if (args.length === 0) { + return ''; + } + + // If every arg does not have a description, print them on one line. + if (args.every(arg => !arg.description)) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + + return ( + '(\n' + + args + .map( + (arg, i) => + printDescription(options, arg, ' ' + indentation, !i) + + ' ' + + indentation + + printInputValue(arg), + ) + .join('\n') + + '\n' + + indentation + + ')' + ); +} + +function printInputValue(arg) { + let argDecl = arg.name + ': ' + String(arg.type); + if (!isInvalid(arg.defaultValue)) { + argDecl += ` = ${print(astFromValue(arg.defaultValue, arg.type))}`; + } + return argDecl; +} + +function printDirective(directive, options) { + return ( + printDescription(options, directive) + + 'directive @' + + directive.name + + printArgs(options, directive.args) + + ' on ' + + directive.locations.join(' | ') + ); +} + +function printDeprecated(fieldOrEnumVal) { + if (!fieldOrEnumVal.isDeprecated) { + return ''; + } + const reason = fieldOrEnumVal.deprecationReason; + if ( + isNullish(reason) || + reason === '' || + reason === DEFAULT_DEPRECATION_REASON + ) { + return ' @deprecated'; + } + return ( + ' @deprecated(reason: ' + print(astFromValue(reason, GraphQLString)) + ')' + ); +} + +function printDescription( + options, + def, + indentation = '', + firstInBlock = true, +): string { + if (!def.description) { + return ''; + } + + const lines = descriptionLines(def.description, 120 - indentation.length); + if (options && options.commentDescriptions) { + return printDescriptionWithComments(lines, indentation, firstInBlock); + } + + let description = + indentation && !firstInBlock + ? '\n' + indentation + '"""' + : indentation + '"""'; + + // In some circumstances, a single line can be used for the description. + if ( + lines.length === 1 && + lines[0].length < 70 && + lines[0][lines[0].length - 1] !== '"' + ) { + return description + escapeQuote(lines[0]) + '"""\n'; + } + + // Format a multi-line block quote to account for leading space. + const hasLeadingSpace = lines[0][0] === ' ' || lines[0][0] === '\t'; + if (!hasLeadingSpace) { + description += '\n'; + } + for (let i = 0; i < lines.length; i++) { + if (i !== 0 || !hasLeadingSpace) { + description += indentation; + } + description += escapeQuote(lines[i]) + '\n'; + } + description += indentation + '"""\n'; + return description; +} + +function escapeQuote(line) { + return line.replace(/"""/g, '\\"""'); +} + +function printDescriptionWithComments(lines, indentation, firstInBlock) { + let description = indentation && !firstInBlock ? '\n' : ''; + for (let i = 0; i < lines.length; i++) { + if (lines[i] === '') { + description += indentation + '#\n'; + } else { + description += indentation + '# ' + lines[i] + '\n'; + } + } + return description; +} + +function descriptionLines(description: string, maxLen: number): Array { + const lines = []; + const rawLines = description.split('\n'); + for (let i = 0; i < rawLines.length; i++) { + if (rawLines[i] === '') { + lines.push(rawLines[i]); + } else { + // For > 120 character long lines, cut at space boundaries into sublines + // of ~80 chars. + const sublines = breakLine(rawLines[i], maxLen); + for (let j = 0; j < sublines.length; j++) { + lines.push(sublines[j]); + } + } + } + return lines; +} + +function breakLine(line: string, maxLen: number): Array { + if (line.length < maxLen + 5) { + return [line]; + } + const parts = line.split(new RegExp(`((?: |^).{15,${maxLen - 40}}(?= |$))`)); + if (parts.length < 4) { + return [line]; + } + const sublines = [parts[0] + parts[1] + parts[2]]; + for (let i = 3; i < parts.length; i += 2) { + sublines.push(parts[i].slice(1) + parts[i + 1]); + } + return sublines; +} diff --git a/node_modules/graphql/utilities/schemaPrinter.mjs b/node_modules/graphql/utilities/schemaPrinter.mjs new file mode 100644 index 0000000..cfc27d3 --- /dev/null +++ b/node_modules/graphql/utilities/schemaPrinter.mjs @@ -0,0 +1,321 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import isNullish from '../jsutils/isNullish'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { astFromValue } from '../utilities/astFromValue'; +import { print } from '../language/printer'; +import { isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType } from '../type/definition'; +import { GraphQLString, isSpecifiedScalarType } from '../type/scalars'; +import { GraphQLDirective, DEFAULT_DEPRECATION_REASON, isSpecifiedDirective } from '../type/directives'; +import { isIntrospectionType } from '../type/introspection'; + +/** + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function printSchema(schema, options) { + return printFilteredSchema(schema, function (n) { + return !isSpecifiedDirective(n); + }, isDefinedType, options); +} +export function printIntrospectionSchema(schema, options) { + return printFilteredSchema(schema, isSpecifiedDirective, isIntrospectionType, options); +} + +function isDefinedType(type) { + return !isSpecifiedScalarType(type) && !isIntrospectionType(type); +} + +function printFilteredSchema(schema, directiveFilter, typeFilter, options) { + var directives = schema.getDirectives().filter(directiveFilter); + var typeMap = schema.getTypeMap(); + var types = objectValues(typeMap).sort(function (type1, type2) { + return type1.name.localeCompare(type2.name); + }).filter(typeFilter); + return [printSchemaDefinition(schema)].concat(directives.map(function (directive) { + return printDirective(directive, options); + }), types.map(function (type) { + return printType(type, options); + })).filter(Boolean).join('\n\n') + '\n'; +} + +function printSchemaDefinition(schema) { + if (isSchemaOfCommonNames(schema)) { + return; + } + + var operationTypes = []; + var queryType = schema.getQueryType(); + + if (queryType) { + operationTypes.push(" query: ".concat(queryType.name)); + } + + var mutationType = schema.getMutationType(); + + if (mutationType) { + operationTypes.push(" mutation: ".concat(mutationType.name)); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType) { + operationTypes.push(" subscription: ".concat(subscriptionType.name)); + } + + return "schema {\n".concat(operationTypes.join('\n'), "\n}"); +} +/** + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * schema { + * query: Query + * mutation: Mutation + * } + * + * When using this naming convention, the schema description can be omitted. + */ + + +function isSchemaOfCommonNames(schema) { + var queryType = schema.getQueryType(); + + if (queryType && queryType.name !== 'Query') { + return false; + } + + var mutationType = schema.getMutationType(); + + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + + return true; +} + +export function printType(type, options) { + if (isScalarType(type)) { + return printScalar(type, options); + } else if (isObjectType(type)) { + return printObject(type, options); + } else if (isInterfaceType(type)) { + return printInterface(type, options); + } else if (isUnionType(type)) { + return printUnion(type, options); + } else if (isEnumType(type)) { + return printEnum(type, options); + } else if (isInputObjectType(type)) { + return printInputObject(type, options); + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} + +function printScalar(type, options) { + return printDescription(options, type) + "scalar ".concat(type.name); +} + +function printObject(type, options) { + var interfaces = type.getInterfaces(); + var implementedInterfaces = interfaces.length ? ' implements ' + interfaces.map(function (i) { + return i.name; + }).join(' & ') : ''; + return printDescription(options, type) + "type ".concat(type.name).concat(implementedInterfaces, " {\n") + printFields(options, type) + '\n' + '}'; +} + +function printInterface(type, options) { + return printDescription(options, type) + "interface ".concat(type.name, " {\n") + printFields(options, type) + '\n' + '}'; +} + +function printUnion(type, options) { + return printDescription(options, type) + "union ".concat(type.name, " = ").concat(type.getTypes().join(' | ')); +} + +function printEnum(type, options) { + return printDescription(options, type) + "enum ".concat(type.name, " {\n") + printEnumValues(type.getValues(), options) + '\n' + '}'; +} + +function printEnumValues(values, options) { + return values.map(function (value, i) { + return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value); + }).join('\n'); +} + +function printInputObject(type, options) { + var fields = objectValues(type.getFields()); + return printDescription(options, type) + "input ".concat(type.name, " {\n") + fields.map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f); + }).join('\n') + '\n' + '}'; +} + +function printFields(options, type) { + var fields = objectValues(type.getFields()); + return fields.map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, f.args, ' ') + ': ' + String(f.type) + printDeprecated(f); + }).join('\n'); +} + +function printArgs(options, args) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + + if (args.length === 0) { + return ''; + } // If every arg does not have a description, print them on one line. + + + if (args.every(function (arg) { + return !arg.description; + })) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + + return '(\n' + args.map(function (arg, i) { + return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg); + }).join('\n') + '\n' + indentation + ')'; +} + +function printInputValue(arg) { + var argDecl = arg.name + ': ' + String(arg.type); + + if (!isInvalid(arg.defaultValue)) { + argDecl += " = ".concat(print(astFromValue(arg.defaultValue, arg.type))); + } + + return argDecl; +} + +function printDirective(directive, options) { + return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + ' on ' + directive.locations.join(' | '); +} + +function printDeprecated(fieldOrEnumVal) { + if (!fieldOrEnumVal.isDeprecated) { + return ''; + } + + var reason = fieldOrEnumVal.deprecationReason; + + if (isNullish(reason) || reason === '' || reason === DEFAULT_DEPRECATION_REASON) { + return ' @deprecated'; + } + + return ' @deprecated(reason: ' + print(astFromValue(reason, GraphQLString)) + ')'; +} + +function printDescription(options, def) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + + if (!def.description) { + return ''; + } + + var lines = descriptionLines(def.description, 120 - indentation.length); + + if (options && options.commentDescriptions) { + return printDescriptionWithComments(lines, indentation, firstInBlock); + } + + var description = indentation && !firstInBlock ? '\n' + indentation + '"""' : indentation + '"""'; // In some circumstances, a single line can be used for the description. + + if (lines.length === 1 && lines[0].length < 70 && lines[0][lines[0].length - 1] !== '"') { + return description + escapeQuote(lines[0]) + '"""\n'; + } // Format a multi-line block quote to account for leading space. + + + var hasLeadingSpace = lines[0][0] === ' ' || lines[0][0] === '\t'; + + if (!hasLeadingSpace) { + description += '\n'; + } + + for (var i = 0; i < lines.length; i++) { + if (i !== 0 || !hasLeadingSpace) { + description += indentation; + } + + description += escapeQuote(lines[i]) + '\n'; + } + + description += indentation + '"""\n'; + return description; +} + +function escapeQuote(line) { + return line.replace(/"""/g, '\\"""'); +} + +function printDescriptionWithComments(lines, indentation, firstInBlock) { + var description = indentation && !firstInBlock ? '\n' : ''; + + for (var i = 0; i < lines.length; i++) { + if (lines[i] === '') { + description += indentation + '#\n'; + } else { + description += indentation + '# ' + lines[i] + '\n'; + } + } + + return description; +} + +function descriptionLines(description, maxLen) { + var lines = []; + var rawLines = description.split('\n'); + + for (var i = 0; i < rawLines.length; i++) { + if (rawLines[i] === '') { + lines.push(rawLines[i]); + } else { + // For > 120 character long lines, cut at space boundaries into sublines + // of ~80 chars. + var sublines = breakLine(rawLines[i], maxLen); + + for (var j = 0; j < sublines.length; j++) { + lines.push(sublines[j]); + } + } + } + + return lines; +} + +function breakLine(line, maxLen) { + if (line.length < maxLen + 5) { + return [line]; + } + + var parts = line.split(new RegExp("((?: |^).{15,".concat(maxLen - 40, "}(?= |$))"))); + + if (parts.length < 4) { + return [line]; + } + + var sublines = [parts[0] + parts[1] + parts[2]]; + + for (var i = 3; i < parts.length; i += 2) { + sublines.push(parts[i].slice(1) + parts[i + 1]); + } + + return sublines; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/separateOperations.js b/node_modules/graphql/utilities/separateOperations.js new file mode 100644 index 0000000..6e129c8 --- /dev/null +++ b/node_modules/graphql/utilities/separateOperations.js @@ -0,0 +1,103 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.separateOperations = separateOperations; + +var _visitor = require("../language/visitor"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + */ +function separateOperations(documentAST) { + var operations = []; + var fragments = Object.create(null); + var positions = new Map(); + var depGraph = Object.create(null); + var fromName; + var idx = 0; // Populate metadata and build a dependency graph. + + (0, _visitor.visit)(documentAST, { + OperationDefinition: function OperationDefinition(node) { + fromName = opName(node); + operations.push(node); + positions.set(node, idx++); + }, + FragmentDefinition: function FragmentDefinition(node) { + fromName = node.name.value; + fragments[fromName] = node; + positions.set(node, idx++); + }, + FragmentSpread: function FragmentSpread(node) { + var toName = node.name.value; + (depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[toName] = true; + } + }); // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + var separatedDocumentASTs = Object.create(null); + + for (var _i = 0; _i < operations.length; _i++) { + var operation = operations[_i]; + var operationName = opName(operation); + var dependencies = Object.create(null); + collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + + var definitions = [operation]; + + var _arr = Object.keys(dependencies); + + for (var _i2 = 0; _i2 < _arr.length; _i2++) { + var name = _arr[_i2]; + definitions.push(fragments[name]); + } + + definitions.sort(function (n1, n2) { + return (positions.get(n1) || 0) - (positions.get(n2) || 0); + }); + separatedDocumentASTs[operationName] = { + kind: 'Document', + definitions: definitions + }; + } + + return separatedDocumentASTs; +} + +// Provides the empty string for anonymous operations. +function opName(operation) { + return operation.name ? operation.name.value : ''; +} // From a dependency graph, collects a list of transitive dependencies by +// recursing through a dependency graph. + + +function collectTransitiveDependencies(collected, depGraph, fromName) { + var immediateDeps = depGraph[fromName]; + + if (immediateDeps) { + var _arr2 = Object.keys(immediateDeps); + + for (var _i3 = 0; _i3 < _arr2.length; _i3++) { + var toName = _arr2[_i3]; + + if (!collected[toName]) { + collected[toName] = true; + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/separateOperations.js.flow b/node_modules/graphql/utilities/separateOperations.js.flow new file mode 100644 index 0000000..0fe8f5b --- /dev/null +++ b/node_modules/graphql/utilities/separateOperations.js.flow @@ -0,0 +1,100 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { visit } from '../language/visitor'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { DocumentNode, OperationDefinitionNode } from '../language/ast'; + +/** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + */ +export function separateOperations( + documentAST: DocumentNode, +): ObjMap { + const operations = []; + const fragments = Object.create(null); + const positions = new Map(); + const depGraph: DepGraph = Object.create(null); + let fromName; + let idx = 0; + + // Populate metadata and build a dependency graph. + visit(documentAST, { + OperationDefinition(node) { + fromName = opName(node); + operations.push(node); + positions.set(node, idx++); + }, + FragmentDefinition(node) { + fromName = node.name.value; + fragments[fromName] = node; + positions.set(node, idx++); + }, + FragmentSpread(node) { + const toName = node.name.value; + (depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[ + toName + ] = true; + }, + }); + + // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + const separatedDocumentASTs = Object.create(null); + for (const operation of operations) { + const operationName = opName(operation); + const dependencies = Object.create(null); + collectTransitiveDependencies(dependencies, depGraph, operationName); + + // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + const definitions = [operation]; + for (const name of Object.keys(dependencies)) { + definitions.push(fragments[name]); + } + definitions.sort( + (n1, n2) => (positions.get(n1) || 0) - (positions.get(n2) || 0), + ); + + separatedDocumentASTs[operationName] = { + kind: 'Document', + definitions, + }; + } + + return separatedDocumentASTs; +} + +type DepGraph = ObjMap>; + +// Provides the empty string for anonymous operations. +function opName(operation: OperationDefinitionNode): string { + return operation.name ? operation.name.value : ''; +} + +// From a dependency graph, collects a list of transitive dependencies by +// recursing through a dependency graph. +function collectTransitiveDependencies( + collected: ObjMap, + depGraph: DepGraph, + fromName: string, +): void { + const immediateDeps = depGraph[fromName]; + if (immediateDeps) { + for (const toName of Object.keys(immediateDeps)) { + if (!collected[toName]) { + collected[toName] = true; + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } +} diff --git a/node_modules/graphql/utilities/separateOperations.mjs b/node_modules/graphql/utilities/separateOperations.mjs new file mode 100644 index 0000000..0de6835 --- /dev/null +++ b/node_modules/graphql/utilities/separateOperations.mjs @@ -0,0 +1,95 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { visit } from '../language/visitor'; + +/** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + */ +export function separateOperations(documentAST) { + var operations = []; + var fragments = Object.create(null); + var positions = new Map(); + var depGraph = Object.create(null); + var fromName; + var idx = 0; // Populate metadata and build a dependency graph. + + visit(documentAST, { + OperationDefinition: function OperationDefinition(node) { + fromName = opName(node); + operations.push(node); + positions.set(node, idx++); + }, + FragmentDefinition: function FragmentDefinition(node) { + fromName = node.name.value; + fragments[fromName] = node; + positions.set(node, idx++); + }, + FragmentSpread: function FragmentSpread(node) { + var toName = node.name.value; + (depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[toName] = true; + } + }); // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + var separatedDocumentASTs = Object.create(null); + + for (var _i = 0; _i < operations.length; _i++) { + var operation = operations[_i]; + var operationName = opName(operation); + var dependencies = Object.create(null); + collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + + var definitions = [operation]; + + var _arr = Object.keys(dependencies); + + for (var _i2 = 0; _i2 < _arr.length; _i2++) { + var name = _arr[_i2]; + definitions.push(fragments[name]); + } + + definitions.sort(function (n1, n2) { + return (positions.get(n1) || 0) - (positions.get(n2) || 0); + }); + separatedDocumentASTs[operationName] = { + kind: 'Document', + definitions: definitions + }; + } + + return separatedDocumentASTs; +} + +// Provides the empty string for anonymous operations. +function opName(operation) { + return operation.name ? operation.name.value : ''; +} // From a dependency graph, collects a list of transitive dependencies by +// recursing through a dependency graph. + + +function collectTransitiveDependencies(collected, depGraph, fromName) { + var immediateDeps = depGraph[fromName]; + + if (immediateDeps) { + var _arr2 = Object.keys(immediateDeps); + + for (var _i3 = 0; _i3 < _arr2.length; _i3++) { + var toName = _arr2[_i3]; + + if (!collected[toName]) { + collected[toName] = true; + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/typeComparators.js b/node_modules/graphql/utilities/typeComparators.js new file mode 100644 index 0000000..3a9e9d6 --- /dev/null +++ b/node_modules/graphql/utilities/typeComparators.js @@ -0,0 +1,129 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isEqualType = isEqualType; +exports.isTypeSubTypeOf = isTypeSubTypeOf; +exports.doTypesOverlap = doTypesOverlap; + +var _definition = require("../type/definition"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Provided two types, return true if the types are equal (invariant). + */ +function isEqualType(typeA, typeB) { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } // If either type is non-null, the other must also be non-null. + + + if ((0, _definition.isNonNullType)(typeA) && (0, _definition.isNonNullType)(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // If either type is a list, the other must also be a list. + + + if ((0, _definition.isListType)(typeA) && (0, _definition.isListType)(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // Otherwise the types are not equal. + + + return false; +} +/** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ + + +function isTypeSubTypeOf(schema, maybeSubType, superType) { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } // If superType is non-null, maybeSubType must also be non-null. + + + if ((0, _definition.isNonNullType)(superType)) { + if ((0, _definition.isNonNullType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if ((0, _definition.isNonNullType)(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } // If superType type is a list, maybeSubType type must also be a list. + + + if ((0, _definition.isListType)(superType)) { + if ((0, _definition.isListType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if ((0, _definition.isListType)(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } // If superType type is an abstract type, maybeSubType type may be a currently + // possible object type. + + + if ((0, _definition.isAbstractType)(superType) && (0, _definition.isObjectType)(maybeSubType) && schema.isPossibleType(superType, maybeSubType)) { + return true; + } // Otherwise, the child type is not a valid subtype of the parent type. + + + return false; +} +/** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ + + +function doTypesOverlap(schema, typeA, typeB) { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } + + if ((0, _definition.isAbstractType)(typeA)) { + if ((0, _definition.isAbstractType)(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema.getPossibleTypes(typeA).some(function (type) { + return schema.isPossibleType(typeB, type); + }); + } // Determine if the latter type is a possible concrete type of the former. + + + return schema.isPossibleType(typeA, typeB); + } + + if ((0, _definition.isAbstractType)(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isPossibleType(typeB, typeA); + } // Otherwise the types do not overlap. + + + return false; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/typeComparators.js.flow b/node_modules/graphql/utilities/typeComparators.js.flow new file mode 100644 index 0000000..b903ff4 --- /dev/null +++ b/node_modules/graphql/utilities/typeComparators.js.flow @@ -0,0 +1,132 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { + isObjectType, + isListType, + isNonNullType, + isAbstractType, +} from '../type/definition'; +import type { GraphQLType, GraphQLCompositeType } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; + +/** + * Provided two types, return true if the types are equal (invariant). + */ +export function isEqualType(typeA: GraphQLType, typeB: GraphQLType): boolean { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } + + // If either type is non-null, the other must also be non-null. + if (isNonNullType(typeA) && isNonNullType(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } + + // If either type is a list, the other must also be a list. + if (isListType(typeA) && isListType(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } + + // Otherwise the types are not equal. + return false; +} + +/** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ +export function isTypeSubTypeOf( + schema: GraphQLSchema, + maybeSubType: GraphQLType, + superType: GraphQLType, +): boolean { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } + + // If superType is non-null, maybeSubType must also be non-null. + if (isNonNullType(superType)) { + if (isNonNullType(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + return false; + } + if (isNonNullType(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } + + // If superType type is a list, maybeSubType type must also be a list. + if (isListType(superType)) { + if (isListType(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + return false; + } + if (isListType(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } + + // If superType type is an abstract type, maybeSubType type may be a currently + // possible object type. + if ( + isAbstractType(superType) && + isObjectType(maybeSubType) && + schema.isPossibleType(superType, maybeSubType) + ) { + return true; + } + + // Otherwise, the child type is not a valid subtype of the parent type. + return false; +} + +/** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ +export function doTypesOverlap( + schema: GraphQLSchema, + typeA: GraphQLCompositeType, + typeB: GraphQLCompositeType, +): boolean { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } + + if (isAbstractType(typeA)) { + if (isAbstractType(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema + .getPossibleTypes(typeA) + .some(type => schema.isPossibleType(typeB, type)); + } + // Determine if the latter type is a possible concrete type of the former. + return schema.isPossibleType(typeA, typeB); + } + + if (isAbstractType(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isPossibleType(typeB, typeA); + } + + // Otherwise the types do not overlap. + return false; +} diff --git a/node_modules/graphql/utilities/typeComparators.mjs b/node_modules/graphql/utilities/typeComparators.mjs new file mode 100644 index 0000000..31a8ac2 --- /dev/null +++ b/node_modules/graphql/utilities/typeComparators.mjs @@ -0,0 +1,117 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { isObjectType, isListType, isNonNullType, isAbstractType } from '../type/definition'; + +/** + * Provided two types, return true if the types are equal (invariant). + */ +export function isEqualType(typeA, typeB) { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } // If either type is non-null, the other must also be non-null. + + + if (isNonNullType(typeA) && isNonNullType(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // If either type is a list, the other must also be a list. + + + if (isListType(typeA) && isListType(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // Otherwise the types are not equal. + + + return false; +} +/** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ + +export function isTypeSubTypeOf(schema, maybeSubType, superType) { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } // If superType is non-null, maybeSubType must also be non-null. + + + if (isNonNullType(superType)) { + if (isNonNullType(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if (isNonNullType(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } // If superType type is a list, maybeSubType type must also be a list. + + + if (isListType(superType)) { + if (isListType(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if (isListType(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } // If superType type is an abstract type, maybeSubType type may be a currently + // possible object type. + + + if (isAbstractType(superType) && isObjectType(maybeSubType) && schema.isPossibleType(superType, maybeSubType)) { + return true; + } // Otherwise, the child type is not a valid subtype of the parent type. + + + return false; +} +/** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ + +export function doTypesOverlap(schema, typeA, typeB) { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } + + if (isAbstractType(typeA)) { + if (isAbstractType(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema.getPossibleTypes(typeA).some(function (type) { + return schema.isPossibleType(typeB, type); + }); + } // Determine if the latter type is a possible concrete type of the former. + + + return schema.isPossibleType(typeA, typeB); + } + + if (isAbstractType(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isPossibleType(typeB, typeA); + } // Otherwise the types do not overlap. + + + return false; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/typeFromAST.js b/node_modules/graphql/utilities/typeFromAST.js new file mode 100644 index 0000000..a6201ac --- /dev/null +++ b/node_modules/graphql/utilities/typeFromAST.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.typeFromAST = typeFromAST; + +var _kinds = require("../language/kinds"); + +var _definition = require("../type/definition"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function typeFromAST(schema, typeNode) { + /* eslint-enable no-redeclare */ + var innerType; + + if (typeNode.kind === _kinds.Kind.LIST_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && (0, _definition.GraphQLList)(innerType); + } + + if (typeNode.kind === _kinds.Kind.NON_NULL_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && (0, _definition.GraphQLNonNull)(innerType); + } + + if (typeNode.kind === _kinds.Kind.NAMED_TYPE) { + return schema.getType(typeNode.name.value); + } + /* istanbul ignore next */ + + + throw new Error("Unexpected type kind: ".concat(typeNode.kind, ".")); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/typeFromAST.js.flow b/node_modules/graphql/utilities/typeFromAST.js.flow new file mode 100644 index 0000000..596e16f --- /dev/null +++ b/node_modules/graphql/utilities/typeFromAST.js.flow @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { Kind } from '../language/kinds'; +import type { + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, +} from '../language/ast'; +import { GraphQLList, GraphQLNonNull } from '../type/definition'; +import type { GraphQLNamedType } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; + +/** + * Given a Schema and an AST node describing a type, return a GraphQLType + * definition which applies to that type. For example, if provided the parsed + * AST node for `[User]`, a GraphQLList instance will be returned, containing + * the type called "User" found in the schema. If a type called "User" is not + * found in the schema, then undefined will be returned. + */ +/* eslint-disable no-redeclare */ +declare function typeFromAST( + schema: GraphQLSchema, + typeNode: NamedTypeNode, +): GraphQLNamedType | void; +declare function typeFromAST( + schema: GraphQLSchema, + typeNode: ListTypeNode, +): GraphQLList | void; +declare function typeFromAST( + schema: GraphQLSchema, + typeNode: NonNullTypeNode, +): GraphQLNonNull | void; +export function typeFromAST(schema, typeNode) { + /* eslint-enable no-redeclare */ + let innerType; + if (typeNode.kind === Kind.LIST_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && GraphQLList(innerType); + } + if (typeNode.kind === Kind.NON_NULL_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && GraphQLNonNull(innerType); + } + if (typeNode.kind === Kind.NAMED_TYPE) { + return schema.getType(typeNode.name.value); + } + /* istanbul ignore next */ + throw new Error(`Unexpected type kind: ${(typeNode.kind: empty)}.`); +} diff --git a/node_modules/graphql/utilities/typeFromAST.mjs b/node_modules/graphql/utilities/typeFromAST.mjs new file mode 100644 index 0000000..e1dee0d --- /dev/null +++ b/node_modules/graphql/utilities/typeFromAST.mjs @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { Kind } from '../language/kinds'; +import { GraphQLList, GraphQLNonNull } from '../type/definition'; +export function typeFromAST(schema, typeNode) { + /* eslint-enable no-redeclare */ + var innerType; + + if (typeNode.kind === Kind.LIST_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && GraphQLList(innerType); + } + + if (typeNode.kind === Kind.NON_NULL_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && GraphQLNonNull(innerType); + } + + if (typeNode.kind === Kind.NAMED_TYPE) { + return schema.getType(typeNode.name.value); + } + /* istanbul ignore next */ + + + throw new Error("Unexpected type kind: ".concat(typeNode.kind, ".")); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/valueFromAST.js b/node_modules/graphql/utilities/valueFromAST.js new file mode 100644 index 0000000..420999e --- /dev/null +++ b/node_modules/graphql/utilities/valueFromAST.js @@ -0,0 +1,207 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.valueFromAST = valueFromAST; + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _kinds = require("../language/kinds"); + +var _definition = require("../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Mixed | + * | NullValue | null | + * + */ +function valueFromAST(valueNode, type, variables) { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } + + if ((0, _definition.isNonNullType)(type)) { + if (valueNode.kind === _kinds.Kind.NULL) { + return; // Invalid: intentionally return no value. + } + + return valueFromAST(valueNode, type.ofType, variables); + } + + if (valueNode.kind === _kinds.Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + + if (valueNode.kind === _kinds.Kind.VARIABLE) { + var variableName = valueNode.name.value; + + if (!variables || (0, _isInvalid.default)(variables[variableName])) { + // No valid return value. + return; + } + + var variableValue = variables[variableName]; + + if (variableValue === null && (0, _definition.isNonNullType)(type)) { + return; // Invalid: intentionally return no value. + } // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + + return variableValue; + } + + if ((0, _definition.isListType)(type)) { + var itemType = type.ofType; + + if (valueNode.kind === _kinds.Kind.LIST) { + var coercedValues = []; + var itemNodes = valueNode.values; + + for (var i = 0; i < itemNodes.length; i++) { + if (isMissingVariable(itemNodes[i], variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if ((0, _definition.isNonNullType)(itemType)) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(null); + } else { + var itemValue = valueFromAST(itemNodes[i], itemType, variables); + + if ((0, _isInvalid.default)(itemValue)) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(itemValue); + } + } + + return coercedValues; + } + + var coercedValue = valueFromAST(valueNode, itemType, variables); + + if ((0, _isInvalid.default)(coercedValue)) { + return; // Invalid: intentionally return no value. + } + + return [coercedValue]; + } + + if ((0, _definition.isInputObjectType)(type)) { + if (valueNode.kind !== _kinds.Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } + + var coercedObj = Object.create(null); + var fieldNodes = (0, _keyMap.default)(valueNode.fields, function (field) { + return field.name.value; + }); + var fields = (0, _objectValues.default)(type.getFields()); + + for (var _i = 0; _i < fields.length; _i++) { + var field = fields[_i]; + var fieldNode = fieldNodes[field.name]; + + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + return; // Invalid: intentionally return no value. + } + + continue; + } + + var fieldValue = valueFromAST(fieldNode.value, field.type, variables); + + if ((0, _isInvalid.default)(fieldValue)) { + return; // Invalid: intentionally return no value. + } + + coercedObj[field.name] = fieldValue; + } + + return coercedObj; + } + + if ((0, _definition.isEnumType)(type)) { + if (valueNode.kind !== _kinds.Kind.ENUM) { + return; // Invalid: intentionally return no value. + } + + var enumValue = type.getValue(valueNode.value); + + if (!enumValue) { + return; // Invalid: intentionally return no value. + } + + return enumValue.value; + } + + if ((0, _definition.isScalarType)(type)) { + // Scalars fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + var result; + + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. + } + + if ((0, _isInvalid.default)(result)) { + return; // Invalid: intentionally return no value. + } + + return result; + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} // Returns true if the provided valueNode is a variable which is not defined +// in the set of variables. + + +function isMissingVariable(valueNode, variables) { + return valueNode.kind === _kinds.Kind.VARIABLE && (!variables || (0, _isInvalid.default)(variables[valueNode.name.value])); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/valueFromAST.js.flow b/node_modules/graphql/utilities/valueFromAST.js.flow new file mode 100644 index 0000000..f198d1f --- /dev/null +++ b/node_modules/graphql/utilities/valueFromAST.js.flow @@ -0,0 +1,179 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import keyMap from '../jsutils/keyMap'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import type { ObjMap } from '../jsutils/ObjMap'; +import { Kind } from '../language/kinds'; +import { + isScalarType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, +} from '../type/definition'; +import type { GraphQLInputType } from '../type/definition'; +import type { ValueNode } from '../language/ast'; + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Mixed | + * | NullValue | null | + * + */ +export function valueFromAST( + valueNode: ?ValueNode, + type: GraphQLInputType, + variables?: ?ObjMap, +): mixed | void { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } + + if (isNonNullType(type)) { + if (valueNode.kind === Kind.NULL) { + return; // Invalid: intentionally return no value. + } + return valueFromAST(valueNode, type.ofType, variables); + } + + if (valueNode.kind === Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + + if (valueNode.kind === Kind.VARIABLE) { + const variableName = valueNode.name.value; + if (!variables || isInvalid(variables[variableName])) { + // No valid return value. + return; + } + const variableValue = variables[variableName]; + if (variableValue === null && isNonNullType(type)) { + return; // Invalid: intentionally return no value. + } + // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + return variableValue; + } + + if (isListType(type)) { + const itemType = type.ofType; + if (valueNode.kind === Kind.LIST) { + const coercedValues = []; + const itemNodes = valueNode.values; + for (let i = 0; i < itemNodes.length; i++) { + if (isMissingVariable(itemNodes[i], variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if (isNonNullType(itemType)) { + return; // Invalid: intentionally return no value. + } + coercedValues.push(null); + } else { + const itemValue = valueFromAST(itemNodes[i], itemType, variables); + if (isInvalid(itemValue)) { + return; // Invalid: intentionally return no value. + } + coercedValues.push(itemValue); + } + } + return coercedValues; + } + const coercedValue = valueFromAST(valueNode, itemType, variables); + if (isInvalid(coercedValue)) { + return; // Invalid: intentionally return no value. + } + return [coercedValue]; + } + + if (isInputObjectType(type)) { + if (valueNode.kind !== Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } + const coercedObj = Object.create(null); + const fieldNodes = keyMap(valueNode.fields, field => field.name.value); + const fields = objectValues(type.getFields()); + for (let i = 0; i < fields.length; i++) { + const field = fields[i]; + const fieldNode = fieldNodes[field.name]; + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if (isNonNullType(field.type)) { + return; // Invalid: intentionally return no value. + } + continue; + } + const fieldValue = valueFromAST(fieldNode.value, field.type, variables); + if (isInvalid(fieldValue)) { + return; // Invalid: intentionally return no value. + } + coercedObj[field.name] = fieldValue; + } + return coercedObj; + } + + if (isEnumType(type)) { + if (valueNode.kind !== Kind.ENUM) { + return; // Invalid: intentionally return no value. + } + const enumValue = type.getValue(valueNode.value); + if (!enumValue) { + return; // Invalid: intentionally return no value. + } + return enumValue.value; + } + + if (isScalarType(type)) { + // Scalars fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + let result; + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. + } + if (isInvalid(result)) { + return; // Invalid: intentionally return no value. + } + return result; + } + + /* istanbul ignore next */ + throw new Error(`Unknown type: ${(type: empty)}.`); +} + +// Returns true if the provided valueNode is a variable which is not defined +// in the set of variables. +function isMissingVariable(valueNode, variables) { + return ( + valueNode.kind === Kind.VARIABLE && + (!variables || isInvalid(variables[valueNode.name.value])) + ); +} diff --git a/node_modules/graphql/utilities/valueFromAST.mjs b/node_modules/graphql/utilities/valueFromAST.mjs new file mode 100644 index 0000000..5ac5695 --- /dev/null +++ b/node_modules/graphql/utilities/valueFromAST.mjs @@ -0,0 +1,192 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import keyMap from '../jsutils/keyMap'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { Kind } from '../language/kinds'; +import { isScalarType, isEnumType, isInputObjectType, isListType, isNonNullType } from '../type/definition'; + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Mixed | + * | NullValue | null | + * + */ +export function valueFromAST(valueNode, type, variables) { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } + + if (isNonNullType(type)) { + if (valueNode.kind === Kind.NULL) { + return; // Invalid: intentionally return no value. + } + + return valueFromAST(valueNode, type.ofType, variables); + } + + if (valueNode.kind === Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + + if (valueNode.kind === Kind.VARIABLE) { + var variableName = valueNode.name.value; + + if (!variables || isInvalid(variables[variableName])) { + // No valid return value. + return; + } + + var variableValue = variables[variableName]; + + if (variableValue === null && isNonNullType(type)) { + return; // Invalid: intentionally return no value. + } // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + + return variableValue; + } + + if (isListType(type)) { + var itemType = type.ofType; + + if (valueNode.kind === Kind.LIST) { + var coercedValues = []; + var itemNodes = valueNode.values; + + for (var i = 0; i < itemNodes.length; i++) { + if (isMissingVariable(itemNodes[i], variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if (isNonNullType(itemType)) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(null); + } else { + var itemValue = valueFromAST(itemNodes[i], itemType, variables); + + if (isInvalid(itemValue)) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(itemValue); + } + } + + return coercedValues; + } + + var coercedValue = valueFromAST(valueNode, itemType, variables); + + if (isInvalid(coercedValue)) { + return; // Invalid: intentionally return no value. + } + + return [coercedValue]; + } + + if (isInputObjectType(type)) { + if (valueNode.kind !== Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } + + var coercedObj = Object.create(null); + var fieldNodes = keyMap(valueNode.fields, function (field) { + return field.name.value; + }); + var fields = objectValues(type.getFields()); + + for (var _i = 0; _i < fields.length; _i++) { + var field = fields[_i]; + var fieldNode = fieldNodes[field.name]; + + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if (isNonNullType(field.type)) { + return; // Invalid: intentionally return no value. + } + + continue; + } + + var fieldValue = valueFromAST(fieldNode.value, field.type, variables); + + if (isInvalid(fieldValue)) { + return; // Invalid: intentionally return no value. + } + + coercedObj[field.name] = fieldValue; + } + + return coercedObj; + } + + if (isEnumType(type)) { + if (valueNode.kind !== Kind.ENUM) { + return; // Invalid: intentionally return no value. + } + + var enumValue = type.getValue(valueNode.value); + + if (!enumValue) { + return; // Invalid: intentionally return no value. + } + + return enumValue.value; + } + + if (isScalarType(type)) { + // Scalars fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + var result; + + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. + } + + if (isInvalid(result)) { + return; // Invalid: intentionally return no value. + } + + return result; + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} // Returns true if the provided valueNode is a variable which is not defined +// in the set of variables. + +function isMissingVariable(valueNode, variables) { + return valueNode.kind === Kind.VARIABLE && (!variables || isInvalid(variables[valueNode.name.value])); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/valueFromASTUntyped.js b/node_modules/graphql/utilities/valueFromASTUntyped.js new file mode 100644 index 0000000..8c289b5 --- /dev/null +++ b/node_modules/graphql/utilities/valueFromASTUntyped.js @@ -0,0 +1,77 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.valueFromASTUntyped = valueFromASTUntyped; + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _kinds = require("../language/kinds"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value + * will reflect the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * + */ +function valueFromASTUntyped(valueNode, variables) { + switch (valueNode.kind) { + case _kinds.Kind.NULL: + return null; + + case _kinds.Kind.INT: + return parseInt(valueNode.value, 10); + + case _kinds.Kind.FLOAT: + return parseFloat(valueNode.value); + + case _kinds.Kind.STRING: + case _kinds.Kind.ENUM: + case _kinds.Kind.BOOLEAN: + return valueNode.value; + + case _kinds.Kind.LIST: + return valueNode.values.map(function (node) { + return valueFromASTUntyped(node, variables); + }); + + case _kinds.Kind.OBJECT: + return (0, _keyValMap.default)(valueNode.fields, function (field) { + return field.name.value; + }, function (field) { + return valueFromASTUntyped(field.value, variables); + }); + + case _kinds.Kind.VARIABLE: + var variableName = valueNode.name.value; + return variables && !(0, _isInvalid.default)(variables[variableName]) ? variables[variableName] : undefined; + } + /* istanbul ignore next */ + + + throw new Error('Unexpected value kind: ' + valueNode.kind); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/valueFromASTUntyped.js.flow b/node_modules/graphql/utilities/valueFromASTUntyped.js.flow new file mode 100644 index 0000000..3ed6558 --- /dev/null +++ b/node_modules/graphql/utilities/valueFromASTUntyped.js.flow @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import keyValMap from '../jsutils/keyValMap'; +import isInvalid from '../jsutils/isInvalid'; +import type { ObjMap } from '../jsutils/ObjMap'; +import { Kind } from '../language/kinds'; +import type { ValueNode } from '../language/ast'; + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value + * will reflect the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * + */ +export function valueFromASTUntyped( + valueNode: ValueNode, + variables?: ?ObjMap, +): mixed { + switch (valueNode.kind) { + case Kind.NULL: + return null; + case Kind.INT: + return parseInt(valueNode.value, 10); + case Kind.FLOAT: + return parseFloat(valueNode.value); + case Kind.STRING: + case Kind.ENUM: + case Kind.BOOLEAN: + return valueNode.value; + case Kind.LIST: + return valueNode.values.map(node => valueFromASTUntyped(node, variables)); + case Kind.OBJECT: + return keyValMap( + valueNode.fields, + field => field.name.value, + field => valueFromASTUntyped(field.value, variables), + ); + case Kind.VARIABLE: + const variableName = valueNode.name.value; + return variables && !isInvalid(variables[variableName]) + ? variables[variableName] + : undefined; + } + /* istanbul ignore next */ + throw new Error('Unexpected value kind: ' + (valueNode.kind: empty)); +} diff --git a/node_modules/graphql/utilities/valueFromASTUntyped.mjs b/node_modules/graphql/utilities/valueFromASTUntyped.mjs new file mode 100644 index 0000000..2f56d73 --- /dev/null +++ b/node_modules/graphql/utilities/valueFromASTUntyped.mjs @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import keyValMap from '../jsutils/keyValMap'; +import isInvalid from '../jsutils/isInvalid'; +import { Kind } from '../language/kinds'; + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value + * will reflect the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * + */ +export function valueFromASTUntyped(valueNode, variables) { + switch (valueNode.kind) { + case Kind.NULL: + return null; + + case Kind.INT: + return parseInt(valueNode.value, 10); + + case Kind.FLOAT: + return parseFloat(valueNode.value); + + case Kind.STRING: + case Kind.ENUM: + case Kind.BOOLEAN: + return valueNode.value; + + case Kind.LIST: + return valueNode.values.map(function (node) { + return valueFromASTUntyped(node, variables); + }); + + case Kind.OBJECT: + return keyValMap(valueNode.fields, function (field) { + return field.name.value; + }, function (field) { + return valueFromASTUntyped(field.value, variables); + }); + + case Kind.VARIABLE: + var variableName = valueNode.name.value; + return variables && !isInvalid(variables[variableName]) ? variables[variableName] : undefined; + } + /* istanbul ignore next */ + + + throw new Error('Unexpected value kind: ' + valueNode.kind); +} \ No newline at end of file diff --git a/node_modules/graphql/validation/ValidationContext.js b/node_modules/graphql/validation/ValidationContext.js new file mode 100644 index 0000000..d69974f --- /dev/null +++ b/node_modules/graphql/validation/ValidationContext.js @@ -0,0 +1,272 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ValidationContext = exports.SDLValidationContext = exports.ASTValidationContext = void 0; + +var _visitor = require("../language/visitor"); + +var _kinds = require("../language/kinds"); + +var _TypeInfo = require("../utilities/TypeInfo"); + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +var ASTValidationContext = +/*#__PURE__*/ +function () { + function ASTValidationContext(ast) { + _defineProperty(this, "_ast", void 0); + + _defineProperty(this, "_errors", void 0); + + this._ast = ast; + this._errors = []; + } + + var _proto = ASTValidationContext.prototype; + + _proto.reportError = function reportError(error) { + this._errors.push(error); + }; + + _proto.getErrors = function getErrors() { + return this._errors; + }; + + _proto.getDocument = function getDocument() { + return this._ast; + }; + + return ASTValidationContext; +}(); + +exports.ASTValidationContext = ASTValidationContext; + +var SDLValidationContext = +/*#__PURE__*/ +function (_ASTValidationContext) { + _inheritsLoose(SDLValidationContext, _ASTValidationContext); + + function SDLValidationContext(ast, schema) { + var _this; + + _this = _ASTValidationContext.call(this, ast) || this; + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_schema", void 0); + + _this._schema = schema; + return _this; + } + + var _proto2 = SDLValidationContext.prototype; + + _proto2.getSchema = function getSchema() { + return this._schema; + }; + + return SDLValidationContext; +}(ASTValidationContext); + +exports.SDLValidationContext = SDLValidationContext; + +var ValidationContext = +/*#__PURE__*/ +function (_ASTValidationContext2) { + _inheritsLoose(ValidationContext, _ASTValidationContext2); + + function ValidationContext(schema, ast, typeInfo) { + var _this2; + + _this2 = _ASTValidationContext2.call(this, ast) || this; + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_schema", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_typeInfo", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_fragments", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_fragmentSpreads", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_recursivelyReferencedFragments", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_variableUsages", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_recursiveVariableUsages", void 0); + + _this2._schema = schema; + _this2._typeInfo = typeInfo; + _this2._fragmentSpreads = new Map(); + _this2._recursivelyReferencedFragments = new Map(); + _this2._variableUsages = new Map(); + _this2._recursiveVariableUsages = new Map(); + return _this2; + } + + var _proto3 = ValidationContext.prototype; + + _proto3.getSchema = function getSchema() { + return this._schema; + }; + + _proto3.getFragment = function getFragment(name) { + var fragments = this._fragments; + + if (!fragments) { + this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) { + if (statement.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + frags[statement.name.value] = statement; + } + + return frags; + }, Object.create(null)); + } + + return fragments[name]; + }; + + _proto3.getFragmentSpreads = function getFragmentSpreads(node) { + var spreads = this._fragmentSpreads.get(node); + + if (!spreads) { + spreads = []; + var setsToVisit = [node]; + + while (setsToVisit.length !== 0) { + var set = setsToVisit.pop(); + + for (var i = 0; i < set.selections.length; i++) { + var selection = set.selections[i]; + + if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + + this._fragmentSpreads.set(node, spreads); + } + + return spreads; + }; + + _proto3.getRecursivelyReferencedFragments = function getRecursivelyReferencedFragments(operation) { + var fragments = this._recursivelyReferencedFragments.get(operation); + + if (!fragments) { + fragments = []; + var collectedNames = Object.create(null); + var nodesToVisit = [operation.selectionSet]; + + while (nodesToVisit.length !== 0) { + var node = nodesToVisit.pop(); + var spreads = this.getFragmentSpreads(node); + + for (var i = 0; i < spreads.length; i++) { + var fragName = spreads[i].name.value; + + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + var fragment = this.getFragment(fragName); + + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + + this._recursivelyReferencedFragments.set(operation, fragments); + } + + return fragments; + }; + + _proto3.getVariableUsages = function getVariableUsages(node) { + var usages = this._variableUsages.get(node); + + if (!usages) { + var newUsages = []; + var typeInfo = new _TypeInfo.TypeInfo(this._schema); + (0, _visitor.visit)(node, (0, _visitor.visitWithTypeInfo)(typeInfo, { + VariableDefinition: function VariableDefinition() { + return false; + }, + Variable: function Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue() + }); + } + })); + usages = newUsages; + + this._variableUsages.set(node, usages); + } + + return usages; + }; + + _proto3.getRecursiveVariableUsages = function getRecursiveVariableUsages(operation) { + var usages = this._recursiveVariableUsages.get(operation); + + if (!usages) { + usages = this.getVariableUsages(operation); + var fragments = this.getRecursivelyReferencedFragments(operation); + + for (var i = 0; i < fragments.length; i++) { + Array.prototype.push.apply(usages, this.getVariableUsages(fragments[i])); + } + + this._recursiveVariableUsages.set(operation, usages); + } + + return usages; + }; + + _proto3.getType = function getType() { + return this._typeInfo.getType(); + }; + + _proto3.getParentType = function getParentType() { + return this._typeInfo.getParentType(); + }; + + _proto3.getInputType = function getInputType() { + return this._typeInfo.getInputType(); + }; + + _proto3.getParentInputType = function getParentInputType() { + return this._typeInfo.getParentInputType(); + }; + + _proto3.getFieldDef = function getFieldDef() { + return this._typeInfo.getFieldDef(); + }; + + _proto3.getDirective = function getDirective() { + return this._typeInfo.getDirective(); + }; + + _proto3.getArgument = function getArgument() { + return this._typeInfo.getArgument(); + }; + + return ValidationContext; +}(ASTValidationContext); + +exports.ValidationContext = ValidationContext; \ No newline at end of file diff --git a/node_modules/graphql/validation/ValidationContext.js.flow b/node_modules/graphql/validation/ValidationContext.js.flow new file mode 100644 index 0000000..27b5243 --- /dev/null +++ b/node_modules/graphql/validation/ValidationContext.js.flow @@ -0,0 +1,254 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from '../jsutils/ObjMap'; +import type { GraphQLError } from '../error'; +import { visit, visitWithTypeInfo } from '../language/visitor'; +import { Kind } from '../language/kinds'; +import type { + DocumentNode, + OperationDefinitionNode, + VariableNode, + SelectionSetNode, + FragmentSpreadNode, + FragmentDefinitionNode, +} from '../language/ast'; +import type { ASTVisitor } from '../language/visitor'; +import type { GraphQLSchema } from '../type/schema'; +import type { + GraphQLInputType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, + GraphQLArgument, +} from '../type/definition'; +import type { GraphQLDirective } from '../type/directives'; +import { TypeInfo } from '../utilities/TypeInfo'; + +type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; +type VariableUsage = {| + +node: VariableNode, + +type: ?GraphQLInputType, + +defaultValue: ?mixed, +|}; + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +export class ASTValidationContext { + _ast: DocumentNode; + _errors: Array; + + constructor(ast: DocumentNode): void { + this._ast = ast; + this._errors = []; + } + + reportError(error: GraphQLError): void { + this._errors.push(error); + } + + getErrors(): $ReadOnlyArray { + return this._errors; + } + + getDocument(): DocumentNode { + return this._ast; + } +} + +export class SDLValidationContext extends ASTValidationContext { + _schema: ?GraphQLSchema; + + constructor(ast: DocumentNode, schema?: ?GraphQLSchema): void { + super(ast); + this._schema = schema; + } + + getSchema(): ?GraphQLSchema { + return this._schema; + } +} + +export type SDLValidationRule = SDLValidationContext => ASTVisitor; + +export class ValidationContext extends ASTValidationContext { + _schema: GraphQLSchema; + _typeInfo: TypeInfo; + _fragments: ObjMap; + _fragmentSpreads: Map>; + _recursivelyReferencedFragments: Map< + OperationDefinitionNode, + $ReadOnlyArray, + >; + _variableUsages: Map>; + _recursiveVariableUsages: Map< + OperationDefinitionNode, + $ReadOnlyArray, + >; + + constructor( + schema: GraphQLSchema, + ast: DocumentNode, + typeInfo: TypeInfo, + ): void { + super(ast); + this._schema = schema; + this._typeInfo = typeInfo; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._variableUsages = new Map(); + this._recursiveVariableUsages = new Map(); + } + + getSchema(): GraphQLSchema { + return this._schema; + } + + getFragment(name: string): ?FragmentDefinitionNode { + let fragments = this._fragments; + if (!fragments) { + this._fragments = fragments = this.getDocument().definitions.reduce( + (frags, statement) => { + if (statement.kind === Kind.FRAGMENT_DEFINITION) { + frags[statement.name.value] = statement; + } + return frags; + }, + Object.create(null), + ); + } + return fragments[name]; + } + + getFragmentSpreads( + node: SelectionSetNode, + ): $ReadOnlyArray { + let spreads = this._fragmentSpreads.get(node); + if (!spreads) { + spreads = []; + const setsToVisit: Array = [node]; + while (setsToVisit.length !== 0) { + const set = setsToVisit.pop(); + for (let i = 0; i < set.selections.length; i++) { + const selection = set.selections[i]; + if (selection.kind === Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + this._fragmentSpreads.set(node, spreads); + } + return spreads; + } + + getRecursivelyReferencedFragments( + operation: OperationDefinitionNode, + ): $ReadOnlyArray { + let fragments = this._recursivelyReferencedFragments.get(operation); + if (!fragments) { + fragments = []; + const collectedNames = Object.create(null); + const nodesToVisit: Array = [operation.selectionSet]; + while (nodesToVisit.length !== 0) { + const node = nodesToVisit.pop(); + const spreads = this.getFragmentSpreads(node); + for (let i = 0; i < spreads.length; i++) { + const fragName = spreads[i].name.value; + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + const fragment = this.getFragment(fragName); + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + this._recursivelyReferencedFragments.set(operation, fragments); + } + return fragments; + } + + getVariableUsages(node: NodeWithSelectionSet): $ReadOnlyArray { + let usages = this._variableUsages.get(node); + if (!usages) { + const newUsages = []; + const typeInfo = new TypeInfo(this._schema); + visit( + node, + visitWithTypeInfo(typeInfo, { + VariableDefinition: () => false, + Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue(), + }); + }, + }), + ); + usages = newUsages; + this._variableUsages.set(node, usages); + } + return usages; + } + + getRecursiveVariableUsages( + operation: OperationDefinitionNode, + ): $ReadOnlyArray { + let usages = this._recursiveVariableUsages.get(operation); + if (!usages) { + usages = this.getVariableUsages(operation); + const fragments = this.getRecursivelyReferencedFragments(operation); + for (let i = 0; i < fragments.length; i++) { + Array.prototype.push.apply( + usages, + this.getVariableUsages(fragments[i]), + ); + } + this._recursiveVariableUsages.set(operation, usages); + } + return usages; + } + + getType(): ?GraphQLOutputType { + return this._typeInfo.getType(); + } + + getParentType(): ?GraphQLCompositeType { + return this._typeInfo.getParentType(); + } + + getInputType(): ?GraphQLInputType { + return this._typeInfo.getInputType(); + } + + getParentInputType(): ?GraphQLInputType { + return this._typeInfo.getParentInputType(); + } + + getFieldDef(): ?GraphQLField<*, *> { + return this._typeInfo.getFieldDef(); + } + + getDirective(): ?GraphQLDirective { + return this._typeInfo.getDirective(); + } + + getArgument(): ?GraphQLArgument { + return this._typeInfo.getArgument(); + } +} + +export type ValidationRule = ValidationContext => ASTVisitor; diff --git a/node_modules/graphql/validation/ValidationContext.mjs b/node_modules/graphql/validation/ValidationContext.mjs new file mode 100644 index 0000000..f415073 --- /dev/null +++ b/node_modules/graphql/validation/ValidationContext.mjs @@ -0,0 +1,263 @@ +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { visit, visitWithTypeInfo } from '../language/visitor'; +import { Kind } from '../language/kinds'; +import { TypeInfo } from '../utilities/TypeInfo'; + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +export var ASTValidationContext = +/*#__PURE__*/ +function () { + function ASTValidationContext(ast) { + _defineProperty(this, "_ast", void 0); + + _defineProperty(this, "_errors", void 0); + + this._ast = ast; + this._errors = []; + } + + var _proto = ASTValidationContext.prototype; + + _proto.reportError = function reportError(error) { + this._errors.push(error); + }; + + _proto.getErrors = function getErrors() { + return this._errors; + }; + + _proto.getDocument = function getDocument() { + return this._ast; + }; + + return ASTValidationContext; +}(); +export var SDLValidationContext = +/*#__PURE__*/ +function (_ASTValidationContext) { + _inheritsLoose(SDLValidationContext, _ASTValidationContext); + + function SDLValidationContext(ast, schema) { + var _this; + + _this = _ASTValidationContext.call(this, ast) || this; + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_schema", void 0); + + _this._schema = schema; + return _this; + } + + var _proto2 = SDLValidationContext.prototype; + + _proto2.getSchema = function getSchema() { + return this._schema; + }; + + return SDLValidationContext; +}(ASTValidationContext); +export var ValidationContext = +/*#__PURE__*/ +function (_ASTValidationContext2) { + _inheritsLoose(ValidationContext, _ASTValidationContext2); + + function ValidationContext(schema, ast, typeInfo) { + var _this2; + + _this2 = _ASTValidationContext2.call(this, ast) || this; + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_schema", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_typeInfo", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_fragments", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_fragmentSpreads", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_recursivelyReferencedFragments", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_variableUsages", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_recursiveVariableUsages", void 0); + + _this2._schema = schema; + _this2._typeInfo = typeInfo; + _this2._fragmentSpreads = new Map(); + _this2._recursivelyReferencedFragments = new Map(); + _this2._variableUsages = new Map(); + _this2._recursiveVariableUsages = new Map(); + return _this2; + } + + var _proto3 = ValidationContext.prototype; + + _proto3.getSchema = function getSchema() { + return this._schema; + }; + + _proto3.getFragment = function getFragment(name) { + var fragments = this._fragments; + + if (!fragments) { + this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) { + if (statement.kind === Kind.FRAGMENT_DEFINITION) { + frags[statement.name.value] = statement; + } + + return frags; + }, Object.create(null)); + } + + return fragments[name]; + }; + + _proto3.getFragmentSpreads = function getFragmentSpreads(node) { + var spreads = this._fragmentSpreads.get(node); + + if (!spreads) { + spreads = []; + var setsToVisit = [node]; + + while (setsToVisit.length !== 0) { + var set = setsToVisit.pop(); + + for (var i = 0; i < set.selections.length; i++) { + var selection = set.selections[i]; + + if (selection.kind === Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + + this._fragmentSpreads.set(node, spreads); + } + + return spreads; + }; + + _proto3.getRecursivelyReferencedFragments = function getRecursivelyReferencedFragments(operation) { + var fragments = this._recursivelyReferencedFragments.get(operation); + + if (!fragments) { + fragments = []; + var collectedNames = Object.create(null); + var nodesToVisit = [operation.selectionSet]; + + while (nodesToVisit.length !== 0) { + var node = nodesToVisit.pop(); + var spreads = this.getFragmentSpreads(node); + + for (var i = 0; i < spreads.length; i++) { + var fragName = spreads[i].name.value; + + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + var fragment = this.getFragment(fragName); + + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + + this._recursivelyReferencedFragments.set(operation, fragments); + } + + return fragments; + }; + + _proto3.getVariableUsages = function getVariableUsages(node) { + var usages = this._variableUsages.get(node); + + if (!usages) { + var newUsages = []; + var typeInfo = new TypeInfo(this._schema); + visit(node, visitWithTypeInfo(typeInfo, { + VariableDefinition: function VariableDefinition() { + return false; + }, + Variable: function Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue() + }); + } + })); + usages = newUsages; + + this._variableUsages.set(node, usages); + } + + return usages; + }; + + _proto3.getRecursiveVariableUsages = function getRecursiveVariableUsages(operation) { + var usages = this._recursiveVariableUsages.get(operation); + + if (!usages) { + usages = this.getVariableUsages(operation); + var fragments = this.getRecursivelyReferencedFragments(operation); + + for (var i = 0; i < fragments.length; i++) { + Array.prototype.push.apply(usages, this.getVariableUsages(fragments[i])); + } + + this._recursiveVariableUsages.set(operation, usages); + } + + return usages; + }; + + _proto3.getType = function getType() { + return this._typeInfo.getType(); + }; + + _proto3.getParentType = function getParentType() { + return this._typeInfo.getParentType(); + }; + + _proto3.getInputType = function getInputType() { + return this._typeInfo.getInputType(); + }; + + _proto3.getParentInputType = function getParentInputType() { + return this._typeInfo.getParentInputType(); + }; + + _proto3.getFieldDef = function getFieldDef() { + return this._typeInfo.getFieldDef(); + }; + + _proto3.getDirective = function getDirective() { + return this._typeInfo.getDirective(); + }; + + _proto3.getArgument = function getArgument() { + return this._typeInfo.getArgument(); + }; + + return ValidationContext; +}(ASTValidationContext); \ No newline at end of file diff --git a/node_modules/graphql/validation/index.js b/node_modules/graphql/validation/index.js new file mode 100644 index 0000000..f981d60 --- /dev/null +++ b/node_modules/graphql/validation/index.js @@ -0,0 +1,229 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function get() { + return _validate.validate; + } +}); +Object.defineProperty(exports, "ValidationContext", { + enumerable: true, + get: function get() { + return _ValidationContext.ValidationContext; + } +}); +Object.defineProperty(exports, "specifiedRules", { + enumerable: true, + get: function get() { + return _specifiedRules.specifiedRules; + } +}); +Object.defineProperty(exports, "FieldsOnCorrectTypeRule", { + enumerable: true, + get: function get() { + return _FieldsOnCorrectType.FieldsOnCorrectType; + } +}); +Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", { + enumerable: true, + get: function get() { + return _FragmentsOnCompositeTypes.FragmentsOnCompositeTypes; + } +}); +Object.defineProperty(exports, "KnownArgumentNamesRule", { + enumerable: true, + get: function get() { + return _KnownArgumentNames.KnownArgumentNames; + } +}); +Object.defineProperty(exports, "KnownDirectivesRule", { + enumerable: true, + get: function get() { + return _KnownDirectives.KnownDirectives; + } +}); +Object.defineProperty(exports, "KnownFragmentNamesRule", { + enumerable: true, + get: function get() { + return _KnownFragmentNames.KnownFragmentNames; + } +}); +Object.defineProperty(exports, "KnownTypeNamesRule", { + enumerable: true, + get: function get() { + return _KnownTypeNames.KnownTypeNames; + } +}); +Object.defineProperty(exports, "LoneAnonymousOperationRule", { + enumerable: true, + get: function get() { + return _LoneAnonymousOperation.LoneAnonymousOperation; + } +}); +Object.defineProperty(exports, "NoFragmentCyclesRule", { + enumerable: true, + get: function get() { + return _NoFragmentCycles.NoFragmentCycles; + } +}); +Object.defineProperty(exports, "NoUndefinedVariablesRule", { + enumerable: true, + get: function get() { + return _NoUndefinedVariables.NoUndefinedVariables; + } +}); +Object.defineProperty(exports, "NoUnusedFragmentsRule", { + enumerable: true, + get: function get() { + return _NoUnusedFragments.NoUnusedFragments; + } +}); +Object.defineProperty(exports, "NoUnusedVariablesRule", { + enumerable: true, + get: function get() { + return _NoUnusedVariables.NoUnusedVariables; + } +}); +Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", { + enumerable: true, + get: function get() { + return _OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged; + } +}); +Object.defineProperty(exports, "PossibleFragmentSpreadsRule", { + enumerable: true, + get: function get() { + return _PossibleFragmentSpreads.PossibleFragmentSpreads; + } +}); +Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", { + enumerable: true, + get: function get() { + return _ProvidedRequiredArguments.ProvidedRequiredArguments; + } +}); +Object.defineProperty(exports, "ScalarLeafsRule", { + enumerable: true, + get: function get() { + return _ScalarLeafs.ScalarLeafs; + } +}); +Object.defineProperty(exports, "SingleFieldSubscriptionsRule", { + enumerable: true, + get: function get() { + return _SingleFieldSubscriptions.SingleFieldSubscriptions; + } +}); +Object.defineProperty(exports, "UniqueArgumentNamesRule", { + enumerable: true, + get: function get() { + return _UniqueArgumentNames.UniqueArgumentNames; + } +}); +Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", { + enumerable: true, + get: function get() { + return _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation; + } +}); +Object.defineProperty(exports, "UniqueFragmentNamesRule", { + enumerable: true, + get: function get() { + return _UniqueFragmentNames.UniqueFragmentNames; + } +}); +Object.defineProperty(exports, "UniqueInputFieldNamesRule", { + enumerable: true, + get: function get() { + return _UniqueInputFieldNames.UniqueInputFieldNames; + } +}); +Object.defineProperty(exports, "UniqueOperationNamesRule", { + enumerable: true, + get: function get() { + return _UniqueOperationNames.UniqueOperationNames; + } +}); +Object.defineProperty(exports, "UniqueVariableNamesRule", { + enumerable: true, + get: function get() { + return _UniqueVariableNames.UniqueVariableNames; + } +}); +Object.defineProperty(exports, "ValuesOfCorrectTypeRule", { + enumerable: true, + get: function get() { + return _ValuesOfCorrectType.ValuesOfCorrectType; + } +}); +Object.defineProperty(exports, "VariablesAreInputTypesRule", { + enumerable: true, + get: function get() { + return _VariablesAreInputTypes.VariablesAreInputTypes; + } +}); +Object.defineProperty(exports, "VariablesInAllowedPositionRule", { + enumerable: true, + get: function get() { + return _VariablesInAllowedPosition.VariablesInAllowedPosition; + } +}); + +var _validate = require("./validate"); + +var _ValidationContext = require("./ValidationContext"); + +var _specifiedRules = require("./specifiedRules"); + +var _FieldsOnCorrectType = require("./rules/FieldsOnCorrectType"); + +var _FragmentsOnCompositeTypes = require("./rules/FragmentsOnCompositeTypes"); + +var _KnownArgumentNames = require("./rules/KnownArgumentNames"); + +var _KnownDirectives = require("./rules/KnownDirectives"); + +var _KnownFragmentNames = require("./rules/KnownFragmentNames"); + +var _KnownTypeNames = require("./rules/KnownTypeNames"); + +var _LoneAnonymousOperation = require("./rules/LoneAnonymousOperation"); + +var _NoFragmentCycles = require("./rules/NoFragmentCycles"); + +var _NoUndefinedVariables = require("./rules/NoUndefinedVariables"); + +var _NoUnusedFragments = require("./rules/NoUnusedFragments"); + +var _NoUnusedVariables = require("./rules/NoUnusedVariables"); + +var _OverlappingFieldsCanBeMerged = require("./rules/OverlappingFieldsCanBeMerged"); + +var _PossibleFragmentSpreads = require("./rules/PossibleFragmentSpreads"); + +var _ProvidedRequiredArguments = require("./rules/ProvidedRequiredArguments"); + +var _ScalarLeafs = require("./rules/ScalarLeafs"); + +var _SingleFieldSubscriptions = require("./rules/SingleFieldSubscriptions"); + +var _UniqueArgumentNames = require("./rules/UniqueArgumentNames"); + +var _UniqueDirectivesPerLocation = require("./rules/UniqueDirectivesPerLocation"); + +var _UniqueFragmentNames = require("./rules/UniqueFragmentNames"); + +var _UniqueInputFieldNames = require("./rules/UniqueInputFieldNames"); + +var _UniqueOperationNames = require("./rules/UniqueOperationNames"); + +var _UniqueVariableNames = require("./rules/UniqueVariableNames"); + +var _ValuesOfCorrectType = require("./rules/ValuesOfCorrectType"); + +var _VariablesAreInputTypes = require("./rules/VariablesAreInputTypes"); + +var _VariablesInAllowedPosition = require("./rules/VariablesInAllowedPosition"); \ No newline at end of file diff --git a/node_modules/graphql/validation/index.js.flow b/node_modules/graphql/validation/index.js.flow new file mode 100644 index 0000000..61b0b36 --- /dev/null +++ b/node_modules/graphql/validation/index.js.flow @@ -0,0 +1,136 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { validate } from './validate'; + +export { ValidationContext } from './ValidationContext'; +export type { ValidationRule } from './ValidationContext'; + +export { specifiedRules } from './specifiedRules'; + +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +export { + FieldsOnCorrectType as FieldsOnCorrectTypeRule, +} from './rules/FieldsOnCorrectType'; + +// Spec Section: "Fragments on Composite Types" +export { + FragmentsOnCompositeTypes as FragmentsOnCompositeTypesRule, +} from './rules/FragmentsOnCompositeTypes'; + +// Spec Section: "Argument Names" +export { + KnownArgumentNames as KnownArgumentNamesRule, +} from './rules/KnownArgumentNames'; + +// Spec Section: "Directives Are Defined" +export { + KnownDirectives as KnownDirectivesRule, +} from './rules/KnownDirectives'; + +// Spec Section: "Fragment spread target defined" +export { + KnownFragmentNames as KnownFragmentNamesRule, +} from './rules/KnownFragmentNames'; + +// Spec Section: "Fragment Spread Type Existence" +export { KnownTypeNames as KnownTypeNamesRule } from './rules/KnownTypeNames'; + +// Spec Section: "Lone Anonymous Operation" +export { + LoneAnonymousOperation as LoneAnonymousOperationRule, +} from './rules/LoneAnonymousOperation'; + +// Spec Section: "Fragments must not form cycles" +export { + NoFragmentCycles as NoFragmentCyclesRule, +} from './rules/NoFragmentCycles'; + +// Spec Section: "All Variable Used Defined" +export { + NoUndefinedVariables as NoUndefinedVariablesRule, +} from './rules/NoUndefinedVariables'; + +// Spec Section: "Fragments must be used" +export { + NoUnusedFragments as NoUnusedFragmentsRule, +} from './rules/NoUnusedFragments'; + +// Spec Section: "All Variables Used" +export { + NoUnusedVariables as NoUnusedVariablesRule, +} from './rules/NoUnusedVariables'; + +// Spec Section: "Field Selection Merging" +export { + OverlappingFieldsCanBeMerged as OverlappingFieldsCanBeMergedRule, +} from './rules/OverlappingFieldsCanBeMerged'; + +// Spec Section: "Fragment spread is possible" +export { + PossibleFragmentSpreads as PossibleFragmentSpreadsRule, +} from './rules/PossibleFragmentSpreads'; + +// Spec Section: "Argument Optionality" +export { + ProvidedRequiredArguments as ProvidedRequiredArgumentsRule, +} from './rules/ProvidedRequiredArguments'; + +// Spec Section: "Leaf Field Selections" +export { ScalarLeafs as ScalarLeafsRule } from './rules/ScalarLeafs'; + +// Spec Section: "Subscriptions with Single Root Field" +export { + SingleFieldSubscriptions as SingleFieldSubscriptionsRule, +} from './rules/SingleFieldSubscriptions'; + +// Spec Section: "Argument Uniqueness" +export { + UniqueArgumentNames as UniqueArgumentNamesRule, +} from './rules/UniqueArgumentNames'; + +// Spec Section: "Directives Are Unique Per Location" +export { + UniqueDirectivesPerLocation as UniqueDirectivesPerLocationRule, +} from './rules/UniqueDirectivesPerLocation'; + +// Spec Section: "Fragment Name Uniqueness" +export { + UniqueFragmentNames as UniqueFragmentNamesRule, +} from './rules/UniqueFragmentNames'; + +// Spec Section: "Input Object Field Uniqueness" +export { + UniqueInputFieldNames as UniqueInputFieldNamesRule, +} from './rules/UniqueInputFieldNames'; + +// Spec Section: "Operation Name Uniqueness" +export { + UniqueOperationNames as UniqueOperationNamesRule, +} from './rules/UniqueOperationNames'; + +// Spec Section: "Variable Uniqueness" +export { + UniqueVariableNames as UniqueVariableNamesRule, +} from './rules/UniqueVariableNames'; + +// Spec Section: "Values Type Correctness" +export { + ValuesOfCorrectType as ValuesOfCorrectTypeRule, +} from './rules/ValuesOfCorrectType'; + +// Spec Section: "Variables are Input Types" +export { + VariablesAreInputTypes as VariablesAreInputTypesRule, +} from './rules/VariablesAreInputTypes'; + +// Spec Section: "All Variable Usages Are Allowed" +export { + VariablesInAllowedPosition as VariablesInAllowedPositionRule, +} from './rules/VariablesInAllowedPosition'; diff --git a/node_modules/graphql/validation/index.mjs b/node_modules/graphql/validation/index.mjs new file mode 100644 index 0000000..8ec3579 --- /dev/null +++ b/node_modules/graphql/validation/index.mjs @@ -0,0 +1,61 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { validate } from './validate'; +export { ValidationContext } from './ValidationContext'; +export { specifiedRules } from './specifiedRules'; // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + +export { FieldsOnCorrectType as FieldsOnCorrectTypeRule } from './rules/FieldsOnCorrectType'; // Spec Section: "Fragments on Composite Types" + +export { FragmentsOnCompositeTypes as FragmentsOnCompositeTypesRule } from './rules/FragmentsOnCompositeTypes'; // Spec Section: "Argument Names" + +export { KnownArgumentNames as KnownArgumentNamesRule } from './rules/KnownArgumentNames'; // Spec Section: "Directives Are Defined" + +export { KnownDirectives as KnownDirectivesRule } from './rules/KnownDirectives'; // Spec Section: "Fragment spread target defined" + +export { KnownFragmentNames as KnownFragmentNamesRule } from './rules/KnownFragmentNames'; // Spec Section: "Fragment Spread Type Existence" + +export { KnownTypeNames as KnownTypeNamesRule } from './rules/KnownTypeNames'; // Spec Section: "Lone Anonymous Operation" + +export { LoneAnonymousOperation as LoneAnonymousOperationRule } from './rules/LoneAnonymousOperation'; // Spec Section: "Fragments must not form cycles" + +export { NoFragmentCycles as NoFragmentCyclesRule } from './rules/NoFragmentCycles'; // Spec Section: "All Variable Used Defined" + +export { NoUndefinedVariables as NoUndefinedVariablesRule } from './rules/NoUndefinedVariables'; // Spec Section: "Fragments must be used" + +export { NoUnusedFragments as NoUnusedFragmentsRule } from './rules/NoUnusedFragments'; // Spec Section: "All Variables Used" + +export { NoUnusedVariables as NoUnusedVariablesRule } from './rules/NoUnusedVariables'; // Spec Section: "Field Selection Merging" + +export { OverlappingFieldsCanBeMerged as OverlappingFieldsCanBeMergedRule } from './rules/OverlappingFieldsCanBeMerged'; // Spec Section: "Fragment spread is possible" + +export { PossibleFragmentSpreads as PossibleFragmentSpreadsRule } from './rules/PossibleFragmentSpreads'; // Spec Section: "Argument Optionality" + +export { ProvidedRequiredArguments as ProvidedRequiredArgumentsRule } from './rules/ProvidedRequiredArguments'; // Spec Section: "Leaf Field Selections" + +export { ScalarLeafs as ScalarLeafsRule } from './rules/ScalarLeafs'; // Spec Section: "Subscriptions with Single Root Field" + +export { SingleFieldSubscriptions as SingleFieldSubscriptionsRule } from './rules/SingleFieldSubscriptions'; // Spec Section: "Argument Uniqueness" + +export { UniqueArgumentNames as UniqueArgumentNamesRule } from './rules/UniqueArgumentNames'; // Spec Section: "Directives Are Unique Per Location" + +export { UniqueDirectivesPerLocation as UniqueDirectivesPerLocationRule } from './rules/UniqueDirectivesPerLocation'; // Spec Section: "Fragment Name Uniqueness" + +export { UniqueFragmentNames as UniqueFragmentNamesRule } from './rules/UniqueFragmentNames'; // Spec Section: "Input Object Field Uniqueness" + +export { UniqueInputFieldNames as UniqueInputFieldNamesRule } from './rules/UniqueInputFieldNames'; // Spec Section: "Operation Name Uniqueness" + +export { UniqueOperationNames as UniqueOperationNamesRule } from './rules/UniqueOperationNames'; // Spec Section: "Variable Uniqueness" + +export { UniqueVariableNames as UniqueVariableNamesRule } from './rules/UniqueVariableNames'; // Spec Section: "Values Type Correctness" + +export { ValuesOfCorrectType as ValuesOfCorrectTypeRule } from './rules/ValuesOfCorrectType'; // Spec Section: "Variables are Input Types" + +export { VariablesAreInputTypes as VariablesAreInputTypesRule } from './rules/VariablesAreInputTypes'; // Spec Section: "All Variable Usages Are Allowed" + +export { VariablesInAllowedPosition as VariablesInAllowedPositionRule } from './rules/VariablesInAllowedPosition'; \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ExecutableDefinitions.js b/node_modules/graphql/validation/rules/ExecutableDefinitions.js new file mode 100644 index 0000000..a3240dc --- /dev/null +++ b/node_modules/graphql/validation/rules/ExecutableDefinitions.js @@ -0,0 +1,67 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.nonExecutableDefinitionMessage = nonExecutableDefinitionMessage; +exports.ExecutableDefinitions = ExecutableDefinitions; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _kinds = require("../../language/kinds"); + +var _predicates = require("../../language/predicates"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function nonExecutableDefinitionMessage(defName) { + return "The ".concat(defName, " definition is not executable."); +} +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + */ + + +function ExecutableDefinitions(context) { + return { + Document: function Document(node) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = node.definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var definition = _step.value; + + if (!(0, _predicates.isExecutableDefinitionNode)(definition)) { + context.reportError(new _GraphQLError.GraphQLError(nonExecutableDefinitionMessage(definition.kind === _kinds.Kind.SCHEMA_DEFINITION || definition.kind === _kinds.Kind.SCHEMA_EXTENSION ? 'schema' : definition.name.value), [definition])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ExecutableDefinitions.js.flow b/node_modules/graphql/validation/rules/ExecutableDefinitions.js.flow new file mode 100644 index 0000000..4af7ec4 --- /dev/null +++ b/node_modules/graphql/validation/rules/ExecutableDefinitions.js.flow @@ -0,0 +1,49 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import { isExecutableDefinitionNode } from '../../language/predicates'; +import type { ASTVisitor } from '../../language/visitor'; + +export function nonExecutableDefinitionMessage(defName: string): string { + return `The ${defName} definition is not executable.`; +} + +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + */ +export function ExecutableDefinitions( + context: ASTValidationContext, +): ASTVisitor { + return { + Document(node) { + for (const definition of node.definitions) { + if (!isExecutableDefinitionNode(definition)) { + context.reportError( + new GraphQLError( + nonExecutableDefinitionMessage( + definition.kind === Kind.SCHEMA_DEFINITION || + definition.kind === Kind.SCHEMA_EXTENSION + ? 'schema' + : definition.name.value, + ), + [definition], + ), + ); + } + } + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/ExecutableDefinitions.mjs b/node_modules/graphql/validation/rules/ExecutableDefinitions.mjs new file mode 100644 index 0000000..26bf753 --- /dev/null +++ b/node_modules/graphql/validation/rules/ExecutableDefinitions.mjs @@ -0,0 +1,55 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import { isExecutableDefinitionNode } from '../../language/predicates'; +export function nonExecutableDefinitionMessage(defName) { + return "The ".concat(defName, " definition is not executable."); +} +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + */ + +export function ExecutableDefinitions(context) { + return { + Document: function Document(node) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = node.definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var definition = _step.value; + + if (!isExecutableDefinitionNode(definition)) { + context.reportError(new GraphQLError(nonExecutableDefinitionMessage(definition.kind === Kind.SCHEMA_DEFINITION || definition.kind === Kind.SCHEMA_EXTENSION ? 'schema' : definition.name.value), [definition])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/FieldsOnCorrectType.js b/node_modules/graphql/validation/rules/FieldsOnCorrectType.js new file mode 100644 index 0000000..25896e7 --- /dev/null +++ b/node_modules/graphql/validation/rules/FieldsOnCorrectType.js @@ -0,0 +1,165 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.undefinedFieldMessage = undefinedFieldMessage; +exports.FieldsOnCorrectType = FieldsOnCorrectType; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList")); + +var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList")); + +var _definition = require("../../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function undefinedFieldMessage(fieldName, type, suggestedTypeNames, suggestedFieldNames) { + var message = "Cannot query field \"".concat(fieldName, "\" on type \"").concat(type, "\"."); + + if (suggestedTypeNames.length !== 0) { + var suggestions = (0, _quotedOrList.default)(suggestedTypeNames); + message += " Did you mean to use an inline fragment on ".concat(suggestions, "?"); + } else if (suggestedFieldNames.length !== 0) { + message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedFieldNames), "?"); + } + + return message; +} +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ + + +function FieldsOnCorrectType(context) { + return { + Field: function Field(node) { + var type = context.getParentType(); + + if (type) { + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + var schema = context.getSchema(); + var fieldName = node.name.value; // First determine if there are any suggested types to condition on. + + var suggestedTypeNames = getSuggestedTypeNames(schema, type, fieldName); // If there are no suggested types, then perhaps this was a typo? + + var suggestedFieldNames = suggestedTypeNames.length !== 0 ? [] : getSuggestedFieldNames(schema, type, fieldName); // Report an error, including helpful suggestions. + + context.reportError(new _GraphQLError.GraphQLError(undefinedFieldMessage(fieldName, type.name, suggestedTypeNames, suggestedFieldNames), [node])); + } + } + } + }; +} +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest + * them, sorted by how often the type is referenced, starting with Interfaces. + */ + + +function getSuggestedTypeNames(schema, type, fieldName) { + if ((0, _definition.isAbstractType)(type)) { + var suggestedObjectTypes = []; + var interfaceUsageCount = Object.create(null); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schema.getPossibleTypes(type)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var possibleType = _step.value; + + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. + + + suggestedObjectTypes.push(possibleType.name); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = possibleType.getInterfaces()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var possibleInterface = _step2.value; + + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. + + + interfaceUsageCount[possibleInterface.name] = (interfaceUsageCount[possibleInterface.name] || 0) + 1; + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } // Suggest interface types based on how common they are. + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var suggestedInterfaceTypes = Object.keys(interfaceUsageCount).sort(function (a, b) { + return interfaceUsageCount[b] - interfaceUsageCount[a]; + }); // Suggest both interface and object types. + + return suggestedInterfaceTypes.concat(suggestedObjectTypes); + } // Otherwise, must be an Object type, which does not have possible fields. + + + return []; +} +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ + + +function getSuggestedFieldNames(schema, type, fieldName) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + var possibleFieldNames = Object.keys(type.getFields()); + return (0, _suggestionList.default)(fieldName, possibleFieldNames); + } // Otherwise, must be a Union type, which does not define fields. + + + return []; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/FieldsOnCorrectType.js.flow b/node_modules/graphql/validation/rules/FieldsOnCorrectType.js.flow new file mode 100644 index 0000000..3f389a9 --- /dev/null +++ b/node_modules/graphql/validation/rules/FieldsOnCorrectType.js.flow @@ -0,0 +1,143 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +import type { FieldNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; +import type { GraphQLSchema } from '../../type/schema'; +import type { GraphQLOutputType } from '../../type/definition'; +import { + isObjectType, + isInterfaceType, + isAbstractType, +} from '../../type/definition'; + +export function undefinedFieldMessage( + fieldName: string, + type: string, + suggestedTypeNames: Array, + suggestedFieldNames: Array, +): string { + let message = `Cannot query field "${fieldName}" on type "${type}".`; + if (suggestedTypeNames.length !== 0) { + const suggestions = quotedOrList(suggestedTypeNames); + message += ` Did you mean to use an inline fragment on ${suggestions}?`; + } else if (suggestedFieldNames.length !== 0) { + message += ` Did you mean ${quotedOrList(suggestedFieldNames)}?`; + } + return message; +} + +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ +export function FieldsOnCorrectType(context: ValidationContext): ASTVisitor { + return { + Field(node: FieldNode) { + const type = context.getParentType(); + if (type) { + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + const schema = context.getSchema(); + const fieldName = node.name.value; + // First determine if there are any suggested types to condition on. + const suggestedTypeNames = getSuggestedTypeNames( + schema, + type, + fieldName, + ); + // If there are no suggested types, then perhaps this was a typo? + const suggestedFieldNames = + suggestedTypeNames.length !== 0 + ? [] + : getSuggestedFieldNames(schema, type, fieldName); + + // Report an error, including helpful suggestions. + context.reportError( + new GraphQLError( + undefinedFieldMessage( + fieldName, + type.name, + suggestedTypeNames, + suggestedFieldNames, + ), + [node], + ), + ); + } + } + }, + }; +} + +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest + * them, sorted by how often the type is referenced, starting with Interfaces. + */ +function getSuggestedTypeNames( + schema: GraphQLSchema, + type: GraphQLOutputType, + fieldName: string, +): Array { + if (isAbstractType(type)) { + const suggestedObjectTypes = []; + const interfaceUsageCount = Object.create(null); + for (const possibleType of schema.getPossibleTypes(type)) { + if (!possibleType.getFields()[fieldName]) { + continue; + } + // This object type defines this field. + suggestedObjectTypes.push(possibleType.name); + for (const possibleInterface of possibleType.getInterfaces()) { + if (!possibleInterface.getFields()[fieldName]) { + continue; + } + // This interface type defines this field. + interfaceUsageCount[possibleInterface.name] = + (interfaceUsageCount[possibleInterface.name] || 0) + 1; + } + } + + // Suggest interface types based on how common they are. + const suggestedInterfaceTypes = Object.keys(interfaceUsageCount).sort( + (a, b) => interfaceUsageCount[b] - interfaceUsageCount[a], + ); + + // Suggest both interface and object types. + return suggestedInterfaceTypes.concat(suggestedObjectTypes); + } + + // Otherwise, must be an Object type, which does not have possible fields. + return []; +} + +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ +function getSuggestedFieldNames( + schema: GraphQLSchema, + type: GraphQLOutputType, + fieldName: string, +): Array { + if (isObjectType(type) || isInterfaceType(type)) { + const possibleFieldNames = Object.keys(type.getFields()); + return suggestionList(fieldName, possibleFieldNames); + } + // Otherwise, must be a Union type, which does not define fields. + return []; +} diff --git a/node_modules/graphql/validation/rules/FieldsOnCorrectType.mjs b/node_modules/graphql/validation/rules/FieldsOnCorrectType.mjs new file mode 100644 index 0000000..3578cd3 --- /dev/null +++ b/node_modules/graphql/validation/rules/FieldsOnCorrectType.mjs @@ -0,0 +1,149 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +import { isObjectType, isInterfaceType, isAbstractType } from '../../type/definition'; +export function undefinedFieldMessage(fieldName, type, suggestedTypeNames, suggestedFieldNames) { + var message = "Cannot query field \"".concat(fieldName, "\" on type \"").concat(type, "\"."); + + if (suggestedTypeNames.length !== 0) { + var suggestions = quotedOrList(suggestedTypeNames); + message += " Did you mean to use an inline fragment on ".concat(suggestions, "?"); + } else if (suggestedFieldNames.length !== 0) { + message += " Did you mean ".concat(quotedOrList(suggestedFieldNames), "?"); + } + + return message; +} +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ + +export function FieldsOnCorrectType(context) { + return { + Field: function Field(node) { + var type = context.getParentType(); + + if (type) { + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + var schema = context.getSchema(); + var fieldName = node.name.value; // First determine if there are any suggested types to condition on. + + var suggestedTypeNames = getSuggestedTypeNames(schema, type, fieldName); // If there are no suggested types, then perhaps this was a typo? + + var suggestedFieldNames = suggestedTypeNames.length !== 0 ? [] : getSuggestedFieldNames(schema, type, fieldName); // Report an error, including helpful suggestions. + + context.reportError(new GraphQLError(undefinedFieldMessage(fieldName, type.name, suggestedTypeNames, suggestedFieldNames), [node])); + } + } + } + }; +} +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest + * them, sorted by how often the type is referenced, starting with Interfaces. + */ + +function getSuggestedTypeNames(schema, type, fieldName) { + if (isAbstractType(type)) { + var suggestedObjectTypes = []; + var interfaceUsageCount = Object.create(null); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schema.getPossibleTypes(type)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var possibleType = _step.value; + + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. + + + suggestedObjectTypes.push(possibleType.name); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = possibleType.getInterfaces()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var possibleInterface = _step2.value; + + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. + + + interfaceUsageCount[possibleInterface.name] = (interfaceUsageCount[possibleInterface.name] || 0) + 1; + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } // Suggest interface types based on how common they are. + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var suggestedInterfaceTypes = Object.keys(interfaceUsageCount).sort(function (a, b) { + return interfaceUsageCount[b] - interfaceUsageCount[a]; + }); // Suggest both interface and object types. + + return suggestedInterfaceTypes.concat(suggestedObjectTypes); + } // Otherwise, must be an Object type, which does not have possible fields. + + + return []; +} +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ + + +function getSuggestedFieldNames(schema, type, fieldName) { + if (isObjectType(type) || isInterfaceType(type)) { + var possibleFieldNames = Object.keys(type.getFields()); + return suggestionList(fieldName, possibleFieldNames); + } // Otherwise, must be a Union type, which does not define fields. + + + return []; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js new file mode 100644 index 0000000..466b90e --- /dev/null +++ b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js @@ -0,0 +1,63 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.inlineFragmentOnNonCompositeErrorMessage = inlineFragmentOnNonCompositeErrorMessage; +exports.fragmentOnNonCompositeErrorMessage = fragmentOnNonCompositeErrorMessage; +exports.FragmentsOnCompositeTypes = FragmentsOnCompositeTypes; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _printer = require("../../language/printer"); + +var _definition = require("../../type/definition"); + +var _typeFromAST = require("../../utilities/typeFromAST"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function inlineFragmentOnNonCompositeErrorMessage(type) { + return "Fragment cannot condition on non composite type \"".concat(type, "\"."); +} + +function fragmentOnNonCompositeErrorMessage(fragName, type) { + return "Fragment \"".concat(fragName, "\" cannot condition on non composite ") + "type \"".concat(type, "\"."); +} +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ + + +function FragmentsOnCompositeTypes(context) { + return { + InlineFragment: function InlineFragment(node) { + var typeCondition = node.typeCondition; + + if (typeCondition) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition); + + if (type && !(0, _definition.isCompositeType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(inlineFragmentOnNonCompositeErrorMessage((0, _printer.print)(typeCondition)), [typeCondition])); + } + } + }, + FragmentDefinition: function FragmentDefinition(node) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition); + + if (type && !(0, _definition.isCompositeType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(fragmentOnNonCompositeErrorMessage(node.name.value, (0, _printer.print)(node.typeCondition)), [node.typeCondition])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js.flow b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js.flow new file mode 100644 index 0000000..f103e03 --- /dev/null +++ b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js.flow @@ -0,0 +1,71 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { print } from '../../language/printer'; +import type { ASTVisitor } from '../../language/visitor'; +import { isCompositeType } from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; + +export function inlineFragmentOnNonCompositeErrorMessage(type: string): string { + return `Fragment cannot condition on non composite type "${type}".`; +} + +export function fragmentOnNonCompositeErrorMessage( + fragName: string, + type: string, +): string { + return ( + `Fragment "${fragName}" cannot condition on non composite ` + + `type "${type}".` + ); +} + +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ +export function FragmentsOnCompositeTypes( + context: ValidationContext, +): ASTVisitor { + return { + InlineFragment(node) { + const typeCondition = node.typeCondition; + if (typeCondition) { + const type = typeFromAST(context.getSchema(), typeCondition); + if (type && !isCompositeType(type)) { + context.reportError( + new GraphQLError( + inlineFragmentOnNonCompositeErrorMessage(print(typeCondition)), + [typeCondition], + ), + ); + } + } + }, + FragmentDefinition(node) { + const type = typeFromAST(context.getSchema(), node.typeCondition); + if (type && !isCompositeType(type)) { + context.reportError( + new GraphQLError( + fragmentOnNonCompositeErrorMessage( + node.name.value, + print(node.typeCondition), + ), + [node.typeCondition], + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.mjs b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.mjs new file mode 100644 index 0000000..df073ff --- /dev/null +++ b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.mjs @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { print } from '../../language/printer'; +import { isCompositeType } from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; +export function inlineFragmentOnNonCompositeErrorMessage(type) { + return "Fragment cannot condition on non composite type \"".concat(type, "\"."); +} +export function fragmentOnNonCompositeErrorMessage(fragName, type) { + return "Fragment \"".concat(fragName, "\" cannot condition on non composite ") + "type \"".concat(type, "\"."); +} +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ + +export function FragmentsOnCompositeTypes(context) { + return { + InlineFragment: function InlineFragment(node) { + var typeCondition = node.typeCondition; + + if (typeCondition) { + var type = typeFromAST(context.getSchema(), typeCondition); + + if (type && !isCompositeType(type)) { + context.reportError(new GraphQLError(inlineFragmentOnNonCompositeErrorMessage(print(typeCondition)), [typeCondition])); + } + } + }, + FragmentDefinition: function FragmentDefinition(node) { + var type = typeFromAST(context.getSchema(), node.typeCondition); + + if (type && !isCompositeType(type)) { + context.reportError(new GraphQLError(fragmentOnNonCompositeErrorMessage(node.name.value, print(node.typeCondition)), [node.typeCondition])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownArgumentNames.js b/node_modules/graphql/validation/rules/KnownArgumentNames.js new file mode 100644 index 0000000..62cab65 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownArgumentNames.js @@ -0,0 +1,172 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownArgMessage = unknownArgMessage; +exports.unknownDirectiveArgMessage = unknownDirectiveArgMessage; +exports.KnownArgumentNames = KnownArgumentNames; +exports.KnownArgumentNamesOnDirectives = KnownArgumentNamesOnDirectives; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList")); + +var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList")); + +var _kinds = require("../../language/kinds"); + +var _directives = require("../../type/directives"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function unknownArgMessage(argName, fieldName, typeName, suggestedArgs) { + var message = "Unknown argument \"".concat(argName, "\" on field \"").concat(fieldName, "\" of ") + "type \"".concat(typeName, "\"."); + + if (suggestedArgs.length) { + message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedArgs), "?"); + } + + return message; +} + +function unknownDirectiveArgMessage(argName, directiveName, suggestedArgs) { + var message = "Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\"."); + + if (suggestedArgs.length) { + message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedArgs), "?"); + } + + return message; +} +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ + + +function KnownArgumentNames(context) { + return _objectSpread({}, KnownArgumentNamesOnDirectives(context), { + Argument: function Argument(argNode) { + var argDef = context.getArgument(); + var fieldDef = context.getFieldDef(); + var parentType = context.getParentType(); + + if (!argDef && fieldDef && parentType) { + var argName = argNode.name.value; + var knownArgsNames = fieldDef.args.map(function (arg) { + return arg.name; + }); + context.reportError(new _GraphQLError.GraphQLError(unknownArgMessage(argName, fieldDef.name, parentType.name, (0, _suggestionList.default)(argName, knownArgsNames)), argNode)); + } + } + }); +} // @internal + + +function KnownArgumentNamesOnDirectives(context) { + var directiveArgs = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + directiveArgs[directive.name] = directive.args.map(function (arg) { + return arg.name; + }); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var def = _step2.value; + + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + directiveArgs[def.name.value] = def.arguments ? def.arguments.map(function (arg) { + return arg.name.value; + }) : []; + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return { + Directive: function Directive(directiveNode) { + var directiveName = directiveNode.name.value; + var knownArgs = directiveArgs[directiveName]; + + if (directiveNode.arguments && knownArgs) { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = directiveNode.arguments[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var argNode = _step3.value; + var argName = argNode.name.value; + + if (knownArgs.indexOf(argName) === -1) { + var suggestions = (0, _suggestionList.default)(argName, knownArgs); + context.reportError(new _GraphQLError.GraphQLError(unknownDirectiveArgMessage(argName, directiveName, suggestions), argNode)); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownArgumentNames.js.flow b/node_modules/graphql/validation/rules/KnownArgumentNames.js.flow new file mode 100644 index 0000000..4c69bb8 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownArgumentNames.js.flow @@ -0,0 +1,127 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { + ValidationContext, + SDLValidationContext, +} from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +import { Kind } from '../../language/kinds'; +import { specifiedDirectives } from '../../type/directives'; + +export function unknownArgMessage( + argName: string, + fieldName: string, + typeName: string, + suggestedArgs: Array, +): string { + let message = + `Unknown argument "${argName}" on field "${fieldName}" of ` + + `type "${typeName}".`; + if (suggestedArgs.length) { + message += ` Did you mean ${quotedOrList(suggestedArgs)}?`; + } + return message; +} + +export function unknownDirectiveArgMessage( + argName: string, + directiveName: string, + suggestedArgs: Array, +): string { + let message = `Unknown argument "${argName}" on directive "@${directiveName}".`; + if (suggestedArgs.length) { + message += ` Did you mean ${quotedOrList(suggestedArgs)}?`; + } + return message; +} + +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ +export function KnownArgumentNames(context: ValidationContext): ASTVisitor { + return { + ...KnownArgumentNamesOnDirectives(context), + Argument(argNode) { + const argDef = context.getArgument(); + const fieldDef = context.getFieldDef(); + const parentType = context.getParentType(); + + if (!argDef && fieldDef && parentType) { + const argName = argNode.name.value; + const knownArgsNames = fieldDef.args.map(arg => arg.name); + context.reportError( + new GraphQLError( + unknownArgMessage( + argName, + fieldDef.name, + parentType.name, + suggestionList(argName, knownArgsNames), + ), + argNode, + ), + ); + } + }, + }; +} + +// @internal +export function KnownArgumentNamesOnDirectives( + context: ValidationContext | SDLValidationContext, +): ASTVisitor { + const directiveArgs = Object.create(null); + + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + for (const directive of definedDirectives) { + directiveArgs[directive.name] = directive.args.map(arg => arg.name); + } + + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + directiveArgs[def.name.value] = def.arguments + ? def.arguments.map(arg => arg.name.value) + : []; + } + } + + return { + Directive(directiveNode) { + const directiveName = directiveNode.name.value; + const knownArgs = directiveArgs[directiveName]; + + if (directiveNode.arguments && knownArgs) { + for (const argNode of directiveNode.arguments) { + const argName = argNode.name.value; + if (knownArgs.indexOf(argName) === -1) { + const suggestions = suggestionList(argName, knownArgs); + context.reportError( + new GraphQLError( + unknownDirectiveArgMessage(argName, directiveName, suggestions), + argNode, + ), + ); + } + } + } + + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/KnownArgumentNames.mjs b/node_modules/graphql/validation/rules/KnownArgumentNames.mjs new file mode 100644 index 0000000..0a13214 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownArgumentNames.mjs @@ -0,0 +1,160 @@ +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +import { Kind } from '../../language/kinds'; +import { specifiedDirectives } from '../../type/directives'; +export function unknownArgMessage(argName, fieldName, typeName, suggestedArgs) { + var message = "Unknown argument \"".concat(argName, "\" on field \"").concat(fieldName, "\" of ") + "type \"".concat(typeName, "\"."); + + if (suggestedArgs.length) { + message += " Did you mean ".concat(quotedOrList(suggestedArgs), "?"); + } + + return message; +} +export function unknownDirectiveArgMessage(argName, directiveName, suggestedArgs) { + var message = "Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\"."); + + if (suggestedArgs.length) { + message += " Did you mean ".concat(quotedOrList(suggestedArgs), "?"); + } + + return message; +} +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ + +export function KnownArgumentNames(context) { + return _objectSpread({}, KnownArgumentNamesOnDirectives(context), { + Argument: function Argument(argNode) { + var argDef = context.getArgument(); + var fieldDef = context.getFieldDef(); + var parentType = context.getParentType(); + + if (!argDef && fieldDef && parentType) { + var argName = argNode.name.value; + var knownArgsNames = fieldDef.args.map(function (arg) { + return arg.name; + }); + context.reportError(new GraphQLError(unknownArgMessage(argName, fieldDef.name, parentType.name, suggestionList(argName, knownArgsNames)), argNode)); + } + } + }); +} // @internal + +export function KnownArgumentNamesOnDirectives(context) { + var directiveArgs = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + directiveArgs[directive.name] = directive.args.map(function (arg) { + return arg.name; + }); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var def = _step2.value; + + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + directiveArgs[def.name.value] = def.arguments ? def.arguments.map(function (arg) { + return arg.name.value; + }) : []; + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return { + Directive: function Directive(directiveNode) { + var directiveName = directiveNode.name.value; + var knownArgs = directiveArgs[directiveName]; + + if (directiveNode.arguments && knownArgs) { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = directiveNode.arguments[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var argNode = _step3.value; + var argName = argNode.name.value; + + if (knownArgs.indexOf(argName) === -1) { + var suggestions = suggestionList(argName, knownArgs); + context.reportError(new GraphQLError(unknownDirectiveArgMessage(argName, directiveName, suggestions), argNode)); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownDirectives.js b/node_modules/graphql/validation/rules/KnownDirectives.js new file mode 100644 index 0000000..e73cc88 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownDirectives.js @@ -0,0 +1,191 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownDirectiveMessage = unknownDirectiveMessage; +exports.misplacedDirectiveMessage = misplacedDirectiveMessage; +exports.KnownDirectives = KnownDirectives; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _kinds = require("../../language/kinds"); + +var _directiveLocation = require("../../language/directiveLocation"); + +var _directives = require("../../type/directives"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function unknownDirectiveMessage(directiveName) { + return "Unknown directive \"".concat(directiveName, "\"."); +} + +function misplacedDirectiveMessage(directiveName, location) { + return "Directive \"".concat(directiveName, "\" may not be used on ").concat(location, "."); +} +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ + + +function KnownDirectives(context) { + var locationsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + locationsMap[directive.name] = directive.locations; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var def = _step2.value; + + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map(function (name) { + return name.value; + }); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return { + Directive: function Directive(node, key, parent, path, ancestors) { + var name = node.name.value; + var locations = locationsMap[name]; + + if (!locations) { + context.reportError(new _GraphQLError.GraphQLError(unknownDirectiveMessage(name), [node])); + return; + } + + var candidateLocation = getDirectiveLocationForASTPath(ancestors); + + if (candidateLocation && locations.indexOf(candidateLocation) === -1) { + context.reportError(new _GraphQLError.GraphQLError(misplacedDirectiveMessage(name, candidateLocation), [node])); + } + } + }; +} + +function getDirectiveLocationForASTPath(ancestors) { + var appliedTo = ancestors[ancestors.length - 1]; + + if (!Array.isArray(appliedTo)) { + switch (appliedTo.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + switch (appliedTo.operation) { + case 'query': + return _directiveLocation.DirectiveLocation.QUERY; + + case 'mutation': + return _directiveLocation.DirectiveLocation.MUTATION; + + case 'subscription': + return _directiveLocation.DirectiveLocation.SUBSCRIPTION; + } + + break; + + case _kinds.Kind.FIELD: + return _directiveLocation.DirectiveLocation.FIELD; + + case _kinds.Kind.FRAGMENT_SPREAD: + return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD; + + case _kinds.Kind.INLINE_FRAGMENT: + return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT; + + case _kinds.Kind.FRAGMENT_DEFINITION: + return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION; + + case _kinds.Kind.VARIABLE_DEFINITION: + return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION; + + case _kinds.Kind.SCHEMA_DEFINITION: + case _kinds.Kind.SCHEMA_EXTENSION: + return _directiveLocation.DirectiveLocation.SCHEMA; + + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.SCALAR; + + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.OBJECT; + + case _kinds.Kind.FIELD_DEFINITION: + return _directiveLocation.DirectiveLocation.FIELD_DEFINITION; + + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INTERFACE; + + case _kinds.Kind.UNION_TYPE_DEFINITION: + case _kinds.Kind.UNION_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.UNION; + + case _kinds.Kind.ENUM_TYPE_DEFINITION: + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.ENUM; + + case _kinds.Kind.ENUM_VALUE_DEFINITION: + return _directiveLocation.DirectiveLocation.ENUM_VALUE; + + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INPUT_OBJECT; + + case _kinds.Kind.INPUT_VALUE_DEFINITION: + var parentNode = ancestors[ancestors.length - 3]; + return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownDirectives.js.flow b/node_modules/graphql/validation/rules/KnownDirectives.js.flow new file mode 100644 index 0000000..52c9a7b --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownDirectives.js.flow @@ -0,0 +1,136 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { + ValidationContext, + SDLValidationContext, +} from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import { DirectiveLocation } from '../../language/directiveLocation'; +import type { ASTVisitor } from '../../language/visitor'; +import { specifiedDirectives } from '../../type/directives'; + +export function unknownDirectiveMessage(directiveName: string): string { + return `Unknown directive "${directiveName}".`; +} + +export function misplacedDirectiveMessage( + directiveName: string, + location: string, +): string { + return `Directive "${directiveName}" may not be used on ${location}.`; +} + +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ +export function KnownDirectives( + context: ValidationContext | SDLValidationContext, +): ASTVisitor { + const locationsMap = Object.create(null); + + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + for (const directive of definedDirectives) { + locationsMap[directive.name] = directive.locations; + } + + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map(name => name.value); + } + } + + return { + Directive(node, key, parent, path, ancestors) { + const name = node.name.value; + const locations = locationsMap[name]; + + if (!locations) { + context.reportError( + new GraphQLError(unknownDirectiveMessage(name), [node]), + ); + return; + } + const candidateLocation = getDirectiveLocationForASTPath(ancestors); + if (candidateLocation && locations.indexOf(candidateLocation) === -1) { + context.reportError( + new GraphQLError(misplacedDirectiveMessage(name, candidateLocation), [ + node, + ]), + ); + } + }, + }; +} + +function getDirectiveLocationForASTPath(ancestors) { + const appliedTo = ancestors[ancestors.length - 1]; + if (!Array.isArray(appliedTo)) { + switch (appliedTo.kind) { + case Kind.OPERATION_DEFINITION: + switch (appliedTo.operation) { + case 'query': + return DirectiveLocation.QUERY; + case 'mutation': + return DirectiveLocation.MUTATION; + case 'subscription': + return DirectiveLocation.SUBSCRIPTION; + } + break; + case Kind.FIELD: + return DirectiveLocation.FIELD; + case Kind.FRAGMENT_SPREAD: + return DirectiveLocation.FRAGMENT_SPREAD; + case Kind.INLINE_FRAGMENT: + return DirectiveLocation.INLINE_FRAGMENT; + case Kind.FRAGMENT_DEFINITION: + return DirectiveLocation.FRAGMENT_DEFINITION; + case Kind.VARIABLE_DEFINITION: + return DirectiveLocation.VARIABLE_DEFINITION; + case Kind.SCHEMA_DEFINITION: + case Kind.SCHEMA_EXTENSION: + return DirectiveLocation.SCHEMA; + case Kind.SCALAR_TYPE_DEFINITION: + case Kind.SCALAR_TYPE_EXTENSION: + return DirectiveLocation.SCALAR; + case Kind.OBJECT_TYPE_DEFINITION: + case Kind.OBJECT_TYPE_EXTENSION: + return DirectiveLocation.OBJECT; + case Kind.FIELD_DEFINITION: + return DirectiveLocation.FIELD_DEFINITION; + case Kind.INTERFACE_TYPE_DEFINITION: + case Kind.INTERFACE_TYPE_EXTENSION: + return DirectiveLocation.INTERFACE; + case Kind.UNION_TYPE_DEFINITION: + case Kind.UNION_TYPE_EXTENSION: + return DirectiveLocation.UNION; + case Kind.ENUM_TYPE_DEFINITION: + case Kind.ENUM_TYPE_EXTENSION: + return DirectiveLocation.ENUM; + case Kind.ENUM_VALUE_DEFINITION: + return DirectiveLocation.ENUM_VALUE; + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + return DirectiveLocation.INPUT_OBJECT; + case Kind.INPUT_VALUE_DEFINITION: + const parentNode = ancestors[ancestors.length - 3]; + return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION + ? DirectiveLocation.INPUT_FIELD_DEFINITION + : DirectiveLocation.ARGUMENT_DEFINITION; + } + } +} diff --git a/node_modules/graphql/validation/rules/KnownDirectives.mjs b/node_modules/graphql/validation/rules/KnownDirectives.mjs new file mode 100644 index 0000000..44588d2 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownDirectives.mjs @@ -0,0 +1,176 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import { DirectiveLocation } from '../../language/directiveLocation'; +import { specifiedDirectives } from '../../type/directives'; +export function unknownDirectiveMessage(directiveName) { + return "Unknown directive \"".concat(directiveName, "\"."); +} +export function misplacedDirectiveMessage(directiveName, location) { + return "Directive \"".concat(directiveName, "\" may not be used on ").concat(location, "."); +} +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ + +export function KnownDirectives(context) { + var locationsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + locationsMap[directive.name] = directive.locations; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var def = _step2.value; + + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map(function (name) { + return name.value; + }); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return { + Directive: function Directive(node, key, parent, path, ancestors) { + var name = node.name.value; + var locations = locationsMap[name]; + + if (!locations) { + context.reportError(new GraphQLError(unknownDirectiveMessage(name), [node])); + return; + } + + var candidateLocation = getDirectiveLocationForASTPath(ancestors); + + if (candidateLocation && locations.indexOf(candidateLocation) === -1) { + context.reportError(new GraphQLError(misplacedDirectiveMessage(name, candidateLocation), [node])); + } + } + }; +} + +function getDirectiveLocationForASTPath(ancestors) { + var appliedTo = ancestors[ancestors.length - 1]; + + if (!Array.isArray(appliedTo)) { + switch (appliedTo.kind) { + case Kind.OPERATION_DEFINITION: + switch (appliedTo.operation) { + case 'query': + return DirectiveLocation.QUERY; + + case 'mutation': + return DirectiveLocation.MUTATION; + + case 'subscription': + return DirectiveLocation.SUBSCRIPTION; + } + + break; + + case Kind.FIELD: + return DirectiveLocation.FIELD; + + case Kind.FRAGMENT_SPREAD: + return DirectiveLocation.FRAGMENT_SPREAD; + + case Kind.INLINE_FRAGMENT: + return DirectiveLocation.INLINE_FRAGMENT; + + case Kind.FRAGMENT_DEFINITION: + return DirectiveLocation.FRAGMENT_DEFINITION; + + case Kind.VARIABLE_DEFINITION: + return DirectiveLocation.VARIABLE_DEFINITION; + + case Kind.SCHEMA_DEFINITION: + case Kind.SCHEMA_EXTENSION: + return DirectiveLocation.SCHEMA; + + case Kind.SCALAR_TYPE_DEFINITION: + case Kind.SCALAR_TYPE_EXTENSION: + return DirectiveLocation.SCALAR; + + case Kind.OBJECT_TYPE_DEFINITION: + case Kind.OBJECT_TYPE_EXTENSION: + return DirectiveLocation.OBJECT; + + case Kind.FIELD_DEFINITION: + return DirectiveLocation.FIELD_DEFINITION; + + case Kind.INTERFACE_TYPE_DEFINITION: + case Kind.INTERFACE_TYPE_EXTENSION: + return DirectiveLocation.INTERFACE; + + case Kind.UNION_TYPE_DEFINITION: + case Kind.UNION_TYPE_EXTENSION: + return DirectiveLocation.UNION; + + case Kind.ENUM_TYPE_DEFINITION: + case Kind.ENUM_TYPE_EXTENSION: + return DirectiveLocation.ENUM; + + case Kind.ENUM_VALUE_DEFINITION: + return DirectiveLocation.ENUM_VALUE; + + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + return DirectiveLocation.INPUT_OBJECT; + + case Kind.INPUT_VALUE_DEFINITION: + var parentNode = ancestors[ancestors.length - 3]; + return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION ? DirectiveLocation.INPUT_FIELD_DEFINITION : DirectiveLocation.ARGUMENT_DEFINITION; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownFragmentNames.js b/node_modules/graphql/validation/rules/KnownFragmentNames.js new file mode 100644 index 0000000..f00b953 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownFragmentNames.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownFragmentMessage = unknownFragmentMessage; +exports.KnownFragmentNames = KnownFragmentNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function unknownFragmentMessage(fragName) { + return "Unknown fragment \"".concat(fragName, "\"."); +} +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ + + +function KnownFragmentNames(context) { + return { + FragmentSpread: function FragmentSpread(node) { + var fragmentName = node.name.value; + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + context.reportError(new _GraphQLError.GraphQLError(unknownFragmentMessage(fragmentName), [node.name])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownFragmentNames.js.flow b/node_modules/graphql/validation/rules/KnownFragmentNames.js.flow new file mode 100644 index 0000000..383e840 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownFragmentNames.js.flow @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function unknownFragmentMessage(fragName: string): string { + return `Unknown fragment "${fragName}".`; +} + +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ +export function KnownFragmentNames(context: ValidationContext): ASTVisitor { + return { + FragmentSpread(node) { + const fragmentName = node.name.value; + const fragment = context.getFragment(fragmentName); + if (!fragment) { + context.reportError( + new GraphQLError(unknownFragmentMessage(fragmentName), [node.name]), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/KnownFragmentNames.mjs b/node_modules/graphql/validation/rules/KnownFragmentNames.mjs new file mode 100644 index 0000000..061772d --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownFragmentNames.mjs @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function unknownFragmentMessage(fragName) { + return "Unknown fragment \"".concat(fragName, "\"."); +} +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ + +export function KnownFragmentNames(context) { + return { + FragmentSpread: function FragmentSpread(node) { + var fragmentName = node.name.value; + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + context.reportError(new GraphQLError(unknownFragmentMessage(fragmentName), [node.name])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownTypeNames.js b/node_modules/graphql/validation/rules/KnownTypeNames.js new file mode 100644 index 0000000..2a4065d --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownTypeNames.js @@ -0,0 +1,69 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownTypeMessage = unknownTypeMessage; +exports.KnownTypeNames = KnownTypeNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList")); + +var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function unknownTypeMessage(typeName, suggestedTypes) { + var message = "Unknown type \"".concat(typeName, "\"."); + + if (suggestedTypes.length) { + message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedTypes), "?"); + } + + return message; +} +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ + + +function KnownTypeNames(context) { + return { + // TODO: when validating IDL, re-enable these. Experimental version does not + // add unreferenced types, resulting in false-positive errors. Squelched + // errors for now. + ObjectTypeDefinition: function ObjectTypeDefinition() { + return false; + }, + InterfaceTypeDefinition: function InterfaceTypeDefinition() { + return false; + }, + UnionTypeDefinition: function UnionTypeDefinition() { + return false; + }, + InputObjectTypeDefinition: function InputObjectTypeDefinition() { + return false; + }, + NamedType: function NamedType(node) { + var schema = context.getSchema(); + var typeName = node.name.value; + var type = schema.getType(typeName); + + if (!type) { + context.reportError(new _GraphQLError.GraphQLError(unknownTypeMessage(typeName, (0, _suggestionList.default)(typeName, Object.keys(schema.getTypeMap()))), [node])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownTypeNames.js.flow b/node_modules/graphql/validation/rules/KnownTypeNames.js.flow new file mode 100644 index 0000000..c65c5bb --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownTypeNames.js.flow @@ -0,0 +1,59 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +import type { ASTVisitor } from '../../language/visitor'; + +export function unknownTypeMessage( + typeName: string, + suggestedTypes: Array, +): string { + let message = `Unknown type "${typeName}".`; + if (suggestedTypes.length) { + message += ` Did you mean ${quotedOrList(suggestedTypes)}?`; + } + return message; +} + +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ +export function KnownTypeNames(context: ValidationContext): ASTVisitor { + return { + // TODO: when validating IDL, re-enable these. Experimental version does not + // add unreferenced types, resulting in false-positive errors. Squelched + // errors for now. + ObjectTypeDefinition: () => false, + InterfaceTypeDefinition: () => false, + UnionTypeDefinition: () => false, + InputObjectTypeDefinition: () => false, + NamedType(node) { + const schema = context.getSchema(); + const typeName = node.name.value; + const type = schema.getType(typeName); + if (!type) { + context.reportError( + new GraphQLError( + unknownTypeMessage( + typeName, + suggestionList(typeName, Object.keys(schema.getTypeMap())), + ), + [node], + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/KnownTypeNames.mjs b/node_modules/graphql/validation/rules/KnownTypeNames.mjs new file mode 100644 index 0000000..861e822 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownTypeNames.mjs @@ -0,0 +1,55 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +export function unknownTypeMessage(typeName, suggestedTypes) { + var message = "Unknown type \"".concat(typeName, "\"."); + + if (suggestedTypes.length) { + message += " Did you mean ".concat(quotedOrList(suggestedTypes), "?"); + } + + return message; +} +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ + +export function KnownTypeNames(context) { + return { + // TODO: when validating IDL, re-enable these. Experimental version does not + // add unreferenced types, resulting in false-positive errors. Squelched + // errors for now. + ObjectTypeDefinition: function ObjectTypeDefinition() { + return false; + }, + InterfaceTypeDefinition: function InterfaceTypeDefinition() { + return false; + }, + UnionTypeDefinition: function UnionTypeDefinition() { + return false; + }, + InputObjectTypeDefinition: function InputObjectTypeDefinition() { + return false; + }, + NamedType: function NamedType(node) { + var schema = context.getSchema(); + var typeName = node.name.value; + var type = schema.getType(typeName); + + if (!type) { + context.reportError(new GraphQLError(unknownTypeMessage(typeName, suggestionList(typeName, Object.keys(schema.getTypeMap()))), [node])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/LoneAnonymousOperation.js b/node_modules/graphql/validation/rules/LoneAnonymousOperation.js new file mode 100644 index 0000000..b492a85 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneAnonymousOperation.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.anonOperationNotAloneMessage = anonOperationNotAloneMessage; +exports.LoneAnonymousOperation = LoneAnonymousOperation; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _kinds = require("../../language/kinds"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function anonOperationNotAloneMessage() { + return 'This anonymous operation must be the only defined operation.'; +} +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ + + +function LoneAnonymousOperation(context) { + var operationCount = 0; + return { + Document: function Document(node) { + operationCount = node.definitions.filter(function (definition) { + return definition.kind === _kinds.Kind.OPERATION_DEFINITION; + }).length; + }, + OperationDefinition: function OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError(new _GraphQLError.GraphQLError(anonOperationNotAloneMessage(), [node])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/LoneAnonymousOperation.js.flow b/node_modules/graphql/validation/rules/LoneAnonymousOperation.js.flow new file mode 100644 index 0000000..2faad31 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneAnonymousOperation.js.flow @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import type { ASTVisitor } from '../../language/visitor'; + +export function anonOperationNotAloneMessage(): string { + return 'This anonymous operation must be the only defined operation.'; +} + +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ +export function LoneAnonymousOperation( + context: ASTValidationContext, +): ASTVisitor { + let operationCount = 0; + return { + Document(node) { + operationCount = node.definitions.filter( + definition => definition.kind === Kind.OPERATION_DEFINITION, + ).length; + }, + OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError( + new GraphQLError(anonOperationNotAloneMessage(), [node]), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/LoneAnonymousOperation.mjs b/node_modules/graphql/validation/rules/LoneAnonymousOperation.mjs new file mode 100644 index 0000000..1b4fe08 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneAnonymousOperation.mjs @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +export function anonOperationNotAloneMessage() { + return 'This anonymous operation must be the only defined operation.'; +} +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ + +export function LoneAnonymousOperation(context) { + var operationCount = 0; + return { + Document: function Document(node) { + operationCount = node.definitions.filter(function (definition) { + return definition.kind === Kind.OPERATION_DEFINITION; + }).length; + }, + OperationDefinition: function OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError(new GraphQLError(anonOperationNotAloneMessage(), [node])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/LoneSchemaDefinition.js b/node_modules/graphql/validation/rules/LoneSchemaDefinition.js new file mode 100644 index 0000000..83e475f --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneSchemaDefinition.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.schemaDefinitionNotAloneMessage = schemaDefinitionNotAloneMessage; +exports.canNotDefineSchemaWithinExtensionMessage = canNotDefineSchemaWithinExtensionMessage; +exports.LoneSchemaDefinition = LoneSchemaDefinition; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function schemaDefinitionNotAloneMessage() { + return 'Must provide only one schema definition.'; +} + +function canNotDefineSchemaWithinExtensionMessage() { + return 'Cannot define a new schema within a schema extension.'; +} +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ + + +function LoneSchemaDefinition(context) { + var oldSchema = context.getSchema(); + var alreadyDefined = oldSchema && (oldSchema.astNode || oldSchema.getQueryType() || oldSchema.getMutationType() || oldSchema.getSubscriptionType()); + var schemaDefinitionsCount = 0; + return { + SchemaDefinition: function SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError(new _GraphQLError.GraphQLError(canNotDefineSchemaWithinExtensionMessage(), node)); + return; + } + + if (schemaDefinitionsCount > 0) { + context.reportError(new _GraphQLError.GraphQLError(schemaDefinitionNotAloneMessage(), node)); + } + + ++schemaDefinitionsCount; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/LoneSchemaDefinition.js.flow b/node_modules/graphql/validation/rules/LoneSchemaDefinition.js.flow new file mode 100644 index 0000000..ac614a0 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneSchemaDefinition.js.flow @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { SDLValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function schemaDefinitionNotAloneMessage(): string { + return 'Must provide only one schema definition.'; +} + +export function canNotDefineSchemaWithinExtensionMessage(): string { + return 'Cannot define a new schema within a schema extension.'; +} + +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ +export function LoneSchemaDefinition( + context: SDLValidationContext, +): ASTVisitor { + const oldSchema = context.getSchema(); + const alreadyDefined = + oldSchema && + (oldSchema.astNode || + oldSchema.getQueryType() || + oldSchema.getMutationType() || + oldSchema.getSubscriptionType()); + + let schemaDefinitionsCount = 0; + return { + SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError( + new GraphQLError(canNotDefineSchemaWithinExtensionMessage(), node), + ); + return; + } + + if (schemaDefinitionsCount > 0) { + context.reportError( + new GraphQLError(schemaDefinitionNotAloneMessage(), node), + ); + } + ++schemaDefinitionsCount; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/LoneSchemaDefinition.mjs b/node_modules/graphql/validation/rules/LoneSchemaDefinition.mjs new file mode 100644 index 0000000..888676a --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneSchemaDefinition.mjs @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function schemaDefinitionNotAloneMessage() { + return 'Must provide only one schema definition.'; +} +export function canNotDefineSchemaWithinExtensionMessage() { + return 'Cannot define a new schema within a schema extension.'; +} +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ + +export function LoneSchemaDefinition(context) { + var oldSchema = context.getSchema(); + var alreadyDefined = oldSchema && (oldSchema.astNode || oldSchema.getQueryType() || oldSchema.getMutationType() || oldSchema.getSubscriptionType()); + var schemaDefinitionsCount = 0; + return { + SchemaDefinition: function SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError(new GraphQLError(canNotDefineSchemaWithinExtensionMessage(), node)); + return; + } + + if (schemaDefinitionsCount > 0) { + context.reportError(new GraphQLError(schemaDefinitionNotAloneMessage(), node)); + } + + ++schemaDefinitionsCount; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoFragmentCycles.js b/node_modules/graphql/validation/rules/NoFragmentCycles.js new file mode 100644 index 0000000..78e108c --- /dev/null +++ b/node_modules/graphql/validation/rules/NoFragmentCycles.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.cycleErrorMessage = cycleErrorMessage; +exports.NoFragmentCycles = NoFragmentCycles; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function cycleErrorMessage(fragName, spreadNames) { + var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : ''; + return "Cannot spread fragment \"".concat(fragName, "\" within itself").concat(via, "."); +} + +function NoFragmentCycles(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors + + var spreadPath = []; // Position in the spread path + + var spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + } + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; + } + + var fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + var spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (var i = 0; i < spreadNodes.length; i++) { + var spreadNode = spreadNodes[i]; + var spreadName = spreadNode.name.value; + var cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + + if (cycleIndex === undefined) { + var spreadFragment = context.getFragment(spreadName); + + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + var cyclePath = spreadPath.slice(cycleIndex); + var fragmentNames = cyclePath.slice(0, -1).map(function (s) { + return s.name.value; + }); + context.reportError(new _GraphQLError.GraphQLError(cycleErrorMessage(spreadName, fragmentNames), cyclePath)); + } + + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoFragmentCycles.js.flow b/node_modules/graphql/validation/rules/NoFragmentCycles.js.flow new file mode 100644 index 0000000..f070774 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoFragmentCycles.js.flow @@ -0,0 +1,86 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { FragmentDefinitionNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; + +export function cycleErrorMessage( + fragName: string, + spreadNames: Array, +): string { + const via = spreadNames.length ? ' via ' + spreadNames.join(', ') : ''; + return `Cannot spread fragment "${fragName}" within itself${via}.`; +} + +export function NoFragmentCycles(context: ValidationContext): ASTVisitor { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedFrags = Object.create(null); + + // Array of AST nodes used to produce meaningful errors + const spreadPath = []; + + // Position in the spread path + const spreadPathIndexByName = Object.create(null); + + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + }, + }; + + // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + function detectCycleRecursive(fragment: FragmentDefinitionNode) { + if (visitedFrags[fragment.name.value]) { + return; + } + + const fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + + const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (let i = 0; i < spreadNodes.length; i++) { + const spreadNode = spreadNodes[i]; + const spreadName = spreadNode.name.value; + const cycleIndex = spreadPathIndexByName[spreadName]; + + spreadPath.push(spreadNode); + if (cycleIndex === undefined) { + const spreadFragment = context.getFragment(spreadName); + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + const cyclePath = spreadPath.slice(cycleIndex); + const fragmentNames = cyclePath.slice(0, -1).map(s => s.name.value); + context.reportError( + new GraphQLError( + cycleErrorMessage(spreadName, fragmentNames), + cyclePath, + ), + ); + } + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} diff --git a/node_modules/graphql/validation/rules/NoFragmentCycles.mjs b/node_modules/graphql/validation/rules/NoFragmentCycles.mjs new file mode 100644 index 0000000..64501db --- /dev/null +++ b/node_modules/graphql/validation/rules/NoFragmentCycles.mjs @@ -0,0 +1,74 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function cycleErrorMessage(fragName, spreadNames) { + var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : ''; + return "Cannot spread fragment \"".concat(fragName, "\" within itself").concat(via, "."); +} +export function NoFragmentCycles(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors + + var spreadPath = []; // Position in the spread path + + var spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + } + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; + } + + var fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + var spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (var i = 0; i < spreadNodes.length; i++) { + var spreadNode = spreadNodes[i]; + var spreadName = spreadNode.name.value; + var cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + + if (cycleIndex === undefined) { + var spreadFragment = context.getFragment(spreadName); + + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + var cyclePath = spreadPath.slice(cycleIndex); + var fragmentNames = cyclePath.slice(0, -1).map(function (s) { + return s.name.value; + }); + context.reportError(new GraphQLError(cycleErrorMessage(spreadName, fragmentNames), cyclePath)); + } + + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUndefinedVariables.js b/node_modules/graphql/validation/rules/NoUndefinedVariables.js new file mode 100644 index 0000000..cbe610b --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUndefinedVariables.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.undefinedVarMessage = undefinedVarMessage; +exports.NoUndefinedVariables = NoUndefinedVariables; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function undefinedVarMessage(varName, opName) { + return opName ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is not defined."); +} +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ + + +function NoUndefinedVariables(context) { + var variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + variableNameDefined = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node; + var varName = node.name.value; + + if (variableNameDefined[varName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(undefinedVarMessage(varName, operation.name && operation.name.value), [node, operation])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUndefinedVariables.js.flow b/node_modules/graphql/validation/rules/NoUndefinedVariables.js.flow new file mode 100644 index 0000000..fcb85c5 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUndefinedVariables.js.flow @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function undefinedVarMessage(varName: string, opName: ?string): string { + return opName + ? `Variable "$${varName}" is not defined by operation "${opName}".` + : `Variable "$${varName}" is not defined.`; +} + +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ +export function NoUndefinedVariables(context: ValidationContext): ASTVisitor { + let variableNameDefined = Object.create(null); + + return { + OperationDefinition: { + enter() { + variableNameDefined = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node } of usages) { + const varName = node.name.value; + if (variableNameDefined[varName] !== true) { + context.reportError( + new GraphQLError( + undefinedVarMessage( + varName, + operation.name && operation.name.value, + ), + [node, operation], + ), + ); + } + } + }, + }, + VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoUndefinedVariables.mjs b/node_modules/graphql/validation/rules/NoUndefinedVariables.mjs new file mode 100644 index 0000000..a7a5b56 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUndefinedVariables.mjs @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function undefinedVarMessage(varName, opName) { + return opName ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is not defined."); +} +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ + +export function NoUndefinedVariables(context) { + var variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + variableNameDefined = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node; + var varName = node.name.value; + + if (variableNameDefined[varName] !== true) { + context.reportError(new GraphQLError(undefinedVarMessage(varName, operation.name && operation.name.value), [node, operation])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUnusedFragments.js b/node_modules/graphql/validation/rules/NoUnusedFragments.js new file mode 100644 index 0000000..855f349 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedFragments.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unusedFragMessage = unusedFragMessage; +exports.NoUnusedFragments = NoUnusedFragments; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function unusedFragMessage(fragName) { + return "Fragment \"".concat(fragName, "\" is never used."); +} +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ + + +function NoUnusedFragments(context) { + var operationDefs = []; + var fragmentDefs = []; + return { + OperationDefinition: function OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave: function leave() { + var fragmentNameUsed = Object.create(null); + + for (var _i = 0; _i < operationDefs.length; _i++) { + var operation = operationDefs[_i]; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = context.getRecursivelyReferencedFragments(operation)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var fragment = _step.value; + fragmentNameUsed[fragment.name.value] = true; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + + for (var _i2 = 0; _i2 < fragmentDefs.length; _i2++) { + var fragmentDef = fragmentDefs[_i2]; + var fragName = fragmentDef.name.value; + + if (fragmentNameUsed[fragName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(unusedFragMessage(fragName), [fragmentDef])); + } + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUnusedFragments.js.flow b/node_modules/graphql/validation/rules/NoUnusedFragments.js.flow new file mode 100644 index 0000000..3e37004 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedFragments.js.flow @@ -0,0 +1,59 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function unusedFragMessage(fragName: string): string { + return `Fragment "${fragName}" is never used.`; +} + +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ +export function NoUnusedFragments(context: ValidationContext): ASTVisitor { + const operationDefs = []; + const fragmentDefs = []; + + return { + OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave() { + const fragmentNameUsed = Object.create(null); + for (const operation of operationDefs) { + for (const fragment of context.getRecursivelyReferencedFragments( + operation, + )) { + fragmentNameUsed[fragment.name.value] = true; + } + } + + for (const fragmentDef of fragmentDefs) { + const fragName = fragmentDef.name.value; + if (fragmentNameUsed[fragName] !== true) { + context.reportError( + new GraphQLError(unusedFragMessage(fragName), [fragmentDef]), + ); + } + } + }, + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoUnusedFragments.mjs b/node_modules/graphql/validation/rules/NoUnusedFragments.mjs new file mode 100644 index 0000000..fc9ed96 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedFragments.mjs @@ -0,0 +1,74 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function unusedFragMessage(fragName) { + return "Fragment \"".concat(fragName, "\" is never used."); +} +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ + +export function NoUnusedFragments(context) { + var operationDefs = []; + var fragmentDefs = []; + return { + OperationDefinition: function OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave: function leave() { + var fragmentNameUsed = Object.create(null); + + for (var _i = 0; _i < operationDefs.length; _i++) { + var operation = operationDefs[_i]; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = context.getRecursivelyReferencedFragments(operation)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var fragment = _step.value; + fragmentNameUsed[fragment.name.value] = true; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + + for (var _i2 = 0; _i2 < fragmentDefs.length; _i2++) { + var fragmentDef = fragmentDefs[_i2]; + var fragName = fragmentDef.name.value; + + if (fragmentNameUsed[fragName] !== true) { + context.reportError(new GraphQLError(unusedFragMessage(fragName), [fragmentDef])); + } + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUnusedVariables.js b/node_modules/graphql/validation/rules/NoUnusedVariables.js new file mode 100644 index 0000000..d62cd94 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedVariables.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unusedVariableMessage = unusedVariableMessage; +exports.NoUnusedVariables = NoUnusedVariables; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function unusedVariableMessage(varName, opName) { + return opName ? "Variable \"$".concat(varName, "\" is never used in operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is never used."); +} +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ + + +function NoUnusedVariables(context) { + var variableDefs = []; + return { + OperationDefinition: { + enter: function enter() { + variableDefs = []; + }, + leave: function leave(operation) { + var variableNameUsed = Object.create(null); + var usages = context.getRecursiveVariableUsages(operation); + var opName = operation.name ? operation.name.value : null; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node; + variableNameUsed[node.name.value] = true; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + for (var _i = 0; _i < variableDefs.length; _i++) { + var variableDef = variableDefs[_i]; + var variableName = variableDef.variable.name.value; + + if (variableNameUsed[variableName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(unusedVariableMessage(variableName, opName), [variableDef])); + } + } + } + }, + VariableDefinition: function VariableDefinition(def) { + variableDefs.push(def); + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUnusedVariables.js.flow b/node_modules/graphql/validation/rules/NoUnusedVariables.js.flow new file mode 100644 index 0000000..e438afb --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedVariables.js.flow @@ -0,0 +1,62 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function unusedVariableMessage( + varName: string, + opName: ?string, +): string { + return opName + ? `Variable "$${varName}" is never used in operation "${opName}".` + : `Variable "$${varName}" is never used.`; +} + +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ +export function NoUnusedVariables(context: ValidationContext): ASTVisitor { + let variableDefs = []; + + return { + OperationDefinition: { + enter() { + variableDefs = []; + }, + leave(operation) { + const variableNameUsed = Object.create(null); + const usages = context.getRecursiveVariableUsages(operation); + const opName = operation.name ? operation.name.value : null; + + for (const { node } of usages) { + variableNameUsed[node.name.value] = true; + } + + for (const variableDef of variableDefs) { + const variableName = variableDef.variable.name.value; + if (variableNameUsed[variableName] !== true) { + context.reportError( + new GraphQLError(unusedVariableMessage(variableName, opName), [ + variableDef, + ]), + ); + } + } + }, + }, + VariableDefinition(def) { + variableDefs.push(def); + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoUnusedVariables.mjs b/node_modules/graphql/validation/rules/NoUnusedVariables.mjs new file mode 100644 index 0000000..08f8f17 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedVariables.mjs @@ -0,0 +1,70 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function unusedVariableMessage(varName, opName) { + return opName ? "Variable \"$".concat(varName, "\" is never used in operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is never used."); +} +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ + +export function NoUnusedVariables(context) { + var variableDefs = []; + return { + OperationDefinition: { + enter: function enter() { + variableDefs = []; + }, + leave: function leave(operation) { + var variableNameUsed = Object.create(null); + var usages = context.getRecursiveVariableUsages(operation); + var opName = operation.name ? operation.name.value : null; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node; + variableNameUsed[node.name.value] = true; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + for (var _i = 0; _i < variableDefs.length; _i++) { + var variableDef = variableDefs[_i]; + var variableName = variableDef.variable.name.value; + + if (variableNameUsed[variableName] !== true) { + context.reportError(new GraphQLError(unusedVariableMessage(variableName, opName), [variableDef])); + } + } + } + }, + VariableDefinition: function VariableDefinition(def) { + variableDefs.push(def); + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js new file mode 100644 index 0000000..4e7f71c --- /dev/null +++ b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js @@ -0,0 +1,595 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fieldsConflictMessage = fieldsConflictMessage; +exports.OverlappingFieldsCanBeMerged = OverlappingFieldsCanBeMerged; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _find = _interopRequireDefault(require("../../jsutils/find")); + +var _kinds = require("../../language/kinds"); + +var _printer = require("../../language/printer"); + +var _definition = require("../../type/definition"); + +var _typeFromAST = require("../../utilities/typeFromAST"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function fieldsConflictMessage(responseName, reason) { + return "Fields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(reason), ". ") + 'Use different aliases on the fields to fetch both if this was intentional.'; +} + +function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason.map(function (_ref) { + var responseName = _ref[0], + subreason = _ref[1]; + return "subfields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(subreason)); + }).join(' and '); + } + + return reason; +} +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ + + +function OverlappingFieldsCanBeMerged(context) { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + + var cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet: function SelectionSet(selectionSet) { + var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet); + + for (var _i = 0; _i < conflicts.length; _i++) { + var _ref3 = conflicts[_i]; + var _ref2$ = _ref3[0]; + var responseName = _ref2$[0]; + var reason = _ref2$[1]; + var fields1 = _ref3[1]; + var fields2 = _ref3[2]; + context.reportError(new _GraphQLError.GraphQLError(fieldsConflictMessage(responseName, reason), fields1.concat(fields2))); + } + } + }; +} + +/** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ +// Find all conflicts found "within" a selection set, including those found +// via spreading in fragments. Called when visiting each SelectionSet in the +// GraphQL Document. +function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) { + var conflicts = []; + + var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet), + fieldMap = _getFieldsAndFragment[0], + fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + + + collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap); + + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + var comparedFragments = Object.create(null); + + for (var i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + + for (var j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]); + } + } + } + + return conflicts; +} // Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. + + +function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) { + // Memoize so a fragment is not compared for conflicts more than once. + if (comparedFragments[fragmentName]) { + return; + } + + comparedFragments[fragmentName] = true; + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + return; + } + + var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment), + fieldMap2 = _getReferencedFieldsA[0], + fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself. + + + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + + for (var i = 0; i < fragmentNames2.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]); + } +} // Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. + + +function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + + + if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { + return; + } + + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + var fragment1 = context.getFragment(fragmentName1); + var fragment2 = context.getFragment(fragmentName2); + + if (!fragment1 || !fragment2) { + return; + } + + var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1), + fieldMap1 = _getReferencedFieldsA2[0], + fragmentNames1 = _getReferencedFieldsA2[1]; + + var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2), + fieldMap2 = _getReferencedFieldsA3[0], + fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + + + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2); + } +} // Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. + + +function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) { + var conflicts = []; + + var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1), + fieldMap1 = _getFieldsAndFragment2[0], + fragmentNames1 = _getFieldsAndFragment2[1]; + + var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2), + fieldMap2 = _getFieldsAndFragment3[0], + fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + + if (fragmentNames2.length !== 0) { + var comparedFragments = Object.create(null); + + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]); + } + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + + + if (fragmentNames1.length !== 0) { + var _comparedFragments = Object.create(null); + + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, _comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]); + } + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + + + for (var _i2 = 0; _i2 < fragmentNames1.length; _i2++) { + for (var _j = 0; _j < fragmentNames2.length; _j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i2], fragmentNames2[_j]); + } + } + + return conflicts; +} // Collect all Conflicts "within" one collection of fields. + + +function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + var _arr = Object.keys(fieldMap); + + for (var _i3 = 0; _i3 < _arr.length; _i3++) { + var responseName = _arr[_i3]; + var fields = fieldMap[responseName]; // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + + if (fields.length > 1) { + for (var i = 0; i < fields.length; i++) { + for (var j = i + 1; j < fields.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive + responseName, fields[i], fields[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. + + +function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + var _arr2 = Object.keys(fieldMap1); + + for (var _i4 = 0; _i4 < _arr2.length; _i4++) { + var responseName = _arr2[_i4]; + var fields2 = fieldMap2[responseName]; + + if (fields2) { + var fields1 = fieldMap1[responseName]; + + for (var i = 0; i < fields1.length; i++) { + for (var j = 0; j < fields2.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. + + +function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) { + var parentType1 = field1[0], + node1 = field1[1], + def1 = field1[2]; + var parentType2 = field2[0], + node2 = field2[1], + def2 = field2[2]; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + + var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, _definition.isObjectType)(parentType1) && (0, _definition.isObjectType)(parentType2); // The return type for each field. + + var type1 = def1 && def1.type; + var type2 = def2 && def2.type; + + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + var name1 = node1.name.value; + var name2 = node2.name.value; + + if (name1 !== name2) { + return [[responseName, "".concat(name1, " and ").concat(name2, " are different fields")], [node1], [node2]]; + } // Two field calls must have the same arguments. + + + if (!sameArguments(node1.arguments || [], node2.arguments || [])) { + return [[responseName, 'they have differing arguments'], [node1], [node2]]; + } + } + + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [[responseName, "they return conflicting types ".concat((0, _inspect.default)(type1), " and ").concat((0, _inspect.default)(type2))], [node1], [node2]]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + + + var selectionSet1 = node1.selectionSet; + var selectionSet2 = node2.selectionSet; + + if (selectionSet1 && selectionSet2) { + var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, (0, _definition.getNamedType)(type1), selectionSet1, (0, _definition.getNamedType)(type2), selectionSet2); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} + +function sameArguments(arguments1, arguments2) { + if (arguments1.length !== arguments2.length) { + return false; + } + + return arguments1.every(function (argument1) { + var argument2 = (0, _find.default)(arguments2, function (argument) { + return argument.name.value === argument1.name.value; + }); + + if (!argument2) { + return false; + } + + return sameValue(argument1.value, argument2.value); + }); +} + +function sameValue(value1, value2) { + return !value1 && !value2 || (0, _printer.print)(value1) === (0, _printer.print)(value2); +} // Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. + + +function doTypesConflict(type1, type2) { + if ((0, _definition.isListType)(type1)) { + return (0, _definition.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if ((0, _definition.isListType)(type2)) { + return true; + } + + if ((0, _definition.isNonNullType)(type1)) { + return (0, _definition.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if ((0, _definition.isNonNullType)(type2)) { + return true; + } + + if ((0, _definition.isLeafType)(type1) || (0, _definition.isLeafType)(type2)) { + return type1 !== type2; + } + + return false; +} // Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. + + +function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) { + var cached = cachedFieldsAndFragmentNames.get(selectionSet); + + if (!cached) { + var nodeAndDefs = Object.create(null); + var fragmentNames = Object.create(null); + + _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames); + + cached = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, cached); + } + + return cached; +} // Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. + + +function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) { + // Short-circuit building a type from the node if possible. + var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + + if (cached) { + return cached; + } + + var fragmentType = (0, _typeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet); +} + +function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) { + for (var i = 0; i < selectionSet.selections.length; i++) { + var selection = selectionSet.selections[i]; + + switch (selection.kind) { + case _kinds.Kind.FIELD: + var fieldName = selection.name.value; + var fieldDef = void 0; + + if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + + var responseName = selection.alias ? selection.alias.value : fieldName; + + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + + case _kinds.Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + + case _kinds.Kind.INLINE_FRAGMENT: + var typeCondition = selection.typeCondition; + var inlineFragmentType = typeCondition ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) : parentType; + + _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames); + + break; + } + } +} // Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. + + +function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [[responseName, conflicts.map(function (_ref4) { + var reason = _ref4[0]; + return reason; + })], conflicts.reduce(function (allFields, _ref5) { + var fields1 = _ref5[1]; + return allFields.concat(fields1); + }, [node1]), conflicts.reduce(function (allFields, _ref6) { + var fields2 = _ref6[2]; + return allFields.concat(fields2); + }, [node2])]; + } +} +/** + * A way to keep track of pairs of things when the ordering of the pair does + * not matter. We do this by maintaining a sort of double adjacency sets. + */ + + +var PairSet = +/*#__PURE__*/ +function () { + function PairSet() { + _defineProperty(this, "_data", void 0); + + this._data = Object.create(null); + } + + var _proto = PairSet.prototype; + + _proto.has = function has(a, b, areMutuallyExclusive) { + var first = this._data[a]; + var result = first && first[b]; + + if (result === undefined) { + return false; + } // areMutuallyExclusive being false is a superset of being true, + // hence if we want to know if this PairSet "has" these two with no + // exclusivity, we have to ensure it was added as such. + + + if (areMutuallyExclusive === false) { + return result === false; + } + + return true; + }; + + _proto.add = function add(a, b, areMutuallyExclusive) { + _pairSetAdd(this._data, a, b, areMutuallyExclusive); + + _pairSetAdd(this._data, b, a, areMutuallyExclusive); + }; + + return PairSet; +}(); + +function _pairSetAdd(data, a, b, areMutuallyExclusive) { + var map = data[a]; + + if (!map) { + map = Object.create(null); + data[a] = map; + } + + map[b] = areMutuallyExclusive; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js.flow b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js.flow new file mode 100644 index 0000000..7a15f4d --- /dev/null +++ b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js.flow @@ -0,0 +1,847 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import inspect from '../../jsutils/inspect'; +import find from '../../jsutils/find'; +import type { ObjMap } from '../../jsutils/ObjMap'; +import type { + SelectionSetNode, + FieldNode, + ArgumentNode, + FragmentDefinitionNode, +} from '../../language/ast'; +import { Kind } from '../../language/kinds'; +import { print } from '../../language/printer'; +import type { ASTVisitor } from '../../language/visitor'; +import { + getNamedType, + isNonNullType, + isLeafType, + isObjectType, + isListType, + isInterfaceType, +} from '../../type/definition'; +import type { + GraphQLNamedType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, +} from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; + +export function fieldsConflictMessage( + responseName: string, + reason: ConflictReasonMessage, +): string { + return ( + `Fields "${responseName}" conflict because ${reasonMessage(reason)}. ` + + 'Use different aliases on the fields to fetch both if this was intentional.' + ); +} + +function reasonMessage(reason: ConflictReasonMessage): string { + if (Array.isArray(reason)) { + return reason + .map( + ([responseName, subreason]) => + `subfields "${responseName}" conflict because ${reasonMessage( + subreason, + )}`, + ) + .join(' and '); + } + return reason; +} + +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ +export function OverlappingFieldsCanBeMerged( + context: ValidationContext, +): ASTVisitor { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + const comparedFragmentPairs = new PairSet(); + + // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + const cachedFieldsAndFragmentNames = new Map(); + + return { + SelectionSet(selectionSet) { + const conflicts = findConflictsWithinSelectionSet( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + context.getParentType(), + selectionSet, + ); + for (const [[responseName, reason], fields1, fields2] of conflicts) { + context.reportError( + new GraphQLError( + fieldsConflictMessage(responseName, reason), + fields1.concat(fields2), + ), + ); + } + }, + }; +} + +type Conflict = [ConflictReason, Array, Array]; +// Field name and reason. +type ConflictReason = [string, ConflictReasonMessage]; +// Reason is a string, or a nested list of conflicts. +type ConflictReasonMessage = string | Array; +// Tuple defining a field node in a context. +type NodeAndDef = [GraphQLCompositeType, FieldNode, ?GraphQLField<*, *>]; +// Map of array of those. +type NodeAndDefCollection = ObjMap>; + +/** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ + +// Find all conflicts found "within" a selection set, including those found +// via spreading in fragments. Called when visiting each SelectionSet in the +// GraphQL Document. +function findConflictsWithinSelectionSet( + context: ValidationContext, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + parentType: ?GraphQLNamedType, + selectionSet: SelectionSetNode, +): Array { + const conflicts = []; + + const [fieldMap, fragmentNames] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType, + selectionSet, + ); + + // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + collectConflictsWithin( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + fieldMap, + ); + + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + const comparedFragments = Object.create(null); + for (let i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragments, + comparedFragmentPairs, + false, + fieldMap, + fragmentNames[i], + ); + // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + for (let j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + false, + fragmentNames[i], + fragmentNames[j], + ); + } + } + } + return conflicts; +} + +// Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. +function collectConflictsBetweenFieldsAndFragment( + context: ValidationContext, + conflicts: Array, + cachedFieldsAndFragmentNames, + comparedFragments: ObjMap, + comparedFragmentPairs: PairSet, + areMutuallyExclusive: boolean, + fieldMap: NodeAndDefCollection, + fragmentName: string, +): void { + // Memoize so a fragment is not compared for conflicts more than once. + if (comparedFragments[fragmentName]) { + return; + } + comparedFragments[fragmentName] = true; + + const fragment = context.getFragment(fragmentName); + if (!fragment) { + return; + } + + const [fieldMap2, fragmentNames2] = getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment, + ); + + // Do not compare a fragment's fieldMap to itself. + if (fieldMap === fieldMap2) { + return; + } + + // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fieldMap2, + ); + + // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + for (let i = 0; i < fragmentNames2.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragments, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fragmentNames2[i], + ); + } +} + +// Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. +function collectConflictsBetweenFragments( + context: ValidationContext, + conflicts: Array, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + areMutuallyExclusive: boolean, + fragmentName1: string, + fragmentName2: string, +): void { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } + + // Memoize so two fragments are not compared for conflicts more than once. + if ( + comparedFragmentPairs.has( + fragmentName1, + fragmentName2, + areMutuallyExclusive, + ) + ) { + return; + } + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + + const fragment1 = context.getFragment(fragmentName1); + const fragment2 = context.getFragment(fragmentName2); + if (!fragment1 || !fragment2) { + return; + } + + const [fieldMap1, fragmentNames1] = getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment1, + ); + const [fieldMap2, fragmentNames2] = getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment2, + ); + + // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); + + // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + for (let j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentNames2[j], + ); + } + + // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + for (let i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentNames1[i], + fragmentName2, + ); + } +} + +// Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. +function findConflictsBetweenSubSelectionSets( + context: ValidationContext, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + areMutuallyExclusive: boolean, + parentType1: ?GraphQLNamedType, + selectionSet1: SelectionSetNode, + parentType2: ?GraphQLNamedType, + selectionSet2: SelectionSetNode, +): Array { + const conflicts = []; + + const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType1, + selectionSet1, + ); + const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType2, + selectionSet2, + ); + + // (H) First, collect all conflicts between these two collections of field. + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); + + // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + if (fragmentNames2.length !== 0) { + const comparedFragments = Object.create(null); + for (let j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragments, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fragmentNames2[j], + ); + } + } + + // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + if (fragmentNames1.length !== 0) { + const comparedFragments = Object.create(null); + for (let i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragments, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap2, + fragmentNames1[i], + ); + } + } + + // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + for (let i = 0; i < fragmentNames1.length; i++) { + for (let j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentNames1[i], + fragmentNames2[j], + ); + } + } + return conflicts; +} + +// Collect all Conflicts "within" one collection of fields. +function collectConflictsWithin( + context: ValidationContext, + conflicts: Array, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + fieldMap: NodeAndDefCollection, +): void { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + for (const responseName of Object.keys(fieldMap)) { + const fields = fieldMap[responseName]; + // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + if (fields.length > 1) { + for (let i = 0; i < fields.length; i++) { + for (let j = i + 1; j < fields.length; j++) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + false, // within one collection is never mutually exclusive + responseName, + fields[i], + fields[j], + ); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} + +// Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. +function collectConflictsBetween( + context: ValidationContext, + conflicts: Array, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + parentFieldsAreMutuallyExclusive: boolean, + fieldMap1: NodeAndDefCollection, + fieldMap2: NodeAndDefCollection, +): void { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + for (const responseName of Object.keys(fieldMap1)) { + const fields2 = fieldMap2[responseName]; + if (fields2) { + const fields1 = fieldMap1[responseName]; + for (let i = 0; i < fields1.length; i++) { + for (let j = 0; j < fields2.length; j++) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + fields1[i], + fields2[j], + ); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} + +// Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. +function findConflict( + context: ValidationContext, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + parentFieldsAreMutuallyExclusive: boolean, + responseName: string, + field1: NodeAndDef, + field2: NodeAndDef, +): ?Conflict { + const [parentType1, node1, def1] = field1; + const [parentType2, node2, def2] = field2; + + // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + const areMutuallyExclusive = + parentFieldsAreMutuallyExclusive || + (parentType1 !== parentType2 && + isObjectType(parentType1) && + isObjectType(parentType2)); + + // The return type for each field. + const type1 = def1 && def1.type; + const type2 = def2 && def2.type; + + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + const name1 = node1.name.value; + const name2 = node2.name.value; + if (name1 !== name2) { + return [ + [responseName, `${name1} and ${name2} are different fields`], + [node1], + [node2], + ]; + } + + // Two field calls must have the same arguments. + if (!sameArguments(node1.arguments || [], node2.arguments || [])) { + return [ + [responseName, 'they have differing arguments'], + [node1], + [node2], + ]; + } + } + + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [ + [ + responseName, + `they return conflicting types ${inspect(type1)} and ${inspect(type2)}`, + ], + [node1], + [node2], + ]; + } + + // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + const selectionSet1 = node1.selectionSet; + const selectionSet2 = node2.selectionSet; + if (selectionSet1 && selectionSet2) { + const conflicts = findConflictsBetweenSubSelectionSets( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + getNamedType(type1), + selectionSet1, + getNamedType(type2), + selectionSet2, + ); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} + +function sameArguments( + arguments1: $ReadOnlyArray, + arguments2: $ReadOnlyArray, +): boolean { + if (arguments1.length !== arguments2.length) { + return false; + } + return arguments1.every(argument1 => { + const argument2 = find( + arguments2, + argument => argument.name.value === argument1.name.value, + ); + if (!argument2) { + return false; + } + return sameValue(argument1.value, argument2.value); + }); +} + +function sameValue(value1, value2) { + return (!value1 && !value2) || print(value1) === print(value2); +} + +// Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. +function doTypesConflict( + type1: GraphQLOutputType, + type2: GraphQLOutputType, +): boolean { + if (isListType(type1)) { + return isListType(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + if (isListType(type2)) { + return true; + } + if (isNonNullType(type1)) { + return isNonNullType(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + if (isNonNullType(type2)) { + return true; + } + if (isLeafType(type1) || isLeafType(type2)) { + return type1 !== type2; + } + return false; +} + +// Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. +function getFieldsAndFragmentNames( + context: ValidationContext, + cachedFieldsAndFragmentNames, + parentType: ?GraphQLNamedType, + selectionSet: SelectionSetNode, +): [NodeAndDefCollection, Array] { + let cached = cachedFieldsAndFragmentNames.get(selectionSet); + if (!cached) { + const nodeAndDefs = Object.create(null); + const fragmentNames = Object.create(null); + _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames, + ); + cached = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, cached); + } + return cached; +} + +// Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. +function getReferencedFieldsAndFragmentNames( + context: ValidationContext, + cachedFieldsAndFragmentNames, + fragment: FragmentDefinitionNode, +) { + // Short-circuit building a type from the node if possible. + const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + if (cached) { + return cached; + } + + const fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragmentType, + fragment.selectionSet, + ); +} + +function _collectFieldsAndFragmentNames( + context: ValidationContext, + parentType: ?GraphQLNamedType, + selectionSet: SelectionSetNode, + nodeAndDefs, + fragmentNames, +): void { + for (let i = 0; i < selectionSet.selections.length; i++) { + const selection = selectionSet.selections[i]; + switch (selection.kind) { + case Kind.FIELD: + const fieldName = selection.name.value; + let fieldDef; + if (isObjectType(parentType) || isInterfaceType(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + const responseName = selection.alias + ? selection.alias.value + : fieldName; + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + case Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + case Kind.INLINE_FRAGMENT: + const typeCondition = selection.typeCondition; + const inlineFragmentType = typeCondition + ? typeFromAST(context.getSchema(), typeCondition) + : parentType; + _collectFieldsAndFragmentNames( + context, + inlineFragmentType, + selection.selectionSet, + nodeAndDefs, + fragmentNames, + ); + break; + } + } +} + +// Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. +function subfieldConflicts( + conflicts: Array, + responseName: string, + node1: FieldNode, + node2: FieldNode, +): ?Conflict { + if (conflicts.length > 0) { + return [ + [responseName, conflicts.map(([reason]) => reason)], + conflicts.reduce((allFields, [, fields1]) => allFields.concat(fields1), [ + node1, + ]), + conflicts.reduce( + (allFields, [, , fields2]) => allFields.concat(fields2), + [node2], + ), + ]; + } +} + +/** + * A way to keep track of pairs of things when the ordering of the pair does + * not matter. We do this by maintaining a sort of double adjacency sets. + */ +class PairSet { + _data: ObjMap>; + + constructor(): void { + this._data = Object.create(null); + } + + has(a: string, b: string, areMutuallyExclusive: boolean) { + const first = this._data[a]; + const result = first && first[b]; + if (result === undefined) { + return false; + } + // areMutuallyExclusive being false is a superset of being true, + // hence if we want to know if this PairSet "has" these two with no + // exclusivity, we have to ensure it was added as such. + if (areMutuallyExclusive === false) { + return result === false; + } + return true; + } + + add(a: string, b: string, areMutuallyExclusive: boolean) { + _pairSetAdd(this._data, a, b, areMutuallyExclusive); + _pairSetAdd(this._data, b, a, areMutuallyExclusive); + } +} + +function _pairSetAdd(data, a, b, areMutuallyExclusive) { + let map = data[a]; + if (!map) { + map = Object.create(null); + data[a] = map; + } + map[b] = areMutuallyExclusive; +} diff --git a/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.mjs b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.mjs new file mode 100644 index 0000000..fce16c2 --- /dev/null +++ b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.mjs @@ -0,0 +1,586 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import inspect from '../../jsutils/inspect'; +import find from '../../jsutils/find'; +import { Kind } from '../../language/kinds'; +import { print } from '../../language/printer'; +import { getNamedType, isNonNullType, isLeafType, isObjectType, isListType, isInterfaceType } from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; +export function fieldsConflictMessage(responseName, reason) { + return "Fields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(reason), ". ") + 'Use different aliases on the fields to fetch both if this was intentional.'; +} + +function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason.map(function (_ref) { + var responseName = _ref[0], + subreason = _ref[1]; + return "subfields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(subreason)); + }).join(' and '); + } + + return reason; +} +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ + + +export function OverlappingFieldsCanBeMerged(context) { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + + var cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet: function SelectionSet(selectionSet) { + var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet); + + for (var _i = 0; _i < conflicts.length; _i++) { + var _ref3 = conflicts[_i]; + var _ref2$ = _ref3[0]; + var responseName = _ref2$[0]; + var reason = _ref2$[1]; + var fields1 = _ref3[1]; + var fields2 = _ref3[2]; + context.reportError(new GraphQLError(fieldsConflictMessage(responseName, reason), fields1.concat(fields2))); + } + } + }; +} + +/** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ +// Find all conflicts found "within" a selection set, including those found +// via spreading in fragments. Called when visiting each SelectionSet in the +// GraphQL Document. +function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) { + var conflicts = []; + + var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet), + fieldMap = _getFieldsAndFragment[0], + fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + + + collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap); + + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + var comparedFragments = Object.create(null); + + for (var i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + + for (var j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]); + } + } + } + + return conflicts; +} // Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. + + +function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) { + // Memoize so a fragment is not compared for conflicts more than once. + if (comparedFragments[fragmentName]) { + return; + } + + comparedFragments[fragmentName] = true; + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + return; + } + + var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment), + fieldMap2 = _getReferencedFieldsA[0], + fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself. + + + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + + for (var i = 0; i < fragmentNames2.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]); + } +} // Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. + + +function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + + + if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { + return; + } + + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + var fragment1 = context.getFragment(fragmentName1); + var fragment2 = context.getFragment(fragmentName2); + + if (!fragment1 || !fragment2) { + return; + } + + var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1), + fieldMap1 = _getReferencedFieldsA2[0], + fragmentNames1 = _getReferencedFieldsA2[1]; + + var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2), + fieldMap2 = _getReferencedFieldsA3[0], + fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + + + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2); + } +} // Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. + + +function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) { + var conflicts = []; + + var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1), + fieldMap1 = _getFieldsAndFragment2[0], + fragmentNames1 = _getFieldsAndFragment2[1]; + + var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2), + fieldMap2 = _getFieldsAndFragment3[0], + fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + + if (fragmentNames2.length !== 0) { + var comparedFragments = Object.create(null); + + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]); + } + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + + + if (fragmentNames1.length !== 0) { + var _comparedFragments = Object.create(null); + + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, _comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]); + } + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + + + for (var _i2 = 0; _i2 < fragmentNames1.length; _i2++) { + for (var _j = 0; _j < fragmentNames2.length; _j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i2], fragmentNames2[_j]); + } + } + + return conflicts; +} // Collect all Conflicts "within" one collection of fields. + + +function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + var _arr = Object.keys(fieldMap); + + for (var _i3 = 0; _i3 < _arr.length; _i3++) { + var responseName = _arr[_i3]; + var fields = fieldMap[responseName]; // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + + if (fields.length > 1) { + for (var i = 0; i < fields.length; i++) { + for (var j = i + 1; j < fields.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive + responseName, fields[i], fields[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. + + +function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + var _arr2 = Object.keys(fieldMap1); + + for (var _i4 = 0; _i4 < _arr2.length; _i4++) { + var responseName = _arr2[_i4]; + var fields2 = fieldMap2[responseName]; + + if (fields2) { + var fields1 = fieldMap1[responseName]; + + for (var i = 0; i < fields1.length; i++) { + for (var j = 0; j < fields2.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. + + +function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) { + var parentType1 = field1[0], + node1 = field1[1], + def1 = field1[2]; + var parentType2 = field2[0], + node2 = field2[1], + def2 = field2[2]; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + + var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && isObjectType(parentType1) && isObjectType(parentType2); // The return type for each field. + + var type1 = def1 && def1.type; + var type2 = def2 && def2.type; + + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + var name1 = node1.name.value; + var name2 = node2.name.value; + + if (name1 !== name2) { + return [[responseName, "".concat(name1, " and ").concat(name2, " are different fields")], [node1], [node2]]; + } // Two field calls must have the same arguments. + + + if (!sameArguments(node1.arguments || [], node2.arguments || [])) { + return [[responseName, 'they have differing arguments'], [node1], [node2]]; + } + } + + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [[responseName, "they return conflicting types ".concat(inspect(type1), " and ").concat(inspect(type2))], [node1], [node2]]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + + + var selectionSet1 = node1.selectionSet; + var selectionSet2 = node2.selectionSet; + + if (selectionSet1 && selectionSet2) { + var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, getNamedType(type1), selectionSet1, getNamedType(type2), selectionSet2); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} + +function sameArguments(arguments1, arguments2) { + if (arguments1.length !== arguments2.length) { + return false; + } + + return arguments1.every(function (argument1) { + var argument2 = find(arguments2, function (argument) { + return argument.name.value === argument1.name.value; + }); + + if (!argument2) { + return false; + } + + return sameValue(argument1.value, argument2.value); + }); +} + +function sameValue(value1, value2) { + return !value1 && !value2 || print(value1) === print(value2); +} // Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. + + +function doTypesConflict(type1, type2) { + if (isListType(type1)) { + return isListType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if (isListType(type2)) { + return true; + } + + if (isNonNullType(type1)) { + return isNonNullType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if (isNonNullType(type2)) { + return true; + } + + if (isLeafType(type1) || isLeafType(type2)) { + return type1 !== type2; + } + + return false; +} // Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. + + +function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) { + var cached = cachedFieldsAndFragmentNames.get(selectionSet); + + if (!cached) { + var nodeAndDefs = Object.create(null); + var fragmentNames = Object.create(null); + + _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames); + + cached = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, cached); + } + + return cached; +} // Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. + + +function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) { + // Short-circuit building a type from the node if possible. + var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + + if (cached) { + return cached; + } + + var fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet); +} + +function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) { + for (var i = 0; i < selectionSet.selections.length; i++) { + var selection = selectionSet.selections[i]; + + switch (selection.kind) { + case Kind.FIELD: + var fieldName = selection.name.value; + var fieldDef = void 0; + + if (isObjectType(parentType) || isInterfaceType(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + + var responseName = selection.alias ? selection.alias.value : fieldName; + + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + + case Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + + case Kind.INLINE_FRAGMENT: + var typeCondition = selection.typeCondition; + var inlineFragmentType = typeCondition ? typeFromAST(context.getSchema(), typeCondition) : parentType; + + _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames); + + break; + } + } +} // Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. + + +function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [[responseName, conflicts.map(function (_ref4) { + var reason = _ref4[0]; + return reason; + })], conflicts.reduce(function (allFields, _ref5) { + var fields1 = _ref5[1]; + return allFields.concat(fields1); + }, [node1]), conflicts.reduce(function (allFields, _ref6) { + var fields2 = _ref6[2]; + return allFields.concat(fields2); + }, [node2])]; + } +} +/** + * A way to keep track of pairs of things when the ordering of the pair does + * not matter. We do this by maintaining a sort of double adjacency sets. + */ + + +var PairSet = +/*#__PURE__*/ +function () { + function PairSet() { + _defineProperty(this, "_data", void 0); + + this._data = Object.create(null); + } + + var _proto = PairSet.prototype; + + _proto.has = function has(a, b, areMutuallyExclusive) { + var first = this._data[a]; + var result = first && first[b]; + + if (result === undefined) { + return false; + } // areMutuallyExclusive being false is a superset of being true, + // hence if we want to know if this PairSet "has" these two with no + // exclusivity, we have to ensure it was added as such. + + + if (areMutuallyExclusive === false) { + return result === false; + } + + return true; + }; + + _proto.add = function add(a, b, areMutuallyExclusive) { + _pairSetAdd(this._data, a, b, areMutuallyExclusive); + + _pairSetAdd(this._data, b, a, areMutuallyExclusive); + }; + + return PairSet; +}(); + +function _pairSetAdd(data, a, b, areMutuallyExclusive) { + var map = data[a]; + + if (!map) { + map = Object.create(null); + data[a] = map; + } + + map[b] = areMutuallyExclusive; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js new file mode 100644 index 0000000..28e1ae4 --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js @@ -0,0 +1,78 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.typeIncompatibleSpreadMessage = typeIncompatibleSpreadMessage; +exports.typeIncompatibleAnonSpreadMessage = typeIncompatibleAnonSpreadMessage; +exports.PossibleFragmentSpreads = PossibleFragmentSpreads; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _GraphQLError = require("../../error/GraphQLError"); + +var _typeComparators = require("../../utilities/typeComparators"); + +var _typeFromAST = require("../../utilities/typeFromAST"); + +var _definition = require("../../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function typeIncompatibleSpreadMessage(fragName, parentType, fragType) { + return "Fragment \"".concat(fragName, "\" cannot be spread here as objects of ") + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\"."); +} + +function typeIncompatibleAnonSpreadMessage(parentType, fragType) { + return 'Fragment cannot be spread here as objects of ' + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\"."); +} +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ + + +function PossibleFragmentSpreads(context) { + return { + InlineFragment: function InlineFragment(node) { + var fragType = context.getType(); + var parentType = context.getParentType(); + + if ((0, _definition.isCompositeType)(fragType) && (0, _definition.isCompositeType)(parentType) && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + context.reportError(new _GraphQLError.GraphQLError(typeIncompatibleAnonSpreadMessage((0, _inspect.default)(parentType), (0, _inspect.default)(fragType)), [node])); + } + }, + FragmentSpread: function FragmentSpread(node) { + var fragName = node.name.value; + var fragType = getFragmentType(context, fragName); + var parentType = context.getParentType(); + + if (fragType && parentType && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + context.reportError(new _GraphQLError.GraphQLError(typeIncompatibleSpreadMessage(fragName, (0, _inspect.default)(parentType), (0, _inspect.default)(fragType)), [node])); + } + } + }; +} + +function getFragmentType(context, name) { + var frag = context.getFragment(name); + + if (frag) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition); + + if ((0, _definition.isCompositeType)(type)) { + return type; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js.flow b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js.flow new file mode 100644 index 0000000..bbcadae --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js.flow @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../../jsutils/inspect'; +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; +import { doTypesOverlap } from '../../utilities/typeComparators'; +import { typeFromAST } from '../../utilities/typeFromAST'; +import { isCompositeType } from '../../type/definition'; + +export function typeIncompatibleSpreadMessage( + fragName: string, + parentType: string, + fragType: string, +): string { + return ( + `Fragment "${fragName}" cannot be spread here as objects of ` + + `type "${parentType}" can never be of type "${fragType}".` + ); +} + +export function typeIncompatibleAnonSpreadMessage( + parentType: string, + fragType: string, +): string { + return ( + 'Fragment cannot be spread here as objects of ' + + `type "${parentType}" can never be of type "${fragType}".` + ); +} + +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ +export function PossibleFragmentSpreads( + context: ValidationContext, +): ASTVisitor { + return { + InlineFragment(node) { + const fragType = context.getType(); + const parentType = context.getParentType(); + if ( + isCompositeType(fragType) && + isCompositeType(parentType) && + !doTypesOverlap(context.getSchema(), fragType, parentType) + ) { + context.reportError( + new GraphQLError( + typeIncompatibleAnonSpreadMessage( + inspect(parentType), + inspect(fragType), + ), + [node], + ), + ); + } + }, + FragmentSpread(node) { + const fragName = node.name.value; + const fragType = getFragmentType(context, fragName); + const parentType = context.getParentType(); + if ( + fragType && + parentType && + !doTypesOverlap(context.getSchema(), fragType, parentType) + ) { + context.reportError( + new GraphQLError( + typeIncompatibleSpreadMessage( + fragName, + inspect(parentType), + inspect(fragType), + ), + [node], + ), + ); + } + }, + }; +} + +function getFragmentType(context, name) { + const frag = context.getFragment(name); + if (frag) { + const type = typeFromAST(context.getSchema(), frag.typeCondition); + if (isCompositeType(type)) { + return type; + } + } +} diff --git a/node_modules/graphql/validation/rules/PossibleFragmentSpreads.mjs b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.mjs new file mode 100644 index 0000000..9b0b858 --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.mjs @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../../jsutils/inspect'; +import { GraphQLError } from '../../error/GraphQLError'; +import { doTypesOverlap } from '../../utilities/typeComparators'; +import { typeFromAST } from '../../utilities/typeFromAST'; +import { isCompositeType } from '../../type/definition'; +export function typeIncompatibleSpreadMessage(fragName, parentType, fragType) { + return "Fragment \"".concat(fragName, "\" cannot be spread here as objects of ") + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\"."); +} +export function typeIncompatibleAnonSpreadMessage(parentType, fragType) { + return 'Fragment cannot be spread here as objects of ' + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\"."); +} +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ + +export function PossibleFragmentSpreads(context) { + return { + InlineFragment: function InlineFragment(node) { + var fragType = context.getType(); + var parentType = context.getParentType(); + + if (isCompositeType(fragType) && isCompositeType(parentType) && !doTypesOverlap(context.getSchema(), fragType, parentType)) { + context.reportError(new GraphQLError(typeIncompatibleAnonSpreadMessage(inspect(parentType), inspect(fragType)), [node])); + } + }, + FragmentSpread: function FragmentSpread(node) { + var fragName = node.name.value; + var fragType = getFragmentType(context, fragName); + var parentType = context.getParentType(); + + if (fragType && parentType && !doTypesOverlap(context.getSchema(), fragType, parentType)) { + context.reportError(new GraphQLError(typeIncompatibleSpreadMessage(fragName, inspect(parentType), inspect(fragType)), [node])); + } + } + }; +} + +function getFragmentType(context, name) { + var frag = context.getFragment(name); + + if (frag) { + var type = typeFromAST(context.getSchema(), frag.typeCondition); + + if (isCompositeType(type)) { + return type; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js new file mode 100644 index 0000000..cf2f12f --- /dev/null +++ b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js @@ -0,0 +1,185 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.missingFieldArgMessage = missingFieldArgMessage; +exports.missingDirectiveArgMessage = missingDirectiveArgMessage; +exports.ProvidedRequiredArguments = ProvidedRequiredArguments; +exports.ProvidedRequiredArgumentsOnDirectives = ProvidedRequiredArgumentsOnDirectives; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _kinds = require("../../language/kinds"); + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _keyMap = _interopRequireDefault(require("../../jsutils/keyMap")); + +var _definition = require("../../type/definition"); + +var _printer = require("../../language/printer"); + +var _directives = require("../../type/directives"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function missingFieldArgMessage(fieldName, argName, type) { + return "Field \"".concat(fieldName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required but not provided."); +} + +function missingDirectiveArgMessage(directiveName, argName, type) { + return "Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required but not provided."); +} +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ + + +function ProvidedRequiredArguments(context) { + return _objectSpread({}, ProvidedRequiredArgumentsOnDirectives(context), { + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(fieldNode) { + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + return false; + } + + var argNodes = fieldNode.arguments || []; + var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) { + return arg.name.value; + }); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = fieldDef.args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var argDef = _step.value; + var argNode = argNodeMap[argDef.name]; + + if (!argNode && (0, _definition.isRequiredArgument)(argDef)) { + context.reportError(new _GraphQLError.GraphQLError(missingFieldArgMessage(fieldDef.name, argDef.name, (0, _inspect.default)(argDef.type)), [fieldNode])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + } + }); +} // @internal + + +function ProvidedRequiredArgumentsOnDirectives(context) { + var requiredArgsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = definedDirectives[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var directive = _step2.value; + requiredArgsMap[directive.name] = (0, _keyMap.default)(directive.args.filter(_definition.isRequiredArgument), function (arg) { + return arg.name; + }); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = astDefinitions[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var def = _step3.value; + + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + requiredArgsMap[def.name.value] = (0, _keyMap.default)(def.arguments ? def.arguments.filter(isRequiredArgumentNode) : [], function (arg) { + return arg.name.value; + }); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(directiveNode) { + var directiveName = directiveNode.name.value; + var requiredArgs = requiredArgsMap[directiveName]; + + if (requiredArgs) { + var argNodes = directiveNode.arguments || []; + var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) { + return arg.name.value; + }); + + var _arr = Object.keys(requiredArgs); + + for (var _i = 0; _i < _arr.length; _i++) { + var argName = _arr[_i]; + + if (!argNodeMap[argName]) { + var argType = requiredArgs[argName].type; + context.reportError(new _GraphQLError.GraphQLError(missingDirectiveArgMessage(directiveName, argName, (0, _definition.isType)(argType) ? (0, _inspect.default)(argType) : (0, _printer.print)(argType)), directiveNode)); + } + } + } + } + } + }; +} + +function isRequiredArgumentNode(arg) { + return arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js.flow b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js.flow new file mode 100644 index 0000000..7ed1c58 --- /dev/null +++ b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js.flow @@ -0,0 +1,145 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { + ValidationContext, + SDLValidationContext, +} from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import inspect from '../../jsutils/inspect'; +import keyMap from '../../jsutils/keyMap'; +import { isType, isRequiredArgument } from '../../type/definition'; +import type { ASTVisitor } from '../../language/visitor'; +import { print } from '../../language/printer'; +import { specifiedDirectives } from '../../type/directives'; + +export function missingFieldArgMessage( + fieldName: string, + argName: string, + type: string, +): string { + return ( + `Field "${fieldName}" argument "${argName}" of type ` + + `"${type}" is required but not provided.` + ); +} + +export function missingDirectiveArgMessage( + directiveName: string, + argName: string, + type: string, +): string { + return ( + `Directive "@${directiveName}" argument "${argName}" of type ` + + `"${type}" is required but not provided.` + ); +} + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ +export function ProvidedRequiredArguments( + context: ValidationContext, +): ASTVisitor { + return { + ...ProvidedRequiredArgumentsOnDirectives(context), + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave(fieldNode) { + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + return false; + } + const argNodes = fieldNode.arguments || []; + + const argNodeMap = keyMap(argNodes, arg => arg.name.value); + for (const argDef of fieldDef.args) { + const argNode = argNodeMap[argDef.name]; + if (!argNode && isRequiredArgument(argDef)) { + context.reportError( + new GraphQLError( + missingFieldArgMessage( + fieldDef.name, + argDef.name, + inspect(argDef.type), + ), + [fieldNode], + ), + ); + } + } + }, + }, + }; +} + +// @internal +export function ProvidedRequiredArgumentsOnDirectives( + context: ValidationContext | SDLValidationContext, +): ASTVisitor { + const requiredArgsMap = Object.create(null); + + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + for (const directive of definedDirectives) { + requiredArgsMap[directive.name] = keyMap( + directive.args.filter(isRequiredArgument), + arg => arg.name, + ); + } + + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + requiredArgsMap[def.name.value] = keyMap( + def.arguments ? def.arguments.filter(isRequiredArgumentNode) : [], + arg => arg.name.value, + ); + } + } + + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave(directiveNode) { + const directiveName = directiveNode.name.value; + const requiredArgs = requiredArgsMap[directiveName]; + if (requiredArgs) { + const argNodes = directiveNode.arguments || []; + const argNodeMap = keyMap(argNodes, arg => arg.name.value); + for (const argName of Object.keys(requiredArgs)) { + if (!argNodeMap[argName]) { + const argType = requiredArgs[argName].type; + context.reportError( + new GraphQLError( + missingDirectiveArgMessage( + directiveName, + argName, + isType(argType) ? inspect(argType) : print(argType), + ), + directiveNode, + ), + ); + } + } + } + }, + }, + }; +} + +function isRequiredArgumentNode(arg) { + return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null; +} diff --git a/node_modules/graphql/validation/rules/ProvidedRequiredArguments.mjs b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.mjs new file mode 100644 index 0000000..0badafa --- /dev/null +++ b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.mjs @@ -0,0 +1,171 @@ +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import inspect from '../../jsutils/inspect'; +import keyMap from '../../jsutils/keyMap'; +import { isType, isRequiredArgument } from '../../type/definition'; +import { print } from '../../language/printer'; +import { specifiedDirectives } from '../../type/directives'; +export function missingFieldArgMessage(fieldName, argName, type) { + return "Field \"".concat(fieldName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required but not provided."); +} +export function missingDirectiveArgMessage(directiveName, argName, type) { + return "Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required but not provided."); +} +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ + +export function ProvidedRequiredArguments(context) { + return _objectSpread({}, ProvidedRequiredArgumentsOnDirectives(context), { + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(fieldNode) { + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + return false; + } + + var argNodes = fieldNode.arguments || []; + var argNodeMap = keyMap(argNodes, function (arg) { + return arg.name.value; + }); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = fieldDef.args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var argDef = _step.value; + var argNode = argNodeMap[argDef.name]; + + if (!argNode && isRequiredArgument(argDef)) { + context.reportError(new GraphQLError(missingFieldArgMessage(fieldDef.name, argDef.name, inspect(argDef.type)), [fieldNode])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + } + }); +} // @internal + +export function ProvidedRequiredArgumentsOnDirectives(context) { + var requiredArgsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = definedDirectives[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var directive = _step2.value; + requiredArgsMap[directive.name] = keyMap(directive.args.filter(isRequiredArgument), function (arg) { + return arg.name; + }); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = astDefinitions[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var def = _step3.value; + + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + requiredArgsMap[def.name.value] = keyMap(def.arguments ? def.arguments.filter(isRequiredArgumentNode) : [], function (arg) { + return arg.name.value; + }); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(directiveNode) { + var directiveName = directiveNode.name.value; + var requiredArgs = requiredArgsMap[directiveName]; + + if (requiredArgs) { + var argNodes = directiveNode.arguments || []; + var argNodeMap = keyMap(argNodes, function (arg) { + return arg.name.value; + }); + + var _arr = Object.keys(requiredArgs); + + for (var _i = 0; _i < _arr.length; _i++) { + var argName = _arr[_i]; + + if (!argNodeMap[argName]) { + var argType = requiredArgs[argName].type; + context.reportError(new GraphQLError(missingDirectiveArgMessage(directiveName, argName, isType(argType) ? inspect(argType) : print(argType)), directiveNode)); + } + } + } + } + } + }; +} + +function isRequiredArgumentNode(arg) { + return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ScalarLeafs.js b/node_modules/graphql/validation/rules/ScalarLeafs.js new file mode 100644 index 0000000..55ae9a8 --- /dev/null +++ b/node_modules/graphql/validation/rules/ScalarLeafs.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.noSubselectionAllowedMessage = noSubselectionAllowedMessage; +exports.requiredSubselectionMessage = requiredSubselectionMessage; +exports.ScalarLeafs = ScalarLeafs; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _GraphQLError = require("../../error/GraphQLError"); + +var _definition = require("../../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function noSubselectionAllowedMessage(fieldName, type) { + return "Field \"".concat(fieldName, "\" must not have a selection since ") + "type \"".concat(type, "\" has no subfields."); +} + +function requiredSubselectionMessage(fieldName, type) { + return "Field \"".concat(fieldName, "\" of type \"").concat(type, "\" must have a ") + "selection of subfields. Did you mean \"".concat(fieldName, " { ... }\"?"); +} +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ + + +function ScalarLeafs(context) { + return { + Field: function Field(node) { + var type = context.getType(); + var selectionSet = node.selectionSet; + + if (type) { + if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) { + if (selectionSet) { + context.reportError(new _GraphQLError.GraphQLError(noSubselectionAllowedMessage(node.name.value, (0, _inspect.default)(type)), [selectionSet])); + } + } else if (!selectionSet) { + context.reportError(new _GraphQLError.GraphQLError(requiredSubselectionMessage(node.name.value, (0, _inspect.default)(type)), [node])); + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ScalarLeafs.js.flow b/node_modules/graphql/validation/rules/ScalarLeafs.js.flow new file mode 100644 index 0000000..b7fe066 --- /dev/null +++ b/node_modules/graphql/validation/rules/ScalarLeafs.js.flow @@ -0,0 +1,69 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../../jsutils/inspect'; +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { FieldNode } from '../../language/ast'; +import { getNamedType, isLeafType } from '../../type/definition'; +import type { ASTVisitor } from '../../language/visitor'; + +export function noSubselectionAllowedMessage( + fieldName: string, + type: string, +): string { + return ( + `Field "${fieldName}" must not have a selection since ` + + `type "${type}" has no subfields.` + ); +} + +export function requiredSubselectionMessage( + fieldName: string, + type: string, +): string { + return ( + `Field "${fieldName}" of type "${type}" must have a ` + + `selection of subfields. Did you mean "${fieldName} { ... }"?` + ); +} + +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ +export function ScalarLeafs(context: ValidationContext): ASTVisitor { + return { + Field(node: FieldNode) { + const type = context.getType(); + const selectionSet = node.selectionSet; + if (type) { + if (isLeafType(getNamedType(type))) { + if (selectionSet) { + context.reportError( + new GraphQLError( + noSubselectionAllowedMessage(node.name.value, inspect(type)), + [selectionSet], + ), + ); + } + } else if (!selectionSet) { + context.reportError( + new GraphQLError( + requiredSubselectionMessage(node.name.value, inspect(type)), + [node], + ), + ); + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/ScalarLeafs.mjs b/node_modules/graphql/validation/rules/ScalarLeafs.mjs new file mode 100644 index 0000000..39d6d58 --- /dev/null +++ b/node_modules/graphql/validation/rules/ScalarLeafs.mjs @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../../jsutils/inspect'; +import { GraphQLError } from '../../error/GraphQLError'; +import { getNamedType, isLeafType } from '../../type/definition'; +export function noSubselectionAllowedMessage(fieldName, type) { + return "Field \"".concat(fieldName, "\" must not have a selection since ") + "type \"".concat(type, "\" has no subfields."); +} +export function requiredSubselectionMessage(fieldName, type) { + return "Field \"".concat(fieldName, "\" of type \"").concat(type, "\" must have a ") + "selection of subfields. Did you mean \"".concat(fieldName, " { ... }\"?"); +} +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ + +export function ScalarLeafs(context) { + return { + Field: function Field(node) { + var type = context.getType(); + var selectionSet = node.selectionSet; + + if (type) { + if (isLeafType(getNamedType(type))) { + if (selectionSet) { + context.reportError(new GraphQLError(noSubselectionAllowedMessage(node.name.value, inspect(type)), [selectionSet])); + } + } else if (!selectionSet) { + context.reportError(new GraphQLError(requiredSubselectionMessage(node.name.value, inspect(type)), [node])); + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js new file mode 100644 index 0000000..602e4c7 --- /dev/null +++ b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.singleFieldOnlyMessage = singleFieldOnlyMessage; +exports.SingleFieldSubscriptions = SingleFieldSubscriptions; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function singleFieldOnlyMessage(name) { + return (name ? "Subscription \"".concat(name, "\" ") : 'Anonymous Subscription ') + 'must select only one top level field.'; +} +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ + + +function SingleFieldSubscriptions(context) { + return { + OperationDefinition: function OperationDefinition(node) { + if (node.operation === 'subscription') { + if (node.selectionSet.selections.length !== 1) { + context.reportError(new _GraphQLError.GraphQLError(singleFieldOnlyMessage(node.name && node.name.value), node.selectionSet.selections.slice(1))); + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js.flow b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js.flow new file mode 100644 index 0000000..6230a12 --- /dev/null +++ b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js.flow @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { OperationDefinitionNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; + +export function singleFieldOnlyMessage(name: ?string): string { + return ( + (name ? `Subscription "${name}" ` : 'Anonymous Subscription ') + + 'must select only one top level field.' + ); +} + +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ +export function SingleFieldSubscriptions( + context: ASTValidationContext, +): ASTVisitor { + return { + OperationDefinition(node: OperationDefinitionNode) { + if (node.operation === 'subscription') { + if (node.selectionSet.selections.length !== 1) { + context.reportError( + new GraphQLError( + singleFieldOnlyMessage(node.name && node.name.value), + node.selectionSet.selections.slice(1), + ), + ); + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/SingleFieldSubscriptions.mjs b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.mjs new file mode 100644 index 0000000..a0e5fcd --- /dev/null +++ b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.mjs @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function singleFieldOnlyMessage(name) { + return (name ? "Subscription \"".concat(name, "\" ") : 'Anonymous Subscription ') + 'must select only one top level field.'; +} +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ + +export function SingleFieldSubscriptions(context) { + return { + OperationDefinition: function OperationDefinition(node) { + if (node.operation === 'subscription') { + if (node.selectionSet.selections.length !== 1) { + context.reportError(new GraphQLError(singleFieldOnlyMessage(node.name && node.name.value), node.selectionSet.selections.slice(1))); + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueArgumentNames.js b/node_modules/graphql/validation/rules/UniqueArgumentNames.js new file mode 100644 index 0000000..e9aafef --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentNames.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateArgMessage = duplicateArgMessage; +exports.UniqueArgumentNames = UniqueArgumentNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateArgMessage(argName) { + return "There can be only one argument named \"".concat(argName, "\"."); +} +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ + + +function UniqueArgumentNames(context) { + var knownArgNames = Object.create(null); + return { + Field: function Field() { + knownArgNames = Object.create(null); + }, + Directive: function Directive() { + knownArgNames = Object.create(null); + }, + Argument: function Argument(node) { + var argName = node.name.value; + + if (knownArgNames[argName]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateArgMessage(argName), [knownArgNames[argName], node.name])); + } else { + knownArgNames[argName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueArgumentNames.js.flow b/node_modules/graphql/validation/rules/UniqueArgumentNames.js.flow new file mode 100644 index 0000000..a49768c --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentNames.js.flow @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateArgMessage(argName: string): string { + return `There can be only one argument named "${argName}".`; +} + +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ +export function UniqueArgumentNames(context: ASTValidationContext): ASTVisitor { + let knownArgNames = Object.create(null); + return { + Field() { + knownArgNames = Object.create(null); + }, + Directive() { + knownArgNames = Object.create(null); + }, + Argument(node) { + const argName = node.name.value; + if (knownArgNames[argName]) { + context.reportError( + new GraphQLError(duplicateArgMessage(argName), [ + knownArgNames[argName], + node.name, + ]), + ); + } else { + knownArgNames[argName] = node.name; + } + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueArgumentNames.mjs b/node_modules/graphql/validation/rules/UniqueArgumentNames.mjs new file mode 100644 index 0000000..3a4b29e --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentNames.mjs @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateArgMessage(argName) { + return "There can be only one argument named \"".concat(argName, "\"."); +} +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ + +export function UniqueArgumentNames(context) { + var knownArgNames = Object.create(null); + return { + Field: function Field() { + knownArgNames = Object.create(null); + }, + Directive: function Directive() { + knownArgNames = Object.create(null); + }, + Argument: function Argument(node) { + var argName = node.name.value; + + if (knownArgNames[argName]) { + context.reportError(new GraphQLError(duplicateArgMessage(argName), [knownArgNames[argName], node.name])); + } else { + knownArgNames[argName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js new file mode 100644 index 0000000..bee9686 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateDirectiveMessage = duplicateDirectiveMessage; +exports.UniqueDirectivesPerLocation = UniqueDirectivesPerLocation; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateDirectiveMessage(directiveName) { + return "The directive \"".concat(directiveName, "\" can only be used once at ") + 'this location.'; +} +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all directives at a given location + * are uniquely named. + */ + + +function UniqueDirectivesPerLocation(context) { + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter: function enter(node) { + // Flow can't refine that node.directives will only contain directives, + var directives = node.directives; + + if (directives) { + var knownDirectives = Object.create(null); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = directives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + var directiveName = directive.name.value; + + if (knownDirectives[directiveName]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateDirectiveMessage(directiveName), [knownDirectives[directiveName], directive])); + } else { + knownDirectives[directiveName] = directive; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js.flow b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js.flow new file mode 100644 index 0000000..a866d81 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js.flow @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { DirectiveNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateDirectiveMessage(directiveName: string): string { + return ( + `The directive "${directiveName}" can only be used once at ` + + 'this location.' + ); +} + +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all directives at a given location + * are uniquely named. + */ +export function UniqueDirectivesPerLocation( + context: ASTValidationContext, +): ASTVisitor { + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter(node) { + // Flow can't refine that node.directives will only contain directives, + // so we cast so the rest of the code is well typed. + const directives: ?$ReadOnlyArray = (node: any).directives; + if (directives) { + const knownDirectives = Object.create(null); + for (const directive of directives) { + const directiveName = directive.name.value; + if (knownDirectives[directiveName]) { + context.reportError( + new GraphQLError(duplicateDirectiveMessage(directiveName), [ + knownDirectives[directiveName], + directive, + ]), + ); + } else { + knownDirectives[directiveName] = directive; + } + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.mjs b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.mjs new file mode 100644 index 0000000..d908fd3 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.mjs @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateDirectiveMessage(directiveName) { + return "The directive \"".concat(directiveName, "\" can only be used once at ") + 'this location.'; +} +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all directives at a given location + * are uniquely named. + */ + +export function UniqueDirectivesPerLocation(context) { + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter: function enter(node) { + // Flow can't refine that node.directives will only contain directives, + var directives = node.directives; + + if (directives) { + var knownDirectives = Object.create(null); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = directives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + var directiveName = directive.name.value; + + if (knownDirectives[directiveName]) { + context.reportError(new GraphQLError(duplicateDirectiveMessage(directiveName), [knownDirectives[directiveName], directive])); + } else { + knownDirectives[directiveName] = directive; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueFragmentNames.js b/node_modules/graphql/validation/rules/UniqueFragmentNames.js new file mode 100644 index 0000000..12719b8 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFragmentNames.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateFragmentNameMessage = duplicateFragmentNameMessage; +exports.UniqueFragmentNames = UniqueFragmentNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateFragmentNameMessage(fragName) { + return "There can be only one fragment named \"".concat(fragName, "\"."); +} +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ + + +function UniqueFragmentNames(context) { + var knownFragmentNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + var fragmentName = node.name.value; + + if (knownFragmentNames[fragmentName]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name])); + } else { + knownFragmentNames[fragmentName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueFragmentNames.js.flow b/node_modules/graphql/validation/rules/UniqueFragmentNames.js.flow new file mode 100644 index 0000000..b03a8a4 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFragmentNames.js.flow @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateFragmentNameMessage(fragName: string): string { + return `There can be only one fragment named "${fragName}".`; +} + +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ +export function UniqueFragmentNames(context: ASTValidationContext): ASTVisitor { + const knownFragmentNames = Object.create(null); + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + const fragmentName = node.name.value; + if (knownFragmentNames[fragmentName]) { + context.reportError( + new GraphQLError(duplicateFragmentNameMessage(fragmentName), [ + knownFragmentNames[fragmentName], + node.name, + ]), + ); + } else { + knownFragmentNames[fragmentName] = node.name; + } + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueFragmentNames.mjs b/node_modules/graphql/validation/rules/UniqueFragmentNames.mjs new file mode 100644 index 0000000..602a98a --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFragmentNames.mjs @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateFragmentNameMessage(fragName) { + return "There can be only one fragment named \"".concat(fragName, "\"."); +} +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ + +export function UniqueFragmentNames(context) { + var knownFragmentNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + var fragmentName = node.name.value; + + if (knownFragmentNames[fragmentName]) { + context.reportError(new GraphQLError(duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name])); + } else { + knownFragmentNames[fragmentName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueInputFieldNames.js b/node_modules/graphql/validation/rules/UniqueInputFieldNames.js new file mode 100644 index 0000000..b1bab2a --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueInputFieldNames.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateInputFieldMessage = duplicateInputFieldMessage; +exports.UniqueInputFieldNames = UniqueInputFieldNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateInputFieldMessage(fieldName) { + return "There can be only one input field named \"".concat(fieldName, "\"."); +} +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ + + +function UniqueInputFieldNames(context) { + var knownNameStack = []; + var knownNames = Object.create(null); + return { + ObjectValue: { + enter: function enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave: function leave() { + knownNames = knownNameStack.pop(); + } + }, + ObjectField: function ObjectField(node) { + var fieldName = node.name.value; + + if (knownNames[fieldName]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateInputFieldMessage(fieldName), [knownNames[fieldName], node.name])); + } else { + knownNames[fieldName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueInputFieldNames.js.flow b/node_modules/graphql/validation/rules/UniqueInputFieldNames.js.flow new file mode 100644 index 0000000..3a07772 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueInputFieldNames.js.flow @@ -0,0 +1,55 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateInputFieldMessage(fieldName: string): string { + return `There can be only one input field named "${fieldName}".`; +} + +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ +export function UniqueInputFieldNames( + context: ASTValidationContext, +): ASTVisitor { + const knownNameStack = []; + let knownNames = Object.create(null); + + return { + ObjectValue: { + enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave() { + knownNames = knownNameStack.pop(); + }, + }, + ObjectField(node) { + const fieldName = node.name.value; + if (knownNames[fieldName]) { + context.reportError( + new GraphQLError(duplicateInputFieldMessage(fieldName), [ + knownNames[fieldName], + node.name, + ]), + ); + } else { + knownNames[fieldName] = node.name; + } + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueInputFieldNames.mjs b/node_modules/graphql/validation/rules/UniqueInputFieldNames.mjs new file mode 100644 index 0000000..c36424e --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueInputFieldNames.mjs @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateInputFieldMessage(fieldName) { + return "There can be only one input field named \"".concat(fieldName, "\"."); +} +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ + +export function UniqueInputFieldNames(context) { + var knownNameStack = []; + var knownNames = Object.create(null); + return { + ObjectValue: { + enter: function enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave: function leave() { + knownNames = knownNameStack.pop(); + } + }, + ObjectField: function ObjectField(node) { + var fieldName = node.name.value; + + if (knownNames[fieldName]) { + context.reportError(new GraphQLError(duplicateInputFieldMessage(fieldName), [knownNames[fieldName], node.name])); + } else { + knownNames[fieldName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueOperationNames.js b/node_modules/graphql/validation/rules/UniqueOperationNames.js new file mode 100644 index 0000000..f64f323 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationNames.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateOperationNameMessage = duplicateOperationNameMessage; +exports.UniqueOperationNames = UniqueOperationNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateOperationNameMessage(operationName) { + return "There can be only one operation named \"".concat(operationName, "\"."); +} +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ + + +function UniqueOperationNames(context) { + var knownOperationNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition(node) { + var operationName = node.name; + + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateOperationNameMessage(operationName.value), [knownOperationNames[operationName.value], operationName])); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + + return false; + }, + FragmentDefinition: function FragmentDefinition() { + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueOperationNames.js.flow b/node_modules/graphql/validation/rules/UniqueOperationNames.js.flow new file mode 100644 index 0000000..d476346 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationNames.js.flow @@ -0,0 +1,46 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateOperationNameMessage(operationName: string): string { + return `There can be only one operation named "${operationName}".`; +} + +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ +export function UniqueOperationNames( + context: ASTValidationContext, +): ASTVisitor { + const knownOperationNames = Object.create(null); + return { + OperationDefinition(node) { + const operationName = node.name; + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError( + new GraphQLError( + duplicateOperationNameMessage(operationName.value), + [knownOperationNames[operationName.value], operationName], + ), + ); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + return false; + }, + FragmentDefinition: () => false, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueOperationNames.mjs b/node_modules/graphql/validation/rules/UniqueOperationNames.mjs new file mode 100644 index 0000000..2d6c180 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationNames.mjs @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateOperationNameMessage(operationName) { + return "There can be only one operation named \"".concat(operationName, "\"."); +} +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ + +export function UniqueOperationNames(context) { + var knownOperationNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition(node) { + var operationName = node.name; + + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError(new GraphQLError(duplicateOperationNameMessage(operationName.value), [knownOperationNames[operationName.value], operationName])); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + + return false; + }, + FragmentDefinition: function FragmentDefinition() { + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueVariableNames.js b/node_modules/graphql/validation/rules/UniqueVariableNames.js new file mode 100644 index 0000000..d374cd0 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueVariableNames.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateVariableMessage = duplicateVariableMessage; +exports.UniqueVariableNames = UniqueVariableNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateVariableMessage(variableName) { + return "There can be only one variable named \"".concat(variableName, "\"."); +} +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ + + +function UniqueVariableNames(context) { + var knownVariableNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + knownVariableNames = Object.create(null); + }, + VariableDefinition: function VariableDefinition(node) { + var variableName = node.variable.name.value; + + if (knownVariableNames[variableName]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateVariableMessage(variableName), [knownVariableNames[variableName], node.variable.name])); + } else { + knownVariableNames[variableName] = node.variable.name; + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueVariableNames.js.flow b/node_modules/graphql/validation/rules/UniqueVariableNames.js.flow new file mode 100644 index 0000000..7020d28 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueVariableNames.js.flow @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import type { VariableDefinitionNode } from '../../language/ast'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateVariableMessage(variableName: string): string { + return `There can be only one variable named "${variableName}".`; +} + +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ +export function UniqueVariableNames(context: ASTValidationContext): ASTVisitor { + let knownVariableNames = Object.create(null); + return { + OperationDefinition() { + knownVariableNames = Object.create(null); + }, + VariableDefinition(node: VariableDefinitionNode) { + const variableName = node.variable.name.value; + if (knownVariableNames[variableName]) { + context.reportError( + new GraphQLError(duplicateVariableMessage(variableName), [ + knownVariableNames[variableName], + node.variable.name, + ]), + ); + } else { + knownVariableNames[variableName] = node.variable.name; + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueVariableNames.mjs b/node_modules/graphql/validation/rules/UniqueVariableNames.mjs new file mode 100644 index 0000000..4c86f9d --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueVariableNames.mjs @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateVariableMessage(variableName) { + return "There can be only one variable named \"".concat(variableName, "\"."); +} +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ + +export function UniqueVariableNames(context) { + var knownVariableNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + knownVariableNames = Object.create(null); + }, + VariableDefinition: function VariableDefinition(node) { + var variableName = node.variable.name.value; + + if (knownVariableNames[variableName]) { + context.reportError(new GraphQLError(duplicateVariableMessage(variableName), [knownVariableNames[variableName], node.variable.name])); + } else { + knownVariableNames[variableName] = node.variable.name; + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ValuesOfCorrectType.js b/node_modules/graphql/validation/rules/ValuesOfCorrectType.js new file mode 100644 index 0000000..1851119 --- /dev/null +++ b/node_modules/graphql/validation/rules/ValuesOfCorrectType.js @@ -0,0 +1,182 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.badValueMessage = badValueMessage; +exports.requiredFieldMessage = requiredFieldMessage; +exports.unknownFieldMessage = unknownFieldMessage; +exports.ValuesOfCorrectType = ValuesOfCorrectType; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _printer = require("../../language/printer"); + +var _definition = require("../../type/definition"); + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _isInvalid = _interopRequireDefault(require("../../jsutils/isInvalid")); + +var _keyMap = _interopRequireDefault(require("../../jsutils/keyMap")); + +var _orList = _interopRequireDefault(require("../../jsutils/orList")); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function badValueMessage(typeName, valueName, message) { + return "Expected type ".concat(typeName, ", found ").concat(valueName) + (message ? "; ".concat(message) : '.'); +} + +function requiredFieldMessage(typeName, fieldName, fieldTypeName) { + return "Field ".concat(typeName, ".").concat(fieldName, " of required type ") + "".concat(fieldTypeName, " was not provided."); +} + +function unknownFieldMessage(typeName, fieldName, message) { + return "Field \"".concat(fieldName, "\" is not defined by type ").concat(typeName) + (message ? "; ".concat(message) : '.'); +} +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + */ + + +function ValuesOfCorrectType(context) { + return { + NullValue: function NullValue(node) { + var type = context.getInputType(); + + if ((0, _definition.isNonNullType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(type), (0, _printer.print)(node)), node)); + } + }, + ListValue: function ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + var type = (0, _definition.getNullableType)(context.getParentInputType()); + + if (!(0, _definition.isListType)(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } + }, + ObjectValue: function ObjectValue(node) { + var type = (0, _definition.getNamedType)(context.getInputType()); + + if (!(0, _definition.isInputObjectType)(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. + + + var inputFields = type.getFields(); + var fieldNodeMap = (0, _keyMap.default)(node.fields, function (field) { + return field.name.value; + }); + + var _arr = Object.keys(inputFields); + + for (var _i = 0; _i < _arr.length; _i++) { + var fieldName = _arr[_i]; + var fieldDef = inputFields[fieldName]; + var fieldNode = fieldNodeMap[fieldName]; + + if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) { + var typeStr = (0, _inspect.default)(fieldDef.type); + context.reportError(new _GraphQLError.GraphQLError(requiredFieldMessage(type.name, fieldName, typeStr), node)); + } + } + }, + ObjectField: function ObjectField(node) { + var parentType = (0, _definition.getNamedType)(context.getParentInputType()); + var fieldType = context.getInputType(); + + if (!fieldType && (0, _definition.isInputObjectType)(parentType)) { + var suggestions = (0, _suggestionList.default)(node.name.value, Object.keys(parentType.getFields())); + var didYouMean = suggestions.length !== 0 ? "Did you mean ".concat((0, _orList.default)(suggestions), "?") : undefined; + context.reportError(new _GraphQLError.GraphQLError(unknownFieldMessage(parentType.name, node.name.value, didYouMean), node)); + } + }, + EnumValue: function EnumValue(node) { + var type = (0, _definition.getNamedType)(context.getInputType()); + + if (!(0, _definition.isEnumType)(type)) { + isValidScalar(context, node); + } else if (!type.getValue(node.value)) { + context.reportError(new _GraphQLError.GraphQLError(badValueMessage(type.name, (0, _printer.print)(node), enumTypeSuggestion(type, node)), node)); + } + }, + IntValue: function IntValue(node) { + return isValidScalar(context, node); + }, + FloatValue: function FloatValue(node) { + return isValidScalar(context, node); + }, + StringValue: function StringValue(node) { + return isValidScalar(context, node); + }, + BooleanValue: function BooleanValue(node) { + return isValidScalar(context, node); + } + }; +} +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ + + +function isValidScalar(context, node) { + // Report any error at the full type expected by the location. + var locationType = context.getInputType(); + + if (!locationType) { + return; + } + + var type = (0, _definition.getNamedType)(locationType); + + if (!(0, _definition.isScalarType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node), enumTypeSuggestion(type, node)), node)); + return; + } // Scalars determine if a literal value is valid via parseLiteral() which + // may throw or return an invalid value to indicate failure. + + + try { + var parseResult = type.parseLiteral(node, undefined + /* variables */ + ); + + if ((0, _isInvalid.default)(parseResult)) { + context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node)), node)); + } + } catch (error) { + // Ensure a reference to the original error is maintained. + context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node), error.message), node, undefined, undefined, undefined, error)); + } +} + +function enumTypeSuggestion(type, node) { + if ((0, _definition.isEnumType)(type)) { + var suggestions = (0, _suggestionList.default)((0, _printer.print)(node), type.getValues().map(function (value) { + return value.name; + })); + + if (suggestions.length !== 0) { + return "Did you mean the enum value ".concat((0, _orList.default)(suggestions), "?"); + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ValuesOfCorrectType.js.flow b/node_modules/graphql/validation/rules/ValuesOfCorrectType.js.flow new file mode 100644 index 0000000..8df1358 --- /dev/null +++ b/node_modules/graphql/validation/rules/ValuesOfCorrectType.js.flow @@ -0,0 +1,221 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ValueNode } from '../../language/ast'; +import { print } from '../../language/printer'; +import type { ASTVisitor } from '../../language/visitor'; +import { + isScalarType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isRequiredInputField, + getNullableType, + getNamedType, +} from '../../type/definition'; +import type { GraphQLType } from '../../type/definition'; +import inspect from '../../jsutils/inspect'; +import isInvalid from '../../jsutils/isInvalid'; +import keyMap from '../../jsutils/keyMap'; +import orList from '../../jsutils/orList'; +import suggestionList from '../../jsutils/suggestionList'; + +export function badValueMessage( + typeName: string, + valueName: string, + message?: string, +): string { + return ( + `Expected type ${typeName}, found ${valueName}` + + (message ? `; ${message}` : '.') + ); +} + +export function requiredFieldMessage( + typeName: string, + fieldName: string, + fieldTypeName: string, +): string { + return ( + `Field ${typeName}.${fieldName} of required type ` + + `${fieldTypeName} was not provided.` + ); +} + +export function unknownFieldMessage( + typeName: string, + fieldName: string, + message?: string, +): string { + return ( + `Field "${fieldName}" is not defined by type ${typeName}` + + (message ? `; ${message}` : '.') + ); +} + +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + */ +export function ValuesOfCorrectType(context: ValidationContext): ASTVisitor { + return { + NullValue(node) { + const type = context.getInputType(); + if (isNonNullType(type)) { + context.reportError( + new GraphQLError(badValueMessage(inspect(type), print(node)), node), + ); + } + }, + ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + const type = getNullableType(context.getParentInputType()); + if (!isListType(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } + }, + ObjectValue(node) { + const type = getNamedType(context.getInputType()); + if (!isInputObjectType(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } + // Ensure every required field exists. + const inputFields = type.getFields(); + const fieldNodeMap = keyMap(node.fields, field => field.name.value); + for (const fieldName of Object.keys(inputFields)) { + const fieldDef = inputFields[fieldName]; + const fieldNode = fieldNodeMap[fieldName]; + if (!fieldNode && isRequiredInputField(fieldDef)) { + const typeStr = inspect(fieldDef.type); + context.reportError( + new GraphQLError( + requiredFieldMessage(type.name, fieldName, typeStr), + node, + ), + ); + } + } + }, + ObjectField(node) { + const parentType = getNamedType(context.getParentInputType()); + const fieldType = context.getInputType(); + if (!fieldType && isInputObjectType(parentType)) { + const suggestions = suggestionList( + node.name.value, + Object.keys(parentType.getFields()), + ); + const didYouMean = + suggestions.length !== 0 + ? `Did you mean ${orList(suggestions)}?` + : undefined; + context.reportError( + new GraphQLError( + unknownFieldMessage(parentType.name, node.name.value, didYouMean), + node, + ), + ); + } + }, + EnumValue(node) { + const type = getNamedType(context.getInputType()); + if (!isEnumType(type)) { + isValidScalar(context, node); + } else if (!type.getValue(node.value)) { + context.reportError( + new GraphQLError( + badValueMessage( + type.name, + print(node), + enumTypeSuggestion(type, node), + ), + node, + ), + ); + } + }, + IntValue: node => isValidScalar(context, node), + FloatValue: node => isValidScalar(context, node), + StringValue: node => isValidScalar(context, node), + BooleanValue: node => isValidScalar(context, node), + }; +} + +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ +function isValidScalar(context: ValidationContext, node: ValueNode): void { + // Report any error at the full type expected by the location. + const locationType = context.getInputType(); + if (!locationType) { + return; + } + + const type = getNamedType(locationType); + + if (!isScalarType(type)) { + context.reportError( + new GraphQLError( + badValueMessage( + inspect(locationType), + print(node), + enumTypeSuggestion(type, node), + ), + node, + ), + ); + return; + } + + // Scalars determine if a literal value is valid via parseLiteral() which + // may throw or return an invalid value to indicate failure. + try { + const parseResult = type.parseLiteral(node, undefined /* variables */); + if (isInvalid(parseResult)) { + context.reportError( + new GraphQLError( + badValueMessage(inspect(locationType), print(node)), + node, + ), + ); + } + } catch (error) { + // Ensure a reference to the original error is maintained. + context.reportError( + new GraphQLError( + badValueMessage(inspect(locationType), print(node), error.message), + node, + undefined, + undefined, + undefined, + error, + ), + ); + } +} + +function enumTypeSuggestion(type: GraphQLType, node: ValueNode): string | void { + if (isEnumType(type)) { + const suggestions = suggestionList( + print(node), + type.getValues().map(value => value.name), + ); + if (suggestions.length !== 0) { + return `Did you mean the enum value ${orList(suggestions)}?`; + } + } +} diff --git a/node_modules/graphql/validation/rules/ValuesOfCorrectType.mjs b/node_modules/graphql/validation/rules/ValuesOfCorrectType.mjs new file mode 100644 index 0000000..a1907c0 --- /dev/null +++ b/node_modules/graphql/validation/rules/ValuesOfCorrectType.mjs @@ -0,0 +1,158 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { print } from '../../language/printer'; +import { isScalarType, isEnumType, isInputObjectType, isListType, isNonNullType, isRequiredInputField, getNullableType, getNamedType } from '../../type/definition'; +import inspect from '../../jsutils/inspect'; +import isInvalid from '../../jsutils/isInvalid'; +import keyMap from '../../jsutils/keyMap'; +import orList from '../../jsutils/orList'; +import suggestionList from '../../jsutils/suggestionList'; +export function badValueMessage(typeName, valueName, message) { + return "Expected type ".concat(typeName, ", found ").concat(valueName) + (message ? "; ".concat(message) : '.'); +} +export function requiredFieldMessage(typeName, fieldName, fieldTypeName) { + return "Field ".concat(typeName, ".").concat(fieldName, " of required type ") + "".concat(fieldTypeName, " was not provided."); +} +export function unknownFieldMessage(typeName, fieldName, message) { + return "Field \"".concat(fieldName, "\" is not defined by type ").concat(typeName) + (message ? "; ".concat(message) : '.'); +} +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + */ + +export function ValuesOfCorrectType(context) { + return { + NullValue: function NullValue(node) { + var type = context.getInputType(); + + if (isNonNullType(type)) { + context.reportError(new GraphQLError(badValueMessage(inspect(type), print(node)), node)); + } + }, + ListValue: function ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + var type = getNullableType(context.getParentInputType()); + + if (!isListType(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } + }, + ObjectValue: function ObjectValue(node) { + var type = getNamedType(context.getInputType()); + + if (!isInputObjectType(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. + + + var inputFields = type.getFields(); + var fieldNodeMap = keyMap(node.fields, function (field) { + return field.name.value; + }); + + var _arr = Object.keys(inputFields); + + for (var _i = 0; _i < _arr.length; _i++) { + var fieldName = _arr[_i]; + var fieldDef = inputFields[fieldName]; + var fieldNode = fieldNodeMap[fieldName]; + + if (!fieldNode && isRequiredInputField(fieldDef)) { + var typeStr = inspect(fieldDef.type); + context.reportError(new GraphQLError(requiredFieldMessage(type.name, fieldName, typeStr), node)); + } + } + }, + ObjectField: function ObjectField(node) { + var parentType = getNamedType(context.getParentInputType()); + var fieldType = context.getInputType(); + + if (!fieldType && isInputObjectType(parentType)) { + var suggestions = suggestionList(node.name.value, Object.keys(parentType.getFields())); + var didYouMean = suggestions.length !== 0 ? "Did you mean ".concat(orList(suggestions), "?") : undefined; + context.reportError(new GraphQLError(unknownFieldMessage(parentType.name, node.name.value, didYouMean), node)); + } + }, + EnumValue: function EnumValue(node) { + var type = getNamedType(context.getInputType()); + + if (!isEnumType(type)) { + isValidScalar(context, node); + } else if (!type.getValue(node.value)) { + context.reportError(new GraphQLError(badValueMessage(type.name, print(node), enumTypeSuggestion(type, node)), node)); + } + }, + IntValue: function IntValue(node) { + return isValidScalar(context, node); + }, + FloatValue: function FloatValue(node) { + return isValidScalar(context, node); + }, + StringValue: function StringValue(node) { + return isValidScalar(context, node); + }, + BooleanValue: function BooleanValue(node) { + return isValidScalar(context, node); + } + }; +} +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ + +function isValidScalar(context, node) { + // Report any error at the full type expected by the location. + var locationType = context.getInputType(); + + if (!locationType) { + return; + } + + var type = getNamedType(locationType); + + if (!isScalarType(type)) { + context.reportError(new GraphQLError(badValueMessage(inspect(locationType), print(node), enumTypeSuggestion(type, node)), node)); + return; + } // Scalars determine if a literal value is valid via parseLiteral() which + // may throw or return an invalid value to indicate failure. + + + try { + var parseResult = type.parseLiteral(node, undefined + /* variables */ + ); + + if (isInvalid(parseResult)) { + context.reportError(new GraphQLError(badValueMessage(inspect(locationType), print(node)), node)); + } + } catch (error) { + // Ensure a reference to the original error is maintained. + context.reportError(new GraphQLError(badValueMessage(inspect(locationType), print(node), error.message), node, undefined, undefined, undefined, error)); + } +} + +function enumTypeSuggestion(type, node) { + if (isEnumType(type)) { + var suggestions = suggestionList(print(node), type.getValues().map(function (value) { + return value.name; + })); + + if (suggestions.length !== 0) { + return "Did you mean the enum value ".concat(orList(suggestions), "?"); + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/VariablesAreInputTypes.js b/node_modules/graphql/validation/rules/VariablesAreInputTypes.js new file mode 100644 index 0000000..b4853b6 --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesAreInputTypes.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.nonInputTypeOnVarMessage = nonInputTypeOnVarMessage; +exports.VariablesAreInputTypes = VariablesAreInputTypes; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _printer = require("../../language/printer"); + +var _definition = require("../../type/definition"); + +var _typeFromAST = require("../../utilities/typeFromAST"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function nonInputTypeOnVarMessage(variableName, typeName) { + return "Variable \"$".concat(variableName, "\" cannot be non-input type \"").concat(typeName, "\"."); +} +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ + + +function VariablesAreInputTypes(context) { + return { + VariableDefinition: function VariableDefinition(node) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.type); // If the variable type is not an input type, return an error. + + if (type && !(0, _definition.isInputType)(type)) { + var variableName = node.variable.name.value; + context.reportError(new _GraphQLError.GraphQLError(nonInputTypeOnVarMessage(variableName, (0, _printer.print)(node.type)), [node.type])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/VariablesAreInputTypes.js.flow b/node_modules/graphql/validation/rules/VariablesAreInputTypes.js.flow new file mode 100644 index 0000000..455cfda --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesAreInputTypes.js.flow @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { VariableDefinitionNode } from '../../language/ast'; +import { print } from '../../language/printer'; +import type { ASTVisitor } from '../../language/visitor'; +import { isInputType } from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; + +export function nonInputTypeOnVarMessage( + variableName: string, + typeName: string, +): string { + return `Variable "$${variableName}" cannot be non-input type "${typeName}".`; +} + +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ +export function VariablesAreInputTypes(context: ValidationContext): ASTVisitor { + return { + VariableDefinition(node: VariableDefinitionNode): ?GraphQLError { + const type = typeFromAST(context.getSchema(), node.type); + + // If the variable type is not an input type, return an error. + if (type && !isInputType(type)) { + const variableName = node.variable.name.value; + context.reportError( + new GraphQLError( + nonInputTypeOnVarMessage(variableName, print(node.type)), + [node.type], + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/VariablesAreInputTypes.mjs b/node_modules/graphql/validation/rules/VariablesAreInputTypes.mjs new file mode 100644 index 0000000..d1810d0 --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesAreInputTypes.mjs @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { print } from '../../language/printer'; +import { isInputType } from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; +export function nonInputTypeOnVarMessage(variableName, typeName) { + return "Variable \"$".concat(variableName, "\" cannot be non-input type \"").concat(typeName, "\"."); +} +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ + +export function VariablesAreInputTypes(context) { + return { + VariableDefinition: function VariableDefinition(node) { + var type = typeFromAST(context.getSchema(), node.type); // If the variable type is not an input type, return an error. + + if (type && !isInputType(type)) { + var variableName = node.variable.name.value; + context.reportError(new GraphQLError(nonInputTypeOnVarMessage(variableName, print(node.type)), [node.type])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js new file mode 100644 index 0000000..7c4fdd0 --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js @@ -0,0 +1,117 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.badVarPosMessage = badVarPosMessage; +exports.VariablesInAllowedPosition = VariablesInAllowedPosition; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _GraphQLError = require("../../error/GraphQLError"); + +var _kinds = require("../../language/kinds"); + +var _definition = require("../../type/definition"); + +var _typeComparators = require("../../utilities/typeComparators"); + +var _typeFromAST = require("../../utilities/typeFromAST"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function badVarPosMessage(varName, varType, expectedType) { + return "Variable \"$".concat(varName, "\" of type \"").concat(varType, "\" used in ") + "position expecting type \"".concat(expectedType, "\"."); +} +/** + * Variables passed to field arguments conform to type + */ + + +function VariablesInAllowedPosition(context) { + var varDefMap = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + varDefMap = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node, + type = _ref2.type, + defaultValue = _ref2.defaultValue; + var varName = node.name.value; + var varDef = varDefMap[varName]; + + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + var schema = context.getSchema(); + var varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type); + + if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) { + context.reportError(new _GraphQLError.GraphQLError(badVarPosMessage(varName, (0, _inspect.default)(varType), (0, _inspect.default)(type)), [varDef, node])); + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + } + }; +} +/** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ + + +function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) { + if ((0, _definition.isNonNullType)(locationType) && !(0, _definition.isNonNullType)(varType)) { + var hasNonNullVariableDefaultValue = varDefaultValue && varDefaultValue.kind !== _kinds.Kind.NULL; + var hasLocationDefaultValue = locationDefaultValue !== undefined; + + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + + var nullableLocationType = locationType.ofType; + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, nullableLocationType); + } + + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType); +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js.flow b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js.flow new file mode 100644 index 0000000..5b1f017 --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js.flow @@ -0,0 +1,110 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../../jsutils/inspect'; +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import type { ValueNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; +import { isNonNullType } from '../../type/definition'; +import { isTypeSubTypeOf } from '../../utilities/typeComparators'; +import { typeFromAST } from '../../utilities/typeFromAST'; +import type { GraphQLType } from '../../type/definition'; +import type { GraphQLSchema } from '../../type/schema'; + +export function badVarPosMessage( + varName: string, + varType: string, + expectedType: string, +): string { + return ( + `Variable "$${varName}" of type "${varType}" used in ` + + `position expecting type "${expectedType}".` + ); +} + +/** + * Variables passed to field arguments conform to type + */ +export function VariablesInAllowedPosition( + context: ValidationContext, +): ASTVisitor { + let varDefMap = Object.create(null); + + return { + OperationDefinition: { + enter() { + varDefMap = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node, type, defaultValue } of usages) { + const varName = node.name.value; + const varDef = varDefMap[varName]; + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + const schema = context.getSchema(); + const varType = typeFromAST(schema, varDef.type); + if ( + varType && + !allowedVariableUsage( + schema, + varType, + varDef.defaultValue, + type, + defaultValue, + ) + ) { + context.reportError( + new GraphQLError( + badVarPosMessage(varName, inspect(varType), inspect(type)), + [varDef, node], + ), + ); + } + } + } + }, + }, + VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + }, + }; +} + +/** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ +function allowedVariableUsage( + schema: GraphQLSchema, + varType: GraphQLType, + varDefaultValue: ?ValueNode, + locationType: GraphQLType, + locationDefaultValue: ?mixed, +): boolean { + if (isNonNullType(locationType) && !isNonNullType(varType)) { + const hasNonNullVariableDefaultValue = + varDefaultValue && varDefaultValue.kind !== Kind.NULL; + const hasLocationDefaultValue = locationDefaultValue !== undefined; + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + const nullableLocationType = locationType.ofType; + return isTypeSubTypeOf(schema, varType, nullableLocationType); + } + return isTypeSubTypeOf(schema, varType, locationType); +} diff --git a/node_modules/graphql/validation/rules/VariablesInAllowedPosition.mjs b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.mjs new file mode 100644 index 0000000..c039ecb --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.mjs @@ -0,0 +1,99 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../../jsutils/inspect'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import { isNonNullType } from '../../type/definition'; +import { isTypeSubTypeOf } from '../../utilities/typeComparators'; +import { typeFromAST } from '../../utilities/typeFromAST'; +export function badVarPosMessage(varName, varType, expectedType) { + return "Variable \"$".concat(varName, "\" of type \"").concat(varType, "\" used in ") + "position expecting type \"".concat(expectedType, "\"."); +} +/** + * Variables passed to field arguments conform to type + */ + +export function VariablesInAllowedPosition(context) { + var varDefMap = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + varDefMap = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node, + type = _ref2.type, + defaultValue = _ref2.defaultValue; + var varName = node.name.value; + var varDef = varDefMap[varName]; + + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + var schema = context.getSchema(); + var varType = typeFromAST(schema, varDef.type); + + if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) { + context.reportError(new GraphQLError(badVarPosMessage(varName, inspect(varType), inspect(type)), [varDef, node])); + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + } + }; +} +/** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ + +function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) { + if (isNonNullType(locationType) && !isNonNullType(varType)) { + var hasNonNullVariableDefaultValue = varDefaultValue && varDefaultValue.kind !== Kind.NULL; + var hasLocationDefaultValue = locationDefaultValue !== undefined; + + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + + var nullableLocationType = locationType.ofType; + return isTypeSubTypeOf(schema, varType, nullableLocationType); + } + + return isTypeSubTypeOf(schema, varType, locationType); +} \ No newline at end of file diff --git a/node_modules/graphql/validation/specifiedRules.js b/node_modules/graphql/validation/specifiedRules.js new file mode 100644 index 0000000..9065587 --- /dev/null +++ b/node_modules/graphql/validation/specifiedRules.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.specifiedSDLRules = exports.specifiedRules = void 0; + +var _ExecutableDefinitions = require("./rules/ExecutableDefinitions"); + +var _UniqueOperationNames = require("./rules/UniqueOperationNames"); + +var _LoneAnonymousOperation = require("./rules/LoneAnonymousOperation"); + +var _SingleFieldSubscriptions = require("./rules/SingleFieldSubscriptions"); + +var _KnownTypeNames = require("./rules/KnownTypeNames"); + +var _FragmentsOnCompositeTypes = require("./rules/FragmentsOnCompositeTypes"); + +var _VariablesAreInputTypes = require("./rules/VariablesAreInputTypes"); + +var _ScalarLeafs = require("./rules/ScalarLeafs"); + +var _FieldsOnCorrectType = require("./rules/FieldsOnCorrectType"); + +var _UniqueFragmentNames = require("./rules/UniqueFragmentNames"); + +var _KnownFragmentNames = require("./rules/KnownFragmentNames"); + +var _NoUnusedFragments = require("./rules/NoUnusedFragments"); + +var _PossibleFragmentSpreads = require("./rules/PossibleFragmentSpreads"); + +var _NoFragmentCycles = require("./rules/NoFragmentCycles"); + +var _UniqueVariableNames = require("./rules/UniqueVariableNames"); + +var _NoUndefinedVariables = require("./rules/NoUndefinedVariables"); + +var _NoUnusedVariables = require("./rules/NoUnusedVariables"); + +var _KnownDirectives = require("./rules/KnownDirectives"); + +var _UniqueDirectivesPerLocation = require("./rules/UniqueDirectivesPerLocation"); + +var _KnownArgumentNames = require("./rules/KnownArgumentNames"); + +var _UniqueArgumentNames = require("./rules/UniqueArgumentNames"); + +var _ValuesOfCorrectType = require("./rules/ValuesOfCorrectType"); + +var _ProvidedRequiredArguments = require("./rules/ProvidedRequiredArguments"); + +var _VariablesInAllowedPosition = require("./rules/VariablesInAllowedPosition"); + +var _OverlappingFieldsCanBeMerged = require("./rules/OverlappingFieldsCanBeMerged"); + +var _UniqueInputFieldNames = require("./rules/UniqueInputFieldNames"); + +var _LoneSchemaDefinition = require("./rules/LoneSchemaDefinition"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +// Spec Section: "Executable Definitions" +// Spec Section: "Operation Name Uniqueness" +// Spec Section: "Lone Anonymous Operation" +// Spec Section: "Subscriptions with Single Root Field" +// Spec Section: "Fragment Spread Type Existence" +// Spec Section: "Fragments on Composite Types" +// Spec Section: "Variables are Input Types" +// Spec Section: "Leaf Field Selections" +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +// Spec Section: "Fragment Name Uniqueness" +// Spec Section: "Fragment spread target defined" +// Spec Section: "Fragments must be used" +// Spec Section: "Fragment spread is possible" +// Spec Section: "Fragments must not form cycles" +// Spec Section: "Variable Uniqueness" +// Spec Section: "All Variable Used Defined" +// Spec Section: "All Variables Used" +// Spec Section: "Directives Are Defined" +// Spec Section: "Directives Are Unique Per Location" +// Spec Section: "Argument Names" +// Spec Section: "Argument Uniqueness" +// Spec Section: "Value Type Correctness" +// Spec Section: "Argument Optionality" +// Spec Section: "All Variable Usages Are Allowed" +// Spec Section: "Field Selection Merging" +// Spec Section: "Input Object Field Uniqueness" + +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ +var specifiedRules = [_ExecutableDefinitions.ExecutableDefinitions, _UniqueOperationNames.UniqueOperationNames, _LoneAnonymousOperation.LoneAnonymousOperation, _SingleFieldSubscriptions.SingleFieldSubscriptions, _KnownTypeNames.KnownTypeNames, _FragmentsOnCompositeTypes.FragmentsOnCompositeTypes, _VariablesAreInputTypes.VariablesAreInputTypes, _ScalarLeafs.ScalarLeafs, _FieldsOnCorrectType.FieldsOnCorrectType, _UniqueFragmentNames.UniqueFragmentNames, _KnownFragmentNames.KnownFragmentNames, _NoUnusedFragments.NoUnusedFragments, _PossibleFragmentSpreads.PossibleFragmentSpreads, _NoFragmentCycles.NoFragmentCycles, _UniqueVariableNames.UniqueVariableNames, _NoUndefinedVariables.NoUndefinedVariables, _NoUnusedVariables.NoUnusedVariables, _KnownDirectives.KnownDirectives, _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation, _KnownArgumentNames.KnownArgumentNames, _UniqueArgumentNames.UniqueArgumentNames, _ValuesOfCorrectType.ValuesOfCorrectType, _ProvidedRequiredArguments.ProvidedRequiredArguments, _VariablesInAllowedPosition.VariablesInAllowedPosition, _OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged, _UniqueInputFieldNames.UniqueInputFieldNames]; +exports.specifiedRules = specifiedRules; +// @internal +var specifiedSDLRules = [_LoneSchemaDefinition.LoneSchemaDefinition, _KnownDirectives.KnownDirectives, _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation, _KnownArgumentNames.KnownArgumentNamesOnDirectives, _UniqueArgumentNames.UniqueArgumentNames, _UniqueInputFieldNames.UniqueInputFieldNames, _ProvidedRequiredArguments.ProvidedRequiredArgumentsOnDirectives]; +exports.specifiedSDLRules = specifiedSDLRules; \ No newline at end of file diff --git a/node_modules/graphql/validation/specifiedRules.js.flow b/node_modules/graphql/validation/specifiedRules.js.flow new file mode 100644 index 0000000..f4e1960 --- /dev/null +++ b/node_modules/graphql/validation/specifiedRules.js.flow @@ -0,0 +1,138 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationRule, SDLValidationRule } from './ValidationContext'; + +// Spec Section: "Executable Definitions" +import { ExecutableDefinitions } from './rules/ExecutableDefinitions'; + +// Spec Section: "Operation Name Uniqueness" +import { UniqueOperationNames } from './rules/UniqueOperationNames'; + +// Spec Section: "Lone Anonymous Operation" +import { LoneAnonymousOperation } from './rules/LoneAnonymousOperation'; + +// Spec Section: "Subscriptions with Single Root Field" +import { SingleFieldSubscriptions } from './rules/SingleFieldSubscriptions'; + +// Spec Section: "Fragment Spread Type Existence" +import { KnownTypeNames } from './rules/KnownTypeNames'; + +// Spec Section: "Fragments on Composite Types" +import { FragmentsOnCompositeTypes } from './rules/FragmentsOnCompositeTypes'; + +// Spec Section: "Variables are Input Types" +import { VariablesAreInputTypes } from './rules/VariablesAreInputTypes'; + +// Spec Section: "Leaf Field Selections" +import { ScalarLeafs } from './rules/ScalarLeafs'; + +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +import { FieldsOnCorrectType } from './rules/FieldsOnCorrectType'; + +// Spec Section: "Fragment Name Uniqueness" +import { UniqueFragmentNames } from './rules/UniqueFragmentNames'; + +// Spec Section: "Fragment spread target defined" +import { KnownFragmentNames } from './rules/KnownFragmentNames'; + +// Spec Section: "Fragments must be used" +import { NoUnusedFragments } from './rules/NoUnusedFragments'; + +// Spec Section: "Fragment spread is possible" +import { PossibleFragmentSpreads } from './rules/PossibleFragmentSpreads'; + +// Spec Section: "Fragments must not form cycles" +import { NoFragmentCycles } from './rules/NoFragmentCycles'; + +// Spec Section: "Variable Uniqueness" +import { UniqueVariableNames } from './rules/UniqueVariableNames'; + +// Spec Section: "All Variable Used Defined" +import { NoUndefinedVariables } from './rules/NoUndefinedVariables'; + +// Spec Section: "All Variables Used" +import { NoUnusedVariables } from './rules/NoUnusedVariables'; + +// Spec Section: "Directives Are Defined" +import { KnownDirectives } from './rules/KnownDirectives'; + +// Spec Section: "Directives Are Unique Per Location" +import { UniqueDirectivesPerLocation } from './rules/UniqueDirectivesPerLocation'; + +// Spec Section: "Argument Names" +import { KnownArgumentNames } from './rules/KnownArgumentNames'; + +// Spec Section: "Argument Uniqueness" +import { UniqueArgumentNames } from './rules/UniqueArgumentNames'; + +// Spec Section: "Value Type Correctness" +import { ValuesOfCorrectType } from './rules/ValuesOfCorrectType'; + +// Spec Section: "Argument Optionality" +import { ProvidedRequiredArguments } from './rules/ProvidedRequiredArguments'; + +// Spec Section: "All Variable Usages Are Allowed" +import { VariablesInAllowedPosition } from './rules/VariablesInAllowedPosition'; + +// Spec Section: "Field Selection Merging" +import { OverlappingFieldsCanBeMerged } from './rules/OverlappingFieldsCanBeMerged'; + +// Spec Section: "Input Object Field Uniqueness" +import { UniqueInputFieldNames } from './rules/UniqueInputFieldNames'; + +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ +export const specifiedRules: $ReadOnlyArray = [ + ExecutableDefinitions, + UniqueOperationNames, + LoneAnonymousOperation, + SingleFieldSubscriptions, + KnownTypeNames, + FragmentsOnCompositeTypes, + VariablesAreInputTypes, + ScalarLeafs, + FieldsOnCorrectType, + UniqueFragmentNames, + KnownFragmentNames, + NoUnusedFragments, + PossibleFragmentSpreads, + NoFragmentCycles, + UniqueVariableNames, + NoUndefinedVariables, + NoUnusedVariables, + KnownDirectives, + UniqueDirectivesPerLocation, + KnownArgumentNames, + UniqueArgumentNames, + ValuesOfCorrectType, + ProvidedRequiredArguments, + VariablesInAllowedPosition, + OverlappingFieldsCanBeMerged, + UniqueInputFieldNames, +]; + +import { LoneSchemaDefinition } from './rules/LoneSchemaDefinition'; +import { KnownArgumentNamesOnDirectives } from './rules/KnownArgumentNames'; +import { ProvidedRequiredArgumentsOnDirectives } from './rules/ProvidedRequiredArguments'; + +// @internal +export const specifiedSDLRules: $ReadOnlyArray = [ + LoneSchemaDefinition, + KnownDirectives, + UniqueDirectivesPerLocation, + KnownArgumentNamesOnDirectives, + UniqueArgumentNames, + UniqueInputFieldNames, + ProvidedRequiredArgumentsOnDirectives, +]; diff --git a/node_modules/graphql/validation/specifiedRules.mjs b/node_modules/graphql/validation/specifiedRules.mjs new file mode 100644 index 0000000..97f0bb8 --- /dev/null +++ b/node_modules/graphql/validation/specifiedRules.mjs @@ -0,0 +1,73 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +// Spec Section: "Executable Definitions" +import { ExecutableDefinitions } from './rules/ExecutableDefinitions'; // Spec Section: "Operation Name Uniqueness" + +import { UniqueOperationNames } from './rules/UniqueOperationNames'; // Spec Section: "Lone Anonymous Operation" + +import { LoneAnonymousOperation } from './rules/LoneAnonymousOperation'; // Spec Section: "Subscriptions with Single Root Field" + +import { SingleFieldSubscriptions } from './rules/SingleFieldSubscriptions'; // Spec Section: "Fragment Spread Type Existence" + +import { KnownTypeNames } from './rules/KnownTypeNames'; // Spec Section: "Fragments on Composite Types" + +import { FragmentsOnCompositeTypes } from './rules/FragmentsOnCompositeTypes'; // Spec Section: "Variables are Input Types" + +import { VariablesAreInputTypes } from './rules/VariablesAreInputTypes'; // Spec Section: "Leaf Field Selections" + +import { ScalarLeafs } from './rules/ScalarLeafs'; // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + +import { FieldsOnCorrectType } from './rules/FieldsOnCorrectType'; // Spec Section: "Fragment Name Uniqueness" + +import { UniqueFragmentNames } from './rules/UniqueFragmentNames'; // Spec Section: "Fragment spread target defined" + +import { KnownFragmentNames } from './rules/KnownFragmentNames'; // Spec Section: "Fragments must be used" + +import { NoUnusedFragments } from './rules/NoUnusedFragments'; // Spec Section: "Fragment spread is possible" + +import { PossibleFragmentSpreads } from './rules/PossibleFragmentSpreads'; // Spec Section: "Fragments must not form cycles" + +import { NoFragmentCycles } from './rules/NoFragmentCycles'; // Spec Section: "Variable Uniqueness" + +import { UniqueVariableNames } from './rules/UniqueVariableNames'; // Spec Section: "All Variable Used Defined" + +import { NoUndefinedVariables } from './rules/NoUndefinedVariables'; // Spec Section: "All Variables Used" + +import { NoUnusedVariables } from './rules/NoUnusedVariables'; // Spec Section: "Directives Are Defined" + +import { KnownDirectives } from './rules/KnownDirectives'; // Spec Section: "Directives Are Unique Per Location" + +import { UniqueDirectivesPerLocation } from './rules/UniqueDirectivesPerLocation'; // Spec Section: "Argument Names" + +import { KnownArgumentNames } from './rules/KnownArgumentNames'; // Spec Section: "Argument Uniqueness" + +import { UniqueArgumentNames } from './rules/UniqueArgumentNames'; // Spec Section: "Value Type Correctness" + +import { ValuesOfCorrectType } from './rules/ValuesOfCorrectType'; // Spec Section: "Argument Optionality" + +import { ProvidedRequiredArguments } from './rules/ProvidedRequiredArguments'; // Spec Section: "All Variable Usages Are Allowed" + +import { VariablesInAllowedPosition } from './rules/VariablesInAllowedPosition'; // Spec Section: "Field Selection Merging" + +import { OverlappingFieldsCanBeMerged } from './rules/OverlappingFieldsCanBeMerged'; // Spec Section: "Input Object Field Uniqueness" + +import { UniqueInputFieldNames } from './rules/UniqueInputFieldNames'; +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ + +export var specifiedRules = [ExecutableDefinitions, UniqueOperationNames, LoneAnonymousOperation, SingleFieldSubscriptions, KnownTypeNames, FragmentsOnCompositeTypes, VariablesAreInputTypes, ScalarLeafs, FieldsOnCorrectType, UniqueFragmentNames, KnownFragmentNames, NoUnusedFragments, PossibleFragmentSpreads, NoFragmentCycles, UniqueVariableNames, NoUndefinedVariables, NoUnusedVariables, KnownDirectives, UniqueDirectivesPerLocation, KnownArgumentNames, UniqueArgumentNames, ValuesOfCorrectType, ProvidedRequiredArguments, VariablesInAllowedPosition, OverlappingFieldsCanBeMerged, UniqueInputFieldNames]; +import { LoneSchemaDefinition } from './rules/LoneSchemaDefinition'; +import { KnownArgumentNamesOnDirectives } from './rules/KnownArgumentNames'; +import { ProvidedRequiredArgumentsOnDirectives } from './rules/ProvidedRequiredArguments'; // @internal + +export var specifiedSDLRules = [LoneSchemaDefinition, KnownDirectives, UniqueDirectivesPerLocation, KnownArgumentNamesOnDirectives, UniqueArgumentNames, UniqueInputFieldNames, ProvidedRequiredArgumentsOnDirectives]; \ No newline at end of file diff --git a/node_modules/graphql/validation/validate.js b/node_modules/graphql/validation/validate.js new file mode 100644 index 0000000..f9a4ab5 --- /dev/null +++ b/node_modules/graphql/validation/validate.js @@ -0,0 +1,110 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validate = validate; +exports.validateSDL = validateSDL; +exports.assertValidSDL = assertValidSDL; +exports.assertValidSDLExtension = assertValidSDLExtension; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _visitor = require("../language/visitor"); + +var _validate = require("../type/validate"); + +var _TypeInfo = require("../utilities/TypeInfo"); + +var _specifiedRules = require("./specifiedRules"); + +var _ValidationContext = require("./ValidationContext"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ +function validate(schema, documentAST) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _specifiedRules.specifiedRules; + var typeInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new _TypeInfo.TypeInfo(schema); + !documentAST ? (0, _invariant.default)(0, 'Must provide document') : void 0; // If the schema used for validation is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); + var context = new _ValidationContext.ValidationContext(schema, documentAST, typeInfo); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + + var visitor = (0, _visitor.visitInParallel)(rules.map(function (rule) { + return rule(context); + })); // Visit the whole document with each instance of all provided rules. + + (0, _visitor.visit)(documentAST, (0, _visitor.visitWithTypeInfo)(typeInfo, visitor)); + return context.getErrors(); +} // @internal + + +function validateSDL(documentAST, schemaToExtend) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _specifiedRules.specifiedSDLRules; + var context = new _ValidationContext.SDLValidationContext(documentAST, schemaToExtend); + var visitors = rules.map(function (rule) { + return rule(context); + }); + (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors)); + return context.getErrors(); +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + + +function assertValidSDL(documentAST) { + var errors = validateSDL(documentAST); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + + +function assertValidSDLExtension(documentAST, schema) { + var errors = validateSDL(documentAST, schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/validate.js.flow b/node_modules/graphql/validation/validate.js.flow new file mode 100644 index 0000000..9fe1b2a --- /dev/null +++ b/node_modules/graphql/validation/validate.js.flow @@ -0,0 +1,95 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import type { GraphQLError } from '../error'; +import { visit, visitInParallel, visitWithTypeInfo } from '../language/visitor'; +import type { DocumentNode } from '../language/ast'; +import type { GraphQLSchema } from '../type/schema'; +import { assertValidSchema } from '../type/validate'; +import { TypeInfo } from '../utilities/TypeInfo'; +import { specifiedRules, specifiedSDLRules } from './specifiedRules'; +import type { SDLValidationRule, ValidationRule } from './ValidationContext'; +import { SDLValidationContext, ValidationContext } from './ValidationContext'; + +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ +export function validate( + schema: GraphQLSchema, + documentAST: DocumentNode, + rules?: $ReadOnlyArray = specifiedRules, + typeInfo?: TypeInfo = new TypeInfo(schema), +): $ReadOnlyArray { + invariant(documentAST, 'Must provide document'); + // If the schema used for validation is invalid, throw an error. + assertValidSchema(schema); + + const context = new ValidationContext(schema, documentAST, typeInfo); + // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + const visitor = visitInParallel(rules.map(rule => rule(context))); + // Visit the whole document with each instance of all provided rules. + visit(documentAST, visitWithTypeInfo(typeInfo, visitor)); + return context.getErrors(); +} + +// @internal +export function validateSDL( + documentAST: DocumentNode, + schemaToExtend?: ?GraphQLSchema, + rules?: $ReadOnlyArray = specifiedSDLRules, +): $ReadOnlyArray { + const context = new SDLValidationContext(documentAST, schemaToExtend); + const visitors = rules.map(rule => rule(context)); + visit(documentAST, visitInParallel(visitors)); + return context.getErrors(); +} + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDL(documentAST: DocumentNode): void { + const errors = validateSDL(documentAST); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } +} + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDLExtension( + documentAST: DocumentNode, + schema: GraphQLSchema, +): void { + const errors = validateSDL(documentAST, schema); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } +} diff --git a/node_modules/graphql/validation/validate.mjs b/node_modules/graphql/validation/validate.mjs new file mode 100644 index 0000000..4170787 --- /dev/null +++ b/node_modules/graphql/validation/validate.mjs @@ -0,0 +1,89 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; +import { visit, visitInParallel, visitWithTypeInfo } from '../language/visitor'; +import { assertValidSchema } from '../type/validate'; +import { TypeInfo } from '../utilities/TypeInfo'; +import { specifiedRules, specifiedSDLRules } from './specifiedRules'; +import { SDLValidationContext, ValidationContext } from './ValidationContext'; +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ + +export function validate(schema, documentAST) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : specifiedRules; + var typeInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new TypeInfo(schema); + !documentAST ? invariant(0, 'Must provide document') : void 0; // If the schema used for validation is invalid, throw an error. + + assertValidSchema(schema); + var context = new ValidationContext(schema, documentAST, typeInfo); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + + var visitor = visitInParallel(rules.map(function (rule) { + return rule(context); + })); // Visit the whole document with each instance of all provided rules. + + visit(documentAST, visitWithTypeInfo(typeInfo, visitor)); + return context.getErrors(); +} // @internal + +export function validateSDL(documentAST, schemaToExtend) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : specifiedSDLRules; + var context = new SDLValidationContext(documentAST, schemaToExtend); + var visitors = rules.map(function (rule) { + return rule(context); + }); + visit(documentAST, visitInParallel(visitors)); + return context.getErrors(); +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +export function assertValidSDL(documentAST) { + var errors = validateSDL(documentAST); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +export function assertValidSDLExtension(documentAST, schema) { + var errors = validateSDL(documentAST, schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} \ No newline at end of file diff --git a/node_modules/iterall/LICENSE b/node_modules/iterall/LICENSE new file mode 100644 index 0000000..32653d2 --- /dev/null +++ b/node_modules/iterall/LICENSE @@ -0,0 +1,18 @@ +Copyright (c) 2016 Lee Byron + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/iterall/README.md b/node_modules/iterall/README.md new file mode 100644 index 0000000..6a47da9 --- /dev/null +++ b/node_modules/iterall/README.md @@ -0,0 +1,808 @@ +# JavaScript [Iterators][] and [AsyncIterators][] for all! + +[![Build Status](https://travis-ci.org/leebyron/iterall.svg?branch=master)](https://travis-ci.org/leebyron/iterall) [![Coverage Status](https://coveralls.io/repos/github/leebyron/iterall/badge.svg?branch=master)](https://coveralls.io/github/leebyron/iterall?branch=master) ![710 bytes minified and gzipped](https://img.shields.io/badge/min%20gzip%20size-757%20B-blue.svg) + +`iterall` provides a few crucial utilities for implementing and working with +[Iterables][iterators], [Async Iterables][asynciterators] and +[Array-likes][array-like] in all JavaScript environments, even old versions of +Internet Explorer, in a tiny library weighing well under 1KB when minified +and gzipped. + +This is a library for libraries. If your library takes Arrays as input, accept +Iterables instead. If your library implements a new data-structure, make +it Iterable. + +When installed via `npm`, `iterall` comes complete with [Flow][] and +[TypeScript][] definition files. Don't want to take the dependency? Feel free to +copy code directly from this repository. + +```js +// Limited to only Arrays 😥 +if (Array.isArray(thing)) { + thing.forEach(function (item, i) { + console.log('Index: ' + i, item) + }) +} + +// Accepts all Iterables and Array-likes, in any JavaScript environment! 🎉 +var isCollection = require('iterall').isCollection +var forEach = require('iterall').forEach + +if (isCollection(thing)) { + forEach(thing, function (item, i) { + console.log('Index: ' + i, item) + }) +} + +// Accepts all AsyncIterators, in any JavaScript environment! ⏳ +var forAwaitEach = require('iterall').forAwaitEach + +forAwaitEach(thing, function (item, i) { + console.log('Index: ' + i, item) +}).then(function () { + console.log('Done') +}) +``` + +## Why use Iterators? + +For most of JavaScript's history it has provided two collection data-structures: +the `Object` and the `Array`. These collections can conceptually describe nearly +all data and so it's no suprise that libraries expecting lists of +things standardized on expecting and checking for an Array. This pattern even +resulted in the addition of a new method in ES5: [`Array.isArray()`][isarray]. + +As JavaScript applications grew in complexity, moved to the [server][nodejs] +where CPU is a constrained resource, faced new problems and implemented new +algorithms, new data-structures are often required. With options from +[linked lists][linked list] to [HAMTs][hamt] developers can use what is most +efficient and provides the right properties for their program. + +However none of these new data-structures can be used in libraries where an +`Array` is expected, which means developers are often stuck between abandoning +their favorite libraries or limiting their data-structure choices at the cost of +efficiency or usefulness. + +To enable many related data-structures to be used interchangably we need a +_[protocol][]_, and luckily for us ES2015 introduced the +[Iteration Protocols][iterators] to describe all list-like data-structures which +can be iterated. That includes not just the new-to-ES2015 [Map][] and [Set][] +collections but also existing ones like [arguments][], [NodeList][] and the +various [TypedArray][], all of which return `false` for [`Array.isArray()`][isarray] +and in ES2015 implement the [Iterator protocol][iterators]. + +While Iterators are defined in ES2015, they _do not require_ ES2015 to work +correctly. In fact, Iterators were first introduced in 2012 in [Firefox v17](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Iterator_property_and_iterator_symbol). Rather than using [`Symbol.iterator`][symbol.iterator], they used the property name `"@@iterator"` (in fact, the ECMAScript +spec still refers to well-known `Symbols` using this `@@` shorthand). By falling +back to use `"@@iterator"` when `Symbol.iterator` is not defined, Iterators can +be both safely defined and used by _any version of JavaScript_. + +Not only were Iterables defined in ES2015, they were also implemented by the +built-in data-structures including [Array][array#@@iterator]. Older JavaScript +environments do not implement `Array.prototype[@@iterator]()`, however this is +only a minor problem. JavaScript has another related and much older protocol: +[Array-like]. A value is "Array-like" if it has a numeric `length` property and +indexed access, but does not necessarily have methods like `.push()` or `.forEach()`. +Much like [`Array.from`][array.from], `iterall`'s `forEach()` and +`createIterator()` methods also accept collections which are not Iterable but +are Array-like. This means that `iterall` can be used with [Array][], +[arguments][], [NodeList][], [TypedArray][] and other Array-like collections +regardless of the JavaScript environment. + +When libraries only accept Arrays as input, they stick developers with a tough +choice: limit which data-structures can be used or limit the ability to use that +library. Accepting Iterables removes this false dichotomy, and allows libraries +to be more generally useful. There's no need to limit to ES2015 environments and +bleeding-edge browsers to accept `Iterable`. + +Only using Arrays can limit the efficiency and usefulness of your application +code, but custom data-structures can often feel like a fish out of water in +JavaScript programs, only working with code written specifically for it. +Protocols like `Iterable` helps these new data-structures work with more +libraries and built-in JavaScript behavior. There's no need to limit to ES2015 +environments and bleeding-edge browsers to implement `Iterable`. + +## Why use AsyncIterators? + +In the same way that `Iterator` provides a common interface for accessing many +different kinds of data-structures, `AsyncIterator` provides a common interface +over an asynchronous sequence of values (similar to Stream or Observable). + +Async Iterators are not yet an official part of JavaScript, however they're +a "Stage 3" proposal to be added, and browser vendors are +[working on adding support](https://bugs.chromium.org/p/v8/issues/detail?id=5855). +However, Async Iterators can be both safely defined and used today by +_any version of JavaScript_, by using the utilities in `iterall`. + +## FAQ + +> Aren't Iterables slower than Arrays? I want the highest performance possible. + +Arrays _are_ Iterables. Iterable is a protocol that Arrays adhere to in ES2015. +It's true that creating an Iterator and stepping through it can present some +overhead compared to a simple for-loop or `array.forEach`. However `iterall`'s +`forEach` will delegate directly to `array.forEach` and will use a for-loop for +Array-like objects, ensuring the best performance for Arrays while still +maintaining support for all Iterables. + +> Should my library functions also return Iterables instead of Arrays? Won't +> that be limiting? + +That could definitely be limiting if you return some generic Iterable where you +could have returned an Array, and (depending on context) I wouldn't recommend +you stop returning Arrays from functions if that's what you're doing today. +However if your functions are returning some collection data-structure that is +_not_ an Array, you should certainly consider having them implement the +Iterable protocol so they can be more widely useful. + +Here are a few examples: + +In [React][], render functions are expected to return view trees, where any +node (e.g. a `
    `) can have many children (e.g. many `
  • `). While it could +expect those children to always be represented as an Array, that would limit +React's usefulness - other data-structures couldn't be used. Instead, React +expects those children to be represented as an _Iterable_. That allows it to +continue to accept Arrays, but also accept many other data-structures. + +[Immutable.js][] implements many new kinds of data-structures (including [HAMT]) +all of which implement _Iterable_, which allows them to be used in many of +JavaScript's built-in functions, but also allows them to be used by many +libraries which accept Iterables, including React. Also, similar to +[`Array.from`][array.from], Immutable.js's constructors accept not only Arrays, +but any _Iterable_, allowing you to build any of these new data-structures from +any other data-structure. + +> Where are all the other functions like `map`, `filter`, and `reduce`? + +Those "higher order" collection functions are awesome, but they don't belong in +this library. Instead this library should be used as a basis for building such +a library (as it should be used for many other libraries). The `forEach` +function provided by `iterall` can be used as the underpinning for these. + +As an example: + +```js +function reduce (collection, reducer, initial) { + var reduced = initial + forEach(collection, function (item) { + reduced = reducer(reduced, item) + }) + return reduced +} +``` + +> How do I break out of a `forEach` or `forAwaitEach` loop early? + +While `for of` and `for await of` loops allow breaking out of a loop early with +a `break` statement, the `forEach()` and `forAwaitEach()` functions (much like +Array's `forEach`) do not support early breaking. + +Similar to the "higher order" functions described above, this library can be the +basis for this extended behavior. To support early break outs, you can use a +wrapping function supporting early breaking by throwing a `BREAK` sentinel value +from the callback and using a try/catch block to early break: + +```js +const BREAK = {} + +function forEachBreakable (collection, callback) { + try { + forEach(collection, callback) + } catch (error) { + if (error !== BREAK) { + throw error + } + } +} + +async function forAwaitEachBreakable (collection, callback) { + try { + await forAwaitEach(collection, callback) + } catch (error) { + if (error !== BREAK) { + throw error + } + } +} + +// Example usages: +forEachBreakable(obj, function (value) { + if (shouldBreakOn(value)) { + throw BREAK + } + console.log(value) +}) + +forAwaitEachBreakable(obj, async function (value) { + if (await shouldBreakOn(value)) { + throw BREAK + } + console.log(value) +}) +``` + +Note: This technique also works with the native Array `forEach` method! + + + +## API + + + +#### Table of Contents + +- [Iterable](#iterable) +- [Iterator](#iterator) +- [$$iterator](#iterator-1) +- [isIterable](#isiterable) +- [isArrayLike](#isarraylike) +- [isCollection](#iscollection) +- [getIterator](#getiterator) +- [getIteratorMethod](#getiteratormethod) +- [createIterator](#createiterator) +- [forEach](#foreach) +- [AsyncIterable](#asynciterable) +- [AsyncIterator](#asynciterator) +- [$$asyncIterator](#asynciterator-1) +- [isAsyncIterable](#isasynciterable) +- [getAsyncIterator](#getasynciterator) +- [getAsyncIteratorMethod](#getasynciteratormethod) +- [createAsyncIterator](#createasynciterator) +- [forAwaitEach](#forawaiteach) + +### Iterable + +- **See: [MDN Iteration protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)** + +[Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable) +is a _protocol_ which when implemented allows a JavaScript object to define +their iteration behavior, such as what values are looped over in a +[`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) +loop or `iterall`'s `forEach` function. Many [built-in types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables) +implement the Iterable protocol, including `Array` and `Map`. + +While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface) +it can be utilized by any version of JavaScript. + +### Iterator + +- **See: [MDN Iteration protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator)** + +[Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator) +is a _protocol_ which describes a standard way to produce a sequence of +values, typically the values of the Iterable represented by this Iterator. + +While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface) +it can be utilized by any version of JavaScript. + +### $$iterator + +A property name to be used as the name of an Iterable's method responsible +for producing an Iterator, referred to as `@@iterator`. Typically represents +the value `Symbol.iterator` but falls back to the string `"@@iterator"` when +`Symbol.iterator` is not defined. + +Use `$$iterator` for defining new Iterables instead of `Symbol.iterator`, +but do not use it for accessing existing Iterables, instead use +[getIterator](#getiterator) or [isIterable](#isiterable). + +**Examples** + +```javascript +var $$iterator = require('iterall').$$iterator + +function Counter (to) { + this.to = to +} + +Counter.prototype[$$iterator] = function () { + return { + to: this.to, + num: 0, + next () { + if (this.num >= this.to) { + return { value: undefined, done: true } + } + return { value: this.num++, done: false } + } + } +} + +var counter = new Counter(3) +for (var number of counter) { + console.log(number) // 0 ... 1 ... 2 +} +``` + +### isIterable + +Returns true if the provided object implements the Iterator protocol via +either implementing a `Symbol.iterator` or `"@@iterator"` method. + +**Parameters** + +- `obj` A value which might implement the Iterable protocol. + +**Examples** + +```javascript +var isIterable = require('iterall').isIterable +isIterable([ 1, 2, 3 ]) // true +isIterable('ABC') // true +isIterable({ length: 1, 0: 'Alpha' }) // false +isIterable({ key: 'value' }) // false +isIterable(new Map()) // true +``` + +Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** true if Iterable. + +### isArrayLike + +Returns true if the provided object implements the Array-like protocol via +defining a positive-integer `length` property. + +**Parameters** + +- `obj` A value which might implement the Array-like protocol. + +**Examples** + +```javascript +var isArrayLike = require('iterall').isArrayLike +isArrayLike([ 1, 2, 3 ]) // true +isArrayLike('ABC') // true +isArrayLike({ length: 1, 0: 'Alpha' }) // true +isArrayLike({ key: 'value' }) // false +isArrayLike(new Map()) // false +``` + +Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** true if Array-like. + +### isCollection + +Returns true if the provided object is an Object (i.e. not a string literal) +and is either Iterable or Array-like. + +This may be used in place of [Array.isArray()][isarray] to determine if an +object should be iterated-over. It always excludes string literals and +includes Arrays (regardless of if it is Iterable). It also includes other +Array-like objects such as NodeList, TypedArray, and Buffer. + +**Parameters** + +- `obj` An Object value which might implement the Iterable or Array-like protocols. + +**Examples** + +```javascript +var isCollection = require('iterall').isCollection +isCollection([ 1, 2, 3 ]) // true +isCollection('ABC') // false +isCollection({ length: 1, 0: 'Alpha' }) // true +isCollection({ key: 'value' }) // false +isCollection(new Map()) // true +``` + +```javascript +var forEach = require('iterall').forEach +if (isCollection(obj)) { + forEach(obj, function (value) { + console.log(value) + }) +} +``` + +Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** true if Iterable or Array-like Object. + +### getIterator + +If the provided object implements the Iterator protocol, its Iterator object +is returned. Otherwise returns undefined. + +**Parameters** + +- `iterable` **[Iterable](#iterable)<T>** An Iterable object which is the source of an Iterator. + +**Examples** + +```javascript +var getIterator = require('iterall').getIterator +var iterator = getIterator([ 1, 2, 3 ]) +iterator.next() // { value: 1, done: false } +iterator.next() // { value: 2, done: false } +iterator.next() // { value: 3, done: false } +iterator.next() // { value: undefined, done: true } +``` + +Returns **[Iterator](#iterator)<T>** new Iterator instance. + +### getIteratorMethod + +If the provided object implements the Iterator protocol, the method +responsible for producing its Iterator object is returned. + +This is used in rare cases for performance tuning. This method must be called +with obj as the contextual this-argument. + +**Parameters** + +- `iterable` **[Iterable](#iterable)<T>** An Iterable object which defines an `@@iterator` method. + +**Examples** + +```javascript +var getIteratorMethod = require('iterall').getIteratorMethod +var myArray = [ 1, 2, 3 ] +var method = getIteratorMethod(myArray) +if (method) { + var iterator = method.call(myArray) +} +``` + +Returns **function (): [Iterator](#iterator)<T>** `@@iterator` method. + +### createIterator + +Similar to [getIterator](#getiterator), this method returns a new Iterator given an +Iterable. However it will also create an Iterator for a non-Iterable +Array-like collection, such as Array in a non-ES2015 environment. + +`createIterator` is complimentary to `forEach`, but allows a "pull"-based +iteration as opposed to `forEach`'s "push"-based iteration. + +`createIterator` produces an Iterator for Array-likes with the same behavior +as ArrayIteratorPrototype described in the ECMAScript specification, and +does _not_ skip over "holes". + +**Parameters** + +- `collection` **([Iterable](#iterable)<T> | {length: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)})** An Iterable or Array-like object to produce an Iterator. + +**Examples** + +```javascript +var createIterator = require('iterall').createIterator + +var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } +var iterator = createIterator(myArraylike) +iterator.next() // { value: 'Alpha', done: false } +iterator.next() // { value: 'Bravo', done: false } +iterator.next() // { value: 'Charlie', done: false } +iterator.next() // { value: undefined, done: true } +``` + +Returns **[Iterator](#iterator)<T>** new Iterator instance. + +### forEach + +Given an object which either implements the Iterable protocol or is +Array-like, iterate over it, calling the `callback` at each iteration. + +Use `forEach` where you would expect to use a `for ... of` loop in ES6. +However `forEach` adheres to the behavior of [Array#forEach][] described in +the ECMAScript specification, skipping over "holes" in Array-likes. It will +also delegate to a `forEach` method on `collection` if one is defined, +ensuring native performance for `Arrays`. + +Similar to [Array#forEach][], the `callback` function accepts three +arguments, and is provided with `thisArg` as the calling context. + +Note: providing an infinite Iterator to forEach will produce an error. + +[array#foreach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach + +**Parameters** + +- `collection` **([Iterable](#iterable)<T> | {length: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)})** The Iterable or array to iterate over. +- `callback` **function (T, [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))** Function to execute for each iteration, taking up to three arguments +- `thisArg` Optional. Value to use as `this` when executing `callback`. + +**Examples** + +```javascript +var forEach = require('iterall').forEach + +forEach(myIterable, function (value, index, iterable) { + console.log(value, index, iterable === myIterable) +}) +``` + +```javascript +// ES6: +for (let value of myIterable) { + console.log(value) +} + +// Any JavaScript environment: +forEach(myIterable, function (value) { + console.log(value) +}) +``` + +### AsyncIterable + +- **See: [Async Iteration Proposal](https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface)** + +[AsyncIterable](https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface) +is a _protocol_ which when implemented allows a JavaScript object to define +an asynchronous iteration behavior, such as what values are looped over in +a [`for-await-of`](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) +loop or `iterall`'s [forAwaitEach](#forawaiteach) function. + +While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) +it can be utilized by any version of JavaScript. + +### AsyncIterator + +- **See: [Async Iteration Proposal](https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface)** + +[AsyncIterator](https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface) +is a _protocol_ which describes a standard way to produce and consume an +asynchronous sequence of values, typically the values of the +[AsyncIterable](#asynciterable) represented by this [AsyncIterator](#asynciterator). + +AsyncIterator is similar to Observable or Stream. Like an [Iterator](#iterator) it +also as a `next()` method, however instead of an IteratorResult, +calling this method returns a [Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise) for a IteratorResult. + +While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) +it can be utilized by any version of JavaScript. + +### $$asyncIterator + +A property name to be used as the name of an AsyncIterable's method +responsible for producing an Iterator, referred to as `@@asyncIterator`. +Typically represents the value `Symbol.asyncIterator` but falls back to the +string `"@@asyncIterator"` when `Symbol.asyncIterator` is not defined. + +Use `$$asyncIterator` for defining new AsyncIterables instead of +`Symbol.asyncIterator`, but do not use it for accessing existing Iterables, +instead use [getAsyncIterator](#getasynciterator) or [isAsyncIterable](#isasynciterable). + +**Examples** + +```javascript +var $$asyncIterator = require('iterall').$$asyncIterator + +function Chirper (to) { + this.to = to +} + +Chirper.prototype[$$asyncIterator] = function () { + return { + to: this.to, + num: 0, + next () { + return new Promise(resolve => { + if (this.num >= this.to) { + resolve({ value: undefined, done: true }) + } else { + setTimeout(() => { + resolve({ value: this.num++, done: false }) + }, 1000) + } + }) + } + } +} + +var chirper = new Chirper(3) +for await (var number of chirper) { + console.log(number) // 0 ...wait... 1 ...wait... 2 +} +``` + +### isAsyncIterable + +Returns true if the provided object implements the AsyncIterator protocol via +either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method. + +**Parameters** + +- `obj` A value which might implement the AsyncIterable protocol. + +**Examples** + +```javascript +var isAsyncIterable = require('iterall').isAsyncIterable +isAsyncIterable(myStream) // true +isAsyncIterable('ABC') // false +``` + +Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** true if AsyncIterable. + +### getAsyncIterator + +If the provided object implements the AsyncIterator protocol, its +AsyncIterator object is returned. Otherwise returns undefined. + +**Parameters** + +- `asyncIterable` **[AsyncIterable](#asynciterable)<T>** An AsyncIterable object which is the source of an AsyncIterator. + +**Examples** + +```javascript +var getAsyncIterator = require('iterall').getAsyncIterator +var asyncIterator = getAsyncIterator(myStream) +asyncIterator.next().then(console.log) // { value: 1, done: false } +asyncIterator.next().then(console.log) // { value: 2, done: false } +asyncIterator.next().then(console.log) // { value: 3, done: false } +asyncIterator.next().then(console.log) // { value: undefined, done: true } +``` + +Returns **[AsyncIterator](#asynciterator)<T>** new AsyncIterator instance. + +### getAsyncIteratorMethod + +If the provided object implements the AsyncIterator protocol, the method +responsible for producing its AsyncIterator object is returned. + +This is used in rare cases for performance tuning. This method must be called +with obj as the contextual this-argument. + +**Parameters** + +- `asyncIterable` **[AsyncIterable](#asynciterable)<T>** An AsyncIterable object which defines an `@@asyncIterator` method. + +**Examples** + +```javascript +var getAsyncIteratorMethod = require('iterall').getAsyncIteratorMethod +var method = getAsyncIteratorMethod(myStream) +if (method) { + var asyncIterator = method.call(myStream) +} +``` + +Returns **function (): [AsyncIterator](#asynciterator)<T>** `@@asyncIterator` method. + +### createAsyncIterator + +Similar to [getAsyncIterator](#getasynciterator), this method returns a new AsyncIterator +given an AsyncIterable. However it will also create an AsyncIterator for a +non-async Iterable as well as non-Iterable Array-like collection, such as +Array in a pre-ES2015 environment. + +`createAsyncIterator` is complimentary to `forAwaitEach`, but allows a +buffering "pull"-based iteration as opposed to `forAwaitEach`'s +"push"-based iteration. + +`createAsyncIterator` produces an AsyncIterator for non-async Iterables as +described in the ECMAScript proposal [Async-from-Sync Iterator Objects](https://tc39.github.io/proposal-async-iteration/#sec-async-from-sync-iterator-objects). + +> Note: Creating `AsyncIterator`s requires the existence of `Promise`. +> While `Promise` has been available in modern browsers for a number of +> years, legacy browsers (like IE 11) may require a polyfill. + +**Parameters** + +- `source` **([AsyncIterable](#asynciterable)<T> | [Iterable](#iterable)<T> | {length: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)})** An AsyncIterable, Iterable, or Array-like object to produce an Iterator. + +**Examples** + +```javascript +var createAsyncIterator = require('iterall').createAsyncIterator + +var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } +var iterator = createAsyncIterator(myArraylike) +iterator.next().then(console.log) // { value: 'Alpha', done: false } +iterator.next().then(console.log) // { value: 'Bravo', done: false } +iterator.next().then(console.log) // { value: 'Charlie', done: false } +iterator.next().then(console.log) // { value: undefined, done: true } +``` + +Returns **[AsyncIterator](#asynciterator)<T>** new AsyncIterator instance. + +### forAwaitEach + +Given an object which either implements the AsyncIterable protocol or is +Array-like, iterate over it, calling the `callback` at each iteration. + +Use `forAwaitEach` where you would expect to use a [for-await-of](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) loop. + +Similar to [Array#forEach][], the `callback` function accepts three +arguments, and is provided with `thisArg` as the calling context. + +> Note: Using `forAwaitEach` requires the existence of `Promise`. +> While `Promise` has been available in modern browsers for a number of +> years, legacy browsers (like IE 11) may require a polyfill. + +**Parameters** + +- `source` **([AsyncIterable](#asynciterable)<T> | [Iterable](#iterable)<([Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<T> | T)> | {length: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)})** The AsyncIterable or array to iterate over. +- `callback` **function (T, [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))** Function to execute for each iteration, taking up to three arguments +- `thisArg` Optional. Value to use as `this` when executing `callback`. + +**Examples** + +```javascript +var forAwaitEach = require('iterall').forAwaitEach + +forAwaitEach(myIterable, function (value, index, iterable) { + console.log(value, index, iterable === myIterable) +}) +``` + +```javascript +// ES2017: +for await (let value of myAsyncIterable) { + console.log(await doSomethingAsync(value)) +} +console.log('done') + +// Any JavaScript environment: +forAwaitEach(myAsyncIterable, function (value) { + return doSomethingAsync(value).then(console.log) +}).then(function () { + console.log('done') +}) +``` + +## Contributing + +Contributions are welcome and encouraged! + +Remember that this library is designed to be small, straight-forward, and +well-tested. The value of new additional features will be weighed against their +size. This library also seeks to leverage and mirror the +[ECMAScript specification][] in its behavior as much as possible and reasonable. + +This repository has far more documentation and explanation than code, and it is +expected that the majority of contributions will come in the form of improving +these. + + + +[arguments]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments + +[array#@@iterator]: (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator) + +[array-like]: http://www.2ality.com/2013/05/quirk-array-like-objects.html + +[array.from]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from + +[array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array + +[ecmascript specification]: http://www.ecma-international.org/ecma-262/6.0/ + +[flow]: https://flowtype.org/ + +[hamt]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie + +[isarray]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray + +[iterators]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols + +[asynciterators]: https://tc39.github.io/proposal-async-iteration/ + +[linked list]: https://en.wikipedia.org/wiki/Linked_list + +[map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map + +[nodejs]: https://nodejs.org/ + +[nodelist]: https://developer.mozilla.org/en-US/docs/Web/API/NodeList + +[protocol]: https://en.wikipedia.org/wiki/Protocol_(object-oriented_programming) + +[react]: https://facebook.github.io/react/ + +[set]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set + +[symbol.iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator + +[typedarray]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray + +[typescript]: http://www.typescriptlang.org/ + +[immutable.js]: http://facebook.github.io/immutable-js/ diff --git a/node_modules/iterall/index.d.ts b/node_modules/iterall/index.d.ts new file mode 100644 index 0000000..e976c31 --- /dev/null +++ b/node_modules/iterall/index.d.ts @@ -0,0 +1,90 @@ +/** + * Copyright (c) 2016, Lee Byron + * All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Note: TypeScript already has built-in definitions for +// Iterable, Iterator, AsyncIterable, and AsyncIterator so they are not +// defined here. However you may need to configure TypeScript to include them. + +export var $$iterator: symbol + +export function isIterable(obj: any): obj is Iterable + +export function isArrayLike(obj: any): obj is { length: number } + +export function isCollection(obj: any): obj is Iterable | { length: number } + +export function getIterator( + iterable: Iterable +): Iterator +export function getIterator(iterable: any): void | Iterator + +export function getIteratorMethod( + iterable: Iterable +): () => Iterator +export function getIteratorMethod(iterable: any): void | (() => Iterator) + +export function createIterator( + collection: Iterable +): Iterator +export function createIterator(collection: { length: number }): Iterator +export function createIterator(collection: any): void | Iterator + +export function forEach>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any +): void +export function forEach( + collection: TCollection, + callbackFn: (value: any, index: number, collection: TCollection) => any, + thisArg?: any +): void + +export var $$asyncIterator: symbol + +export function isAsyncIterable(obj: any): obj is AsyncIterable + +export function getAsyncIterator( + asyncIterable: AsyncIterable +): AsyncIterator +export function getAsyncIterator( + asyncIterable: any +): void | AsyncIterator + +export function getAsyncIteratorMethod( + asyncIterable: AsyncIterable +): () => AsyncIterator +export function getAsyncIteratorMethod( + asyncIterable: any +): void | (() => AsyncIterator) + +export function createAsyncIterator( + collection: AsyncIterable | Iterable | TValue> +): AsyncIterator +export function createAsyncIterator( + collection: {length: number} +): AsyncIterator +export function createAsyncIterator( + collection: any +): void | AsyncIterator + +export function forAwaitEach>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any +): Promise +export function forAwaitEach | TValue>>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any +): Promise +export function forAwaitEach( + collection: TCollection, + callbackFn: (value: any, index: number, collection: TCollection) => any, + thisArg?: any +): Promise diff --git a/node_modules/iterall/index.js b/node_modules/iterall/index.js new file mode 100644 index 0000000..c80aecb --- /dev/null +++ b/node_modules/iterall/index.js @@ -0,0 +1,180 @@ +'use strict'; + +exports.isIterable = isIterable; +exports.isArrayLike = isArrayLike; +exports.isCollection = isCollection; +exports.getIterator = getIterator; +exports.getIteratorMethod = getIteratorMethod; +exports.createIterator = createIterator; +exports.forEach = forEach; +exports.isAsyncIterable = isAsyncIterable; +exports.getAsyncIterator = getAsyncIterator; +exports.getAsyncIteratorMethod = getAsyncIteratorMethod; +exports.createAsyncIterator = createAsyncIterator; +exports.forAwaitEach = forAwaitEach; + +var SYMBOL = typeof Symbol === 'function' ? Symbol : void 0; + +var SYMBOL_ITERATOR = SYMBOL && SYMBOL.iterator; + +var $$iterator = exports.$$iterator = SYMBOL_ITERATOR || '@@iterator'; + +function isIterable(obj) { + return !!getIteratorMethod(obj); +} + +function isArrayLike(obj) { + var length = obj != null && obj.length; + return typeof length === 'number' && length >= 0 && length % 1 === 0; +} + +function isCollection(obj) { + return Object(obj) === obj && (isArrayLike(obj) || isIterable(obj)); +} + +function getIterator(iterable) { + var method = getIteratorMethod(iterable); + if (method) { + return method.call(iterable); + } +} + +function getIteratorMethod(iterable) { + if (iterable != null) { + var method = SYMBOL_ITERATOR && iterable[SYMBOL_ITERATOR] || iterable['@@iterator']; + if (typeof method === 'function') { + return method; + } + } +} + +function createIterator(collection) { + if (collection != null) { + var iterator = getIterator(collection); + if (iterator) { + return iterator; + } + if (isArrayLike(collection)) { + return new ArrayLikeIterator(collection); + } + } +} + +function ArrayLikeIterator(obj) { + this._o = obj; + this._i = 0; +} + +ArrayLikeIterator.prototype[$$iterator] = function () { + return this; +}; + +ArrayLikeIterator.prototype.next = function () { + if (this._o === void 0 || this._i >= this._o.length) { + this._o = void 0; + return { value: void 0, done: true }; + } + return { value: this._o[this._i++], done: false }; +}; + +function forEach(collection, callback, thisArg) { + if (collection != null) { + if (typeof collection.forEach === 'function') { + return collection.forEach(callback, thisArg); + } + var i = 0; + var iterator = getIterator(collection); + if (iterator) { + var step; + while (!(step = iterator.next()).done) { + callback.call(thisArg, step.value, i++, collection); + + if (i > 9999999) { + throw new TypeError('Near-infinite iteration.'); + } + } + } else if (isArrayLike(collection)) { + for (; i < collection.length; i++) { + if (collection.hasOwnProperty(i)) { + callback.call(thisArg, collection[i], i, collection); + } + } + } + } +} + +var SYMBOL_ASYNC_ITERATOR = SYMBOL && SYMBOL.asyncIterator; + +var $$asyncIterator = exports.$$asyncIterator = SYMBOL_ASYNC_ITERATOR || '@@asyncIterator'; + +function isAsyncIterable(obj) { + return !!getAsyncIteratorMethod(obj); +} + +function getAsyncIterator(asyncIterable) { + var method = getAsyncIteratorMethod(asyncIterable); + if (method) { + return method.call(asyncIterable); + } +} + +function getAsyncIteratorMethod(asyncIterable) { + if (asyncIterable != null) { + var method = SYMBOL_ASYNC_ITERATOR && asyncIterable[SYMBOL_ASYNC_ITERATOR] || asyncIterable['@@asyncIterator']; + if (typeof method === 'function') { + return method; + } + } +} + +function createAsyncIterator(source) { + if (source != null) { + var asyncIterator = getAsyncIterator(source); + if (asyncIterator) { + return asyncIterator; + } + var iterator = createIterator(source); + if (iterator) { + return new AsyncFromSyncIterator(iterator); + } + } +} + +function AsyncFromSyncIterator(iterator) { + this._i = iterator; +} + +AsyncFromSyncIterator.prototype[$$asyncIterator] = function () { + return this; +}; + +AsyncFromSyncIterator.prototype.next = function () { + var step = this._i.next(); + return Promise.resolve(step.value).then(function (value) { + return { value: value, done: step.done }; + }); +}; + +function forAwaitEach(source, callback, thisArg) { + var asyncIterator = createAsyncIterator(source); + if (asyncIterator) { + var i = 0; + return new Promise(function (resolve, reject) { + function next() { + asyncIterator.next().then(function (step) { + if (!step.done) { + Promise.resolve(callback.call(thisArg, step.value, i++, source)).then(next).catch(reject); + } else { + resolve(); + } + + return null; + }).catch(reject); + + return null; + } + next(); + }); + } +} + diff --git a/node_modules/iterall/index.js.flow b/node_modules/iterall/index.js.flow new file mode 100644 index 0000000..fa3002a --- /dev/null +++ b/node_modules/iterall/index.js.flow @@ -0,0 +1,702 @@ +/** + * Copyright (c) 2016, Lee Byron + * All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @ignore + */ + +/** + * [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator) + * is a *protocol* which describes a standard way to produce a sequence of + * values, typically the values of the Iterable represented by this Iterator. + * + * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface) + * it can be utilized by any version of JavaScript. + * + * @external Iterator + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator|MDN Iteration protocols} + */ + +/** + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable) + * is a *protocol* which when implemented allows a JavaScript object to define + * their iteration behavior, such as what values are looped over in a + * [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) + * loop or `iterall`'s `forEach` function. Many [built-in types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables) + * implement the Iterable protocol, including `Array` and `Map`. + * + * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface) + * it can be utilized by any version of JavaScript. + * + * @external Iterable + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable|MDN Iteration protocols} + */ + +// In ES2015 environments, Symbol exists +var SYMBOL /*: any */ = typeof Symbol === 'function' ? Symbol : void 0 + +// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator +var SYMBOL_ITERATOR = SYMBOL && SYMBOL.iterator + +/** + * A property name to be used as the name of an Iterable's method responsible + * for producing an Iterator, referred to as `@@iterator`. Typically represents + * the value `Symbol.iterator` but falls back to the string `"@@iterator"` when + * `Symbol.iterator` is not defined. + * + * Use `$$iterator` for defining new Iterables instead of `Symbol.iterator`, + * but do not use it for accessing existing Iterables, instead use + * {@link getIterator} or {@link isIterable}. + * + * @example + * + * var $$iterator = require('iterall').$$iterator + * + * function Counter (to) { + * this.to = to + * } + * + * Counter.prototype[$$iterator] = function () { + * return { + * to: this.to, + * num: 0, + * next () { + * if (this.num >= this.to) { + * return { value: undefined, done: true } + * } + * return { value: this.num++, done: false } + * } + * } + * } + * + * var counter = new Counter(3) + * for (var number of counter) { + * console.log(number) // 0 ... 1 ... 2 + * } + * + * @type {Symbol|string} + */ +/*:: declare export var $$iterator: '@@iterator'; */ +export var $$iterator = SYMBOL_ITERATOR || '@@iterator' + +/** + * Returns true if the provided object implements the Iterator protocol via + * either implementing a `Symbol.iterator` or `"@@iterator"` method. + * + * @example + * + * var isIterable = require('iterall').isIterable + * isIterable([ 1, 2, 3 ]) // true + * isIterable('ABC') // true + * isIterable({ length: 1, 0: 'Alpha' }) // false + * isIterable({ key: 'value' }) // false + * isIterable(new Map()) // true + * + * @param obj + * A value which might implement the Iterable protocol. + * @return {boolean} true if Iterable. + */ +/*:: declare export function isIterable(obj: any): boolean; */ +export function isIterable(obj) { + return !!getIteratorMethod(obj) +} + +/** + * Returns true if the provided object implements the Array-like protocol via + * defining a positive-integer `length` property. + * + * @example + * + * var isArrayLike = require('iterall').isArrayLike + * isArrayLike([ 1, 2, 3 ]) // true + * isArrayLike('ABC') // true + * isArrayLike({ length: 1, 0: 'Alpha' }) // true + * isArrayLike({ key: 'value' }) // false + * isArrayLike(new Map()) // false + * + * @param obj + * A value which might implement the Array-like protocol. + * @return {boolean} true if Array-like. + */ +/*:: declare export function isArrayLike(obj: any): boolean; */ +export function isArrayLike(obj) { + var length = obj != null && obj.length + return typeof length === 'number' && length >= 0 && length % 1 === 0 +} + +/** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and is either Iterable or Array-like. + * + * This may be used in place of [Array.isArray()][isArray] to determine if an + * object should be iterated-over. It always excludes string literals and + * includes Arrays (regardless of if it is Iterable). It also includes other + * Array-like objects such as NodeList, TypedArray, and Buffer. + * + * @example + * + * var isCollection = require('iterall').isCollection + * isCollection([ 1, 2, 3 ]) // true + * isCollection('ABC') // false + * isCollection({ length: 1, 0: 'Alpha' }) // true + * isCollection({ key: 'value' }) // false + * isCollection(new Map()) // true + * + * @example + * + * var forEach = require('iterall').forEach + * if (isCollection(obj)) { + * forEach(obj, function (value) { + * console.log(value) + * }) + * } + * + * @param obj + * An Object value which might implement the Iterable or Array-like protocols. + * @return {boolean} true if Iterable or Array-like Object. + */ +/*:: declare export function isCollection(obj: any): boolean; */ +export function isCollection(obj) { + return Object(obj) === obj && (isArrayLike(obj) || isIterable(obj)) +} + +/** + * If the provided object implements the Iterator protocol, its Iterator object + * is returned. Otherwise returns undefined. + * + * @example + * + * var getIterator = require('iterall').getIterator + * var iterator = getIterator([ 1, 2, 3 ]) + * iterator.next() // { value: 1, done: false } + * iterator.next() // { value: 2, done: false } + * iterator.next() // { value: 3, done: false } + * iterator.next() // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {Iterable} iterable + * An Iterable object which is the source of an Iterator. + * @return {Iterator} new Iterator instance. + */ +/*:: declare export var getIterator: + & (<+TValue>(iterable: Iterable) => Iterator) + & ((iterable: mixed) => void | Iterator); */ +export function getIterator(iterable) { + var method = getIteratorMethod(iterable) + if (method) { + return method.call(iterable) + } +} + +/** + * If the provided object implements the Iterator protocol, the method + * responsible for producing its Iterator object is returned. + * + * This is used in rare cases for performance tuning. This method must be called + * with obj as the contextual this-argument. + * + * @example + * + * var getIteratorMethod = require('iterall').getIteratorMethod + * var myArray = [ 1, 2, 3 ] + * var method = getIteratorMethod(myArray) + * if (method) { + * var iterator = method.call(myArray) + * } + * + * @template T the type of each iterated value + * @param {Iterable} iterable + * An Iterable object which defines an `@@iterator` method. + * @return {function(): Iterator} `@@iterator` method. + */ +/*:: declare export var getIteratorMethod: + & (<+TValue>(iterable: Iterable) => (() => Iterator)) + & ((iterable: mixed) => (void | (() => Iterator))); */ +export function getIteratorMethod(iterable) { + if (iterable != null) { + var method = + (SYMBOL_ITERATOR && iterable[SYMBOL_ITERATOR]) || iterable['@@iterator'] + if (typeof method === 'function') { + return method + } + } +} + +/** + * Similar to {@link getIterator}, this method returns a new Iterator given an + * Iterable. However it will also create an Iterator for a non-Iterable + * Array-like collection, such as Array in a non-ES2015 environment. + * + * `createIterator` is complimentary to `forEach`, but allows a "pull"-based + * iteration as opposed to `forEach`'s "push"-based iteration. + * + * `createIterator` produces an Iterator for Array-likes with the same behavior + * as ArrayIteratorPrototype described in the ECMAScript specification, and + * does *not* skip over "holes". + * + * @example + * + * var createIterator = require('iterall').createIterator + * + * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } + * var iterator = createIterator(myArraylike) + * iterator.next() // { value: 'Alpha', done: false } + * iterator.next() // { value: 'Bravo', done: false } + * iterator.next() // { value: 'Charlie', done: false } + * iterator.next() // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {Iterable|{ length: number }} collection + * An Iterable or Array-like object to produce an Iterator. + * @return {Iterator} new Iterator instance. + */ +/*:: declare export var createIterator: + & (<+TValue>(collection: Iterable) => Iterator) + & ((collection: {length: number}) => Iterator) + & ((collection: mixed) => (void | Iterator)); */ +export function createIterator(collection) { + if (collection != null) { + var iterator = getIterator(collection) + if (iterator) { + return iterator + } + if (isArrayLike(collection)) { + return new ArrayLikeIterator(collection) + } + } +} + +// When the object provided to `createIterator` is not Iterable but is +// Array-like, this simple Iterator is created. +function ArrayLikeIterator(obj) { + this._o = obj + this._i = 0 +} + +// Note: all Iterators are themselves Iterable. +ArrayLikeIterator.prototype[$$iterator] = function() { + return this +} + +// A simple state-machine determines the IteratorResult returned, yielding +// each value in the Array-like object in order of their indicies. +ArrayLikeIterator.prototype.next = function() { + if (this._o === void 0 || this._i >= this._o.length) { + this._o = void 0 + return { value: void 0, done: true } + } + return { value: this._o[this._i++], done: false } +} + +/** + * Given an object which either implements the Iterable protocol or is + * Array-like, iterate over it, calling the `callback` at each iteration. + * + * Use `forEach` where you would expect to use a `for ... of` loop in ES6. + * However `forEach` adheres to the behavior of [Array#forEach][] described in + * the ECMAScript specification, skipping over "holes" in Array-likes. It will + * also delegate to a `forEach` method on `collection` if one is defined, + * ensuring native performance for `Arrays`. + * + * Similar to [Array#forEach][], the `callback` function accepts three + * arguments, and is provided with `thisArg` as the calling context. + * + * Note: providing an infinite Iterator to forEach will produce an error. + * + * [Array#forEach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach + * + * @example + * + * var forEach = require('iterall').forEach + * + * forEach(myIterable, function (value, index, iterable) { + * console.log(value, index, iterable === myIterable) + * }) + * + * @example + * + * // ES6: + * for (let value of myIterable) { + * console.log(value) + * } + * + * // Any JavaScript environment: + * forEach(myIterable, function (value) { + * console.log(value) + * }) + * + * @template T the type of each iterated value + * @param {Iterable|{ length: number }} collection + * The Iterable or array to iterate over. + * @param {function(T, number, object)} callback + * Function to execute for each iteration, taking up to three arguments + * @param [thisArg] + * Optional. Value to use as `this` when executing `callback`. + */ +/*:: declare export var forEach: + & (<+TValue, TCollection: Iterable>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any + ) => void) + & (( + collection: TCollection, + callbackFn: (value: mixed, index: number, collection: TCollection) => any, + thisArg?: any + ) => void); */ +export function forEach(collection, callback, thisArg) { + if (collection != null) { + if (typeof collection.forEach === 'function') { + return collection.forEach(callback, thisArg) + } + var i = 0 + var iterator = getIterator(collection) + if (iterator) { + var step + while (!(step = iterator.next()).done) { + callback.call(thisArg, step.value, i++, collection) + // Infinite Iterators could cause forEach to run forever. + // After a very large number of iterations, produce an error. + /* istanbul ignore if */ + if (i > 9999999) { + throw new TypeError('Near-infinite iteration.') + } + } + } else if (isArrayLike(collection)) { + for (; i < collection.length; i++) { + if (collection.hasOwnProperty(i)) { + callback.call(thisArg, collection[i], i, collection) + } + } + } + } +} + +///////////////////////////////////////////////////// +// // +// ASYNC ITERATORS // +// // +///////////////////////////////////////////////////// + +/** + * [AsyncIterable](https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface) + * is a *protocol* which when implemented allows a JavaScript object to define + * an asynchronous iteration behavior, such as what values are looped over in + * a [`for-await-of`](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) + * loop or `iterall`'s {@link forAwaitEach} function. + * + * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) + * it can be utilized by any version of JavaScript. + * + * @external AsyncIterable + * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface|Async Iteration Proposal} + * @template T The type of each iterated value + * @property {function (): AsyncIterator} Symbol.asyncIterator + * A method which produces an AsyncIterator for this AsyncIterable. + */ + +/** + * [AsyncIterator](https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface) + * is a *protocol* which describes a standard way to produce and consume an + * asynchronous sequence of values, typically the values of the + * {@link AsyncIterable} represented by this {@link AsyncIterator}. + * + * AsyncIterator is similar to Observable or Stream. Like an {@link Iterator} it + * also as a `next()` method, however instead of an IteratorResult, + * calling this method returns a {@link Promise} for a IteratorResult. + * + * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) + * it can be utilized by any version of JavaScript. + * + * @external AsyncIterator + * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface|Async Iteration Proposal} + */ + +// In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator +var SYMBOL_ASYNC_ITERATOR = SYMBOL && SYMBOL.asyncIterator + +/** + * A property name to be used as the name of an AsyncIterable's method + * responsible for producing an Iterator, referred to as `@@asyncIterator`. + * Typically represents the value `Symbol.asyncIterator` but falls back to the + * string `"@@asyncIterator"` when `Symbol.asyncIterator` is not defined. + * + * Use `$$asyncIterator` for defining new AsyncIterables instead of + * `Symbol.asyncIterator`, but do not use it for accessing existing Iterables, + * instead use {@link getAsyncIterator} or {@link isAsyncIterable}. + * + * @example + * + * var $$asyncIterator = require('iterall').$$asyncIterator + * + * function Chirper (to) { + * this.to = to + * } + * + * Chirper.prototype[$$asyncIterator] = function () { + * return { + * to: this.to, + * num: 0, + * next () { + * return new Promise(resolve => { + * if (this.num >= this.to) { + * resolve({ value: undefined, done: true }) + * } else { + * setTimeout(() => { + * resolve({ value: this.num++, done: false }) + * }, 1000) + * } + * }) + * } + * } + * } + * + * var chirper = new Chirper(3) + * for await (var number of chirper) { + * console.log(number) // 0 ...wait... 1 ...wait... 2 + * } + * + * @type {Symbol|string} + */ +/*:: declare export var $$asyncIterator: '@@asyncIterator'; */ +export var $$asyncIterator = SYMBOL_ASYNC_ITERATOR || '@@asyncIterator' + +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method. + * + * @example + * + * var isAsyncIterable = require('iterall').isAsyncIterable + * isAsyncIterable(myStream) // true + * isAsyncIterable('ABC') // false + * + * @param obj + * A value which might implement the AsyncIterable protocol. + * @return {boolean} true if AsyncIterable. + */ +/*:: declare export function isAsyncIterable(obj: any): boolean; */ +export function isAsyncIterable(obj) { + return !!getAsyncIteratorMethod(obj) +} + +/** + * If the provided object implements the AsyncIterator protocol, its + * AsyncIterator object is returned. Otherwise returns undefined. + * + * @example + * + * var getAsyncIterator = require('iterall').getAsyncIterator + * var asyncIterator = getAsyncIterator(myStream) + * asyncIterator.next().then(console.log) // { value: 1, done: false } + * asyncIterator.next().then(console.log) // { value: 2, done: false } + * asyncIterator.next().then(console.log) // { value: 3, done: false } + * asyncIterator.next().then(console.log) // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {AsyncIterable} asyncIterable + * An AsyncIterable object which is the source of an AsyncIterator. + * @return {AsyncIterator} new AsyncIterator instance. + */ +/*:: declare export var getAsyncIterator: + & (<+TValue>(asyncIterable: AsyncIterable) => AsyncIterator) + & ((asyncIterable: mixed) => (void | AsyncIterator)); */ +export function getAsyncIterator(asyncIterable) { + var method = getAsyncIteratorMethod(asyncIterable) + if (method) { + return method.call(asyncIterable) + } +} + +/** + * If the provided object implements the AsyncIterator protocol, the method + * responsible for producing its AsyncIterator object is returned. + * + * This is used in rare cases for performance tuning. This method must be called + * with obj as the contextual this-argument. + * + * @example + * + * var getAsyncIteratorMethod = require('iterall').getAsyncIteratorMethod + * var method = getAsyncIteratorMethod(myStream) + * if (method) { + * var asyncIterator = method.call(myStream) + * } + * + * @template T the type of each iterated value + * @param {AsyncIterable} asyncIterable + * An AsyncIterable object which defines an `@@asyncIterator` method. + * @return {function(): AsyncIterator} `@@asyncIterator` method. + */ +/*:: declare export var getAsyncIteratorMethod: + & (<+TValue>(asyncIterable: AsyncIterable) => (() => AsyncIterator)) + & ((asyncIterable: mixed) => (void | (() => AsyncIterator))); */ +export function getAsyncIteratorMethod(asyncIterable) { + if (asyncIterable != null) { + var method = + (SYMBOL_ASYNC_ITERATOR && asyncIterable[SYMBOL_ASYNC_ITERATOR]) || + asyncIterable['@@asyncIterator'] + if (typeof method === 'function') { + return method + } + } +} + +/** + * Similar to {@link getAsyncIterator}, this method returns a new AsyncIterator + * given an AsyncIterable. However it will also create an AsyncIterator for a + * non-async Iterable as well as non-Iterable Array-like collection, such as + * Array in a pre-ES2015 environment. + * + * `createAsyncIterator` is complimentary to `forAwaitEach`, but allows a + * buffering "pull"-based iteration as opposed to `forAwaitEach`'s + * "push"-based iteration. + * + * `createAsyncIterator` produces an AsyncIterator for non-async Iterables as + * described in the ECMAScript proposal [Async-from-Sync Iterator Objects](https://tc39.github.io/proposal-async-iteration/#sec-async-from-sync-iterator-objects). + * + * > Note: Creating `AsyncIterator`s requires the existence of `Promise`. + * > While `Promise` has been available in modern browsers for a number of + * > years, legacy browsers (like IE 11) may require a polyfill. + * + * @example + * + * var createAsyncIterator = require('iterall').createAsyncIterator + * + * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } + * var iterator = createAsyncIterator(myArraylike) + * iterator.next().then(console.log) // { value: 'Alpha', done: false } + * iterator.next().then(console.log) // { value: 'Bravo', done: false } + * iterator.next().then(console.log) // { value: 'Charlie', done: false } + * iterator.next().then(console.log) // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {AsyncIterable|Iterable|{ length: number }} source + * An AsyncIterable, Iterable, or Array-like object to produce an Iterator. + * @return {AsyncIterator} new AsyncIterator instance. + */ +/*:: declare export var createAsyncIterator: + & (<+TValue>( + collection: Iterable | TValue> | AsyncIterable + ) => AsyncIterator) + & ((collection: {length: number}) => AsyncIterator) + & ((collection: mixed) => (void | AsyncIterator)); */ +export function createAsyncIterator(source) { + if (source != null) { + var asyncIterator = getAsyncIterator(source) + if (asyncIterator) { + return asyncIterator + } + var iterator = createIterator(source) + if (iterator) { + return new AsyncFromSyncIterator(iterator) + } + } +} + +// When the object provided to `createAsyncIterator` is not AsyncIterable but is +// sync Iterable, this simple wrapper is created. +function AsyncFromSyncIterator(iterator) { + this._i = iterator +} + +// Note: all AsyncIterators are themselves AsyncIterable. +AsyncFromSyncIterator.prototype[$$asyncIterator] = function() { + return this +} + +// A simple state-machine determines the IteratorResult returned, yielding +// each value in the Array-like object in order of their indicies. +AsyncFromSyncIterator.prototype.next = function() { + var step = this._i.next() + return Promise.resolve(step.value).then(function(value) { + return { value: value, done: step.done } + }) +} + +/** + * Given an object which either implements the AsyncIterable protocol or is + * Array-like, iterate over it, calling the `callback` at each iteration. + * + * Use `forAwaitEach` where you would expect to use a [for-await-of](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) loop. + * + * Similar to [Array#forEach][], the `callback` function accepts three + * arguments, and is provided with `thisArg` as the calling context. + * + * > Note: Using `forAwaitEach` requires the existence of `Promise`. + * > While `Promise` has been available in modern browsers for a number of + * > years, legacy browsers (like IE 11) may require a polyfill. + * + * @example + * + * var forAwaitEach = require('iterall').forAwaitEach + * + * forAwaitEach(myIterable, function (value, index, iterable) { + * console.log(value, index, iterable === myIterable) + * }) + * + * @example + * + * // ES2017: + * for await (let value of myAsyncIterable) { + * console.log(await doSomethingAsync(value)) + * } + * console.log('done') + * + * // Any JavaScript environment: + * forAwaitEach(myAsyncIterable, function (value) { + * return doSomethingAsync(value).then(console.log) + * }).then(function () { + * console.log('done') + * }) + * + * @template T the type of each iterated value + * @param {AsyncIterable|Iterable | T>|{ length: number }} source + * The AsyncIterable or array to iterate over. + * @param {function(T, number, object)} callback + * Function to execute for each iteration, taking up to three arguments + * @param [thisArg] + * Optional. Value to use as `this` when executing `callback`. + */ +/*:: declare export var forAwaitEach: + & (<+TValue, TCollection: Iterable | TValue> | AsyncIterable>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any + ) => Promise) + & (( + collection: TCollection, + callbackFn: (value: mixed, index: number, collection: TCollection) => any, + thisArg?: any + ) => Promise); */ +export function forAwaitEach(source, callback, thisArg) { + var asyncIterator = createAsyncIterator(source) + if (asyncIterator) { + var i = 0 + return new Promise(function(resolve, reject) { + function next() { + asyncIterator + .next() + .then(function(step) { + if (!step.done) { + Promise.resolve(callback.call(thisArg, step.value, i++, source)) + .then(next) + .catch(reject) + } else { + resolve() + } + // Explicitly return null, silencing bluebird-style warnings. + return null + }) + .catch(reject) + // Explicitly return null, silencing bluebird-style warnings. + return null + } + next() + }) + } +} diff --git a/node_modules/iterall/index.mjs b/node_modules/iterall/index.mjs new file mode 100644 index 0000000..fa3002a --- /dev/null +++ b/node_modules/iterall/index.mjs @@ -0,0 +1,702 @@ +/** + * Copyright (c) 2016, Lee Byron + * All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @ignore + */ + +/** + * [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator) + * is a *protocol* which describes a standard way to produce a sequence of + * values, typically the values of the Iterable represented by this Iterator. + * + * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface) + * it can be utilized by any version of JavaScript. + * + * @external Iterator + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator|MDN Iteration protocols} + */ + +/** + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable) + * is a *protocol* which when implemented allows a JavaScript object to define + * their iteration behavior, such as what values are looped over in a + * [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) + * loop or `iterall`'s `forEach` function. Many [built-in types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables) + * implement the Iterable protocol, including `Array` and `Map`. + * + * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface) + * it can be utilized by any version of JavaScript. + * + * @external Iterable + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable|MDN Iteration protocols} + */ + +// In ES2015 environments, Symbol exists +var SYMBOL /*: any */ = typeof Symbol === 'function' ? Symbol : void 0 + +// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator +var SYMBOL_ITERATOR = SYMBOL && SYMBOL.iterator + +/** + * A property name to be used as the name of an Iterable's method responsible + * for producing an Iterator, referred to as `@@iterator`. Typically represents + * the value `Symbol.iterator` but falls back to the string `"@@iterator"` when + * `Symbol.iterator` is not defined. + * + * Use `$$iterator` for defining new Iterables instead of `Symbol.iterator`, + * but do not use it for accessing existing Iterables, instead use + * {@link getIterator} or {@link isIterable}. + * + * @example + * + * var $$iterator = require('iterall').$$iterator + * + * function Counter (to) { + * this.to = to + * } + * + * Counter.prototype[$$iterator] = function () { + * return { + * to: this.to, + * num: 0, + * next () { + * if (this.num >= this.to) { + * return { value: undefined, done: true } + * } + * return { value: this.num++, done: false } + * } + * } + * } + * + * var counter = new Counter(3) + * for (var number of counter) { + * console.log(number) // 0 ... 1 ... 2 + * } + * + * @type {Symbol|string} + */ +/*:: declare export var $$iterator: '@@iterator'; */ +export var $$iterator = SYMBOL_ITERATOR || '@@iterator' + +/** + * Returns true if the provided object implements the Iterator protocol via + * either implementing a `Symbol.iterator` or `"@@iterator"` method. + * + * @example + * + * var isIterable = require('iterall').isIterable + * isIterable([ 1, 2, 3 ]) // true + * isIterable('ABC') // true + * isIterable({ length: 1, 0: 'Alpha' }) // false + * isIterable({ key: 'value' }) // false + * isIterable(new Map()) // true + * + * @param obj + * A value which might implement the Iterable protocol. + * @return {boolean} true if Iterable. + */ +/*:: declare export function isIterable(obj: any): boolean; */ +export function isIterable(obj) { + return !!getIteratorMethod(obj) +} + +/** + * Returns true if the provided object implements the Array-like protocol via + * defining a positive-integer `length` property. + * + * @example + * + * var isArrayLike = require('iterall').isArrayLike + * isArrayLike([ 1, 2, 3 ]) // true + * isArrayLike('ABC') // true + * isArrayLike({ length: 1, 0: 'Alpha' }) // true + * isArrayLike({ key: 'value' }) // false + * isArrayLike(new Map()) // false + * + * @param obj + * A value which might implement the Array-like protocol. + * @return {boolean} true if Array-like. + */ +/*:: declare export function isArrayLike(obj: any): boolean; */ +export function isArrayLike(obj) { + var length = obj != null && obj.length + return typeof length === 'number' && length >= 0 && length % 1 === 0 +} + +/** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and is either Iterable or Array-like. + * + * This may be used in place of [Array.isArray()][isArray] to determine if an + * object should be iterated-over. It always excludes string literals and + * includes Arrays (regardless of if it is Iterable). It also includes other + * Array-like objects such as NodeList, TypedArray, and Buffer. + * + * @example + * + * var isCollection = require('iterall').isCollection + * isCollection([ 1, 2, 3 ]) // true + * isCollection('ABC') // false + * isCollection({ length: 1, 0: 'Alpha' }) // true + * isCollection({ key: 'value' }) // false + * isCollection(new Map()) // true + * + * @example + * + * var forEach = require('iterall').forEach + * if (isCollection(obj)) { + * forEach(obj, function (value) { + * console.log(value) + * }) + * } + * + * @param obj + * An Object value which might implement the Iterable or Array-like protocols. + * @return {boolean} true if Iterable or Array-like Object. + */ +/*:: declare export function isCollection(obj: any): boolean; */ +export function isCollection(obj) { + return Object(obj) === obj && (isArrayLike(obj) || isIterable(obj)) +} + +/** + * If the provided object implements the Iterator protocol, its Iterator object + * is returned. Otherwise returns undefined. + * + * @example + * + * var getIterator = require('iterall').getIterator + * var iterator = getIterator([ 1, 2, 3 ]) + * iterator.next() // { value: 1, done: false } + * iterator.next() // { value: 2, done: false } + * iterator.next() // { value: 3, done: false } + * iterator.next() // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {Iterable} iterable + * An Iterable object which is the source of an Iterator. + * @return {Iterator} new Iterator instance. + */ +/*:: declare export var getIterator: + & (<+TValue>(iterable: Iterable) => Iterator) + & ((iterable: mixed) => void | Iterator); */ +export function getIterator(iterable) { + var method = getIteratorMethod(iterable) + if (method) { + return method.call(iterable) + } +} + +/** + * If the provided object implements the Iterator protocol, the method + * responsible for producing its Iterator object is returned. + * + * This is used in rare cases for performance tuning. This method must be called + * with obj as the contextual this-argument. + * + * @example + * + * var getIteratorMethod = require('iterall').getIteratorMethod + * var myArray = [ 1, 2, 3 ] + * var method = getIteratorMethod(myArray) + * if (method) { + * var iterator = method.call(myArray) + * } + * + * @template T the type of each iterated value + * @param {Iterable} iterable + * An Iterable object which defines an `@@iterator` method. + * @return {function(): Iterator} `@@iterator` method. + */ +/*:: declare export var getIteratorMethod: + & (<+TValue>(iterable: Iterable) => (() => Iterator)) + & ((iterable: mixed) => (void | (() => Iterator))); */ +export function getIteratorMethod(iterable) { + if (iterable != null) { + var method = + (SYMBOL_ITERATOR && iterable[SYMBOL_ITERATOR]) || iterable['@@iterator'] + if (typeof method === 'function') { + return method + } + } +} + +/** + * Similar to {@link getIterator}, this method returns a new Iterator given an + * Iterable. However it will also create an Iterator for a non-Iterable + * Array-like collection, such as Array in a non-ES2015 environment. + * + * `createIterator` is complimentary to `forEach`, but allows a "pull"-based + * iteration as opposed to `forEach`'s "push"-based iteration. + * + * `createIterator` produces an Iterator for Array-likes with the same behavior + * as ArrayIteratorPrototype described in the ECMAScript specification, and + * does *not* skip over "holes". + * + * @example + * + * var createIterator = require('iterall').createIterator + * + * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } + * var iterator = createIterator(myArraylike) + * iterator.next() // { value: 'Alpha', done: false } + * iterator.next() // { value: 'Bravo', done: false } + * iterator.next() // { value: 'Charlie', done: false } + * iterator.next() // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {Iterable|{ length: number }} collection + * An Iterable or Array-like object to produce an Iterator. + * @return {Iterator} new Iterator instance. + */ +/*:: declare export var createIterator: + & (<+TValue>(collection: Iterable) => Iterator) + & ((collection: {length: number}) => Iterator) + & ((collection: mixed) => (void | Iterator)); */ +export function createIterator(collection) { + if (collection != null) { + var iterator = getIterator(collection) + if (iterator) { + return iterator + } + if (isArrayLike(collection)) { + return new ArrayLikeIterator(collection) + } + } +} + +// When the object provided to `createIterator` is not Iterable but is +// Array-like, this simple Iterator is created. +function ArrayLikeIterator(obj) { + this._o = obj + this._i = 0 +} + +// Note: all Iterators are themselves Iterable. +ArrayLikeIterator.prototype[$$iterator] = function() { + return this +} + +// A simple state-machine determines the IteratorResult returned, yielding +// each value in the Array-like object in order of their indicies. +ArrayLikeIterator.prototype.next = function() { + if (this._o === void 0 || this._i >= this._o.length) { + this._o = void 0 + return { value: void 0, done: true } + } + return { value: this._o[this._i++], done: false } +} + +/** + * Given an object which either implements the Iterable protocol or is + * Array-like, iterate over it, calling the `callback` at each iteration. + * + * Use `forEach` where you would expect to use a `for ... of` loop in ES6. + * However `forEach` adheres to the behavior of [Array#forEach][] described in + * the ECMAScript specification, skipping over "holes" in Array-likes. It will + * also delegate to a `forEach` method on `collection` if one is defined, + * ensuring native performance for `Arrays`. + * + * Similar to [Array#forEach][], the `callback` function accepts three + * arguments, and is provided with `thisArg` as the calling context. + * + * Note: providing an infinite Iterator to forEach will produce an error. + * + * [Array#forEach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach + * + * @example + * + * var forEach = require('iterall').forEach + * + * forEach(myIterable, function (value, index, iterable) { + * console.log(value, index, iterable === myIterable) + * }) + * + * @example + * + * // ES6: + * for (let value of myIterable) { + * console.log(value) + * } + * + * // Any JavaScript environment: + * forEach(myIterable, function (value) { + * console.log(value) + * }) + * + * @template T the type of each iterated value + * @param {Iterable|{ length: number }} collection + * The Iterable or array to iterate over. + * @param {function(T, number, object)} callback + * Function to execute for each iteration, taking up to three arguments + * @param [thisArg] + * Optional. Value to use as `this` when executing `callback`. + */ +/*:: declare export var forEach: + & (<+TValue, TCollection: Iterable>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any + ) => void) + & (( + collection: TCollection, + callbackFn: (value: mixed, index: number, collection: TCollection) => any, + thisArg?: any + ) => void); */ +export function forEach(collection, callback, thisArg) { + if (collection != null) { + if (typeof collection.forEach === 'function') { + return collection.forEach(callback, thisArg) + } + var i = 0 + var iterator = getIterator(collection) + if (iterator) { + var step + while (!(step = iterator.next()).done) { + callback.call(thisArg, step.value, i++, collection) + // Infinite Iterators could cause forEach to run forever. + // After a very large number of iterations, produce an error. + /* istanbul ignore if */ + if (i > 9999999) { + throw new TypeError('Near-infinite iteration.') + } + } + } else if (isArrayLike(collection)) { + for (; i < collection.length; i++) { + if (collection.hasOwnProperty(i)) { + callback.call(thisArg, collection[i], i, collection) + } + } + } + } +} + +///////////////////////////////////////////////////// +// // +// ASYNC ITERATORS // +// // +///////////////////////////////////////////////////// + +/** + * [AsyncIterable](https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface) + * is a *protocol* which when implemented allows a JavaScript object to define + * an asynchronous iteration behavior, such as what values are looped over in + * a [`for-await-of`](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) + * loop or `iterall`'s {@link forAwaitEach} function. + * + * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) + * it can be utilized by any version of JavaScript. + * + * @external AsyncIterable + * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface|Async Iteration Proposal} + * @template T The type of each iterated value + * @property {function (): AsyncIterator} Symbol.asyncIterator + * A method which produces an AsyncIterator for this AsyncIterable. + */ + +/** + * [AsyncIterator](https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface) + * is a *protocol* which describes a standard way to produce and consume an + * asynchronous sequence of values, typically the values of the + * {@link AsyncIterable} represented by this {@link AsyncIterator}. + * + * AsyncIterator is similar to Observable or Stream. Like an {@link Iterator} it + * also as a `next()` method, however instead of an IteratorResult, + * calling this method returns a {@link Promise} for a IteratorResult. + * + * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) + * it can be utilized by any version of JavaScript. + * + * @external AsyncIterator + * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface|Async Iteration Proposal} + */ + +// In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator +var SYMBOL_ASYNC_ITERATOR = SYMBOL && SYMBOL.asyncIterator + +/** + * A property name to be used as the name of an AsyncIterable's method + * responsible for producing an Iterator, referred to as `@@asyncIterator`. + * Typically represents the value `Symbol.asyncIterator` but falls back to the + * string `"@@asyncIterator"` when `Symbol.asyncIterator` is not defined. + * + * Use `$$asyncIterator` for defining new AsyncIterables instead of + * `Symbol.asyncIterator`, but do not use it for accessing existing Iterables, + * instead use {@link getAsyncIterator} or {@link isAsyncIterable}. + * + * @example + * + * var $$asyncIterator = require('iterall').$$asyncIterator + * + * function Chirper (to) { + * this.to = to + * } + * + * Chirper.prototype[$$asyncIterator] = function () { + * return { + * to: this.to, + * num: 0, + * next () { + * return new Promise(resolve => { + * if (this.num >= this.to) { + * resolve({ value: undefined, done: true }) + * } else { + * setTimeout(() => { + * resolve({ value: this.num++, done: false }) + * }, 1000) + * } + * }) + * } + * } + * } + * + * var chirper = new Chirper(3) + * for await (var number of chirper) { + * console.log(number) // 0 ...wait... 1 ...wait... 2 + * } + * + * @type {Symbol|string} + */ +/*:: declare export var $$asyncIterator: '@@asyncIterator'; */ +export var $$asyncIterator = SYMBOL_ASYNC_ITERATOR || '@@asyncIterator' + +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method. + * + * @example + * + * var isAsyncIterable = require('iterall').isAsyncIterable + * isAsyncIterable(myStream) // true + * isAsyncIterable('ABC') // false + * + * @param obj + * A value which might implement the AsyncIterable protocol. + * @return {boolean} true if AsyncIterable. + */ +/*:: declare export function isAsyncIterable(obj: any): boolean; */ +export function isAsyncIterable(obj) { + return !!getAsyncIteratorMethod(obj) +} + +/** + * If the provided object implements the AsyncIterator protocol, its + * AsyncIterator object is returned. Otherwise returns undefined. + * + * @example + * + * var getAsyncIterator = require('iterall').getAsyncIterator + * var asyncIterator = getAsyncIterator(myStream) + * asyncIterator.next().then(console.log) // { value: 1, done: false } + * asyncIterator.next().then(console.log) // { value: 2, done: false } + * asyncIterator.next().then(console.log) // { value: 3, done: false } + * asyncIterator.next().then(console.log) // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {AsyncIterable} asyncIterable + * An AsyncIterable object which is the source of an AsyncIterator. + * @return {AsyncIterator} new AsyncIterator instance. + */ +/*:: declare export var getAsyncIterator: + & (<+TValue>(asyncIterable: AsyncIterable) => AsyncIterator) + & ((asyncIterable: mixed) => (void | AsyncIterator)); */ +export function getAsyncIterator(asyncIterable) { + var method = getAsyncIteratorMethod(asyncIterable) + if (method) { + return method.call(asyncIterable) + } +} + +/** + * If the provided object implements the AsyncIterator protocol, the method + * responsible for producing its AsyncIterator object is returned. + * + * This is used in rare cases for performance tuning. This method must be called + * with obj as the contextual this-argument. + * + * @example + * + * var getAsyncIteratorMethod = require('iterall').getAsyncIteratorMethod + * var method = getAsyncIteratorMethod(myStream) + * if (method) { + * var asyncIterator = method.call(myStream) + * } + * + * @template T the type of each iterated value + * @param {AsyncIterable} asyncIterable + * An AsyncIterable object which defines an `@@asyncIterator` method. + * @return {function(): AsyncIterator} `@@asyncIterator` method. + */ +/*:: declare export var getAsyncIteratorMethod: + & (<+TValue>(asyncIterable: AsyncIterable) => (() => AsyncIterator)) + & ((asyncIterable: mixed) => (void | (() => AsyncIterator))); */ +export function getAsyncIteratorMethod(asyncIterable) { + if (asyncIterable != null) { + var method = + (SYMBOL_ASYNC_ITERATOR && asyncIterable[SYMBOL_ASYNC_ITERATOR]) || + asyncIterable['@@asyncIterator'] + if (typeof method === 'function') { + return method + } + } +} + +/** + * Similar to {@link getAsyncIterator}, this method returns a new AsyncIterator + * given an AsyncIterable. However it will also create an AsyncIterator for a + * non-async Iterable as well as non-Iterable Array-like collection, such as + * Array in a pre-ES2015 environment. + * + * `createAsyncIterator` is complimentary to `forAwaitEach`, but allows a + * buffering "pull"-based iteration as opposed to `forAwaitEach`'s + * "push"-based iteration. + * + * `createAsyncIterator` produces an AsyncIterator for non-async Iterables as + * described in the ECMAScript proposal [Async-from-Sync Iterator Objects](https://tc39.github.io/proposal-async-iteration/#sec-async-from-sync-iterator-objects). + * + * > Note: Creating `AsyncIterator`s requires the existence of `Promise`. + * > While `Promise` has been available in modern browsers for a number of + * > years, legacy browsers (like IE 11) may require a polyfill. + * + * @example + * + * var createAsyncIterator = require('iterall').createAsyncIterator + * + * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } + * var iterator = createAsyncIterator(myArraylike) + * iterator.next().then(console.log) // { value: 'Alpha', done: false } + * iterator.next().then(console.log) // { value: 'Bravo', done: false } + * iterator.next().then(console.log) // { value: 'Charlie', done: false } + * iterator.next().then(console.log) // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {AsyncIterable|Iterable|{ length: number }} source + * An AsyncIterable, Iterable, or Array-like object to produce an Iterator. + * @return {AsyncIterator} new AsyncIterator instance. + */ +/*:: declare export var createAsyncIterator: + & (<+TValue>( + collection: Iterable | TValue> | AsyncIterable + ) => AsyncIterator) + & ((collection: {length: number}) => AsyncIterator) + & ((collection: mixed) => (void | AsyncIterator)); */ +export function createAsyncIterator(source) { + if (source != null) { + var asyncIterator = getAsyncIterator(source) + if (asyncIterator) { + return asyncIterator + } + var iterator = createIterator(source) + if (iterator) { + return new AsyncFromSyncIterator(iterator) + } + } +} + +// When the object provided to `createAsyncIterator` is not AsyncIterable but is +// sync Iterable, this simple wrapper is created. +function AsyncFromSyncIterator(iterator) { + this._i = iterator +} + +// Note: all AsyncIterators are themselves AsyncIterable. +AsyncFromSyncIterator.prototype[$$asyncIterator] = function() { + return this +} + +// A simple state-machine determines the IteratorResult returned, yielding +// each value in the Array-like object in order of their indicies. +AsyncFromSyncIterator.prototype.next = function() { + var step = this._i.next() + return Promise.resolve(step.value).then(function(value) { + return { value: value, done: step.done } + }) +} + +/** + * Given an object which either implements the AsyncIterable protocol or is + * Array-like, iterate over it, calling the `callback` at each iteration. + * + * Use `forAwaitEach` where you would expect to use a [for-await-of](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) loop. + * + * Similar to [Array#forEach][], the `callback` function accepts three + * arguments, and is provided with `thisArg` as the calling context. + * + * > Note: Using `forAwaitEach` requires the existence of `Promise`. + * > While `Promise` has been available in modern browsers for a number of + * > years, legacy browsers (like IE 11) may require a polyfill. + * + * @example + * + * var forAwaitEach = require('iterall').forAwaitEach + * + * forAwaitEach(myIterable, function (value, index, iterable) { + * console.log(value, index, iterable === myIterable) + * }) + * + * @example + * + * // ES2017: + * for await (let value of myAsyncIterable) { + * console.log(await doSomethingAsync(value)) + * } + * console.log('done') + * + * // Any JavaScript environment: + * forAwaitEach(myAsyncIterable, function (value) { + * return doSomethingAsync(value).then(console.log) + * }).then(function () { + * console.log('done') + * }) + * + * @template T the type of each iterated value + * @param {AsyncIterable|Iterable | T>|{ length: number }} source + * The AsyncIterable or array to iterate over. + * @param {function(T, number, object)} callback + * Function to execute for each iteration, taking up to three arguments + * @param [thisArg] + * Optional. Value to use as `this` when executing `callback`. + */ +/*:: declare export var forAwaitEach: + & (<+TValue, TCollection: Iterable | TValue> | AsyncIterable>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any + ) => Promise) + & (( + collection: TCollection, + callbackFn: (value: mixed, index: number, collection: TCollection) => any, + thisArg?: any + ) => Promise); */ +export function forAwaitEach(source, callback, thisArg) { + var asyncIterator = createAsyncIterator(source) + if (asyncIterator) { + var i = 0 + return new Promise(function(resolve, reject) { + function next() { + asyncIterator + .next() + .then(function(step) { + if (!step.done) { + Promise.resolve(callback.call(thisArg, step.value, i++, source)) + .then(next) + .catch(reject) + } else { + resolve() + } + // Explicitly return null, silencing bluebird-style warnings. + return null + }) + .catch(reject) + // Explicitly return null, silencing bluebird-style warnings. + return null + } + next() + }) + } +}