@alxia/graphql 0.7.1 → 0.8.1

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/README.md CHANGED
@@ -222,7 +222,16 @@ const { status, data, errors } = await client.query(
222
222
  );
223
223
  ```
224
224
 
225
- A `TypedDocumentNode` types `data` and the variables. See
225
+ A `TypedDocumentNode` types `data` and the variables. `method: 'GET'` sends
226
+ the operation in the URL; `persisted` sends the hash of a persisted operation,
227
+ alone when the app allows nothing else (you name `TData`); the client adds no
228
+ CSRF header, put yours in `headers`:
229
+
230
+ ```ts
231
+ const result = await client.query<{ hello: string }>({ persisted: hash, method: 'GET' });
232
+ ```
233
+
234
+ See
226
235
  [the testing guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/testing.md).
227
236
 
228
237
  ## API
@@ -236,8 +245,8 @@ A `TypedDocumentNode` types `data` and the variables. See
236
245
  | `SandboxOptions` | its options: `title`, `initialDocument`, `initialHeaders`, `pollForSchemaUpdates`, `includeCookies` |
237
246
  | `GraphQLContext<App, UserContext?>` | what a resolver reads |
238
247
  | `ServerContext<Ctx>`, `GraphQLOptions` | its types |
239
- | `graphqlClient(app, { path?, headers? })` (`@alxia/graphql/testing`) | `query(document, { variables?, operationName?, headers? })` in process: `{ status, data?, errors?, response }` |
240
- | `GraphQLClient`, `GraphQLResult`, `QueryDocument`, `QueryOptions`, `GraphQLClientOptions`, `ResponseError` (`@alxia/graphql/testing`) | its types |
248
+ | `graphqlClient(app, { path?, headers?, method? })` (`@alxia/graphql/testing`) | `query(document, { variables?, operationName?, headers?, method?, extensions?, persisted? })`, or `query({ persisted })` with no document, in process: `{ status, data?, errors?, response }` |
249
+ | `GraphQLClient`, `GraphQLResult`, `QueryDocument`, `QueryOptions`, `PersistedQueryOptions`, `HttpMethod`, `GraphQLClientOptions`, `ResponseError` (`@alxia/graphql/testing`) | its types |
241
250
 
242
251
  ## Documentation
243
252
 
@@ -25,20 +25,54 @@ export interface GraphQLResult<TData = unknown> {
25
25
  /** The response, its body still unread: `headers`, `ok`. */
26
26
  readonly response: Response;
27
27
  }
28
+ /** How the operation travels: a JSON body, or the URL's query string. */
29
+ export type HttpMethod = 'GET' | 'POST';
28
30
  export interface GraphQLClientOptions {
29
31
  /** The endpoint's path. Default `/graphql`. */
30
32
  readonly path?: string;
31
- /** Sent with every query: an `authorization` header, a CSRF one. */
33
+ /**
34
+ * Sent with every query: an `authorization` header, and the CSRF one the
35
+ * app's `useCSRFPrevention` asks of a `GET` (the client sends none of its
36
+ * own: its name is the app's).
37
+ */
32
38
  readonly headers?: HeadersInit;
39
+ /** How a call is sent unless it says. Default `'POST'`. */
40
+ readonly method?: HttpMethod;
33
41
  }
34
42
  export interface QueryOptions<TVars = Record<string, unknown>> {
35
43
  readonly variables?: TVars;
36
44
  readonly operationName?: string;
37
45
  /** Added to the client's, and replacing one of the same name. */
38
46
  readonly headers?: HeadersInit;
47
+ /** This call's method, over the client's. */
48
+ readonly method?: HttpMethod;
49
+ /**
50
+ * Sent as `extensions`, beside the `persistedQuery` that `persisted`
51
+ * adds: what an app that reads an operation's id from its own extension
52
+ * (`extractPersistedOperationId`) is sent.
53
+ */
54
+ readonly extensions?: Record<string, unknown>;
55
+ /**
56
+ * The hash of a persisted operation, sent as Apollo's
57
+ * `extensions.persistedQuery: { version: 1, sha256Hash }`, the shape of
58
+ * `@graphql-yoga/plugin-persisted-operations` by default. With a
59
+ * document it is sent too; alone, only it is.
60
+ */
61
+ readonly persisted?: string;
39
62
  }
63
+ /**
64
+ * A call with no document: the operation is the one `persisted` names, or
65
+ * the one an app reads from the `extensions` it is sent (an id).
66
+ */
67
+ export type PersistedQueryOptions<TVars = Record<string, unknown>> = QueryOptions<TVars> & ({
68
+ readonly persisted: string;
69
+ } | {
70
+ readonly extensions: Record<string, unknown>;
71
+ });
40
72
  export interface GraphQLClient {
41
73
  query<TData = unknown, TVars = Record<string, unknown>>(document: QueryDocument<TData, TVars>, options?: QueryOptions<TVars>): Promise<GraphQLResult<TData>>;
74
+ /** A persisted operation, by its hash or id alone: name `TData` yourself. */
75
+ query<TData = unknown, TVars = Record<string, unknown>>(options: PersistedQueryOptions<TVars>): Promise<GraphQLResult<TData>>;
42
76
  }
43
77
  /** What it calls: an alxia app, or anything with a `fetch(Request)`. */
44
78
  export interface Servable {
@@ -50,8 +84,10 @@ export interface Servable {
50
84
  * Yoga's plugins) in play. Meant for specs; import it from
51
85
  * `@alxia/graphql/testing`, never from the app.
52
86
  *
53
- * A body that is not JSON (a 413 from a body limit, a 404) leaves `data` and
54
- * `errors` unset: read `status`, or `response`'s headers.
87
+ * It POSTs JSON, or with `method: 'GET'` puts `query`, `variables`,
88
+ * `operationName` and `extensions` in the URL. A body that is not JSON (a 413
89
+ * from a body limit, a 404) leaves `data` and `errors` unset: read `status`,
90
+ * or `response`'s headers.
55
91
  */
56
92
  export declare function graphqlClient(app: Servable, options?: GraphQLClientOptions): GraphQLClient;
57
93
  //# sourceMappingURL=client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/testing/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAS,KAAK,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAEhF;;;;;GAKG;AACH,MAAM,MAAM,aAAa,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IACvE,MAAM,GACN,sBAAsB,CAAC,KAAK,SAAS,MAAM,GAAG,KAAK,GAAG,KAAK,EAAE,KAAK,CAAC,GACnE,CAAC,YAAY,GAAG;IAAE,SAAS,CAAC,EAAE,CAAC,SAAS,EAAE,KAAK,KAAK,KAAK,CAAA;CAAE,CAAC,CAAC;AAEhE,0CAA0C;AAC1C,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,CA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EACrD,QAAQ,EAAE,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,EACrC,OAAO,CAAC,EAAE,YAAY,CAAC,KAAK,CAAC,GAC3B,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC;IACjC,6EAA6E;IAC7E,KAAK,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACrD,OAAO,EAAE,qBAAqB,CAAC,KAAK,CAAC,GACnC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC;CACjC;AAED,wEAAwE;AACxE,MAAM,WAAW,QAAQ;IACxB,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACtD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAC5B,GAAG,EAAE,QAAQ,EACb,OAAO,GAAE,oBAAyB,GAChC,aAAa,CAiBf"}
@@ -1,2 +1,2 @@
1
- export { type GraphQLClient, type GraphQLClientOptions, type GraphQLResult, graphqlClient, type QueryDocument, type QueryOptions, type ResponseError, } from './client';
1
+ export { type GraphQLClient, type GraphQLClientOptions, type GraphQLResult, graphqlClient, type HttpMethod, type PersistedQueryOptions, type QueryDocument, type QueryOptions, type ResponseError, } from './client';
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAClB,aAAa,EACb,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,aAAa,GAClB,MAAM,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAClB,aAAa,EACb,KAAK,UAAU,EACf,KAAK,qBAAqB,EAC1B,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,aAAa,GAClB,MAAM,UAAU,CAAC"}
@@ -3,27 +3,49 @@ import { print } from "graphql";
3
3
  function graphqlClient(app, options = {}) {
4
4
  const { path = "/graphql" } = options;
5
5
  return {
6
- async query(document, call = {}) {
7
- const headers = new Headers(options.headers);
8
- headers.set("content-type", "application/json");
9
- for (const [name, value] of new Headers(call.headers)) {
10
- headers.set(name, value);
11
- }
12
- const body = JSON.stringify({
13
- query: typeof document === "string" ? document : print(document),
14
- variables: call.variables,
15
- operationName: call.operationName
16
- });
17
- const response = await app.fetch(new Request(new URL(path, "http://localhost"), {
18
- method: "POST",
19
- headers,
20
- body
21
- }));
6
+ async query(first, second = {}) {
7
+ const [document, call] = isCall(first) ? [undefined, first] : [first, second];
8
+ const response = await app.fetch(buildRequest(path, document, call, options));
22
9
  const text = await response.clone().text();
23
10
  return { status: response.status, ...parse(text), response };
24
11
  }
25
12
  };
26
13
  }
14
+ function isCall(value) {
15
+ return typeof value === "object" && !("kind" in value);
16
+ }
17
+ function payload(document, call) {
18
+ const extensions = {
19
+ ...call.extensions,
20
+ ...call.persisted === undefined ? {} : { persistedQuery: { version: 1, sha256Hash: call.persisted } }
21
+ };
22
+ return {
23
+ ...document === undefined ? {} : { query: typeof document === "string" ? document : print(document) },
24
+ ...call.variables === undefined ? {} : { variables: call.variables },
25
+ ...call.operationName === undefined ? {} : { operationName: call.operationName },
26
+ ...Object.keys(extensions).length === 0 ? {} : { extensions }
27
+ };
28
+ }
29
+ function buildRequest(path, document, call, client) {
30
+ const headers = new Headers(client.headers);
31
+ for (const [name, value] of new Headers(call.headers)) {
32
+ headers.set(name, value);
33
+ }
34
+ const url = new URL(path, "http://localhost");
35
+ const parts = payload(document, call);
36
+ if ((call.method ?? client.method ?? "POST") === "GET") {
37
+ for (const [name, value] of Object.entries(parts)) {
38
+ url.searchParams.set(name, typeof value === "string" ? value : JSON.stringify(value));
39
+ }
40
+ return new Request(url, { method: "GET", headers });
41
+ }
42
+ headers.set("content-type", "application/json");
43
+ return new Request(url, {
44
+ method: "POST",
45
+ headers,
46
+ body: JSON.stringify(parts)
47
+ });
48
+ }
27
49
  function parse(text) {
28
50
  try {
29
51
  const body = JSON.parse(text);
@@ -43,5 +65,5 @@ export {
43
65
  graphqlClient
44
66
  };
45
67
 
46
- //# debugId=BDA79F393E3D161364756E2164756E21
68
+ //# debugId=7C558AD3A041624964756E2164756E21
47
69
  //# sourceMappingURL=index.js.map
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/testing/client.ts"],
4
4
  "sourcesContent": [
5
- "import { type DocumentNode, print, type TypedQueryDocumentNode } from 'graphql';\n\n/**\n * A document that carries its types: `graphql`'s own `TypedQueryDocumentNode`,\n * or the `TypedDocumentNode` of `@graphql-typed-document-node/core` that\n * GraphQL Code Generator writes, read by its `__apiType` marker. Both are a\n * `DocumentNode` with an optional function, so neither package is imported.\n */\nexport type QueryDocument<TData = unknown, TVars = Record<string, unknown>> =\n\t| string\n\t| TypedQueryDocumentNode<TData extends object ? TData : never, TVars>\n\t| (DocumentNode & { __apiType?: (variables: TVars) => TData });\n\n/** One entry of a response's `errors`. */\nexport interface ResponseError {\n\treadonly message: string;\n\treadonly path?: readonly (string | number)[];\n\treadonly extensions?: {\n\t\treadonly code?: string;\n\t\treadonly [key: string]: unknown;\n\t};\n}\n\n/** What `query` resolves to: the HTTP status, the parsed body, the response. */\nexport interface GraphQLResult<TData = unknown> {\n\treadonly status: number;\n\treadonly data?: TData | null;\n\treadonly errors?: readonly ResponseError[];\n\t/** The response, its body still unread: `headers`, `ok`. */\n\treadonly response: Response;\n}\n\nexport interface GraphQLClientOptions {\n\t/** The endpoint's path. Default `/graphql`. */\n\treadonly path?: string;\n\t/** Sent with every query: an `authorization` header, a CSRF one. */\n\treadonly headers?: HeadersInit;\n}\n\nexport interface QueryOptions<TVars = Record<string, unknown>> {\n\treadonly variables?: TVars;\n\treadonly operationName?: string;\n\t/** Added to the client's, and replacing one of the same name. */\n\treadonly headers?: HeadersInit;\n}\n\nexport interface GraphQLClient {\n\tquery<TData = unknown, TVars = Record<string, unknown>>(\n\t\tdocument: QueryDocument<TData, TVars>,\n\t\toptions?: QueryOptions<TVars>,\n\t): Promise<GraphQLResult<TData>>;\n}\n\n/** What it calls: an alxia app, or anything with a `fetch(Request)`. */\nexport interface Servable {\n\tfetch(request: Request): Response | Promise<Response>;\n}\n\n/**\n * Sends operations to an app's GraphQL endpoint in process, through\n * `app.fetch`: no port, no server, the whole chain (middlewares, body limit,\n * Yoga's plugins) in play. Meant for specs; import it from\n * `@alxia/graphql/testing`, never from the app.\n *\n * A body that is not JSON (a 413 from a body limit, a 404) leaves `data` and\n * `errors` unset: read `status`, or `response`'s headers.\n */\nexport function graphqlClient(\n\tapp: Servable,\n\toptions: GraphQLClientOptions = {},\n): GraphQLClient {\n\tconst { path = '/graphql' } = options;\n\treturn {\n\t\tasync query(document, call = {}) {\n\t\t\tconst headers = new Headers(options.headers);\n\t\t\theaders.set('content-type', 'application/json');\n\t\t\tfor (const [name, value] of new Headers(call.headers)) {\n\t\t\t\theaders.set(name, value);\n\t\t\t}\n\t\t\tconst body = JSON.stringify({\n\t\t\t\tquery: typeof document === 'string' ? document : print(document),\n\t\t\t\tvariables: call.variables,\n\t\t\t\toperationName: call.operationName,\n\t\t\t});\n\t\t\tconst response = await app.fetch(\n\t\t\t\tnew Request(new URL(path, 'http://localhost'), {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders,\n\t\t\t\t\tbody,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tconst text = await response.clone().text();\n\t\t\treturn { status: response.status, ...parse(text), response };\n\t\t},\n\t};\n}\n\n/** `data` and `errors` of a JSON object body, each only when it has one. */\nfunction parse<TData>(text: string): {\n\tdata?: TData | null;\n\terrors?: readonly ResponseError[];\n} {\n\ttry {\n\t\tconst body: unknown = JSON.parse(text);\n\t\tif (typeof body !== 'object' || body === null || Array.isArray(body)) {\n\t\t\treturn {};\n\t\t}\n\t\tconst { data, errors } = body as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(data === undefined ? {} : { data: data as TData | null }),\n\t\t\t...(errors === undefined\n\t\t\t\t? {}\n\t\t\t\t: { errors: errors as readonly ResponseError[] }),\n\t\t};\n\t} catch {\n\t\treturn {};\n\t}\n}\n"
5
+ "import { type DocumentNode, print, type TypedQueryDocumentNode } from 'graphql';\n\n/**\n * A document that carries its types: `graphql`'s own `TypedQueryDocumentNode`,\n * or the `TypedDocumentNode` of `@graphql-typed-document-node/core` that\n * GraphQL Code Generator writes, read by its `__apiType` marker. Both are a\n * `DocumentNode` with an optional function, so neither package is imported.\n */\nexport type QueryDocument<TData = unknown, TVars = Record<string, unknown>> =\n\t| string\n\t| TypedQueryDocumentNode<TData extends object ? TData : never, TVars>\n\t| (DocumentNode & { __apiType?: (variables: TVars) => TData });\n\n/** One entry of a response's `errors`. */\nexport interface ResponseError {\n\treadonly message: string;\n\treadonly path?: readonly (string | number)[];\n\treadonly extensions?: {\n\t\treadonly code?: string;\n\t\treadonly [key: string]: unknown;\n\t};\n}\n\n/** What `query` resolves to: the HTTP status, the parsed body, the response. */\nexport interface GraphQLResult<TData = unknown> {\n\treadonly status: number;\n\treadonly data?: TData | null;\n\treadonly errors?: readonly ResponseError[];\n\t/** The response, its body still unread: `headers`, `ok`. */\n\treadonly response: Response;\n}\n\n/** How the operation travels: a JSON body, or the URL's query string. */\nexport type HttpMethod = 'GET' | 'POST';\n\nexport interface GraphQLClientOptions {\n\t/** The endpoint's path. Default `/graphql`. */\n\treadonly path?: string;\n\t/**\n\t * Sent with every query: an `authorization` header, and the CSRF one the\n\t * app's `useCSRFPrevention` asks of a `GET` (the client sends none of its\n\t * own: its name is the app's).\n\t */\n\treadonly headers?: HeadersInit;\n\t/** How a call is sent unless it says. Default `'POST'`. */\n\treadonly method?: HttpMethod;\n}\n\nexport interface QueryOptions<TVars = Record<string, unknown>> {\n\treadonly variables?: TVars;\n\treadonly operationName?: string;\n\t/** Added to the client's, and replacing one of the same name. */\n\treadonly headers?: HeadersInit;\n\t/** This call's method, over the client's. */\n\treadonly method?: HttpMethod;\n\t/**\n\t * Sent as `extensions`, beside the `persistedQuery` that `persisted`\n\t * adds: what an app that reads an operation's id from its own extension\n\t * (`extractPersistedOperationId`) is sent.\n\t */\n\treadonly extensions?: Record<string, unknown>;\n\t/**\n\t * The hash of a persisted operation, sent as Apollo's\n\t * `extensions.persistedQuery: { version: 1, sha256Hash }`, the shape of\n\t * `@graphql-yoga/plugin-persisted-operations` by default. With a\n\t * document it is sent too; alone, only it is.\n\t */\n\treadonly persisted?: string;\n}\n\n/**\n * A call with no document: the operation is the one `persisted` names, or\n * the one an app reads from the `extensions` it is sent (an id).\n */\nexport type PersistedQueryOptions<TVars = Record<string, unknown>> =\n\tQueryOptions<TVars> &\n\t\t(\n\t\t\t| { readonly persisted: string }\n\t\t\t| { readonly extensions: Record<string, unknown> }\n\t\t);\n\nexport interface GraphQLClient {\n\tquery<TData = unknown, TVars = Record<string, unknown>>(\n\t\tdocument: QueryDocument<TData, TVars>,\n\t\toptions?: QueryOptions<TVars>,\n\t): Promise<GraphQLResult<TData>>;\n\t/** A persisted operation, by its hash or id alone: name `TData` yourself. */\n\tquery<TData = unknown, TVars = Record<string, unknown>>(\n\t\toptions: PersistedQueryOptions<TVars>,\n\t): Promise<GraphQLResult<TData>>;\n}\n\n/** What it calls: an alxia app, or anything with a `fetch(Request)`. */\nexport interface Servable {\n\tfetch(request: Request): Response | Promise<Response>;\n}\n\n/**\n * Sends operations to an app's GraphQL endpoint in process, through\n * `app.fetch`: no port, no server, the whole chain (middlewares, body limit,\n * Yoga's plugins) in play. Meant for specs; import it from\n * `@alxia/graphql/testing`, never from the app.\n *\n * It POSTs JSON, or with `method: 'GET'` puts `query`, `variables`,\n * `operationName` and `extensions` in the URL. A body that is not JSON (a 413\n * from a body limit, a 404) leaves `data` and `errors` unset: read `status`,\n * or `response`'s headers.\n */\nexport function graphqlClient(\n\tapp: Servable,\n\toptions: GraphQLClientOptions = {},\n): GraphQLClient {\n\tconst { path = '/graphql' } = options;\n\treturn {\n\t\tasync query(\n\t\t\tfirst: QueryDocument | PersistedQueryOptions,\n\t\t\tsecond: QueryOptions = {},\n\t\t) {\n\t\t\tconst [document, call] = isCall(first)\n\t\t\t\t? [undefined, first]\n\t\t\t\t: [first, second];\n\t\t\tconst response = await app.fetch(\n\t\t\t\tbuildRequest(path, document, call, options),\n\t\t\t);\n\t\t\tconst text = await response.clone().text();\n\t\t\treturn { status: response.status, ...parse(text), response };\n\t\t},\n\t} as GraphQLClient;\n}\n\n/** A call's options, not a document: a `DocumentNode` has a `kind`. */\nfunction isCall(\n\tvalue: QueryDocument | PersistedQueryOptions,\n): value is PersistedQueryOptions {\n\treturn typeof value === 'object' && !('kind' in value);\n}\n\n/** The operation's parts, each only when the call has it. */\nfunction payload(\n\tdocument: QueryDocument | undefined,\n\tcall: QueryOptions,\n): Record<string, unknown> {\n\tconst extensions = {\n\t\t...call.extensions,\n\t\t...(call.persisted === undefined\n\t\t\t? {}\n\t\t\t: { persistedQuery: { version: 1, sha256Hash: call.persisted } }),\n\t};\n\treturn {\n\t\t...(document === undefined\n\t\t\t? {}\n\t\t\t: { query: typeof document === 'string' ? document : print(document) }),\n\t\t...(call.variables === undefined ? {} : { variables: call.variables }),\n\t\t...(call.operationName === undefined\n\t\t\t? {}\n\t\t\t: { operationName: call.operationName }),\n\t\t...(Object.keys(extensions).length === 0 ? {} : { extensions }),\n\t};\n}\n\nfunction buildRequest(\n\tpath: string,\n\tdocument: QueryDocument | undefined,\n\tcall: QueryOptions,\n\tclient: GraphQLClientOptions,\n): Request {\n\tconst headers = new Headers(client.headers);\n\tfor (const [name, value] of new Headers(call.headers)) {\n\t\theaders.set(name, value);\n\t}\n\tconst url = new URL(path, 'http://localhost');\n\tconst parts = payload(document, call);\n\tif ((call.method ?? client.method ?? 'POST') === 'GET') {\n\t\t// `variables` and `extensions` are JSON in the URL, as Yoga reads them.\n\t\tfor (const [name, value] of Object.entries(parts)) {\n\t\t\turl.searchParams.set(\n\t\t\t\tname,\n\t\t\t\ttypeof value === 'string' ? value : JSON.stringify(value),\n\t\t\t);\n\t\t}\n\t\treturn new Request(url, { method: 'GET', headers });\n\t}\n\theaders.set('content-type', 'application/json');\n\treturn new Request(url, {\n\t\tmethod: 'POST',\n\t\theaders,\n\t\tbody: JSON.stringify(parts),\n\t});\n}\n\n/** `data` and `errors` of a JSON object body, each only when it has one. */\nfunction parse<TData>(text: string): {\n\tdata?: TData | null;\n\terrors?: readonly ResponseError[];\n} {\n\ttry {\n\t\tconst body: unknown = JSON.parse(text);\n\t\tif (typeof body !== 'object' || body === null || Array.isArray(body)) {\n\t\t\treturn {};\n\t\t}\n\t\tconst { data, errors } = body as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(data === undefined ? {} : { data: data as TData | null }),\n\t\t\t...(errors === undefined\n\t\t\t\t? {}\n\t\t\t\t: { errors: errors as readonly ResponseError[] }),\n\t\t};\n\t} catch {\n\t\treturn {};\n\t}\n}\n"
6
6
  ],
7
- "mappings": ";AAAA;AAmEO,SAAS,aAAa,CAC5B,KACA,UAAgC,CAAC,GACjB;AAAA,EAChB,QAAQ,OAAO,eAAe;AAAA,EAC9B,OAAO;AAAA,SACA,MAAK,CAAC,UAAU,OAAO,CAAC,GAAG;AAAA,MAChC,MAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;AAAA,MAC3C,QAAQ,IAAI,gBAAgB,kBAAkB;AAAA,MAC9C,YAAY,MAAM,UAAU,IAAI,QAAQ,KAAK,OAAO,GAAG;AAAA,QACtD,QAAQ,IAAI,MAAM,KAAK;AAAA,MACxB;AAAA,MACA,MAAM,OAAO,KAAK,UAAU;AAAA,QAC3B,OAAO,OAAO,aAAa,WAAW,WAAW,MAAM,QAAQ;AAAA,QAC/D,WAAW,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A,QAAQ,IAAI,gBAAgB,kBAAkB;AAAA,EAC9C,OAAO,IAAI,QAAQ,KAAK;AAAA,IACvB,QAAQ;AAAA,IACR;AAAA,IACA,MAAM,KAAK,UAAU,KAAK;AAAA,EAC3B,CAAC;AAAA;AAIF,SAAS,KAAY,CAAC,MAGpB;AAAA,EACD,IAAI;AAAA,IACH,MAAM,OAAgB,KAAK,MAAM,IAAI;AAAA,IACrC,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,IAAI,GAAG;AAAA,MACrE,OAAO,CAAC;AAAA,IACT;AAAA,IACA,QAAQ,MAAM,WAAW;AAAA,IACzB,OAAO;AAAA,SACF,SAAS,YAAY,CAAC,IAAI,EAAE,KAA2B;AAAA,SACvD,WAAW,YACZ,CAAC,IACD,EAAE,OAA2C;AAAA,IACjD;AAAA,IACC,MAAM;AAAA,IACP,OAAO,CAAC;AAAA;AAAA;",
8
+ "debugId": "7C558AD3A041624964756E2164756E21",
9
9
  "names": []
10
10
  }
package/docs/README.md CHANGED
@@ -14,7 +14,7 @@ a realistic example for each.
14
14
  | [GraphQL over WebSocket](guide/websockets.md) | serving Apollo Client's, urql's or `graphql-ws`'s WebSocket clients with `ws: true`, guarding the upgrade, reading `connectionParams`, the subprotocol, closing the sockets on shutdown, or testing a subscription over a socket |
15
15
  | [Harden it for production](guide/production.md) | putting a GraphQL API on the internet: rate limiting the endpoint, depth limits, introspection off outside development, masked errors and the errors a client may read, a body limit, CSRF for a cookie session, persisted operations |
16
16
  | [GraphiQL and Apollo Sandbox](guide/ide.md) | choosing the IDE a browser gets, configuring it, keeping it working under a strict `Content-Security-Policy`, or serving it outside dev with `ide: 'graphiql'` |
17
- | [Testing the endpoint](guide/testing.md) | testing a GraphQL app without a server: `graphqlClient`, an auth header, a custom path, a typed document, the HTTP status of a 400 or a 413 |
17
+ | [Testing the endpoint](guide/testing.md) | testing a GraphQL app without a server: `graphqlClient`, an auth header, a custom path, `GET`, persisted operations, the CSRF header, a typed document, the HTTP status of a 400 or a 413 |
18
18
  | [Troubleshooting](troubleshooting.md) | something went wrong and you have the message |
19
19
  | [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
20
20
 
@@ -98,10 +98,74 @@ data?.hello; // string
98
98
  // client.query(Hello, { variables: { name: 1 } }); // compile error
99
99
  ```
100
100
 
101
+ ## GET
102
+
103
+ `method: 'GET'` puts the operation in the URL instead of a JSON body:
104
+ `query`, `operationName`, and `variables` and `extensions` as JSON. Set it
105
+ per call, or for every call with `graphqlClient(app, { method: 'GET' })`; a
106
+ call's own `method` wins.
107
+
108
+ ```ts
109
+ const { data } = await client.query('query ($name: String) { hello(name: $name) }', {
110
+ method: 'GET',
111
+ variables: { name: 'Ada' },
112
+ });
113
+ ```
114
+
115
+ A `GET` has no `Content-Type`.
116
+
117
+ ## Persisted operations
118
+
119
+ `persisted` is the hash of an operation the app registered. It is sent as
120
+ Apollo's `extensions.persistedQuery: { version: 1, sha256Hash }`, the shape
121
+ `@graphql-yoga/plugin-persisted-operations` reads by default. With no
122
+ document, only the hash is sent, so an app that allows nothing else
123
+ (`allowArbitraryOperations: false`) can be tested; `TData` is yours to name,
124
+ since nothing types it:
125
+
126
+ ```ts
127
+ const result = await client.query<{ notes: { text: string }[] }>({
128
+ persisted: '5f1bb2a0c2a0',
129
+ variables: { first: 10 },
130
+ method: 'GET', // or the default POST
131
+ });
132
+ ```
133
+
134
+ With a document too, both are sent (Apollo's automatic persisted queries
135
+ register one that way). An unknown hash is the server's own answer, not a
136
+ client error: with the plugin's defaults, `errors[0].message` is
137
+ `PersistedQueryNotFound`, with code `PERSISTED_QUERY_NOT_IN_LIST`; a
138
+ document sent to an app that allows only persisted ones is
139
+ `PersistedQueryOnly`.
140
+
141
+ An app that names an operation by an **id** in an extension of its own
142
+ (a custom `extractPersistedOperationId`) is sent that extension: `extensions`
143
+ is sent as given, and counts as a call with no document.
144
+
145
+ ```ts
146
+ await client.query({ extensions: { documentId: 'abc123' } });
147
+ ```
148
+
149
+ ## CSRF
150
+
151
+ The client sends **no CSRF header of its own**: its name belongs to the app
152
+ (`x-graphql-yoga-csrf` by default in Yoga's `useCSRFPrevention`, `x-csrf` in
153
+ the [recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md)),
154
+ and a spec that never sends it could not see the plugin refuse. Put it in the
155
+ client's `headers`, as a browser app does in its own client. Yoga's plugin lets
156
+ a JSON `POST` through with no header, since a browser needs a preflight for
157
+ that content type, but refuses a `GET` (no content type) with a 403
158
+ (`Required CSRF header(s) not present`): test that with a `GET` without the
159
+ header, and the app's real traffic with it.
160
+
161
+ ```ts
162
+ const production = graphqlClient(app, { headers: { 'x-csrf': '1' } });
163
+ expect((await graphqlClient(app).query('{ me { name } }', { method: 'GET' })).status).toBe(403);
164
+ ```
165
+
101
166
  ## Not covered
102
167
 
103
- It always POSTs JSON. A subscription over server-sent events or a socket,
104
- a `GET` and a persisted operation sent by hash are not sent by it; use
105
- `app.request` for those (the
168
+ A subscription over server-sent events or a socket, a form-encoded `POST`
169
+ and a batch are not sent by it; use `app.request` for those (the
106
170
  [recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md#6-test-it-in-process)
107
- reads a stream).
171
+ reads a stream, and checks the 415 a form gets).
package/docs/roadmap.md CHANGED
@@ -7,31 +7,11 @@ number on it. Every release, with each change it made, is in
7
7
 
8
8
  ## Now
9
9
 
10
- - **GraphiQL in dev alone, under a pinned policy.** Without `ide`, a
11
- browser gets GraphiQL only while the serving app is in dev
12
- (`NODE_ENV=development`, or `alxia({ dev: true })`); `ide: 'graphiql'`
13
- serves it everywhere. Its `Content-Security-Policy` allows the one
14
- pinned `@graphql-yoga/graphiql` folder it loads from, the Monaco workers
15
- included, and no frame ([IDE guide](guide/ide.md)).
16
- - **Subscriptions drained on shutdown.** When the app starts shutting
17
- down — `SIGTERM`, `SIGINT`, `stop()` — a subscription over server-sent
18
- events ends, so `@alxia/core`'s drain answers the queries in flight and
19
- exits without waiting for it; `health()` probes mount beside the
20
- endpoint, and GraphQL errors stay in `errors[]` under core's problem
21
- details ([endpoint guide](guide/endpoint.md#errors-health-and-shutdown)).
22
- - **GraphQL over WebSocket.** `ws: true` serves the endpoint over
23
- WebSocket too, with the `graphql-transport-ws` protocol of `graphql-ws`
24
- — Apollo Client's and urql's default — beside server-sent events: the
25
- upgrade runs the app's middlewares, so a guard refuses the socket and a
26
- resolver reads what they added; each operation runs through Yoga's
27
- plugins, with the client's `connectionParams` in its context; a
28
- shutdown closes the sockets with 1001 and completes their subscriptions
29
- ([WebSocket guide](guide/websockets.md)).
10
+ Nothing in progress.
30
11
 
31
12
  ## Next
32
13
 
33
- - **Persisted operations in the test client.** A `GET` and a hash sent in
34
- place of the document, for an app that allows nothing else.
14
+ Nothing scheduled yet.
35
15
 
36
16
  ## Later
37
17
 
@@ -39,6 +19,13 @@ Nothing scheduled yet.
39
19
 
40
20
  ## Shipped
41
21
 
22
+ ### 0.8.0
23
+
24
+ - **`GET` and persisted operations in the test client.** `graphqlClient`
25
+ sends `method: 'GET'` with the operation in the URL, and `persisted`, the
26
+ hash of a registered operation, with no document, so an app that allows
27
+ nothing else can be tested; it adds no CSRF header of its own ([testing guide](guide/testing.md#persisted-operations)).
28
+
42
29
  ### 0.7.0
43
30
 
44
31
  - **A test client.** `graphqlClient(app)` from `@alxia/graphql/testing`
@@ -54,6 +41,32 @@ Nothing scheduled yet.
54
41
 
55
42
  - **The operation, told to the observers.** Each operation the endpoint executes is reported to the middlewares around it: `@alxia/logger` writes `operationName` and `operationType` on the request's line, `@alxia/telemetry` names its span `query GetNotes` with `graphql.operation.name` and `graphql.operation.type`. A batched body is one line and one span, `batch`, with every name ([endpoint guide](guide/endpoint.md#the-operation-in-the-log-and-the-trace)).
56
43
 
44
+ ### 0.4.0
45
+
46
+ - **GraphQL over WebSocket.** `ws: true` serves the endpoint over
47
+ WebSocket too, with the `graphql-transport-ws` protocol of `graphql-ws`
48
+ — Apollo Client's and urql's default — beside server-sent events: the
49
+ upgrade runs the app's middlewares, so a guard refuses the socket and a
50
+ resolver reads what they added; each operation runs through Yoga's
51
+ plugins, with the client's `connectionParams` in its context; a
52
+ shutdown closes the sockets with 1001 and completes their subscriptions
53
+ ([WebSocket guide](guide/websockets.md)).
54
+
55
+ ### 0.3.0
56
+
57
+ - **GraphiQL in dev alone, under a pinned policy.** Without `ide`, a
58
+ browser gets GraphiQL only while the serving app is in dev
59
+ (`NODE_ENV=development`, or `alxia({ dev: true })`); `ide: 'graphiql'`
60
+ serves it everywhere. Its `Content-Security-Policy` allows the one
61
+ pinned `@graphql-yoga/graphiql` folder it loads from, the Monaco workers
62
+ included, and no frame ([IDE guide](guide/ide.md)).
63
+ - **Subscriptions drained on shutdown.** When the app starts shutting
64
+ down — `SIGTERM`, `SIGINT`, `stop()` — a subscription over server-sent
65
+ events ends, so `@alxia/core`'s drain answers the queries in flight and
66
+ exits without waiting for it; `health()` probes mount beside the
67
+ endpoint, and GraphQL errors stay in `errors[]` under core's problem
68
+ details ([endpoint guide](guide/endpoint.md#errors-health-and-shutdown)).
69
+
57
70
  ### 0.1.0
58
71
 
59
72
  - **GraphQL Yoga as a route.** `graphql(app, options)` serves a schema at
@@ -28,6 +28,8 @@ symptom.
28
28
  **Responses**
29
29
 
30
30
  - [`200 {"errors":[{"message":"Unexpected error.", … "code":"INTERNAL_SERVER_ERROR"}}]}`](#200-errorsmessageunexpected-error--codeinternal_server_error)
31
+ - [`403 Required CSRF header(s) not present` from the test client](#403-required-csrf-headers-not-present-from-the-test-client)
32
+ - [`PersistedQueryNotFound` or `PersistedQueryOnly`](#persistedquerynotfound-or-persistedqueryonly)
31
33
  - [`405 {"error":"method_not_allowed"}` on `OPTIONS /graphql`](#405-errormethod_not_allowed-on-options-graphql)
32
34
  - [`405 {"errors":[{"message":"Can only perform a mutation operation from a POST request."}]}`](#405-errorsmessagecan-only-perform-a-mutation-operation-from-a-post-request)
33
35
  - [`406` with an empty body](#406-with-an-empty-body)
@@ -309,6 +311,36 @@ alxia()
309
311
  .plugin((app) => graphql(app, { schema }));
310
312
  ```
311
313
 
314
+ ### `403 Required CSRF header(s) not present` from the test client
315
+
316
+ **When:** `graphqlClient(app).query(…, { method: 'GET' })` on an app with
317
+ Yoga's `useCSRFPrevention`.
318
+
319
+ **Why:** a `GET` has no `Content-Type`, so the plugin asks for its header,
320
+ and the client sends none of its own: its name is the app's. A JSON `POST`
321
+ passes without it.
322
+
323
+ **Fix:** the app's header, in the client's `headers`:
324
+
325
+ ```ts
326
+ graphqlClient(app, { headers: { 'x-csrf': '1' } });
327
+ ```
328
+
329
+ ### `PersistedQueryNotFound` or `PersistedQueryOnly`
330
+
331
+ **When:** `query({ persisted: hash })` answers `PersistedQueryNotFound`
332
+ (`PERSISTED_QUERY_NOT_IN_LIST`), or a call with a document answers
333
+ `PersistedQueryOnly` (`CANNOT_SEND_PQ_ID_AND_BODY`); `PersistedQueryKeyNotFound`
334
+ when no id was found.
335
+
336
+ **Why:** the app's `usePersistedOperations` does not know the hash, refuses
337
+ every document (`allowArbitraryOperations: false`), or reads the id from an
338
+ extension other than `persistedQuery.sha256Hash` (its default, which
339
+ `persisted` sends).
340
+
341
+ **Fix:** register the hash, send no document, or send the app's own extension:
342
+ `query({ extensions: { documentId } })`.
343
+
312
344
  ### `405 {"error":"method_not_allowed"}` on `OPTIONS /graphql`
313
345
 
314
346
  **When:** a browser on another origin calls the endpoint; its preflight
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alxia/graphql",
3
- "version": "0.7.1",
3
+ "version": "0.8.1",
4
4
  "description": "GraphQL for alxia with GraphQL Yoga: its plugins, subscriptions over SSE or WebSocket (graphql-ws) and GraphiQL, behind the app's hooks, its resolvers reading the app's typed context",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -47,13 +47,13 @@
47
47
  ]
48
48
  },
49
49
  "devDependencies": {
50
- "@alxia/core": "^0.14.0",
50
+ "@alxia/core": "^0.14.2",
51
51
  "@alxia/logger": "^0.6.6",
52
- "@alxia/telemetry": "^0.7.3",
52
+ "@alxia/telemetry": "^0.7.4",
53
53
  "@envelop/depth-limit": "^7.2.1",
54
54
  "@graphql-yoga/plugin-csrf-prevention": "^3.24.2",
55
55
  "@graphql-yoga/plugin-persisted-operations": "^3.24.2",
56
- "@nxgt/telemetry": "^0.2.1",
56
+ "@nxgt/telemetry": "^0.2.2",
57
57
  "@types/bun": "^1.4.2",
58
58
  "dataloader": "^2.2.3",
59
59
  "graphql": "^16.11.0",
@@ -61,7 +61,7 @@
61
61
  "graphql-yoga": "^5.16.0"
62
62
  },
63
63
  "peerDependencies": {
64
- "@alxia/core": "^0.14.0",
64
+ "@alxia/core": "^0.14.2",
65
65
  "graphql": "^16.11.0 || ^17.0.0",
66
66
  "graphql-ws": "^6.1.0",
67
67
  "graphql-yoga": "^5.16.0",