@distilled.cloud/core 1.0.0-rc.12 → 1.0.0-rc.14
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.
- package/lib/api.d.ts +4 -4
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +3 -5
- package/lib/api.js.map +1 -1
- package/lib/category.d.ts.map +1 -1
- package/lib/category.js +3 -5
- package/lib/category.js.map +1 -1
- package/lib/codegen/boolean-string-enums.d.ts +8 -8
- package/lib/codegen/boolean-string-enums.d.ts.map +1 -1
- package/lib/codegen/boolean-string-enums.js +83 -30
- package/lib/codegen/boolean-string-enums.js.map +1 -1
- package/lib/codegen/boolean-string-enums.test.js +130 -2
- package/lib/codegen/boolean-string-enums.test.js.map +1 -1
- package/lib/codegen/cli.d.ts +5 -4
- package/lib/codegen/cli.d.ts.map +1 -1
- package/lib/codegen/cli.js +12 -9
- package/lib/codegen/cli.js.map +1 -1
- package/lib/codegen/defer-naming.test.d.ts +2 -0
- package/lib/codegen/defer-naming.test.d.ts.map +1 -0
- package/lib/codegen/defer-naming.test.js +105 -0
- package/lib/codegen/defer-naming.test.js.map +1 -0
- package/lib/codegen/emit.d.ts.map +1 -1
- package/lib/codegen/emit.js +1 -3
- package/lib/codegen/emit.js.map +1 -1
- package/lib/codegen/format.d.ts +0 -12
- package/lib/codegen/format.d.ts.map +1 -1
- package/lib/codegen/format.js +10 -6
- package/lib/codegen/format.js.map +1 -1
- package/lib/codegen/generated-at.d.ts +29 -0
- package/lib/codegen/generated-at.d.ts.map +1 -0
- package/lib/codegen/generated-at.js +78 -0
- package/lib/codegen/generated-at.js.map +1 -0
- package/lib/codegen/generated-at.test.d.ts +2 -0
- package/lib/codegen/generated-at.test.d.ts.map +1 -0
- package/lib/codegen/generated-at.test.js +81 -0
- package/lib/codegen/generated-at.test.js.map +1 -0
- package/lib/codegen/generator.d.ts +24 -5
- package/lib/codegen/generator.d.ts.map +1 -1
- package/lib/codegen/generator.js +69 -80
- package/lib/codegen/generator.js.map +1 -1
- package/lib/codegen/generator.test.d.ts +2 -0
- package/lib/codegen/generator.test.d.ts.map +1 -0
- package/lib/codegen/generator.test.js +121 -0
- package/lib/codegen/generator.test.js.map +1 -0
- package/lib/codegen/graphql-client.d.ts +7 -1
- package/lib/codegen/graphql-client.d.ts.map +1 -1
- package/lib/codegen/graphql-client.js +264 -148
- package/lib/codegen/graphql-client.js.map +1 -1
- package/lib/codegen/graphql-client.test.js +98 -238
- package/lib/codegen/graphql-client.test.js.map +1 -1
- package/lib/codegen/graphql.d.ts.map +1 -1
- package/lib/codegen/graphql.js +7 -20
- package/lib/codegen/graphql.js.map +1 -1
- package/lib/codegen/model-diff.d.ts +10 -0
- package/lib/codegen/model-diff.d.ts.map +1 -0
- package/lib/codegen/model-diff.js +67 -0
- package/lib/codegen/model-diff.js.map +1 -0
- package/lib/codegen/naming.d.ts.map +1 -1
- package/lib/codegen/naming.js.map +1 -1
- package/lib/codegen/openapi-binary.test.d.ts +2 -0
- package/lib/codegen/openapi-binary.test.d.ts.map +1 -0
- package/lib/codegen/openapi-binary.test.js +67 -0
- package/lib/codegen/openapi-binary.test.js.map +1 -0
- package/lib/codegen/openapi-cli.d.ts +11 -11
- package/lib/codegen/openapi-cli.d.ts.map +1 -1
- package/lib/codegen/openapi-cli.js +26 -51
- package/lib/codegen/openapi-cli.js.map +1 -1
- package/lib/codegen/openapi.d.ts +16 -2
- package/lib/codegen/openapi.d.ts.map +1 -1
- package/lib/codegen/openapi.js +56 -39
- package/lib/codegen/openapi.js.map +1 -1
- package/lib/codegen/operations.d.ts.map +1 -1
- package/lib/codegen/operations.js.map +1 -1
- package/lib/codegen/pagination.d.ts.map +1 -1
- package/lib/codegen/pagination.js +2 -4
- package/lib/codegen/pagination.js.map +1 -1
- package/lib/codegen/patch-audit.d.ts +84 -0
- package/lib/codegen/patch-audit.d.ts.map +1 -0
- package/lib/codegen/patch-audit.js +366 -0
- package/lib/codegen/patch-audit.js.map +1 -0
- package/lib/codegen/patch-audit.test.d.ts +2 -0
- package/lib/codegen/patch-audit.test.d.ts.map +1 -0
- package/lib/codegen/patch-audit.test.js +141 -0
- package/lib/codegen/patch-audit.test.js.map +1 -0
- package/lib/codegen/patches.d.ts +75 -11
- package/lib/codegen/patches.d.ts.map +1 -1
- package/lib/codegen/patches.js +301 -65
- package/lib/codegen/patches.js.map +1 -1
- package/lib/codegen/patches.test.js +55 -5
- package/lib/codegen/patches.test.js.map +1 -1
- package/lib/codegen/prelude.js +1 -1
- package/lib/codegen/prelude.js.map +1 -1
- package/lib/codegen/proto.d.ts.map +1 -1
- package/lib/codegen/proto.js +2 -4
- package/lib/codegen/proto.js.map +1 -1
- package/lib/codegen/protocol-imports.test.d.ts +2 -0
- package/lib/codegen/protocol-imports.test.d.ts.map +1 -0
- package/lib/codegen/protocol-imports.test.js +36 -0
- package/lib/codegen/protocol-imports.test.js.map +1 -0
- package/lib/codegen/rewrite-operation-ids.d.ts +23 -0
- package/lib/codegen/rewrite-operation-ids.d.ts.map +1 -1
- package/lib/codegen/rewrite-operation-ids.js +97 -59
- package/lib/codegen/rewrite-operation-ids.js.map +1 -1
- package/lib/codegen/rewrite-operation-ids.test.js +19 -101
- package/lib/codegen/rewrite-operation-ids.test.js.map +1 -1
- package/lib/codegen/spec-path.d.ts +1 -1
- package/lib/codegen/spec-path.d.ts.map +1 -1
- package/lib/codegen/spec-path.js +1 -1
- package/lib/codegen/spec-path.js.map +1 -1
- package/lib/codegen/untagged-unions.test.d.ts +2 -0
- package/lib/codegen/untagged-unions.test.d.ts.map +1 -0
- package/lib/codegen/untagged-unions.test.js +80 -0
- package/lib/codegen/untagged-unions.test.js.map +1 -0
- package/lib/error-category.d.ts.map +1 -1
- package/lib/error-category.js.map +1 -1
- package/lib/errors.d.ts +2 -1
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +9 -4
- package/lib/errors.js.map +1 -1
- package/lib/fixtures/xml/upstream-validator.json +397 -0
- package/lib/graphql.d.ts +292 -205
- package/lib/graphql.d.ts.map +1 -1
- package/lib/graphql.js +945 -636
- package/lib/graphql.js.map +1 -1
- package/lib/graphql.test.js +135 -764
- package/lib/graphql.test.js.map +1 -1
- package/lib/graphql.types.d.ts +10 -0
- package/lib/graphql.types.d.ts.map +1 -1
- package/lib/graphql.types.js +4 -44
- package/lib/graphql.types.js.map +1 -1
- package/lib/index.d.ts +27 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +27 -0
- package/lib/index.js.map +1 -0
- package/lib/json-patch.d.ts +13 -6
- package/lib/json-patch.d.ts.map +1 -1
- package/lib/json-patch.js +34 -19
- package/lib/json-patch.js.map +1 -1
- package/lib/json-patch.test.d.ts +2 -0
- package/lib/json-patch.test.d.ts.map +1 -0
- package/lib/json-patch.test.js +65 -0
- package/lib/json-patch.test.js.map +1 -0
- package/lib/pagination.d.ts +2 -1
- package/lib/pagination.d.ts.map +1 -1
- package/lib/pagination.js +28 -30
- package/lib/pagination.js.map +1 -1
- package/lib/pagination.test.d.ts +2 -0
- package/lib/pagination.test.d.ts.map +1 -0
- package/lib/pagination.test.js +131 -0
- package/lib/pagination.test.js.map +1 -0
- package/lib/protocol-http.d.ts +30 -16
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-http.js +133 -84
- package/lib/protocol-http.js.map +1 -1
- package/lib/protocol-http.test.js +141 -1
- package/lib/protocol-http.test.js.map +1 -1
- package/lib/protocol-rest.d.ts +18 -1
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/protocol-rest.js +32 -21
- package/lib/protocol-rest.js.map +1 -1
- package/lib/protocol-rest.test.d.ts +2 -0
- package/lib/protocol-rest.test.d.ts.map +1 -0
- package/lib/protocol-rest.test.js +498 -0
- package/lib/protocol-rest.test.js.map +1 -0
- package/lib/query.d.ts +29 -0
- package/lib/query.d.ts.map +1 -0
- package/lib/query.js +27 -0
- package/lib/query.js.map +1 -0
- package/lib/response-validation.d.ts +67 -0
- package/lib/response-validation.d.ts.map +1 -0
- package/lib/response-validation.js +76 -0
- package/lib/response-validation.js.map +1 -0
- package/lib/response-validation.test.d.ts +2 -0
- package/lib/response-validation.test.d.ts.map +1 -0
- package/lib/response-validation.test.js +72 -0
- package/lib/response-validation.test.js.map +1 -0
- package/lib/retry-after.d.ts.map +1 -1
- package/lib/retry-after.js +1 -1
- package/lib/retry-after.js.map +1 -1
- package/lib/retry-after.test.d.ts +2 -0
- package/lib/retry-after.test.d.ts.map +1 -0
- package/lib/retry-after.test.js +204 -0
- package/lib/retry-after.test.js.map +1 -0
- package/lib/retry.d.ts.map +1 -1
- package/lib/retry.js +1 -2
- package/lib/retry.js.map +1 -1
- package/lib/retry.test.d.ts +2 -0
- package/lib/retry.test.d.ts.map +1 -0
- package/lib/retry.test.js +407 -0
- package/lib/retry.test.js.map +1 -0
- package/lib/sdks.test.d.ts +2 -0
- package/lib/sdks.test.d.ts.map +1 -0
- package/lib/sdks.test.js +76 -0
- package/lib/sdks.test.js.map +1 -0
- package/lib/testing.d.ts +39 -0
- package/lib/testing.d.ts.map +1 -0
- package/lib/testing.js +41 -0
- package/lib/testing.js.map +1 -0
- package/lib/trait.d.ts +29 -9
- package/lib/trait.d.ts.map +1 -1
- package/lib/trait.js +8 -0
- package/lib/trait.js.map +1 -1
- package/lib/xml.d.ts +44 -0
- package/lib/xml.d.ts.map +1 -0
- package/lib/xml.js +311 -0
- package/lib/xml.js.map +1 -0
- package/lib/xml.test.d.ts +2 -0
- package/lib/xml.test.d.ts.map +1 -0
- package/lib/xml.test.js +210 -0
- package/lib/xml.test.js.map +1 -0
- package/package.json +8 -11
- package/src/api.ts +38 -55
- package/src/category.ts +21 -50
- package/src/codegen/boolean-string-enums.test.ts +148 -17
- package/src/codegen/boolean-string-enums.ts +81 -32
- package/src/codegen/cli.ts +29 -47
- package/src/codegen/defer-naming.test.ts +113 -0
- package/src/codegen/emit.ts +2 -5
- package/src/codegen/format.ts +12 -10
- package/src/codegen/generated-at.test.ts +89 -0
- package/src/codegen/generated-at.ts +88 -0
- package/src/codegen/generator.test.ts +137 -0
- package/src/codegen/generator.ts +132 -193
- package/src/codegen/graphql-client.test.ts +100 -297
- package/src/codegen/graphql-client.ts +302 -210
- package/src/codegen/graphql.ts +22 -94
- package/src/codegen/model-diff.ts +67 -0
- package/src/codegen/naming.ts +1 -2
- package/src/codegen/openapi-binary.test.ts +91 -0
- package/src/codegen/openapi-cli.ts +38 -79
- package/src/codegen/openapi.ts +98 -133
- package/src/codegen/operations.ts +2 -5
- package/src/codegen/pagination.ts +4 -11
- package/src/codegen/patch-audit.test.ts +160 -0
- package/src/codegen/patch-audit.ts +480 -0
- package/src/codegen/patches.test.ts +73 -15
- package/src/codegen/patches.ts +389 -99
- package/src/codegen/prelude.ts +1 -1
- package/src/codegen/proto.ts +18 -54
- package/src/codegen/protocol-imports.test.ts +39 -0
- package/src/codegen/rewrite-operation-ids.test.ts +23 -114
- package/src/codegen/rewrite-operation-ids.ts +111 -98
- package/src/codegen/spec-path.ts +3 -6
- package/src/codegen/untagged-unions.test.ts +85 -0
- package/src/error-category.ts +5 -17
- package/src/errors.ts +18 -30
- package/src/fixtures/xml/upstream-validator.json +397 -0
- package/src/graphql.test.ts +173 -949
- package/src/graphql.ts +1468 -1186
- package/src/graphql.types.ts +78 -164
- package/src/index.ts +26 -0
- package/src/json-patch.test.ts +77 -0
- package/src/json-patch.ts +54 -60
- package/src/pagination.test.ts +169 -0
- package/src/pagination.ts +46 -103
- package/src/protocol-http.test.ts +178 -9
- package/src/protocol-http.ts +174 -163
- package/src/protocol-rest.test.ts +703 -0
- package/src/protocol-rest.ts +76 -65
- package/src/query.ts +39 -0
- package/src/response-validation.test.ts +89 -0
- package/src/response-validation.ts +107 -0
- package/src/retry-after.test.ts +267 -0
- package/src/retry-after.ts +4 -10
- package/src/retry.test.ts +566 -0
- package/src/retry.ts +6 -21
- package/src/sdks.test.ts +87 -0
- package/src/testing.ts +72 -0
- package/src/trait.ts +48 -63
- package/src/xml.test.ts +251 -0
- package/src/xml.ts +323 -0
- package/lib/graphql.fixture.d.ts +0 -249
- package/lib/graphql.fixture.d.ts.map +0 -1
- package/lib/graphql.fixture.js +0 -240
- package/lib/graphql.fixture.js.map +0 -1
- package/src/graphql.fixture.ts +0 -371
package/src/graphql.ts
CHANGED
|
@@ -1,217 +1,97 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* GraphQL Query algebra — the runtime generated GraphQL SDKs target.
|
|
3
|
+
*
|
|
4
|
+
* ── Why this exists ────────────────────────────────────────────────────────
|
|
5
|
+
* A GraphQL document is a *selection*, not an RPC. Distilled used to bake a
|
|
6
|
+
* max-depth selection into every operation (`Railway.me({})` downloaded the
|
|
7
|
+
* world). This module instead treats every field as a lazy `Query<Value>`:
|
|
8
|
+
* reading `user.email` records that field, and nothing is posted until
|
|
9
|
+
* `Query.fn` evaluates the plan you returned.
|
|
10
|
+
*
|
|
11
|
+
* ── The two phases ─────────────────────────────────────────────────────────
|
|
12
|
+
* 1. Build (your function). `Railway.me()` / `user.email` / `Query.map` do
|
|
13
|
+
* not talk to the network. They construct an expression tree:
|
|
14
|
+
* Of | Map | Filter | FlatMap | Prop | Root
|
|
15
|
+
* The inner function of `Query.fn` is therefore a *builder*, not an
|
|
16
|
+
* Effect generator. No `yield*` inside it.
|
|
17
|
+
*
|
|
18
|
+
* 2. Evaluate (`Query.fn`). Walk the returned plan, paint every GraphQL
|
|
19
|
+
* field that appears onto one selection forest, POST that document
|
|
20
|
+
* once through {@link GqlTransport}, then interpret Map/Filter/FlatMap
|
|
21
|
+
* against the JSON. Effects reached via FlatMap (e.g.
|
|
22
|
+
* `usernameIsAvailable(name)`) run *after* the POST, with real values.
|
|
23
|
+
*
|
|
24
|
+
* ── Combinators ────────────────────────────────────────────────────────────
|
|
25
|
+
* - `Query.of(x)` — a literal; never selected.
|
|
26
|
+
* - `Query.map` on a list — callback receives `Query<Item>` so `p.name` is
|
|
27
|
+
* still a Query (selected). On a scalar, callback receives the value
|
|
28
|
+
* after extract (`stars => stars > 5`). Relay connections (`edges { node }`)
|
|
29
|
+
* are lists of the node type, so `projects({ first: 20 }).pipe(Query.map)`
|
|
30
|
+
* maps projects, not edges.
|
|
31
|
+
* - `Query.filter` — predicate is `Query<Item> => Query<boolean>`; the
|
|
32
|
+
* boolean Query is walked for fields, then run per row after the POST.
|
|
33
|
+
* - `Query.flatMap` — after extract, run `(value) => Effect | Query`.
|
|
34
|
+
* - `Query.pages` / `Query.items` — a Stream over every page / node of a
|
|
35
|
+
* Relay connection, one POST per page (see "Pagination").
|
|
36
|
+
*
|
|
37
|
+
* ── Types ──────────────────────────────────────────────────────────────────
|
|
38
|
+
* `Query<Value>` is `QueryNode<Value>` plus the GraphQL fields of `Value`,
|
|
39
|
+
* so `user.name` type-checks. That copy is a circular type alias
|
|
40
|
+
* (`Query<User>` contains `Query<Project[]>` which contains `Query<User>`
|
|
41
|
+
* again). TypeScript leaves the cycle lazy; there is no depth cap.
|
|
42
|
+
*
|
|
43
|
+
* ── Transport ──────────────────────────────────────────────────────────────
|
|
44
|
+
* {@link GqlTransport.execute} posts `{ query, variables, operationName }`.
|
|
45
|
+
* The Effect it returns may require Credentials / HttpClient; those leak
|
|
46
|
+
* into `Query.fn`'s requirements. It returns the parsed `data` and raw
|
|
47
|
+
* `errors`; `Query.fn` classifies the errors (see "Errors" below). Compile
|
|
48
|
+
* failures are {@link GqlError} defects.
|
|
49
|
+
*
|
|
50
|
+
* Generated SDKs export *roots* (`Railway.me`, `Railway.project`).
|
|
51
|
+
* Combinators live in `@distilled.cloud/core/query`.
|
|
52
|
+
*/
|
|
53
|
+
import * as Context from "effect/Context";
|
|
2
54
|
import * as Data from "effect/Data";
|
|
3
55
|
import * as Effect from "effect/Effect";
|
|
4
56
|
import * as Option from "effect/Option";
|
|
5
|
-
import * as S from "effect/Schema";
|
|
6
57
|
import * as Schedule from "effect/Schedule";
|
|
58
|
+
import * as S from "effect/Schema";
|
|
7
59
|
import * as Stream from "effect/Stream";
|
|
8
|
-
import {
|
|
9
|
-
Kind,
|
|
10
|
-
parseType,
|
|
11
|
-
print,
|
|
12
|
-
type FieldNode,
|
|
13
|
-
type SelectionNode,
|
|
14
|
-
type VariableDefinitionNode,
|
|
15
|
-
} from "graphql";
|
|
16
|
-
import type { GraphQLModel, GraphQLField } from "./codegen/graphql-client.ts";
|
|
17
|
-
|
|
18
|
-
export type { GraphQLModel } from "./codegen/graphql-client.ts";
|
|
19
|
-
|
|
20
|
-
/** A generated field's arguments, GraphQL output reference, and error tags. */
|
|
21
|
-
export interface Field<Args, Ref extends string, E extends string = never> {
|
|
22
|
-
readonly args: Args;
|
|
23
|
-
readonly type: Ref;
|
|
24
|
-
readonly errors: E;
|
|
25
|
-
}
|
|
26
60
|
|
|
27
|
-
export
|
|
28
|
-
|
|
29
|
-
scalars: Record<string, unknown>;
|
|
30
|
-
errors: Record<string, GraphQLIssue>;
|
|
31
|
-
possibleTypes: Record<string, string>;
|
|
32
|
-
query: string;
|
|
33
|
-
mutation: string;
|
|
34
|
-
subscription: string;
|
|
35
|
-
globalErrors: string;
|
|
36
|
-
}
|
|
61
|
+
export const QuerySymbol = Symbol.for("@distilled.cloud/graphql/Query");
|
|
62
|
+
const inspect = Symbol.for("nodejs.util.inspect.custom");
|
|
37
63
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
: {};
|
|
46
|
-
type TypeOf<F> = F extends Field<any, infer T, any> ? T : never;
|
|
47
|
-
type ArgsOf<F> = F extends Field<infer A, any, any> ? A : never;
|
|
48
|
-
type TagsOf<F> = F extends Field<any, any, infer E> ? E : never;
|
|
49
|
-
type Where<A> = {} extends A ? { readonly where?: A } : { readonly where: A };
|
|
50
|
-
type Directives = { readonly $include?: boolean; readonly $skip?: boolean };
|
|
51
|
-
type FieldSelection<C extends Schema, F> =
|
|
52
|
-
Named<TypeOf<F>> extends keyof C["scalars"]
|
|
53
|
-
?
|
|
54
|
-
| ({} extends ArgsOf<F> ? boolean : never)
|
|
55
|
-
| (Where<ArgsOf<F>> & Directives & { readonly select?: true })
|
|
56
|
-
:
|
|
57
|
-
| (keyof ArgsOf<F> extends never
|
|
58
|
-
? Selection<C, Named<TypeOf<F>>>
|
|
59
|
-
: never)
|
|
60
|
-
| (Where<ArgsOf<F>> &
|
|
61
|
-
Directives & { readonly select: Selection<C, Named<TypeOf<F>>> });
|
|
62
|
-
type Alias<C extends Schema, N extends string> = {
|
|
63
|
-
[K in keyof Fields<C, N>]: {
|
|
64
|
-
readonly [P in K]: FieldSelection<C, Fields<C, N>[K]>;
|
|
65
|
-
};
|
|
66
|
-
}[keyof Fields<C, N>];
|
|
67
|
-
|
|
68
|
-
/** Mobius-style field selection. Arguments are passed in `where`. */
|
|
69
|
-
export type Selection<C extends Schema, N extends string> = {
|
|
70
|
-
readonly [K in keyof Fields<C, N>]?: FieldSelection<C, Fields<C, N>[K]>;
|
|
71
|
-
} & {
|
|
72
|
-
readonly __typename?: boolean;
|
|
73
|
-
readonly __alias?: Readonly<Record<string, Alias<C, N>>>;
|
|
74
|
-
readonly __on?: N extends keyof C["possibleTypes"]
|
|
75
|
-
? { readonly [K in C["possibleTypes"][N]]?: Selection<C, K> }
|
|
76
|
-
: never;
|
|
77
|
-
};
|
|
78
|
-
type Selected<Q> = Q extends { readonly select: infer P } ? P : Q;
|
|
79
|
-
type Keys<Q> = {
|
|
80
|
-
[K in keyof Q]: Q[K] extends false | undefined ? never : K;
|
|
81
|
-
}[keyof Q];
|
|
82
|
-
type Simplify<A> = { [K in keyof A]: A[K] };
|
|
83
|
-
type AliasValue<C extends Schema, N extends string, Q> = {
|
|
84
|
-
[K in Extract<Keys<Q>, keyof Fields<C, N>>]: Result<
|
|
85
|
-
C,
|
|
86
|
-
TypeOf<Fields<C, N>[K]>,
|
|
87
|
-
Selected<Q[K]>
|
|
88
|
-
>;
|
|
89
|
-
}[Extract<Keys<Q>, keyof Fields<C, N>>];
|
|
90
|
-
type AliasResult<C extends Schema, N extends string, Q> = Q extends {
|
|
91
|
-
readonly __alias: infer A;
|
|
64
|
+
/** A plan that cannot be compiled (a programming error, raised as a defect). */
|
|
65
|
+
export class GqlError {
|
|
66
|
+
readonly _tag = "GqlError" as const;
|
|
67
|
+
readonly message: string;
|
|
68
|
+
constructor(message: string) {
|
|
69
|
+
this.message = message;
|
|
70
|
+
}
|
|
92
71
|
}
|
|
93
|
-
? Simplify<
|
|
94
|
-
{
|
|
95
|
-
[
|
|
96
|
-
K in keyof A as Conditional<A[K][keyof A[K]]> extends true ? never : K
|
|
97
|
-
]: AliasValue<C, N, A[K]>;
|
|
98
|
-
} & {
|
|
99
|
-
[
|
|
100
|
-
K in keyof A as Conditional<A[K][keyof A[K]]> extends true ? K : never
|
|
101
|
-
]?: AliasValue<C, N, A[K]>;
|
|
102
|
-
}
|
|
103
|
-
>
|
|
104
|
-
: {};
|
|
105
|
-
type Conditional<Q> = boolean extends Q
|
|
106
|
-
? true
|
|
107
|
-
: Q extends { readonly $include: infer I }
|
|
108
|
-
? [I] extends [true]
|
|
109
|
-
? Q extends { readonly $skip: infer S }
|
|
110
|
-
? [S] extends [false]
|
|
111
|
-
? false
|
|
112
|
-
: true
|
|
113
|
-
: false
|
|
114
|
-
: true
|
|
115
|
-
: Q extends { readonly $skip: infer S }
|
|
116
|
-
? [S] extends [false]
|
|
117
|
-
? false
|
|
118
|
-
: true
|
|
119
|
-
: false;
|
|
120
|
-
type ObjectFields<C extends Schema, N extends string, Q> = {
|
|
121
|
-
[
|
|
122
|
-
K in Extract<Keys<Q>, keyof Fields<C, N>> as Conditional<Q[K]> extends true
|
|
123
|
-
? never
|
|
124
|
-
: K
|
|
125
|
-
]: Result<C, TypeOf<Fields<C, N>[K]>, Selected<Q[K]>>;
|
|
126
|
-
} & {
|
|
127
|
-
[
|
|
128
|
-
K in Extract<Keys<Q>, keyof Fields<C, N>> as Conditional<Q[K]> extends true
|
|
129
|
-
? K
|
|
130
|
-
: never
|
|
131
|
-
]?: Result<C, TypeOf<Fields<C, N>[K]>, Selected<Q[K]>>;
|
|
132
|
-
};
|
|
133
|
-
type ObjectResult<C extends Schema, N extends string, Q> = Simplify<
|
|
134
|
-
ObjectFields<C, N, Q> &
|
|
135
|
-
(Q extends { readonly __typename: true } ? { __typename: N } : {}) &
|
|
136
|
-
AliasResult<C, N, Q>
|
|
137
|
-
>;
|
|
138
|
-
type Branch<
|
|
139
|
-
C extends Schema,
|
|
140
|
-
N extends string,
|
|
141
|
-
Q,
|
|
142
|
-
T extends string,
|
|
143
|
-
> = T extends unknown
|
|
144
|
-
? Simplify<
|
|
145
|
-
Omit<ObjectResult<C, N, Q>, "__typename"> &
|
|
146
|
-
(Q extends { readonly __on: infer O }
|
|
147
|
-
? T extends keyof O
|
|
148
|
-
? ObjectResult<C, T, O[T]>
|
|
149
|
-
: {}
|
|
150
|
-
: {}) & { __typename: T }
|
|
151
|
-
>
|
|
152
|
-
: never;
|
|
153
|
-
type Value<C extends Schema, T extends string, Q> = T extends `[${infer I}]`
|
|
154
|
-
? Array<Result<C, I, Q>>
|
|
155
|
-
: T extends keyof C["scalars"]
|
|
156
|
-
? C["scalars"][T]
|
|
157
|
-
: T extends keyof C["possibleTypes"]
|
|
158
|
-
? Branch<C, T, Q, C["possibleTypes"][T]>
|
|
159
|
-
: ObjectResult<C, T, Q>;
|
|
160
|
-
/** Selected output, preserving list and nullable wrappers. */
|
|
161
|
-
export type Result<
|
|
162
|
-
C extends Schema,
|
|
163
|
-
Ref extends string,
|
|
164
|
-
Q,
|
|
165
|
-
> = Ref extends `${infer T}!` ? Value<C, T, Q> : Value<C, Ref, Q> | null;
|
|
166
|
-
type SelectionTags<C extends Schema, N extends string, Q> = string extends N
|
|
167
|
-
? string
|
|
168
|
-
: Q extends object
|
|
169
|
-
?
|
|
170
|
-
| {
|
|
171
|
-
[K in Extract<Keys<Q>, keyof Fields<C, N>>]:
|
|
172
|
-
| TagsOf<Fields<C, N>[K]>
|
|
173
|
-
| SelectionTags<
|
|
174
|
-
C,
|
|
175
|
-
Named<TypeOf<Fields<C, N>[K]>>,
|
|
176
|
-
Selected<Q[K]>
|
|
177
|
-
>;
|
|
178
|
-
}[Extract<Keys<Q>, keyof Fields<C, N>>]
|
|
179
|
-
| (Q extends { readonly __on: infer O }
|
|
180
|
-
? { [K in keyof O & string]: SelectionTags<C, K, O[K]> }[keyof O &
|
|
181
|
-
string]
|
|
182
|
-
: never)
|
|
183
|
-
| (Q extends { readonly __alias: infer A }
|
|
184
|
-
? { [K in keyof A]: SelectionTags<C, N, A[K]> }[keyof A]
|
|
185
|
-
: never)
|
|
186
|
-
: never;
|
|
187
|
-
/** Known selected errors plus provider-wide errors and an honest fallback. */
|
|
188
|
-
export type Errors<C extends Schema, N extends string, Q> =
|
|
189
|
-
| (SelectionTags<C, N, Q> extends infer Tags
|
|
190
|
-
? C["errors"][Extract<C["globalErrors"] | Tags, keyof C["errors"]>]
|
|
191
|
-
: never)
|
|
192
|
-
| UnknownGraphQLError;
|
|
193
|
-
type Root<C extends Schema, K extends OperationKind> = K extends "query"
|
|
194
|
-
? C["query"]
|
|
195
|
-
: C["mutation"];
|
|
196
|
-
type OperationSelection<
|
|
197
|
-
C extends Schema,
|
|
198
|
-
N extends string,
|
|
199
|
-
K extends keyof Fields<C, N>,
|
|
200
|
-
Q,
|
|
201
|
-
> = { [P in K]: { select: Q } };
|
|
202
72
|
|
|
73
|
+
// ── Errors ──────────────────────────────────────────────────────────────────
|
|
74
|
+
//
|
|
75
|
+
// Every entry of a GraphQL `errors` array becomes one typed issue. Generated
|
|
76
|
+
// SDKs declare tagged error classes plus the matchers that recognize them,
|
|
77
|
+
// scoped to the root fields that can return them (or global). `Query.fn`
|
|
78
|
+
// classifies each entry against the roots its path points at, so the error
|
|
79
|
+
// channel is the union of the errors declared by the roots the plan reads.
|
|
80
|
+
|
|
81
|
+
/** Fields every classified GraphQL error carries. */
|
|
203
82
|
export const errorFields = {
|
|
204
83
|
message: S.String,
|
|
205
84
|
code: S.optional(S.String),
|
|
206
85
|
path: S.optional(S.Array(S.Union([S.String, S.Number]))),
|
|
207
|
-
locations: S.optional(
|
|
208
|
-
S.Array(S.Struct({ line: S.Number, column: S.Number })),
|
|
209
|
-
),
|
|
86
|
+
locations: S.optional(S.Array(S.Struct({ line: S.Number, column: S.Number }))),
|
|
210
87
|
extensions: S.optional(S.Unknown),
|
|
211
88
|
traceId: S.optional(S.String),
|
|
212
89
|
status: S.optional(S.Number),
|
|
90
|
+
/** Server retry hint in seconds. */
|
|
213
91
|
retryAfter: S.optional(S.Number),
|
|
214
92
|
};
|
|
93
|
+
|
|
94
|
+
/** The shape shared by every classified GraphQL error. */
|
|
215
95
|
export interface GraphQLIssue {
|
|
216
96
|
readonly _tag: string;
|
|
217
97
|
readonly message: string;
|
|
@@ -224,649 +104,1174 @@ export interface GraphQLIssue {
|
|
|
224
104
|
readonly extensions?: unknown;
|
|
225
105
|
readonly traceId?: string;
|
|
226
106
|
readonly status?: number;
|
|
227
|
-
/** Server retry hint in seconds. */
|
|
228
107
|
readonly retryAfter?: number;
|
|
229
108
|
}
|
|
109
|
+
|
|
110
|
+
export type GraphQLIssueProps = Omit<GraphQLIssue, "_tag">;
|
|
111
|
+
|
|
112
|
+
/** A GraphQL error no declared matcher recognizes. */
|
|
230
113
|
export class UnknownGraphQLError extends S.TaggedError<UnknownGraphQLError>()(
|
|
231
114
|
"UnknownGraphQLError",
|
|
232
115
|
{
|
|
233
116
|
...errorFields,
|
|
117
|
+
/** Root field the error path points at, when the path is known. */
|
|
234
118
|
coordinate: S.optional(S.String),
|
|
235
119
|
},
|
|
236
120
|
) {}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
121
|
+
|
|
122
|
+
/** One response carried errors with different tags; none is hidden. */
|
|
123
|
+
export class GraphQLFailure<E extends GraphQLIssue = GraphQLIssue> extends Data.TaggedError(
|
|
124
|
+
"GraphQLFailure",
|
|
125
|
+
)<{
|
|
241
126
|
readonly errors: readonly [E, ...E[]];
|
|
242
127
|
readonly data: unknown;
|
|
243
|
-
readonly status
|
|
128
|
+
readonly status?: number;
|
|
244
129
|
}> {
|
|
245
130
|
get message(): string {
|
|
246
131
|
return this.errors
|
|
247
|
-
.map(
|
|
248
|
-
(e) =>
|
|
249
|
-
`${e._tag}${e.path?.length ? ` at ${e.path.join(".")}` : ""}: ${e.message}`,
|
|
250
|
-
)
|
|
132
|
+
.map((e) => `${e._tag}${e.path?.length ? ` at ${e.path.join(".")}` : ""}: ${e.message}`)
|
|
251
133
|
.join("; ");
|
|
252
134
|
}
|
|
253
135
|
}
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
)<{
|
|
136
|
+
|
|
137
|
+
/** The request never produced a GraphQL response (network, HTTP, non-JSON). */
|
|
138
|
+
export class GraphQLTransportError extends Data.TaggedError("GraphQLTransportError")<{
|
|
257
139
|
readonly message: string;
|
|
258
|
-
readonly cause?: unknown;
|
|
259
140
|
readonly status?: number;
|
|
141
|
+
/** Server retry hint in seconds. */
|
|
260
142
|
readonly retryAfter?: number;
|
|
143
|
+
readonly cause?: unknown;
|
|
261
144
|
}> {}
|
|
262
|
-
|
|
145
|
+
|
|
146
|
+
/** A paginated connection reported more pages without a new cursor. */
|
|
147
|
+
export class GraphQLPaginationError extends Data.TaggedError("GraphQLPaginationError")<{
|
|
263
148
|
readonly message: string;
|
|
264
|
-
readonly
|
|
265
|
-
readonly cause?: unknown;
|
|
149
|
+
readonly cursor: string | null;
|
|
266
150
|
}> {}
|
|
267
|
-
export class GraphQLRequestError extends Data.TaggedError(
|
|
268
|
-
"GraphQLRequestError",
|
|
269
|
-
)<{ readonly message: string }> {}
|
|
270
|
-
export type ClientError =
|
|
271
|
-
| GraphQLTransportError
|
|
272
|
-
| GraphQLDecodeError
|
|
273
|
-
| GraphQLRequestError;
|
|
274
|
-
type IssueOf<E> = E extends GraphQLFailure<infer I> ? I : never;
|
|
275
|
-
/** True only when every issue has an allowed tag; mixed failures are never hidden. */
|
|
276
|
-
export const isErrorTag = (
|
|
277
|
-
error: unknown,
|
|
278
|
-
tags: string | readonly string[],
|
|
279
|
-
): boolean => {
|
|
280
|
-
const allowed = typeof tags === "string" ? [tags] : tags;
|
|
281
|
-
return (
|
|
282
|
-
error instanceof GraphQLFailure &&
|
|
283
|
-
error.errors.length > 0 &&
|
|
284
|
-
error.errors.every((issue) => allowed.includes(issue._tag))
|
|
285
|
-
);
|
|
286
|
-
};
|
|
287
|
-
/** Recover only an aggregate whose every issue matches. The original aggregate is also supplied. */
|
|
288
|
-
export const catchTags =
|
|
289
|
-
<const T extends readonly string[] | string, B, E2, R2>(
|
|
290
|
-
tags: T,
|
|
291
|
-
handler: (
|
|
292
|
-
error: GraphQLIssue & { readonly _tag: T extends string ? T : T[number] },
|
|
293
|
-
failure: GraphQLFailure,
|
|
294
|
-
) => Effect.Effect<B, E2, R2>,
|
|
295
|
-
) =>
|
|
296
|
-
<A, E, R>(
|
|
297
|
-
self: Effect.Effect<A, E, R>,
|
|
298
|
-
): Effect.Effect<A | B, E | E2, R | R2> =>
|
|
299
|
-
self.pipe(
|
|
300
|
-
Effect.catch((error): Effect.Effect<B, E | E2, R2> =>
|
|
301
|
-
isErrorTag(error, tags)
|
|
302
|
-
? handler(
|
|
303
|
-
(error as GraphQLFailure).errors[0] as any,
|
|
304
|
-
error as GraphQLFailure,
|
|
305
|
-
)
|
|
306
|
-
: Effect.fail(error),
|
|
307
|
-
),
|
|
308
|
-
);
|
|
309
151
|
|
|
310
|
-
|
|
311
|
-
export interface
|
|
312
|
-
readonly
|
|
313
|
-
readonly
|
|
314
|
-
readonly
|
|
315
|
-
|
|
152
|
+
/** Recognizes a raw GraphQL error. Every present property must match. */
|
|
153
|
+
export interface ErrorMatcher {
|
|
154
|
+
readonly code?: string;
|
|
155
|
+
readonly message?: string;
|
|
156
|
+
readonly messageIncludes?: string;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Runtime description of one generated error class. */
|
|
160
|
+
export interface ErrorSpec<E extends GraphQLIssue = GraphQLIssue> {
|
|
161
|
+
readonly tag: E["_tag"];
|
|
162
|
+
readonly make: (props: GraphQLIssueProps) => E;
|
|
163
|
+
readonly matchers: ReadonlyArray<ErrorMatcher>;
|
|
164
|
+
/** Queries failing only with retryable errors are retried. */
|
|
165
|
+
readonly retryable: boolean;
|
|
166
|
+
/** Applies to every root, including errors that carry no path. */
|
|
167
|
+
readonly global: boolean;
|
|
316
168
|
}
|
|
169
|
+
|
|
170
|
+
export const errorSpec = <E extends GraphQLIssue>(
|
|
171
|
+
make: new (props: GraphQLIssueProps) => E,
|
|
172
|
+
tag: E["_tag"],
|
|
173
|
+
matchers: ReadonlyArray<ErrorMatcher>,
|
|
174
|
+
options: { readonly retryable?: boolean; readonly global?: boolean } = {},
|
|
175
|
+
): ErrorSpec<E> => ({
|
|
176
|
+
tag,
|
|
177
|
+
make: (props) => new make(props),
|
|
178
|
+
matchers,
|
|
179
|
+
retryable: options.retryable ?? false,
|
|
180
|
+
global: options.global ?? false,
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
/** An entry of a GraphQL response's `errors` array, as sent on the wire. */
|
|
184
|
+
export interface RawGraphQLError {
|
|
185
|
+
readonly message: string;
|
|
186
|
+
readonly path?: ReadonlyArray<string | number>;
|
|
187
|
+
readonly locations?: ReadonlyArray<{
|
|
188
|
+
readonly line: number;
|
|
189
|
+
readonly column: number;
|
|
190
|
+
}>;
|
|
191
|
+
readonly extensions?: Record<string, unknown>;
|
|
192
|
+
readonly [key: string]: unknown;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** What a transport returns once it has a GraphQL response body. */
|
|
317
196
|
export interface GraphQLResponse {
|
|
318
|
-
readonly
|
|
319
|
-
readonly
|
|
320
|
-
readonly
|
|
197
|
+
readonly data?: unknown;
|
|
198
|
+
readonly errors?: ReadonlyArray<RawGraphQLError>;
|
|
199
|
+
readonly status?: number;
|
|
200
|
+
readonly headers?: Readonly<Record<string, string | undefined>>;
|
|
321
201
|
}
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
readonly
|
|
334
|
-
readonly
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
202
|
+
|
|
203
|
+
export type ArgMeta = Record<string, string>;
|
|
204
|
+
|
|
205
|
+
export type FieldMeta = {
|
|
206
|
+
readonly name: string;
|
|
207
|
+
readonly kind: "scalar" | "object" | "list" | "connection";
|
|
208
|
+
readonly of?: TypeMeta;
|
|
209
|
+
readonly argTypes?: ArgMeta;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
export type TypeMeta = {
|
|
213
|
+
readonly name: string;
|
|
214
|
+
readonly fields: Record<string, FieldMeta>;
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
export const scalarField = (name: string): FieldMeta => ({
|
|
218
|
+
name,
|
|
219
|
+
kind: "scalar",
|
|
220
|
+
});
|
|
221
|
+
export const objectField = (name: string, objectType: TypeMeta): FieldMeta => ({
|
|
222
|
+
name,
|
|
223
|
+
kind: "object",
|
|
224
|
+
of: objectType,
|
|
225
|
+
});
|
|
226
|
+
export const listField = (name: string, itemType: TypeMeta, argTypes?: ArgMeta): FieldMeta => ({
|
|
227
|
+
name,
|
|
228
|
+
kind: "list",
|
|
229
|
+
of: itemType,
|
|
230
|
+
argTypes,
|
|
231
|
+
});
|
|
232
|
+
/** Relay connection: GraphQL `edges { node }` presented as `Query<Item[]>`. */
|
|
233
|
+
export const connectionField = (
|
|
234
|
+
name: string,
|
|
235
|
+
nodeType: TypeMeta,
|
|
236
|
+
argTypes?: ArgMeta,
|
|
237
|
+
): FieldMeta => ({
|
|
238
|
+
name,
|
|
239
|
+
kind: "connection",
|
|
240
|
+
of: nodeType,
|
|
241
|
+
argTypes,
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
export type TypeRef =
|
|
245
|
+
| { readonly tag: "scalar" }
|
|
246
|
+
| { readonly tag: "object"; readonly meta: TypeMeta }
|
|
247
|
+
| { readonly tag: "list"; readonly of: TypeRef };
|
|
248
|
+
|
|
249
|
+
const objectRef = (meta: TypeMeta): TypeRef => ({ tag: "object", meta });
|
|
250
|
+
const listRef = (itemType: TypeRef): TypeRef => ({
|
|
251
|
+
tag: "list",
|
|
252
|
+
of: itemType,
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
const fieldResult = (parent: TypeRef, field: FieldMeta): TypeRef => {
|
|
256
|
+
const inner = (): TypeRef => {
|
|
257
|
+
if (field.kind === "scalar") return { tag: "scalar" };
|
|
258
|
+
if (field.kind === "object") return objectRef(field.of!);
|
|
259
|
+
return listRef(objectRef(field.of!)); // list | connection
|
|
260
|
+
};
|
|
261
|
+
return parent.tag === "list" ? listRef(fieldResult(parent.of, field)) : inner();
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
const unwrapList = (typeRef: TypeRef): TypeRef => {
|
|
265
|
+
if (typeRef.tag !== "list") throw new GqlError("expected a list Query");
|
|
266
|
+
return typeRef.of;
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
const fieldsOf = (typeRef: TypeRef): Record<string, FieldMeta> => {
|
|
270
|
+
if (typeRef.tag === "object") return typeRef.meta.fields;
|
|
271
|
+
if (typeRef.tag === "list") return fieldsOf(typeRef.of);
|
|
272
|
+
return {};
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
export interface SelNode {
|
|
276
|
+
field: string;
|
|
277
|
+
alias: string | undefined;
|
|
278
|
+
args: Record<string, string> | undefined;
|
|
279
|
+
children: Map<string, SelNode>;
|
|
280
|
+
isScalar: boolean;
|
|
281
|
+
isList: boolean;
|
|
339
282
|
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
readonly
|
|
283
|
+
|
|
284
|
+
export interface CompiledOperation {
|
|
285
|
+
readonly document: string;
|
|
286
|
+
readonly operationName: string;
|
|
287
|
+
readonly variables: Record<string, unknown>;
|
|
288
|
+
readonly kind: "query" | "mutation";
|
|
289
|
+
readonly tree: SelNode;
|
|
343
290
|
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
291
|
+
|
|
292
|
+
export class GqlTransport extends Context.Service<
|
|
293
|
+
GqlTransport,
|
|
294
|
+
{
|
|
295
|
+
readonly execute: (
|
|
296
|
+
req: CompiledOperation,
|
|
297
|
+
) => Effect.Effect<GraphQLResponse, GraphQLTransportError, any>;
|
|
298
|
+
}
|
|
299
|
+
>()("@distilled.cloud/graphql/Transport") {}
|
|
300
|
+
|
|
301
|
+
const log = (..._args: Array<unknown>): void => {};
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* GraphQL fields copied onto a Query so `user.name` type-checks.
|
|
305
|
+
* `Query<User>` contains `projects: Query<Project[]>`, which contains
|
|
306
|
+
* `owner: Query<User>` again — TypeScript leaves the cycle lazy. Fields
|
|
307
|
+
* inherit the errors of the root they were read from.
|
|
308
|
+
*/
|
|
309
|
+
type QueryFields<Value, Error> = [NonNullable<Value>] extends [ReadonlyArray<infer Item>]
|
|
310
|
+
? {
|
|
311
|
+
readonly [Field in keyof NonNullable<Item>]: Query<
|
|
312
|
+
NonNullable<Item>[Field] | Nullish<Item>,
|
|
313
|
+
Error
|
|
314
|
+
>;
|
|
315
|
+
} & {
|
|
316
|
+
(args: Record<string, unknown>): Query<Value, Error>;
|
|
317
|
+
}
|
|
318
|
+
: [NonNullable<Value>] extends [object]
|
|
319
|
+
? {
|
|
320
|
+
readonly [Field in keyof NonNullable<Value>]: Query<
|
|
321
|
+
NonNullable<Value>[Field] | Nullish<Value>,
|
|
322
|
+
Error
|
|
323
|
+
>;
|
|
324
|
+
}
|
|
325
|
+
: {};
|
|
326
|
+
|
|
327
|
+
/** A field read through a `null` parent is `null`. */
|
|
328
|
+
type Nullish<Value> = Extract<Value, null | undefined>;
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* A lazy GraphQL selection. `Value` is the plain data after `Query.fn` runs;
|
|
332
|
+
* `Error` is the union of typed errors the roots it reads can return.
|
|
333
|
+
*/
|
|
334
|
+
export type Query<Value, Error = never> = QueryNode<Value, Error> & QueryFields<Value, Error>;
|
|
335
|
+
|
|
336
|
+
/** Strip Query/Effect wrappers from a returned plan down to plain data. */
|
|
337
|
+
export type UnwrapPlan<Plan> =
|
|
338
|
+
Plan extends QueryNode<infer Value, any>
|
|
339
|
+
? Value
|
|
340
|
+
: Plan extends Effect.Effect<infer Success, any, any>
|
|
341
|
+
? Success
|
|
342
|
+
: Plan extends ReadonlyArray<infer Element>
|
|
343
|
+
? ReadonlyArray<UnwrapPlan<Element>>
|
|
344
|
+
: Plan extends object
|
|
345
|
+
? { readonly [Key in keyof Plan]: UnwrapPlan<Plan[Key]> }
|
|
346
|
+
: Plan;
|
|
347
|
+
|
|
348
|
+
/** Typed errors of every Query and Effect in a returned plan. */
|
|
349
|
+
export type PlanError<Plan> =
|
|
350
|
+
Plan extends QueryNode<any, infer Error>
|
|
351
|
+
? Error
|
|
352
|
+
: Plan extends Effect.Effect<any, infer Error, any>
|
|
353
|
+
? Error
|
|
354
|
+
: Plan extends ReadonlyArray<infer Element>
|
|
355
|
+
? PlanError<Element>
|
|
356
|
+
: Plan extends object
|
|
357
|
+
? { readonly [Key in keyof Plan]: PlanError<Plan[Key]> }[keyof Plan]
|
|
358
|
+
: never;
|
|
359
|
+
|
|
360
|
+
/** Failures of evaluating a plan whose roots declare `Error`. */
|
|
361
|
+
export type QueryError<Error> =
|
|
362
|
+
| Error
|
|
363
|
+
| GraphQLFailure<Extract<Error, GraphQLIssue> | UnknownGraphQLError>
|
|
364
|
+
| UnknownGraphQLError
|
|
365
|
+
| GraphQLTransportError;
|
|
366
|
+
|
|
367
|
+
type Expr =
|
|
368
|
+
| RootExpr
|
|
369
|
+
| PropExpr
|
|
370
|
+
| ItemExpr
|
|
371
|
+
| MapValueExpr
|
|
372
|
+
| MapItemsExpr
|
|
373
|
+
| FilterExpr
|
|
374
|
+
| FlatMapExpr
|
|
375
|
+
| LiteralExpr;
|
|
376
|
+
|
|
377
|
+
type RootExpr = {
|
|
378
|
+
readonly _tag: "Root";
|
|
379
|
+
readonly op: "query" | "mutation";
|
|
380
|
+
readonly field: string;
|
|
381
|
+
readonly args: Record<string, unknown> | undefined;
|
|
382
|
+
readonly argTypes: ArgMeta | undefined;
|
|
383
|
+
readonly type: TypeRef;
|
|
384
|
+
/** Relay connection: paint `edges { node }`, extract an array of nodes. */
|
|
385
|
+
readonly connection?: boolean;
|
|
386
|
+
/** Errors this root field can return, including global errors. */
|
|
387
|
+
readonly errors: ReadonlyArray<ErrorSpec>;
|
|
350
388
|
};
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
389
|
+
|
|
390
|
+
type PropExpr = {
|
|
391
|
+
readonly _tag: "Prop";
|
|
392
|
+
readonly parent: Expr;
|
|
393
|
+
readonly field: FieldMeta;
|
|
394
|
+
readonly type: TypeRef;
|
|
395
|
+
readonly args?: Record<string, unknown>;
|
|
354
396
|
};
|
|
355
397
|
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
398
|
+
type ItemExpr = {
|
|
399
|
+
readonly _tag: "Item";
|
|
400
|
+
readonly list: Expr;
|
|
401
|
+
readonly type: TypeRef;
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
type MapValueExpr = {
|
|
405
|
+
readonly _tag: "MapValue";
|
|
406
|
+
readonly parent: Expr;
|
|
407
|
+
readonly mapFn: (value: unknown) => unknown;
|
|
408
|
+
readonly type: TypeRef;
|
|
409
|
+
};
|
|
410
|
+
|
|
411
|
+
type MapItemsExpr = {
|
|
412
|
+
readonly _tag: "MapItems";
|
|
413
|
+
readonly parent: Expr;
|
|
414
|
+
readonly mapped: unknown;
|
|
415
|
+
/** Map one object (`null` stays `null`) instead of every list item. */
|
|
416
|
+
readonly single?: boolean;
|
|
417
|
+
readonly type: TypeRef;
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
type FilterExpr = {
|
|
421
|
+
readonly _tag: "Filter";
|
|
422
|
+
readonly parent: Expr;
|
|
423
|
+
readonly predicate: Expr;
|
|
424
|
+
readonly type: TypeRef;
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
type FlatMapExpr = {
|
|
428
|
+
readonly _tag: "FlatMap";
|
|
429
|
+
readonly parent: Expr;
|
|
430
|
+
readonly flatMapFn: (value: unknown) => unknown;
|
|
431
|
+
readonly type: TypeRef;
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
type LiteralExpr = {
|
|
435
|
+
readonly _tag: "Literal";
|
|
436
|
+
readonly value: unknown;
|
|
437
|
+
readonly type: TypeRef;
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
export class QueryNode<out Value = unknown, out Error = never> {
|
|
441
|
+
readonly [QuerySymbol] = QuerySymbol;
|
|
442
|
+
declare readonly valueType: Value;
|
|
443
|
+
declare readonly errorType: Error;
|
|
444
|
+
readonly expr: Expr;
|
|
445
|
+
constructor(expr: Expr) {
|
|
446
|
+
this.expr = expr;
|
|
447
|
+
return proxy(this) as QueryNode<Value, Error>;
|
|
367
448
|
}
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
449
|
+
pipe<Self>(this: Self): Self;
|
|
450
|
+
pipe<Self, Out1>(this: Self, step1: (_: Self) => Out1): Out1;
|
|
451
|
+
pipe<Self, Out1, Out2>(this: Self, step1: (_: Self) => Out1, step2: (_: Out1) => Out2): Out2;
|
|
452
|
+
pipe<Self, Out1, Out2, Out3>(
|
|
453
|
+
this: Self,
|
|
454
|
+
step1: (_: Self) => Out1,
|
|
455
|
+
step2: (_: Out1) => Out2,
|
|
456
|
+
step3: (_: Out2) => Out3,
|
|
457
|
+
): Out3;
|
|
458
|
+
pipe<Self, Out1, Out2, Out3, Out4>(
|
|
459
|
+
this: Self,
|
|
460
|
+
step1: (_: Self) => Out1,
|
|
461
|
+
step2: (_: Out1) => Out2,
|
|
462
|
+
step3: (_: Out2) => Out3,
|
|
463
|
+
step4: (_: Out3) => Out4,
|
|
464
|
+
): Out4;
|
|
465
|
+
pipe<Self, Out1, Out2, Out3, Out4, Out5>(
|
|
466
|
+
this: Self,
|
|
467
|
+
step1: (_: Self) => Out1,
|
|
468
|
+
step2: (_: Out1) => Out2,
|
|
469
|
+
step3: (_: Out2) => Out3,
|
|
470
|
+
step4: (_: Out3) => Out4,
|
|
471
|
+
step5: (_: Out4) => Out5,
|
|
472
|
+
): Out5;
|
|
473
|
+
pipe<Self, Out1, Out2, Out3, Out4, Out5, Out6>(
|
|
474
|
+
this: Self,
|
|
475
|
+
step1: (_: Self) => Out1,
|
|
476
|
+
step2: (_: Out1) => Out2,
|
|
477
|
+
step3: (_: Out2) => Out3,
|
|
478
|
+
step4: (_: Out3) => Out4,
|
|
479
|
+
step5: (_: Out4) => Out5,
|
|
480
|
+
step6: (_: Out5) => Out6,
|
|
481
|
+
): Out6;
|
|
482
|
+
pipe<Self, Out1, Out2, Out3, Out4, Out5, Out6, Out7>(
|
|
483
|
+
this: Self,
|
|
484
|
+
step1: (_: Self) => Out1,
|
|
485
|
+
step2: (_: Out1) => Out2,
|
|
486
|
+
step3: (_: Out2) => Out3,
|
|
487
|
+
step4: (_: Out3) => Out4,
|
|
488
|
+
step5: (_: Out4) => Out5,
|
|
489
|
+
step6: (_: Out5) => Out6,
|
|
490
|
+
step7: (_: Out6) => Out7,
|
|
491
|
+
): Out7;
|
|
492
|
+
pipe<Self, Out1, Out2, Out3, Out4, Out5, Out6, Out7, Out8>(
|
|
493
|
+
this: Self,
|
|
494
|
+
step1: (_: Self) => Out1,
|
|
495
|
+
step2: (_: Out1) => Out2,
|
|
496
|
+
step3: (_: Out2) => Out3,
|
|
497
|
+
step4: (_: Out3) => Out4,
|
|
498
|
+
step5: (_: Out4) => Out5,
|
|
499
|
+
step6: (_: Out5) => Out6,
|
|
500
|
+
step7: (_: Out6) => Out7,
|
|
501
|
+
step8: (_: Out7) => Out8,
|
|
502
|
+
): Out8;
|
|
503
|
+
pipe(...steps: Array<(_: any) => any>): unknown {
|
|
504
|
+
return steps.reduce((current, step) => step(current), this as never);
|
|
375
505
|
}
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
if (type.kind === "INPUT_OBJECT") {
|
|
379
|
-
if (!object(value)) requestError(`${at} must be an input object`);
|
|
380
|
-
const input = value as Record<string, unknown>;
|
|
381
|
-
const result: Record<string, unknown> = {};
|
|
382
|
-
for (const key of Object.keys(input))
|
|
383
|
-
if (!type.inputFields?.[key])
|
|
384
|
-
requestError(`${at}: unknown input field ${key}`);
|
|
385
|
-
for (const [key, field] of Object.entries(type.inputFields ?? {})) {
|
|
386
|
-
if (input[key] === undefined) {
|
|
387
|
-
if (field.type.endsWith("!") && field.defaultValue === undefined)
|
|
388
|
-
requestError(`${at}.${key} is required`);
|
|
389
|
-
} else
|
|
390
|
-
result[key] = encodeInput(
|
|
391
|
-
model,
|
|
392
|
-
field.type,
|
|
393
|
-
input[key],
|
|
394
|
-
`${at}.${key}`,
|
|
395
|
-
);
|
|
396
|
-
}
|
|
397
|
-
return result;
|
|
506
|
+
[inspect](): string {
|
|
507
|
+
return printExpr(this.expr);
|
|
398
508
|
}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
requestError(`${at}: invalid ${base}`);
|
|
402
|
-
} else if (type.scalar === "string" || base === "String" || base === "ID") {
|
|
403
|
-
if (typeof value !== "string") requestError(`${at} must be a string`);
|
|
404
|
-
} else if (type.scalar === "number" || base === "Int" || base === "Float") {
|
|
405
|
-
if (typeof value !== "number" || !Number.isFinite(value))
|
|
406
|
-
requestError(`${at} must be a finite number`);
|
|
407
|
-
if (
|
|
408
|
-
base === "Int" &&
|
|
409
|
-
(!Number.isInteger(value) ||
|
|
410
|
-
(value as number) < -2147483648 ||
|
|
411
|
-
(value as number) > 2147483647)
|
|
412
|
-
)
|
|
413
|
-
requestError(`${at} must be a GraphQL Int`);
|
|
414
|
-
} else if (type.scalar === "boolean" || base === "Boolean") {
|
|
415
|
-
if (typeof value !== "boolean") requestError(`${at} must be a boolean`);
|
|
509
|
+
toString(): string {
|
|
510
|
+
return this[inspect]();
|
|
416
511
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
}
|
|
433
|
-
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
export const isQuery = (value: unknown): value is Query<unknown> =>
|
|
515
|
+
(typeof value === "object" || typeof value === "function") &&
|
|
516
|
+
value !== null &&
|
|
517
|
+
QuerySymbol in value;
|
|
518
|
+
|
|
519
|
+
const make = <Value, Error = never>(expr: Expr): Query<Value, Error> =>
|
|
520
|
+
new QueryNode<Value, Error>(expr) as unknown as Query<Value, Error>;
|
|
521
|
+
|
|
522
|
+
const itemQuery = (list: QueryNode): QueryNode =>
|
|
523
|
+
new QueryNode({
|
|
524
|
+
_tag: "Item",
|
|
525
|
+
list: list.expr,
|
|
526
|
+
type: unwrapList(list.expr.type),
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
function proxy(self: QueryNode<unknown, unknown>): Query<unknown> {
|
|
530
|
+
const callable = Object.assign(function (bag?: Record<string, unknown>) {
|
|
531
|
+
return bag == null ? self : applyBag(self, bag);
|
|
532
|
+
}, self);
|
|
533
|
+
return new Proxy(callable, {
|
|
534
|
+
has: (_, prop) =>
|
|
535
|
+
prop === QuerySymbol ||
|
|
536
|
+
prop === inspect ||
|
|
537
|
+
prop in self ||
|
|
538
|
+
(typeof prop === "string" && prop in fieldsOf(self.expr.type)),
|
|
539
|
+
get: (_target, prop) => {
|
|
540
|
+
if (prop === QuerySymbol) return QuerySymbol;
|
|
541
|
+
if (prop === inspect) return self[inspect].bind(self);
|
|
542
|
+
if (prop === "pipe") return self.pipe.bind(self);
|
|
543
|
+
if (typeof prop === "string" && prop in self) {
|
|
544
|
+
const member = (self as unknown as Record<string, unknown>)[prop];
|
|
545
|
+
return typeof member === "function" ? member.bind(self) : member;
|
|
546
|
+
}
|
|
547
|
+
if (typeof prop !== "string") return undefined;
|
|
548
|
+
const field = fieldsOf(self.expr.type)[prop];
|
|
549
|
+
if (!field) return undefined;
|
|
550
|
+
return make({
|
|
551
|
+
_tag: "Prop",
|
|
552
|
+
parent: self.expr,
|
|
553
|
+
field,
|
|
554
|
+
type: fieldResult(self.expr.type, field),
|
|
555
|
+
});
|
|
556
|
+
},
|
|
557
|
+
apply: (_target, _thisArg, args) => applyBag(self, args[0] ?? {}),
|
|
558
|
+
}) as unknown as Query<unknown>;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const applyBag = <Value, Error>(
|
|
562
|
+
self: QueryNode<Value, Error>,
|
|
563
|
+
bag: Record<string, unknown>,
|
|
564
|
+
): Query<Value, Error> => {
|
|
565
|
+
const argTypes =
|
|
566
|
+
self.expr._tag === "Prop"
|
|
567
|
+
? self.expr.field.argTypes
|
|
568
|
+
: self.expr._tag === "Root"
|
|
569
|
+
? self.expr.argTypes
|
|
570
|
+
: undefined;
|
|
571
|
+
const args: Record<string, unknown> = {};
|
|
572
|
+
for (const [argName, argValue] of Object.entries(bag)) {
|
|
573
|
+
if (argTypes && argName in argTypes) args[argName] = argValue;
|
|
574
|
+
}
|
|
575
|
+
if (self.expr._tag === "Prop") {
|
|
576
|
+
return make<Value, Error>({
|
|
577
|
+
...self.expr,
|
|
578
|
+
args: { ...self.expr.args, ...args },
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
if (self.expr._tag === "Root") {
|
|
582
|
+
return make<Value, Error>({
|
|
583
|
+
...self.expr,
|
|
584
|
+
args: { ...self.expr.args, ...args },
|
|
585
|
+
});
|
|
434
586
|
}
|
|
587
|
+
return self as unknown as Query<Value, Error>;
|
|
435
588
|
};
|
|
436
589
|
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
590
|
+
export const root = <Value, Error = never>(
|
|
591
|
+
op: "query" | "mutation",
|
|
592
|
+
field: string,
|
|
593
|
+
meta: TypeMeta,
|
|
594
|
+
args?: Record<string, unknown>,
|
|
595
|
+
argTypes?: ArgMeta,
|
|
596
|
+
errors: ReadonlyArray<ErrorSpec> = [],
|
|
597
|
+
): Query<Value, Error> =>
|
|
598
|
+
make({
|
|
599
|
+
_tag: "Root",
|
|
600
|
+
op,
|
|
601
|
+
field,
|
|
602
|
+
args,
|
|
603
|
+
argTypes,
|
|
604
|
+
type: objectRef(meta),
|
|
605
|
+
errors,
|
|
606
|
+
});
|
|
607
|
+
|
|
608
|
+
export const rootList = <Item, Error = never>(
|
|
609
|
+
op: "query" | "mutation",
|
|
610
|
+
field: string,
|
|
611
|
+
meta: TypeMeta,
|
|
612
|
+
args?: Record<string, unknown>,
|
|
613
|
+
argTypes?: ArgMeta,
|
|
614
|
+
errors: ReadonlyArray<ErrorSpec> = [],
|
|
615
|
+
): Query<ReadonlyArray<Item>, Error> =>
|
|
616
|
+
make({
|
|
617
|
+
_tag: "Root",
|
|
618
|
+
op,
|
|
619
|
+
field,
|
|
620
|
+
args,
|
|
621
|
+
argTypes,
|
|
622
|
+
type: listRef(objectRef(meta)),
|
|
623
|
+
errors,
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
/** Root Relay connection: typed as `Query<Item[]>`, document uses `edges { node }`. */
|
|
627
|
+
export const rootConnection = <Item, Error = never>(
|
|
628
|
+
op: "query" | "mutation",
|
|
629
|
+
field: string,
|
|
630
|
+
meta: TypeMeta,
|
|
631
|
+
args?: Record<string, unknown>,
|
|
632
|
+
argTypes?: ArgMeta,
|
|
633
|
+
errors: ReadonlyArray<ErrorSpec> = [],
|
|
634
|
+
): Query<ReadonlyArray<Item>, Error> =>
|
|
635
|
+
make({
|
|
636
|
+
_tag: "Root",
|
|
637
|
+
op,
|
|
638
|
+
field,
|
|
639
|
+
args,
|
|
640
|
+
argTypes,
|
|
641
|
+
type: listRef(objectRef(meta)),
|
|
642
|
+
connection: true,
|
|
643
|
+
errors,
|
|
644
|
+
});
|
|
645
|
+
|
|
646
|
+
/** Root field whose GraphQL type is a scalar, enum, or list of those. */
|
|
647
|
+
export const rootLeaf = <Value, Error = never>(
|
|
648
|
+
op: "query" | "mutation",
|
|
649
|
+
field: string,
|
|
650
|
+
list: boolean,
|
|
651
|
+
args?: Record<string, unknown>,
|
|
652
|
+
argTypes?: ArgMeta,
|
|
653
|
+
errors: ReadonlyArray<ErrorSpec> = [],
|
|
654
|
+
): Query<Value, Error> =>
|
|
655
|
+
make({
|
|
656
|
+
_tag: "Root",
|
|
657
|
+
op,
|
|
658
|
+
field,
|
|
659
|
+
args,
|
|
660
|
+
argTypes,
|
|
661
|
+
type: list ? listRef({ tag: "scalar" }) : { tag: "scalar" },
|
|
662
|
+
errors,
|
|
663
|
+
});
|
|
664
|
+
|
|
665
|
+
const printExpr = (expr: Expr): string => {
|
|
666
|
+
switch (expr._tag) {
|
|
667
|
+
case "Root":
|
|
668
|
+
return expr.args ? `${expr.field}(${JSON.stringify(expr.args)})` : expr.field;
|
|
669
|
+
case "Prop":
|
|
670
|
+
return `${printExpr(expr.parent)}.${expr.field.name}`;
|
|
671
|
+
case "Item":
|
|
672
|
+
return "$item";
|
|
673
|
+
case "MapValue":
|
|
674
|
+
return `map(${printExpr(expr.parent)})`;
|
|
675
|
+
case "MapItems":
|
|
676
|
+
return `mapItems(${printExpr(expr.parent)})`;
|
|
677
|
+
case "Filter":
|
|
678
|
+
return `filter(${printExpr(expr.parent)})`;
|
|
679
|
+
case "FlatMap":
|
|
680
|
+
return `flatMap(${printExpr(expr.parent)})`;
|
|
681
|
+
case "Literal":
|
|
682
|
+
return `of(${String(expr.value)})`;
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
const emptySel = (field: string): SelNode => ({
|
|
687
|
+
field,
|
|
688
|
+
alias: undefined,
|
|
689
|
+
args: undefined,
|
|
690
|
+
children: new Map(),
|
|
691
|
+
isScalar: false,
|
|
692
|
+
isList: false,
|
|
693
|
+
});
|
|
694
|
+
|
|
695
|
+
const stableStringify = (value: unknown): string => {
|
|
696
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
697
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
|
698
|
+
const keys = Object.keys(value as object).sort();
|
|
699
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify((value as Record<string, unknown>)[key])}`).join(",")}}`;
|
|
700
|
+
};
|
|
701
|
+
|
|
702
|
+
type Forest = {
|
|
703
|
+
kind: "query" | "mutation" | undefined;
|
|
704
|
+
roots: SelNode;
|
|
705
|
+
vars: Map<string, { type: string; value: unknown }>;
|
|
706
|
+
varI: number;
|
|
707
|
+
aliasI: number;
|
|
708
|
+
rootAlias: WeakMap<object, string>;
|
|
709
|
+
/** Response key of each root → the root field and its declared errors. */
|
|
710
|
+
rootErrors: Map<string, RootErrors>;
|
|
711
|
+
};
|
|
712
|
+
|
|
713
|
+
interface RootErrors {
|
|
714
|
+
readonly field: string;
|
|
715
|
+
readonly errors: ReadonlyArray<ErrorSpec>;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
const bindArgs = (
|
|
719
|
+
forest: Forest,
|
|
720
|
+
args: Record<string, unknown> | undefined,
|
|
721
|
+
argTypes: ArgMeta | undefined,
|
|
722
|
+
): Record<string, string> | undefined => {
|
|
723
|
+
if (args === undefined) return undefined;
|
|
724
|
+
const bound: Record<string, string> = {};
|
|
725
|
+
let hasArgs = false;
|
|
726
|
+
for (const [name, value] of Object.entries(args)) {
|
|
727
|
+
if (value === undefined) continue;
|
|
728
|
+
forest.vars.set(`v${forest.varI}`, {
|
|
729
|
+
type: argTypes?.[name] ?? "String",
|
|
730
|
+
value,
|
|
456
731
|
});
|
|
457
|
-
|
|
732
|
+
bound[name] = `v${forest.varI++}`;
|
|
733
|
+
hasArgs = true;
|
|
734
|
+
}
|
|
735
|
+
return hasArgs ? bound : undefined;
|
|
736
|
+
};
|
|
737
|
+
|
|
738
|
+
const ensureChild = (
|
|
739
|
+
forest: Forest,
|
|
740
|
+
parent: SelNode,
|
|
741
|
+
field: string,
|
|
742
|
+
options: {
|
|
743
|
+
args?: Record<string, unknown>;
|
|
744
|
+
argTypes?: ArgMeta;
|
|
745
|
+
isScalar?: boolean;
|
|
746
|
+
isList?: boolean;
|
|
747
|
+
},
|
|
748
|
+
): SelNode => {
|
|
749
|
+
const key = options.args === undefined ? field : `${field}:${stableStringify(options.args)}`;
|
|
750
|
+
const existing = parent.children.get(key);
|
|
751
|
+
if (existing) return existing;
|
|
752
|
+
const taken = new Set([...parent.children.values()].map((c) => c.alias ?? c.field));
|
|
753
|
+
let alias: string | undefined;
|
|
754
|
+
if (taken.has(field)) {
|
|
755
|
+
do {
|
|
756
|
+
alias = `${field}_${forest.aliasI++}`;
|
|
757
|
+
} while (taken.has(alias));
|
|
758
|
+
}
|
|
759
|
+
const sel: SelNode = {
|
|
760
|
+
field,
|
|
761
|
+
alias,
|
|
762
|
+
args: bindArgs(forest, options.args, options.argTypes),
|
|
763
|
+
children: new Map(),
|
|
764
|
+
isScalar: options.isScalar ?? false,
|
|
765
|
+
isList: options.isList ?? false,
|
|
458
766
|
};
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
if (
|
|
475
|
-
|
|
476
|
-
`Duplicate response key ${parent}.${key}; use distinct aliases`,
|
|
477
|
-
);
|
|
478
|
-
const field: GraphQLField | undefined =
|
|
479
|
-
fieldName === "__typename"
|
|
480
|
-
? { type: "String!", args: {}, errors: [] }
|
|
481
|
-
: type.fields?.[fieldName];
|
|
482
|
-
if (!field) return requestError(`Unknown field ${parent}.${fieldName}`);
|
|
483
|
-
const wrapper =
|
|
484
|
-
object(selected) &&
|
|
485
|
-
("where" in selected ||
|
|
486
|
-
"select" in selected ||
|
|
487
|
-
"$include" in selected ||
|
|
488
|
-
"$skip" in selected)
|
|
489
|
-
? selected
|
|
490
|
-
: undefined;
|
|
491
|
-
const args = wrapper?.where ?? {};
|
|
492
|
-
if (!object(args))
|
|
493
|
-
return requestError(`${parent}.${fieldName}.where must be an object`);
|
|
494
|
-
for (const arg of Object.keys(args))
|
|
495
|
-
if (!field.args[arg])
|
|
496
|
-
return requestError(
|
|
497
|
-
`Unknown argument ${parent}.${fieldName}(${arg})`,
|
|
498
|
-
);
|
|
499
|
-
const arguments_: NonNullable<FieldNode["arguments"]>[number][] = [];
|
|
500
|
-
for (const [arg, definition] of Object.entries(field.args)) {
|
|
501
|
-
if (args[arg] === undefined) {
|
|
502
|
-
if (
|
|
503
|
-
definition.type.endsWith("!") &&
|
|
504
|
-
definition.defaultValue === undefined
|
|
505
|
-
)
|
|
506
|
-
return requestError(`${parent}.${fieldName}(${arg}) is required`);
|
|
507
|
-
} else
|
|
508
|
-
arguments_.push({
|
|
509
|
-
kind: Kind.ARGUMENT,
|
|
510
|
-
name: nameNode(arg),
|
|
511
|
-
value: variable(
|
|
512
|
-
definition.type,
|
|
513
|
-
encodeInput(
|
|
514
|
-
model,
|
|
515
|
-
definition.type,
|
|
516
|
-
args[arg],
|
|
517
|
-
`${parent}.${fieldName}(${arg})`,
|
|
518
|
-
),
|
|
519
|
-
),
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
const directives: NonNullable<FieldNode["directives"]>[number][] = [];
|
|
523
|
-
for (const directive of ["include", "skip"] as const) {
|
|
524
|
-
const value = wrapper?.[`$${directive}`];
|
|
525
|
-
if (value !== undefined) {
|
|
526
|
-
if (typeof value !== "boolean")
|
|
527
|
-
return requestError(`$${directive} must be a boolean`);
|
|
528
|
-
directives.push({
|
|
529
|
-
kind: Kind.DIRECTIVE,
|
|
530
|
-
name: nameNode(directive),
|
|
531
|
-
arguments: [
|
|
532
|
-
{
|
|
533
|
-
kind: Kind.ARGUMENT,
|
|
534
|
-
name: nameNode("if"),
|
|
535
|
-
value: variable("Boolean!", value),
|
|
536
|
-
},
|
|
537
|
-
],
|
|
538
|
-
});
|
|
539
|
-
}
|
|
767
|
+
parent.children.set(key, sel);
|
|
768
|
+
return sel;
|
|
769
|
+
};
|
|
770
|
+
|
|
771
|
+
type Path = Array<string | "*">;
|
|
772
|
+
|
|
773
|
+
const paintConnection = (forest: Forest, connection: SelNode): Path => {
|
|
774
|
+
const edges = ensureChild(forest, connection, "edges", { isList: true });
|
|
775
|
+
ensureChild(forest, edges, "node", {});
|
|
776
|
+
return ["edges", "node"];
|
|
777
|
+
};
|
|
778
|
+
|
|
779
|
+
const paintAbs = (forest: Forest, expr: Expr): Path => {
|
|
780
|
+
switch (expr._tag) {
|
|
781
|
+
case "Root": {
|
|
782
|
+
if (forest.kind !== undefined && forest.kind !== expr.op) {
|
|
783
|
+
throw new GqlError(`cannot mix ${forest.kind} and ${expr.op} in one document`);
|
|
540
784
|
}
|
|
541
|
-
|
|
542
|
-
const
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
if (sub !== true && sub !== undefined)
|
|
550
|
-
return requestError(
|
|
551
|
-
`${parent}.${fieldName} is a leaf and takes no selection`,
|
|
552
|
-
);
|
|
553
|
-
} else child = walk(named(field.type), sub);
|
|
554
|
-
nodes.push({
|
|
555
|
-
kind: Kind.FIELD,
|
|
556
|
-
name: nameNode(fieldName),
|
|
557
|
-
...(alias ? { alias: nameNode(alias) } : {}),
|
|
558
|
-
arguments: arguments_,
|
|
559
|
-
directives,
|
|
560
|
-
...(!leaf
|
|
561
|
-
? {
|
|
562
|
-
selectionSet: {
|
|
563
|
-
kind: Kind.SELECTION_SET,
|
|
564
|
-
selections: child.nodes,
|
|
565
|
-
},
|
|
566
|
-
}
|
|
567
|
-
: {}),
|
|
785
|
+
forest.kind = expr.op;
|
|
786
|
+
const node = ensureChild(forest, forest.roots, expr.field, {
|
|
787
|
+
args: expr.args,
|
|
788
|
+
argTypes: expr.argTypes,
|
|
789
|
+
// Leaf roots (`projectDelete: Boolean!`) take no sub-selection.
|
|
790
|
+
isScalar:
|
|
791
|
+
expr.type.tag === "scalar" || (expr.type.tag === "list" && expr.type.of.tag === "scalar"),
|
|
792
|
+
isList: expr.type.tag === "list" && !expr.connection,
|
|
568
793
|
});
|
|
569
|
-
const
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
conditional: wrapper?.$include === false || wrapper?.$skip === true,
|
|
794
|
+
const key = node.alias ?? node.field;
|
|
795
|
+
forest.rootAlias.set(expr, key);
|
|
796
|
+
forest.rootErrors.set(key, { field: expr.field, errors: expr.errors });
|
|
797
|
+
return expr.connection ? [key, ...paintConnection(forest, node)] : [key];
|
|
798
|
+
}
|
|
799
|
+
case "Prop": {
|
|
800
|
+
const parentPath = paintAbs(forest, expr.parent);
|
|
801
|
+
const parentSel = selAt(forest.roots, parentPath);
|
|
802
|
+
const node = ensureChild(forest, parentSel, expr.field.name, {
|
|
803
|
+
args: expr.args,
|
|
804
|
+
argTypes: expr.field.argTypes,
|
|
805
|
+
isScalar: expr.field.kind === "scalar",
|
|
806
|
+
isList: expr.field.kind === "list",
|
|
583
807
|
});
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
if (key === "__alias") {
|
|
587
|
-
if (!object(value))
|
|
588
|
-
return requestError(`${parent}.__alias must be an object`);
|
|
589
|
-
for (const [alias, fields] of Object.entries(value)) {
|
|
590
|
-
if (!object(fields) || Object.keys(fields).length !== 1)
|
|
591
|
-
return requestError(`Alias ${alias} must select exactly one field`);
|
|
592
|
-
const [field, selected] = Object.entries(fields)[0]!;
|
|
593
|
-
addField(field, selected, alias);
|
|
594
|
-
}
|
|
595
|
-
} else if (key === "__on") {
|
|
596
|
-
if (!object(value))
|
|
597
|
-
return requestError(`${parent}.__on must be an object`);
|
|
598
|
-
for (const [branch, fields] of Object.entries(value)) {
|
|
599
|
-
if (!type.possibleTypes?.includes(branch))
|
|
600
|
-
return requestError(
|
|
601
|
-
`${branch} is not a possible type of ${parent}`,
|
|
602
|
-
);
|
|
603
|
-
const children = walk(branch, fields);
|
|
604
|
-
nodes.push({
|
|
605
|
-
kind: Kind.INLINE_FRAGMENT,
|
|
606
|
-
typeCondition: { kind: Kind.NAMED_TYPE, name: nameNode(branch) },
|
|
607
|
-
selectionSet: {
|
|
608
|
-
kind: Kind.SELECTION_SET,
|
|
609
|
-
selections: children.nodes,
|
|
610
|
-
},
|
|
611
|
-
});
|
|
612
|
-
positions.push({
|
|
613
|
-
field: "__fragment",
|
|
614
|
-
key: "",
|
|
615
|
-
coordinate: parent,
|
|
616
|
-
type: branch,
|
|
617
|
-
errors: [],
|
|
618
|
-
children: children.positions,
|
|
619
|
-
branches: {},
|
|
620
|
-
conditional: false,
|
|
621
|
-
});
|
|
622
|
-
}
|
|
623
|
-
} else addField(key, value);
|
|
808
|
+
const path = [...parentPath, node.alias ?? node.field];
|
|
809
|
+
return expr.field.kind === "connection" ? [...path, ...paintConnection(forest, node)] : path;
|
|
624
810
|
}
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
811
|
+
default:
|
|
812
|
+
throw new GqlError(`paintAbs: ${expr._tag}`);
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
|
|
816
|
+
const selAt = (roots: SelNode, path: Path): SelNode => {
|
|
817
|
+
let current = roots;
|
|
818
|
+
for (const segment of path) {
|
|
819
|
+
if (segment === "*") continue;
|
|
820
|
+
const child = [...current.children.values()].find(
|
|
821
|
+
(candidate) => (candidate.alias ?? candidate.field) === segment,
|
|
822
|
+
);
|
|
823
|
+
if (!child) {
|
|
824
|
+
throw new GqlError(`internal: missing ${String(segment)}`);
|
|
825
|
+
}
|
|
826
|
+
current = child;
|
|
827
|
+
}
|
|
828
|
+
return current;
|
|
829
|
+
};
|
|
830
|
+
|
|
831
|
+
const connectionNodeSel = (connection: SelNode): SelNode => {
|
|
832
|
+
const edges = [...connection.children.values()].find((c) => c.field === "edges");
|
|
833
|
+
const node = edges ? [...edges.children.values()].find((c) => c.field === "node") : undefined;
|
|
834
|
+
if (!node) throw new GqlError("internal: connection missing edges.node");
|
|
835
|
+
return node;
|
|
836
|
+
};
|
|
837
|
+
|
|
838
|
+
const relSel = (expr: Expr, listSel: SelNode): SelNode => {
|
|
839
|
+
switch (expr._tag) {
|
|
840
|
+
case "Item":
|
|
841
|
+
return listSel;
|
|
842
|
+
case "Prop": {
|
|
843
|
+
const parent = relSel(expr.parent, listSel);
|
|
844
|
+
const child = [...parent.children.values()].find((c) => c.field === expr.field.name);
|
|
845
|
+
if (!child) {
|
|
846
|
+
throw new GqlError(`missing ${expr.field.name} in list selection`);
|
|
847
|
+
}
|
|
848
|
+
return expr.field.kind === "connection" ? connectionNodeSel(child) : child;
|
|
849
|
+
}
|
|
850
|
+
default:
|
|
851
|
+
return listSel;
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
|
|
855
|
+
const paintRel = (forest: Forest, expr: Expr, listSel: SelNode): void => {
|
|
856
|
+
switch (expr._tag) {
|
|
857
|
+
case "Item":
|
|
858
|
+
case "Literal":
|
|
859
|
+
return;
|
|
860
|
+
case "Prop": {
|
|
861
|
+
paintRel(forest, expr.parent, listSel);
|
|
862
|
+
const child = ensureChild(forest, relSel(expr.parent, listSel), expr.field.name, {
|
|
863
|
+
args: expr.args,
|
|
864
|
+
argTypes: expr.field.argTypes,
|
|
865
|
+
isScalar: expr.field.kind === "scalar",
|
|
866
|
+
isList: expr.field.kind === "list",
|
|
867
|
+
});
|
|
868
|
+
if (expr.field.kind === "connection") paintConnection(forest, child);
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
case "MapValue":
|
|
872
|
+
case "FlatMap":
|
|
873
|
+
paintRel(forest, expr.parent, listSel);
|
|
874
|
+
return;
|
|
875
|
+
case "MapItems":
|
|
876
|
+
paintRel(forest, expr.parent, listSel);
|
|
877
|
+
visitRel(expr.mapped, forest, relSel(expr.parent, listSel));
|
|
878
|
+
return;
|
|
879
|
+
case "Filter":
|
|
880
|
+
paintRel(forest, expr.parent, listSel);
|
|
881
|
+
paintRel(forest, expr.predicate, relSel(expr.parent, listSel));
|
|
882
|
+
return;
|
|
883
|
+
case "Root":
|
|
884
|
+
throw new GqlError("root inside list item");
|
|
885
|
+
}
|
|
886
|
+
};
|
|
887
|
+
|
|
888
|
+
const visitExpr = (forest: Forest, expr: Expr): void => {
|
|
889
|
+
switch (expr._tag) {
|
|
890
|
+
case "Root":
|
|
891
|
+
case "Prop":
|
|
892
|
+
paintAbs(forest, expr);
|
|
893
|
+
return;
|
|
894
|
+
case "Item":
|
|
895
|
+
return;
|
|
896
|
+
case "Literal":
|
|
897
|
+
return;
|
|
898
|
+
case "MapValue":
|
|
899
|
+
case "FlatMap":
|
|
900
|
+
visitExpr(forest, expr.parent);
|
|
901
|
+
return;
|
|
902
|
+
case "MapItems": {
|
|
903
|
+
visitExpr(forest, expr.parent);
|
|
904
|
+
const path = paintAbs(forest, graphqlBase(expr.parent));
|
|
905
|
+
visitRel(expr.mapped, forest, selAt(forest.roots, path));
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
case "Filter": {
|
|
909
|
+
visitExpr(forest, expr.parent);
|
|
910
|
+
const path = paintAbs(forest, graphqlBase(expr.parent));
|
|
911
|
+
paintRel(forest, expr.predicate, selAt(forest.roots, path));
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
};
|
|
916
|
+
|
|
917
|
+
const graphqlBase = (expr: Expr): Expr => {
|
|
918
|
+
switch (expr._tag) {
|
|
919
|
+
case "Root":
|
|
920
|
+
case "Prop":
|
|
921
|
+
case "Item":
|
|
922
|
+
return expr;
|
|
923
|
+
case "MapValue":
|
|
924
|
+
case "MapItems":
|
|
925
|
+
case "Filter":
|
|
926
|
+
case "FlatMap":
|
|
927
|
+
return graphqlBase(expr.parent);
|
|
928
|
+
case "Literal":
|
|
929
|
+
throw new GqlError("literal has no graphql base");
|
|
930
|
+
}
|
|
931
|
+
};
|
|
932
|
+
|
|
933
|
+
const visitRel = (plan: unknown, forest: Forest, listSel: SelNode): void => {
|
|
934
|
+
if (isQuery(plan)) {
|
|
935
|
+
paintRel(forest, (plan as QueryNode).expr, listSel);
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
if (plan !== null && typeof plan === "object" && !Effect.isEffect(plan)) {
|
|
939
|
+
for (const nested of Object.values(plan as Record<string, unknown>)) {
|
|
940
|
+
visitRel(nested, forest, listSel);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
};
|
|
944
|
+
|
|
945
|
+
/**
|
|
946
|
+
* Recurse through a builder return value. Query nodes contribute GraphQL
|
|
947
|
+
* fields to `forest`; Effects are ignored until interpret (FlatMap).
|
|
948
|
+
*/
|
|
949
|
+
const visitPlan = (plan: unknown, forest: Forest): void => {
|
|
950
|
+
if (isQuery(plan)) {
|
|
951
|
+
log("visit", printExpr((plan as QueryNode).expr));
|
|
952
|
+
visitExpr(forest, (plan as QueryNode).expr);
|
|
953
|
+
return;
|
|
954
|
+
}
|
|
955
|
+
if (Effect.isEffect(plan)) return;
|
|
956
|
+
if (plan !== null && typeof plan === "object" && !Array.isArray(plan)) {
|
|
957
|
+
for (const nested of Object.values(plan as Record<string, unknown>)) {
|
|
958
|
+
visitPlan(nested, forest);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
};
|
|
962
|
+
|
|
963
|
+
const validate = (node: SelNode): string | undefined => {
|
|
964
|
+
for (const child of node.children.values()) {
|
|
965
|
+
if (!child.isScalar && child.children.size === 0) {
|
|
966
|
+
return `field "${child.field}" has no sub-selection`;
|
|
967
|
+
}
|
|
968
|
+
const inner = validate(child);
|
|
969
|
+
if (inner) return inner;
|
|
970
|
+
}
|
|
971
|
+
return undefined;
|
|
972
|
+
};
|
|
973
|
+
|
|
974
|
+
const printChildren = (node: SelNode, indent: number): string => {
|
|
975
|
+
const pad = " ".repeat(indent);
|
|
976
|
+
const lines: Array<string> = [];
|
|
977
|
+
for (const child of node.children.values()) {
|
|
978
|
+
let head = child.alias ? `${child.alias}: ${child.field}` : child.field;
|
|
979
|
+
if (child.args && Object.keys(child.args).length > 0) {
|
|
980
|
+
const printed = Object.entries(child.args)
|
|
981
|
+
.map(([argName, varName]) => `${argName}: $${varName}`)
|
|
982
|
+
.join(", ");
|
|
983
|
+
head += `(${printed})`;
|
|
984
|
+
}
|
|
985
|
+
if (child.isScalar) lines.push(`${pad}${head}`);
|
|
986
|
+
else {
|
|
987
|
+
lines.push(`${pad}${head} {`);
|
|
988
|
+
lines.push(printChildren(child, indent + 1));
|
|
989
|
+
lines.push(`${pad}}`);
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
return lines.join("\n");
|
|
993
|
+
};
|
|
994
|
+
|
|
995
|
+
const emptyForest = (): Forest => ({
|
|
996
|
+
kind: undefined,
|
|
997
|
+
roots: emptySel(""),
|
|
998
|
+
vars: new Map(),
|
|
999
|
+
varI: 0,
|
|
1000
|
+
aliasI: 0,
|
|
1001
|
+
rootAlias: new WeakMap(),
|
|
1002
|
+
rootErrors: new Map(),
|
|
1003
|
+
});
|
|
1004
|
+
|
|
1005
|
+
const emit = (forest: Forest): Compiled => {
|
|
1006
|
+
const err = validate(forest.roots);
|
|
1007
|
+
if (err) throw new GqlError(err);
|
|
1008
|
+
const kind = forest.kind ?? "query";
|
|
1009
|
+
const varDefs = [...forest.vars.entries()]
|
|
1010
|
+
.map(([name, binding]) => `$${name}: ${binding.type}`)
|
|
1011
|
+
.join(", ");
|
|
1012
|
+
const header = varDefs.length > 0 ? `${kind} Gql(${varDefs})` : `${kind} Gql`;
|
|
1013
|
+
const variables: Record<string, unknown> = {};
|
|
1014
|
+
for (const [name, binding] of forest.vars) variables[name] = binding.value;
|
|
643
1015
|
return {
|
|
644
|
-
|
|
1016
|
+
document: `${header} {\n${printChildren(forest.roots, 1)}\n}`,
|
|
1017
|
+
operationName: "Gql",
|
|
645
1018
|
variables,
|
|
646
|
-
operationName,
|
|
647
1019
|
kind,
|
|
648
|
-
|
|
649
|
-
|
|
1020
|
+
tree: forest.roots,
|
|
1021
|
+
rootAlias: forest.rootAlias,
|
|
1022
|
+
rootErrors: forest.rootErrors,
|
|
650
1023
|
};
|
|
651
1024
|
};
|
|
652
1025
|
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
1026
|
+
type Compiled = CompiledOperation & {
|
|
1027
|
+
readonly rootAlias: WeakMap<object, string>;
|
|
1028
|
+
readonly rootErrors: ReadonlyMap<string, RootErrors>;
|
|
1029
|
+
};
|
|
1030
|
+
|
|
1031
|
+
const nodesFromConnection = (value: unknown): unknown => {
|
|
1032
|
+
if (value == null) return value;
|
|
1033
|
+
if (Array.isArray(value)) return value.map(nodesFromConnection);
|
|
1034
|
+
const edges = (value as Record<string, unknown>).edges;
|
|
1035
|
+
if (!Array.isArray(edges)) return [];
|
|
1036
|
+
return edges.map((edge) => (edge == null ? edge : (edge as Record<string, unknown>).node));
|
|
658
1037
|
};
|
|
659
|
-
|
|
660
|
-
const
|
|
661
|
-
|
|
662
|
-
|
|
1038
|
+
|
|
1039
|
+
const readField = (parent: unknown, name: string): unknown => {
|
|
1040
|
+
if (parent == null) return parent;
|
|
1041
|
+
if (Array.isArray(parent)) {
|
|
1042
|
+
return parent.map((item) => (item == null ? item : (item as Record<string, unknown>)[name]));
|
|
1043
|
+
}
|
|
1044
|
+
return (parent as Record<string, unknown>)[name];
|
|
1045
|
+
};
|
|
1046
|
+
|
|
1047
|
+
const extractAbs = (expr: Expr, data: unknown, rootAlias: WeakMap<object, string>): unknown => {
|
|
1048
|
+
switch (expr._tag) {
|
|
1049
|
+
case "Root": {
|
|
1050
|
+
const raw = (data as Record<string, unknown>)[rootAlias.get(expr) ?? expr.field];
|
|
1051
|
+
return expr.connection ? nodesFromConnection(raw) : raw;
|
|
1052
|
+
}
|
|
1053
|
+
case "Prop": {
|
|
1054
|
+
const value = readField(extractAbs(expr.parent, data, rootAlias), expr.field.name);
|
|
1055
|
+
return expr.field.kind === "connection" ? nodesFromConnection(value) : value;
|
|
1056
|
+
}
|
|
1057
|
+
default:
|
|
1058
|
+
throw new GqlError(`extractAbs: ${expr._tag}`);
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
|
|
1062
|
+
const extractRel = (expr: Expr, item: unknown): unknown => {
|
|
1063
|
+
switch (expr._tag) {
|
|
1064
|
+
case "Item":
|
|
1065
|
+
return item;
|
|
1066
|
+
case "Prop": {
|
|
1067
|
+
const value = readField(extractRel(expr.parent, item), expr.field.name);
|
|
1068
|
+
return expr.field.kind === "connection" ? nodesFromConnection(value) : value;
|
|
1069
|
+
}
|
|
1070
|
+
default:
|
|
1071
|
+
throw new GqlError(`extractRel: ${expr._tag}`);
|
|
1072
|
+
}
|
|
1073
|
+
};
|
|
1074
|
+
|
|
1075
|
+
const inItem = (expr: Expr): boolean => {
|
|
1076
|
+
switch (expr._tag) {
|
|
1077
|
+
case "Item":
|
|
1078
|
+
return true;
|
|
1079
|
+
case "Prop":
|
|
1080
|
+
case "MapValue":
|
|
1081
|
+
case "MapItems":
|
|
1082
|
+
case "Filter":
|
|
1083
|
+
case "FlatMap":
|
|
1084
|
+
return inItem(expr.parent);
|
|
1085
|
+
default:
|
|
1086
|
+
return false;
|
|
1087
|
+
}
|
|
1088
|
+
};
|
|
1089
|
+
|
|
1090
|
+
const interpretExpr = (
|
|
1091
|
+
expr: Expr,
|
|
663
1092
|
data: unknown,
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
path: ReadonlyArray<string | number>,
|
|
1093
|
+
rootAlias: WeakMap<object, string>,
|
|
1094
|
+
item: unknown,
|
|
667
1095
|
): unknown => {
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
return
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
return
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
1096
|
+
switch (expr._tag) {
|
|
1097
|
+
case "Literal":
|
|
1098
|
+
return expr.value;
|
|
1099
|
+
case "Item":
|
|
1100
|
+
return item;
|
|
1101
|
+
case "Root":
|
|
1102
|
+
case "Prop":
|
|
1103
|
+
return inItem(expr) ? extractRel(expr, item) : extractAbs(expr, data, rootAlias);
|
|
1104
|
+
case "MapValue":
|
|
1105
|
+
return expr.mapFn(interpretExpr(expr.parent, data, rootAlias, item));
|
|
1106
|
+
case "Filter": {
|
|
1107
|
+
const list = interpretExpr(expr.parent, data, rootAlias, item);
|
|
1108
|
+
const arr = Array.isArray(list) ? list : [];
|
|
1109
|
+
return arr.filter((row) => Boolean(interpretExpr(expr.predicate, data, rootAlias, row)));
|
|
1110
|
+
}
|
|
1111
|
+
case "MapItems": {
|
|
1112
|
+
const list = interpretExpr(expr.parent, data, rootAlias, item);
|
|
1113
|
+
if (expr.single) {
|
|
1114
|
+
return list == null ? null : interpretValueSync(expr.mapped, data, rootAlias, list);
|
|
1115
|
+
}
|
|
1116
|
+
const arr = Array.isArray(list) ? list : [];
|
|
1117
|
+
return arr.map((row) => interpretValueSync(expr.mapped, data, rootAlias, row));
|
|
1118
|
+
}
|
|
1119
|
+
case "FlatMap":
|
|
1120
|
+
throw new GqlError("FlatMap must be interpreted as Effect");
|
|
684
1121
|
}
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
Int: "number",
|
|
696
|
-
Float: "number",
|
|
697
|
-
} as Record<string, string>
|
|
698
|
-
)[base];
|
|
699
|
-
if (
|
|
700
|
-
primitive === "string | number" &&
|
|
701
|
-
typeof data !== "string" &&
|
|
702
|
-
typeof data !== "number"
|
|
703
|
-
)
|
|
704
|
-
return decodeFailure(`Expected ${base}`, path);
|
|
705
|
-
if (
|
|
706
|
-
base === "BigInt" &&
|
|
707
|
-
((typeof data === "number" && !Number.isSafeInteger(data)) ||
|
|
708
|
-
(typeof data === "string" && !/^-?\d+$/.test(data)))
|
|
709
|
-
)
|
|
710
|
-
return decodeFailure(`Invalid ${base}`, path);
|
|
711
|
-
if (
|
|
712
|
-
["string", "number", "boolean"].includes(primitive ?? "") &&
|
|
713
|
-
typeof data !== primitive
|
|
714
|
-
)
|
|
715
|
-
return decodeFailure(`Expected ${base}`, path);
|
|
716
|
-
if (
|
|
717
|
-
typeof data === "number" &&
|
|
718
|
-
(!Number.isFinite(data) ||
|
|
719
|
-
(base === "Int" &&
|
|
720
|
-
(!Number.isInteger(data) || data < -2147483648 || data > 2147483647)))
|
|
721
|
-
)
|
|
722
|
-
return decodeFailure(`Invalid ${base}`, path);
|
|
723
|
-
return data;
|
|
1122
|
+
};
|
|
1123
|
+
|
|
1124
|
+
const interpretValueSync = (
|
|
1125
|
+
plan: unknown,
|
|
1126
|
+
data: unknown,
|
|
1127
|
+
rootAlias: WeakMap<object, string>,
|
|
1128
|
+
item: unknown,
|
|
1129
|
+
): unknown => {
|
|
1130
|
+
if (isQuery(plan)) {
|
|
1131
|
+
return interpretExpr((plan as QueryNode).expr, data, rootAlias, item);
|
|
724
1132
|
}
|
|
725
|
-
if (
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
1133
|
+
if (plan !== null && typeof plan === "object" && !Effect.isEffect(plan)) {
|
|
1134
|
+
const out: Record<string, unknown> = {};
|
|
1135
|
+
for (const [key, nested] of Object.entries(plan as Record<string, unknown>)) {
|
|
1136
|
+
out[key] = interpretValueSync(nested, data, rootAlias, item);
|
|
1137
|
+
}
|
|
1138
|
+
return out;
|
|
729
1139
|
}
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
1140
|
+
return plan;
|
|
1141
|
+
};
|
|
1142
|
+
|
|
1143
|
+
const interpretPlan = (
|
|
1144
|
+
plan: unknown,
|
|
1145
|
+
data: unknown,
|
|
1146
|
+
rootAlias: WeakMap<object, string>,
|
|
1147
|
+
): Effect.Effect<unknown, unknown, GqlTransport> =>
|
|
1148
|
+
Effect.gen(function* () {
|
|
1149
|
+
if (isQuery(plan)) {
|
|
1150
|
+
const expr = (plan as QueryNode).expr;
|
|
1151
|
+
if (expr._tag === "FlatMap") {
|
|
1152
|
+
const resolved = interpretExpr(expr.parent, data, rootAlias, undefined);
|
|
1153
|
+
const next = expr.flatMapFn(resolved);
|
|
1154
|
+
if (Effect.isEffect(next)) return yield* next;
|
|
1155
|
+
if (isQuery(next)) return yield* interpretPlan(next, data, rootAlias);
|
|
1156
|
+
return next;
|
|
1157
|
+
}
|
|
1158
|
+
return interpretExpr(expr, data, rootAlias, undefined);
|
|
1159
|
+
}
|
|
1160
|
+
if (Effect.isEffect(plan)) return yield* plan;
|
|
1161
|
+
if (plan !== null && typeof plan === "object" && !Array.isArray(plan)) {
|
|
1162
|
+
const out: Record<string, unknown> = {};
|
|
1163
|
+
for (const [key, nested] of Object.entries(plan as Record<string, unknown>)) {
|
|
1164
|
+
out[key] = yield* interpretPlan(nested, data, rootAlias);
|
|
1165
|
+
}
|
|
1166
|
+
return out;
|
|
1167
|
+
}
|
|
1168
|
+
return plan;
|
|
1169
|
+
}) as Effect.Effect<unknown, unknown, GqlTransport>;
|
|
1170
|
+
|
|
1171
|
+
/**
|
|
1172
|
+
* Compile every Query in `plan` into one document, POST it, then replace
|
|
1173
|
+
* Query/Effect leaves with plain data (`UnwrapPlan`).
|
|
1174
|
+
*/
|
|
1175
|
+
const evaluatePlan = <Plan>(
|
|
1176
|
+
plan: Plan,
|
|
1177
|
+
): Effect.Effect<UnwrapPlan<Plan>, QueryError<PlanError<Plan>>, GqlTransport> =>
|
|
1178
|
+
Effect.gen(function* () {
|
|
1179
|
+
const forest = emptyForest();
|
|
1180
|
+
visitPlan(plan, forest);
|
|
1181
|
+
let data: unknown = {};
|
|
1182
|
+
let rootAlias: WeakMap<object, string> = new WeakMap();
|
|
1183
|
+
if (forest.roots.children.size > 0) {
|
|
1184
|
+
const compiled = emit(forest);
|
|
1185
|
+
log("document\n" + compiled.document);
|
|
1186
|
+
data = yield* execute(compiled);
|
|
1187
|
+
rootAlias = compiled.rootAlias;
|
|
1188
|
+
}
|
|
1189
|
+
return (yield* interpretPlan(plan, data, rootAlias)) as UnwrapPlan<Plan>;
|
|
1190
|
+
}) as Effect.Effect<UnwrapPlan<Plan>, QueryError<PlanError<Plan>>, GqlTransport>;
|
|
1191
|
+
|
|
1192
|
+
/**
|
|
1193
|
+
* POST one compiled document and fail with its classified errors. Queries
|
|
1194
|
+
* are retried (bounded) while every failure is retryable; mutations never
|
|
1195
|
+
* are, since an error can follow a side effect that already happened.
|
|
1196
|
+
*/
|
|
1197
|
+
const execute = (compiled: Compiled): Effect.Effect<unknown, ExecuteError, GqlTransport> => {
|
|
1198
|
+
const once = Effect.gen(function* () {
|
|
1199
|
+
const transport = yield* GqlTransport;
|
|
1200
|
+
const response = yield* transport.execute(compiled);
|
|
1201
|
+
const raw = response.errors ?? [];
|
|
1202
|
+
if (raw.length === 0) return response.data;
|
|
1203
|
+
const issues = raw.map((error) => classify(compiled, error, response));
|
|
1204
|
+
const [first, ...rest] = issues as [GraphQLIssue, ...GraphQLIssue[]];
|
|
1205
|
+
return yield* Effect.fail(
|
|
1206
|
+
rest.every((issue) => issue._tag === first._tag)
|
|
1207
|
+
? first
|
|
1208
|
+
: new GraphQLFailure({
|
|
1209
|
+
errors: [first, ...rest],
|
|
1210
|
+
data: response.data,
|
|
1211
|
+
status: response.status,
|
|
1212
|
+
}),
|
|
770
1213
|
);
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
1214
|
+
});
|
|
1215
|
+
return compiled.kind === "query"
|
|
1216
|
+
? once.pipe(
|
|
1217
|
+
Effect.retry({
|
|
1218
|
+
while: (error) => isRetryable(compiled, error),
|
|
1219
|
+
times: 5,
|
|
1220
|
+
schedule: Schedule.exponential("200 millis"),
|
|
1221
|
+
}),
|
|
778
1222
|
)
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
writable: true,
|
|
788
|
-
});
|
|
789
|
-
} else
|
|
790
|
-
Object.defineProperty(result, position.key, {
|
|
791
|
-
value: decodeData(
|
|
792
|
-
model,
|
|
793
|
-
position.type,
|
|
794
|
-
data[position.key],
|
|
795
|
-
position.children,
|
|
796
|
-
position.branches,
|
|
797
|
-
[...path, position.key],
|
|
798
|
-
),
|
|
799
|
-
enumerable: true,
|
|
800
|
-
configurable: true,
|
|
801
|
-
writable: true,
|
|
802
|
-
});
|
|
1223
|
+
: once;
|
|
1224
|
+
};
|
|
1225
|
+
|
|
1226
|
+
type ExecuteError = GraphQLIssue | GraphQLFailure | GraphQLTransportError;
|
|
1227
|
+
|
|
1228
|
+
const isRetryable = (compiled: Compiled, error: ExecuteError): boolean => {
|
|
1229
|
+
if (error instanceof GraphQLTransportError) {
|
|
1230
|
+
return error.status === undefined || error.status === 429 || error.status >= 500;
|
|
803
1231
|
}
|
|
804
|
-
|
|
1232
|
+
const retryable = new Set(
|
|
1233
|
+
[...compiled.rootErrors.values()].flatMap((root) =>
|
|
1234
|
+
root.errors.filter((spec) => spec.retryable).map((spec) => spec.tag),
|
|
1235
|
+
),
|
|
1236
|
+
);
|
|
1237
|
+
return error instanceof GraphQLFailure
|
|
1238
|
+
? error.errors.every((issue) => retryable.has(issue._tag))
|
|
1239
|
+
: retryable.has(error._tag);
|
|
805
1240
|
};
|
|
806
1241
|
|
|
807
|
-
|
|
1242
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
1243
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1244
|
+
|
|
1245
|
+
/**
|
|
1246
|
+
* Pick the most specific matcher among the errors the root at `path[0]`
|
|
1247
|
+
* declares (or the global errors for a path-less error). A tie between
|
|
1248
|
+
* different tags is ambiguous and stays {@link UnknownGraphQLError}.
|
|
1249
|
+
*/
|
|
808
1250
|
const classify = (
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
raw: Record<string, any>,
|
|
1251
|
+
compiled: Compiled,
|
|
1252
|
+
raw: RawGraphQLError,
|
|
812
1253
|
response: GraphQLResponse,
|
|
813
|
-
classes: Readonly<Record<string, ErrorConstructor>>,
|
|
814
1254
|
): GraphQLIssue => {
|
|
815
|
-
const path = Array.isArray(raw.path)
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
const
|
|
825
|
-
positions: readonly Position[],
|
|
826
|
-
value: unknown,
|
|
827
|
-
): readonly Position[] =>
|
|
828
|
-
positions.flatMap((p) => [
|
|
829
|
-
...p.children,
|
|
830
|
-
...(object(value) && typeof value.__typename === "string"
|
|
831
|
-
? (p.branches[value.__typename] ?? [])
|
|
832
|
-
: Object.values(p.branches).flat()),
|
|
833
|
-
]);
|
|
834
|
-
let valid = !!path?.length;
|
|
835
|
-
for (const segment of path ?? []) {
|
|
836
|
-
if (typeof segment === "number") {
|
|
837
|
-
currentData = Array.isArray(currentData)
|
|
838
|
-
? currentData[segment]
|
|
839
|
-
: undefined;
|
|
840
|
-
candidates = descendants(parents, currentData);
|
|
841
|
-
continue;
|
|
842
|
-
}
|
|
843
|
-
const matches = candidates.filter((p) => p.key === segment);
|
|
844
|
-
if (!matches.length) {
|
|
845
|
-
valid = false;
|
|
846
|
-
break;
|
|
847
|
-
}
|
|
848
|
-
position = {
|
|
849
|
-
...matches[0]!,
|
|
850
|
-
errors: [...new Set(matches.flatMap((p) => p.errors))],
|
|
851
|
-
};
|
|
852
|
-
currentData = object(currentData) ? currentData[segment] : undefined;
|
|
853
|
-
parents = matches;
|
|
854
|
-
candidates = descendants(matches, currentData);
|
|
855
|
-
}
|
|
856
|
-
const extensions = object(raw.extensions) ? raw.extensions : {};
|
|
1255
|
+
const path = Array.isArray(raw.path) ? raw.path : undefined;
|
|
1256
|
+
const root = typeof path?.[0] === "string" ? compiled.rootErrors.get(path[0]) : undefined;
|
|
1257
|
+
const candidates = root
|
|
1258
|
+
? root.errors
|
|
1259
|
+
: uniqueByTag(
|
|
1260
|
+
[...compiled.rootErrors.values()].flatMap((entry) =>
|
|
1261
|
+
entry.errors.filter((spec) => spec.global),
|
|
1262
|
+
),
|
|
1263
|
+
);
|
|
1264
|
+
const extensions = isRecord(raw.extensions) ? raw.extensions : {};
|
|
857
1265
|
const code =
|
|
858
1266
|
typeof extensions.code === "string"
|
|
859
1267
|
? extensions.code
|
|
860
1268
|
: typeof extensions.errorCode === "string"
|
|
861
1269
|
? extensions.errorCode
|
|
862
1270
|
: undefined;
|
|
863
|
-
const
|
|
864
|
-
const
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
: undefined;
|
|
868
|
-
const props = {
|
|
869
|
-
message: raw.message,
|
|
1271
|
+
const message = typeof raw.message === "string" ? raw.message : "";
|
|
1272
|
+
const retryHeader = response.headers?.["retry-after"];
|
|
1273
|
+
const props: GraphQLIssueProps = {
|
|
1274
|
+
message,
|
|
870
1275
|
code,
|
|
871
1276
|
path,
|
|
872
1277
|
locations: raw.locations,
|
|
@@ -878,444 +1283,321 @@ const classify = (
|
|
|
878
1283
|
? raw.traceId
|
|
879
1284
|
: undefined,
|
|
880
1285
|
status: response.status,
|
|
881
|
-
retryAfter,
|
|
1286
|
+
retryAfter: retryHeader && /^\d+(\.\d+)?$/.test(retryHeader) ? Number(retryHeader) : undefined,
|
|
882
1287
|
};
|
|
883
|
-
const
|
|
884
|
-
|
|
885
|
-
...(valid ? (position?.errors ?? []) : []),
|
|
886
|
-
];
|
|
887
|
-
const matches = tags.flatMap((tag) =>
|
|
888
|
-
(model.errors[tag]?.matchers ?? [])
|
|
1288
|
+
const matches = candidates.flatMap((spec) =>
|
|
1289
|
+
spec.matchers
|
|
889
1290
|
.filter(
|
|
890
1291
|
(matcher) =>
|
|
891
1292
|
(matcher.code === undefined || matcher.code === code) &&
|
|
892
|
-
(matcher.message === undefined || matcher.message ===
|
|
893
|
-
(matcher.messageIncludes === undefined ||
|
|
894
|
-
raw.message.includes(matcher.messageIncludes)),
|
|
1293
|
+
(matcher.message === undefined || matcher.message === message) &&
|
|
1294
|
+
(matcher.messageIncludes === undefined || message.includes(matcher.messageIncludes)),
|
|
895
1295
|
)
|
|
896
1296
|
.map((matcher) => ({
|
|
897
|
-
|
|
1297
|
+
spec,
|
|
898
1298
|
score:
|
|
899
|
-
(matcher.code ? 1 : 0) +
|
|
900
|
-
(matcher.message ? 4 : 0) +
|
|
901
|
-
(matcher.messageIncludes ? 2 : 0),
|
|
1299
|
+
(matcher.code ? 1 : 0) + (matcher.message ? 4 : 0) + (matcher.messageIncludes ? 2 : 0),
|
|
902
1300
|
})),
|
|
903
1301
|
);
|
|
904
1302
|
matches.sort((a, b) => b.score - a.score);
|
|
905
1303
|
const best = matches[0];
|
|
906
|
-
|
|
907
|
-
best &&
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
1304
|
+
if (
|
|
1305
|
+
best &&
|
|
1306
|
+
!matches.some((match) => match.score === best.score && match.spec.tag !== best.spec.tag)
|
|
1307
|
+
) {
|
|
1308
|
+
return best.spec.make(props);
|
|
1309
|
+
}
|
|
911
1310
|
return new UnknownGraphQLError({
|
|
912
1311
|
...props,
|
|
913
|
-
coordinate:
|
|
1312
|
+
coordinate: root?.field,
|
|
914
1313
|
});
|
|
915
1314
|
};
|
|
916
1315
|
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
1316
|
+
const uniqueByTag = (specs: ReadonlyArray<ErrorSpec>): ErrorSpec[] => [
|
|
1317
|
+
...new Map(specs.map((spec) => [spec.tag, spec])).values(),
|
|
1318
|
+
];
|
|
1319
|
+
|
|
1320
|
+
/** `Query.of` / pure. */
|
|
1321
|
+
export const ofQuery = <Value>(value: Value): Query<Value> =>
|
|
1322
|
+
make({ _tag: "Literal", value, type: { tag: "scalar" } });
|
|
1323
|
+
|
|
1324
|
+
const filterImpl = (
|
|
1325
|
+
source: QueryNode,
|
|
1326
|
+
predicate: (item: QueryNode) => QueryNode,
|
|
1327
|
+
): Query<unknown> => {
|
|
1328
|
+
const proto = itemQuery(source);
|
|
1329
|
+
const predicateQuery = predicate(proto);
|
|
1330
|
+
log("filter pred", printExpr(predicateQuery.expr));
|
|
1331
|
+
return make({
|
|
1332
|
+
_tag: "Filter",
|
|
1333
|
+
parent: source.expr,
|
|
1334
|
+
predicate: predicateQuery.expr,
|
|
1335
|
+
type: source.expr.type,
|
|
1336
|
+
});
|
|
1337
|
+
};
|
|
1338
|
+
|
|
1339
|
+
export function filterQuery<Item, Error = never>(
|
|
1340
|
+
predicate: (item: Query<Item>) => QueryNode<boolean, any>,
|
|
1341
|
+
): (source: QueryNode<readonly Item[] | null, Error>) => Query<readonly Item[], Error>;
|
|
1342
|
+
export function filterQuery<Item, Error = never>(
|
|
1343
|
+
source: QueryNode<readonly Item[] | null, Error>,
|
|
1344
|
+
predicate: (item: Query<Item>) => QueryNode<boolean, any>,
|
|
1345
|
+
): Query<readonly Item[], Error>;
|
|
1346
|
+
export function filterQuery(sourceOrPredicate: any, predicate?: any): any {
|
|
1347
|
+
if (predicate === undefined) {
|
|
1348
|
+
return (source: QueryNode) => filterImpl(source, sourceOrPredicate);
|
|
1349
|
+
}
|
|
1350
|
+
return filterImpl(sourceOrPredicate, predicate);
|
|
922
1351
|
}
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
1352
|
+
|
|
1353
|
+
/**
|
|
1354
|
+
* What `Query.map`'s callback receives: a Query per item for lists, a Query
|
|
1355
|
+
* for an object (so its fields get selected), the plain value for scalars.
|
|
1356
|
+
*/
|
|
1357
|
+
type MapInput<Value> = [NonNullable<Value>] extends [ReadonlyArray<infer Item>]
|
|
1358
|
+
? Query<Item>
|
|
1359
|
+
: [NonNullable<Value>] extends [object]
|
|
1360
|
+
? Query<NonNullable<Value>>
|
|
1361
|
+
: Value;
|
|
1362
|
+
|
|
1363
|
+
/** An object mapped through a `null` value stays `null`. */
|
|
1364
|
+
type MapOutput<Value, Mapped> = [NonNullable<Value>] extends [ReadonlyArray<unknown>]
|
|
1365
|
+
? ReadonlyArray<UnwrapPlan<Mapped>>
|
|
1366
|
+
: [NonNullable<Value>] extends [object]
|
|
1367
|
+
? UnwrapPlan<Mapped> | Nullish<Value>
|
|
1368
|
+
: Mapped;
|
|
1369
|
+
|
|
1370
|
+
const mapImpl = (source: QueryNode, mapFn: (value: any) => unknown): Query<unknown> => {
|
|
1371
|
+
if (source.expr.type.tag === "object") {
|
|
1372
|
+
const mapped = mapFn(
|
|
1373
|
+
new QueryNode({
|
|
1374
|
+
_tag: "Item",
|
|
1375
|
+
list: source.expr,
|
|
1376
|
+
type: source.expr.type,
|
|
1377
|
+
}),
|
|
1378
|
+
);
|
|
1379
|
+
log("map object", printExpr(source.expr));
|
|
1380
|
+
return make({
|
|
1381
|
+
_tag: "MapItems",
|
|
1382
|
+
parent: source.expr,
|
|
1383
|
+
mapped,
|
|
1384
|
+
single: true,
|
|
1385
|
+
type: { tag: "scalar" },
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
if (source.expr.type.tag === "list") {
|
|
1389
|
+
const proto = itemQuery(source);
|
|
1390
|
+
const mapped = mapFn(proto);
|
|
1391
|
+
log("map items", printExpr(source.expr));
|
|
1392
|
+
return make({
|
|
1393
|
+
_tag: "MapItems",
|
|
1394
|
+
parent: source.expr,
|
|
1395
|
+
mapped,
|
|
1396
|
+
type: source.expr.type,
|
|
1397
|
+
});
|
|
1398
|
+
}
|
|
1399
|
+
log("map value", printExpr(source.expr));
|
|
1400
|
+
return make({
|
|
1401
|
+
_tag: "MapValue",
|
|
1402
|
+
parent: source.expr,
|
|
1403
|
+
mapFn,
|
|
1404
|
+
type: { tag: "scalar" },
|
|
1405
|
+
});
|
|
1406
|
+
};
|
|
1407
|
+
|
|
1408
|
+
export function mapQuery<Value, Mapped, Error = never>(
|
|
1409
|
+
mapFn: (value: NoInfer<MapInput<Value>>) => Mapped,
|
|
1410
|
+
): (source: QueryNode<Value, Error>) => Query<MapOutput<Value, Mapped>, Error>;
|
|
1411
|
+
export function mapQuery<Value, Mapped, Error = never>(
|
|
1412
|
+
source: QueryNode<Value, Error>,
|
|
1413
|
+
mapFn: (value: NoInfer<MapInput<Value>>) => Mapped,
|
|
1414
|
+
): Query<MapOutput<Value, Mapped>, Error>;
|
|
1415
|
+
export function mapQuery(sourceOrMapFn: any, mapFn?: any): any {
|
|
1416
|
+
if (mapFn === undefined) {
|
|
1417
|
+
return (source: QueryNode) => mapImpl(source, sourceOrMapFn);
|
|
1418
|
+
}
|
|
1419
|
+
return mapImpl(sourceOrMapFn, mapFn);
|
|
952
1420
|
}
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
)
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
1421
|
+
|
|
1422
|
+
const flatMapImpl = (source: QueryNode, flatMapFn: (value: unknown) => unknown): Query<unknown> => {
|
|
1423
|
+
log("flatMap", printExpr(source.expr));
|
|
1424
|
+
return make({
|
|
1425
|
+
_tag: "FlatMap",
|
|
1426
|
+
parent: source.expr,
|
|
1427
|
+
flatMapFn,
|
|
1428
|
+
type: { tag: "scalar" },
|
|
1429
|
+
});
|
|
1430
|
+
};
|
|
1431
|
+
|
|
1432
|
+
export function flatMapQuery<Value, Result, Error, Requirements, SourceError = never>(
|
|
1433
|
+
flatMapFn: (
|
|
1434
|
+
value: Value,
|
|
1435
|
+
) => Effect.Effect<Result, Error, Requirements> | QueryNode<Result, Error>,
|
|
1436
|
+
): (source: QueryNode<Value, SourceError>) => Query<Result, SourceError | Error>;
|
|
1437
|
+
export function flatMapQuery<Value, Result, Error, Requirements, SourceError = never>(
|
|
1438
|
+
source: QueryNode<Value, SourceError>,
|
|
1439
|
+
flatMapFn: (
|
|
1440
|
+
value: Value,
|
|
1441
|
+
) => Effect.Effect<Result, Error, Requirements> | QueryNode<Result, Error>,
|
|
1442
|
+
): Query<Result, SourceError | Error>;
|
|
1443
|
+
export function flatMapQuery(sourceOrFlatMapFn: any, flatMapFn?: any): any {
|
|
1444
|
+
if (flatMapFn === undefined) {
|
|
1445
|
+
return (source: QueryNode) => flatMapImpl(source, sourceOrFlatMapFn);
|
|
1446
|
+
}
|
|
1447
|
+
return flatMapImpl(sourceOrFlatMapFn, flatMapFn);
|
|
966
1448
|
}
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
):
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
)
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1449
|
+
|
|
1450
|
+
/**
|
|
1451
|
+
* Builder → Effect. The inner function is *not* a generator; it returns a
|
|
1452
|
+
* plan of Query/Effect values. Query.fn visits the plan, POSTs one document,
|
|
1453
|
+
* then interprets Map/Filter/FlatMap/Of.
|
|
1454
|
+
*/
|
|
1455
|
+
export const queryFn =
|
|
1456
|
+
<Arguments extends Array<unknown>, Plan>(
|
|
1457
|
+
build: (...args: Arguments) => Plan,
|
|
1458
|
+
): ((
|
|
1459
|
+
...args: Arguments
|
|
1460
|
+
) => Effect.Effect<UnwrapPlan<Plan>, QueryError<PlanError<Plan>>, GqlTransport>) =>
|
|
1461
|
+
(...args) => {
|
|
1462
|
+
const plan = build(...args);
|
|
1463
|
+
return evaluatePlan(plan);
|
|
1464
|
+
};
|
|
1465
|
+
|
|
1466
|
+
// ── Pagination ──────────────────────────────────────────────────────────────
|
|
1467
|
+
//
|
|
1468
|
+
// A connection lens hides `edges`/`pageInfo`. `Query.pages` re-evaluates the
|
|
1469
|
+
// query once per page: it sets the connection's `after` argument, paints
|
|
1470
|
+
// `pageInfo { hasNextPage endCursor }` next to `edges`, and stops when
|
|
1471
|
+
// `hasNextPage` is false.
|
|
1472
|
+
|
|
1473
|
+
/** The connection a paged query reads, below any list-level Map/Filter. */
|
|
1474
|
+
const connectionOf = (expr: Expr): RootExpr | PropExpr => {
|
|
1475
|
+
const base = graphqlBase(expr);
|
|
1476
|
+
const isConnection =
|
|
1477
|
+
(base._tag === "Root" && base.connection === true) ||
|
|
1478
|
+
(base._tag === "Prop" && base.field.kind === "connection");
|
|
1479
|
+
if (!isConnection || inItem(base)) {
|
|
1480
|
+
throw new GqlError(`Query.pages needs a Relay connection, got ${printExpr(base)}`);
|
|
1481
|
+
}
|
|
1482
|
+
const argTypes = base._tag === "Root" ? base.argTypes : base.field.argTypes;
|
|
1483
|
+
if (!argTypes || !("after" in argTypes)) {
|
|
1484
|
+
throw new GqlError(`${printExpr(base)} takes no "after" cursor`);
|
|
1485
|
+
}
|
|
1486
|
+
return base as RootExpr | PropExpr;
|
|
1487
|
+
};
|
|
1488
|
+
|
|
1489
|
+
/** Rebuild `expr` with the connection's `after` argument set. */
|
|
1490
|
+
const withCursor = (expr: Expr, connection: Expr, after: string | undefined): Expr => {
|
|
1491
|
+
if (expr === connection) {
|
|
1492
|
+
const current = expr as RootExpr | PropExpr;
|
|
1493
|
+
return { ...current, args: { ...current.args, after } } as Expr;
|
|
1494
|
+
}
|
|
1495
|
+
switch (expr._tag) {
|
|
1496
|
+
case "MapItems":
|
|
1497
|
+
case "Filter":
|
|
1498
|
+
case "MapValue":
|
|
1499
|
+
case "FlatMap":
|
|
1500
|
+
return { ...expr, parent: withCursor(expr.parent, connection, after) };
|
|
1501
|
+
default:
|
|
1502
|
+
throw new GqlError(`withCursor: ${expr._tag}`);
|
|
1503
|
+
}
|
|
1504
|
+
};
|
|
1505
|
+
|
|
1506
|
+
const readPath = (data: unknown, path: Path): unknown => {
|
|
1507
|
+
let current = data;
|
|
1508
|
+
for (const segment of path) {
|
|
1509
|
+
if (current == null) return undefined;
|
|
1510
|
+
if (Array.isArray(current)) {
|
|
1511
|
+
throw new GqlError("Query.pages cannot page a connection inside a list");
|
|
1512
|
+
}
|
|
1513
|
+
current = (current as Record<string, unknown>)[segment];
|
|
1514
|
+
}
|
|
1515
|
+
return current;
|
|
1516
|
+
};
|
|
1517
|
+
|
|
1518
|
+
interface PageState {
|
|
1519
|
+
readonly after: string | undefined;
|
|
1520
|
+
readonly seen: ReadonlySet<string>;
|
|
1011
1521
|
}
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
? cause
|
|
1047
|
-
: new GraphQLRequestError({ message: String(cause) }),
|
|
1522
|
+
|
|
1523
|
+
const fetchPage = <Item>(
|
|
1524
|
+
query: QueryNode<ReadonlyArray<Item> | null, unknown>,
|
|
1525
|
+
connection: RootExpr | PropExpr,
|
|
1526
|
+
state: PageState,
|
|
1527
|
+
) =>
|
|
1528
|
+
Effect.gen(function* () {
|
|
1529
|
+
const pageExpr = withCursor(query.expr, connection, state.after);
|
|
1530
|
+
const forest = emptyForest();
|
|
1531
|
+
visitExpr(forest, pageExpr);
|
|
1532
|
+
const nodePath = paintAbs(forest, withCursor(connection, connection, state.after));
|
|
1533
|
+
const connectionPath = nodePath.slice(0, -2);
|
|
1534
|
+
const pageInfo = ensureChild(forest, selAt(forest.roots, connectionPath), "pageInfo", {});
|
|
1535
|
+
ensureChild(forest, pageInfo, "hasNextPage", { isScalar: true });
|
|
1536
|
+
ensureChild(forest, pageInfo, "endCursor", { isScalar: true });
|
|
1537
|
+
const compiled = emit(forest);
|
|
1538
|
+
log("page\n" + compiled.document);
|
|
1539
|
+
const data = yield* execute(compiled);
|
|
1540
|
+
const items = (yield* interpretPlan(make(pageExpr), data, compiled.rootAlias)) as
|
|
1541
|
+
| ReadonlyArray<Item>
|
|
1542
|
+
| null
|
|
1543
|
+
| undefined;
|
|
1544
|
+
const info = readPath(data, [...connectionPath, "pageInfo"]) as
|
|
1545
|
+
| { hasNextPage?: boolean; endCursor?: string | null }
|
|
1546
|
+
| null
|
|
1547
|
+
| undefined;
|
|
1548
|
+
const cursor = info?.endCursor ?? null;
|
|
1549
|
+
if (info?.hasNextPage !== true) {
|
|
1550
|
+
return [items ?? [], Option.none<PageState>()] as const;
|
|
1551
|
+
}
|
|
1552
|
+
if (cursor === null || cursor === state.after || state.seen.has(cursor)) {
|
|
1553
|
+
return yield* new GraphQLPaginationError({
|
|
1554
|
+
message: `${printExpr(connection)} returned a non-advancing cursor`,
|
|
1555
|
+
cursor,
|
|
1048
1556
|
});
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
message: `HTTP ${response.status} without a GraphQL response`,
|
|
1079
|
-
status: response.status,
|
|
1080
|
-
});
|
|
1081
|
-
return decodeFailure(
|
|
1082
|
-
"GraphQL response has neither data nor errors",
|
|
1083
|
-
[],
|
|
1084
|
-
);
|
|
1085
|
-
}
|
|
1086
|
-
if (response.status >= 400 && !rawErrors.length)
|
|
1087
|
-
throw new GraphQLTransportError({
|
|
1088
|
-
message: `HTTP ${response.status} without GraphQL errors`,
|
|
1089
|
-
status: response.status,
|
|
1090
|
-
});
|
|
1091
|
-
const errors = rawErrors.map((raw: Record<string, any>) =>
|
|
1092
|
-
classify(model, compiled, raw, response, classes),
|
|
1093
|
-
);
|
|
1094
|
-
let data = body.data;
|
|
1095
|
-
if (data !== undefined && data !== null)
|
|
1096
|
-
data = decodeData(
|
|
1097
|
-
model,
|
|
1098
|
-
compiled.rootType + "!",
|
|
1099
|
-
data,
|
|
1100
|
-
compiled.positions,
|
|
1101
|
-
{},
|
|
1102
|
-
[],
|
|
1103
|
-
);
|
|
1104
|
-
if ((data === undefined || data === null) && !errors.length)
|
|
1105
|
-
return decodeFailure("GraphQL success has no data", []);
|
|
1106
|
-
return {
|
|
1107
|
-
data,
|
|
1108
|
-
errors,
|
|
1109
|
-
status: response.status,
|
|
1110
|
-
extensions: body.extensions,
|
|
1111
|
-
};
|
|
1557
|
+
}
|
|
1558
|
+
return [
|
|
1559
|
+
items ?? [],
|
|
1560
|
+
Option.some({ after: cursor, seen: new Set([...state.seen, cursor]) }),
|
|
1561
|
+
] as const;
|
|
1562
|
+
});
|
|
1563
|
+
|
|
1564
|
+
/**
|
|
1565
|
+
* Every page of a Relay connection, one request per page. `query` is a
|
|
1566
|
+
* connection lens (root or nested under objects), optionally mapped or
|
|
1567
|
+
* filtered: `Query.pages(Railway.project({ id }).services({ first: 50 }))`.
|
|
1568
|
+
* Starts from the query's own `after` argument, if any.
|
|
1569
|
+
*/
|
|
1570
|
+
export const pagesQuery = <Item, Error>(
|
|
1571
|
+
query: QueryNode<ReadonlyArray<Item> | null, Error>,
|
|
1572
|
+
): Stream.Stream<ReadonlyArray<Item>, QueryError<Error> | GraphQLPaginationError, GqlTransport> =>
|
|
1573
|
+
Stream.unwrap(
|
|
1574
|
+
Effect.sync(() => {
|
|
1575
|
+
const connection = connectionOf(query.expr);
|
|
1576
|
+
const after = connection.args?.after;
|
|
1577
|
+
return Stream.paginate<
|
|
1578
|
+
PageState,
|
|
1579
|
+
ReadonlyArray<Item>,
|
|
1580
|
+
QueryError<Error> | GraphQLPaginationError,
|
|
1581
|
+
GqlTransport
|
|
1582
|
+
>(
|
|
1583
|
+
{
|
|
1584
|
+
after: typeof after === "string" ? after : undefined,
|
|
1585
|
+
seen: new Set(),
|
|
1112
1586
|
},
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
});
|
|
1122
|
-
});
|
|
1123
|
-
const retryable = (error: ClientError | GraphQLFailure): boolean =>
|
|
1124
|
-
error instanceof GraphQLFailure
|
|
1125
|
-
? error.errors.every(
|
|
1126
|
-
(issue) => model.errors[issue._tag]?.retryable === true,
|
|
1127
|
-
)
|
|
1128
|
-
: error instanceof GraphQLTransportError &&
|
|
1129
|
-
(error.status === undefined ||
|
|
1130
|
-
error.status === 429 ||
|
|
1131
|
-
error.status >= 500);
|
|
1132
|
-
const execute = (
|
|
1133
|
-
kind: OperationKind,
|
|
1134
|
-
selection: unknown,
|
|
1135
|
-
): Effect.Effect<any, ClientError | GraphQLFailure, R> => {
|
|
1136
|
-
const effect = executeReport(kind, selection).pipe(
|
|
1137
|
-
Effect.flatMap((report) =>
|
|
1138
|
-
report.errors.length
|
|
1139
|
-
? Effect.fail(
|
|
1140
|
-
new GraphQLFailure({
|
|
1141
|
-
errors: report.errors as [GraphQLIssue, ...GraphQLIssue[]],
|
|
1142
|
-
data: report.data,
|
|
1143
|
-
status: report.status,
|
|
1144
|
-
}),
|
|
1145
|
-
)
|
|
1146
|
-
: Effect.succeed(report.data),
|
|
1147
|
-
),
|
|
1148
|
-
);
|
|
1149
|
-
return kind === "query"
|
|
1150
|
-
? effect.pipe(
|
|
1151
|
-
Effect.retry({
|
|
1152
|
-
while: retryable,
|
|
1153
|
-
times: 5,
|
|
1154
|
-
schedule: Schedule.exponential("200 millis"),
|
|
1155
|
-
}),
|
|
1156
|
-
)
|
|
1157
|
-
: effect;
|
|
1158
|
-
};
|
|
1159
|
-
const operation = <
|
|
1160
|
-
K extends OperationKind,
|
|
1161
|
-
N extends keyof Fields<C, Root<C, K>> & string,
|
|
1162
|
-
>(
|
|
1163
|
-
kind: K,
|
|
1164
|
-
name: N,
|
|
1165
|
-
): Operation<C, K, N, R> => {
|
|
1166
|
-
const field =
|
|
1167
|
-
model.types[kind === "query" ? model.queryType : model.mutationType!]
|
|
1168
|
-
?.fields?.[name];
|
|
1169
|
-
const call = (args: unknown, selection?: unknown) =>
|
|
1170
|
-
execute(kind, {
|
|
1171
|
-
[name]: { where: args, select: selection ?? true },
|
|
1172
|
-
}).pipe(Effect.map((data) => data[name]));
|
|
1173
|
-
const pages = (args: any, selection: any) =>
|
|
1174
|
-
Stream.unwrap(
|
|
1175
|
-
Effect.try({
|
|
1176
|
-
try: () => {
|
|
1177
|
-
const connection = field && model.types[named(field.type)];
|
|
1178
|
-
if (
|
|
1179
|
-
kind !== "query" ||
|
|
1180
|
-
!field?.args.after ||
|
|
1181
|
-
!connection?.fields?.edges ||
|
|
1182
|
-
!connection.fields.pageInfo
|
|
1183
|
-
)
|
|
1184
|
-
return Stream.fromEffect(
|
|
1185
|
-
Effect.fail(
|
|
1186
|
-
new GraphQLRequestError({
|
|
1187
|
-
message: `${name} is not a paginated query connection`,
|
|
1188
|
-
}),
|
|
1189
|
-
),
|
|
1190
|
-
);
|
|
1191
|
-
// Cursor fields are internal additions; the caller's projection remains exact.
|
|
1192
|
-
const projection = compile(model, kind, {
|
|
1193
|
-
[name]: { where: args, select: selection },
|
|
1194
|
-
}).positions[0]!;
|
|
1195
|
-
let cursorKey = "pageInfo";
|
|
1196
|
-
let complete: Record<string, unknown>;
|
|
1197
|
-
if (
|
|
1198
|
-
selection.__alias &&
|
|
1199
|
-
Object.hasOwn(selection.__alias, "pageInfo")
|
|
1200
|
-
) {
|
|
1201
|
-
cursorKey = "_distilledPageInfo";
|
|
1202
|
-
while (
|
|
1203
|
-
Object.hasOwn(selection, cursorKey) ||
|
|
1204
|
-
Object.hasOwn(selection.__alias, cursorKey)
|
|
1205
|
-
)
|
|
1206
|
-
cursorKey += "_";
|
|
1207
|
-
complete = {
|
|
1208
|
-
...selection,
|
|
1209
|
-
__alias: {
|
|
1210
|
-
...selection.__alias,
|
|
1211
|
-
[cursorKey]: {
|
|
1212
|
-
pageInfo: { endCursor: true, hasNextPage: true },
|
|
1213
|
-
},
|
|
1214
|
-
},
|
|
1215
|
-
};
|
|
1216
|
-
} else {
|
|
1217
|
-
const {
|
|
1218
|
-
$include: _include,
|
|
1219
|
-
$skip: _skip,
|
|
1220
|
-
...pageFields
|
|
1221
|
-
} = selection.pageInfo?.select ?? selection.pageInfo ?? {};
|
|
1222
|
-
complete = {
|
|
1223
|
-
...selection,
|
|
1224
|
-
pageInfo: { ...pageFields, endCursor: true, hasNextPage: true },
|
|
1225
|
-
};
|
|
1226
|
-
}
|
|
1227
|
-
return Stream.paginate(
|
|
1228
|
-
{
|
|
1229
|
-
after: args.after as string | undefined,
|
|
1230
|
-
seen: new Set<string>(),
|
|
1231
|
-
},
|
|
1232
|
-
(state) =>
|
|
1233
|
-
call({ ...args, after: state.after }, complete).pipe(
|
|
1234
|
-
Effect.flatMap((page) => {
|
|
1235
|
-
const cursor = page?.[cursorKey]?.endCursor;
|
|
1236
|
-
const more = page?.[cursorKey]?.hasNextPage;
|
|
1237
|
-
if (
|
|
1238
|
-
more &&
|
|
1239
|
-
(typeof cursor !== "string" ||
|
|
1240
|
-
cursor === state.after ||
|
|
1241
|
-
state.seen.has(cursor))
|
|
1242
|
-
)
|
|
1243
|
-
return Effect.fail(
|
|
1244
|
-
new GraphQLDecodeError({
|
|
1245
|
-
message: `${name} returned a non-advancing pagination cursor`,
|
|
1246
|
-
}),
|
|
1247
|
-
);
|
|
1248
|
-
const seen = new Set(state.seen);
|
|
1249
|
-
if (typeof cursor === "string") seen.add(cursor);
|
|
1250
|
-
const projected: any = decodeData(
|
|
1251
|
-
model,
|
|
1252
|
-
field.type,
|
|
1253
|
-
page,
|
|
1254
|
-
projection.children,
|
|
1255
|
-
projection.branches,
|
|
1256
|
-
[],
|
|
1257
|
-
);
|
|
1258
|
-
return Effect.succeed([
|
|
1259
|
-
[projected],
|
|
1260
|
-
more
|
|
1261
|
-
? Option.some({ after: cursor, seen })
|
|
1262
|
-
: Option.none(),
|
|
1263
|
-
] as const);
|
|
1264
|
-
}),
|
|
1265
|
-
),
|
|
1266
|
-
);
|
|
1267
|
-
},
|
|
1268
|
-
catch: (cause) =>
|
|
1269
|
-
cause instanceof GraphQLRequestError
|
|
1270
|
-
? cause
|
|
1271
|
-
: new GraphQLRequestError({ message: String(cause) }),
|
|
1272
|
-
}),
|
|
1587
|
+
(state) =>
|
|
1588
|
+
fetchPage(query, connection, state).pipe(
|
|
1589
|
+
Effect.map(([items, next]) => [[items], next] as const),
|
|
1590
|
+
) as Effect.Effect<
|
|
1591
|
+
readonly [ReadonlyArray<ReadonlyArray<Item>>, Option.Option<PageState>],
|
|
1592
|
+
QueryError<Error> | GraphQLPaginationError,
|
|
1593
|
+
GqlTransport
|
|
1594
|
+
>,
|
|
1273
1595
|
);
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
),
|
|
1283
|
-
),
|
|
1284
|
-
),
|
|
1285
|
-
),
|
|
1286
|
-
}) as unknown as Operation<C, K, N, R>;
|
|
1287
|
-
};
|
|
1288
|
-
return {
|
|
1289
|
-
query: <const Q extends Selection<C, C["query"]>>(
|
|
1290
|
-
selection: Q,
|
|
1291
|
-
): Effect.Effect<
|
|
1292
|
-
Result<C, `${C["query"]}!`, Q>,
|
|
1293
|
-
Failure<C, C["query"], Q>,
|
|
1294
|
-
R
|
|
1295
|
-
> => execute("query", selection) as any,
|
|
1296
|
-
mutation: <const Q extends Selection<C, C["mutation"]>>(
|
|
1297
|
-
selection: Q,
|
|
1298
|
-
): Effect.Effect<
|
|
1299
|
-
Result<C, `${C["mutation"]}!`, Q>,
|
|
1300
|
-
Failure<C, C["mutation"], Q>,
|
|
1301
|
-
R
|
|
1302
|
-
> => execute("mutation", selection) as any,
|
|
1303
|
-
report: {
|
|
1304
|
-
query: <const Q extends Selection<C, C["query"]>>(
|
|
1305
|
-
selection: Q,
|
|
1306
|
-
): Effect.Effect<
|
|
1307
|
-
Report<Result<C, `${C["query"]}!`, Q>, Errors<C, C["query"], Q>>,
|
|
1308
|
-
ClientError,
|
|
1309
|
-
R
|
|
1310
|
-
> => executeReport("query", selection) as any,
|
|
1311
|
-
mutation: <const Q extends Selection<C, C["mutation"]>>(
|
|
1312
|
-
selection: Q,
|
|
1313
|
-
): Effect.Effect<
|
|
1314
|
-
Report<Result<C, `${C["mutation"]}!`, Q>, Errors<C, C["mutation"], Q>>,
|
|
1315
|
-
ClientError,
|
|
1316
|
-
R
|
|
1317
|
-
> => executeReport("mutation", selection) as any,
|
|
1318
|
-
},
|
|
1319
|
-
operation,
|
|
1320
|
-
};
|
|
1321
|
-
};
|
|
1596
|
+
}),
|
|
1597
|
+
);
|
|
1598
|
+
|
|
1599
|
+
/** Every node of a Relay connection, across all pages. */
|
|
1600
|
+
export const itemsQuery = <Item, Error>(
|
|
1601
|
+
query: QueryNode<ReadonlyArray<Item> | null, Error>,
|
|
1602
|
+
): Stream.Stream<Item, QueryError<Error> | GraphQLPaginationError, GqlTransport> =>
|
|
1603
|
+
pagesQuery(query).pipe(Stream.flatMap(Stream.fromIterable));
|