@softistx/alxia-graphql 0.0.0-stage → 0.20.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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +445 -2
  3. package/dist/bounded-stream.d.ts +37 -0
  4. package/dist/bounded-stream.d.ts.map +1 -0
  5. package/dist/endpoint.d.ts +17 -0
  6. package/dist/endpoint.d.ts.map +1 -0
  7. package/dist/executor.d.ts +49 -0
  8. package/dist/executor.d.ts.map +1 -0
  9. package/dist/explorer.d.ts +24 -0
  10. package/dist/explorer.d.ts.map +1 -0
  11. package/dist/graphql.d.ts +63 -0
  12. package/dist/graphql.d.ts.map +1 -0
  13. package/dist/handler.d.ts +11 -0
  14. package/dist/handler.d.ts.map +1 -0
  15. package/dist/index.d.ts +8 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +621 -0
  18. package/dist/index.js.map +21 -0
  19. package/dist/once-per-request.d.ts +28 -0
  20. package/dist/once-per-request.d.ts.map +1 -0
  21. package/dist/operation.d.ts +3 -0
  22. package/dist/operation.d.ts.map +1 -0
  23. package/dist/options.d.ts +38 -0
  24. package/dist/options.d.ts.map +1 -0
  25. package/dist/removed.d.ts +14 -0
  26. package/dist/removed.d.ts.map +1 -0
  27. package/dist/sandbox.d.ts +15 -0
  28. package/dist/sandbox.d.ts.map +1 -0
  29. package/dist/testing/client.d.ts +95 -0
  30. package/dist/testing/client.d.ts.map +1 -0
  31. package/dist/testing/index.d.ts +2 -0
  32. package/dist/testing/index.d.ts.map +1 -0
  33. package/dist/testing/index.js +73 -0
  34. package/dist/testing/index.js.map +10 -0
  35. package/dist/ws.d.ts +30 -0
  36. package/dist/ws.d.ts.map +1 -0
  37. package/docs/README.md +31 -0
  38. package/docs/guide/context.md +351 -0
  39. package/docs/guide/endpoint.md +293 -0
  40. package/docs/guide/executor.md +75 -0
  41. package/docs/guide/ide.md +160 -0
  42. package/docs/guide/plugins.md +316 -0
  43. package/docs/guide/production.md +374 -0
  44. package/docs/guide/testing.md +171 -0
  45. package/docs/guide/websockets.md +329 -0
  46. package/docs/migrating-to-graxia.md +408 -0
  47. package/docs/roadmap.md +122 -0
  48. package/docs/troubleshooting.md +963 -0
  49. package/package.json +69 -5
@@ -0,0 +1,75 @@
1
+ # Running operations in process
2
+
3
+ `graphqlExecutor(options)` runs a query or a mutation inside the process,
4
+ without a route or a socket. Use it when the caller is not a browser: an MCP
5
+ tool that serves GraphQL to a model, a background job, a script. It builds the
6
+ same graxia as `graphql()` from the same options, so the plugins, the token and
7
+ nesting limits, the parse cache and the masking of errors apply as they do on
8
+ the route. The server context is the one you pass.
9
+
10
+ ```ts
11
+ import { graphqlExecutor } from '@softistx/alxia-graphql';
12
+
13
+ const execute = graphqlExecutor({
14
+ schema,
15
+ plugins: [useAuth()], // the route's plugins, minus the HTTP-only ones
16
+ maxTokens: 5_000,
17
+ logging: 'warn',
18
+ });
19
+
20
+ const { data, errors } = await execute(
21
+ {
22
+ query: 'query ($id: ID!) { user(id: $id) { name } }',
23
+ variables: { id: '1' },
24
+ },
25
+ { viewer, services }, // what a resolver reads as its context
26
+ { signal }, // optional: stops the operation, as a client leaving does
27
+ );
28
+ ```
29
+
30
+ ## What it takes
31
+
32
+ | Argument | |
33
+ | --- | --- |
34
+ | `request` | `{ query, operationName?, variables? }` |
35
+ | `context` | the server context: what the resolvers read, in place of what the app's middlewares would have built. Typed by `graphqlExecutor<ServerCtx>` |
36
+ | `call.signal` | an `AbortSignal` that stops the operation |
37
+
38
+ It answers `{ data?, errors? }`, plain JSON as the endpoint's body would be:
39
+ a GraphQL error is in `errors`, not thrown. An aborted `signal` does not reject: see below.
40
+
41
+ ## Aborting
42
+
43
+ An aborted `signal`, before the call or while the operation runs, resolves to
44
+ `{ errors: [{ message: 'The operation was aborted.', extensions: { code: 'OPERATION_ABORTED' } }] }`
45
+ with no `data`. It never rejects, and `context.signal` aborts so a resolver
46
+ can stop its work. Errors come back as plain objects, not `GraphQLError`
47
+ instances.
48
+
49
+ ```ts
50
+ const result = await execute({ query }, context, { signal: AbortSignal.timeout(2_000) });
51
+ if (result.errors?.[0]?.extensions?.code === 'OPERATION_ABORTED') retryLater();
52
+ ```
53
+
54
+ ## Its options
55
+
56
+ `schema`, `plugins`, `maskErrors` (on by default), `limits` (`tokens` 15 000,
57
+ `nesting` 1 000), `caches` (`parse`: 1 024 documents; `false` for none) and
58
+ graxia's other options. Not `path`, `ide`, `ws`, `bodyLimit`, `csrf` or `cors`:
59
+ they belong to a route. CSRF is off for the executor, since there is no
60
+ browser request to forge, while the route has it on by default.
61
+
62
+ ## What it does not do
63
+
64
+ - It does not run the app's middlewares (`use(...)`): the context is what you
65
+ pass. Build it as the middlewares would.
66
+ - A plugin that only makes sense over HTTP (a check of a client header,
67
+ `cache-control: no-store`) goes in the route's `plugins` and not in the
68
+ executor's. Share the rest in one array.
69
+ - It runs queries and mutations. A subscription is answered with an error
70
+ whose code is `SUBSCRIPTION_NOT_SUPPORTED`.
71
+ - Its parse cache is its own, apart from the route's.
72
+ - It holds a graxia instance: `await executor.dispose()` when you are done
73
+ (a test's `afterAll`, a job's shutdown). A call after it rejects.
74
+
75
+ See also: [Plugins and options](plugins.md), [the typed context](context.md).
@@ -0,0 +1,160 @@
1
+ # GraphiQL and Apollo Sandbox
2
+
3
+ This page covers what a browser gets when it opens the endpoint — GraphiQL, Apollo Sandbox, or nothing — their options, the
4
+ `Content-Security-Policy` each loads under.
5
+
6
+ ```ts
7
+ import { alxia } from '@softistx/alxia';
8
+ import { graphql } from '@softistx/alxia-graphql';
9
+ import { createSchema } from '@softistx/graxia';
10
+
11
+ const schema = createSchema()({
12
+ typeDefs: /* GraphQL */ `type Query { hello: String! }`,
13
+ resolvers: { Query: { hello: () => 'world' } },
14
+ });
15
+
16
+ const app = alxia().plugin((app) =>
17
+ graphql(app, {
18
+ schema,
19
+ ide: Bun.env['NODE_ENV'] === 'development' && 'apollo-sandbox', // read at runtime
20
+ sandbox: { title: 'Hello API', initialDocument: '{ hello }' },
21
+ }),
22
+ );
23
+ // open http://localhost:3000/graphql in a browser
24
+ ```
25
+
26
+ ## `ide`
27
+
28
+ | `ide` | A browser's `GET` at the endpoint gets | Options |
29
+ | --- | --- | --- |
30
+ | not given (default) | GraphiQL in the serving app's dev — `alxia({ dev })`, else `NODE_ENV=development` — and no page elsewhere | `graphiql` |
31
+ | `'graphiql'` | GraphiQL, in every mode | `graphiql` |
32
+ | `'apollo-sandbox'` | [Apollo Sandbox](https://www.apollographql.com/docs/graphos/platform/sandbox), embedded | `sandbox` |
33
+ | `false` | no page: the request is answered as a GraphQL request | — |
34
+
35
+ A `GET` that accepts `text/html` gets the page: GraphiQL with or without a
36
+ `query` parameter (it opens with that query), Apollo Sandbox only without
37
+ one. Every other request is a GraphQL request, answered in JSON. A browser
38
+ sends `*/*` beside `text/html`, so where no page is served — `ide: false`,
39
+ or Sandbox with `?query=` — it gets the JSON result (or
40
+ `Must provide query string.` with no query). A client whose `Accept` allows
41
+ only `text/html` gets a [`406` with an empty
42
+ body](../troubleshooting.md#406-with-an-empty-body) instead.
43
+
44
+ Both IDEs run the schema's introspection and any operation against the
45
+ endpoint, behind the same middlewares as every other request: a guard before
46
+ the endpoint guards the page too, and a browser without a token gets the
47
+ guard's reply. By default the IDE is off outside dev; give `ide:
48
+ 'graphiql'` only where you mean to publish it. Before 0.5, GraphiQL was
49
+ on in every mode.
50
+
51
+ The default follows the app's own dev flag, the one `isDev(ctx)` reads
52
+ (`alxia({ dev })`, else `NODE_ENV=development`), not `NODE_ENV` alone, and it
53
+ is read for each request: `alxia({ dev: false })` serves no page under
54
+ `NODE_ENV=development`, and `alxia({ dev: true })` serves it under
55
+ `NODE_ENV=production`. Apollo Sandbox, chosen with `ide: 'apollo-sandbox'`,
56
+ is served in every mode, like `ide: 'graphiql'`; pick it with a condition of
57
+ your own to keep it out of production.
58
+
59
+ ## GraphiQL
60
+
61
+ The default, in dev. `graphiql` takes `@softistx/graxia-graphiql`'s `GraphiQLOptions` — not `true` or
62
+ `false`, which `ide` decides:
63
+
64
+ ```ts
65
+ graphql(app, {
66
+ schema,
67
+ graphiql: {
68
+ title: 'Users API',
69
+ defaultQuery: '{ me }',
70
+ headers: JSON.stringify({ authorization: 'Bearer <token>' }),
71
+ },
72
+ });
73
+ ```
74
+
75
+ Its other options are listed in the `@softistx/graxia-graphiql` documentation.
76
+
77
+ The page serves GraphiQL's script and stylesheet itself, from the endpoint
78
+ (`?graphiql-asset=<file>`): nothing loads from a third-party host. The
79
+ response carries a strict `Content-Security-Policy` that lets those files
80
+ alone load, runs no worker and lets no one frame the page:
81
+
82
+ ```text
83
+ default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; worker-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'
84
+ ```
85
+
86
+ ## Apollo Sandbox
87
+
88
+ `ide: 'apollo-sandbox'` serves a page embedding Apollo Sandbox, pointed at
89
+ the endpoint: the page's own address without its query, read by the
90
+ browser, prefixes included. Behind a proxy that terminates TLS, the Sandbox
91
+ asks over `https` as the browser did, with no option and no
92
+ `X-Forwarded-Proto`. `sandbox` takes `SandboxOptions`:
93
+
94
+ ```ts
95
+ interface SandboxOptions {
96
+ readonly title?: string;
97
+ readonly initialDocument?: string;
98
+ readonly initialHeaders?: Readonly<Record<string, string>>;
99
+ readonly includeCookies?: boolean;
100
+ }
101
+ ```
102
+
103
+ | Option | Type | Default | Effect |
104
+ | --- | --- | --- | --- |
105
+ | `title` | `string` | `'Apollo Sandbox'` | The page's `<title>`. |
106
+ | `initialDocument` | `string` | none | The operation the Sandbox opens with. |
107
+ | `initialHeaders` | `Record<string, string>` | none | Headers every operation sends, shown and editable in the Sandbox. |
108
+ | `includeCookies` | `boolean` | `true` | Whether operations send the browser's cookies, such as a session cookie. |
109
+
110
+ ```ts
111
+ graphql(app, {
112
+ schema,
113
+ ide: 'apollo-sandbox',
114
+ sandbox: {
115
+ title: 'Users API',
116
+ initialDocument: '{ me }',
117
+ initialHeaders: { 'x-tenant': 'acme' },
118
+ includeCookies: false,
119
+ },
120
+ });
121
+ ```
122
+
123
+ The endpoint shown in the Sandbox is not editable. Every value is escaped
124
+ into the page's HTML and script, so a title or document from configuration
125
+ cannot break out of it.
126
+
127
+ The page loads the Sandbox's script from Apollo's CDN and frames
128
+ `sandbox.embed.apollographql.com`; it is sent with `sandboxContentSecurityPolicy()` from `@softistx/graxia-graphiql`:
129
+
130
+ ```text
131
+ default-src 'self'; script-src 'self' 'unsafe-inline' https://embeddable-sandbox.cdn.apollographql.com; style-src 'self' 'unsafe-inline'; frame-src https://sandbox.embed.apollographql.com; img-src 'self' data: https:; connect-src 'self'
132
+ ```
133
+
134
+ ## With `@softistx/alxia-secure-headers`
135
+
136
+ `@softistx/alxia-secure-headers` keeps a header a response already has, so the
137
+ IDE's policy survives it and every other route keeps the strict one. A middleware
138
+ of your own that **overwrites** `Content-Security-Policy` on every
139
+ response blocks the IDE's scripts, and the page stays blank: set it only
140
+ when the response has none.
141
+
142
+ ```ts
143
+ import { alxia, defineMiddleware, settle, withHeaders } from '@softistx/alxia';
144
+
145
+ const defaultPolicy = defineMiddleware(async (ctx, next) =>
146
+ withHeaders(await settle(ctx, next()), (headers) => {
147
+ if (!headers.has('content-security-policy'))
148
+ headers.set('content-security-policy', "default-src 'self'");
149
+ }),
150
+ );
151
+
152
+ const app = alxia()
153
+ .use(defaultPolicy)
154
+ .plugin((app) => graphql(app, { schema }));
155
+ ```
156
+
157
+ ## See also
158
+
159
+ - [Mounting the endpoint](endpoint.md): which middlewares run before the page.
160
+ - [Troubleshooting](../troubleshooting.md#the-ide-page-is-blank): a blank IDE page.
@@ -0,0 +1,316 @@
1
+ # Graxia's plugins and options
2
+
3
+ This page covers what passes through to graxia (`@softistx/graxia`): its plugins
4
+ and Envelop's, error masking, batching, subscriptions over server-sent events
5
+ (and over WebSocket with [`ws`](websockets.md)), and how CORS and
6
+ compression meet the endpoint.
7
+
8
+ ```ts
9
+ import { alxia } from '@softistx/alxia';
10
+ import { graphql } from '@softistx/alxia-graphql';
11
+ import { createSchema } from '@softistx/graxia';
12
+
13
+ const schema = createSchema()({
14
+ typeDefs: /* GraphQL */ `type Query { hello: String! }`,
15
+ resolvers: { Query: { hello: () => 'world' } },
16
+ });
17
+
18
+ const app = alxia().plugin((app) =>
19
+ graphql(app, {
20
+ schema,
21
+ batching: { limit: 5 },
22
+ }),
23
+ );
24
+ ```
25
+
26
+ ## What passes through
27
+
28
+ `GraphQLOptions` is graxia's `GraxiaOptions`, minus the keys the package owns
29
+ or maps:
30
+
31
+ | graxia's option | Here |
32
+ | --- | --- |
33
+ | `path` | set from `path` and the app's prefix ([Mounting the endpoint](endpoint.md#where-it-is-served)) |
34
+ | `plugins` | yours, plus the package's own: the IDE ([GraphiQL and Apollo Sandbox](ide.md)) and the reporter that names the operation for `@softistx/alxia-logger` and `@softistx/alxia-telemetry` |
35
+ | `limits` | `bodyBytes` is set from `bodyLimit`; `tokens` and `nesting` may also come from the deprecated `maxTokens` and `maxNesting` ([Cap what a request costs](production.md#cap-what-a-request-costs)) |
36
+ | `caches` | `parse` may also come from the deprecated `parseCache` |
37
+ | `subscriptions` | set from `ws`: server-sent events always, WebSocket when `ws` is on ([GraphQL over WebSocket](websockets.md)) |
38
+ | `schema` | required, and checked against the app's context ([The typed context](context.md)) |
39
+ | `telemetry` | `operationSpans: false`, so an operation is one span, the one `@softistx/alxia-telemetry` makes |
40
+
41
+ Everything else (`context`, `maskErrors`, `batching`, `csrf`, `trustedDocuments`,
42
+ `uploads`…) goes to `createGraxia` as it is, with graxia's defaults. Its
43
+ reference is [graxia's documentation](https://github.com/softistx/graxia/tree/develop/packages/core/docs).
44
+
45
+ Some of Yoga's options no longer exist and are refused where `graphql()` is
46
+ declared, with the fix in the message: `logging`, `requestId`, `cors` and
47
+ `sameOrigin`. See [Migrating to graxia](../migrating-to-graxia.md).
48
+
49
+ ## Plugins
50
+
51
+ `plugins` takes graxia's plugins, in the order they run
52
+ ([graxia's plugin guide](https://github.com/softistx/graxia/blob/develop/packages/core/docs/guide/plugins.md)).
53
+ An Envelop plugin goes through `fromEnvelop` from `@softistx/graxia-envelop`, which is not a peer: install `@softistx/graxia-envelop` yourself to use Envelop plugins.
54
+
55
+ ```sh
56
+ bun add @softistx/graxia-envelop @envelop/depth-limit
57
+ ```
58
+
59
+ ```ts
60
+ import { useDepthLimit } from '@envelop/depth-limit';
61
+ import { fromEnvelop } from '@softistx/graxia-envelop';
62
+
63
+ graphql(app, {
64
+ schema,
65
+ plugins: [fromEnvelop([useDepthLimit({ maxDepth: 8 })])],
66
+ });
67
+ ```
68
+
69
+ A plugin of your own is an object with a `name` and the hooks it needs,
70
+ typed by `definePlugin`:
71
+
72
+ ```ts
73
+ import { definePlugin } from '@softistx/graxia';
74
+
75
+ const slowOperations = definePlugin({
76
+ name: 'slow-operations',
77
+ onExecute: ({ args }) => {
78
+ const started = performance.now();
79
+ return () => {
80
+ const ms = performance.now() - started;
81
+ if (ms > 500) console.warn(`slow operation ${args.operationName ?? 'anonymous'}: ${ms}ms`);
82
+ };
83
+ },
84
+ });
85
+
86
+ graphql(app, { schema, plugins: [slowOperations] });
87
+ ```
88
+
89
+ Two plugins with the same `name` throw a `GraxiaConfigError` where
90
+ `graphql()` is declared. A plugin that adds to the context (`onContext`
91
+ returns the added fields) is the way to give a resolver a value, and what it adds is part of the context the schema is checked against (a `plugins` array literal is read as a tuple, so each plugin's added fields count); for one that
92
+ depends on the request alone, the `context` option does the same
93
+ ([The typed context](context.md#the-context-option)).
94
+
95
+ Graxia's plugins run inside the route, after the app's middlewares: a plugin
96
+ sees only requests the middlewares let through, and its `serverContext` holds
97
+ what they added.
98
+
99
+ ## Errors
100
+
101
+ graxia masks errors by default (`maskErrors: true`; the deprecated
102
+ `maskedErrors: false` is the same as `maskErrors: false`): an `Error` thrown
103
+ by a resolver reaches the client as `Unexpected error.`, with a correlation
104
+ id in `extensions.reference`, and its message — a connection string, a
105
+ stack — stays on the server.
106
+
107
+ ```text
108
+ 200 {"errors":[{"message":"Unexpected error.","path":["crash"],"extensions":{"code":"INTERNAL_SERVER_ERROR","reference":"…"}}],"data":{"crash":null}}
109
+ ```
110
+
111
+ An error meant for the client is made with `exposedError(code, message)`
112
+ from `@softistx/graxia`, which carries a stable `code` and an optional `fix`:
113
+
114
+ ```ts
115
+ import { exposedError } from '@softistx/graxia';
116
+
117
+ const resolvers = {
118
+ Query: {
119
+ admin: (_: unknown, __: unknown, { viewer }: GraphQLContext<typeof base>) => {
120
+ if (viewer !== 'admin')
121
+ throw exposedError('FORBIDDEN', 'Admins only', { fix: 'Sign in as an admin.' });
122
+ return 'welcome';
123
+ },
124
+ },
125
+ };
126
+ ```
127
+
128
+ ```text
129
+ 200 {"errors":[{"message":"Admins only","path":["admin"],"extensions":{"code":"FORBIDDEN","fix":"Sign in as an admin."}}],"data":{"admin":null}}
130
+ ```
131
+
132
+ A `GraphQLError` of your own with no `originalError` is exposed as it is.
133
+ Yoga's `http: { status }` extension is not read: a resolver's error is
134
+ answered with the operation's status (200 under `application/json`).
135
+ `maskErrors: false` sends every message as it is: for development only.
136
+ A resolver's error is graxia's to answer; it never reaches a try/catch
137
+ middleware before the endpoint, which sees only what fails around it — a
138
+ middleware that throws, say.
139
+
140
+ ## Batching
141
+
142
+ `batching` lets a client send an array of operations in one `POST`, and
143
+ get an array of results:
144
+
145
+ ```ts
146
+ graphql(app, { schema, batching: { limit: 5 } });
147
+ ```
148
+
149
+ ```text
150
+ POST [{"query":"{ admin }"},{"query":"{ __typename }"}]
151
+ 200 [{"data":{"admin":"welcome"}},{"data":{"__typename":"Query"}}]
152
+ ```
153
+
154
+ `batching: true` allows 10 operations. Without it, a batch is refused with
155
+ `400 BATCHING_DISABLED`; one over the limit is `BATCH_TOO_LARGE`. A batch is
156
+ one request, so one log line and one span: `@softistx/alxia-logger` writes
157
+ `operationType: 'batch'` and every name, `operationName: 'GetNotes,AddNote'`,
158
+ and `@softistx/alxia-telemetry` names the span `batch GetNotes,AddNote`
159
+ ([endpoint guide](endpoint.md#the-operation-in-the-log-and-the-trace)).
160
+
161
+ ## Subscriptions
162
+
163
+ Subscriptions are served over server-sent events: a
164
+ `POST` (or `GET`) with `Accept: text/event-stream` gets a stream of results.
165
+ A resolver's `subscribe` is an async iterable — an `async *` generator, or
166
+ graxia's `createPubSub`:
167
+
168
+ ```ts
169
+ import { createPubSub, createSchema } from '@softistx/graxia';
170
+
171
+ const pubsub = createPubSub<{ message: [payload: { text: string }] }>();
172
+
173
+ const schema = createSchema()({
174
+ typeDefs: /* GraphQL */ `
175
+ type Query { ok: Boolean }
176
+ type Mutation { send(text: String!): Boolean! }
177
+ type Subscription { message: String!, countdown(from: Int!): Int! }
178
+ `,
179
+ resolvers: {
180
+ Mutation: {
181
+ send: (_, { text }: { text: string }) => {
182
+ pubsub.publish('message', { text });
183
+ return true;
184
+ },
185
+ },
186
+ Subscription: {
187
+ message: {
188
+ subscribe: () => pubsub.subscribe('message'),
189
+ resolve: (payload: { text: string }) => payload.text,
190
+ },
191
+ countdown: {
192
+ async *subscribe(_, { from }: { from: number }) {
193
+ for (let n = from; n >= 0; n--) yield { countdown: n };
194
+ },
195
+ },
196
+ },
197
+ },
198
+ });
199
+ ```
200
+
201
+ ```sh
202
+ curl -N localhost:3000/graphql -H 'content-type: application/json' -H 'accept: text/event-stream' \
203
+ -H 'x-graphql-csrf: 1' \
204
+ -d '{"query":"subscription { countdown(from: 2) }"}'
205
+ # event: next
206
+ # data: {"data":{"countdown":2}}
207
+ # …
208
+ ```
209
+
210
+ A subscription asked for with `Accept: application/json` is refused with an
211
+ error (400 under `application/graphql-response+json`, 200 under
212
+ `application/json`): there is no stream to send it on. A client that speaks WebSocket —
213
+ `graphql-ws`, Apollo Client's `GraphQLWsLink`, urql's `subscriptionExchange` —
214
+ needs `ws: true` ([GraphQL over WebSocket](websockets.md)); server-sent events
215
+ stay served beside it. `createPubSub` lives in one process; across several,
216
+ give it an event target backed by a broker, as
217
+ [graxia's PubSub guide](https://github.com/softistx/graxia/blob/develop/packages/core/docs/guide/pubsub.md)
218
+ describes.
219
+
220
+ `@softistx/alxia-compress` leaves a `text/event-stream` alone by default, so results
221
+ are sent as they are produced. A `compressible` that lets event streams in
222
+ still sends each result at once: a streamed body is flushed as it comes.
223
+
224
+ ### Bound a subscription
225
+
226
+ A long-lived stream should not outlive its welcome: a client that went quiet,
227
+ a session that was revoked, a reader nobody releases. `boundedStream` wraps
228
+ the source of a `subscribe` and declares the limits:
229
+
230
+ ```ts
231
+ import { boundedStream } from '@softistx/alxia-graphql';
232
+
233
+ declare function subscribeToTopic(topicId: string): AsyncIterable<unknown>;
234
+ declare function toGraphQLError(e: unknown): Error;
235
+
236
+ const resolvers = {
237
+ Subscription: {
238
+ events: {
239
+ subscribe: (_: unknown, args: { topicId: string }, ctx: { assertSession(): Promise<void> }) =>
240
+ boundedStream(subscribeToTopic(args.topicId), {
241
+ idleMs: 90_000, // ends after 90 s without an event
242
+ totalMs: 10 * 60_000, // and 10 minutes after it began
243
+ checkEveryMs: 30_000, // re-checks the session, also while idle
244
+ checkDebounceMs: 1_000, // and before an event if the last check is 1 s old
245
+ check: () => ctx.assertSession(), // throws to refuse
246
+ mapError: (error) => toGraphQLError(error), // optional
247
+ }),
248
+ resolve: (event: unknown) => event,
249
+ },
250
+ },
251
+ };
252
+ ```
253
+
254
+ - It ends **cleanly** (the client sees a complete stream, and reconnects if it
255
+ wants more) on the idle bound, on the total bound and when the source ends.
256
+ - `check` runs every `checkEveryMs`, also while no event comes, and before an
257
+ event is yielded when the last check is at least `checkDebounceMs` old
258
+ (default `0`: every event). When it throws, or when the source itself
259
+ throws, the stream throws `mapError(error)` (the error itself by default)
260
+ and ends.
261
+ - The source's `return()` is called at once when the consumer leaves (the
262
+ client disconnected) and on any end, even while a read is pending, so a
263
+ pub/sub reader is released. Pass `signal` (an `AbortSignal`) to end it on an
264
+ abort too.
265
+ - `source` is any `AsyncIterable` or `AsyncIterator`. No timer is left behind
266
+ once the stream has ended.
267
+
268
+ graxia's keep-alive comments are not events of the source, so they do not reset
269
+ `idleMs`.
270
+
271
+ ### Keep an idle subscription open
272
+
273
+ graxia sends a keep-alive comment on an open stream every 12 seconds
274
+ (`subscriptions.sse.keepAliveMs`). `Bun.serve`
275
+ closes a connection that has been idle for `idleTimeout` seconds, 10 by
276
+ default, so on a real server a subscription that has nothing to send is reset
277
+ at about 8 to 10 seconds, before the first ping. `app.request(…)` in a spec
278
+ goes through no socket and never shows it. Give `listen` an `idleTimeout`
279
+ above the ping interval:
280
+
281
+ ```ts
282
+ app.listen({ port: 3000, idleTimeout: 30 }); // seconds, longer than the 12 s ping
283
+ ```
284
+
285
+ Calling `server.timeout(request, 0)` from a resolver does not lift it for the
286
+ stream. Behind a proxy or load balancer, its own read timeout must be longer
287
+ than 12 seconds too. See
288
+ [the troubleshooting entry](../troubleshooting.md#an-idle-subscription-over-sse-is-reset-after-about-10-seconds).
289
+
290
+ ## CORS
291
+
292
+ graxia has no CORS of its own: the endpoint is a route of the app,
293
+ and `@softistx/alxia-cors` answers for the whole app, preflights included.
294
+
295
+ ```ts
296
+ import { alxia } from '@softistx/alxia';
297
+ import { cors } from '@softistx/alxia-cors';
298
+ import { graphql } from '@softistx/alxia-graphql';
299
+
300
+ const app = alxia()
301
+ .use(cors({ origin: 'https://app.example.com', credentials: true }))
302
+ .plugin((app) => graphql(app, { schema }));
303
+ // OPTIONS /graphql → 204, Access-Control-Allow-Origin: https://app.example.com
304
+ ```
305
+
306
+ Without it, a browser's preflight `OPTIONS /graphql` is a
307
+ `405 {"error":"method_not_allowed"}`, and the browser blocks the call.
308
+ A `cors` option is refused where `graphql()` is declared.
309
+
310
+ ## See also
311
+
312
+ - [Mounting the endpoint](endpoint.md): what the endpoint answers.
313
+ - [The typed context](context.md): the `context` option.
314
+ - [Harden it for production](production.md): depth limits, introspection off, a body limit, CSRF and persisted operations, run.
315
+ - [Migrating to graxia](../migrating-to-graxia.md): what changed from Yoga.
316
+ - [Troubleshooting](../troubleshooting.md): `Unexpected error.`, the `405`.