@hyper-fetch/graphql 9.9.0 → 10.1.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 (57) hide show
  1. package/README.md +152 -84
  2. package/__tests__/e2e/e2e.conformance.spec.ts +206 -0
  3. package/__tests__/e2e/e2e.graphql-ws-server.ts +187 -0
  4. package/__tests__/e2e/e2e.graphql-ws.spec.ts +306 -0
  5. package/__tests__/e2e/e2e.react-subscriptions.spec.tsx +208 -0
  6. package/__tests__/features/adapter/adapter.browser.spec.ts +23 -5
  7. package/__tests__/features/adapter/adapter.document.spec.ts +17 -13
  8. package/__tests__/features/adapter/adapter.headers.spec.ts +65 -0
  9. package/__tests__/features/adapter/adapter.keys.spec.ts +235 -0
  10. package/__tests__/features/adapter/adapter.persisted-queries.spec.ts +207 -0
  11. package/__tests__/features/adapter/adapter.progress.spec.ts +39 -0
  12. package/__tests__/features/adapter/adapter.responses.spec.ts +162 -1
  13. package/__tests__/features/adapter/adapter.server.spec.ts +6 -6
  14. package/__tests__/features/adapter/adapter.types.spec.ts +121 -2
  15. package/__tests__/features/adapter/adapter.utils.spec.ts +4 -2
  16. package/__tests__/features/adapter/adapter.variables.spec.ts +3 -3
  17. package/__tests__/features/socket/socket.connection.spec.ts +892 -0
  18. package/__tests__/features/socket/socket.fuzz.spec.ts +329 -0
  19. package/__tests__/features/socket/socket.subscriptions.spec.ts +515 -0
  20. package/__tests__/features/socket/socket.types.spec.ts +160 -0
  21. package/__tests__/utils/controlled-websocket.ts +238 -0
  22. package/dist/adapter/adapter.constants.d.ts +5 -0
  23. package/dist/adapter/adapter.constants.d.ts.map +1 -1
  24. package/dist/adapter/adapter.types.d.ts +55 -2
  25. package/dist/adapter/adapter.types.d.ts.map +1 -1
  26. package/dist/adapter/adapter.utils.d.ts +51 -4
  27. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  28. package/dist/adapter/http-adapter.fetch.d.ts.map +1 -1
  29. package/dist/index.d.ts +1 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.mjs +958 -128
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/socket/index.d.ts +5 -0
  34. package/dist/socket/index.d.ts.map +1 -0
  35. package/dist/socket/socket.constants.d.ts +44 -0
  36. package/dist/socket/socket.constants.d.ts.map +1 -0
  37. package/dist/socket/socket.subscriptions.d.ts +74 -0
  38. package/dist/socket/socket.subscriptions.d.ts.map +1 -0
  39. package/dist/socket/socket.types.d.ts +102 -0
  40. package/dist/socket/socket.types.d.ts.map +1 -0
  41. package/dist/socket/socket.utils.d.ts +80 -0
  42. package/dist/socket/socket.utils.d.ts.map +1 -0
  43. package/dist/socket/socket.websocket.d.ts +30 -0
  44. package/dist/socket/socket.websocket.d.ts.map +1 -0
  45. package/package.json +14 -9
  46. package/src/adapter/adapter.constants.ts +6 -0
  47. package/src/adapter/adapter.types.ts +69 -3
  48. package/src/adapter/adapter.utils.ts +196 -25
  49. package/src/adapter/http-adapter.fetch.ts +93 -43
  50. package/src/index.ts +1 -0
  51. package/src/socket/index.ts +4 -0
  52. package/src/socket/socket.constants.ts +59 -0
  53. package/src/socket/socket.subscriptions.ts +160 -0
  54. package/src/socket/socket.types.ts +118 -0
  55. package/src/socket/socket.utils.ts +150 -0
  56. package/src/socket/socket.websocket.ts +555 -0
  57. package/vite.config.ts +4 -0
@@ -0,0 +1,150 @@
1
+ import type { ShouldReconnectType } from "@hyper-fetch/sockets";
2
+ import { defaultShouldReconnect } from "@hyper-fetch/sockets";
3
+ import type { GraphQLFormattedError } from "graphql";
4
+
5
+ import { GraphqlWsMessageType, fatalGraphqlWsCloseCodes, retriedStandardCloseCodes } from "./socket.constants";
6
+ import type { GraphqlSubscriptionErrorOptionsType } from "./socket.types";
7
+
8
+ /** The object check of the `graphql-ws` client, so both accept the same messages */
9
+ export const isRecord = (value: unknown): value is Record<string, unknown> => {
10
+ return typeof value === "object" && value !== null;
11
+ };
12
+
13
+ export const toError = (value: unknown): Error => {
14
+ return value instanceof Error ? value : new Error(String(value));
15
+ };
16
+
17
+ /** A message the server may send - every other one breaks the protocol */
18
+ export type GraphqlWsServerMessageType =
19
+ | { type: typeof GraphqlWsMessageType.CONNECTION_ACK; payload?: Record<string, unknown> | null }
20
+ | { type: typeof GraphqlWsMessageType.PING; payload?: Record<string, unknown> | null }
21
+ | { type: typeof GraphqlWsMessageType.PONG; payload?: Record<string, unknown> | null }
22
+ | { type: typeof GraphqlWsMessageType.NEXT; id: string; payload: Record<string, unknown> }
23
+ | { type: typeof GraphqlWsMessageType.ERROR; id: string; payload: GraphQLFormattedError[] }
24
+ | { type: typeof GraphqlWsMessageType.COMPLETE; id: string };
25
+
26
+ const isFormattedErrors = (value: unknown): value is GraphQLFormattedError[] => {
27
+ return Array.isArray(value) && value.length > 0 && value.every((error) => isRecord(error) && "message" in error);
28
+ };
29
+
30
+ const hasId = (message: Record<string, unknown>): message is Record<string, unknown> & { id: string } => {
31
+ return typeof message.id === "string" && message.id.length > 0;
32
+ };
33
+
34
+ /**
35
+ * Reads a frame of the server. Throws when it breaks the protocol - the same checks the `graphql-ws` client makes, so
36
+ * a server that works with it works with the adapter.
37
+ */
38
+ export const parseServerMessage = (data: unknown): GraphqlWsServerMessageType => {
39
+ if (typeof data !== "string") {
40
+ throw new TypeError("Expected a text frame");
41
+ }
42
+ const message: unknown = JSON.parse(data);
43
+ if (!isRecord(message) || typeof message.type !== "string") {
44
+ throw new TypeError("Expected a message object with a string 'type'");
45
+ }
46
+
47
+ switch (message.type) {
48
+ case GraphqlWsMessageType.CONNECTION_ACK:
49
+ case GraphqlWsMessageType.PING:
50
+ case GraphqlWsMessageType.PONG: {
51
+ if (message.payload !== undefined && message.payload !== null && !isRecord(message.payload)) {
52
+ throw new TypeError(`"${message.type}" expects the payload to be an object or nullish`);
53
+ }
54
+ return message as GraphqlWsServerMessageType;
55
+ }
56
+ case GraphqlWsMessageType.NEXT: {
57
+ if (!hasId(message) || !isRecord(message.payload)) {
58
+ throw new TypeError(`"next" expects a non-empty string 'id' and an object payload`);
59
+ }
60
+ return message as GraphqlWsServerMessageType;
61
+ }
62
+ case GraphqlWsMessageType.ERROR: {
63
+ if (!hasId(message) || !isFormattedErrors(message.payload)) {
64
+ throw new TypeError(`"error" expects a non-empty string 'id' and an array of GraphQL errors as the payload`);
65
+ }
66
+ return message as GraphqlWsServerMessageType;
67
+ }
68
+ case GraphqlWsMessageType.COMPLETE: {
69
+ if (!hasId(message)) {
70
+ throw new TypeError(`"complete" expects a non-empty string 'id'`);
71
+ }
72
+ return message as GraphqlWsServerMessageType;
73
+ }
74
+ default: {
75
+ throw new TypeError(`Unexpected message type "${message.type}"`);
76
+ }
77
+ }
78
+ };
79
+
80
+ /** Reported to `onError` when the server breaks the protocol - the connection is closed with 4004 */
81
+ export const getBadResponseError = (cause: unknown): Error => {
82
+ return new Error("Received a malformed GraphQL over WebSocket message", { cause });
83
+ };
84
+
85
+ /**
86
+ * The close reason may hold at most 123 bytes. Longer reasons are cut by the `graphql-ws` client the same way:
87
+ * replaced with a short generic one.
88
+ */
89
+ export const limitCloseReason = (reason: string, fallback: string) => {
90
+ return new TextEncoder().encode(reason).byteLength <= 123 ? reason : fallback;
91
+ };
92
+
93
+ /**
94
+ * The default `shouldReconnect` of the GraphQL WebSocket adapter. It gives up on the close codes a retry can't fix -
95
+ * bad requests, unauthorized, a missing subprotocol, protocol errors and the like, the same ones the `graphql-ws` client
96
+ * gives up on - and on a normal closure (1000), as every socket adapter does. Everything else is retried. The socket's
97
+ * own `shouldReconnect` replaces it, so call this one from yours to keep these rules.
98
+ *
99
+ * @example
100
+ * const socket = new Socket({
101
+ * url,
102
+ * adapter: GraphqlWsAdapter(),
103
+ * // Retry after a normal closure too
104
+ * shouldReconnect: (loss) => loss.code === 1000 || shouldReconnectGraphqlWs(loss),
105
+ * });
106
+ */
107
+ export const shouldReconnectGraphqlWs: ShouldReconnectType = (loss) => {
108
+ const { code } = loss;
109
+ if (code === undefined) {
110
+ return true;
111
+ }
112
+ if (fatalGraphqlWsCloseCodes.has(code)) {
113
+ return false;
114
+ }
115
+ if (code > 1000 && code <= 1999 && !retriedStandardCloseCodes.has(code)) {
116
+ return false;
117
+ }
118
+ return defaultShouldReconnect(loss);
119
+ };
120
+
121
+ /**
122
+ * Error of a GraphQL subscription, reported to the `socket.onError` callbacks and to the `onEnd` of its listeners.
123
+ * The server ended the subscription with the `error` message - its validation or its source failed. `errors` holds what
124
+ * it sent.
125
+ *
126
+ * Errors of a single event do not end the subscription and come with the event in `extra.errors`.
127
+ *
128
+ * @example
129
+ * socket.onError(({ error }) => {
130
+ * if (error instanceof GraphqlSubscriptionError && error.errors[0].extensions?.code === "UNAUTHENTICATED") {
131
+ * logout();
132
+ * }
133
+ * });
134
+ */
135
+ export class GraphqlSubscriptionError extends Error {
136
+ /** Errors sent by the server with the `error` message */
137
+ readonly errors: GraphQLFormattedError[];
138
+ /** Topic of the failed subscription */
139
+ readonly topic: string;
140
+ /** Variables of the failed subscription */
141
+ readonly payload: unknown;
142
+
143
+ constructor({ errors, topic, payload }: GraphqlSubscriptionErrorOptionsType) {
144
+ super(errors.map((error) => error.message).join("\n"));
145
+ this.name = "GraphqlSubscriptionError";
146
+ this.errors = errors;
147
+ this.topic = topic;
148
+ this.payload = payload;
149
+ }
150
+ }
@@ -0,0 +1,555 @@
1
+ /* eslint-disable @typescript-eslint/no-use-before-define */
2
+ import type { EmptyTypes, QueryParamsType } from "@hyper-fetch/core";
3
+ import { stringifyQueryParams } from "@hyper-fetch/core";
4
+ import type { ConnectionAttemptType, ConnectionLossType } from "@hyper-fetch/sockets";
5
+ import {
6
+ SocketAdapter,
7
+ WebsocketReadyState,
8
+ createReconnectingConnection,
9
+ getSocketError,
10
+ getSocketUrl,
11
+ getWebsocketConstructor,
12
+ } from "@hyper-fetch/sockets";
13
+
14
+ import {
15
+ GRAPHQL_TRANSPORT_WS_PROTOCOL,
16
+ GraphqlWsCloseCode,
17
+ GraphqlWsMessageType,
18
+ defaultKeepAlive,
19
+ } from "./socket.constants";
20
+ import type { GraphqlSubscriptionType } from "./socket.subscriptions";
21
+ import { createGraphqlSubscriptions } from "./socket.subscriptions";
22
+ import type {
23
+ GraphqlWsAdapterOptionsType,
24
+ GraphqlWsAdapterType,
25
+ GraphqlWsExtraType,
26
+ GraphqlWsListenerOptionsType,
27
+ } from "./socket.types";
28
+ import type { GraphqlWsServerMessageType } from "./socket.utils";
29
+ import {
30
+ GraphqlSubscriptionError,
31
+ getBadResponseError,
32
+ limitCloseReason,
33
+ parseServerMessage,
34
+ shouldReconnectGraphqlWs,
35
+ toError,
36
+ } from "./socket.utils";
37
+
38
+ /** A close the client starts because of the protocol - sent to the server with its code */
39
+ type ProtocolCloseType = { code: number; reason: string };
40
+
41
+ type CloseEventLikeType = Pick<CloseEvent, "code"> & Partial<Pick<CloseEvent, "reason">> & Event;
42
+
43
+ /** Explains a lost connection - the protocol codes (4000+) carry the server's reason */
44
+ const getCloseError = (event: CloseEventLikeType) => {
45
+ if (event.code >= 4000) {
46
+ return new Error(`The server closed the connection with ${event.code}: ${event.reason || "no reason given"}`);
47
+ }
48
+ return new Error(getSocketError(event));
49
+ };
50
+
51
+ /**
52
+ * Socket adapter for GraphQL subscriptions over WebSocket. It speaks `graphql-transport-ws`, the protocol of the
53
+ * `graphql-ws` library - supported by Apollo Server, GraphQL Yoga, Mercurius, Hot Chocolate, Hasura and most others.
54
+ *
55
+ * - The connection counts as open once the server acknowledged `connection_init`, so the socket's
56
+ * `connectionTimeout` covers the whole handshake. `connectionParams` are sent with it, a function runs on every
57
+ * connection attempt.
58
+ * - Every document with one set of variables is one server subscription, shared by the listeners with those
59
+ * variables. Subscriptions started before the connection is acknowledged wait for it, and after a reconnect they are
60
+ * sent again.
61
+ * - The server's `ping` is answered, and `keepAlive` pings a quiet connection to notice when it died.
62
+ * - Reconnecting follows the socket's reconnection options. Close codes a retry can't fix (4400, 4401, 4409...) stop
63
+ * it - see {@link shouldReconnectGraphqlWs}.
64
+ * - With `lazy`, the connection is open only while there are subscriptions.
65
+ *
66
+ * Queries and mutations are sent with the `GraphqlAdapter` - `emit` throws.
67
+ *
68
+ * @example
69
+ * const socket = new Socket({
70
+ * url: "ws://localhost:4000/graphql",
71
+ * adapter: GraphqlWsAdapter(),
72
+ * adapterOptions: { connectionParams: () => ({ token: getToken() }) },
73
+ * });
74
+ *
75
+ * const onMessage = socket.createListener()({ topic: "OnMessage", options: { document: OnMessageDocument } });
76
+ * onMessage.listen(({ data, extra }) => {}, { payload: { room: "general" } });
77
+ */
78
+ export const GraphqlWsAdapter = (): GraphqlWsAdapterType =>
79
+ new SocketAdapter<
80
+ GraphqlWsExtraType,
81
+ GraphqlWsAdapterOptionsType,
82
+ GraphqlWsListenerOptionsType,
83
+ undefined,
84
+ QueryParamsType | string,
85
+ typeof stringifyQueryParams
86
+ >({
87
+ name: "graphql-ws",
88
+ // A subscription counts as started once it was sent over an acknowledged connection - the protocol has no
89
+ // confirmation of its own, and before the acknowledgement nothing can be sent
90
+ confirmsSubscriptions: true,
91
+ })
92
+ .setQueryParamsMapper(stringifyQueryParams)
93
+ .setConnector((bindings) => {
94
+ const { adapter, getQueryParams, onConnectFailed, onError } = bindings;
95
+
96
+ // The transport of the current attempt - `undefined` once it is detached
97
+ let websocket: WebSocket | undefined;
98
+ // The server acknowledged the current transport - only then subscriptions can be sent
99
+ let acknowledged = false;
100
+ // Options of the current connection attempt (after onConnect interceptors)
101
+ let options: GraphqlWsAdapterOptionsType | EmptyTypes = adapter.adapterOptions;
102
+ // Ends the current attempt - the keep-alive and the protocol checks use it
103
+ let loseCurrent: ((loss: ConnectionLossType) => void) | undefined;
104
+ // The code to close the current transport with, when the client ends it because of the protocol
105
+ let protocolClose: ProtocolCloseType | undefined;
106
+
107
+ let pingTimer: ReturnType<typeof setTimeout> | undefined;
108
+ let pongTimer: ReturnType<typeof setTimeout> | undefined;
109
+ let lazyCloseTimer: ReturnType<typeof setTimeout> | undefined;
110
+ // With `lazy`, the connection is closed because no subscription needs it - the next subscription opens it
111
+ let lazyIdle = true;
112
+
113
+ // Ids are never reused, so a late message of a stopped subscription can't reach a new one
114
+ let lastId = 0;
115
+ // Subscriptions running on the current connection, by their id
116
+ const running = new Map<string, GraphqlSubscriptionType>();
117
+ const ids = new Map<GraphqlSubscriptionType, string>();
118
+
119
+ const subscriptions = createGraphqlSubscriptions({
120
+ bindings,
121
+ onStart: (subscription) => startSubscription(subscription),
122
+ onStop: (subscription) => stopSubscription(subscription),
123
+ });
124
+
125
+ const isLazy = () => !!adapter.adapterOptions?.lazy;
126
+
127
+ /** Sends a message. Returns the error instead of throwing, so callers decide how to report it. */
128
+ const send = (message: Record<string, unknown>): Error | null => {
129
+ try {
130
+ // Messages are sent only while there is a transport - a closed one throws and the error is returned
131
+ websocket?.send(JSON.stringify(message));
132
+ return null;
133
+ } catch (error) {
134
+ return toError(error);
135
+ }
136
+ };
137
+
138
+ const sendOrReport = (message: Record<string, unknown>) => {
139
+ const error = send(message);
140
+ if (error) {
141
+ onError({ error });
142
+ }
143
+ return !error;
144
+ };
145
+
146
+ /**
147
+ * Ends the current connection because of the protocol, e.g. a malformed message. The transport is closed with
148
+ * the protocol `code`, so the server learns why, and the engine decides about the next attempt with it.
149
+ */
150
+ const failConnection = (
151
+ attempt: ConnectionAttemptType<GraphqlWsAdapterType>,
152
+ close: ProtocolCloseType,
153
+ error: Error,
154
+ ) => {
155
+ protocolClose = close;
156
+ // The socket is reported as disconnected first, then the error that explains why
157
+ attempt.lost({ code: close.code, reason: close.reason, error });
158
+ onError({ error });
159
+ };
160
+
161
+ /**
162
+ * Lazy connection
163
+ */
164
+
165
+ const cancelLazyClose = () => {
166
+ clearTimeout(lazyCloseTimer);
167
+ lazyCloseTimer = undefined;
168
+ };
169
+
170
+ /** With `lazy`, the first subscription opens the connection */
171
+ const connectLazily = () => {
172
+ cancelLazyClose();
173
+ if (!isLazy() || !lazyIdle) {
174
+ return;
175
+ }
176
+ lazyIdle = false;
177
+ connection.connect();
178
+ };
179
+
180
+ /** With `lazy`, the connection closes once no subscription needs it anymore */
181
+ const closeLazily = () => {
182
+ if (!isLazy() || subscriptions.getAll().length > 0) {
183
+ return;
184
+ }
185
+ cancelLazyClose();
186
+ // Every subscription that starts cancels the timer, so it only fires while there are none
187
+ const close = () => {
188
+ lazyCloseTimer = undefined;
189
+ lazyIdle = true;
190
+ connection.disconnect();
191
+ };
192
+ const timeout = adapter.adapterOptions?.lazyCloseTimeout ?? 0;
193
+ if (timeout > 0) {
194
+ lazyCloseTimer = setTimeout(close, timeout);
195
+ } else {
196
+ close();
197
+ }
198
+ };
199
+
200
+ /**
201
+ * Subscriptions
202
+ */
203
+
204
+ const startSubscription = (subscription: GraphqlSubscriptionType) => {
205
+ // Not acknowledged yet - every subscription is sent once the server acknowledges the connection
206
+ if (!websocket || !acknowledged) {
207
+ connectLazily();
208
+ return;
209
+ }
210
+ cancelLazyClose();
211
+ lastId += 1;
212
+ const id = String(lastId);
213
+ const message = {
214
+ id,
215
+ type: GraphqlWsMessageType.SUBSCRIBE,
216
+ payload: {
217
+ query: subscription.query,
218
+ operationName: subscription.operationName,
219
+ variables: subscription.payload,
220
+ },
221
+ };
222
+ if (sendOrReport(message)) {
223
+ running.set(id, subscription);
224
+ ids.set(subscription, id);
225
+ subscriptions.confirm(subscription);
226
+ }
227
+ };
228
+
229
+ /** The server forgets the subscription - after `complete`, an error or when the connection closes */
230
+ const forget = (subscription: GraphqlSubscriptionType) => {
231
+ const id = ids.get(subscription);
232
+ if (id !== undefined) {
233
+ running.delete(id);
234
+ }
235
+ ids.delete(subscription);
236
+ };
237
+
238
+ /** The connection is gone, and the server stopped every subscription of it - they are sent again on reconnect */
239
+ const forgetAll = () => {
240
+ running.forEach(subscriptions.unconfirm);
241
+ running.clear();
242
+ ids.clear();
243
+ };
244
+
245
+ const stopSubscription = (subscription: GraphqlSubscriptionType) => {
246
+ const id = ids.get(subscription);
247
+ forget(subscription);
248
+ if (id !== undefined) {
249
+ sendOrReport({ id, type: GraphqlWsMessageType.COMPLETE });
250
+ }
251
+ closeLazily();
252
+ };
253
+
254
+ /** The server ended the subscription - with `complete` (`error: null`) or the `error` message */
255
+ const endSubscription = (subscription: GraphqlSubscriptionType, error: Error | null) => {
256
+ forget(subscription);
257
+ if (error) {
258
+ onError({ error });
259
+ }
260
+ subscriptions.end(subscription, error);
261
+ closeLazily();
262
+ };
263
+
264
+ /**
265
+ * Messages
266
+ */
267
+
268
+ const onAcknowledged = (attempt: ConnectionAttemptType<GraphqlWsAdapterType>) => {
269
+ acknowledged = true;
270
+ attempt.ready();
271
+ // A connected callback may have closed the connection already
272
+ if (!attempt.isCurrent()) {
273
+ return;
274
+ }
275
+ subscriptions.getAll().forEach(startSubscription);
276
+ onHeartbeat();
277
+ };
278
+
279
+ const onSubscriptionMessage = (message: Extract<GraphqlWsServerMessageType, { id: string }>) => {
280
+ const subscription = running.get(message.id);
281
+ // Late messages of a subscription stopped by the client
282
+ if (!subscription) {
283
+ return;
284
+ }
285
+ switch (message.type) {
286
+ case GraphqlWsMessageType.NEXT: {
287
+ const { data, errors, extensions } = message.payload;
288
+ subscriptions.deliver(subscription, {
289
+ data: data ?? null,
290
+ errors: Array.isArray(errors) ? errors : undefined,
291
+ extensions,
292
+ });
293
+ return;
294
+ }
295
+ case GraphqlWsMessageType.ERROR: {
296
+ const error = new GraphqlSubscriptionError({
297
+ errors: message.payload,
298
+ topic: subscription.topic,
299
+ payload: subscription.payload,
300
+ });
301
+ endSubscription(subscription, error);
302
+ return;
303
+ }
304
+ default: {
305
+ endSubscription(subscription, null);
306
+ }
307
+ }
308
+ };
309
+
310
+ const onMessage = (event: MessageEvent, attempt: ConnectionAttemptType<GraphqlWsAdapterType>) => {
311
+ // Any message proves the connection is alive
312
+ onHeartbeat();
313
+
314
+ let message: GraphqlWsServerMessageType;
315
+ try {
316
+ message = parseServerMessage(event.data);
317
+ } catch (error) {
318
+ const reason = limitCloseReason(toError(error).message, "Bad response");
319
+ failConnection(attempt, { code: GraphqlWsCloseCode.BAD_RESPONSE, reason }, getBadResponseError(error));
320
+ return;
321
+ }
322
+
323
+ switch (message.type) {
324
+ case GraphqlWsMessageType.PING: {
325
+ sendOrReport(
326
+ message.payload
327
+ ? { type: GraphqlWsMessageType.PONG, payload: message.payload }
328
+ : { type: GraphqlWsMessageType.PONG },
329
+ );
330
+ return;
331
+ }
332
+ case GraphqlWsMessageType.PONG: {
333
+ return;
334
+ }
335
+ case GraphqlWsMessageType.CONNECTION_ACK: {
336
+ // A repeated acknowledgement changes nothing
337
+ if (!acknowledged) {
338
+ onAcknowledged(attempt);
339
+ }
340
+ return;
341
+ }
342
+ default: {
343
+ if (!acknowledged) {
344
+ const reason = `First message cannot be of type ${message.type}`;
345
+ failConnection(
346
+ attempt,
347
+ { code: GraphqlWsCloseCode.BAD_RESPONSE, reason },
348
+ getBadResponseError(new Error(reason)),
349
+ );
350
+ return;
351
+ }
352
+ onSubscriptionMessage(message);
353
+ }
354
+ }
355
+ };
356
+
357
+ /**
358
+ * Connection
359
+ */
360
+
361
+ /** Sends `connection_init` with the connection params of the attempt */
362
+ const initialize = async (attempt: ConnectionAttemptType<GraphqlWsAdapterType>, transport: WebSocket) => {
363
+ const connectionParams = options?.connectionParams;
364
+ let payload: Record<string, unknown> | undefined;
365
+ try {
366
+ payload = typeof connectionParams === "function" ? await connectionParams() : connectionParams;
367
+ } catch (error) {
368
+ if (attempt.isCurrent()) {
369
+ const cause = toError(error);
370
+ const reason = limitCloseReason(cause.message, "Internal client error");
371
+ failConnection(
372
+ attempt,
373
+ { code: GraphqlWsCloseCode.INTERNAL_CLIENT_ERROR, reason },
374
+ new Error("Could not get the connection params", { cause }),
375
+ );
376
+ }
377
+ return;
378
+ }
379
+ // The connection may be gone while the params were prepared
380
+ if (!attempt.isCurrent() || transport.readyState !== WebsocketReadyState.OPEN) {
381
+ return;
382
+ }
383
+ sendOrReport(
384
+ payload
385
+ ? { type: GraphqlWsMessageType.CONNECTION_INIT, payload }
386
+ : { type: GraphqlWsMessageType.CONNECTION_INIT },
387
+ );
388
+ };
389
+
390
+ /** Creates the transport, reporting a failed attempt when the environment or the connection details are invalid */
391
+ const createWebsocket = (url: string) => {
392
+ try {
393
+ const WebsocketConstructor = getWebsocketConstructor(options);
394
+ if (!WebsocketConstructor) {
395
+ onConnectFailed({ error: new Error("WebSocket is not available in this environment") });
396
+ return null;
397
+ }
398
+ return new WebsocketConstructor(url, GRAPHQL_TRANSPORT_WS_PROTOCOL);
399
+ } catch (error) {
400
+ onConnectFailed({ error: toError(error) });
401
+ return null;
402
+ }
403
+ };
404
+
405
+ /**
406
+ * Closes a detached transport. The server stops every subscription of a closed connection on its own, so they
407
+ * are sent again on the next one. Resolves on the close - or on an error, as a transport that fails while
408
+ * closing may report only `error` (Node.js 22).
409
+ */
410
+ const closeWebsocket = (transport: WebSocket): Promise<void> => {
411
+ // The engine closes an attempt before it opens the next one, so this is always the current transport
412
+ const { code, reason } = protocolClose ?? { code: 1000, reason: "Normal Closure" };
413
+ websocket = undefined;
414
+ acknowledged = false;
415
+ loseCurrent = undefined;
416
+ protocolClose = undefined;
417
+ clearTimers();
418
+ forgetAll();
419
+ if (transport.readyState === WebsocketReadyState.CLOSED) {
420
+ return Promise.resolve();
421
+ }
422
+ return new Promise<void>((resolve) => {
423
+ transport.addEventListener("close", () => resolve(), { once: true });
424
+ transport.addEventListener("error", () => resolve(), { once: true });
425
+ try {
426
+ transport.close(code, reason);
427
+ } catch {
428
+ // Closing a transport that never connected may throw in some runtimes - it is detached already
429
+ resolve();
430
+ }
431
+ });
432
+ };
433
+
434
+ const connection = createReconnectingConnection({
435
+ bindings,
436
+ // A lazy connection waits for its first subscription
437
+ autoConnect: !adapter.adapterOptions?.lazy && (adapter.adapterOptions?.autoConnect ?? true),
438
+ shouldReconnect: shouldReconnectGraphqlWs,
439
+ open: (attempt) => {
440
+ options = attempt.connection.adapterOptions;
441
+ const url = getSocketUrl(attempt.connection.url, getQueryParams(attempt.connection.queryParams));
442
+ const transport = createWebsocket(url);
443
+ if (!transport) {
444
+ return null;
445
+ }
446
+ websocket = transport;
447
+ acknowledged = false;
448
+
449
+ // Ignored by the engine once the attempt was replaced
450
+ loseCurrent = attempt.lost;
451
+
452
+ /** The transport is gone - report it and let the engine decide about the next attempt */
453
+ const onTransportClosed = (event: CloseEventLikeType) => {
454
+ // The socket is reported as disconnected first, then the error that explains why
455
+ attempt.lost({ code: event.code, reason: event.reason || undefined });
456
+ onError({ error: getCloseError(event) });
457
+ };
458
+
459
+ transport.addEventListener("open", () => {
460
+ if (attempt.isCurrent()) {
461
+ initialize(attempt, transport);
462
+ }
463
+ });
464
+
465
+ transport.addEventListener("close", (event) => {
466
+ if (attempt.isCurrent()) {
467
+ onTransportClosed(event);
468
+ }
469
+ });
470
+
471
+ // Node.js 22 reports a failed handshake with `error` only - no `close` follows and the transport stays
472
+ // CONNECTING. Browsers set CLOSED before the error and send the close event, which handles it as usual.
473
+ // Here it is treated as an abnormally closed transport (1006).
474
+ transport.addEventListener("error", () => {
475
+ if (!attempt.isCurrent() || transport.readyState !== WebsocketReadyState.CONNECTING) {
476
+ return;
477
+ }
478
+ onTransportClosed(Object.assign(new Event("close"), { code: 1006 }));
479
+ });
480
+
481
+ transport.addEventListener("message", (event) => {
482
+ if (attempt.isCurrent()) {
483
+ onMessage(event, attempt);
484
+ }
485
+ });
486
+
487
+ return { close: () => closeWebsocket(transport) };
488
+ },
489
+ });
490
+
491
+ /**
492
+ * Keep-alive
493
+ */
494
+
495
+ const clearTimers = () => {
496
+ clearTimeout(pingTimer);
497
+ clearTimeout(pongTimer);
498
+ };
499
+
500
+ const onHeartbeat = () => {
501
+ const { enabled = false, ...keepAlive } = options?.keepAlive ?? {};
502
+ const { intervalMs, pongTimeoutMs } = { ...defaultKeepAlive, ...keepAlive };
503
+
504
+ if (!acknowledged || !enabled) {
505
+ return;
506
+ }
507
+ clearTimers();
508
+ pingTimer = setTimeout(() => {
509
+ sendOrReport({ type: GraphqlWsMessageType.PING });
510
+ pongTimer = setTimeout(() => {
511
+ onHeartbeatTimeout();
512
+ }, pongTimeoutMs);
513
+ }, intervalMs);
514
+ };
515
+
516
+ /**
517
+ * The server did not answer the ping - the connection is dead. Its closing handshake may never finish, so the
518
+ * engine detaches the transport right away instead of waiting for its `close` event.
519
+ */
520
+ const onHeartbeatTimeout = () => {
521
+ const error = new Error("Keep-alive timeout - the server did not answer the ping in time");
522
+ // The socket is reported as disconnected first, then the error that explains why
523
+ loseCurrent?.({ error });
524
+ onError({ error });
525
+ };
526
+
527
+ // Subscriptions only - queries and mutations are sent with the GraphqlAdapter. Throwing synchronously makes
528
+ // `emitter.emit()` fail right at the call site, the same way the SSE adapter does it.
529
+ const emit = () => {
530
+ throw new Error("Cannot emit events with the GraphQL WebSocket adapter, it supports subscriptions only");
531
+ };
532
+
533
+ return {
534
+ connect: () => {
535
+ lazyIdle = false;
536
+ return connection.connect();
537
+ },
538
+ reconnect: () => {
539
+ lazyIdle = false;
540
+ return connection.reconnect();
541
+ },
542
+ disconnect: () => {
543
+ cancelLazyClose();
544
+ return connection.disconnect();
545
+ },
546
+ listen: subscriptions.listen,
547
+ emit,
548
+ // The socket is destroyed or the adapter moves to another socket - stop following the network state
549
+ dispose: () => {
550
+ connection.dispose();
551
+ clearTimers();
552
+ cancelLazyClose();
553
+ },
554
+ };
555
+ });