/** * GraphQL Query algebra -- the runtime generated GraphQL SDKs target. * * U+2500U+2500 Why this exists U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500 * A GraphQL document is a *selection*, not an RPC. Distilled used to bake a * max-depth selection into every operation (`Railway.me({})` downloaded the * world). This module instead treats every field as a lazy `Query`: * reading `user.email` records that field, and nothing is posted until * `Query.fn` evaluates the plan you returned. * * U+2500U+2500 The two phases U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500 * 1. Build (your function). `Railway.me()` / `user.email` / `Query.map` do * not talk to the network. They construct an expression tree: * Of | Map | Filter | FlatMap | Prop | Root * The inner function of `Query.fn` is therefore a *builder*, not an * Effect generator. No `yield*` inside it. * * 2. Evaluate (`Query.fn`). Walk the returned plan, paint every GraphQL * field that appears onto one selection forest, POST that document * once through {@link GqlTransport}, then interpret Map/Filter/FlatMap * against the JSON. Effects reached via FlatMap (e.g. * `usernameIsAvailable(name)`) run *after* the POST, with real values. * * U+2500U+2500 Combinators U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500 * - `Query.of(x)` -- a literal; never selected. * - `Query.map` on a list -- callback receives `Query` so `p.name` is * still a Query (selected). On a scalar, callback receives the value * after extract (`stars => stars > 5`). Relay connections (`edges { node }`) * are lists of the node type, so `projects({ first: 20 }).pipe(Query.map)` * maps projects, not edges. * - `Query.filter` -- predicate is `Query => Query`; the * boolean Query is walked for fields, then run per row after the POST. * - `Query.flatMap` -- after extract, run `(value) => Effect | Query`. * - `Query.pages` / `Query.items` -- a Stream over every page / node of a * Relay connection, one POST per page (see "Pagination"). * * U+2500U+2500 Types U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500 * `Query` is `QueryNode` plus the GraphQL fields of `Value`, * so `user.name` type-checks. That copy is a circular type alias * (`Query` contains `Query` which contains `Query` * again). TypeScript leaves the cycle lazy; there is no depth cap. * * U+2500U+2500 Transport U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500 * {@link GqlTransport.execute} posts `{ query, variables, operationName }`. * The Effect it returns may require Credentials / HttpClient; those leak * into `Query.fn`'s requirements. It returns the parsed `data` and raw * `errors`; `Query.fn` classifies the errors (see "Errors" below). A plan * that can't be compiled fails with {@link GqlError}. * * Generated SDKs export *roots* (`Railway.me`, `Railway.project`). * Combinators live in `@distilled.cloud/core/query`. */ import * as Context from "effect/Context"; import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Redacted from "effect/Redacted"; import * as Schedule from "effect/Schedule"; import * as S from "effect/Schema"; import * as Stream from "effect/Stream"; import { unwrapRedactedDeep } from "./plain-values.ts"; import * as Telemetry from "./telemetry.ts"; export const QuerySymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/graphql/Query"); const inspect = /*@__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); /** * A plan that cannot be compiled (a programming error in the query). The * compiler throws it; `Query.fn`, `Query.pages` and `Query.items` fail with * it (see {@link compiling}). */ export class GqlError extends /*@__PURE__*/ Data.TaggedError("GqlError")<{ readonly message: string; }> { constructor(message: string) { super({ message }); } } /** `f()`, with what the compiler throws failed as a {@link GqlError}. */ const compiling = (f: () => A): Effect.Effect => Effect.try({ try: f, catch: (e) => e instanceof GqlError ? e : new GqlError(e instanceof Error ? e.message : String(e)), }); // U+2500U+2500 Errors U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500 // // Every entry of a GraphQL `errors` array becomes one typed issue. Generated // SDKs declare tagged error classes plus the matchers that recognize them, // scoped to the root fields that can return them (or global). `Query.fn` // classifies each entry against the roots its path points at, so the error // channel is the union of the errors declared by the roots the plan reads. /** Fields every classified GraphQL error carries. */ export const errorFields = { message: S.String, code: /*@__PURE__*/ S.optional(S.String), path: /*@__PURE__*/ S.optional( /*@__PURE__*/ S.Array(/*@__PURE__*/ S.Union([S.String, S.Number])), ), locations: /*@__PURE__*/ S.optional( /*@__PURE__*/ S.Array(/*@__PURE__*/ S.Struct({ line: S.Number, column: S.Number })), ), extensions: /*@__PURE__*/ S.optional(S.Unknown), traceId: /*@__PURE__*/ S.optional(S.String), status: /*@__PURE__*/ S.optional(S.Number), /** Server retry hint in seconds. */ retryAfter: /*@__PURE__*/ S.optional(S.Number), }; /** The shape shared by every classified GraphQL error. */ export interface GraphQLIssue { readonly _tag: string; readonly message: string; readonly code?: string; readonly path?: ReadonlyArray; readonly locations?: ReadonlyArray<{ readonly line: number; readonly column: number; }>; readonly extensions?: unknown; readonly traceId?: string; readonly status?: number; readonly retryAfter?: number; } export type GraphQLIssueProps = Omit; /** A GraphQL error no declared matcher recognizes. */ export class UnknownGraphQLError extends /*@__PURE__*/ S.TaggedError()("UnknownGraphQLError", { ...errorFields, /** Root field the error path points at, when the path is known. */ coordinate: /*@__PURE__*/ S.optional(S.String), }) {} /** One response carried errors with different tags; none is hidden. */ export class GraphQLFailure extends /*@__PURE__*/ Data.TaggedError("GraphQLFailure")<{ readonly errors: readonly [E, ...E[]]; /** The partial response data, with sensitive fields wrapped in `Redacted`. */ readonly data: unknown; readonly status?: number; }> { get message(): string { return this.errors .map((e) => `${e._tag}${e.path?.length ? ` at ${e.path.join(".")}` : ""}: ${e.message}`) .join("; "); } } /** The request never produced a GraphQL response (network, HTTP, non-JSON). */ export class GraphQLTransportError extends /*@__PURE__*/ Data.TaggedError("GraphQLTransportError")<{ readonly message: string; readonly status?: number; /** Server retry hint in seconds. */ readonly retryAfter?: number; readonly cause?: unknown; }> {} /** A paginated connection reported more pages without a new cursor. */ export class GraphQLPaginationError extends /*@__PURE__*/ Data.TaggedError("GraphQLPaginationError")<{ readonly message: string; readonly cursor: string | null; }> {} /** Recognizes a raw GraphQL error. Every present property must match. */ export interface ErrorMatcher { readonly code?: string; readonly message?: string; readonly messageIncludes?: string; } /** Runtime description of one generated error class. */ export interface ErrorSpec { readonly tag: E["_tag"]; readonly make: (props: GraphQLIssueProps) => E; readonly matchers: ReadonlyArray; /** Queries failing only with retryable errors are retried. */ readonly retryable: boolean; /** Applies to every root, including errors that carry no path. */ readonly global: boolean; } export const errorSpec = ( make: new (props: GraphQLIssueProps) => E, tag: E["_tag"], matchers: ReadonlyArray, options: { readonly retryable?: boolean; readonly global?: boolean } = {}, ): ErrorSpec => ({ tag, make: (props) => new make(props), matchers, retryable: options.retryable ?? false, global: options.global ?? false, }); /** An entry of a GraphQL response's `errors` array, as sent on the wire. */ export interface RawGraphQLError { readonly message: string; readonly path?: ReadonlyArray; readonly locations?: ReadonlyArray<{ readonly line: number; readonly column: number; }>; readonly extensions?: Record; readonly [key: string]: unknown; } /** What a transport returns once it has a GraphQL response body. */ export interface GraphQLResponse { readonly data?: unknown; readonly errors?: ReadonlyArray; readonly status?: number; readonly headers?: Readonly>; } export type ArgMeta = Record; export type FieldMeta = { readonly name: string; readonly kind: "scalar" | "object" | "list" | "connection"; readonly of?: TypeMeta; readonly argTypes?: ArgMeta; /** The value is a secret: extracted values are wrapped in `Redacted`. */ readonly sensitive?: boolean; }; export type TypeMeta = { readonly name: string; readonly fields: Record; }; export const scalarField = ( name: string, options: { readonly sensitive?: boolean; readonly argTypes?: ArgMeta } = {}, ): FieldMeta => ({ name, kind: "scalar", ...(options.argTypes ? { argTypes: options.argTypes } : {}), ...(options.sensitive ? { sensitive: true } : {}), }); export const objectField = (name: string, objectType: TypeMeta, argTypes?: ArgMeta): FieldMeta => ({ name, kind: "object", of: objectType, ...(argTypes ? { argTypes } : {}), }); export const listField = (name: string, itemType: TypeMeta, argTypes?: ArgMeta): FieldMeta => ({ name, kind: "list", of: itemType, argTypes, }); /** Relay connection: GraphQL `edges { node }` presented as `Query`. */ export const connectionField = ( name: string, nodeType: TypeMeta, argTypes?: ArgMeta, ): FieldMeta => ({ name, kind: "connection", of: nodeType, argTypes, }); export type TypeRef = | { readonly tag: "scalar" } | { readonly tag: "object"; readonly meta: TypeMeta } | { readonly tag: "list"; readonly of: TypeRef }; const objectRef = (meta: TypeMeta): TypeRef => ({ tag: "object", meta }); const listRef = (itemType: TypeRef): TypeRef => ({ tag: "list", of: itemType, }); const fieldResult = (parent: TypeRef, field: FieldMeta): TypeRef => { const inner = (): TypeRef => { if (field.kind === "scalar") return { tag: "scalar" }; if (field.kind === "object") return objectRef(field.of!); return listRef(objectRef(field.of!)); // list | connection }; return parent.tag === "list" ? listRef(fieldResult(parent.of, field)) : inner(); }; const unwrapList = (typeRef: TypeRef): TypeRef => { if (typeRef.tag !== "list") throw new GqlError("expected a list Query"); return typeRef.of; }; const fieldsOf = (typeRef: TypeRef): Record => { if (typeRef.tag === "object") return typeRef.meta.fields; if (typeRef.tag === "list") return fieldsOf(typeRef.of); return {}; }; export interface SelNode { field: string; alias: string | undefined; args: Record | undefined; children: Map; isScalar: boolean; isList: boolean; /** The value is a secret: its strings are wrapped in `Redacted`. */ sensitive?: boolean; } export interface CompiledOperation { readonly document: string; readonly operationName: string; readonly variables: Record; readonly kind: "query" | "mutation"; readonly tree: SelNode; } /** * What a GraphQL SDK's document spans carry, generated from its GraphQL * model's `telemetry` entry (see `packages/dev/src/codegen/telemetry-traits.md`). * One span per document: `.`, or `.` when * the document selects several root fields. */ export interface GraphQLTelemetry extends Telemetry.ServiceTelemetry { readonly prefix: string; /** `.`, then argument name, then the attributes read from its value. */ readonly fields?: Readonly< Record>>> >; } export class GqlTransport extends /*@__PURE__*/ Context.Service< GqlTransport, { readonly execute: ( req: CompiledOperation, ) => Effect.Effect; /** The SDK's span facts; no spans without it. */ readonly telemetry?: GraphQLTelemetry; } >()("@distilled.cloud/graphql/Transport") {} const log = (..._args: Array): void => {}; /** * GraphQL fields copied onto a Query so `user.name` type-checks. * `Query` contains `projects: Query`, which contains * `owner: Query` again -- TypeScript leaves the cycle lazy. Fields * inherit the errors of the root they were read from. */ type QueryFields = [NonNullable] extends [ReadonlyArray] ? { readonly [Field in keyof NonNullable]: FieldQuery< NonNullable[Field], Nullish, Error >; } & { (args: Record): Query; } : [NonNullable] extends [object] ? { readonly [Field in keyof NonNullable]: FieldQuery< NonNullable[Field], Nullish, Error >; } : {}; /** * A field that takes arguments, as it appears in a generated data type. * Through a Query it is a call: `account.byId({ accountId })`. When every * argument is optional (`Required` false) the field also reads bare. */ export interface FieldWithArgs { readonly "~fieldArgs": { readonly value: Value; readonly args: Args; readonly required: Required; }; } /** The Query for one field: a call for a field with arguments, else a property. */ type FieldQuery = [Field] extends [ FieldWithArgs, ] ? [Required] extends [true] ? (args: Args) => Query : Query & ((args?: Args) => Query) : Query; /** A field read through a `null` parent is `null`. */ type Nullish = Extract; /** * A lazy GraphQL selection. `Value` is the plain data after `Query.fn` runs; * `Error` is the union of typed errors the roots it reads can return. */ export type Query = QueryNode & QueryFields; /** Strip Query/Effect wrappers from a returned plan down to plain data. */ export type UnwrapPlan = Plan extends QueryNode ? Value : Plan extends Effect.Effect ? Success : Plan extends ReadonlyArray ? ReadonlyArray> : Plan extends object ? { readonly [Key in keyof Plan]: UnwrapPlan } : Plan; /** Typed errors of every Query and Effect in a returned plan. */ export type PlanError = Plan extends QueryNode ? Error : Plan extends Effect.Effect ? Error : Plan extends ReadonlyArray ? PlanError : Plan extends object ? { readonly [Key in keyof Plan]: PlanError }[keyof Plan] : never; /** Failures of evaluating a plan whose roots declare `Error`. */ export type QueryError = | Error | GraphQLFailure | UnknownGraphQLError> | UnknownGraphQLError | GraphQLTransportError | GqlError; type Expr = | RootExpr | PropExpr | ItemExpr | MapValueExpr | MapItemsExpr | FilterExpr | FlatMapExpr | LiteralExpr; type RootExpr = { readonly _tag: "Root"; readonly op: "query" | "mutation"; readonly field: string; readonly args: Record | undefined; readonly argTypes: ArgMeta | undefined; readonly type: TypeRef; /** Relay connection: paint `edges { node }`, extract an array of nodes. */ readonly connection?: boolean; /** Errors this root field can return, including global errors. */ readonly errors: ReadonlyArray; /** Leaf root whose value is a secret: extracted strings are wrapped in `Redacted`. */ readonly sensitive?: boolean; }; type PropExpr = { readonly _tag: "Prop"; readonly parent: Expr; readonly field: FieldMeta; readonly type: TypeRef; readonly args?: Record; }; type ItemExpr = { readonly _tag: "Item"; readonly list: Expr; readonly type: TypeRef; }; type MapValueExpr = { readonly _tag: "MapValue"; readonly parent: Expr; readonly mapFn: (value: unknown) => unknown; readonly type: TypeRef; }; type MapItemsExpr = { readonly _tag: "MapItems"; readonly parent: Expr; readonly mapped: unknown; /** Map one object (`null` stays `null`) instead of every list item. */ readonly single?: boolean; readonly type: TypeRef; }; type FilterExpr = { readonly _tag: "Filter"; readonly parent: Expr; readonly predicate: Expr; readonly type: TypeRef; }; type FlatMapExpr = { readonly _tag: "FlatMap"; readonly parent: Expr; readonly flatMapFn: (value: unknown) => unknown; readonly type: TypeRef; }; type LiteralExpr = { readonly _tag: "Literal"; readonly value: unknown; readonly type: TypeRef; }; export class QueryNode { readonly [QuerySymbol] = QuerySymbol; declare readonly valueType: Value; declare readonly errorType: Error; readonly expr: Expr; constructor(expr: Expr) { this.expr = expr; return proxy(this) as QueryNode; } pipe(this: Self): Self; pipe(this: Self, step1: (_: Self) => Out1): Out1; pipe(this: Self, step1: (_: Self) => Out1, step2: (_: Out1) => Out2): Out2; pipe( this: Self, step1: (_: Self) => Out1, step2: (_: Out1) => Out2, step3: (_: Out2) => Out3, ): Out3; pipe( this: Self, step1: (_: Self) => Out1, step2: (_: Out1) => Out2, step3: (_: Out2) => Out3, step4: (_: Out3) => Out4, ): Out4; pipe( this: Self, step1: (_: Self) => Out1, step2: (_: Out1) => Out2, step3: (_: Out2) => Out3, step4: (_: Out3) => Out4, step5: (_: Out4) => Out5, ): Out5; pipe( this: Self, step1: (_: Self) => Out1, step2: (_: Out1) => Out2, step3: (_: Out2) => Out3, step4: (_: Out3) => Out4, step5: (_: Out4) => Out5, step6: (_: Out5) => Out6, ): Out6; pipe( this: Self, step1: (_: Self) => Out1, step2: (_: Out1) => Out2, step3: (_: Out2) => Out3, step4: (_: Out3) => Out4, step5: (_: Out4) => Out5, step6: (_: Out5) => Out6, step7: (_: Out6) => Out7, ): Out7; pipe( this: Self, step1: (_: Self) => Out1, step2: (_: Out1) => Out2, step3: (_: Out2) => Out3, step4: (_: Out3) => Out4, step5: (_: Out4) => Out5, step6: (_: Out5) => Out6, step7: (_: Out6) => Out7, step8: (_: Out7) => Out8, ): Out8; pipe(...steps: Array<(_: any) => any>): unknown { return steps.reduce((current, step) => step(current), this as never); } [inspect](): string { return printExpr(this.expr); } toString(): string { return this[inspect](); } } export const isQuery = (value: unknown): value is Query => (typeof value === "object" || typeof value === "function") && value !== null && QuerySymbol in value; const make = (expr: Expr): Query => new QueryNode(expr) as unknown as Query; const itemQuery = (list: QueryNode): QueryNode => new QueryNode({ _tag: "Item", list: list.expr, type: unwrapList(list.expr.type), }); function proxy(self: QueryNode): Query { const callable = Object.assign(function (bag?: Record) { return bag == null ? self : applyBag(self, bag); }, self); return new Proxy(callable, { has: (_, prop) => prop === QuerySymbol || prop === inspect || prop in self || (typeof prop === "string" && prop in fieldsOf(self.expr.type)), get: (_target, prop) => { if (prop === QuerySymbol) return QuerySymbol; if (prop === inspect) return self[inspect].bind(self); if (prop === "pipe") return self.pipe.bind(self); if (typeof prop === "string" && prop in self) { const member = (self as unknown as Record)[prop]; return typeof member === "function" ? member.bind(self) : member; } if (typeof prop !== "string") return undefined; const field = fieldsOf(self.expr.type)[prop]; if (!field) return undefined; return make({ _tag: "Prop", parent: self.expr, field, type: fieldResult(self.expr.type, field), }); }, apply: (_target, _thisArg, args) => applyBag(self, args[0] ?? {}), }) as unknown as Query; } const applyBag = ( self: QueryNode, bag: Record, ): Query => { const argTypes = self.expr._tag === "Prop" ? self.expr.field.argTypes : self.expr._tag === "Root" ? self.expr.argTypes : undefined; const args: Record = {}; for (const [argName, argValue] of Object.entries(bag)) { if (argTypes && argName in argTypes) args[argName] = argValue; } if (self.expr._tag === "Prop") { return make({ ...self.expr, args: { ...self.expr.args, ...args }, }); } if (self.expr._tag === "Root") { return make({ ...self.expr, args: { ...self.expr.args, ...args }, }); } return self as unknown as Query; }; export const root = ( op: "query" | "mutation", field: string, meta: TypeMeta, args?: Record, argTypes?: ArgMeta, errors: ReadonlyArray = [], ): Query => make({ _tag: "Root", op, field, args, argTypes, type: objectRef(meta), errors, }); export const rootList = ( op: "query" | "mutation", field: string, meta: TypeMeta, args?: Record, argTypes?: ArgMeta, errors: ReadonlyArray = [], ): Query, Error> => make({ _tag: "Root", op, field, args, argTypes, type: listRef(objectRef(meta)), errors, }); /** Root Relay connection: typed as `Query`, document uses `edges { node }`. */ export const rootConnection = ( op: "query" | "mutation", field: string, meta: TypeMeta, args?: Record, argTypes?: ArgMeta, errors: ReadonlyArray = [], ): Query, Error> => make({ _tag: "Root", op, field, args, argTypes, type: listRef(objectRef(meta)), connection: true, errors, }); /** Root field whose GraphQL type is a scalar, enum, or list of those. */ export const rootLeaf = ( op: "query" | "mutation", field: string, list: boolean, args?: Record, argTypes?: ArgMeta, errors: ReadonlyArray = [], options: { readonly sensitive?: boolean } = {}, ): Query => make({ _tag: "Root", op, field, args, argTypes, type: list ? listRef({ tag: "scalar" }) : { tag: "scalar" }, errors, ...(options.sensitive ? { sensitive: true } : {}), }); const printExpr = (expr: Expr): string => { switch (expr._tag) { case "Root": return expr.args ? `${expr.field}(${JSON.stringify(expr.args)})` : expr.field; case "Prop": return `${printExpr(expr.parent)}.${expr.field.name}`; case "Item": return "$item"; case "MapValue": return `map(${printExpr(expr.parent)})`; case "MapItems": return `mapItems(${printExpr(expr.parent)})`; case "Filter": return `filter(${printExpr(expr.parent)})`; case "FlatMap": return `flatMap(${printExpr(expr.parent)})`; case "Literal": return `of(${String(expr.value)})`; } }; const emptySel = (field: string): SelNode => ({ field, alias: undefined, args: undefined, children: new Map(), isScalar: false, isList: false, }); const stableStringify = (value: unknown): string => { if (value === null || typeof value !== "object") return JSON.stringify(value); if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`; const keys = Object.keys(value as object).sort(); return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify((value as Record)[key])}`).join(",")}}`; }; type Forest = { kind: "query" | "mutation" | undefined; roots: SelNode; vars: Map; varI: number; aliasI: number; rootAlias: WeakMap; /** Response key of each root -> the root field and its declared errors. */ rootErrors: Map; }; interface RootErrors { readonly field: string; readonly errors: ReadonlyArray; } const bindArgs = ( forest: Forest, args: Record | undefined, argTypes: ArgMeta | undefined, ): Record | undefined => { if (args === undefined) return undefined; const bound: Record = {}; let hasArgs = false; for (const [name, value] of Object.entries(args)) { if (value === undefined) continue; forest.vars.set(`v${forest.varI}`, { type: argTypes?.[name] ?? "String", value, }); bound[name] = `v${forest.varI++}`; hasArgs = true; } return hasArgs ? bound : undefined; }; const ensureChild = ( forest: Forest, parent: SelNode, field: string, options: { args?: Record; argTypes?: ArgMeta; isScalar?: boolean; isList?: boolean; sensitive?: boolean; }, ): SelNode => { const args = unwrapRedactedDeep(options.args) as Record | undefined; const key = args === undefined ? field : `${field}:${stableStringify(args)}`; const existing = parent.children.get(key); if (existing) return existing; const taken = new Set([...parent.children.values()].map((c) => c.alias ?? c.field)); let alias: string | undefined; if (taken.has(field)) { do { alias = `${field}_${forest.aliasI++}`; } while (taken.has(alias)); } const sel: SelNode = { field, alias, args: bindArgs(forest, args, options.argTypes), children: new Map(), isScalar: options.isScalar ?? false, isList: options.isList ?? false, ...(options.sensitive ? { sensitive: true } : {}), }; parent.children.set(key, sel); return sel; }; type Path = Array; const paintConnection = (forest: Forest, connection: SelNode): Path => { const edges = ensureChild(forest, connection, "edges", { isList: true }); ensureChild(forest, edges, "node", {}); return ["edges", "node"]; }; const paintAbs = (forest: Forest, expr: Expr): Path => { switch (expr._tag) { case "Root": { if (forest.kind !== undefined && forest.kind !== expr.op) { throw new GqlError(`cannot mix ${forest.kind} and ${expr.op} in one document`); } forest.kind = expr.op; const node = ensureChild(forest, forest.roots, expr.field, { args: expr.args, argTypes: expr.argTypes, // Leaf roots (`projectDelete: Boolean!`) take no sub-selection. isScalar: expr.type.tag === "scalar" || (expr.type.tag === "list" && expr.type.of.tag === "scalar"), isList: expr.type.tag === "list" && !expr.connection, sensitive: expr.sensitive, }); const key = node.alias ?? node.field; forest.rootAlias.set(expr, key); forest.rootErrors.set(key, { field: expr.field, errors: expr.errors }); return expr.connection ? [key, ...paintConnection(forest, node)] : [key]; } case "Prop": { const parentPath = paintAbs(forest, expr.parent); const parentSel = selAt(forest.roots, parentPath); const node = ensureChild(forest, parentSel, expr.field.name, { args: expr.args, argTypes: expr.field.argTypes, isScalar: expr.field.kind === "scalar", isList: expr.field.kind === "list", sensitive: expr.field.sensitive, }); const key = node.alias ?? node.field; forest.rootAlias.set(expr, key); const path = [...parentPath, key]; return expr.field.kind === "connection" ? [...path, ...paintConnection(forest, node)] : path; } default: throw new GqlError(`paintAbs: ${expr._tag}`); } }; const selAt = (roots: SelNode, path: Path): SelNode => { let current = roots; for (const segment of path) { if (segment === "*") continue; const child = [...current.children.values()].find( (candidate) => (candidate.alias ?? candidate.field) === segment, ); if (!child) { throw new GqlError(`internal: missing ${String(segment)}`); } current = child; } return current; }; const connectionNodeSel = (connection: SelNode): SelNode => { const edges = [...connection.children.values()].find((c) => c.field === "edges"); const node = edges ? [...edges.children.values()].find((c) => c.field === "node") : undefined; if (!node) throw new GqlError("internal: connection missing edges.node"); return node; }; const relSel = (forest: Forest, expr: Expr, listSel: SelNode): SelNode => { switch (expr._tag) { case "Item": return listSel; case "Prop": { const parent = relSel(forest, expr.parent, listSel); const key = forest.rootAlias.get(expr) ?? expr.field.name; const child = [...parent.children.values()].find((c) => (c.alias ?? c.field) === key); if (!child) { throw new GqlError(`missing ${expr.field.name} in list selection`); } return expr.field.kind === "connection" ? connectionNodeSel(child) : child; } default: return listSel; } }; const paintRel = (forest: Forest, expr: Expr, listSel: SelNode): void => { switch (expr._tag) { case "Item": case "Literal": return; case "Prop": { paintRel(forest, expr.parent, listSel); const child = ensureChild(forest, relSel(forest, expr.parent, listSel), expr.field.name, { args: expr.args, argTypes: expr.field.argTypes, isScalar: expr.field.kind === "scalar", isList: expr.field.kind === "list", sensitive: expr.field.sensitive, }); forest.rootAlias.set(expr, child.alias ?? child.field); if (expr.field.kind === "connection") paintConnection(forest, child); return; } case "MapValue": case "FlatMap": paintRel(forest, expr.parent, listSel); return; case "MapItems": paintRel(forest, expr.parent, listSel); visitRel(expr.mapped, forest, relSel(forest, expr.parent, listSel)); return; case "Filter": paintRel(forest, expr.parent, listSel); paintRel(forest, expr.predicate, relSel(forest, expr.parent, listSel)); return; case "Root": throw new GqlError("root inside list item"); } }; const visitExpr = (forest: Forest, expr: Expr): void => { switch (expr._tag) { case "Root": case "Prop": paintAbs(forest, expr); return; case "Item": return; case "Literal": return; case "MapValue": case "FlatMap": visitExpr(forest, expr.parent); return; case "MapItems": { visitExpr(forest, expr.parent); const path = paintAbs(forest, graphqlBase(expr.parent)); visitRel(expr.mapped, forest, selAt(forest.roots, path)); return; } case "Filter": { visitExpr(forest, expr.parent); const path = paintAbs(forest, graphqlBase(expr.parent)); paintRel(forest, expr.predicate, selAt(forest.roots, path)); return; } } }; const graphqlBase = (expr: Expr): Expr => { switch (expr._tag) { case "Root": case "Prop": case "Item": return expr; case "MapValue": case "MapItems": case "Filter": case "FlatMap": return graphqlBase(expr.parent); case "Literal": throw new GqlError("literal has no graphql base"); } }; const visitRel = (plan: unknown, forest: Forest, listSel: SelNode): void => { if (isQuery(plan)) { paintRel(forest, (plan as QueryNode).expr, listSel); return; } if (plan !== null && typeof plan === "object" && !Effect.isEffect(plan)) { for (const nested of Object.values(plan as Record)) { visitRel(nested, forest, listSel); } } }; /** * Recurse through a builder return value. Query nodes contribute GraphQL * fields to `forest`; Effects are ignored until interpret (FlatMap). */ const visitPlan = (plan: unknown, forest: Forest): void => { if (isQuery(plan)) { log("visit", printExpr((plan as QueryNode).expr)); visitExpr(forest, (plan as QueryNode).expr); return; } if (Effect.isEffect(plan)) return; if (plan !== null && typeof plan === "object" && !Array.isArray(plan)) { for (const nested of Object.values(plan as Record)) { visitPlan(nested, forest); } } }; const validate = (node: SelNode): string | undefined => { for (const child of node.children.values()) { if (!child.isScalar && child.children.size === 0) { return `field "${child.field}" has no sub-selection`; } const inner = validate(child); if (inner) return inner; } return undefined; }; const printChildren = (node: SelNode, indent: number): string => { const pad = " ".repeat(indent); const lines: Array = []; for (const child of node.children.values()) { let head = child.alias ? `${child.alias}: ${child.field}` : child.field; if (child.args && Object.keys(child.args).length > 0) { const printed = Object.entries(child.args) .map(([argName, varName]) => `${argName}: $${varName}`) .join(", "); head += `(${printed})`; } if (child.isScalar) lines.push(`${pad}${head}`); else { lines.push(`${pad}${head} {`); lines.push(printChildren(child, indent + 1)); lines.push(`${pad}}`); } } return lines.join("\n"); }; const emptyForest = (): Forest => ({ kind: undefined, roots: emptySel(""), vars: new Map(), varI: 0, aliasI: 0, rootAlias: new WeakMap(), rootErrors: new Map(), }); const emit = (forest: Forest): Compiled => { const err = validate(forest.roots); if (err) throw new GqlError(err); const kind = forest.kind ?? "query"; const varDefs = [...forest.vars.entries()] .map(([name, binding]) => `$${name}: ${binding.type}`) .join(", "); const header = varDefs.length > 0 ? `${kind} Gql(${varDefs})` : `${kind} Gql`; const variables: Record = {}; for (const [name, binding] of forest.vars) variables[name] = binding.value; return { document: `${header} {\n${printChildren(forest.roots, 1)}\n}`, operationName: "Gql", variables, kind, tree: forest.roots, rootAlias: forest.rootAlias, rootErrors: forest.rootErrors, }; }; type Compiled = CompiledOperation & { readonly rootAlias: WeakMap; readonly rootErrors: ReadonlyMap; }; const nodesFromConnection = (value: unknown): unknown => { if (value == null) return value; if (Array.isArray(value)) return value.map(nodesFromConnection); const edges = (value as Record).edges; if (!Array.isArray(edges)) return []; return edges.map((edge) => (edge == null ? edge : (edge as Record).node)); }; const readField = (parent: unknown, name: string): unknown => { if (parent == null) return parent; if (Array.isArray(parent)) { return parent.map((item) => (item == null ? item : (item as Record)[name])); } return (parent as Record)[name]; }; /** * Wrap a sensitive scalar in `Redacted`: a string, a JSON object, or each * item of a list of them. */ const redactValues = (value: unknown): unknown => value === null || value === undefined ? value : Array.isArray(value) ? value.map(redactValues) : Redacted.make(value); /** Copy `data` with the value of every sensitive field `sel` selects wrapped in `Redacted`. */ const redactSelected = (sel: SelNode, data: unknown): unknown => { if (sel.children.size === 0 || data === null || typeof data !== "object") return data; if (Array.isArray(data)) return data.map((item) => redactSelected(sel, item)); const out: Record = { ...data }; for (const child of sel.children.values()) { const key = child.alias ?? child.field; out[key] = child.sensitive ? redactValues(out[key]) : redactSelected(child, out[key]); } return out; }; const extractAbs = (expr: Expr, data: unknown, rootAlias: WeakMap): unknown => { switch (expr._tag) { case "Root": { const raw = (data as Record)[rootAlias.get(expr) ?? expr.field]; return expr.connection ? nodesFromConnection(raw) : raw; } case "Prop": { const value = readField( extractAbs(expr.parent, data, rootAlias), rootAlias.get(expr) ?? expr.field.name, ); return expr.field.kind === "connection" ? nodesFromConnection(value) : value; } default: throw new GqlError(`extractAbs: ${expr._tag}`); } }; const extractRel = (expr: Expr, item: unknown, rootAlias: WeakMap): unknown => { switch (expr._tag) { case "Item": return item; case "Prop": { const value = readField( extractRel(expr.parent, item, rootAlias), rootAlias.get(expr) ?? expr.field.name, ); return expr.field.kind === "connection" ? nodesFromConnection(value) : value; } default: throw new GqlError(`extractRel: ${expr._tag}`); } }; const inItem = (expr: Expr): boolean => { switch (expr._tag) { case "Item": return true; case "Prop": case "MapValue": case "MapItems": case "Filter": case "FlatMap": return inItem(expr.parent); default: return false; } }; const interpretExpr = ( expr: Expr, data: unknown, rootAlias: WeakMap, item: unknown, ): unknown => { switch (expr._tag) { case "Literal": return expr.value; case "Item": return item; case "Root": case "Prop": return inItem(expr) ? extractRel(expr, item, rootAlias) : extractAbs(expr, data, rootAlias); case "MapValue": return expr.mapFn(interpretExpr(expr.parent, data, rootAlias, item)); case "Filter": { const list = interpretExpr(expr.parent, data, rootAlias, item); const arr = Array.isArray(list) ? list : []; return arr.filter((row) => Boolean(interpretExpr(expr.predicate, data, rootAlias, row))); } case "MapItems": { const list = interpretExpr(expr.parent, data, rootAlias, item); if (expr.single) { return list == null ? null : interpretValueSync(expr.mapped, data, rootAlias, list); } const arr = Array.isArray(list) ? list : []; return arr.map((row) => interpretValueSync(expr.mapped, data, rootAlias, row)); } case "FlatMap": throw new GqlError("FlatMap must be interpreted as Effect"); } }; const interpretValueSync = ( plan: unknown, data: unknown, rootAlias: WeakMap, item: unknown, ): unknown => { if (isQuery(plan)) { return interpretExpr((plan as QueryNode).expr, data, rootAlias, item); } if (plan !== null && typeof plan === "object" && !Effect.isEffect(plan)) { const out: Record = {}; for (const [key, nested] of Object.entries(plan as Record)) { out[key] = interpretValueSync(nested, data, rootAlias, item); } return out; } return plan; }; const interpretPlan = ( plan: unknown, data: unknown, rootAlias: WeakMap, ): Effect.Effect => Effect.gen(function* () { if (isQuery(plan)) { const expr = (plan as QueryNode).expr; if (expr._tag === "FlatMap") { const resolved = yield* compiling(() => interpretExpr(expr.parent, data, rootAlias, undefined), ); const next = expr.flatMapFn(resolved); if (Effect.isEffect(next)) return yield* next; if (isQuery(next)) return yield* interpretPlan(next, data, rootAlias); return next; } return yield* compiling(() => interpretExpr(expr, data, rootAlias, undefined)); } if (Effect.isEffect(plan)) return yield* plan; if (plan !== null && typeof plan === "object" && !Array.isArray(plan)) { const out: Record = {}; for (const [key, nested] of Object.entries(plan as Record)) { out[key] = yield* interpretPlan(nested, data, rootAlias); } return out; } return plan; }) as Effect.Effect; /** * Compile every Query in `plan` into one document, POST it, then replace * Query/Effect leaves with plain data (`UnwrapPlan`). */ const evaluatePlan = ( plan: Plan, ): Effect.Effect, QueryError>, GqlTransport> => Effect.gen(function* () { const forest = emptyForest(); const compiled = yield* compiling(() => { visitPlan(plan, forest); return forest.roots.children.size > 0 ? emit(forest) : undefined; }); let data: unknown = {}; let rootAlias: WeakMap = new WeakMap(); if (compiled !== undefined) { log("document\n" + compiled.document); data = yield* execute(compiled); rootAlias = compiled.rootAlias; } return (yield* interpretPlan(plan, data, rootAlias)) as UnwrapPlan; }) as Effect.Effect, QueryError>, GqlTransport>; /** * POST one compiled document and fail with its classified errors. Queries * are retried (bounded) while every failure is retryable; mutations never * are, since an error can follow a side effect that already happened. */ const execute = (compiled: Compiled): Effect.Effect => { const once = Effect.gen(function* () { const transport = yield* GqlTransport; const response = yield* transport.execute(compiled); const data = redactSelected(compiled.tree, response.data); const raw = response.errors ?? []; if (raw.length === 0) { // Without errors, a GraphQL response must carry a `data` object. if (!isRecord(response.data)) { return yield* Effect.fail( new GraphQLTransportError({ message: "GraphQL response has no data object and no errors", status: response.status, }), ); } return data; } const issues = raw.map((error) => classify(compiled, error, response)); const [first, ...rest] = issues as [GraphQLIssue, ...GraphQLIssue[]]; return yield* Effect.fail( rest.every((issue) => issue._tag === first._tag) ? first : new GraphQLFailure({ errors: [first, ...rest], data, status: response.status, }), ); }); const attempts = Effect.withFiber((fiber) => { if (compiled.kind !== "query") return once; const context = fiber.context as Context.Context; let retries = 0; return once.pipe( Effect.retry({ while: (error) => { const retry = isRetryable(compiled, error) && retries < 5; // Schedule.exponential("200 millis"): 200 ms, then doubling. if (retry) Telemetry.retried(context, ++retries, error, 200 * 2 ** (retries - 1)); return retry; }, times: 5, schedule: Schedule.exponential("200 millis"), }), ); }); return Effect.withFiber((fiber) => { const debug = fiber.getRef(Telemetry.Debug); const telemetry = Context.getOrUndefined(fiber.context, GqlTransport)?.telemetry; if (telemetry === undefined) return attempts; const [info, input] = documentInfo(telemetry, compiled); return Telemetry.operationSpan(fiber, debug, info, undefined, input, () => attempts); }) as Effect.Effect; }; /** * One document's span facts: its root fields name it, and their arguments * fill the attributes the SDK's `fields` rules name (an input object keyed * `..`). */ const documentInfo = ( telemetry: GraphQLTelemetry, compiled: Compiled, ): readonly [Telemetry.OperationInfo, Record] => { const roots = [...new Set([...compiled.tree.children.values()].map((node) => node.field))]; const single = roots.length === 1 ? roots[0] : undefined; const target = single ?? compiled.kind; const input: Record = {}; const rules: Record> = {}; for (const node of compiled.tree.children.values()) { const fieldRules = telemetry.fields?.[`${compiled.kind}.${node.field}`]; if (fieldRules === undefined || node.args === undefined) continue; for (const arg in node.args) { const argRules = fieldRules[arg]; if (argRules === undefined) continue; const key = `${compiled.kind}.${node.field}.${arg}`; input[key] = compiled.variables[node.args[arg]!]; rules[key] = argRules; } } const info = Telemetry.operationInfo( telemetry, { name: `${telemetry.prefix}.${target}`, method: `${telemetry.prefix}/${target}`, attributes: { "graphql.operation.type": compiled.kind, ...(single !== undefined ? { "graphql.operation.name": single } : {}), }, input: rules, }, undefined, ); return [info, input]; }; type ExecuteError = GraphQLIssue | GraphQLFailure | GraphQLTransportError; const isRetryable = (compiled: Compiled, error: ExecuteError): boolean => { if (error instanceof GraphQLTransportError) { return error.status === undefined || error.status === 429 || error.status >= 500; } const retryable = new Set( [...compiled.rootErrors.values()].flatMap((root) => root.errors.filter((spec) => spec.retryable).map((spec) => spec.tag), ), ); return error instanceof GraphQLFailure ? error.errors.every((issue) => retryable.has(issue._tag)) : retryable.has(error._tag); }; const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); /** * Pick the most specific matcher among the errors the root at `path[0]` * declares (or the global errors for a path-less error). A tie between * different tags is ambiguous and stays {@link UnknownGraphQLError}. */ const classify = (compiled: Compiled, entry: unknown, response: GraphQLResponse): GraphQLIssue => { // The entry comes from the wire: anything that is not an object (`null`, // a bare string) is read as an error with only a message. const raw: Partial = isRecord(entry) ? (entry as Partial) : { message: typeof entry === "string" ? entry : `malformed GraphQL error entry (${entry === null ? "null" : typeof entry})`, }; const rawPath = Array.isArray(raw.path) ? (raw.path as ReadonlyArray) : undefined; const root = typeof rawPath?.[0] === "string" ? compiled.rootErrors.get(rawPath[0]) : undefined; // The error classes validate `path` and `locations`, so a malformed value // is left out instead of making the constructor throw. const path = rawPath?.every((key) => typeof key === "string" || typeof key === "number") ? (rawPath as ReadonlyArray) : undefined; const locations = Array.isArray(raw.locations) && raw.locations.every( (location: unknown) => isRecord(location) && typeof location.line === "number" && typeof location.column === "number", ) ? raw.locations : undefined; const candidates = root ? root.errors : uniqueByTag( [...compiled.rootErrors.values()].flatMap((entry) => entry.errors.filter((spec) => spec.global), ), ); const extensions = isRecord(raw.extensions) ? raw.extensions : {}; const code = typeof extensions.code === "string" ? extensions.code : typeof extensions.errorCode === "string" ? extensions.errorCode : undefined; const message = typeof raw.message === "string" ? raw.message : ""; const retryHeader = response.headers?.["retry-after"]; const props: GraphQLIssueProps = { message, code, path, locations, extensions: raw.extensions, traceId: typeof extensions.traceId === "string" ? extensions.traceId : typeof raw.traceId === "string" ? raw.traceId : undefined, status: response.status, retryAfter: retryHeader && /^\d+(\.\d+)?$/.test(retryHeader) ? Number(retryHeader) : undefined, }; const matches = candidates.flatMap((spec) => spec.matchers .filter( (matcher) => (matcher.code === undefined || matcher.code === code) && (matcher.message === undefined || matcher.message === message) && (matcher.messageIncludes === undefined || message.includes(matcher.messageIncludes)), ) .map((matcher) => ({ spec, score: (matcher.code ? 1 : 0) + (matcher.message ? 4 : 0) + (matcher.messageIncludes ? 2 : 0), })), ); matches.sort((a, b) => b.score - a.score); const best = matches[0]; if ( best && !matches.some((match) => match.score === best.score && match.spec.tag !== best.spec.tag) ) { return best.spec.make(props); } return new UnknownGraphQLError({ ...props, coordinate: root?.field, }); }; const uniqueByTag = (specs: ReadonlyArray): ErrorSpec[] => [ ...new Map(specs.map((spec) => [spec.tag, spec])).values(), ]; /** `Query.of` / pure. */ export const ofQuery = (value: Value): Query => make({ _tag: "Literal", value, type: { tag: "scalar" } }); const filterImpl = ( source: QueryNode, predicate: (item: QueryNode) => QueryNode, ): Query => { const proto = itemQuery(source); const predicateQuery = predicate(proto); log("filter pred", printExpr(predicateQuery.expr)); return make({ _tag: "Filter", parent: source.expr, predicate: predicateQuery.expr, type: source.expr.type, }); }; export function filterQuery( predicate: (item: Query) => QueryNode, ): (source: QueryNode) => Query; export function filterQuery( source: QueryNode, predicate: (item: Query) => QueryNode, ): Query; export function filterQuery(sourceOrPredicate: any, predicate?: any): any { if (predicate === undefined) { return (source: QueryNode) => filterImpl(source, sourceOrPredicate); } return filterImpl(sourceOrPredicate, predicate); } /** * What `Query.map`'s callback receives: a Query per item for lists, a Query * for an object (so its fields get selected), the plain value for scalars. */ type MapInput = [NonNullable] extends [ReadonlyArray] ? Query : [NonNullable] extends [object] ? Query> : Value; /** An object mapped through a `null` value stays `null`. */ type MapOutput = [NonNullable] extends [ReadonlyArray] ? ReadonlyArray> : [NonNullable] extends [object] ? UnwrapPlan | Nullish : Mapped; const mapImpl = (source: QueryNode, mapFn: (value: any) => unknown): Query => { if (source.expr.type.tag === "object") { const mapped = mapFn( new QueryNode({ _tag: "Item", list: source.expr, type: source.expr.type, }), ); log("map object", printExpr(source.expr)); return make({ _tag: "MapItems", parent: source.expr, mapped, single: true, type: { tag: "scalar" }, }); } if (source.expr.type.tag === "list") { const proto = itemQuery(source); const mapped = mapFn(proto); log("map items", printExpr(source.expr)); return make({ _tag: "MapItems", parent: source.expr, mapped, type: source.expr.type, }); } log("map value", printExpr(source.expr)); return make({ _tag: "MapValue", parent: source.expr, mapFn, type: { tag: "scalar" }, }); }; export function mapQuery( mapFn: (value: NoInfer>) => Mapped, ): (source: QueryNode) => Query, Error>; export function mapQuery( source: QueryNode, mapFn: (value: NoInfer>) => Mapped, ): Query, Error>; export function mapQuery(sourceOrMapFn: any, mapFn?: any): any { if (mapFn === undefined) { return (source: QueryNode) => mapImpl(source, sourceOrMapFn); } return mapImpl(sourceOrMapFn, mapFn); } const flatMapImpl = (source: QueryNode, flatMapFn: (value: unknown) => unknown): Query => { log("flatMap", printExpr(source.expr)); return make({ _tag: "FlatMap", parent: source.expr, flatMapFn, type: { tag: "scalar" }, }); }; export function flatMapQuery( flatMapFn: ( value: Value, ) => Effect.Effect | QueryNode, ): (source: QueryNode) => Query; export function flatMapQuery( source: QueryNode, flatMapFn: ( value: Value, ) => Effect.Effect | QueryNode, ): Query; export function flatMapQuery(sourceOrFlatMapFn: any, flatMapFn?: any): any { if (flatMapFn === undefined) { return (source: QueryNode) => flatMapImpl(source, sourceOrFlatMapFn); } return flatMapImpl(sourceOrFlatMapFn, flatMapFn); } /** * Builder -> Effect. The inner function is *not* a generator; it returns a * plan of Query/Effect values. Query.fn visits the plan, POSTs one document, * then interprets Map/Filter/FlatMap/Of. */ export const queryFn = , Plan>( build: (...args: Arguments) => Plan, ): (( ...args: Arguments ) => Effect.Effect, QueryError>, GqlTransport>) => (...args) => { const plan = build(...args); return evaluatePlan(plan); }; // U+2500U+2500 Pagination U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500 // // A connection lens hides `edges`/`pageInfo`. `Query.pages` re-evaluates the // query once per page: it sets the connection's `after` argument, paints // `pageInfo { hasNextPage endCursor }` next to `edges`, and stops when // `hasNextPage` is false. /** The connection a paged query reads, below any list-level Map/Filter. */ const connectionOf = (expr: Expr): RootExpr | PropExpr => { const base = graphqlBase(expr); const isConnection = (base._tag === "Root" && base.connection === true) || (base._tag === "Prop" && base.field.kind === "connection"); if (!isConnection || inItem(base)) { throw new GqlError(`Query.pages needs a Relay connection, got ${printExpr(base)}`); } const argTypes = base._tag === "Root" ? base.argTypes : base.field.argTypes; if (!argTypes || !("after" in argTypes)) { throw new GqlError(`${printExpr(base)} takes no "after" cursor`); } return base as RootExpr | PropExpr; }; /** Rebuild `expr` with the connection's `after` argument set. */ const withCursor = (expr: Expr, connection: Expr, after: string | undefined): Expr => { if (expr === connection) { const current = expr as RootExpr | PropExpr; return { ...current, args: { ...current.args, after } } as Expr; } switch (expr._tag) { case "MapItems": case "Filter": case "MapValue": case "FlatMap": return { ...expr, parent: withCursor(expr.parent, connection, after) }; default: throw new GqlError(`withCursor: ${expr._tag}`); } }; const readPath = (data: unknown, path: Path): unknown => { let current = data; for (const segment of path) { if (current == null) return undefined; if (Array.isArray(current)) { throw new GqlError("Query.pages cannot page a connection inside a list"); } current = (current as Record)[segment]; } return current; }; interface PageState { readonly after: string | undefined; readonly seen: ReadonlySet; } const fetchPage = ( query: QueryNode | null, unknown>, connection: RootExpr | PropExpr, state: PageState, ) => Effect.gen(function* () { const { pageExpr, connectionPath, compiled } = yield* compiling(() => { const pageExpr = withCursor(query.expr, connection, state.after); const forest = emptyForest(); visitExpr(forest, pageExpr); const nodePath = paintAbs(forest, withCursor(connection, connection, state.after)); const connectionPath = nodePath.slice(0, -2); const pageInfo = ensureChild(forest, selAt(forest.roots, connectionPath), "pageInfo", {}); ensureChild(forest, pageInfo, "hasNextPage", { isScalar: true }); ensureChild(forest, pageInfo, "endCursor", { isScalar: true }); return { pageExpr, connectionPath, compiled: emit(forest) }; }); log("page\n" + compiled.document); const data = yield* execute(compiled); const items = (yield* interpretPlan(make(pageExpr), data, compiled.rootAlias)) as | ReadonlyArray | null | undefined; const info = readPath(data, [...connectionPath, "pageInfo"]) as | { hasNextPage?: boolean; endCursor?: string | null } | null | undefined; const cursor = info?.endCursor ?? null; if (info?.hasNextPage !== true) { return [items ?? [], Option.none()] as const; } if (cursor === null || cursor === state.after || state.seen.has(cursor)) { return yield* new GraphQLPaginationError({ message: `${printExpr(connection)} returned a non-advancing cursor`, cursor, }); } return [ items ?? [], Option.some({ after: cursor, seen: new Set([...state.seen, cursor]) }), ] as const; }); /** * Every page of a Relay connection, one request per page. `query` is a * connection lens (root or nested under objects), optionally mapped or * filtered: `Query.pages(Railway.project({ id }).services({ first: 50 }))`. * Starts from the query's own `after` argument, if any. */ export const pagesQuery = ( query: QueryNode | null, Error>, ): Stream.Stream, QueryError | GraphQLPaginationError, GqlTransport> => Stream.unwrap( Effect.map( compiling(() => connectionOf(query.expr)), (connection) => { const after = connection.args?.after; return Stream.paginate< PageState, ReadonlyArray, QueryError | GraphQLPaginationError, GqlTransport >( { after: typeof after === "string" ? after : undefined, seen: new Set(), }, (state) => fetchPage(query, connection, state).pipe( Effect.map(([items, next]) => [[items], next] as const), ) as Effect.Effect< readonly [ReadonlyArray>, Option.Option], QueryError | GraphQLPaginationError, GqlTransport >, ); }, ), ); /** Every node of a Relay connection, across all pages. */ export const itemsQuery = ( query: QueryNode | null, Error>, ): Stream.Stream | GraphQLPaginationError, GqlTransport> => pagesQuery(query).pipe(Stream.flatMap(Stream.fromIterable));