@znight/graphql 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-BWcayUtH.mjs","names":["DONE","GraphQLErrorClass","isPromise"],"sources":["../src/errors.ts","../src/context.ts","../src/format.ts","../src/limits.ts","../src/tokens.ts","../src/transport/abort.ts","../src/execution.ts","../src/transport/accept.ts","../src/transport/graphiql.ts","../src/transport/sse.ts","../src/transport/http.ts"],"sourcesContent":["/**\n * GraphQL errors shown to clients (RFC 0005 §5.10, §8.8): `GraphQLException` and the\n * `extensions.code` values the plugin produces (Apollo conventions, which clients already know).\n *\n * Import-free: the exception is a plain `Error` subclass, rendered by the runtime as\n * `{ message, locations, path, extensions: { code, ...extensions } }`.\n */\n\n/** `extensions.code` values produced by `@znight/graphql`. Applications may use their own codes too. */\nexport const GraphQLErrorCode: {\n /** The document does not parse (syntax error, `limits.maxTokens`). */\n readonly ParseFailed: 'GRAPHQL_PARSE_FAILED'\n /** The document is not valid against the schema. */\n readonly ValidationFailed: 'GRAPHQL_VALIDATION_FAILED'\n /** Invalid variables or arguments (Standard Schema issues in `extensions.issues`), HTTP 400. */\n readonly BadUserInput: 'BAD_USER_INPUT'\n /** The document exceeds `limits.maxDepth`, `maxAliases` or `maxDirectives`. */\n readonly QueryTooComplex: 'QUERY_TOO_COMPLEX'\n /** HTTP 401. */\n readonly Unauthenticated: 'UNAUTHENTICATED'\n /** A guard returned `false`, or HTTP 403. */\n readonly Forbidden: 'FORBIDDEN'\n /** HTTP 404, or a key missing from `orderByKeys`. */\n readonly NotFound: 'NOT_FOUND'\n /** HTTP 409. */\n readonly Conflict: 'CONFLICT'\n /** HTTP 429. */\n readonly TooManyRequests: 'TOO_MANY_REQUESTS'\n /** Any other HTTP 4xx. */\n readonly BadRequest: 'BAD_REQUEST'\n /** A subscriber fell behind its buffer: its stream ends with this error. */\n readonly SubscriptionOverflow: 'SUBSCRIPTION_OVERFLOW'\n /** Too many active subscriptions (`subscriptions.maxActive`), HTTP 503. */\n readonly ServiceUnavailable: 'SERVICE_UNAVAILABLE'\n /** An unexpected error, masked (`Unexpected error.`) unless `exposeErrors`. */\n readonly InternalServerError: 'INTERNAL_SERVER_ERROR'\n} = Object.freeze({\n ParseFailed: 'GRAPHQL_PARSE_FAILED',\n ValidationFailed: 'GRAPHQL_VALIDATION_FAILED',\n BadUserInput: 'BAD_USER_INPUT',\n QueryTooComplex: 'QUERY_TOO_COMPLEX',\n Unauthenticated: 'UNAUTHENTICATED',\n Forbidden: 'FORBIDDEN',\n NotFound: 'NOT_FOUND',\n Conflict: 'CONFLICT',\n TooManyRequests: 'TOO_MANY_REQUESTS',\n BadRequest: 'BAD_REQUEST',\n SubscriptionOverflow: 'SUBSCRIPTION_OVERFLOW',\n ServiceUnavailable: 'SERVICE_UNAVAILABLE',\n InternalServerError: 'INTERNAL_SERVER_ERROR',\n})\n\n/** One of the {@link GraphQLErrorCode} values. */\nexport type GraphQLErrorCodeValue = (typeof GraphQLErrorCode)[keyof typeof GraphQLErrorCode]\n\n/** Options of {@link GraphQLException}. */\nexport interface GraphQLExceptionOptions {\n /** `extensions.code` (`'NOT_FOUND'`, `'CONFLICT'`, or an application code). */\n readonly code: GraphQLErrorCodeValue | (string & Record<never, never>)\n /** Extra `extensions` entries, sent to the client (`code` always wins). */\n readonly extensions?: Readonly<Record<string, unknown>>\n /**\n * The original error: never sent, logged once at `error` level with the request id, the schema\n * coordinate and the path when the exception is shown for a field.\n */\n readonly cause?: unknown\n}\n\n/**\n * An error whose message and extensions are sent to the client as they are (§5.10): throw it from a\n * resolver or return it from a `GraphQLErrorMapper`.\n *\n * ```ts\n * throw new GraphQLException(`No book ${id}`, { code: 'NOT_FOUND', extensions: { bookId: id } })\n * ```\n */\nexport class GraphQLException extends Error {\n /** `extensions.code`. */\n readonly code: string\n /** Extra `extensions` entries. */\n readonly extensions: Readonly<Record<string, unknown>> | undefined\n\n constructor(message: string, options: GraphQLExceptionOptions) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause })\n this.name = 'GraphQLException'\n this.code = options.code\n this.extensions = options.extensions\n }\n}\n","/**\n * The implementation of `GraphQLContext` (RFC 0005 §5.8): one per operation, passed to graphql-js\n * as `contextValue` and stored in the request scope (`@znight/graphql#GraphQLContext`).\n *\n * Everything that is not needed by every operation is computed on first read: the request id (a\n * UUID for direct executions), the HTTP context of an enclosing request, the signal, the state map\n * and the loader registry.\n */\nimport type { Container, ScopeContext, Token } from '@znight/core'\nimport type { HttpContext } from '@znight/http'\nimport type { DocumentNode, OperationDefinitionNode } from 'graphql'\nimport type { LoaderFactory } from './loaders.ts'\nimport type {\n BatchLoad,\n BatchLoadClass,\n BatchLoader,\n GraphQLContext,\n GraphQLOperationKind,\n GraphQLTransport,\n LoaderKey,\n LoaderValue,\n} from './types.ts'\n\nimport { randomUUID } from 'node:crypto'\nimport { ErrorCode, ZnightError } from '@znight/core'\nimport { HttpTokens } from '@znight/http'\n\n/** What every operation context of a plugin shares. */\nexport interface ContextRuntime {\n readonly container: Container\n readonly loaders: LoaderFactory\n /** The plugin's own signal (aborted by `onStop`): the signal of direct executions. */\n readonly signal: AbortSignal\n}\n\n/** What a request carries that the context exposes (a `GraphQLRequest`). */\nexport interface ContextRequest {\n readonly variables?: Readonly<Record<string, unknown>> | null | undefined\n}\n\n/** How the request reached the executor (`ExecuteOptions`). */\nexport interface ContextOptions {\n readonly transport?: GraphQLTransport\n readonly http?: HttpContext\n readonly signal?: AbortSignal\n readonly requestId?: string\n /** The driver that received the operation (RFC 0009); `'builtin'` when absent. */\n readonly driver?: string\n /** The driver's context (`ExecutionArgs.contextValue` given to the engine). */\n readonly serverContext?: unknown\n}\n\nconst NO_VARIABLES: Readonly<Record<string, unknown>> = Object.freeze({})\n\n/**\n * The `GraphQLContext` of one operation. Built from references the executor already holds (the\n * operation node, the request, the options, the enclosing scope): one allocation per operation,\n * every field read on demand.\n */\nexport class OperationContext implements GraphQLContext {\n readonly document: DocumentNode\n readonly #runtime: ContextRuntime\n readonly #operation: OperationDefinitionNode\n readonly #request: ContextRequest\n readonly #options: ContextOptions\n readonly #scope: ScopeContext | undefined\n #requestId: string | undefined\n #http: HttpContext | null | undefined\n #signal: AbortSignal | undefined\n #ended: AbortSignal | undefined\n #state: Map<string | symbol, unknown> | undefined\n #loaders: Map<Token, BatchLoader<unknown, unknown>> | undefined\n\n constructor(\n runtime: ContextRuntime,\n document: DocumentNode,\n operation: OperationDefinitionNode,\n request: ContextRequest,\n options: ContextOptions,\n scope: ScopeContext | undefined,\n ) {\n this.#runtime = runtime\n this.document = document\n this.#operation = operation\n this.#request = request\n this.#options = options\n this.#scope = scope\n this.#requestId = options.requestId\n }\n\n get transport(): GraphQLTransport {\n return this.#options.transport ?? 'direct'\n }\n\n /** The driver that received the operation: `'builtin'` for the built-in transport and direct calls. */\n get driver(): string {\n return this.#options.driver ?? 'builtin'\n }\n\n get serverContext(): unknown {\n return this.#options.serverContext\n }\n\n get operationType(): GraphQLOperationKind {\n return this.#operation.operation\n }\n\n get operationName(): string | undefined {\n return this.#operation.name?.value\n }\n\n get requestId(): string {\n let id = this.#requestId\n if (id === undefined) {\n const http = this.http\n const scoped = http === undefined ? this.#scope?.get(HttpTokens.RequestId) : undefined\n id = http?.requestId ?? (typeof scoped === 'string' ? scoped : randomUUID())\n this.#requestId = id\n }\n return id\n }\n\n get http(): HttpContext | undefined {\n let http = this.#http\n if (http === undefined) {\n // a controller calling plugin.execute(): the HTTP request of the enclosing scope\n http = this.#options.http ?? this.#scope?.get(HttpTokens.Context) ?? null\n this.#http = http\n }\n return http ?? undefined\n }\n\n get variables(): Readonly<Record<string, unknown>> {\n return this.#request.variables ?? NO_VARIABLES\n }\n\n get signal(): AbortSignal {\n let signal = this.#signal\n if (signal === undefined) {\n // HttpContext.signal is created on first read: only read it when someone asks\n const base = this.#options.signal ?? this.http?.signal ?? this.#runtime.signal\n const ended = this.#ended\n signal = ended === undefined ? base : AbortSignal.any([base, ended])\n this.#signal = signal\n }\n return signal\n }\n\n /**\n * Ties {@link signal} to the end of a subscription: it also aborts when `ended` does (the stream\n * ended by itself or with `return()`). Called before any resolver runs.\n */\n endsWith(ended: AbortSignal): void {\n this.#ended = ended\n }\n\n get state(): Map<string | symbol, unknown> {\n this.#state ??= new Map()\n return this.#state\n }\n\n loader<L extends BatchLoad<unknown, unknown>>(loader: BatchLoadClass<L>): BatchLoader<LoaderKey<L>, LoaderValue<L>>\n loader(token: Token): BatchLoader<unknown, unknown>\n loader(key: Token | BatchLoadClass): BatchLoader<unknown, unknown> {\n const token = typeof key === 'string' ? key : this.#tokenOf(key)\n let loaders = this.#loaders\n if (loaders === undefined) {\n loaders = new Map()\n this.#loaders = loaders\n }\n let loader = loaders.get(token)\n if (loader === undefined) {\n loader = this.#runtime.loaders.create(token)\n loaders.set(token, loader)\n }\n return loader\n }\n\n /** Starts a new execution (a subscription event): loaders and their caches are renewed. */\n resetLoaders(): void {\n this.#loaders = undefined\n }\n\n #tokenOf(loader: BatchLoadClass): Token {\n const token = typeof loader === 'function' ? this.#runtime.container.tokenOf(loader) : undefined\n if (token === undefined) {\n const name = typeof loader === 'function' ? loader.name || '<anonymous>' : String(loader)\n throw new ZnightError(ErrorCode.MissingProvider, `GraphQLContext.loader(): ${name} is not a provider`, {\n hints: ['Add @Injectable() to the loader class (it implements BatchLoad<K, V>)'],\n })\n }\n return token\n }\n}\n","/**\n * Error formatting (RFC 0005 §5.10, §8.8): what clients see of the errors of a result.\n *\n * Execution errors, in order: a `GraphQLException` (or a `GraphQLError` thrown by user code) as is →\n * the error mappers, in order → an `HttpException` mapped by status (5xx masked) → anything else\n * masked as `Unexpected error.` with `INTERNAL_SERVER_ERROR`, logged once (unless `exposeErrors`).\n * The `cause` of a shown `GraphQLException` is logged once too, never sent.\n * Request errors (parse, validation, variables, limits) carry their code and are never logged\n * above `debug`.\n *\n * Kept apart from the import-free `errors.ts`, which the compiler side may reach.\n */\nimport type { Container, CoreLogger, Token } from '@znight/core'\nimport type {\n ASTNode,\n DocumentNode,\n FieldNode,\n FragmentDefinitionNode,\n GraphQLField,\n GraphQLFormattedError,\n GraphQLNamedType,\n GraphQLSchema,\n OperationDefinitionNode,\n SelectionSetNode,\n} from 'graphql'\nimport type { GraphQLContext, GraphQLErrorMapper } from './types.ts'\n\nimport { isHttpException, ValidationException } from '@znight/http'\nimport { GraphQLError, getNamedType, isObjectType, Kind } from 'graphql'\n\nimport { GraphQLErrorCode, GraphQLException } from './errors.ts'\n\n/** A provider resolved once (singleton, instance) or per use, in the current scope (token). */\nexport type Resolvable<T> = { readonly instance: T; readonly token?: undefined } | { readonly token: Token }\n\n/** Resolves a {@link Resolvable} (in the current scope for scoped providers). */\nexport function resolveIn<T>(container: Container, resolvable: Resolvable<T>): T {\n return resolvable.token === undefined ? resolvable.instance : (container.get(resolvable.token) as T)\n}\n\n/** Message of masked errors. */\nexport const MASKED_MESSAGE = 'Unexpected error.'\n\n/** `HttpException` status → `extensions.code` (other 4xx: `BAD_REQUEST`, 5xx: masked). */\nconst STATUS_CODES: ReadonlyMap<number, string> = new Map([\n [400, GraphQLErrorCode.BadUserInput],\n [401, GraphQLErrorCode.Unauthenticated],\n [403, GraphQLErrorCode.Forbidden],\n [404, GraphQLErrorCode.NotFound],\n [409, GraphQLErrorCode.Conflict],\n [429, GraphQLErrorCode.TooManyRequests],\n])\n\n/** Options of {@link ErrorFormatter}. */\nexport interface ErrorFormatterOptions {\n readonly container: Container\n readonly mappers: readonly Resolvable<GraphQLErrorMapper>[]\n readonly exposeErrors: boolean\n readonly logger: CoreLogger\n readonly schema: GraphQLSchema\n}\n\n/** Formats the errors of execution results. One per plugin, built at boot. */\nexport class ErrorFormatter {\n readonly #container: Container\n readonly #mappers: readonly Resolvable<GraphQLErrorMapper>[]\n readonly #expose: boolean\n readonly #logger: CoreLogger\n readonly #schema: GraphQLSchema\n\n constructor(options: ErrorFormatterOptions) {\n this.#container = options.container\n this.#mappers = options.mappers\n this.#expose = options.exposeErrors\n this.#logger = options.logger\n this.#schema = options.schema\n }\n\n /** Formats the errors of an executed operation (field errors). */\n format(errors: readonly GraphQLError[], ctx: GraphQLContext): GraphQLFormattedError[] {\n const result: GraphQLFormattedError[] = new Array(errors.length)\n // the same cause may fail several fields (a loader rejecting every key): logged once\n let logged: Set<unknown> | undefined\n for (let index = 0; index < errors.length; index++) {\n const error = errors[index] as GraphQLError\n const original = error.originalError\n if (original === undefined || original === null) {\n // produced by graphql-js during execution (non-null violation...): about the schema, shown as is\n result[index] = withCode(\n error,\n error.extensions['code'] === undefined ? GraphQLErrorCode.InternalServerError : undefined,\n )\n continue\n }\n const exposed = this.#exposed(original, ctx)\n if (exposed !== undefined) {\n result[index] = render(error, exposed)\n // the original failure behind a presented error (`{ cause }`): logged once, never sent\n const cause = exposed.cause\n if (cause !== undefined) {\n logged ??= new Set()\n if (!logged.has(cause)) {\n logged.add(cause)\n this.#log(error, cause, ctx, exposed.code)\n }\n }\n continue\n }\n if (original instanceof GraphQLError && !isCompletionError(original)) {\n result[index] = { ...original.toJSON(), ...located(error) }\n continue\n }\n logged ??= new Set()\n if (!logged.has(original)) {\n logged.add(original)\n this.#log(error, original, ctx, undefined)\n }\n result[index] = {\n message: this.#expose && original instanceof Error ? original.message : MASKED_MESSAGE,\n ...located(error),\n extensions: { code: GraphQLErrorCode.InternalServerError },\n }\n }\n return result\n }\n\n /** The exception shown for `original`, `undefined` when it must be masked. */\n #exposed(original: unknown, ctx: GraphQLContext): GraphQLException | undefined {\n if (original instanceof GraphQLException) return original\n for (const resolvable of this.#mappers) {\n let mapped: GraphQLException | undefined\n try {\n mapped = resolveIn(this.#container, resolvable).map(original, ctx)\n } catch (error) {\n this.#logger.error('GraphQLPlugin: an error mapper failed', { err: error, requestId: ctx.requestId })\n continue\n }\n if (mapped !== undefined) return mapped\n }\n if (isHttpException(original)) {\n const status = original.status\n if (original instanceof ValidationException) {\n return new GraphQLException(original.message, {\n code: GraphQLErrorCode.BadUserInput,\n extensions: { issues: original.details },\n })\n }\n if (status >= 500) return undefined\n return new GraphQLException(original.message, {\n code: STATUS_CODES.get(status) ?? GraphQLErrorCode.BadRequest,\n })\n }\n return undefined\n }\n\n /** Logs an unexpected error, or the cause of a presented one (`code`), at `error` level. */\n #log(error: GraphQLError, cause: unknown, ctx: GraphQLContext, code: string | undefined): void {\n const coordinate = coordinateOf(this.#schema, ctx.document, ctx.operationName, error.path)\n const what = code === undefined ? 'unexpected error' : `${code} error`\n this.#logger.error(`GraphQL: ${what}${coordinate === undefined ? '' : ` in ${coordinate}`}`, {\n err: cause,\n requestId: ctx.requestId,\n ...(code === undefined ? {} : { code }),\n ...(coordinate === undefined ? {} : { coordinate }),\n ...(error.path === undefined ? {} : { path: error.path.join('.') }),\n })\n }\n}\n\n/**\n * What graphql-js raises while completing a resolver's value: a built-in scalar or an enum that\n * cannot represent it (`String cannot represent value: { passwordHash: ... }`), a list value that\n * is not iterable, a union or interface value that resolves to no member. A server bug whose message\n * holds the value, masked and logged like any unexpected error. graphql-js throws plain\n * `GraphQLError`s without code there, told apart from the ones of user code by their message.\n */\nconst COMPLETION_ERROR =\n /^(?:(?:Int|Float|String|Boolean|ID) cannot represent |Enum \"[^\"]*\" cannot represent |Expected Iterable, but did not find one for field \"|Abstract type \"|Runtime Object type \")/\n\nfunction isCompletionError(error: GraphQLError): boolean {\n return (\n error.constructor === GraphQLError && error.extensions['code'] === undefined && COMPLETION_ERROR.test(error.message)\n )\n}\n\nfunction located(error: GraphQLError): Pick<GraphQLFormattedError, 'locations' | 'path'> {\n return {\n ...(error.locations === undefined ? {} : { locations: error.locations }),\n ...(error.path === undefined ? {} : { path: error.path }),\n }\n}\n\n/** `{ message, locations, path, extensions: { ...extensions, code } }`. */\nfunction render(error: GraphQLError, exception: GraphQLException): GraphQLFormattedError {\n return {\n message: exception.message,\n ...located(error),\n extensions: { ...exception.extensions, code: exception.code },\n }\n}\n\n/** A graphql-js error formatted with `extensions.code` set to `code` (kept as is without code). */\nexport function withCode(error: GraphQLError, code: string | undefined): GraphQLFormattedError {\n const formatted = error.toJSON()\n if (code === undefined) return formatted\n return { ...formatted, extensions: { ...formatted.extensions, code } }\n}\n\n/** A request error (no location): `{ message, extensions: { code } }`. */\nexport function requestError(\n message: string,\n code: string,\n nodes?: ASTNode | readonly ASTNode[],\n): GraphQLFormattedError {\n return withCode(new GraphQLError(message, nodes === undefined ? {} : { nodes }), code)\n}\n\n/**\n * The schema coordinate (`Book.author`) of the field at `path`, found by walking the operation's\n * selections (aliases, fragments, inline fragments). Best effort, for logs: `undefined` when the\n * path crosses a union without a type condition.\n */\nexport function coordinateOf(\n schema: GraphQLSchema,\n document: DocumentNode,\n operationName: string | undefined,\n path: readonly (string | number)[] | undefined,\n): string | undefined {\n if (path === undefined || path.length === 0) return undefined\n const fragments = new Map<string, FragmentDefinitionNode>()\n let operation: OperationDefinitionNode | undefined\n for (const definition of document.definitions) {\n if (definition.kind === Kind.FRAGMENT_DEFINITION) fragments.set(definition.name.value, definition)\n else if (\n definition.kind === Kind.OPERATION_DEFINITION &&\n (operationName === undefined || definition.name?.value === operationName)\n ) {\n operation ??= definition\n }\n }\n if (operation === undefined) return undefined\n let type: GraphQLNamedType | undefined | null = schema.getRootType(operation.operation)\n let selections: SelectionSetNode[] = [operation.selectionSet]\n let coordinate: string | undefined\n for (const segment of path) {\n if (typeof segment === 'number') continue\n const found = findField(selections, segment, fragments, type?.name)\n if (found === undefined || type === undefined || type === null) return undefined\n const parent: GraphQLNamedType | undefined | null =\n found.typeCondition === undefined ? type : schema.getType(found.typeCondition)\n if (!isObjectType(parent)) return undefined\n const field: GraphQLField<unknown, unknown> | undefined = parent.getFields()[found.field.name.value]\n coordinate = `${parent.name}.${found.field.name.value}`\n if (field === undefined) return coordinate\n type = getNamedType(field.type)\n selections = found.field.selectionSet === undefined ? [] : [found.field.selectionSet]\n }\n return coordinate\n}\n\nfunction findField(\n sets: readonly SelectionSetNode[],\n key: string,\n fragments: ReadonlyMap<string, FragmentDefinitionNode>,\n typeCondition: string | undefined,\n): { readonly field: FieldNode; readonly typeCondition: string | undefined } | undefined {\n for (const set of sets) {\n for (const selection of set.selections) {\n if (selection.kind === Kind.FIELD) {\n if ((selection.alias ?? selection.name).value === key) return { field: selection, typeCondition }\n } else {\n const nested = selection.kind === Kind.INLINE_FRAGMENT ? selection : fragments.get(selection.name.value)\n if (nested === undefined) continue\n const found = findField(\n [nested.selectionSet],\n key,\n fragments,\n nested.typeCondition?.name.value ?? typeCondition,\n )\n if (found !== undefined) return found\n }\n }\n }\n return undefined\n}\n","/**\n * Document limits (RFC 0005 §8.9): depth, aliases and directives, checked in one walk of the parsed\n * document **before** the specified validation rules, so that an abusive document is rejected\n * before rules whose cost grows with it (`OverlappingFieldsCanBeMerged`) run. Aliases are counted as\n * written, and, when the document spreads fragments, as each operation executes them (a fragment\n * spread several times counts each time). `maxTokens` is enforced by `parse()` itself.\n */\nimport type { DirectiveNode, DocumentNode, FragmentDefinitionNode, SelectionSetNode, ValidationRule } from 'graphql'\n\nimport { GraphQLError, Kind } from 'graphql'\n\nimport { GraphQLErrorCode } from './errors.ts'\n\n/** Resolved limits: `undefined` disables one. */\nexport interface DocumentLimits {\n readonly maxDepth: number | undefined\n readonly maxAliases: number | undefined\n readonly maxDirectives: number | undefined\n}\n\n/** The limit errors of `document` (`QUERY_TOO_COMPLEX`), `undefined` when it is within its limits. */\nexport function checkLimits(document: DocumentNode, limits: DocumentLimits): GraphQLError[] | undefined {\n const { maxDepth, maxAliases, maxDirectives } = limits\n if (maxDepth === undefined && maxAliases === undefined && maxDirectives === undefined) return undefined\n const counter = { aliases: 0, directives: 0, spreads: 0 }\n const fragments = new Map<string, FragmentDefinitionNode>()\n for (const definition of document.definitions) {\n if (definition.kind === Kind.FRAGMENT_DEFINITION) fragments.set(definition.name.value, definition)\n }\n let errors: GraphQLError[] | undefined\n const fail = (message: string): void => {\n errors ??= []\n errors.push(new GraphQLError(message, { extensions: { code: GraphQLErrorCode.QueryTooComplex } }))\n }\n // counts every selection once, where it is written (fragment spreads expanded below for aliases)\n for (const definition of document.definitions) {\n if (definition.kind === Kind.OPERATION_DEFINITION || definition.kind === Kind.FRAGMENT_DEFINITION) {\n countDirectives(definition.directives, counter)\n if (definition.kind === Kind.OPERATION_DEFINITION) {\n for (const variable of definition.variableDefinitions ?? []) countDirectives(variable.directives, counter)\n }\n count(definition.selectionSet, counter)\n }\n }\n if (maxAliases !== undefined) {\n if (counter.aliases > maxAliases) {\n fail(`The document has ${counter.aliases} aliases, more than the limit of ${maxAliases}.`)\n } else if (counter.spreads > 0) {\n // a fragment spread several times executes its aliases each time: counted as executed\n const memo = new Map<string, number>()\n for (const definition of document.definitions) {\n if (definition.kind !== Kind.OPERATION_DEFINITION) continue\n const executed = aliasesOf(definition.selectionSet, fragments, memo, new Set(), maxAliases + 1)\n if (executed > maxAliases) {\n const name = definition.name === undefined ? 'The operation' : `The operation ${definition.name.value}`\n fail(`${name} has more than ${maxAliases} aliases once its fragments are expanded.`)\n break\n }\n }\n }\n }\n if (maxDirectives !== undefined && counter.directives > maxDirectives) {\n fail(`The document has ${counter.directives} directives, more than the limit of ${maxDirectives}.`)\n }\n if (maxDepth !== undefined) {\n const depths = new Map<string, number>()\n for (const definition of document.definitions) {\n if (definition.kind !== Kind.OPERATION_DEFINITION) continue\n const depth = depthOf(definition.selectionSet, fragments, depths, new Set())\n if (depth > maxDepth) {\n const name = definition.name === undefined ? 'The operation' : `The operation ${definition.name.value}`\n fail(`${name} is ${depth} levels deep, more than the limit of ${maxDepth}.`)\n }\n }\n }\n return errors\n}\n\n/**\n * The limits as a graphql-js validation rule (`GraphQLEngine.rules`, RFC 0009), for GraphQL servers\n * that parse and validate documents themselves: the same check as {@link checkLimits}, run once on\n * the document node. `undefined` when every limit is disabled.\n */\nexport function limitsRule(limits: DocumentLimits): ValidationRule | undefined {\n if (limits.maxDepth === undefined && limits.maxAliases === undefined && limits.maxDirectives === undefined) {\n return undefined\n }\n const rule: ValidationRule = context => ({\n Document(node) {\n const errors = checkLimits(node, limits)\n if (errors !== undefined) for (const error of errors) context.reportError(error)\n // the whole document is checked at once: nothing to visit below it\n return false\n },\n })\n Object.defineProperty(rule, 'name', { value: 'ZnightDocumentLimitsRule' })\n return rule\n}\n\ninterface Counter {\n aliases: number\n directives: number\n spreads: number\n}\n\nfunction countDirectives(directives: readonly DirectiveNode[] | undefined, counter: Counter): void {\n if (directives !== undefined) counter.directives += directives.length\n}\n\nfunction count(set: SelectionSetNode, counter: Counter): void {\n for (const selection of set.selections) {\n countDirectives(selection.directives, counter)\n if (selection.kind === Kind.FIELD) {\n if (selection.alias !== undefined) counter.aliases++\n if (selection.selectionSet !== undefined) count(selection.selectionSet, counter)\n } else if (selection.kind === Kind.INLINE_FRAGMENT) {\n count(selection.selectionSet, counter)\n } else {\n counter.spreads++\n }\n }\n}\n\n/**\n * Aliases a selection set executes, fragment spreads expanded (`a: f { ...F } b: f { ...F }` counts\n * the aliases of `F` twice). Fragment counts are memoised, so the walk stays linear in the document;\n * counts saturate at `cap` (one more than the limit) and a fragment cycle counts 0 (validation\n * rejects it).\n */\nfunction aliasesOf(\n set: SelectionSetNode,\n fragments: ReadonlyMap<string, FragmentDefinitionNode>,\n memo: Map<string, number>,\n visiting: Set<string>,\n cap: number,\n): number {\n let total = 0\n for (const selection of set.selections) {\n if (selection.kind === Kind.FIELD) {\n if (selection.alias !== undefined) total++\n if (selection.selectionSet !== undefined)\n total += aliasesOf(selection.selectionSet, fragments, memo, visiting, cap)\n } else if (selection.kind === Kind.INLINE_FRAGMENT) {\n total += aliasesOf(selection.selectionSet, fragments, memo, visiting, cap)\n } else {\n const name = selection.name.value\n let known = memo.get(name)\n if (known === undefined) {\n const fragment = fragments.get(name)\n if (fragment === undefined || visiting.has(name)) continue\n visiting.add(name)\n known = aliasesOf(fragment.selectionSet, fragments, memo, visiting, cap)\n visiting.delete(name)\n memo.set(name, known)\n }\n total += known\n }\n if (total >= cap) return cap\n }\n return total\n}\n\n/**\n * Field nesting of a selection set (`{ a { b } }` is 2). Introspection fields (`__schema`,\n * `__type`) do not count: `MaxIntrospectionDepthRule` bounds them. Fragment depths are memoised; a\n * fragment cycle counts 0 (validation rejects it).\n */\nfunction depthOf(\n set: SelectionSetNode,\n fragments: ReadonlyMap<string, FragmentDefinitionNode>,\n depths: Map<string, number>,\n visiting: Set<string>,\n): number {\n let max = 0\n for (const selection of set.selections) {\n let depth = 0\n if (selection.kind === Kind.FIELD) {\n if (selection.name.value.startsWith('__')) continue\n depth =\n selection.selectionSet === undefined ? 1 : 1 + depthOf(selection.selectionSet, fragments, depths, visiting)\n } else if (selection.kind === Kind.INLINE_FRAGMENT) {\n depth = depthOf(selection.selectionSet, fragments, depths, visiting)\n } else {\n const name = selection.name.value\n const known = depths.get(name)\n if (known === undefined) {\n const fragment = fragments.get(name)\n if (fragment === undefined || visiting.has(name)) continue\n visiting.add(name)\n depth = depthOf(fragment.selectionSet, fragments, depths, visiting)\n visiting.delete(name)\n depths.set(name, depth)\n } else depth = known\n }\n if (depth > max) max = depth\n }\n return max\n}\n","import type { TypedToken } from '@znight/core'\nimport type { GraphQLPlugin } from './plugin.ts'\nimport type { PubSub } from './pubsub.ts'\nimport type { GraphQLContext } from './types.ts'\n\n/**\n * Tokens of the values `GraphQLPlugin` supplies to the container (declared in the package\n * manifest). `GraphQLContext` is a request-scoped external: inject it in request-scoped providers\n * or through `Lazy<GraphQLContext>`.\n */\nexport const GraphQLTokens: {\n /** The {@link GraphQLContext} of the current operation (request scope). */\n readonly Context: TypedToken<GraphQLContext>\n /** The application {@link PubSub} (singleton). */\n readonly PubSub: TypedToken<PubSub>\n /** The {@link GraphQLPlugin} instance (singleton). */\n readonly Plugin: TypedToken<GraphQLPlugin>\n} = Object.freeze({\n Context: '@znight/graphql#GraphQLContext',\n PubSub: '@znight/graphql#PubSub',\n Plugin: '@znight/graphql#GraphQLPlugin',\n})\n","/**\n * A deferred abort signal for graphql-js (RFC 0005 §8.3, \"Cancellation\").\n *\n * `HttpContext.signal` is created on first read, and creating it costs an `AbortController` plus a\n * close listener on the connection; graphql-js then adds and removes an abort listener per\n * execution. A query whose resolvers are synchronous cannot be cancelled anyway, so the transport\n * passes this stand-in instead: it records the listener graphql-js registers and starts following\n * `ctx.signal` only when the execution turned asynchronous ({@link DeferredAbort.follow}).\n *\n * It implements the part of `AbortSignal` graphql-js 17 reads (`aborted`, `reason`,\n * `throwIfAborted()`, `addEventListener('abort')`, `removeEventListener('abort')`); the transport\n * tests check that a client leaving during an asynchronous query aborts it.\n */\n\ntype Listener = () => void\n\n/** The stand-in passed as graphql-js `abortSignal` by the HTTP transport (one per request). */\nexport class DeferredAbort {\n aborted = false\n reason: unknown = undefined\n /** graphql-js registers one listener per execution; more are kept in {@link #others}. */\n #listener: Listener | undefined = undefined\n #others: Listener[] | undefined = undefined\n\n throwIfAborted(): void {\n if (this.aborted) throw this.reason\n }\n\n addEventListener(type: string, listener: Listener): void {\n if (type !== 'abort') return\n if (this.#listener === undefined) {\n this.#listener = listener\n return\n }\n this.#others ??= []\n this.#others.push(listener)\n }\n\n removeEventListener(type: string, listener: Listener): void {\n if (type !== 'abort') return\n if (this.#listener === listener) {\n this.#listener = undefined\n return\n }\n const others = this.#others\n const index = others === undefined ? -1 : others.indexOf(listener)\n if (index !== -1) others?.splice(index, 1)\n }\n\n /**\n * The execution is asynchronous: from now on, `signal` aborting aborts the execution. Reads the\n * signal only when graphql-js still listens (a pending execution).\n */\n follow(read: () => AbortSignal): void {\n if (this.#listener === undefined && (this.#others === undefined || this.#others.length === 0)) return\n const signal = read()\n if (signal.aborted) {\n this.#abort(signal.reason)\n return\n }\n signal.addEventListener('abort', () => this.#abort(signal.reason), { once: true })\n }\n\n /** This stand-in, typed as the `AbortSignal` graphql-js expects. */\n asSignal(): AbortSignal {\n return this as unknown as AbortSignal\n }\n\n #abort(reason: unknown): void {\n if (this.aborted) return\n this.aborted = true\n this.reason = reason\n const listener = this.#listener\n const others = this.#others\n this.#listener = undefined\n this.#others = undefined\n listener?.()\n if (others !== undefined) for (const other of others) other()\n }\n}\n","/**\n * Execution (RFC 0005 §8.4, §8.7–§8.10): the document cache, request checks, operation selection,\n * graphql-js `execute` and subscriptions, error formatting and the `graphql:operation` hook.\n *\n * `GraphQLExecutor` is the internal API of the transports (`plugin.execute()`, GraphQL over HTTP\n * and SSE): `execute()` answers a request with a status and a formatted result, `subscribe()` with\n * a stream of formatted results (or a rejection). The `*Document()` methods are what the public\n * `GraphQLEngine` of the drivers calls (RFC 0009 §4.2): graphql-js-shaped, on a parsed document,\n * answering `GraphQLError` instances. They share the document cache, the context, the pipelines,\n * the formatting and the hook with the transport methods, whose code they leave untouched.\n *\n * Per operation, on the hot path (a cached query over a scope that already exists): one cache\n * lookup, one context object, graphql-js `execute`, and the result as graphql-js returned it when\n * it has no error. Synchronous when every resolver is; nothing is awaited that is not a promise.\n * The hook event is built only when the hook has wrappers or listeners.\n */\nimport type { Container, CoreLogger, GraphQLOperationEvent, Hooks, ScopeContext } from '@znight/core'\nimport type { HttpContext } from '@znight/http'\nimport type {\n DocumentNode,\n ExecutionArgs,\n ExecutionResult,\n FormattedExecutionResult,\n GraphQLError,\n GraphQLFormattedError,\n GraphQLSchema,\n OperationDefinitionNode,\n Source,\n ValidatedSubscriptionArgs,\n ValidationRule,\n} from 'graphql'\nimport type { ContextRuntime } from './context.ts'\nimport type { ErrorFormatter } from './format.ts'\nimport type { DocumentLimits } from './limits.ts'\nimport type { GraphQLOperationKind, GraphQLTransport } from './types.ts'\n\nimport { createHash, randomUUID } from 'node:crypto'\nimport { ErrorCode, ZnightError } from '@znight/core'\nimport { HttpTokens } from '@znight/http'\nimport {\n AbortedGraphQLExecutionError,\n createSourceEventStream,\n execute,\n executeSubscriptionEvent,\n GraphQLError as GraphQLErrorClass,\n Kind,\n NoSchemaIntrospectionCustomRule,\n parse,\n print,\n specifiedRules,\n validate,\n validateSubscriptionArgs,\n} from 'graphql'\n\nimport { OperationContext } from './context.ts'\nimport { GraphQLErrorCode } from './errors.ts'\nimport { requestError, withCode } from './format.ts'\nimport { checkLimits, limitsRule } from './limits.ts'\nimport { GraphQLTokens } from './tokens.ts'\nimport { DeferredAbort } from './transport/abort.ts'\n\n/** A GraphQL request: the body of a GraphQL-over-HTTP request, or the argument of `plugin.execute()`. */\nexport interface GraphQLRequest {\n readonly query: string\n readonly operationName?: string | null | undefined\n readonly variables?: Readonly<Record<string, unknown>> | null | undefined\n /** Request extensions (ignored by the executor; available to transports). */\n readonly extensions?: Readonly<Record<string, unknown>> | null | undefined\n}\n\n/** How a request reached the executor. */\nexport interface ExecuteOptions {\n /** Default `'direct'`. */\n readonly transport?: GraphQLTransport\n /** The HTTP request carrying the operation (GraphQL over HTTP and SSE). */\n readonly http?: HttpContext\n /**\n * Cancels the operation (passed to graphql-js `abortSignal`, and `GraphQLContext.signal`). Only\n * passed when given: graphql-js then adds an abort listener per execution. Over HTTP, the\n * transport passes `ctx.signal`.\n */\n readonly signal?: AbortSignal\n /**\n * Passed to graphql-js as `abortSignal` instead of {@link signal} (which stays the signal of\n * `GraphQLContext.signal`). The HTTP transport passes a stand-in that reads `ctx.signal` only when\n * an execution turns asynchronous (see `transport/abort.ts`).\n */\n readonly abortSignal?: AbortSignal\n /** Default: the HTTP request id, the request id of the enclosing scope, or a UUID (on first read). */\n readonly requestId?: string\n /** GET: queries only, other operations are rejected with 405 and `allow: POST`. */\n readonly queriesOnly?: boolean\n /**\n * {@link GraphQLExecutor.execute} answers a subscription with {@link SUBSCRIBE} (nothing observed\n * yet) instead of a 400: the HTTP transport then streams it (the client accepts an event stream).\n */\n readonly streamSubscriptions?: boolean\n /** The driver that received the operation (`GraphQLOperationEvent.driver`). Default `'builtin'`. */\n readonly driver?: string\n /** The driver's context (`ExecutionArgs.contextValue`): `GraphQLContext.serverContext`. */\n readonly serverContext?: unknown\n}\n\n/**\n * The answer of {@link GraphQLExecutor.execute} to a subscription with\n * {@link ExecuteOptions.streamSubscriptions}: start it with {@link GraphQLExecutor.subscribe}.\n */\nexport const SUBSCRIBE: GraphQLResponse = Object.freeze({ status: 0, result: Object.freeze({}) })\n\n/** The answer to a request: an HTTP-like status and the formatted result. */\nexport interface GraphQLResponse {\n /**\n * 200: executed (the result may hold field errors); 400: request error (parse, validation,\n * variables, limits, operation selection, subscription without stream); 405: not a query with\n * `queriesOnly`; 503: too many active subscriptions.\n */\n readonly status: number\n readonly result: FormattedExecutionResult\n /** Headers of the HTTP response (`allow` with a 405). */\n readonly headers?: Readonly<Record<string, string>>\n}\n\n/** The results of a subscription (one per event), or the single result of a query sent as a stream. */\nexport interface GraphQLResultStream extends AsyncIterableIterator<FormattedExecutionResult> {\n /** Ends the stream: the source event stream is returned (unsubscribed). */\n return(): Promise<IteratorResult<FormattedExecutionResult>>\n}\n\n/** The stream of results of a subscription started through the engine (`GraphQLEngine.subscribe`). */\nexport type EngineStream = AsyncGenerator<ExecutionResult, void, void>\n\n/** Any result the hook reads: a transport response, or an engine one (`GraphQLError` instances). */\ninterface Settled {\n readonly status: number\n readonly result: {\n readonly data?: unknown\n readonly errors?: readonly {\n readonly message: string\n readonly path?: readonly (string | number)[] | undefined\n readonly extensions?: { readonly [key: string]: unknown } | undefined\n }[]\n }\n}\n\n/** The answer to an engine execution: like {@link GraphQLResponse}, with a graphql-js result. */\ninterface EngineResponse {\n readonly status: number\n readonly result: ExecutionResult\n}\n\n/** What {@link GraphQLExecutor} is built from (resolved plugin options). */\nexport interface ExecutorOptions {\n readonly schema: GraphQLSchema\n readonly container: Container\n readonly hooks: Hooks\n readonly logger: CoreLogger\n readonly formatter: ErrorFormatter\n readonly runtime: ContextRuntime\n readonly limits: DocumentLimits & { readonly maxTokens: number | undefined }\n readonly introspection: boolean\n /** Entries of the document cache, 0 disables it. */\n readonly documentCache: number\n /** Active subscriptions cap, `undefined`: none. */\n readonly maxActiveSubscriptions: number | undefined\n /**\n * `subscriptions: false`: the engine answers a subscription with a `BAD_REQUEST` error result\n * (the built-in transport refuses event streams itself). Default `true`.\n */\n readonly subscriptions?: boolean\n}\n\nconst OPERATION_HOOK = 'graphql:operation'\nconst DIRECT: ExecuteOptions = Object.freeze({})\nconst NO_ERRORS: readonly GraphQLError[] = Object.freeze([])\nconst DONE: IteratorResult<FormattedExecutionResult> = Object.freeze({ done: true, value: undefined })\n\n/** SHA-256 (hex) of a query text: `GraphQLOperationEvent.documentId`. */\nfunction documentId(query: string): string {\n return createHash('sha256').update(query, 'utf8').digest('hex')\n}\n\n/** A parsed and validated document, kept by the document cache. */\nclass CachedDocument {\n readonly query: string\n readonly document: DocumentNode\n /** The operation of a single-operation document. */\n readonly single: OperationDefinitionNode | undefined\n /** Operations by name (documents with several operations). */\n readonly named: ReadonlyMap<string, OperationDefinitionNode> | undefined\n #id: string | undefined\n\n constructor(query: string, document: DocumentNode) {\n this.query = query\n this.document = document\n let single: OperationDefinitionNode | undefined\n let named: Map<string, OperationDefinitionNode> | undefined\n let count = 0\n for (const definition of document.definitions) {\n if (definition.kind !== Kind.OPERATION_DEFINITION) continue\n count++\n single = definition\n if (definition.name !== undefined) {\n named ??= new Map()\n named.set(definition.name.value, definition)\n }\n }\n this.single = count === 1 ? single : undefined\n this.named = named\n }\n\n /** SHA-256 of the query, computed on first read (only the hook needs it). */\n get id(): string {\n this.#id ??= documentId(this.query)\n return this.#id\n }\n}\n\n/** A bounded LRU of documents by exact query text. */\nclass DocumentCache {\n readonly #max: number\n readonly #entries = new Map<string, CachedDocument>()\n #last: string | undefined\n\n constructor(max: number) {\n this.#max = max\n }\n\n get size(): number {\n return this.#entries.size\n }\n\n get(query: string): CachedDocument | undefined {\n const entry = this.#entries.get(query)\n // refresh the recency (a re-insertion), except for the most recent entry: the hot loop of one query\n if (entry !== undefined && this.#last !== query) {\n this.#entries.delete(query)\n this.#entries.set(query, entry)\n this.#last = query\n }\n return entry\n }\n\n set(query: string, entry: CachedDocument): void {\n if (this.#max === 0) return\n if (this.#entries.size >= this.#max) {\n const oldest = this.#entries.keys().next()\n if (oldest.done !== true) this.#entries.delete(oldest.value)\n }\n this.#entries.set(query, entry)\n this.#last = query\n }\n\n clear(): void {\n this.#entries.clear()\n this.#last = undefined\n }\n}\n\n/** A request refused before execution. */\nclass Rejection {\n readonly status: number\n readonly errors: GraphQLFormattedError[]\n readonly operationType: GraphQLOperationKind | undefined\n readonly operationName: string | undefined\n readonly documentId: string | undefined\n readonly headers: Readonly<Record<string, string>> | undefined\n\n constructor(\n status: number,\n errors: GraphQLFormattedError[],\n documentId: string | undefined,\n operation?: OperationDefinitionNode,\n headers?: Readonly<Record<string, string>>,\n ) {\n this.status = status\n this.errors = errors\n this.documentId = documentId\n this.operationType = operation?.operation\n this.operationName = operation?.name?.value\n this.headers = headers\n }\n\n response(): GraphQLResponse {\n return {\n status: this.status,\n result: { errors: this.errors },\n ...(this.headers === undefined ? {} : { headers: this.headers }),\n }\n }\n}\n\n/** A request ready to execute. */\ninterface Prepared {\n readonly entry: CachedDocument\n readonly operation: OperationDefinitionNode\n}\n\n/** What starting a subscription gives: a stream, a rejection, or (engine) an error result. */\ntype Started = GraphQLResultStream | EngineStream | ExecutionResult | Rejection\n\n/** The GraphQL executor of a plugin. */\nexport class GraphQLExecutor {\n readonly #schema: GraphQLSchema\n readonly #container: Container\n readonly #hooks: Hooks\n readonly #logger: CoreLogger\n readonly #formatter: ErrorFormatter\n readonly #runtime: ContextRuntime\n readonly #rules: readonly ValidationRule[]\n readonly #limits: DocumentLimits\n readonly #maxTokens: number | undefined\n readonly #hideSuggestions: boolean\n readonly #cache: DocumentCache\n readonly #maxActive: number | undefined\n readonly #subscriptions: boolean\n readonly #streams = new Set<SubscriptionStream<unknown>>()\n /**\n * The streams the plugin ends in `onStop`: direct subscriptions and those of the engine. The SSE\n * streams of the built-in transport are ended by `HttpPlugin`'s shutdown (with a `retry` hint).\n */\n readonly #owned = new Set<SubscriptionStream<unknown>>()\n /** The streams of the engine (drivers), a part of {@link #owned}: ended when `HttpPlugin` drains. */\n readonly #engineStreams = new Set<SubscriptionStream<unknown>>()\n /** The application stops (`HttpPlugin` drains, or the plugin stops): the engine refuses new subscriptions (503). */\n #closing = false\n /** Subscriptions counted against `maxActive` while their source starts (not yet in `#streams`). */\n #starting = 0\n /** The engine's extra rules (`GraphQLEngine.rules`): the limits, introspection. Built on first use. */\n #engineRules: readonly ValidationRule[] | undefined\n /** The document limits as a rule, `undefined` when every limit is off. */\n readonly #limitsRule: ValidationRule | undefined\n /** Documents parsed by {@link parseDocument}: within their limits, not checked again by validation. */\n readonly #limited = new WeakSet<DocumentNode>()\n /** Operations of the documents the engine executed, by document (the server's or the cache's). */\n readonly #documents = new WeakMap<DocumentNode, CachedDocument>()\n\n constructor(options: ExecutorOptions) {\n this.#schema = options.schema\n this.#container = options.container\n this.#hooks = options.hooks\n this.#logger = options.logger\n this.#formatter = options.formatter\n this.#runtime = options.runtime\n this.#rules = options.introspection ? specifiedRules : [...specifiedRules, NoSchemaIntrospectionCustomRule]\n this.#limits = options.limits\n this.#maxTokens = options.limits.maxTokens\n // without introspection, suggestions would leak field and type names\n this.#hideSuggestions = !options.introspection\n this.#cache = new DocumentCache(options.documentCache)\n this.#maxActive = options.maxActiveSubscriptions\n this.#subscriptions = options.subscriptions !== false\n this.#limitsRule = limitsRule(options.limits)\n }\n\n /** The schema operations run against. */\n get schema(): GraphQLSchema {\n return this.#schema\n }\n\n /** The engine's own validation rules (`GraphQLEngine.rules`): the limits, and introspection when it is off. */\n get engineRules(): readonly ValidationRule[] {\n let rules = this.#engineRules\n if (rules === undefined) {\n const list: ValidationRule[] = []\n if (this.#limitsRule !== undefined) list.push(this.#limitsRule)\n if (this.#hideSuggestions) list.push(NoSchemaIntrospectionCustomRule)\n rules = Object.freeze(list)\n this.#engineRules = rules\n }\n return rules\n }\n\n /** Active subscriptions (every transport). */\n get activeSubscriptions(): number {\n return this.#streams.size\n }\n\n /** Documents in the cache. */\n get cachedDocuments(): number {\n return this.#cache.size\n }\n\n /**\n * Executes a query or a mutation. Resolves (or returns, when every resolver is synchronous) a\n * response; rejects only when `options.signal` aborts the execution (with the signal's reason).\n * A subscription is a 400: it needs {@link subscribe} ({@link SUBSCRIBE} with\n * `streamSubscriptions`).\n */\n execute(request: GraphQLRequest, options: ExecuteOptions = DIRECT): GraphQLResponse | Promise<GraphQLResponse> {\n const prepared = this.#prepare(request, options)\n if (prepared instanceof Rejection) return this.#reject(prepared, request, options)\n if (prepared.operation.operation === 'subscription') {\n if (options.streamSubscriptions === true) return SUBSCRIBE\n return this.#reject(\n new Rejection(\n 400,\n [\n requestError(\n 'Subscriptions are delivered as a stream: send the request with accept: text/event-stream (GraphQL over SSE), or call GraphQLPlugin.subscribe()',\n GraphQLErrorCode.BadRequest,\n ),\n ],\n prepared.entry.id,\n prepared.operation,\n ),\n request,\n options,\n )\n }\n const scope = this.#container.currentScope()\n const ctx = this.#context(prepared, request, options, scope)\n const hooks = this.#hooks\n if (!hooks.hasWrappers(OPERATION_HOOK) && !hooks.hasListeners(OPERATION_HOOK)) {\n return this.#inScope(scope, ctx, () => this.#run(prepared, request, options, ctx))\n }\n return this.#inScope(scope, ctx, () =>\n this.#observed(ctx, prepared.entry.id, () => this.#run(prepared, request, options, ctx)),\n )\n }\n\n /**\n * Subscribes: a stream of results, one per source event, or a rejection (status 400, 405 or 503).\n * A query or a mutation gives a stream of its single result. The stream ends when the source\n * ends, when `options.signal` aborts, or with `return()`; a source failure ends it with a final\n * error result (`SUBSCRIPTION_OVERFLOW` for a subscriber that fell behind `MemoryPubSub`).\n */\n async subscribe(\n request: GraphQLRequest,\n options: ExecuteOptions = DIRECT,\n ): Promise<GraphQLResponse | GraphQLResultStream> {\n const prepared = this.#prepare(request, options)\n if (prepared instanceof Rejection) return this.#reject(prepared, request, options)\n if (prepared.operation.operation !== 'subscription') {\n const response = await this.execute(request, options)\n return response.status === 200 ? new SingleResultStream(response.result) : response\n }\n if (this.#full()) return this.#reject(overflow(prepared), request, options)\n const started = await this.#start(prepared, request, options, false)\n return started instanceof Rejection ? started.response() : (started as GraphQLResultStream)\n }\n\n /** Every slot of `subscriptions.maxActive` is taken (started streams and starting ones). */\n #full(): boolean {\n return this.#maxActive !== undefined && this.#streams.size + this.#starting >= this.#maxActive\n }\n\n /**\n * Starts a subscription in the current scope (or in one of its own, open as long as the stream):\n * the slot reserved, the context and the hook observer created, the source started. A rejection\n * (variables) is observed and returned for the caller to answer.\n */\n async #start(\n prepared: Prepared,\n request: GraphQLRequest,\n options: ExecuteOptions,\n engine: boolean,\n ): Promise<Started> {\n // the slot is reserved before the source starts (guards and subscribe methods may be async):\n // concurrent subscriptions see it; released once the stream is counted or did not start\n let reserved = this.#maxActive !== undefined\n if (reserved) this.#starting++\n const release = (): void => {\n if (reserved) {\n reserved = false\n this.#starting--\n }\n }\n const outer = this.#container.currentScope()\n const ctx = this.#context(prepared, request, options, outer)\n // ctx.signal also aborts when the stream ends (return() included, on every transport): the\n // source, started before the first read (SubscriptionStream), then lets go of its PubSub topic\n const ended = new AbortController()\n ctx.endsWith(ended.signal)\n let run: <R>(fn: () => R) => R\n let close: () => void\n if (outer === undefined) {\n // a direct subscription: its own scope, open as long as the stream\n const opened = this.#container.openScope([[GraphQLTokens.Context, ctx]])\n run = fn => opened.run(fn)\n close = () => {\n ended.abort()\n opened.close()?.catch(error => this.#runtimeLogError('Failed to close the scope of a subscription', error))\n }\n } else {\n outer.set(GraphQLTokens.Context, ctx)\n run = fn => fn()\n close = () => ended.abort()\n }\n const observer = this.#observer(ctx, prepared.entry.id)\n try {\n const stream = await run(() =>\n this.#startSubscription(prepared, request, options, ctx, observer, run, close, release, engine),\n )\n release()\n if (stream instanceof Rejection) {\n close()\n observer?.end('rejected', stream.errors)\n }\n return stream\n } catch (error) {\n release()\n close()\n observer?.end('error', undefined)\n throw error\n }\n }\n\n /**\n * Ends every subscription the plugin owns (plugin `onStop`): direct ones and those started\n * through the engine (drivers). Built-in SSE streams end with `HttpPlugin`'s shutdown.\n */\n async stopStreams(): Promise<void> {\n this.#closing = true\n await Promise.all([...this.#owned].map(stream => stream.return()))\n }\n\n /**\n * Ends the subscriptions of the engine (`HttpPlugin` drains, `GraphQLPlugin.onHttpDrain()`): a\n * driver serves them as streamed responses `HttpPlugin` does not close. New ones are refused (503).\n */\n async stopEngineStreams(): Promise<void> {\n this.#closing = true\n await Promise.all([...this.#engineStreams].map(stream => stream.return()))\n }\n\n /** Forgets every cached document. */\n clear(): void {\n this.#cache.clear()\n }\n\n // ------------------------------------------------------------------------------------------------\n // engine (RFC 0009 §4.2): graphql-js-shaped, on parsed documents, for GraphQL servers (drivers)\n\n /**\n * `GraphQLEngine.parse`: the document of the cache for a valid text, otherwise the text parsed\n * with `maxTokens` and checked against the depth, aliases and directives limits. Throws a\n * `GraphQLError` (`GRAPHQL_PARSE_FAILED`, `QUERY_TOO_COMPLEX`), observed as a rejected operation.\n */\n parseDocument(source: string | Source, driver: string): DocumentNode {\n const text = typeof source === 'string' ? source : (source as Source | undefined)?.body\n if (typeof text === 'string') {\n const cached = this.#cache.get(text)\n if (cached !== undefined) return cached.document\n }\n let document: DocumentNode\n try {\n document = parse(source, this.#maxTokens === undefined ? undefined : { maxTokens: this.#maxTokens })\n } catch (error) {\n if (!(error instanceof GraphQLErrorClass)) throw error\n const failed = coded(error, GraphQLErrorCode.ParseFailed)\n this.#rejectedDocument([failed], text, driver)\n throw failed\n }\n const limited = checkLimits(document, this.#limits)\n if (limited !== undefined) {\n this.#rejectedDocument(limited, text, driver)\n throw limited[0]\n }\n this.#limited.add(document)\n return document\n }\n\n /**\n * `GraphQLEngine.validate`: `rules` (default: graphql-js `specifiedRules`) plus the engine's own\n * (the limits, unless {@link parseDocument} checked them, and introspection), with\n * `hideSuggestions` when introspection is off. With the default rules on the engine's schema, a\n * cached document is not validated again, and a valid one enters the document cache. Errors carry\n * `GRAPHQL_VALIDATION_FAILED` (or the limit's code) and are observed as a rejected operation.\n */\n validateDocument(\n schema: GraphQLSchema,\n document: DocumentNode,\n rules: readonly ValidationRule[] | undefined,\n driver: string,\n ): readonly GraphQLError[] {\n const standard = rules === undefined || isSpecifiedRules(rules)\n const cacheable = standard && schema === this.#schema\n const text = document.loc?.source.body\n if (cacheable && text !== undefined && this.#cache.get(text)?.document === document) return NO_ERRORS\n const limited = this.#limited.has(document)\n let all: readonly ValidationRule[]\n if (standard) {\n all = limited || this.#limitsRule === undefined ? this.#rules : [this.#limitsRule, ...this.#rules]\n } else {\n // the server's rules (Envelop plugins add some) and the engine's, each once\n const merged = new Set<ValidationRule>(limited ? rules : [...this.engineRules, ...rules])\n for (const rule of this.engineRules) merged.add(rule)\n if (limited && this.#limitsRule !== undefined) merged.delete(this.#limitsRule)\n all = [...merged]\n }\n const errors = validate(schema, document, all, { hideSuggestions: this.#hideSuggestions })\n if (errors.length === 0) {\n if (cacheable && text !== undefined) {\n const entry = new CachedDocument(text, document)\n this.#cache.set(text, entry)\n this.#documents.set(document, entry)\n }\n return NO_ERRORS\n }\n const failed = errors.map(error =>\n coded(error, error.extensions['code'] === undefined ? GraphQLErrorCode.ValidationFailed : undefined),\n )\n this.#rejectedDocument(failed, text, driver)\n return failed\n }\n\n /**\n * `GraphQLEngine.execute`: a validated query or mutation of `args.document`, in the current\n * request scope (or one of its own), with the operation's `GraphQLContext` as `contextValue`\n * (`args.contextValue` becomes `serverContext`). The result is graphql-js's, its errors mapped\n * and masked, as `GraphQLError` instances without `originalError`. Without `options.signal`, an\n * execution that turns asynchronous follows `GraphQLContext.signal` (the HTTP request's).\n */\n executeDocument(args: ExecutionArgs, options: ExecuteOptions): ExecutionResult | Promise<ExecutionResult> {\n const prepared = this.#prepareDocument(args)\n if (prepared instanceof Rejection) return asEngineResult(this.#reject(prepared, requestOf(args), options))\n if (prepared.operation.operation === 'subscription') {\n return asEngineResult(\n this.#reject(\n new Rejection(\n 400,\n [requestError('Subscriptions are started with GraphQLEngine.subscribe()', GraphQLErrorCode.BadRequest)],\n prepared.entry.id,\n prepared.operation,\n ),\n requestOf(args),\n options,\n ),\n )\n }\n const request: GraphQLRequest = {\n query: prepared.entry.query,\n operationName: args.operationName,\n variables: args.variableValues,\n }\n let abort: DeferredAbort | undefined\n let effective = options\n if (options.signal === undefined) {\n // like the HTTP transport: the request's signal is only followed once the execution is pending\n abort = new DeferredAbort()\n effective = { ...options, abortSignal: abort.asSignal() }\n }\n const scope = this.#container.currentScope()\n const ctx = this.#context(prepared, request, effective, scope)\n const run = (): EngineResponse | Promise<EngineResponse> =>\n this.#runEngine(prepared, request, effective, ctx, args.rootValue)\n const hooks = this.#hooks\n const response =\n !hooks.hasWrappers(OPERATION_HOOK) && !hooks.hasListeners(OPERATION_HOOK)\n ? this.#inScope(scope, ctx, run)\n : this.#inScope(scope, ctx, () => this.#observed(ctx, prepared.entry.id, run))\n if (!isPromise(response)) return response.result\n abort?.follow(() => ctx.signal)\n return response.then(resultOf)\n }\n\n /**\n * `GraphQLEngine.subscribe`: starts a validated subscription, a stream of graphql-js results (its\n * loaders renewed per event), or a single error result (rejected, past `maxActive`, a source that\n * could not start). A query or a mutation is executed: its single result. The stream ends with\n * `return()`, `options.signal` (default: the HTTP request's), its source, or the plugin's stop.\n */\n async subscribeDocument(args: ExecutionArgs, options: ExecuteOptions): Promise<EngineStream | ExecutionResult> {\n const prepared = this.#prepareDocument(args)\n if (prepared instanceof Rejection) return asEngineResult(this.#reject(prepared, requestOf(args), options))\n if (prepared.operation.operation !== 'subscription') return this.executeDocument(args, options)\n if (!this.#subscriptions) {\n return asEngineResult(\n this.#reject(\n new Rejection(\n 400,\n [requestError('Subscriptions are disabled on this server', GraphQLErrorCode.BadRequest)],\n prepared.entry.id,\n prepared.operation,\n ),\n requestOf(args),\n options,\n ),\n )\n }\n if (this.#full() || this.#closing) {\n return asEngineResult(this.#reject(unavailable(prepared, this.#closing), requestOf(args), options))\n }\n const request: GraphQLRequest = {\n query: prepared.entry.query,\n operationName: args.operationName,\n variables: args.variableValues,\n }\n let effective = options\n if (options.signal === undefined) {\n const http = this.#container.currentScope()?.get(HttpTokens.Context) as HttpContext | undefined\n if (http !== undefined) effective = { ...options, signal: http.signal }\n }\n const started = await this.#start(prepared, request, effective, true)\n if (started instanceof Rejection) return { errors: started.errors.map(fromFormatted) }\n return started as EngineStream | ExecutionResult\n }\n\n /** The document of `args` and its operation, or a rejection (operation selection). */\n #prepareDocument(args: ExecutionArgs): Prepared | Rejection {\n if (args?.schema !== this.#schema) {\n throw new ZnightError(\n ErrorCode.InvalidGraphQLSetup,\n \"GraphQLEngine: the operation targets another schema than the engine's (ExecutionArgs.schema)\",\n { hints: [\"Give the GraphQL server engine.schema: its resolvers are the engine's pipelines\"] },\n )\n }\n const document = args.document\n let entry = this.#documents.get(document)\n if (entry === undefined) {\n const text = document.loc?.source.body\n const cached = text === undefined ? undefined : this.#cache.get(text)\n entry =\n cached !== undefined && cached.document === document\n ? cached\n : new CachedDocument(text ?? print(document), document)\n this.#documents.set(document, entry)\n }\n const operationName = args.operationName\n let operation: OperationDefinitionNode | undefined\n if (operationName === undefined || operationName === null) {\n operation = entry.single\n if (operation === undefined) {\n return new Rejection(\n 400,\n [\n requestError(\n 'Must provide operation name if query contains multiple operations.',\n GraphQLErrorCode.BadRequest,\n ),\n ],\n entry.id,\n )\n }\n } else {\n operation = entry.named?.get(operationName)\n if (operation === undefined) {\n return new Rejection(\n 400,\n [requestError(`Unknown operation named \"${operationName}\".`, GraphQLErrorCode.BadRequest)],\n entry.id,\n )\n }\n }\n return { entry, operation }\n }\n\n #runEngine(\n prepared: Prepared,\n request: GraphQLRequest,\n options: ExecuteOptions,\n ctx: OperationContext,\n rootValue: unknown,\n ): EngineResponse | Promise<EngineResponse> {\n let result: ExecutionResult | Promise<ExecutionResult>\n try {\n result = execute({\n schema: this.#schema,\n document: prepared.entry.document,\n rootValue,\n operationName: request.operationName,\n variableValues: request.variables,\n contextValue: ctx,\n abortSignal: options.abortSignal ?? options.signal,\n hideSuggestions: this.#hideSuggestions,\n })\n } catch (error) {\n return Promise.reject(abortReason(error, options))\n }\n if (isPromise(result)) {\n return result.then(\n settled => this.#respondEngine(settled, ctx),\n (error: unknown) => Promise.reject(abortReason(error, options)),\n )\n }\n return this.#respondEngine(result, ctx)\n }\n\n /** {@link #respond} for the engine: the errors as `GraphQLError` instances. */\n #respondEngine(result: ExecutionResult, ctx: OperationContext): EngineResponse {\n const errors = result.errors\n if (errors === undefined) return { status: 200, result }\n if (!('data' in result)) {\n // no data: graphql-js refused the variables before executing\n return {\n status: 400,\n result: {\n errors: errors.map(error =>\n coded(error, error.extensions['code'] === undefined ? GraphQLErrorCode.BadUserInput : undefined),\n ),\n },\n }\n }\n return {\n status: 200,\n result: {\n data: result.data,\n errors: asGraphQLErrors(errors, this.#formatter.format(errors, ctx)),\n ...(result.extensions === undefined ? {} : { extensions: result.extensions }),\n },\n }\n }\n\n /** A document rejected by {@link parseDocument} or {@link validateDocument}, for the hook. */\n #rejectedDocument(errors: readonly GraphQLError[], text: string | undefined, driver: string): void {\n const hooks = this.#hooks\n const wrapped = hooks.hasWrappers(OPERATION_HOOK)\n if (!wrapped && !hooks.hasListeners(OPERATION_HOOK)) return\n const event: GraphQLOperationEvent = {\n operationType: undefined,\n operationName: undefined,\n documentId: text === undefined ? undefined : documentId(text),\n transport: 'http',\n driver,\n requestId: this.#scopedRequestId(),\n context: undefined,\n startTime: performance.now(),\n outcome: 'rejected',\n errors: summaries(errors),\n }\n if (!wrapped) {\n hooks.emit(OPERATION_HOOK, event)\n return\n }\n // parse and validate are synchronous: wrappers see the rejection, they cannot delay it\n hooks\n .run(OPERATION_HOOK, event, () => Promise.resolve())\n .then(\n () => {\n if (hooks.hasListeners(OPERATION_HOOK)) hooks.emit(OPERATION_HOOK, event)\n },\n (error: unknown) => this.#runtimeLogError('A \"graphql:operation\" hook wrapper failed', error),\n )\n }\n\n // ------------------------------------------------------------------------------------------------\n // preparation\n\n /** Request checks, the document (cached, or parsed, limited and validated), the operation. */\n #prepare(request: GraphQLRequest, options: ExecuteOptions): Prepared | Rejection {\n const query: unknown = request?.query\n if (typeof query !== 'string' || query === '') {\n return badRequest(typeof query === 'string' ? 'The query is empty' : 'Missing query (a string)')\n }\n const operationName: unknown = request.operationName\n if (operationName !== undefined && operationName !== null && typeof operationName !== 'string') {\n return badRequest('operationName must be a string')\n }\n const variables: unknown = request.variables\n if (variables !== undefined && variables !== null && (typeof variables !== 'object' || Array.isArray(variables))) {\n return badRequest('variables must be an object')\n }\n const entry = this.#cache.get(query) ?? this.#load(query)\n if (entry instanceof Rejection) return entry\n let operation: OperationDefinitionNode | undefined\n if (operationName === undefined || operationName === null) {\n operation = entry.single\n if (operation === undefined) {\n return new Rejection(\n 400,\n [\n requestError(\n 'Must provide operation name if query contains multiple operations.',\n GraphQLErrorCode.BadRequest,\n ),\n ],\n entry.id,\n )\n }\n } else {\n operation = entry.named?.get(operationName)\n if (operation === undefined) {\n return new Rejection(\n 400,\n [requestError(`Unknown operation named \"${operationName}\".`, GraphQLErrorCode.BadRequest)],\n entry.id,\n )\n }\n }\n if (options.queriesOnly === true && operation.operation !== 'query') {\n return new Rejection(\n 405,\n [requestError(`A ${operation.operation} cannot be sent with GET: use POST`, GraphQLErrorCode.BadRequest)],\n entry.id,\n operation,\n { allow: 'POST' },\n )\n }\n return { entry, operation }\n }\n\n /** Parses, limits and validates a document; caches it when valid (rejected documents are not cached). */\n #load(query: string): CachedDocument | Rejection {\n let document: DocumentNode\n try {\n document = parse(query, this.#maxTokens === undefined ? undefined : { maxTokens: this.#maxTokens })\n } catch (error) {\n if (!(error instanceof GraphQLErrorClass)) throw error\n return new Rejection(400, [withCode(error, GraphQLErrorCode.ParseFailed)], documentId(query))\n }\n const limited = checkLimits(document, this.#limits)\n if (limited !== undefined) {\n return new Rejection(\n 400,\n limited.map(error => withCode(error, undefined)),\n documentId(query),\n )\n }\n const errors = validate(this.#schema, document, this.#rules, { hideSuggestions: this.#hideSuggestions })\n if (errors.length > 0) {\n return new Rejection(\n 400,\n errors.map(error => withCode(error, GraphQLErrorCode.ValidationFailed)),\n documentId(query),\n )\n }\n const entry = new CachedDocument(query, document)\n this.#cache.set(query, entry)\n return entry\n }\n\n #context(\n prepared: Prepared,\n request: GraphQLRequest,\n options: ExecuteOptions,\n scope: ScopeContext | undefined,\n ): OperationContext {\n return new OperationContext(this.#runtime, prepared.entry.document, prepared.operation, request, options, scope)\n }\n\n // ------------------------------------------------------------------------------------------------\n // execution\n\n /** Runs `fn` in the current scope (the GraphQL context set in it) or in a new one, closed after. */\n #inScope<R>(scope: ScopeContext | undefined, ctx: OperationContext, fn: () => R | Promise<R>): R | Promise<R> {\n if (scope !== undefined) {\n scope.set(GraphQLTokens.Context, ctx)\n return fn()\n }\n const opened = this.#container.openScope([[GraphQLTokens.Context, ctx]])\n let result: R | Promise<R>\n try {\n result = opened.run(fn)\n } catch (error) {\n const closing = opened.close()\n if (closing === undefined) throw error\n return closing.then(\n () => Promise.reject(error),\n () => Promise.reject(error),\n )\n }\n if (isPromise(result)) {\n return result.then(\n value => {\n const closing = opened.close()\n return closing === undefined ? value : closing.then(() => value)\n },\n (error: unknown) => {\n const closing = opened.close()\n if (closing === undefined) throw error\n return closing.then(\n () => Promise.reject(error),\n () => Promise.reject(error),\n )\n },\n )\n }\n // request-scoped providers created by a synchronous execution: disposed before answering\n const closing = opened.close()\n return closing === undefined ? result : closing.then(() => result)\n }\n\n #run(\n prepared: Prepared,\n request: GraphQLRequest,\n options: ExecuteOptions,\n ctx: OperationContext,\n ): GraphQLResponse | Promise<GraphQLResponse> {\n let result: ExecutionResult | Promise<ExecutionResult>\n try {\n result = execute({\n schema: this.#schema,\n document: prepared.entry.document,\n operationName: request.operationName,\n variableValues: request.variables,\n contextValue: ctx,\n // undefined: no abort listener in graphql-js (one per execution otherwise)\n abortSignal: options.abortSignal ?? options.signal,\n hideSuggestions: this.#hideSuggestions,\n })\n } catch (error) {\n return Promise.reject(abortReason(error, options))\n }\n if (isPromise(result)) {\n return result.then(\n settled => this.#respond(settled, ctx),\n (error: unknown) => Promise.reject(abortReason(error, options)),\n )\n }\n return this.#respond(result, ctx)\n }\n\n /** The response of an execution result: as is without errors, formatted errors otherwise. */\n #respond(result: ExecutionResult, ctx: OperationContext): GraphQLResponse {\n const errors = result.errors\n if (errors === undefined) return { status: 200, result: result as FormattedExecutionResult }\n if (!('data' in result)) {\n // no data: graphql-js refused the variables before executing\n return { status: 400, result: { errors: errors.map(variableError) } }\n }\n return {\n status: 200,\n result: {\n data: result.data,\n errors: this.#formatter.format(errors, ctx),\n ...(result.extensions === undefined ? {} : { extensions: result.extensions }),\n },\n }\n }\n\n /** Formats a subscription result: an event, a source that could not start or failed (field errors). */\n formatEvent(result: ExecutionResult, ctx: OperationContext): FormattedExecutionResult {\n const errors = result.errors\n if (errors === undefined) return result as FormattedExecutionResult\n return {\n ...('data' in result ? { data: result.data } : {}),\n errors: this.#formatter.format(errors, ctx),\n }\n }\n\n /** {@link formatEvent} for the engine: the errors formatted, then given back as `GraphQLError` instances. */\n engineEvent(result: ExecutionResult, ctx: OperationContext): ExecutionResult {\n const errors = result.errors\n if (errors === undefined) return result\n return {\n ...('data' in result ? { data: result.data } : {}),\n errors: asGraphQLErrors(errors, this.#formatter.format(errors, ctx)),\n }\n }\n\n /**\n * Starts the source of a subscription. `engine`: the results are graphql-js results\n * ({@link engineEvent}) and a source that could not start is an error result instead of a stream\n * of one result.\n */\n #startSubscription(\n prepared: Prepared,\n request: GraphQLRequest,\n options: ExecuteOptions,\n ctx: OperationContext,\n observer: Observer | undefined,\n run: <R>(fn: () => R) => R,\n close: () => void,\n release: () => void,\n engine: boolean,\n ): Promise<Started> | Started {\n const validated = validateSubscriptionArgs({\n schema: this.#schema,\n document: prepared.entry.document,\n operationName: request.operationName,\n variableValues: request.variables,\n contextValue: ctx,\n abortSignal: options.signal,\n hideSuggestions: this.#hideSuggestions,\n })\n if (!('schema' in validated)) {\n return new Rejection(400, validated.map(variableError), prepared.entry.id, prepared.operation)\n }\n const start = (source: AsyncIterable<unknown> | ExecutionResult): Started => {\n // the reservation becomes the stream (counted in #streams), or ends with the failed start\n release()\n if (!isAsyncIterable(source)) {\n // the subscription could not start (guard, resolver error): one error result\n if (engine) {\n const result = this.engineEvent(source, ctx)\n close()\n observer?.end('error', result.errors)\n return result\n }\n const result = this.formatEvent(source, ctx)\n close()\n observer?.end('error', result.errors)\n return new SingleResultStream(result)\n }\n const stream = new SubscriptionStream<unknown>({\n executor: this,\n source: source[Symbol.asyncIterator](),\n validated,\n ctx,\n run,\n signal: options.signal,\n field: responseKey(prepared.operation),\n engine,\n onEnd: (outcome, errors) => {\n this.#streams.delete(stream)\n this.#owned.delete(stream)\n if (engine) this.#engineStreams.delete(stream)\n close()\n observer?.end(outcome, errors)\n },\n })\n this.#streams.add(stream)\n if (engine || ctx.transport === 'direct') this.#owned.add(stream)\n if (engine) {\n this.#engineStreams.add(stream)\n // stopped while its source started: ended at once\n if (this.#closing) void stream.return()\n }\n return stream as GraphQLResultStream | EngineStream\n }\n const source = createSourceEventStream(validated)\n return isPromise(source) ? source.then(start) : start(source)\n }\n\n // ------------------------------------------------------------------------------------------------\n // hook\n\n /** A rejection as a response, observed by the hook (outcome `rejected`). */\n #reject(\n rejection: Rejection,\n request: GraphQLRequest,\n options: ExecuteOptions,\n ): GraphQLResponse | Promise<GraphQLResponse> {\n const hooks = this.#hooks\n const wrapped = hooks.hasWrappers(OPERATION_HOOK)\n if (!wrapped && !hooks.hasListeners(OPERATION_HOOK)) return rejection.response()\n const event: GraphQLOperationEvent = {\n operationType: rejection.operationType,\n operationName:\n rejection.operationName ?? (typeof request?.operationName === 'string' ? request.operationName : undefined),\n documentId: rejection.documentId,\n transport: options.transport ?? 'direct',\n driver: options.driver ?? 'builtin',\n requestId: options.requestId ?? options.http?.requestId ?? this.#scopedRequestId(),\n context: undefined,\n startTime: performance.now(),\n outcome: 'rejected',\n errors: summaries(rejection.errors),\n }\n if (!wrapped) {\n hooks.emit(OPERATION_HOOK, event)\n return rejection.response()\n }\n return hooks\n .run(OPERATION_HOOK, event, () => Promise.resolve(rejection.response()))\n .then(response => {\n if (hooks.hasListeners(OPERATION_HOOK)) hooks.emit(OPERATION_HOOK, event)\n return response\n })\n }\n\n /** An executed query or mutation, observed by the hook. */\n #observed<T extends Settled>(ctx: OperationContext, id: string, run: () => T | Promise<T>): T | Promise<T> {\n const hooks = this.#hooks\n const event = operationEvent(ctx, id)\n const done = (response: T): T => {\n event.outcome = outcomeOf(response)\n if (response.result.errors !== undefined) event.errors = summaries(response.result.errors)\n return response\n }\n const failed = (error: unknown): never => {\n event.outcome = 'error'\n throw error\n }\n const emit = (): void => {\n if (hooks.hasListeners(OPERATION_HOOK)) hooks.emit(OPERATION_HOOK, event)\n }\n if (hooks.hasWrappers(OPERATION_HOOK)) {\n const promise = hooks.run(OPERATION_HOOK, event, () => Promise.resolve(run()).then(done, failed))\n return promise.then(\n response => {\n emit()\n return response\n },\n (error: unknown) => {\n emit()\n throw error\n },\n )\n }\n // listeners only: no promise added to a synchronous execution\n let response: T | Promise<T>\n try {\n response = run()\n } catch (error) {\n event.outcome = 'error'\n emit()\n throw error\n }\n if (!isPromise(response)) {\n done(response)\n emit()\n return response\n }\n return response.then(\n settled => {\n done(settled)\n emit()\n return settled\n },\n (error: unknown) => {\n event.outcome = 'error'\n emit()\n throw error\n },\n )\n }\n\n /** The hook of a subscription, for its whole life (`end()` settles it), or `undefined` without wrappers nor listeners. */\n #observer(ctx: OperationContext, id: string): Observer | undefined {\n const hooks = this.#hooks\n const wrapped = hooks.hasWrappers(OPERATION_HOOK)\n if (!wrapped && !hooks.hasListeners(OPERATION_HOOK)) return undefined\n const event = operationEvent(ctx, id)\n let resolve: (() => void) | undefined\n if (wrapped) {\n const ended = new Promise<void>(settle => {\n resolve = settle\n })\n hooks\n .run(OPERATION_HOOK, event, () => ended)\n .catch(error => this.#runtimeLogError('A \"graphql:operation\" hook wrapper failed', error))\n }\n let ended = false\n return {\n end: (outcome, errors) => {\n if (ended) return\n ended = true\n event.outcome = outcome\n if (errors !== undefined && errors.length > 0) event.errors = summaries(errors)\n resolve?.()\n if (hooks.hasListeners(OPERATION_HOOK)) hooks.emit(OPERATION_HOOK, event)\n },\n }\n }\n\n /** The request id of the enclosing scope (a controller calling GraphQL), or a new one. */\n #scopedRequestId(): string {\n const id = this.#container.currentScope()?.get(HttpTokens.RequestId)\n return typeof id === 'string' ? id : randomUUID()\n }\n\n #runtimeLogError(message: string, error: unknown): void {\n this.#logger.error(`GraphQLPlugin: ${message}`, { err: error })\n }\n}\n\n/** Settles the hook event of a subscription. */\ninterface Observer {\n end(\n outcome: NonNullable<GraphQLOperationEvent['outcome']>,\n errors: NonNullable<Settled['result']['errors']> | undefined,\n ): void\n}\n\n/** The 503 of a subscription past `subscriptions.maxActive`. */\nfunction overflow(prepared: Prepared): Rejection {\n return new Rejection(\n 503,\n [requestError('Too many active subscriptions, retry later', GraphQLErrorCode.ServiceUnavailable)],\n prepared.entry.id,\n prepared.operation,\n )\n}\n\n/** The 503 of an engine subscription past `subscriptions.maxActive`, or while the application stops. */\nfunction unavailable(prepared: Prepared, closing: boolean): Rejection {\n if (!closing) return overflow(prepared)\n return new Rejection(\n 503,\n [requestError('The server is shutting down, retry later', GraphQLErrorCode.ServiceUnavailable)],\n prepared.entry.id,\n prepared.operation,\n )\n}\n\n/** Whether `rules` are graphql-js `specifiedRules` (the same list, or a copy of it). */\nfunction isSpecifiedRules(rules: readonly ValidationRule[]): boolean {\n if (rules === specifiedRules) return true\n if (rules.length !== specifiedRules.length) return false\n for (let index = 0; index < rules.length; index++) if (rules[index] !== specifiedRules[index]) return false\n return true\n}\n\n/** The request of engine arguments, for the hook of a rejection (its operation name). */\nfunction requestOf(args: ExecutionArgs): GraphQLRequest {\n return { query: '', operationName: args.operationName }\n}\n\nfunction resultOf(response: EngineResponse): ExecutionResult {\n return response.result\n}\n\n/** `error` with `extensions.code` set to `code` (as is without code), without its original error. */\nfunction coded(error: GraphQLError, code: string | undefined): GraphQLError {\n if (code === undefined) return error\n return new GraphQLErrorClass(error.message, {\n nodes: error.nodes,\n source: error.source,\n positions: error.positions,\n path: error.path,\n extensions: { ...error.extensions, code },\n })\n}\n\n/**\n * The formatted errors of an execution as `GraphQLError` instances (RFC 0009 §4.2, rule 5): the\n * formatted message and extensions, the locations and path of the error they come from, no\n * `originalError` (servers such as Apollo Server wrap anything that is not an `Error`).\n */\nfunction asGraphQLErrors(\n originals: readonly GraphQLError[],\n formatted: readonly GraphQLFormattedError[],\n): GraphQLError[] {\n const errors: GraphQLError[] = new Array(formatted.length)\n for (let index = 0; index < formatted.length; index++) {\n const original = originals[index] as GraphQLError\n const shown = formatted[index] as GraphQLFormattedError\n errors[index] = new GraphQLErrorClass(shown.message, {\n nodes: original.nodes,\n source: original.source,\n positions: original.positions,\n path: original.path,\n extensions: shown.extensions,\n })\n }\n return errors\n}\n\n/** A request error (formatted, without location) as a `GraphQLError`. */\nfunction fromFormatted(error: GraphQLFormattedError): GraphQLError {\n return new GraphQLErrorClass(error.message, { path: error.path, extensions: error.extensions })\n}\n\n/** A rejection answered to the engine: a result of `GraphQLError`s. */\nfunction asEngineResult(\n response: GraphQLResponse | Promise<GraphQLResponse>,\n): ExecutionResult | Promise<ExecutionResult> {\n const settle = (settled: GraphQLResponse): ExecutionResult => ({\n errors: (settled.result.errors ?? []).map(fromFormatted),\n })\n return isPromise(response) ? response.then(settle) : settle(response)\n}\n\nfunction noop(): void {}\n\nfunction badRequest(message: string): Rejection {\n return new Rejection(400, [requestError(message, GraphQLErrorCode.BadRequest)], undefined)\n}\n\nfunction variableError(error: GraphQLError): GraphQLFormattedError {\n return withCode(error, error.extensions['code'] === undefined ? GraphQLErrorCode.BadUserInput : undefined)\n}\n\n/** graphql-js rejects with `AbortedGraphQLExecutionError`: callers get the reason of their signal. */\nfunction abortReason(error: unknown, options: ExecuteOptions): unknown {\n const signal = options.abortSignal ?? options.signal\n if (error instanceof AbortedGraphQLExecutionError && signal?.aborted === true) return signal.reason\n return error\n}\n\nfunction operationEvent(ctx: OperationContext, id: string): GraphQLOperationEvent {\n return {\n operationType: ctx.operationType,\n operationName: ctx.operationName,\n documentId: id,\n transport: ctx.transport,\n driver: ctx.driver,\n requestId: ctx.requestId,\n context: ctx,\n startTime: performance.now(),\n }\n}\n\nfunction outcomeOf(response: Settled): NonNullable<GraphQLOperationEvent['outcome']> {\n if (response.status !== 200) return 'rejected'\n const result = response.result\n if (result.errors === undefined || result.errors.length === 0) return 'success'\n return result.data === null || result.data === undefined ? 'error' : 'partial'\n}\n\nfunction summaries(errors: NonNullable<Settled['result']['errors']>): NonNullable<GraphQLOperationEvent['errors']> {\n return errors.map(error => {\n const code = error.extensions?.['code']\n return {\n message: error.message,\n code: typeof code === 'string' ? code : undefined,\n ...(error.path === undefined ? {} : { path: error.path }),\n }\n })\n}\n\n/** The response key of the root field of a subscription (its single selection). */\nfunction responseKey(operation: OperationDefinitionNode): string | undefined {\n const selection = operation.selectionSet.selections[0]\n return selection?.kind === Kind.FIELD ? (selection.alias ?? selection.name).value : undefined\n}\n\nfunction isPromise<T>(value: T | Promise<T>): value is Promise<T> {\n return typeof (value as { then?: unknown } | null)?.then === 'function'\n}\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'\n )\n}\n\n/** A stream of one result (a query sent as a stream, a rejection for `plugin.subscribe()`). */\nexport function singleResult(result: FormattedExecutionResult): GraphQLResultStream {\n return new SingleResultStream(result)\n}\n\n/** The stream of a query or a mutation sent as a stream (SSE): its single result. */\nclass SingleResultStream implements GraphQLResultStream {\n #result: FormattedExecutionResult | undefined\n\n constructor(result: FormattedExecutionResult) {\n this.#result = result\n }\n\n next(): Promise<IteratorResult<FormattedExecutionResult>> {\n const result = this.#result\n if (result === undefined) return Promise.resolve(DONE)\n this.#result = undefined\n return Promise.resolve({ done: false, value: result })\n }\n\n return(): Promise<IteratorResult<FormattedExecutionResult>> {\n this.#result = undefined\n return Promise.resolve(DONE)\n }\n\n [Symbol.asyncIterator](): GraphQLResultStream {\n return this\n }\n}\n\ninterface SubscriptionStreamInit {\n readonly executor: GraphQLExecutor\n readonly source: AsyncIterator<unknown>\n readonly validated: ValidatedSubscriptionArgs\n readonly ctx: OperationContext\n readonly run: <R>(fn: () => R) => R\n readonly signal: AbortSignal | undefined\n readonly field: string | undefined\n /** Results as graphql-js results with `GraphQLError` instances (the engine), or formatted. */\n readonly engine: boolean\n readonly onEnd: (\n outcome: NonNullable<GraphQLOperationEvent['outcome']>,\n errors: NonNullable<Settled['result']['errors']> | undefined,\n ) => void\n}\n\n/**\n * The results of a subscription: each source event executed with `executeSubscriptionEvent`, a\n * fresh per-execution state (loaders) and the operation's `GraphQLContext`. `R` is\n * `FormattedExecutionResult` for the transports (`GraphQLResultStream`), `ExecutionResult` for the\n * engine (`EngineStream`).\n *\n * The source is started at once: its first `next()` is requested when the stream is created, so\n * that a resolver written as an async generator (`for await (const x of pubsub.subscribe(...))`)\n * has subscribed when `subscribe()` resolves, whatever the transport and however late its consumer\n * reads (an SSE body pulled on demand). Only that first event is read ahead; the next ones are read\n * when the consumer asks (backpressure).\n */\nclass SubscriptionStream<R> implements AsyncIterableIterator<R> {\n readonly #init: SubscriptionStreamInit\n readonly #onAbort: (() => void) | undefined\n /** The first `next()` of the source, requested at creation and consumed by the first read. */\n #first: Promise<IteratorResult<unknown>> | undefined\n /** `next()` calls of the source still pending. */\n #reading = 0\n #ended = false\n #partial = false\n\n constructor(init: SubscriptionStreamInit) {\n this.#init = init\n const signal = init.signal\n if (signal !== undefined) {\n this.#onAbort = () => {\n void this.return()\n }\n signal.addEventListener('abort', this.#onAbort, { once: true })\n }\n const first = init.run(() => this.#read())\n // handled by the first read; ignored when the stream ends before it\n first.catch(noop)\n this.#first = first\n // the client may have left while the operation was starting (async guards): end at once\n if (signal?.aborted === true) void this.return()\n }\n\n next(): Promise<IteratorResult<R, void>> {\n if (this.#ended) return Promise.resolve(DONE as IteratorResult<R, void>)\n return this.#init.run(() => this.#pull())\n }\n\n /** The next event of the source. */\n async #read(): Promise<IteratorResult<unknown>> {\n this.#reading++\n try {\n return await this.#init.source.next()\n } finally {\n this.#reading--\n }\n }\n\n /** A result of the subscription, formatted for its consumer. */\n #format(result: ExecutionResult): R {\n const init = this.#init\n return (\n init.engine ? init.executor.engineEvent(result, init.ctx) : init.executor.formatEvent(result, init.ctx)\n ) as R\n }\n\n async #pull(): Promise<IteratorResult<R, void>> {\n const init = this.#init\n let step: IteratorResult<unknown>\n try {\n const first = this.#first\n this.#first = undefined\n step = await (first ?? this.#read())\n } catch (error) {\n if (this.#ended) return DONE as IteratorResult<R, void>\n // the source failed (MemoryPubSub overflow...): a final error result, then the end\n const result = this.#format({\n errors: [\n new GraphQLErrorClass(errorMessage(error), {\n originalError: asError(error),\n path: init.field === undefined ? undefined : [init.field],\n }),\n ],\n })\n this.#end('error', (result as Settled['result']).errors)\n return { done: false, value: result }\n }\n if (step.done === true || this.#ended) {\n this.#end(this.#partial ? 'partial' : 'success', undefined)\n return DONE as IteratorResult<R, void>\n }\n init.ctx.resetLoaders()\n const executed = executeSubscriptionEvent({ ...init.validated, rootValue: step.value })\n const result = this.#format(isPromise(executed) ? await executed : executed)\n if ((result as Settled['result']).errors !== undefined) this.#partial = true\n return { done: false, value: result }\n }\n\n async return(): Promise<IteratorResult<R, void>> {\n if (this.#ended) return DONE as IteratorResult<R, void>\n this.#first = undefined\n // ends ctx.signal: a source following it (MemoryPubSub, a generator iterating it) ends at once\n this.#end(this.#partial ? 'partial' : 'success', undefined)\n const reading = this.#reading > 0\n try {\n const returned = Promise.resolve(this.#init.source.return?.())\n // an async generator runs return() only once its pending next() settles, which a source\n // ignoring ctx.signal may never do: do not wait for it then\n if (reading) returned.catch(noop)\n else await returned\n } catch {\n // the source is gone either way\n }\n return DONE as IteratorResult<R, void>\n }\n\n throw(): Promise<IteratorResult<R, void>> {\n return this.return()\n }\n\n [Symbol.asyncIterator](): this {\n return this\n }\n\n /** `await using`: ends the stream (an `AsyncGenerator` is disposable). */\n async [Symbol.asyncDispose](): Promise<void> {\n await this.return()\n }\n\n #end(\n outcome: NonNullable<GraphQLOperationEvent['outcome']>,\n errors: NonNullable<Settled['result']['errors']> | undefined,\n ): void {\n if (this.#ended) return\n this.#ended = true\n if (this.#onAbort !== undefined) this.#init.signal?.removeEventListener('abort', this.#onAbort)\n this.#init.onEnd(outcome, errors)\n }\n}\n\nfunction asError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * Content negotiation of the GraphQL endpoint (RFC 0005 §8.3): which of the media types the\n * endpoint produces a request accepts best. Import-free.\n *\n * `application/json` is the only type matched by wildcards (`*\\/*`, `application/*`): the\n * GraphQL-over-HTTP draft asks for `application/json` when the client accepts anything, and the\n * other types change the protocol (`application/graphql-response+json` statuses, an event stream,\n * the GraphiQL page), so they are chosen only when listed. Among types of equal quality,\n * `application/graphql-response+json` wins, then `application/json`, then HTML (a browser listing\n * `text/html` first gets GraphiQL). An event stream is chosen only when it is strictly preferred, or\n * the only acceptable type: a client listing JSON and `text/event-stream` alike (urql, for\n * incremental delivery) gets its queries and mutations as one JSON body, and its subscriptions as\n * a stream ({@link STREAMABLE}).\n */\n\n/** What a response is encoded as. */\nexport const Media: {\n readonly EventStream: 0\n readonly GraphQLJson: 1\n readonly Json: 2\n readonly Html: 3\n /** Nothing the endpoint produces is acceptable: 406. */\n readonly None: 4\n} = Object.freeze({ EventStream: 0, GraphQLJson: 1, Json: 2, Html: 3, None: 4 })\n\n/** One of the {@link Media} values. */\nexport type MediaKind = (typeof Media)[keyof typeof Media]\n\n/**\n * Added to a negotiated JSON type when an event stream is acceptable too, though not preferred: a\n * subscription, which has no JSON answer, is then streamed. `answer & MEDIA` is the {@link MediaKind}.\n */\nexport const STREAMABLE = 8\n\n/** The {@link MediaKind} bits of a {@link negotiate} answer. */\nexport const MEDIA = 7\n\n/** The media type names, by {@link Media} value (`None` excluded). */\nconst NAMES: readonly (readonly [type: string, subtype: string])[] = [\n ['text', 'event-stream'],\n ['application', 'graphql-response+json'],\n ['application', 'json'],\n ['text', 'html'],\n]\n\n/** A media range of an `accept` header. */\ninterface Range {\n readonly type: string\n readonly subtype: string\n readonly q: number\n}\n\n/** The media ranges of an `accept` header (lower-case, without parameters other than `q`). */\nfunction parseRanges(header: string): Range[] {\n const ranges: Range[] = []\n for (const item of header.split(',')) {\n const parts = item.split(';')\n const media = (parts[0] as string).trim().toLowerCase()\n const slash = media.indexOf('/')\n if (slash <= 0 || slash === media.length - 1) continue\n let q = 1\n for (let index = 1; index < parts.length; index++) {\n const parameter = (parts[index] as string).trim()\n if (parameter.length < 2 || (parameter.charCodeAt(0) | 0x20) !== 0x71 /* q */ || parameter[1] !== '=') continue\n const value = Number(parameter.slice(2))\n // an invalid weight leaves the range as it is (RFC 9110 §12.4.2 allows 0 to 1, 3 decimals)\n if (value >= 0 && value <= 1) q = value\n }\n ranges.push({ type: media.slice(0, slash), subtype: media.slice(slash + 1), q })\n }\n return ranges\n}\n\n/**\n * The quality of `type/subtype` in `ranges`: that of the most specific matching range (RFC 9110\n * §12.5.1), wildcards only when `wildcards` is set; 0 when nothing matches.\n */\nfunction quality(ranges: readonly Range[], type: string, subtype: string, wildcards: boolean): number {\n let best = -1\n let specificity = -1\n for (const range of ranges) {\n let level: number\n if (range.type === type && range.subtype === subtype) level = 2\n else if (!wildcards) continue\n else if (range.type === type && range.subtype === '*') level = 1\n else if (range.type === '*' && range.subtype === '*') level = 0\n else continue\n if (level > specificity || (level === specificity && range.q > best)) {\n specificity = level\n best = range.q\n }\n }\n return best < 0 ? 0 : best\n}\n\n/**\n * Chooses the media type of a response among `produced` (a bit mask of `1 << Media.X`), per\n * `accept` (`undefined`: no header, i.e. `application/json`): a {@link MediaKind}, plus\n * {@link STREAMABLE} when a JSON type wins and an event stream is acceptable too.\n */\nexport function negotiate(accept: string | undefined, produced: number): number {\n if (accept === undefined) return produced & (1 << Media.Json) ? Media.Json : Media.None\n const ranges = parseRanges(accept)\n if (ranges.length === 0) return produced & (1 << Media.Json) ? Media.Json : Media.None\n let chosen: number = Media.None\n let best = 0\n for (let media: number = Media.GraphQLJson; media < NAMES.length; media++) {\n if ((produced & (1 << media)) === 0) continue\n const [type, subtype] = NAMES[media] as readonly [string, string]\n const q = quality(ranges, type, subtype, media === Media.Json)\n if (q > best) {\n best = q\n chosen = media\n }\n }\n if (produced & (1 << Media.EventStream)) {\n const q = quality(ranges, 'text', 'event-stream', false)\n // strictly preferred, or the only acceptable type\n if (q > best) return Media.EventStream\n if (q > 0 && (chosen === Media.GraphQLJson || chosen === Media.Json)) chosen |= STREAMABLE\n }\n return chosen\n}\n\nconst CACHE_MAX = 64\n\n/**\n * {@link negotiate} for one route, memoised by header value: a server sees a handful of `accept`\n * values, so a request costs a map lookup. Bounded, since clients choose the values: cleared when\n * full.\n */\nexport class Negotiator {\n readonly #produced: number\n readonly #cache = new Map<string, number>()\n /** The answer without `accept` header. */\n readonly #absent: number\n\n /** `produced`: a bit mask of `1 << Media.X`. */\n constructor(produced: number) {\n this.#produced = produced\n this.#absent = negotiate(undefined, produced)\n }\n\n /** The {@link negotiate} answer: a {@link MediaKind}, possibly with {@link STREAMABLE}. */\n choose(accept: string | undefined): number {\n if (accept === undefined) return this.#absent\n let media = this.#cache.get(accept)\n if (media === undefined) {\n media = negotiate(accept, this.#produced)\n if (this.#cache.size === CACHE_MAX) this.#cache.clear()\n this.#cache.set(accept, media)\n }\n return media\n }\n}\n","/**\n * The GraphiQL page (RFC 0005 §8.3, §8.9): served on `GET path` with `accept: text/html` when the\n * `graphiql` option is on (default: `NODE_ENV === 'development'`). React and GraphiQL load from a\n * pinned CDN with Subresource Integrity; the inline script is fixed at boot and allowed by hash in\n * the page's own `content-security-policy`, which overrides the strict API default of RFC 0001 on\n * this response only.\n */\nimport { createHash } from 'node:crypto'\n\n/** jsDelivr. */\nexport const GRAPHIQL_CDN = 'https://cdn.jsdelivr.net'\n\n/** A pinned CDN asset. */\nexport interface GraphiQLAsset {\n readonly url: string\n /** Subresource Integrity of the pinned file. */\n readonly integrity: string\n readonly kind: 'script' | 'style'\n}\n\n/**\n * The assets of the page: GraphiQL 3 (the last major with a UMD build) on React 18. Bumped by hand,\n * with their SRI hashes (`sha384` of the files on the CDN).\n */\nexport const GRAPHIQL_ASSETS: readonly GraphiQLAsset[] = Object.freeze([\n {\n url: `${GRAPHIQL_CDN}/npm/graphiql@3.9.0/graphiql.min.css`,\n integrity: 'sha384-QMux00XgRtwRLSYIY3kw2rj1ovk5AuuliAchk+HSQbqdbGFnz9GYuqIlOqxhwCE2',\n kind: 'style',\n },\n {\n url: `${GRAPHIQL_CDN}/npm/react@18.3.1/umd/react.production.min.js`,\n integrity: 'sha384-DGyLxAyjq0f9SPpVevD6IgztCFlnMF6oW/XQGmfe+IsZ8TqEiDrcHkMLKI6fiB/Z',\n kind: 'script',\n },\n {\n url: `${GRAPHIQL_CDN}/npm/react-dom@18.3.1/umd/react-dom.production.min.js`,\n integrity: 'sha384-gTGxhz21lVGYNMcdJOyq01Edg0jhn/c22nsx0kyqP0TxaV5WVdsSH1fSDUf5YJj1',\n kind: 'script',\n },\n {\n url: `${GRAPHIQL_CDN}/npm/graphiql@3.9.0/graphiql.min.js`,\n integrity: 'sha384-8NGfVj4CVlqHajlZj+bPJT4thxPMHMJYn7DWK2CvtopLd02E7qsPHazniBYvVjOO',\n kind: 'script',\n },\n])\n\n/** The rendered page. */\nexport interface GraphiQLPage {\n readonly html: string\n readonly csp: string\n}\n\n/** `<`, `>` and `&` escaped: JSON safe inside a `<script>` element. */\nfunction scriptJson(value: unknown): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c').replace(/>/g, '\\\\u003e').replace(/&/g, '\\\\u0026')\n}\n\nfunction escapeHtml(text: string): string {\n return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;')\n}\n\n/** The GraphiQL page of the endpoint `endpoint` (an absolute path, prefix included) and its CSP. */\nexport function renderGraphiQL(endpoint: string): GraphiQLPage {\n const tags = GRAPHIQL_ASSETS.map(asset =>\n asset.kind === 'style'\n ? `<link rel=\"stylesheet\" href=\"${escapeHtml(asset.url)}\" integrity=\"${asset.integrity}\" crossorigin=\"anonymous\">`\n : `<script src=\"${escapeHtml(asset.url)}\" integrity=\"${asset.integrity}\" crossorigin=\"anonymous\"></script>`,\n )\n const inline = [\n `const fetcher = GraphiQL.createFetcher({ url: ${scriptJson(endpoint)} })`,\n `ReactDOM.createRoot(document.getElementById('graphiql')).render(React.createElement(GraphiQL, { fetcher }))`,\n ].join('\\n')\n const hash = `'sha256-${createHash('sha256').update(inline).digest('base64')}'`\n const html = [\n '<!doctype html>',\n '<html lang=\"en\">',\n '<head>',\n '<meta charset=\"utf-8\">',\n '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">',\n '<title>GraphiQL</title>',\n '<style>body { margin: 0; } #graphiql { height: 100dvh; }</style>',\n ...tags.filter(tag => tag.startsWith('<link')),\n '</head>',\n '<body>',\n '<div id=\"graphiql\">Loading GraphiQL…</div>',\n ...tags.filter(tag => tag.startsWith('<script')),\n `<script>${inline}</script>`,\n '</body>',\n '</html>',\n '',\n ].join('\\n')\n const csp = [\n \"default-src 'none'\",\n `script-src ${GRAPHIQL_CDN} ${hash}`,\n // GraphiQL and CodeMirror set inline styles\n `style-src 'unsafe-inline' ${GRAPHIQL_CDN}`,\n `font-src data: ${GRAPHIQL_CDN}`,\n \"img-src 'self' data:\",\n \"connect-src 'self'\",\n \"base-uri 'none'\",\n \"form-action 'none'\",\n \"frame-ancestors 'self'\",\n ].join('; ')\n return { html, csp }\n}\n","/**\n * GraphQL over SSE, distinct connections mode (RFC 0005 §5.6, §8.3, §8.11): the results of an\n * operation as `next` events, then a `complete` event. Everything else (headers, heartbeats,\n * backpressure, client abort, graceful close) is RFC 0006's `HttpResponse.sse()`.\n */\nimport type { SseEvent } from '@znight/http'\nimport type { GraphQLResultStream } from '../execution.ts'\n\n/** The last event of a stream that ended normally. */\nconst COMPLETE: SseEvent<string> = Object.freeze({ event: 'complete', data: '' })\nconst DONE: IteratorResult<SseEvent> = Object.freeze({ done: true, value: undefined })\n\n/**\n * The event source of an operation: one `next` event per result, then `complete` when the\n * operation ended by itself. A stream ended by `ctx.signal` (client gone, shutdown, `maxDuration`)\n * gets no `complete`: GraphQL-over-SSE clients then treat it as a lost connection and retry.\n */\nexport class ResultEvents implements AsyncIterableIterator<SseEvent> {\n readonly #results: GraphQLResultStream\n readonly #signal: AbortSignal\n #done = false\n\n constructor(results: GraphQLResultStream, signal: AbortSignal) {\n this.#results = results\n this.#signal = signal\n }\n\n async next(): Promise<IteratorResult<SseEvent>> {\n if (this.#done) return DONE\n const step = await this.#results.next()\n if (step.done !== true) return { done: false, value: { event: 'next', data: step.value } }\n this.#done = true\n return this.#signal.aborted ? DONE : { done: false, value: COMPLETE }\n }\n\n async return(): Promise<IteratorResult<SseEvent>> {\n this.#done = true\n await this.#results.return()\n return DONE\n }\n\n [Symbol.asyncIterator](): AsyncIterableIterator<SseEvent> {\n return this\n }\n}\n","/**\n * GraphQL over HTTP (RFC 0005 §8.3, GraphQL-over-HTTP specification draft), the handlers of the two\n * plugin routes of the endpoint (`GET` and `POST` on `path`).\n *\n * - `POST`: `application/json` bodies only (415 otherwise: no form or text body, so cross-site\n * requests are always preflighted), read by the handler so that every malformed request gets a\n * GraphQL-shaped error (malformed JSON, missing query, batching: 400; body limit: 413).\n * - `GET`: queries only (405 with `allow: POST` otherwise), when `http.get` is on; GraphiQL with\n * `accept: text/html` when enabled.\n * - The response is `application/graphql-response+json` when the client lists it (200 with data,\n * 400 for request errors), otherwise `application/json` (200 for every well-formed request); no\n * `accept` header is `application/json`; nothing acceptable is 406. `accept: text/event-stream`\n * selects GraphQL over SSE for any operation when it is preferred to the JSON types (or the only\n * one listed); listed at the same quality as a JSON type, only subscriptions are streamed.\n *\n * Hot path (a cached query whose resolvers are synchronous): a memoised negotiation (a map lookup),\n * the query string read without `URLSearchParams` or the body read and parsed once, one options\n * object and one deferred abort per request, the executor's synchronous result, and a single\n * `JSON.stringify` by the serialiser. Every answer stays on the fast lane of `@znight/http` (no\n * promise while the route is synchronous, headers from a template) unless the application adds\n * CORS, guards, `http:request` listeners or wrappers: a `GET` answered as `application/json` with\n * status 200 returns the plain result; the other answers are an `HttpResponse` with a plain JSON\n * body, at most a `content-type` header and an explicit status (a `POST` route answers 201 by\n * default), which the fast lane serves too.\n */\nimport type { HttpContext, SseOptions } from '@znight/http'\nimport type { FormattedExecutionResult } from 'graphql'\nimport type { ExecuteOptions, GraphQLExecutor, GraphQLRequest, GraphQLResponse } from '../execution.ts'\n\nimport { HttpResponse, isHttpException, parseMediaType } from '@znight/http'\n\nimport { GraphQLErrorCode } from '../errors.ts'\nimport { SUBSCRIBE } from '../execution.ts'\nimport { DeferredAbort } from './abort.ts'\nimport { MEDIA, Media, type MediaKind, Negotiator, STREAMABLE } from './accept.ts'\nimport { renderGraphiQL } from './graphiql.ts'\nimport { ResultEvents } from './sse.ts'\n\n/** What the transport is built from (resolved plugin options). */\nexport interface HttpTransportOptions {\n /** The executor of the plugin, built at bootstrap (after the routes may have been collected). */\n readonly executor: () => GraphQLExecutor\n /** Absolute path of the endpoint, prefix included (GraphiQL's fetcher). */\n readonly endpoint: string\n /** Queries over `GET`. */\n readonly get: boolean\n readonly graphiql: boolean\n /** `HttpResponse.sse()` options of GraphQL over SSE; `false`: no event streams. */\n readonly sse: SseOptions | false\n}\n\nconst JSON_TYPE = 'application/json; charset=utf-8'\nconst GRAPHQL_JSON_TYPE = 'application/graphql-response+json; charset=utf-8'\n\n/** Response options of `application/graphql-response+json` replies, by status. */\nconst GRAPHQL_JSON_200 = Object.freeze({ status: 200, headers: Object.freeze({ 'content-type': GRAPHQL_JSON_TYPE }) })\nconst GRAPHQL_JSON_400 = Object.freeze({ status: 400, headers: Object.freeze({ 'content-type': GRAPHQL_JSON_TYPE }) })\n/** `application/json` is what the serialiser gives an object body: only the status is set. */\nconst JSON_200 = Object.freeze({ status: 200 })\n\nconst UTF8 = new TextDecoder('utf-8', { fatal: true })\n\n/** A request error before execution: `{ errors: [{ message, extensions: { code } }] }`. */\nfunction errorBody(message: string, code: string = GraphQLErrorCode.BadRequest): FormattedExecutionResult {\n return { errors: [{ message, extensions: { code } }] }\n}\n\n/** A reply of `status` carrying a GraphQL error body in the negotiated JSON type (`application/json` before negotiation). */\nfunction errorReply(\n media: MediaKind,\n status: number,\n body: FormattedExecutionResult,\n headers?: Readonly<Record<string, string>>,\n): HttpResponse<FormattedExecutionResult> {\n const type = media === Media.GraphQLJson ? GRAPHQL_JSON_TYPE : JSON_TYPE\n return new HttpResponse(body, { status, headers: { ...headers, 'content-type': type } })\n}\n\nconst NOT_ACCEPTABLE = errorReply(\n Media.Json,\n 406,\n errorBody(\n 'None of the accepted media types can be produced: accept application/graphql-response+json, application/json or text/event-stream',\n ),\n)\nconst GET_NOT_ALLOWED = errorReply(\n Media.Json,\n 405,\n errorBody('GraphQL operations are sent with POST on this endpoint'),\n Object.freeze({ allow: 'POST' }),\n)\n\n/**\n * Whether a `POST` body is JSON (`application/json`, UTF-8): the only body the endpoint takes (and\n * the Yoga driver), so that a cross-site request, which cannot send it without a CORS preflight,\n * never executes an operation. `content-type` values seen most often are compared before parsing.\n */\nexport function isJsonRequest(contentType: string | undefined): boolean {\n if (contentType === 'application/json' || contentType === 'application/json; charset=utf-8') return true\n // parsed once per distinct value (memoised by @znight/http)\n const media = parseMediaType(contentType)\n if (media === undefined || media.type !== 'application/json') return false\n return media.charset === undefined || media.charset === 'utf-8' || media.charset === 'utf8'\n}\n\n/** The 415 of a `POST` body that is not JSON, in the negotiated JSON type. */\nexport function notJson(media: MediaKind): HttpResponse<FormattedExecutionResult> {\n return errorReply(media, 415, errorBody('Send GraphQL requests as application/json (content-type: application/json)'))\n}\n\n/** Why the parameters of a request are invalid, `undefined` when they are valid. */\nfunction invalidParams(params: Readonly<Record<string, unknown>>): string | undefined {\n const query = params['query']\n if (typeof query !== 'string') {\n return query === undefined || query === null\n ? 'Missing query: send { query, variables?, operationName?, extensions? }'\n : 'The query must be a string'\n }\n const operationName = params['operationName']\n if (operationName !== undefined && operationName !== null && typeof operationName !== 'string') {\n return 'operationName must be a string'\n }\n if (!isMapOrNull(params['variables'])) return 'variables must be an object'\n if (!isMapOrNull(params['extensions'])) return 'extensions must be an object'\n return undefined\n}\n\n/** The parameters of a GraphQL `GET` request. */\nconst GET_PARAMS = ['query', 'operationName', 'variables', 'extensions'] as const\n\ntype GetParams = Partial<Record<(typeof GET_PARAMS)[number], string | string[]>>\n\n/** A query string component decoded like `URLSearchParams` (`+` is a space); `undefined` when malformed. */\nfunction decodeComponent(text: string): string | undefined {\n if (text.indexOf('%') === -1 && text.indexOf('+') === -1) return text\n try {\n return decodeURIComponent(text.replaceAll('+', ' '))\n } catch {\n return undefined\n }\n}\n\n/**\n * The GraphQL parameters of a request target, read directly: `ctx.query` builds a record of every\n * parameter through `URLSearchParams` (about 0.35 µs of a `GET` on Node.js, 0.15 µs on Bun, see\n * `test/bench/http.bench.ts`). A repeated parameter\n * becomes an array, like `ctx.query`. `undefined` when a component is malformed percent-encoding:\n * the caller falls back to `ctx.query` (which keeps such sequences as they are).\n */\nfunction readGetParams(url: string): GetParams | undefined {\n const params: GetParams = {}\n const mark = url.indexOf('?')\n if (mark === -1) return params\n const length = url.length\n let start = mark + 1\n while (start < length) {\n let end = url.indexOf('&', start)\n if (end === -1) end = length\n if (end > start) {\n let equals = url.indexOf('=', start)\n if (equals === -1 || equals > end) equals = end\n const name = decodeComponent(url.slice(start, equals))\n if (name === undefined) return undefined\n if (name === 'query' || name === 'operationName' || name === 'variables' || name === 'extensions') {\n const value = equals === end ? '' : decodeComponent(url.slice(equals + 1, end))\n if (value === undefined) return undefined\n const existing = params[name]\n if (existing === undefined) params[name] = value\n else params[name] = typeof existing === 'string' ? [existing, value] : [...existing, value]\n }\n }\n start = end + 1\n }\n return params\n}\n\nfunction isMapOrNull(value: unknown): boolean {\n return value === undefined || value === null || (typeof value === 'object' && !Array.isArray(value))\n}\n\nfunction isPromise<T>(value: T | Promise<T>): value is Promise<T> {\n return typeof (value as { then?: unknown } | null)?.then === 'function'\n}\n\n/** The handlers of the GraphQL endpoint. */\nexport class HttpTransport {\n readonly #resolveExecutor: () => GraphQLExecutor\n #executor: GraphQLExecutor | undefined\n readonly #getQueries: boolean\n readonly #sse: SseOptions | false\n readonly #post: Negotiator\n readonly #get: Negotiator\n /** The GraphiQL page, `undefined` when disabled. */\n readonly #graphiql: HttpResponse<Uint8Array> | undefined\n\n constructor(options: HttpTransportOptions) {\n this.#resolveExecutor = options.executor\n this.#getQueries = options.get\n this.#sse = options.sse\n const json = (1 << Media.GraphQLJson) | (1 << Media.Json) | (options.sse === false ? 0 : 1 << Media.EventStream)\n this.#post = new Negotiator(json)\n this.#get = new Negotiator(options.graphiql ? json | (1 << Media.Html) : json)\n if (options.graphiql) {\n const page = renderGraphiQL(options.endpoint)\n // encoded once: the same immutable response serves every request\n this.#graphiql = new HttpResponse(new TextEncoder().encode(page.html), {\n status: 200,\n headers: {\n 'content-type': 'text/html; charset=utf-8',\n 'content-security-policy': page.csp,\n 'cache-control': 'no-store',\n },\n })\n }\n }\n\n /** `POST path`. */\n readonly post = (ctx: HttpContext): unknown => {\n const headers = ctx.headers\n const negotiated = this.#post.choose(headers['accept'])\n const media = (negotiated & MEDIA) as MediaKind\n if (media === Media.None) return NOT_ACCEPTABLE\n if (!isJsonRequest(headers['content-type'])) return notJson(media)\n const encoding = headers['content-encoding']\n if (encoding !== undefined && encoding.trim().toLowerCase() !== 'identity' && encoding.trim() !== '') {\n return errorReply(media, 415, errorBody(`Unsupported content encoding \"${encoding}\"`))\n }\n return ctx.rawBody().then(\n bytes => this.#posted(ctx, bytes, media, negotiated >= STREAMABLE),\n (error: unknown) => transportError(error, media),\n )\n }\n\n /** `GET path`. */\n readonly get = (ctx: HttpContext): unknown => {\n const media = (this.#get.choose(ctx.headers['accept']) & MEDIA) as MediaKind\n if (media === Media.Html) return this.#graphiql\n if (media === Media.None) return NOT_ACCEPTABLE\n if (!this.#getQueries) return GET_NOT_ALLOWED\n const params = readGetParams(ctx.url) ?? ctx.query\n const request: Record<string, unknown> = {}\n for (const name of GET_PARAMS) {\n const value = params[name]\n if (value === undefined) continue\n if (typeof value !== 'string') return errorReply(media, 400, errorBody(`Repeated ${name} parameter`))\n if (name === 'variables' || name === 'extensions') {\n try {\n request[name] = JSON.parse(value)\n } catch {\n return errorReply(media, 400, errorBody(`The ${name} parameter must be JSON`))\n }\n } else {\n request[name] = value\n }\n }\n const invalid = invalidParams(request)\n if (invalid !== undefined) return errorReply(media, 400, errorBody(invalid))\n if (media === Media.EventStream) return this.#stream(ctx, request as unknown as GraphQLRequest, true)\n // GET carries queries only: no subscription to stream\n return this.#execute(ctx, request as unknown as GraphQLRequest, media, true, false)\n }\n\n /** A `POST` body read: parsed, checked, executed or streamed. */\n #posted(ctx: HttpContext, bytes: Uint8Array, media: MediaKind, streamable: boolean): unknown {\n if (bytes.byteLength === 0) {\n return errorReply(media, 400, errorBody('Missing request body: send { query, variables?, operationName? }'))\n }\n let body: unknown\n try {\n body = JSON.parse(UTF8.decode(bytes))\n } catch {\n return errorReply(media, 400, errorBody('Malformed JSON body'))\n }\n if (body === null || typeof body !== 'object') {\n return errorReply(media, 400, errorBody('The body must be a JSON object: { query, variables?, operationName? }'))\n }\n if (Array.isArray(body)) {\n return errorReply(media, 400, errorBody('Operation batching is not supported: send one operation per request'))\n }\n const invalid = invalidParams(body as Record<string, unknown>)\n if (invalid !== undefined) return errorReply(media, 400, errorBody(invalid))\n if (media === Media.EventStream) return this.#stream(ctx, body as GraphQLRequest, false)\n return this.#execute(ctx, body as GraphQLRequest, media, false, streamable)\n }\n\n /**\n * Executes a query or a mutation; synchronous while the execution is. A subscription is streamed\n * when the client accepts an event stream (`streamable`), a 400 otherwise.\n */\n #execute(ctx: HttpContext, request: GraphQLRequest, media: MediaKind, get: boolean, streamable: boolean): unknown {\n const executor = this.#executor ?? this.#bind()\n const abort = new DeferredAbort()\n const options: ExecuteOptions = {\n transport: 'http',\n http: ctx,\n abortSignal: abort.asSignal(),\n queriesOnly: get,\n streamSubscriptions: streamable,\n }\n const response = executor.execute(request, options)\n if (response === SUBSCRIBE) return this.#stream(ctx, request, get)\n if (!isPromise(response)) return reply(response, media, get)\n // asynchronous resolvers: a client leaving now aborts the execution\n abort.follow(() => ctx.signal)\n return response.then(\n settled => reply(settled, media, get),\n (error: unknown) => {\n if (!abort.aborted || error !== abort.reason) throw error\n // nobody reads it: the client is gone (or the server stops)\n return errorReply(media, 503, errorBody('The request was aborted', GraphQLErrorCode.ServiceUnavailable))\n },\n )\n }\n\n /** GraphQL over SSE: any operation, its results as `next` events. */\n #stream(ctx: HttpContext, request: GraphQLRequest, get: boolean): Promise<unknown> {\n const executor = this.#executor ?? this.#bind()\n const signal = ctx.signal\n const options: ExecuteOptions = { transport: 'sse', http: ctx, signal, queriesOnly: get }\n return executor.subscribe(request, options).then(\n outcome => {\n if ('status' in outcome) {\n return errorReply(Media.Json, outcome.status, outcome.result, outcome.headers)\n }\n // the SSE options were checked at boot (see sseOptions)\n return HttpResponse.sse(new ResultEvents(outcome, signal), this.#sse as SseOptions)\n },\n (error: unknown) => {\n if (!signal.aborted || error !== signal.reason) throw error\n return errorReply(Media.Json, 503, errorBody('The request was aborted', GraphQLErrorCode.ServiceUnavailable))\n },\n )\n }\n\n #bind(): GraphQLExecutor {\n this.#executor = this.#resolveExecutor()\n return this.#executor\n }\n}\n\n/**\n * The HTTP reply of an executor response. `application/json` answers 200 to every well-formed\n * request (request errors included); `application/graphql-response+json` keeps the status.\n */\nfunction reply(response: GraphQLResponse, media: MediaKind, get: boolean): unknown {\n const status = response.status\n const result = response.result\n if (media === Media.Json) {\n if (status === 200 || status === 400) {\n // a plain object on a GET route: 200 application/json (a POST route would answer 201)\n return get ? result : new HttpResponse(result, JSON_200)\n }\n return errorReply(media, status, result, response.headers)\n }\n if (response.headers === undefined) {\n if (status === 200) return new HttpResponse(result, GRAPHQL_JSON_200)\n if (status === 400) return new HttpResponse(result, GRAPHQL_JSON_400)\n }\n return errorReply(media, status, result, response.headers)\n}\n\n/** A failure reading the body (413 past the body limit, 400 for an aborted body) with a GraphQL error body. */\nfunction transportError(error: unknown, media: MediaKind): HttpResponse<FormattedExecutionResult> {\n if (!isHttpException(error)) throw error\n return errorReply(media, error.status, errorBody(error.message))\n}\n\n/** Checks the SSE options once (`HttpResponse.sse()` validates them): `undefined` when they are valid. */\nexport function checkSseOptions(options: SseOptions): string | undefined {\n try {\n HttpResponse.sse([], options)\n return undefined\n } catch (error) {\n return error instanceof Error ? error.message : String(error)\n }\n}\n"],"mappings":";;;;;;;;;;;;;AASA,MAAa,mBA2BT,OAAO,OAAO;CAChB,aAAa;CACb,kBAAkB;CAClB,cAAc;CACd,iBAAiB;CACjB,iBAAiB;CACjB,WAAW;CACX,UAAU;CACV,UAAU;CACV,iBAAiB;CACjB,YAAY;CACZ,sBAAsB;CACtB,oBAAoB;CACpB,qBAAqB;AACvB,CAAC;;;;;;;;;AA0BD,IAAa,mBAAb,cAAsC,MAAM;;CAE1C;;CAEA;CAEA,YAAY,SAAiB,SAAkC;EAC7D,MAAM,SAAS,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;EACjF,KAAK,OAAO;EACZ,KAAK,OAAO,QAAQ;EACpB,KAAK,aAAa,QAAQ;CAC5B;AACF;;ACpCA,MAAM,eAAkD,OAAO,OAAO,CAAC,CAAC;;;;;;AAOxE,IAAa,mBAAb,MAAwD;CACtD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YACE,SACA,UACA,WACA,SACA,SACA,OACA;EACA,KAAK,WAAW;EAChB,KAAK,WAAW;EAChB,KAAK,aAAa;EAClB,KAAK,WAAW;EAChB,KA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AAM,UAA2B,OAAkB,KAAuB;CACjF,MAAM,SAAS,SAAS;CACxB,MAAM,SAAS,SAAS;CACxB,IAAI,UAAU,MAAM,MAAM;EACxB,IAAI,WAAW,OAAO,WAAW,KAE/B,OAAO,MAAM,SAAS,IAAI,aAAa,QAAQ,QAAQ;EAEzD,OAAO,WAAW,OAAO,QAAQ,QAAQ,SAAS,OAAO;CAC3D;CACA,IAAI,SAAS,YAAY,KAAA,GAAW;EAClC,IAAI,WAAW,KAAK,OAAO,IAAI,aAAa,QAAQ,gBAAgB;EACpE,IAAI,WAAW,KAAK,OAAO,IAAI,aAAa,QAAQ,gBAAgB;CACtE;CACA,OAAO,WAAW,OAAO,QAAQ,QAAQ,SAAS,OAAO;AAC3D;;AAGA,SAAS,eAAe,OAAgB,OAA0D;CAChG,IAAI,CAAC,gBAAgB,KAAK,GAAG,MAAM;CACnC,OAAO,WAAW,OAAO,MAAM,QAAQ,UAAU,MAAM,OAAO,CAAC;AACjE;;AAGA,SAAgB,gBAAgB,SAAyC;CACvE,IAAI;EACF,aAAa,IAAI,CAAC,GAAG,OAAO;EAC5B;CACF,SAAS,OAAO;EACd,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAC9D;AACF"}
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
- import { C as GraphQLExceptionOptions, S as GraphQLException, _ as LoaderValue, a as GraphQLContext, b as GraphQLErrorCode, c as GraphQLGuard, d as GraphQLResultMapper, f as GraphQLResultMapperClass, g as LoaderOptions, h as LoaderKey, i as GraphQLArgs, l as GraphQLGuardClass, m as GraphQLTransport, n as BatchLoadClass, o as GraphQLErrorMapper, p as GraphQLResultTypes, r as BatchLoader, s as GraphQLErrorMapperClass, t as BatchLoad, u as GraphQLOperationKind, v as ResolverContext, x as GraphQLErrorCodeValue, y as ScalarDefinition } from "./types-DQ713UgI.mjs";
1
+ import { A as ScalarDefinition, C as GraphQLResultMapperClass, D as LoaderOptions, E as LoaderKey, M as GraphQLErrorCodeValue, N as GraphQLException, O as LoaderValue, P as GraphQLExceptionOptions, S as GraphQLResultMapper, T as GraphQLTransport, _ as GraphQLErrorMapper, a as EngineExecuteOptions, b as GraphQLGuardClass, c as GraphQLRequest, d as orderByKeys, f as BatchLoad, g as GraphQLContext, h as GraphQLArgs, i as GraphQLDriverRoutesContext, j as GraphQLErrorCode, k as ResolverContext, l as GraphQLResultStream, m as BatchLoader, n as GraphQLDriverContext, o as GraphQLEngine, p as BatchLoadClass, r as GraphQLDriverRoute, s as GraphQLEngineSettings, t as GraphQLDriver, u as OrderByKeysOptions, v as GraphQLErrorMapperClass, w as GraphQLResultTypes, x as GraphQLOperationKind, y as GraphQLGuard } from "./driver-Cnze8Oyr.mjs";
2
2
  import { ClassMarker, MethodMarker, ParameterMarker, Plugin, PluginContext, PluginOptions, PluginRootsContext, ProviderKey, Scope, Token, TypedToken, ZnightError } from "@znight/core";
3
- import { ByteSize, GuardRef, HttpContext, HttpRouteGroupDefinition, InferSchemaOutput, PluginHttpRoutes, PluginHttpRoutesContext, PluginRoute, RouteMetaEntry, StandardSchemaV1, StandardSchemaV1 as StandardSchemaV1$1 } from "@znight/http";
4
- import { DocumentNode, FormattedExecutionResult, GraphQLError, GraphQLFormattedError, GraphQLResolveInfo, GraphQLScalarType, GraphQLSchema } from "graphql";
3
+ import { ByteSize, GuardRef, HttpRouteGroupDefinition, InferSchemaOutput, PluginHttpRoutes, PluginHttpRoutesContext, PluginRoute, RouteMetaEntry, StandardSchemaV1, StandardSchemaV1 as StandardSchemaV1$1 } from "@znight/http";
4
+ import { FormattedExecutionResult, GraphQLResolveInfo, GraphQLScalarType, GraphQLSchema } from "graphql";
5
5
  /** GraphQL `ID`: a string on the wire and in TypeScript. Recognised by the compiler through the alias. */
6
6
  type ID = string;
7
7
  /** GraphQL `Int` (32-bit signed integer). A `number` in TypeScript; plain `number` maps to `Float`. */
@@ -134,43 +134,6 @@ export declare function UseGuard(..._guards: [GraphQLGuardClass, ...GraphQLGuard
134
134
  */
135
135
  export declare function scalar<T>(name: string, definition: ScalarDefinition<T>): ScalarDefinition<T>;
136
136
  export declare function scalar<T>(name: string, definition: GraphQLScalarType): GraphQLScalarType<T>;
137
- /** Options of {@link orderByKeys}. */
138
- interface OrderByKeysOptions {
139
- /**
140
- * What a key without value gets: `'error'` (default) a `NOT_FOUND` `GraphQLException` failing that
141
- * key only, `'null'` the value `null`.
142
- */
143
- readonly missing?: "error" | "null";
144
- }
145
- /**
146
- * Reorders `values` (rows in any order, some keys possibly missing) to match `keys`, what a
147
- * `BatchLoad.load()` must return. Keys are compared with `Map` semantics (`===`, `NaN` equal).
148
- *
149
- * ```ts
150
- * async load(ids: readonly ID[]): Promise<readonly (Author | Error)[]> {
151
- * return orderByKeys(ids, await this.authors.findMany(ids), author => author.id)
152
- * }
153
- * ```
154
- */
155
- export declare function orderByKeys<K, V>(keys: readonly K[], values: Iterable<V>, keyOf: (value: V) => K, options?: OrderByKeysOptions & {
156
- readonly missing?: "error";
157
- }): (V | Error)[];
158
- export declare function orderByKeys<K, V>(keys: readonly K[], values: Iterable<V>, keyOf: (value: V) => K, options: OrderByKeysOptions & {
159
- readonly missing: "null";
160
- }): (V | null)[];
161
- /** A GraphQL request: the body of a GraphQL-over-HTTP request, or the argument of `plugin.execute()`. */
162
- interface GraphQLRequest {
163
- readonly query: string;
164
- readonly operationName?: string | null | undefined;
165
- readonly variables?: Readonly<Record<string, unknown>> | null | undefined;
166
- /** Request extensions (ignored by the executor; available to transports). */
167
- readonly extensions?: Readonly<Record<string, unknown>> | null | undefined;
168
- }
169
- /** The results of a subscription (one per event), or the single result of a query sent as a stream. */
170
- interface GraphQLResultStream extends AsyncIterableIterator<FormattedExecutionResult> {
171
- /** Ends the stream: the source event stream is returned (unsubscribed). */
172
- return(): Promise<IteratorResult<FormattedExecutionResult>>;
173
- }
174
137
  /**
175
138
  * The `PubSub` contract (RFC 0005 §5.6, §8.7): topics and payloads of subscriptions. `PubSub` is
176
139
  * an injectable external of `GraphQLPlugin` (`@znight/graphql#PubSub`, singleton), in memory by
@@ -249,9 +212,12 @@ interface GraphQLSubscriptionOptions {
249
212
  readonly maxActive?: number;
250
213
  /** Events buffered per subscriber by the default `MemoryPubSub`. Default 100. */
251
214
  readonly bufferSize?: number;
252
- /** SSE heartbeat (ms), `false` for none. Default: the `HttpPlugin` `sse` option. */
215
+ /**
216
+ * SSE heartbeat (ms), `false` for none. Default: the `HttpPlugin` `sse` option. Built-in transport
217
+ * only: with a `driver`, its own keep-alive options apply (ZNIGHT066).
218
+ */
253
219
  readonly heartbeat?: number | false;
254
- /** SSE maximum duration (ms). Default: none. */
220
+ /** SSE maximum duration (ms). Default: none. Built-in transport only (ZNIGHT066 with a `driver`). */
255
221
  readonly maxDuration?: number;
256
222
  }
257
223
  /** Options of `GraphQLPlugin.configure()`. */
@@ -273,12 +239,15 @@ interface GraphQLPluginOptions {
273
239
  readonly exposeErrors?: boolean;
274
240
  /** Introspection; off, suggestions are hidden too. Default `NODE_ENV !== 'production'`. */
275
241
  readonly introspection?: boolean;
276
- /** GraphiQL on `GET path` with `accept: text/html`. Default `NODE_ENV === 'development'`. */
242
+ /**
243
+ * GraphiQL on `GET path` with `accept: text/html`; with a `driver`, the driver's IDE. Default
244
+ * `NODE_ENV === 'development'`.
245
+ */
277
246
  readonly graphiql?: boolean;
278
247
  readonly limits?: GraphQLLimits;
279
248
  /** Distinct documents kept parsed and validated (LRU); 0 disables the cache. Default 1 000. */
280
249
  readonly documentCache?: number;
281
- /** `false` disables subscriptions over SSE. */
250
+ /** `false` disables subscriptions over SSE (with a `driver`, subscriptions altogether). */
282
251
  readonly subscriptions?: GraphQLSubscriptionOptions | false;
283
252
  /** The `PubSub` provided to the container. Default: a `MemoryPubSub` (closed with the application). */
284
253
  readonly pubsub?: AnyPubSub;
@@ -287,6 +256,11 @@ interface GraphQLPluginOptions {
287
256
  * `'error'` (default) fails the boot, `'warn'` logs.
288
257
  */
289
258
  readonly enforcement?: "error" | "warn";
259
+ /**
260
+ * The GraphQL server serving the schema (RFC 0009): a driver of a subpath (`yogaDriver()`) or a
261
+ * third party's. Default: the built-in GraphQL-over-HTTP and SSE transport, the fastest.
262
+ */
263
+ readonly driver?: GraphQLDriver;
290
264
  }
291
265
  /** Options of {@link MemoryPubSub}. */
292
266
  interface MemoryPubSubOptions {
@@ -522,16 +496,30 @@ export declare class GraphQLPlugin implements Plugin, PluginHttpRoutes {
522
496
  initRoots(context?: PluginRootsContext): readonly ProviderKey[];
523
497
  register(ctx: PluginContext): void;
524
498
  /**
525
- * The `PluginHttpRoutes` contract of `@znight/http`: the GraphQL endpoint (`GET` and `POST` on
526
- * `path`). `[]` with `http: false`.
499
+ * The `PluginHttpRoutes` contract of `@znight/http`: the routes of the driver, with the `http`
500
+ * option's meta and guards, and its body limit on the routes that are not `GET`. For the built-in
501
+ * transport, the GraphQL endpoint (`GET` and `POST` on `path`). `[]` with `http: false`.
527
502
  */
528
503
  httpRoutes(context: PluginHttpRoutesContext): readonly PluginRoute[];
529
- onBootstrap(ctx: PluginContext): void;
504
+ onBootstrap(ctx: PluginContext): void | Promise<void>;
530
505
  onStart(ctx: PluginContext): void;
506
+ /**
507
+ * The `PluginHttpRoutes` contract: `HttpPlugin` starts draining, whatever the plugin order. The
508
+ * subscriptions of the engine end (a route-mounted driver serves them as streamed responses
509
+ * `HttpPlugin` does not close), and new ones are refused (503); queries and mutations in flight
510
+ * are served. Built-in SSE streams are closed by `HttpPlugin` itself.
511
+ */
512
+ onHttpDrain(): Promise<void> | undefined;
531
513
  onStop(): Promise<void>;
532
- onDispose(): void;
514
+ onDispose(): void | Promise<void>;
533
515
  /** The schema (after bootstrap). */
534
516
  get schema(): GraphQLSchema;
517
+ /**
518
+ * The GraphQL engine (after bootstrap, RFC 0009): graphql-js-shaped `parse`, `validate`, `execute`
519
+ * and `subscribe` running this plugin's schema with its guards, loaders, request scope, error
520
+ * formatting and hook. What drivers receive in `start()`; any GraphQL server can call it.
521
+ */
522
+ get engine(): GraphQLEngine;
535
523
  /** The SDL of the schema (graphql-js `printSchema`). */
536
524
  printSchema(): string;
537
525
  /** The `PubSub` of the application: the `pubsub` option, or the plugin's `MemoryPubSub`. */
@@ -579,5 +567,5 @@ export declare const GraphQLTokens: {
579
567
  * @throws TypeError when `schema` is not a Standard Schema v1 (a programming error, masked).
580
568
  */
581
569
  export declare function validateArgs<S extends StandardSchemaV1$1>(schema: S, value: unknown, label: string): InferSchemaOutput<S> | Promise<InferSchemaOutput<S>>;
582
- export { type AnyPubSub, type BatchLoad, type BatchLoadClass, type BatchLoader, type DirectExecuteOptions, type Float, type GraphQLArgs, type GraphQLArgumentDefinition, type GraphQLBuiltinScalarDefinition, type GraphQLContext, type GraphQLCustomScalarDefinition, type GraphQLDiscriminator, type GraphQLEnumTypeDefinition, type GraphQLEnumValueDefinition, GraphQLErrorCode, type GraphQLErrorCodeValue, type GraphQLErrorMapper, type GraphQLErrorMapperClass, type GraphQLErrorMapperRef, GraphQLException, type GraphQLExceptionOptions, type GraphQLFieldDefinition, type GraphQLGuard, type GraphQLGuardClass, type GraphQLGuardRef, type GraphQLHttpOptions, type GraphQLInputFieldDefinition, type GraphQLInputTypeDefinition, type GraphQLInterfaceTypeDefinition, type GraphQLLimits, type GraphQLMetadata, type GraphQLObjectTypeDefinition, type GraphQLOperationKind, type GraphQLPluginOptions, type GraphQLRequest, type GraphQLResolverBinding, type GraphQLResolverOperation, type GraphQLResultMapper, type GraphQLResultMapperClass, type GraphQLResultMapperRef, type GraphQLResultStream, type GraphQLResultTypes, type GraphQLRootTypes, type GraphQLSubscriptionOptions, type GraphQLTransport, type GraphQLTypeDefinition, type GraphQLUnionTypeDefinition, type ID, type Int, type JSONValue, type LoaderKey, type LoaderOptions, type LoaderValue, type MaybePromise, type MemoryPubSubOptions, type OrderByKeysOptions, type ResolverContext, type ResolverOptions, type ScalarDefinition, type StandardSchemaV1, type SubscribeOptions };
570
+ export { type AnyPubSub, type BatchLoad, type BatchLoadClass, type BatchLoader, type DirectExecuteOptions, type EngineExecuteOptions, type Float, type GraphQLArgs, type GraphQLArgumentDefinition, type GraphQLBuiltinScalarDefinition, type GraphQLContext, type GraphQLCustomScalarDefinition, type GraphQLDiscriminator, type GraphQLDriver, type GraphQLDriverContext, type GraphQLDriverRoute, type GraphQLDriverRoutesContext, type GraphQLEngine, type GraphQLEngineSettings, type GraphQLEnumTypeDefinition, type GraphQLEnumValueDefinition, GraphQLErrorCode, type GraphQLErrorCodeValue, type GraphQLErrorMapper, type GraphQLErrorMapperClass, type GraphQLErrorMapperRef, GraphQLException, type GraphQLExceptionOptions, type GraphQLFieldDefinition, type GraphQLGuard, type GraphQLGuardClass, type GraphQLGuardRef, type GraphQLHttpOptions, type GraphQLInputFieldDefinition, type GraphQLInputTypeDefinition, type GraphQLInterfaceTypeDefinition, type GraphQLLimits, type GraphQLMetadata, type GraphQLObjectTypeDefinition, type GraphQLOperationKind, type GraphQLPluginOptions, type GraphQLRequest, type GraphQLResolverBinding, type GraphQLResolverOperation, type GraphQLResultMapper, type GraphQLResultMapperClass, type GraphQLResultMapperRef, type GraphQLResultStream, type GraphQLResultTypes, type GraphQLRootTypes, type GraphQLSubscriptionOptions, type GraphQLTransport, type GraphQLTypeDefinition, type GraphQLUnionTypeDefinition, type ID, type Int, type JSONValue, type LoaderKey, type LoaderOptions, type LoaderValue, type MaybePromise, type MemoryPubSubOptions, type OrderByKeysOptions, type ResolverContext, type ResolverOptions, type ScalarDefinition, type StandardSchemaV1, type SubscribeOptions, orderByKeys };
583
571
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { a as MemoryPubSub, c as GraphQLErrorCode, i as GraphQLTokens, l as GraphQLException, o as PubSub, s as orderByKeys, t as GraphQLPlugin } from "./plugin-CR_wVfRU.mjs";
1
+ import { f as GraphQLErrorCode, l as GraphQLTokens, p as GraphQLException } from "./http-BWcayUtH.mjs";
2
+ import { a as PubSub, i as MemoryPubSub, o as orderByKeys, t as GraphQLPlugin } from "./plugin-q4oz7d6s.mjs";
2
3
  import { l as GRAPHQL_METADATA_VERSION } from "./names-BlzDM5cF.mjs";
3
4
  import { isThenable, toIssueDetail } from "@znight/http";
4
5
  // src/decorators.ts