@alxia/graphql 0.8.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -186,6 +186,42 @@ their subscriptions. `ws: { path, keepAlive }` moves the socket or spaces
186
186
  its pings. See [the WebSocket guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/websockets.md),
187
187
  Apollo Client's and urql's setup included.
188
188
 
189
+ ## Limits
190
+
191
+ Four limits bound what a request costs before any resolver runs. A document
192
+ may hold at most **15 000 tokens** (`maxTokens`, `false` for no cap): a longer
193
+ one is refused by the parser as `GRAPHQL_PARSE_FAILED`, 400 under
194
+ `application/graphql-response+json`, and never reaches the schema. It may
195
+ nest at most **1 000 levels** of `{`, `(` and `[` (`maxNesting`, `false` for
196
+ no limit): graphql-js parses by recursion and overflows the stack a few
197
+ thousand levels down, so a deeper document is refused the same way before the
198
+ parser recurses into it, never a 500. It counts `{`, `(` and `[` together,
199
+ arguments and lists included, so it is not a selection-depth rule; use a
200
+ validation rule for that. The
201
+ documents Yoga parses are kept in a cache bounded by weight, **64 MiB** per
202
+ endpoint, **1 024** documents, **one hour** (`parseCache`), where Yoga's own
203
+ has no size bound. A `POST` body may hold **1 MiB** (`bodyLimit`) unless the
204
+ app declared its own `bodyLimit()` before `graphql()`, which is kept; a body
205
+ past it is core's 413 and never reaches Yoga. `bodyLimit` bounds a `POST`
206
+ alone: a WebSocket `subscribe` message is bounded by Bun's `maxPayloadLength`
207
+ (16 MiB by default):
208
+
209
+ ```ts
210
+ graphql(app, {
211
+ schema,
212
+ maxTokens: 20_000, // false: no cap
213
+ parseCache: { maxBytes: 32 * 1024 * 1024, max: 512, ttl: 30 * 60_000 }, // false: no cache
214
+ bodyLimit: 5 * 1024 * 1024, // 1 MiB by default; a multipart upload needs more
215
+ });
216
+ ```
217
+
218
+ A refused document is a 200 with `errors` under `application/json` (400 under
219
+ `application/graphql-response+json`). A bad option value throws a `TypeError`
220
+ where `graphql()` is declared.
221
+
222
+ A client query is a few thousand tokens; the introspection query is 163. See
223
+ [Cap what a request costs](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/production.md#cap-what-a-request-costs).
224
+
189
225
  ## Errors, health and shutdown
190
226
 
191
227
  A GraphQL error stays GraphQL's — an entry of `errors[]`, inside a 200 —
@@ -238,7 +274,7 @@ See
238
274
 
239
275
  | export | |
240
276
  | --- | --- |
241
- | `graphql(app, options)` | the endpoint: `schema`, `path`, `ide`, `sandbox`, `ws`, and every Yoga option |
277
+ | `graphql(app, options)` | the endpoint: `schema`, `path`, `ide`, `sandbox`, `ws`, `maxTokens`, `maxNesting`, `parseCache`, `bodyLimit`, and every Yoga option |
242
278
  | `GraphQLWsOptions` | `ws`'s options: `path`, `keepAlive` |
243
279
  | `GraphQLWsContext` | what an operation over WebSocket adds to the context: `connectionParams` |
244
280
  | `renderSandbox(endpoint, options?)`, `SANDBOX_POLICY` | the Sandbox page, and the policy it loads under |
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Yoga reads the request body itself, and turns any failure of the read
3
3
  * into its own 400. A body past core's `bodyLimit` fails the read with a
4
- * `ContentTooLargeError`; `watchBody` keeps that error, so the handler
5
- * can throw it again once Yoga has answered, and the app's own boundary
4
+ * `ContentTooLargeError`; `watchBody` keeps that error and hands Yoga its
5
+ * own 413 error in its place, so Yoga logs nothing, and the handler can
6
+ * throw core's again once Yoga has answered: the app's own boundary
6
7
  * answers the 413 in its error format, leaking nothing of Yoga's.
7
8
  */
8
9
  import type { ContentTooLargeError } from '@alxia/core';
@@ -1 +1 @@
1
- {"version":3,"file":"body-refusal.d.ts","sourceRoot":"","sources":["../src/body-refusal.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAcxD,MAAM,WAAW,cAAc;IAC9B,+DAA+D;IAC/D,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,yEAAyE;IACzE,OAAO,IAAI,oBAAoB,GAAG,SAAS,CAAC;CAC5C;AAED,sFAAsF;AACtF,wBAAgB,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,cAAc,CAwB1D;AAMD;;;;;GAKG;AACH,wBAAsB,oBAAoB,CACzC,QAAQ,EAAE,QAAQ,GAChB,OAAO,CAAC,QAAQ,CAAC,CAqBnB"}
1
+ {"version":3,"file":"body-refusal.d.ts","sourceRoot":"","sources":["../src/body-refusal.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAexD,MAAM,WAAW,cAAc;IAC9B,+DAA+D;IAC/D,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,yEAAyE;IACzE,OAAO,IAAI,oBAAoB,GAAG,SAAS,CAAC;CAC5C;AAED,sFAAsF;AACtF,wBAAgB,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,cAAc,CAgC1D;AAMD;;;;;GAKG;AACH,wBAAsB,oBAAoB,CACzC,QAAQ,EAAE,QAAQ,GAChB,OAAO,CAAC,QAAQ,CAAC,CAqBnB"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The parse cache `graphql()` gives Yoga: a least-recently-used map bounded
3
+ * by entries, by age and by estimated bytes, since a parsed document costs
4
+ * by its tokens and no count of entries bounds that.
5
+ */
6
+ import { type DocumentNode } from 'graphql';
7
+ /** Yoga's `Cache` contract. */
8
+ export interface Cache<T> {
9
+ get(key: string): T | undefined;
10
+ set(key: string, value: T): void;
11
+ }
12
+ export interface BoundedCacheOptions<T> {
13
+ /** The most entries kept. */
14
+ readonly max: number;
15
+ /** How long an entry lives, in milliseconds. */
16
+ readonly ttl: number;
17
+ /** The most estimated bytes kept, the sum of the weights. */
18
+ readonly maxBytes: number;
19
+ /** The estimated bytes an entry holds. */
20
+ readonly weigh: (key: string, value: T) => number;
21
+ /** The clock, in milliseconds; injectable for the specs. */
22
+ readonly now?: () => number;
23
+ }
24
+ /**
25
+ * A least-recently-used cache that evicts by `max`, `ttl` and `maxBytes`.
26
+ * An entry heavier than `maxBytes / 8` is not stored and evicts nothing.
27
+ */
28
+ export declare function boundedCache<T>(options: BoundedCacheOptions<T>): Cache<T>;
29
+ /**
30
+ * A parsed document's estimated bytes: every token the lexer linked,
31
+ * comments included, plus the source as the key and as token values, plus
32
+ * 32 B per char of escaped string literals. Without `loc` (`noLocation`),
33
+ * nothing tells where the strings are: `tokenCount` and 36 B per char stand
34
+ * in; without `tokenCount` (older graphql), the source's length does.
35
+ */
36
+ export declare function documentWeight(source: string, document: DocumentNode): number;
37
+ /** A parse error's estimated bytes: its source as the key, and the error (1 024 B). */
38
+ export declare function errorWeight(source: string): number;
39
+ //# sourceMappingURL=document-cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document-cache.d.ts","sourceRoot":"","sources":["../src/document-cache.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,KAAK,YAAY,EAAyB,MAAM,SAAS,CAAC;AAEnE,+BAA+B;AAC/B,MAAM,WAAW,KAAK,CAAC,CAAC;IACvB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS,CAAC;IAChC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC;CACjC;AAED,MAAM,WAAW,mBAAmB,CAAC,CAAC;IACrC,6BAA6B;IAC7B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,gDAAgD;IAChD,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,6DAA6D;IAC7D,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,0CAA0C;IAC1C,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,KAAK,MAAM,CAAC;IAClD,4DAA4D;IAC5D,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC5B;AAQD;;;GAGG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,OAAO,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAoCzE;AA2DD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,GAAG,MAAM,CAc7E;AAED,uFAAuF;AACvF,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAElD"}
@@ -0,0 +1,5 @@
1
+ import type { Alxia } from '@alxia/core';
2
+ import type { graphqlSocket } from './ws';
3
+ /** `GET` and `POST` at `path` on `app`, and the WebSocket when `ws` is on. */
4
+ export declare function declareEndpoint(app: Alxia<never, string>, path: string, handler: unknown, bodyLimit: number | undefined, socket: ReturnType<typeof graphqlSocket> | undefined): void;
5
+ //# sourceMappingURL=endpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endpoint.d.ts","sourceRoot":"","sources":["../src/endpoint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AAK1C,8EAA8E;AAC9E,wBAAgB,eAAe,CAC9B,GAAG,EAAE,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,EACzB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,MAAM,EAAE,UAAU,CAAC,OAAO,aAAa,CAAC,GAAG,SAAS,GAClD,IAAI,CAkBN"}
package/dist/graphql.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type Alxia, type BaseContext, type Empty, type RoutePath } from '@alxia/core';
2
2
  import type { GraphQLSchemaWithContext, YogaInitialContext, YogaServerOptions } from 'graphql-yoga';
3
3
  import { type YogaContext } from './handler';
4
+ import { type ParseCacheOptions } from './parse-limits';
4
5
  import type { SandboxOptions } from './sandbox';
5
6
  import { type GraphQLWsOptions } from './ws';
6
7
  /** The parts of a route's context Yoga owns, or that mean nothing to a resolver. */
@@ -66,6 +67,36 @@ export interface GraphQLOptions<ServerCtx extends YogaContext, UserCtx extends Y
66
67
  * events, which stay served beside it.
67
68
  */
68
69
  readonly ws?: boolean | GraphQLWsOptions;
70
+ /**
71
+ * The most tokens a document may hold, 15 000 by default (Apollo
72
+ * Router's own), or `false` for no cap. A longer document is refused by
73
+ * the parser before anything runs, as Yoga refuses any document it
74
+ * cannot parse: `GRAPHQL_PARSE_FAILED`.
75
+ */
76
+ readonly maxTokens?: number | false;
77
+ /**
78
+ * The most levels of `{`, `(` and `[` a document may nest, 1 000 by
79
+ * default, or `false` for no limit. A deeper document is refused before
80
+ * the parser recurses into it, as `GRAPHQL_PARSE_FAILED`: graphql-js
81
+ * overflows the stack a few thousand levels down, well under
82
+ * `maxTokens`. A document that overflows it anyway is refused the same
83
+ * way.
84
+ */
85
+ readonly maxNesting?: number | false;
86
+ /**
87
+ * The cache of parsed documents, one per endpoint, weighed by its tokens and bytes:
88
+ * `maxBytes` (64 MiB by default), `max` documents (1 024) and `ttl`
89
+ * milliseconds (one hour). `false` parses every request. Yoga's own
90
+ * `parserAndValidationCache` replaces it, and cannot be given with it.
91
+ */
92
+ readonly parseCache?: false | ParseCacheOptions;
93
+ /**
94
+ * The most bytes a `POST` body may hold, over which core answers a 413.
95
+ * Without it, the `bodyLimit()` the app declared before `graphql()`
96
+ * applies as it is; without that, 1 MiB. An upload through a
97
+ * `multipart` mutation needs a larger one.
98
+ */
99
+ readonly bodyLimit?: number;
69
100
  }
70
101
  /**
71
102
  * The check Yoga's types leave out: the context the app builds must hold
@@ -1 +1 @@
1
- {"version":3,"file":"graphql.d.ts","sourceRoot":"","sources":["../src/graphql.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,KAAK,EACV,K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;;GAIG;AACH,KAAK,eAAe,CAAC,QAAQ,EAAE,QAAQ,IAAI,QAAQ,SAAS,QAAQ,GACjE,OAAO,GACP;IACA,QAAQ,CAAC,MAAM,EAAE,yEAAyE,OAAO,CAChG,MAAM,QAAQ,EACd,MAAM,QAAQ,CACd,GACA,MAAM,EAAE,CAAC;CACV,CAAC;AAEJ;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,OAAO,CACtB,GAAG,SAAS,MAAM,EAClB,MAAM,SAAS,MAAM,EACrB,SAAS,EACT,OAAO,SAAS,WAAW,GAAG,KAAK,EACnC,KAAK,CAAC,IAAI,SAAS,SAAS,GAAG,UAAU,EAEzC,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EACvB,OAAO,EAAE,cAAc,CAAC,aAAa,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,GACpE,eAAe,CACd,kBAAkB,GAAG,aAAa,CAAC,GAAG,CAAC,GAAG,OAAO,EACjD,SAAS,CACT,GACA,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAkDpB"}
package/dist/handler.d.ts CHANGED
@@ -20,7 +20,7 @@ export declare function graphiqlPolicy(html: string): string;
20
20
  * mounted under a prefix serves the same routes at a longer path, and
21
21
  * GraphiQL must ask that one.
22
22
  */
23
- export declare function yogaServers<UserCtx extends YogaContext>(options: Omit<YogaServerOptions<YogaContext, UserCtx>, 'graphqlEndpoint'>): (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>;
23
+ export declare function yogaServers<UserCtx extends YogaContext>(options: Omit<YogaServerOptions<YogaContext, UserCtx>, 'graphqlEndpoint'>, caches?: () => YogaServerOptions<YogaContext, UserCtx>['parserAndValidationCache']): (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>;
24
24
  /**
25
25
  * What Yoga is handed as its server context: the route's context — the
26
26
  * middlewares' work — minus what a resolver has no use for.
@@ -1 +1 @@
1
- {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,UAAU,EAAkB,MAAM,aAAa,CAAC;AAChF,OAAO,EAEN,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAiC,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AAE/E,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAM9C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAanD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,SAAS,WAAW,EACtD,OAAO,EAAE,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,OAAO,CAAC,EAAE,iBAAiB,CAAC,GACvE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,CAahE;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAC5B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAYzB;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,WAAW,EACzD,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,EACtE,OAAO,EAAE,cAAc,GAAG,KAAK,IAK9B,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,WAAW,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,qJA4CxE"}
1
+ {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EACN,KAAK,WAAW,EAChB,KAAK,UAAU,EAGf,MAAM,aAAa,CAAC;AACrB,OAAO,EAEN,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAiC,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AAE/E,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAM9C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAanD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,SAAS,WAAW,EACtD,OAAO,EAAE,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,OAAO,CAAC,EAAE,iBAAiB,CAAC,EACzE,MAAM,CAAC,EAAE,MAAM,iBAAiB,CAC/B,WAAW,EACX,OAAO,CACP,CAAC,0BAA0B,CAAC,GAC3B,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,CAchE;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAC5B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAYzB;AAUD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,WAAW,EACzD,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,EACtE,OAAO,EAAE,cAAc,GAAG,KAAK,IAK9B,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,WAAW,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,qJAsDxE"}
package/dist/index.js CHANGED
@@ -3,13 +3,29 @@ import {
3
3
  isDev
4
4
  } from "@alxia/core";
5
5
 
6
+ // src/endpoint.ts
7
+ var DEFAULT_BODY_LIMIT = 1048576;
8
+ function declareEndpoint(app, path, handler, bodyLimit, socket) {
9
+ const route = app;
10
+ route.get(path, handler);
11
+ const inherited = app.routes.at(-1)?.bodyLimit;
12
+ route.post(path, { bodyLimit: bodyLimit ?? inherited ?? DEFAULT_BODY_LIMIT }, handler);
13
+ if (socket !== undefined) {
14
+ route.ws(socket.path, socket.middleware, socket.handlers);
15
+ }
16
+ }
17
+
6
18
  // src/handler.ts
7
- import { shutdownSignal } from "@alxia/core";
19
+ import {
20
+ shutdownSignal,
21
+ vary
22
+ } from "@alxia/core";
8
23
  import {
9
24
  createYoga
10
25
  } from "graphql-yoga";
11
26
 
12
27
  // src/body-refusal.ts
28
+ import { GraphQLError } from "graphql";
13
29
  function isTooLarge(error) {
14
30
  return error instanceof Error && error.name === "ContentTooLargeError" && typeof error.limit === "number";
15
31
  }
@@ -31,9 +47,15 @@ function watchBody(request) {
31
47
  else
32
48
  controller.enqueue(value);
33
49
  } catch (error) {
34
- if (isTooLarge(error))
35
- refused = error;
36
- throw error;
50
+ if (!isTooLarge(error))
51
+ throw error;
52
+ refused = error;
53
+ throw new GraphQLError("Request body too large", {
54
+ extensions: {
55
+ code: "REQUEST_ENTITY_TOO_LARGE",
56
+ http: { status: 413 }
57
+ }
58
+ });
37
59
  }
38
60
  },
39
61
  cancel: (reason) => reader.cancel(reason)
@@ -129,13 +151,14 @@ function graphiqlPolicy(html) {
129
151
  "frame-ancestors 'none'"
130
152
  ].join("; ");
131
153
  }
132
- function yogaServers(options) {
154
+ function yogaServers(options, caches) {
133
155
  const servers = new Map;
134
156
  return (endpoint) => {
135
157
  let yoga = servers.get(endpoint);
136
158
  if (yoga === undefined) {
137
159
  yoga = createYoga({
138
160
  ...options,
161
+ ...caches === undefined ? {} : { parserAndValidationCache: caches() },
139
162
  graphqlEndpoint: endpoint
140
163
  });
141
164
  servers.set(endpoint, yoga);
@@ -156,6 +179,12 @@ function serverContext(ctx) {
156
179
  } = ctx;
157
180
  return server;
158
181
  }
182
+ var REFUSAL_OWN_HEADERS = new Set([
183
+ "content-type",
184
+ "content-length",
185
+ "content-encoding",
186
+ "transfer-encoding"
187
+ ]);
159
188
  function graphqlHandler(yogaAt, sandbox) {
160
189
  return async function graphql(ctx) {
161
190
  const { reply } = ctx;
@@ -173,6 +202,17 @@ function graphqlHandler(yogaAt, sandbox) {
173
202
  const refusal = watched.refusal();
174
203
  if (refusal !== undefined) {
175
204
  answered.body?.cancel();
205
+ for (const [name, value] of answered.headers) {
206
+ if (REFUSAL_OWN_HEADERS.has(name))
207
+ continue;
208
+ if (name === "set-cookie")
209
+ ctx.set.headers.append(name, value);
210
+ else if (name === "vary") {
211
+ for (const part of value.split(","))
212
+ vary(ctx.set.headers, part);
213
+ } else
214
+ ctx.set.headers.set(name, value);
215
+ }
176
216
  throw refusal;
177
217
  }
178
218
  const response = await withoutOriginalError(answered);
@@ -251,6 +291,232 @@ function reportsOperations() {
251
291
  };
252
292
  }
253
293
 
294
+ // src/parse-limits.ts
295
+ import { Source, syntaxError } from "graphql";
296
+
297
+ // src/document-cache.ts
298
+ import { TokenKind } from "graphql";
299
+ function boundedCache(options) {
300
+ const { max, ttl, maxBytes, weigh, now = Date.now } = options;
301
+ const entries = new Map;
302
+ let total = 0;
303
+ const drop = (key, entry) => {
304
+ entries.delete(key);
305
+ total -= entry.weight;
306
+ };
307
+ return {
308
+ get(key) {
309
+ const entry = entries.get(key);
310
+ if (entry === undefined)
311
+ return;
312
+ if (entry.expires <= now()) {
313
+ drop(key, entry);
314
+ return;
315
+ }
316
+ entries.delete(key);
317
+ entries.set(key, entry);
318
+ return entry.value;
319
+ },
320
+ set(key, value) {
321
+ const previous = entries.get(key);
322
+ if (previous !== undefined)
323
+ drop(key, previous);
324
+ const weight = weigh(key, value);
325
+ if (weight > maxBytes / 8)
326
+ return;
327
+ entries.set(key, { value, weight, expires: now() + ttl });
328
+ total += weight;
329
+ for (const [oldest, entry] of entries) {
330
+ if (entries.size <= max && total <= maxBytes)
331
+ break;
332
+ drop(oldest, entry);
333
+ }
334
+ }
335
+ };
336
+ }
337
+ var BYTES_PER_TOKEN = 512;
338
+ var BYTES_PER_CHAR = 4;
339
+ var BYTES_PER_ESCAPED_CHAR = 32;
340
+ var BYTES_PER_CHAR_NO_LOC = BYTES_PER_CHAR + BYTES_PER_ESCAPED_CHAR;
341
+ var flattened = 0;
342
+ function chainWalk(document) {
343
+ const first = document.loc?.startToken;
344
+ if (first === undefined)
345
+ return;
346
+ let tokens = 0;
347
+ let extra = 0;
348
+ for (let token = first;token !== null; token = token.next) {
349
+ tokens++;
350
+ if (token.kind === TokenKind.STRING && token.value.length < token.end - token.start - 2) {
351
+ extra += BYTES_PER_ESCAPED_CHAR * (token.end - token.start);
352
+ if (token.value.length > 0)
353
+ flattened = token.value.charCodeAt(0);
354
+ }
355
+ }
356
+ return { tokens, extra: extra + (flattened & 0) };
357
+ }
358
+ function documentWeight(source, document) {
359
+ const walk = chainWalk(document);
360
+ if (walk !== undefined) {
361
+ return BYTES_PER_TOKEN * walk.tokens + BYTES_PER_CHAR * source.length + walk.extra;
362
+ }
363
+ const tokenCount = document.tokenCount;
364
+ if (typeof tokenCount !== "number") {
365
+ return Math.max(256, BYTES_PER_CHAR_NO_LOC) * source.length;
366
+ }
367
+ return BYTES_PER_TOKEN * tokenCount + BYTES_PER_CHAR_NO_LOC * source.length;
368
+ }
369
+ function errorWeight(source) {
370
+ return BYTES_PER_CHAR * source.length + 1024;
371
+ }
372
+
373
+ // src/nesting.ts
374
+ var DEFAULT_MAX_NESTING = 1000;
375
+ function nestingLimit(maxNesting) {
376
+ if (maxNesting === undefined)
377
+ return DEFAULT_MAX_NESTING;
378
+ if (maxNesting === false)
379
+ return false;
380
+ if (typeof maxNesting === "number" && Number.isSafeInteger(maxNesting)) {
381
+ if (maxNesting > 0)
382
+ return maxNesting;
383
+ }
384
+ throw new TypeError(`graphql(app, { maxNesting }): maxNesting is the most levels of { ( [ a document may nest, a positive whole number, or false for none; got ${String(maxNesting)}`);
385
+ }
386
+ var QUOTE = 34;
387
+ var BACKSLASH = 92;
388
+ var HASH = 35;
389
+ var LF = 10;
390
+ var CR = 13;
391
+ function tooDeepAt(body, max) {
392
+ let depth = 0;
393
+ const end = body.length;
394
+ for (let i = 0;i < end; i++) {
395
+ const code = body.charCodeAt(i);
396
+ if (code === 123 || code === 40 || code === 91) {
397
+ if (++depth > max)
398
+ return i;
399
+ } else if (code === 125 || code === 41 || code === 93) {
400
+ if (depth > 0)
401
+ depth--;
402
+ } else if (code === HASH) {
403
+ while (i + 1 < end) {
404
+ const next = body.charCodeAt(i + 1);
405
+ if (next === LF || next === CR)
406
+ break;
407
+ i++;
408
+ }
409
+ } else if (code === QUOTE) {
410
+ if (body.startsWith('"""', i)) {
411
+ i += 3;
412
+ while (i < end) {
413
+ if (body.startsWith('\\"""', i))
414
+ i += 4;
415
+ else if (body.startsWith('"""', i))
416
+ break;
417
+ else
418
+ i++;
419
+ }
420
+ i += 2;
421
+ } else {
422
+ i++;
423
+ while (i < end) {
424
+ const inString = body.charCodeAt(i);
425
+ if (inString === BACKSLASH)
426
+ i += 2;
427
+ else if (inString === QUOTE || inString === LF || inString === CR) {
428
+ break;
429
+ } else
430
+ i++;
431
+ }
432
+ }
433
+ }
434
+ }
435
+ return -1;
436
+ }
437
+
438
+ // src/parse-limits.ts
439
+ var DEFAULT_MAX_TOKENS = 15000;
440
+ var DEFAULT_BYTES = 64 * 1024 * 1024;
441
+ function positive(name, value, what, alternative = "") {
442
+ if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) {
443
+ return value;
444
+ }
445
+ throw new TypeError(`graphql(app, { ${name} }): ${what}, a positive whole number${alternative}; got ${String(value)}`);
446
+ }
447
+ function tokenLimit(maxTokens) {
448
+ if (maxTokens === undefined)
449
+ return DEFAULT_MAX_TOKENS;
450
+ if (maxTokens === false)
451
+ return false;
452
+ return positive("maxTokens", maxTokens, "maxTokens is the most tokens a document may hold", ", or false for none");
453
+ }
454
+ var overflowed = (error) => error instanceof RangeError && /call stack/i.test(error.message);
455
+ function limitsParsing(maxTokens, maxNesting) {
456
+ return {
457
+ onParse({ parseFn, setParseFn }) {
458
+ setParseFn((source, options) => {
459
+ const body = typeof source === "string" ? source : source.body;
460
+ const refuse = (position, why) => syntaxError(typeof source === "string" ? new Source(source) : source, position, why);
461
+ if (maxNesting !== false) {
462
+ const at = tooDeepAt(body, maxNesting);
463
+ if (at >= 0) {
464
+ throw refuse(at, `Document is nested more than ${maxNesting} levels deep. Parsing aborted.`);
465
+ }
466
+ }
467
+ try {
468
+ return parseFn(source, maxTokens === false ? options : { ...options, maxTokens });
469
+ } catch (error) {
470
+ if (!overflowed(error))
471
+ throw error;
472
+ throw refuse(0, "Document is nested too deeply to parse.");
473
+ }
474
+ });
475
+ }
476
+ };
477
+ }
478
+ function cacheSizes(parseCache) {
479
+ if (parseCache === false)
480
+ return false;
481
+ if (parseCache !== undefined && (typeof parseCache !== "object" || parseCache === null)) {
482
+ throw new TypeError(`graphql(app, { parseCache }): parseCache is an object of cache sizes, or false for none; got ${String(parseCache)}`);
483
+ }
484
+ const given = parseCache ?? {};
485
+ return {
486
+ maxBytes: positive("parseCache.maxBytes", given.maxBytes ?? DEFAULT_BYTES, "maxBytes is the most estimated bytes of documents kept"),
487
+ max: positive("parseCache.max", given.max ?? 1024, "max is the most documents kept"),
488
+ ttl: positive("parseCache.ttl", given.ttl ?? 3600000, "ttl is the milliseconds a document is kept")
489
+ };
490
+ }
491
+ function resolveLimits(maxTokens, maxNesting, parseCache, yogaOptions) {
492
+ const tokens = tokenLimit(maxTokens);
493
+ const depth = nestingLimit(maxNesting);
494
+ if (parseCache !== undefined && yogaOptions.parserAndValidationCache !== undefined) {
495
+ throw new TypeError("graphql(app, { parseCache, parserAndValidationCache }): give one: parseCache sizes alxia's bounded cache, parserAndValidationCache replaces it");
496
+ }
497
+ cacheSizes(parseCache);
498
+ return { tokens, depth };
499
+ }
500
+ function parseCaches(parseCache) {
501
+ const sizes = cacheSizes(parseCache);
502
+ if (sizes === false)
503
+ return false;
504
+ const { maxBytes, max, ttl } = sizes;
505
+ const documentCache = boundedCache({
506
+ max,
507
+ ttl,
508
+ maxBytes,
509
+ weigh: (source, document) => documentWeight(source, document)
510
+ });
511
+ const errorCache = boundedCache({
512
+ max,
513
+ ttl,
514
+ maxBytes: Math.floor(maxBytes / 8),
515
+ weigh: (source) => errorWeight(source)
516
+ });
517
+ return { documentCache, errorCache };
518
+ }
519
+
254
520
  // src/ws-operations.ts
255
521
  import { startOperation } from "@alxia/core";
256
522
  import { getOperationAST as getOperationAST2 } from "graphql";
@@ -454,23 +720,26 @@ function graphql(app, options) {
454
720
  graphiql,
455
721
  sandbox,
456
722
  ws = false,
723
+ maxTokens,
724
+ maxNesting,
725
+ parseCache,
726
+ bodyLimit,
457
727
  ...yogaOptions
458
728
  } = options;
729
+ const limits = resolveLimits(maxTokens, maxNesting, parseCache, yogaOptions);
459
730
  const page = graphiql ?? true;
460
731
  const yogaAt = yogaServers({
461
732
  ...yogaOptions,
462
- plugins: [...yogaOptions.plugins ?? [], reportsOperations()],
733
+ plugins: [
734
+ limitsParsing(limits.tokens, limits.depth),
735
+ ...yogaOptions.plugins ?? [],
736
+ reportsOperations()
737
+ ],
463
738
  cors,
464
739
  graphiql: ide === undefined ? (_request, context) => isDev(context) && page : ide === "graphiql" ? page : false
465
- });
740
+ }, yogaOptions.parserAndValidationCache === undefined ? () => parseCaches(parseCache) : undefined);
466
741
  const handler = graphqlHandler(yogaAt, ide === "apollo-sandbox" ? sandbox ?? {} : false);
467
- const route = app;
468
- route.get(path, handler);
469
- route.post(path, handler);
470
- if (ws !== false) {
471
- const socket = graphqlSocket(yogaAt, path, ws === true ? {} : ws);
472
- route.ws(socket.path, socket.middleware, socket.handlers);
473
- }
742
+ declareEndpoint(app, path, handler, bodyLimit, ws === false ? undefined : graphqlSocket(yogaAt, path, ws === true ? {} : ws));
474
743
  return app;
475
744
  }
476
745
  export {
@@ -479,5 +748,5 @@ export {
479
748
  renderSandbox
480
749
  };
481
750
 
482
- //# debugId=DFFFDD9B5123148464756E2164756E21
751
+ //# debugId=01B66A2C6AD2881F64756E2164756E21
483
752
  //# sourceMappingURL=index.js.map