@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.
- package/README.md +152 -84
- package/__tests__/e2e/e2e.conformance.spec.ts +206 -0
- package/__tests__/e2e/e2e.graphql-ws-server.ts +187 -0
- package/__tests__/e2e/e2e.graphql-ws.spec.ts +306 -0
- package/__tests__/e2e/e2e.react-subscriptions.spec.tsx +208 -0
- package/__tests__/features/adapter/adapter.browser.spec.ts +23 -5
- package/__tests__/features/adapter/adapter.document.spec.ts +17 -13
- package/__tests__/features/adapter/adapter.headers.spec.ts +65 -0
- package/__tests__/features/adapter/adapter.keys.spec.ts +235 -0
- package/__tests__/features/adapter/adapter.persisted-queries.spec.ts +207 -0
- package/__tests__/features/adapter/adapter.progress.spec.ts +39 -0
- package/__tests__/features/adapter/adapter.responses.spec.ts +162 -1
- package/__tests__/features/adapter/adapter.server.spec.ts +6 -6
- package/__tests__/features/adapter/adapter.types.spec.ts +121 -2
- package/__tests__/features/adapter/adapter.utils.spec.ts +4 -2
- package/__tests__/features/adapter/adapter.variables.spec.ts +3 -3
- package/__tests__/features/socket/socket.connection.spec.ts +892 -0
- package/__tests__/features/socket/socket.fuzz.spec.ts +329 -0
- package/__tests__/features/socket/socket.subscriptions.spec.ts +515 -0
- package/__tests__/features/socket/socket.types.spec.ts +160 -0
- package/__tests__/utils/controlled-websocket.ts +238 -0
- package/dist/adapter/adapter.constants.d.ts +5 -0
- package/dist/adapter/adapter.constants.d.ts.map +1 -1
- package/dist/adapter/adapter.types.d.ts +55 -2
- package/dist/adapter/adapter.types.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts +51 -4
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/adapter/http-adapter.fetch.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +958 -128
- package/dist/index.mjs.map +1 -1
- package/dist/socket/index.d.ts +5 -0
- package/dist/socket/index.d.ts.map +1 -0
- package/dist/socket/socket.constants.d.ts +44 -0
- package/dist/socket/socket.constants.d.ts.map +1 -0
- package/dist/socket/socket.subscriptions.d.ts +74 -0
- package/dist/socket/socket.subscriptions.d.ts.map +1 -0
- package/dist/socket/socket.types.d.ts +102 -0
- package/dist/socket/socket.types.d.ts.map +1 -0
- package/dist/socket/socket.utils.d.ts +80 -0
- package/dist/socket/socket.utils.d.ts.map +1 -0
- package/dist/socket/socket.websocket.d.ts +30 -0
- package/dist/socket/socket.websocket.d.ts.map +1 -0
- package/package.json +14 -9
- package/src/adapter/adapter.constants.ts +6 -0
- package/src/adapter/adapter.types.ts +69 -3
- package/src/adapter/adapter.utils.ts +196 -25
- package/src/adapter/http-adapter.fetch.ts +93 -43
- package/src/index.ts +1 -0
- package/src/socket/index.ts +4 -0
- package/src/socket/socket.constants.ts +59 -0
- package/src/socket/socket.subscriptions.ts +160 -0
- package/src/socket/socket.types.ts +118 -0
- package/src/socket/socket.utils.ts +150 -0
- package/src/socket/socket.websocket.ts +555 -0
- package/vite.config.ts +4 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/adapter/adapter.constants.ts","../src/adapter/adapter.types.ts","../src/adapter/adapter.utils.ts","../src/adapter/http-adapter.fetch.ts","../src/adapter/adapter.ts"],"sourcesContent":["import { Time } from \"@hyper-fetch/core\";\n\nimport type { GraphQlExtraType } from \"./adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\nexport const gqlExtra: GraphQlExtraType = {\n headers: {},\n extensions: {},\n};\n","import type { Adapter, DefaultMapperType, EmptyTypes, QueryParamsType, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { DocumentNode } from \"graphql/language/ast\";\n\nexport enum GraphqlMethod {\n POST = \"POST\",\n GET = \"GET\",\n}\n\nexport type GraphQlExtraType = { headers: HeadersInit; extensions: Record<string, any> };\n\nexport type GraphQlEndpointType = string | DocumentNode;\n\nexport type FetchGraphqlAdapterOptionsType = Omit<RequestInit, \"method\" | \"headers\" | \"body\" | \"signal\"> & {\n timeout?: number;\n};\n\nexport type GraphqlRequestOptionsType = {\n /**\n * GraphQL document sent as `query`. When it is set, `endpoint` becomes a URL path appended to `client.url`,\n * the same way as in the HttpAdapter. When it is omitted, `endpoint` holds the document and the URL is `client.url`.\n */\n document?: GraphQlEndpointType;\n};\n\nexport type GraphqlAdapterType = Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n QueryParamsType | string | undefined,\n GraphQlEndpointType,\n (endpoint: GraphQlEndpointType) => string,\n typeof stringifyQueryParams,\n DefaultMapperType,\n DefaultMapperType,\n GraphqlRequestOptionsType\n>;\n\n// Extract\n\ntype GqlParamType = boolean | string | number | Record<string, any> | EmptyTypes;\n\nexport type ExtractGqlRouteParams<T extends string> = string extends T\n ? EmptyTypes\n : T extends `${string}query ${infer Parameters} {${infer QueryRest}`\n ? Parameters extends `${string}$${infer Param},${infer Rest}`\n ? GqlParameter<Param, Rest> &\n // eslint-disable-next-line @typescript-eslint/ban-types\n (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n : Parameters extends `${string}$${infer Param})${infer Rest}`\n ? GqlParameter<Param, Rest> &\n // eslint-disable-next-line @typescript-eslint/ban-types\n (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n : EmptyTypes\n : T extends `${string}$${infer Parameters},${infer Rest}`\n ? GqlParameter<Parameters, Rest>\n : T extends `${string}$${infer Parameters})${infer Rest}`\n ? GqlParameter<Parameters, Rest>\n : EmptyTypes;\n\nexport type GqlParameter<T extends string, Rest extends string> = T extends `${infer Param}:${string}!`\n ? { [k in Param]: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n ? // eslint-disable-next-line @typescript-eslint/ban-types\n {}\n : ExtractGqlRouteParams<Rest>)\n : T extends `${infer Param}:${string}`\n ? { [k in Param]?: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n ? // eslint-disable-next-line @typescript-eslint/ban-types\n {}\n : ExtractGqlRouteParams<Rest>)\n : EmptyTypes;\n","import type { EmptyTypes, QueryParamsType, RequestInstance } from \"@hyper-fetch/core\";\nimport { HttpMethods, stringifyKey, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { DocumentNode, OperationDefinitionNode } from \"graphql\";\nimport { print, parse } from \"graphql\";\n\nimport type { GraphQlEndpointType, GraphqlRequestOptionsType } from \"./adapter.types\";\n\nconst getDocumentOption = (request: RequestInstance) => {\n return (request.requestOptions as unknown as GraphqlRequestOptionsType).document;\n};\n\nconst hasDocumentOption = (request: RequestInstance) => getDocumentOption(request) != null;\n\n/** The document of the request - from the `document` option or, when it is omitted, from the `endpoint` */\nexport const getGqlDocument = (request: RequestInstance): GraphQlEndpointType => {\n return getDocumentOption(request) ?? request.endpoint;\n};\n\n/** Query string keys owned by the GraphQL over HTTP GET format - they win over the user query params */\nconst reservedQueryParams = [\"query\", \"variables\"];\n\nconst isReservedQueryParam = (param: string) => {\n const [rawKey] = param.split(\"=\");\n try {\n // Array formats encode the key as `key[]` or `key[0]`\n return reservedQueryParams.includes(decodeURIComponent(rawKey).split(\"[\")[0]);\n } catch {\n return false;\n }\n};\n\nconst omitReservedQueryParams = (queryString: string) => {\n return queryString\n .replace(/^\\?/, \"\")\n .split(\"&\")\n .filter((param) => !isReservedQueryParam(param))\n .join(\"&\");\n};\n\nconst joinQueryStrings = (...queryStrings: string[]) => {\n const joined = queryStrings\n .map((queryString) => queryString.replace(/^\\?/, \"\"))\n .filter(Boolean)\n .join(\"&\");\n\n return joined ? `?${joined}` : \"\";\n};\n\nexport const getRequestValues = <R extends RequestInstance>(\n request: R,\n queryParams: unknown = request.client.adapter.unstable_queryParamsMapper(request.queryParams),\n) => {\n const isPostRequest = request.method === HttpMethods.POST;\n\n const query = gqlEndpointMapper(getGqlDocument(request));\n const variables = request.payload;\n\n const url = hasDocumentOption(request) ? `${request.client.url}${request.endpoint}` : request.client.url;\n // Mappers can return anything, so we normalize their result to the query string\n const queryString = stringifyQueryParams(queryParams as QueryParamsType | string | EmptyTypes);\n\n const fullUrl = isPostRequest\n ? url + joinQueryStrings(queryString)\n : url + joinQueryStrings(stringifyQueryParams({ query, variables }), omitReservedQueryParams(queryString));\n\n const payload = isPostRequest\n ? JSON.stringify({\n query,\n variables,\n })\n : null;\n\n return { fullUrl, payload };\n};\n\nexport const gqlEndpointMapper = <E extends GraphQlEndpointType>(endpoint: E): string => {\n if (typeof endpoint === \"string\") {\n return endpoint;\n }\n return print(endpoint);\n};\n\nconst getOperationName = (ast: DocumentNode): string | undefined => {\n const operationDefinition = ast.definitions.find(\n (def): def is OperationDefinitionNode => def.kind === \"OperationDefinition\",\n );\n\n if (operationDefinition) {\n if (operationDefinition.name?.value) {\n return operationDefinition.name.value;\n }\n\n const selection = operationDefinition.selectionSet.selections[0];\n if (selection?.kind === \"Field\") {\n return selection.name.value;\n }\n if (selection?.kind === \"InlineFragment\" && selection.typeCondition) {\n return selection.typeCondition.name.value;\n }\n }\n\n return undefined;\n};\n\nexport const gqlEndpointNameMapper = (endpoint: GraphQlEndpointType): string => {\n if (typeof endpoint !== \"string\") {\n return getOperationName(endpoint) || \"graphql-request\";\n }\n\n try {\n const name = getOperationName(parse(endpoint));\n\n if (name) {\n return name;\n }\n } catch {\n // We can ignore this error and just return some fallback\n }\n\n // Fallback for invalid gql queries or something else\n const clearedQuery = endpoint\n .replace(/(query|mutation|subscription)/, \"\")\n .replaceAll(/[{}().,:]/g, \" \")\n .trim();\n const [name] = clearedQuery.split(\" \");\n\n return name || \"graphql-request\";\n};\n\n/**\n * Name identifying the request in the cache, query and abort keys.\n * With the `document` option the same operation can be sent to many paths, so the path is a part of the name.\n */\nexport const gqlRequestNameMapper = (request: RequestInstance): string => {\n const name = gqlEndpointNameMapper(getGqlDocument(request));\n\n return hasDocumentOption(request) ? `${name}${request.requestOptions.endpoint}` : name;\n};\n\n/**\n * Cache and query key of a request. The variables are a part of it: the same operation with other variables is\n * another query, with its own cached data and its own place in the queue.\n */\nexport const gqlRequestKeyMapper = (request: RequestInstance): string => {\n const key = `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n const variables = stringifyKey(request.payload);\n\n return variables ? `${key}-${variables}` : key;\n};\n","import type { DefaultMapperType, QueryParamsType } from \"@hyper-fetch/core\";\nimport { parseResponse, getErrorMessage, Adapter, stringifyQueryParams } from \"@hyper-fetch/core\";\n\nimport { gqlExtra, defaultTimeout } from \"./adapter.constants\";\nimport type {\n GraphqlAdapterType,\n GraphQlExtraType,\n GraphQlEndpointType,\n FetchGraphqlAdapterOptionsType,\n GraphqlRequestOptionsType,\n} from \"./adapter.types\";\nimport { GraphqlMethod } from \"./adapter.types\";\nimport {\n getRequestValues,\n gqlEndpointMapper,\n gqlEndpointNameMapper,\n gqlRequestKeyMapper,\n gqlRequestNameMapper,\n} from \"./adapter.utils\";\n\nexport const getGqlAdapter = (): GraphqlAdapterType =>\n new Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n QueryParamsType | string | undefined,\n GraphQlEndpointType,\n DefaultMapperType,\n DefaultMapperType,\n DefaultMapperType,\n DefaultMapperType,\n GraphqlRequestOptionsType\n >({\n name: \"graphql\",\n defaultMethod: GraphqlMethod.POST,\n defaultExtra: gqlExtra,\n systemErrorStatus: 0,\n systemErrorExtra: gqlExtra,\n })\n .onInitialize(({ client }) => {\n client.setCacheKeyMapper(gqlRequestKeyMapper);\n client.setQueryKeyMapper(gqlRequestKeyMapper);\n client.setAbortKeyMapper((request) => {\n return `${request.method}_${gqlRequestNameMapper(request)}-${request.cancelable}`;\n });\n })\n .setInternalErrorMapping((error) => [error])\n .setDevtoolsEndpointGetter((endpoint, requestOptions) =>\n gqlEndpointNameMapper(requestOptions?.document ?? endpoint),\n )\n .setEndpointMapper(gqlEndpointMapper)\n .setQueryParamsMapper(stringifyQueryParams)\n .setFetcher(\n async ({\n request,\n queryParams,\n adapterOptions,\n headers,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n getAbortController,\n onResponseProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onSuccess,\n }) => {\n const { fullUrl, payload } = getRequestValues(request, queryParams);\n\n const controller = getAbortController();\n const { timeout: timeoutMs = defaultTimeout, ...restOptions } = adapterOptions || {};\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const unmountListener = createAbortListener({\n status: 0,\n extra: gqlExtra,\n });\n\n if (timeoutMs > 0 && controller) {\n timeoutId = setTimeout(() => {\n timedOut = true;\n unmountListener();\n controller.abort();\n }, timeoutMs);\n }\n\n onBeforeRequest();\n onRequestStart();\n\n try {\n const init: RequestInit = {\n method: request.method,\n headers: headers as Record<string, string>,\n signal: controller?.signal,\n ...restOptions,\n };\n\n if (payload) {\n init.body = payload;\n\n if (typeof payload === \"string\") {\n const total = new Blob([payload]).size;\n onRequestProgress({ total, loaded: total } as ProgressEvent);\n }\n }\n\n onRequestEnd();\n\n const response = await fetch(fullUrl, init);\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n onResponseStart();\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n let body: string;\n\n if (response.body && typeof response.body.getReader === \"function\") {\n const reader = response.body.getReader();\n const contentLength = parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n let receivedLength = 0;\n const chunks: Uint8Array[] = [];\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n chunks.push(value);\n receivedLength += value.length;\n onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);\n }\n\n const allChunks = new Uint8Array(receivedLength);\n let position = 0;\n // eslint-disable-next-line no-restricted-syntax\n for (const chunk of chunks) {\n allChunks.set(chunk, position);\n position += chunk.length;\n }\n body = new TextDecoder().decode(allChunks);\n } else {\n body = await response.text();\n }\n\n onResponseEnd();\n unmountListener();\n\n const { status } = response;\n const parsed = parseResponse(body);\n const data = parsed?.data ?? null;\n // An empty `errors` list is not a failure\n const errors = Array.isArray(parsed?.errors) && parsed.errors.length === 0 ? null : parsed?.errors || null;\n const extensions = parsed?.extensions || {};\n const failure = errors || status > 399 || status === 0;\n\n if (failure) {\n const error = errors || [getErrorMessage()];\n onError({ error, status, extra: { headers: responseHeaders, extensions } });\n } else {\n onSuccess({\n data,\n error: errors,\n status,\n extra: { headers: responseHeaders, extensions },\n });\n }\n } catch (error: any) {\n if (timeoutId) clearTimeout(timeoutId);\n unmountListener();\n\n if (controller?.signal?.aborted) {\n if (timedOut) {\n onTimeoutError({ status: 0, extra: gqlExtra });\n }\n return;\n }\n\n // Errors are always a list, like the GraphQL `errors` and the abort and timeout errors\n onError({ error: [error], status: 0, extra: gqlExtra });\n }\n },\n );\n","import type { GraphqlAdapterType } from \"./adapter.types\";\nimport { getGqlAdapter } from \"./http-adapter.fetch\";\n\nexport const GraphqlAdapter = (): GraphqlAdapterType => {\n return getGqlAdapter();\n};\n"],"mappings":";;;AAIA,IAAa,iBAAiB,KAAK,MAAM;AAEzC,IAAa,WAA6B;CACxC,SAAS,EAAE;CACX,YAAY,EAAE;CACf;;;ACND,IAAY,gBAAL,yBAAA,eAAA;AACL,eAAA,UAAA;AACA,eAAA,SAAA;;KACD;;;ACCD,IAAM,qBAAqB,YAA6B;AACtD,QAAQ,QAAQ,eAAwD;;AAG1E,IAAM,qBAAqB,YAA6B,kBAAkB,QAAQ,IAAI;;AAGtF,IAAa,kBAAkB,YAAkD;AAC/E,QAAO,kBAAkB,QAAQ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nML,IAAa,uBAA2C;AACtD,QAAO,eAAe"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/adapter/adapter.constants.ts","../src/adapter/adapter.types.ts","../src/adapter/adapter.utils.ts","../src/adapter/http-adapter.fetch.ts","../src/adapter/adapter.ts","../src/socket/socket.constants.ts","../src/socket/socket.utils.ts","../src/socket/socket.subscriptions.ts","../src/socket/socket.websocket.ts"],"sourcesContent":["import { Time } from \"@hyper-fetch/core\";\n\nimport type { GraphQlExtraType } from \"./adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\n/**\n * GraphQL over HTTP media type first, so spec compliant servers answer with meaningful status codes,\n * and JSON as the fallback for the others.\n */\nexport const gqlAcceptHeader = \"application/graphql-response+json, application/json;q=0.9\";\n\nexport const gqlExtra: GraphQlExtraType = {\n headers: {},\n extensions: {},\n};\n","import type {\n Adapter,\n DefaultMapperType,\n EmptyTypes,\n ExtractEndpointPayloadType,\n ExtractEndpointResponseType,\n QueryParamsType,\n RequestInstance,\n stringifyQueryParams,\n} from \"@hyper-fetch/core\";\nimport type { GraphQLFormattedError } from \"graphql\";\nimport type { DocumentNode } from \"graphql/language/ast\";\n\nexport enum GraphqlMethod {\n POST = \"POST\",\n GET = \"GET\",\n}\n\nexport type GraphQlExtraType = {\n headers: HeadersInit;\n extensions: Record<string, any>;\n /**\n * The `errors` of the response body, when the server sent any. With the `\"all\"` error policy a response with\n * partial data succeeds, and this is where its errors are.\n */\n errors?: GraphQLFormattedError[];\n};\n\n/**\n * What a response that has both `data` and `errors` resolves to.\n *\n * - `\"none\"` - it fails: `data` is `null` and `error` holds the errors.\n * - `\"all\"` - it succeeds with the partial `data`, and the errors are in `extra.errors`. A response without `data`\n * still fails.\n */\nexport type GraphqlErrorPolicy = \"none\" | \"all\";\n\n/**\n * Error of a GraphQL request: the `errors` of the response body, or a single network, abort or timeout error.\n * Pass it to the client to type `response.error` - `new Client<GraphqlErrorType>({ url })`.\n */\nexport type GraphqlErrorType = (GraphQLFormattedError | Error)[];\n\nexport type GraphQlEndpointType = string | DocumentNode;\n\nexport type FetchGraphqlAdapterOptionsType = Omit<RequestInit, \"method\" | \"headers\" | \"body\" | \"signal\"> & {\n timeout?: number;\n /**\n * What a response with both `data` and `errors` resolves to. `\"none\"` fails it, `\"all\"` keeps the partial data.\n * @default \"none\"\n */\n errorPolicy?: GraphqlErrorPolicy;\n /**\n * Automatic persisted queries. The request sends the SHA-256 hash of the query instead of the query, and the full\n * query only when the server does not know the hash yet. Hashed `GET` requests stay short, so CDNs can cache them.\n * Without Web Crypto (`crypto.subtle`) the full query is sent.\n * @default false\n */\n persistedQueries?: boolean;\n};\n\n/** The `persistedQuery` extension of automatic persisted queries */\nexport type GraphqlPersistedQueryType = { version: 1; sha256Hash: string };\n\nexport type GraphqlRequestOptionsType = {\n /**\n * GraphQL document sent as `query`. When it is set, `endpoint` becomes a URL path appended to `client.url`,\n * the same way as in the HttpAdapter. When it is omitted, `endpoint` holds the document and the URL is `client.url`.\n */\n document?: GraphQlEndpointType;\n};\n\n/**\n * Response and payload of a typed document - a `TypedDocumentNode` from graphql-codegen or a gql.tada document.\n * `createRequest` reads them from a typed document passed as `endpoint` by itself. Use this type when the document is\n * passed with the `document` option, or to combine the document types with other request types.\n *\n * @example\n * ```ts\n * const getUser = client.createRequest<GraphqlDocumentTypes<typeof GetUserDocument>>()({\n * endpoint: \"/User\",\n * document: GetUserDocument,\n * });\n * ```\n */\nexport type GraphqlDocumentTypes<Document> = {\n response: ExtractEndpointResponseType<Document>;\n payload: ExtractEndpointPayloadType<Document>;\n};\n\nexport type GraphqlAdapterType = Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n QueryParamsType | string | undefined,\n GraphQlEndpointType,\n (endpoint: GraphQlEndpointType) => string,\n typeof stringifyQueryParams,\n (request: RequestInstance) => HeadersInit,\n DefaultMapperType,\n GraphqlRequestOptionsType\n>;\n\n// Extract\n\ntype GqlParamType = boolean | string | number | Record<string, any> | EmptyTypes;\n\nexport type ExtractGqlRouteParams<T extends string> = string extends T\n ? EmptyTypes\n : T extends `${string}query ${infer Parameters} {${infer QueryRest}`\n ? Parameters extends `${string}$${infer Param},${infer Rest}`\n ? GqlParameter<Param, Rest> &\n // eslint-disable-next-line @typescript-eslint/ban-types\n (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n : Parameters extends `${string}$${infer Param})${infer Rest}`\n ? GqlParameter<Param, Rest> &\n // eslint-disable-next-line @typescript-eslint/ban-types\n (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n : EmptyTypes\n : T extends `${string}$${infer Parameters},${infer Rest}`\n ? GqlParameter<Parameters, Rest>\n : T extends `${string}$${infer Parameters})${infer Rest}`\n ? GqlParameter<Parameters, Rest>\n : EmptyTypes;\n\nexport type GqlParameter<T extends string, Rest extends string> = T extends `${infer Param}:${string}!`\n ? { [k in Param]: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n ? // eslint-disable-next-line @typescript-eslint/ban-types\n {}\n : ExtractGqlRouteParams<Rest>)\n : T extends `${infer Param}:${string}`\n ? { [k in Param]?: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n ? // eslint-disable-next-line @typescript-eslint/ban-types\n {}\n : ExtractGqlRouteParams<Rest>)\n : EmptyTypes;\n","import type { EmptyTypes, QueryParamsType, RequestInstance } from \"@hyper-fetch/core\";\nimport { getAdapterHeaders, HttpMethods, Request, stringifyKey, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { DocumentNode, OperationDefinitionNode } from \"graphql\";\nimport { print, parse } from \"graphql\";\n\nimport type { GraphQlEndpointType, GraphqlPersistedQueryType, GraphqlRequestOptionsType } from \"./adapter.types\";\nimport { GraphqlMethod } from \"./adapter.types\";\n\n/** Whether the request headers name the content type, also with an empty value that removes it */\nconst hasContentTypeHeader = (headers: HeadersInit | undefined) => {\n if (!headers) return false;\n const names =\n typeof Headers !== \"undefined\" && headers instanceof Headers\n ? [...headers.keys()]\n : (Array.isArray(headers) ? headers : Object.entries(headers)).map(([name]) => name);\n return names.some((name) => name.toLowerCase() === \"content-type\");\n};\n\n/**\n * A POST body is always JSON (`query`, `operationName`, `variables`, `extensions`), also for an operation without\n * variables, so it needs the JSON content type. A GET request has no body and sends the operation in the URL, so it\n * gets none - the header would only trigger a CORS preflight. A content type given with the request always wins.\n */\nexport const getGqlHeaders = (request: RequestInstance): HeadersInit => {\n const headers = { ...(getAdapterHeaders(request) as Record<string, string>) };\n\n if (hasContentTypeHeader(request.headers)) {\n return headers;\n }\n\n delete headers[\"Content-Type\"];\n if (request.method === GraphqlMethod.POST) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n return headers;\n};\n\nconst getDocumentOption = (request: RequestInstance) => {\n return (request.requestOptions as unknown as GraphqlRequestOptionsType).document;\n};\n\nconst hasDocumentOption = (request: RequestInstance) => getDocumentOption(request) != null;\n\n/** The document of the request - from the `document` option or, when it is omitted, from the `endpoint` */\nexport const getGqlDocument = (request: RequestInstance): GraphQlEndpointType => {\n return getDocumentOption(request) ?? request.endpoint;\n};\n\n/** Query string keys owned by the GraphQL over HTTP GET format - they win over the user query params */\nconst reservedQueryParams = new Set([\"query\", \"operationName\", \"variables\", \"extensions\"]);\n\nconst isReservedQueryParam = (param: string) => {\n const [rawKey] = param.split(\"=\");\n try {\n // Array formats encode the key as `key[]` or `key[0]`\n return reservedQueryParams.has(decodeURIComponent(rawKey).split(\"[\")[0]);\n } catch {\n return false;\n }\n};\n\nconst omitReservedQueryParams = (queryString: string) => {\n return queryString\n .replace(/^\\?/, \"\")\n .split(\"&\")\n .filter((param) => !isReservedQueryParam(param))\n .join(\"&\");\n};\n\nconst joinQueryStrings = (...queryStrings: string[]) => {\n const joined = queryStrings\n .map((queryString) => queryString.replace(/^\\?/, \"\"))\n .filter(Boolean)\n .join(\"&\");\n\n return joined ? `?${joined}` : \"\";\n};\n\n/**\n * Url and body of the request in the GraphQL over HTTP format.\n * With `persisted`, the `persistedQuery` extension is sent, and the query only when `withQuery` is set.\n */\nexport const getRequestValues = <R extends RequestInstance>(\n request: R,\n queryParams: unknown = request.client.adapter.unstable_queryParamsMapper(request.queryParams),\n persisted?: { persistedQuery: GraphqlPersistedQueryType; withQuery: boolean },\n) => {\n const isPostRequest = request.method === HttpMethods.POST;\n\n const document = getGqlDocument(request);\n const query = !persisted || persisted.withQuery ? gqlEndpointMapper(document) : undefined;\n const operationName = getGqlOperationName(document);\n const variables = request.payload;\n const extensions = persisted ? { persistedQuery: persisted.persistedQuery } : undefined;\n\n const url = hasDocumentOption(request) ? `${request.client.url}${request.endpoint}` : request.client.url;\n // Mappers can return anything, so we normalize their result to the query string\n const queryString = stringifyQueryParams(queryParams as QueryParamsType | string | EmptyTypes);\n\n const fullUrl = isPostRequest\n ? url + joinQueryStrings(queryString)\n : url +\n joinQueryStrings(\n stringifyQueryParams({ query, operationName, variables, extensions }),\n omitReservedQueryParams(queryString),\n );\n\n const payload = isPostRequest\n ? JSON.stringify({\n query,\n operationName,\n variables,\n extensions,\n })\n : null;\n\n return { fullUrl, payload };\n};\n\nexport const gqlEndpointMapper = <E extends GraphQlEndpointType>(endpoint: E): string => {\n if (typeof endpoint === \"string\") {\n return endpoint;\n }\n return print(endpoint);\n};\n\nconst findOperation = (ast: DocumentNode) => {\n return ast.definitions.find((def): def is OperationDefinitionNode => def.kind === \"OperationDefinition\");\n};\n\nconst parseDocument = (document: GraphQlEndpointType): DocumentNode | undefined => {\n if (typeof document !== \"string\") {\n return document;\n }\n try {\n return parse(document);\n } catch {\n // The server reports an invalid document, the name and the operationName are only a best effort\n return undefined;\n }\n};\n\n/**\n * Name of the first operation of the document, sent as `operationName`.\n * Anonymous operations and documents that do not parse have none.\n */\nexport const getGqlOperationName = (document: GraphQlEndpointType): string | undefined => {\n const ast = parseDocument(document);\n\n return ast ? findOperation(ast)?.name?.value : undefined;\n};\n\nconst getOperationLabel = (ast: DocumentNode): string | undefined => {\n const operationDefinition = findOperation(ast);\n\n if (operationDefinition) {\n if (operationDefinition.name?.value) {\n return operationDefinition.name.value;\n }\n\n const selection = operationDefinition.selectionSet.selections[0];\n if (selection?.kind === \"Field\") {\n return selection.name.value;\n }\n if (selection?.kind === \"InlineFragment\" && selection.typeCondition) {\n return selection.typeCondition.name.value;\n }\n }\n\n return undefined;\n};\n\n/** Readable name of the document - the operation name or, for anonymous operations, the first selected field */\nexport const gqlEndpointNameMapper = (endpoint: GraphQlEndpointType): string => {\n const ast = parseDocument(endpoint);\n const name = ast ? getOperationLabel(ast) : undefined;\n\n if (name) {\n return name;\n }\n\n if (typeof endpoint !== \"string\") {\n return \"graphql-request\";\n }\n\n // Fallback for invalid gql queries or something else\n const clearedQuery = endpoint\n .replace(/(query|mutation|subscription)/, \"\")\n .replaceAll(/[{}().,:]/g, \" \")\n .trim();\n const [fallbackName] = clearedQuery.split(\" \");\n\n return fallbackName || \"graphql-request\";\n};\n\n/** FNV-1a - a short and stable fingerprint of a text */\nconst hashText = (text: string): string => {\n let hash = 2_166_136_261; // FNV offset basis\n for (let index = 0; index < text.length; index += 1) {\n // Code units, not code points - the loop walks every UTF-16 unit once\n // eslint-disable-next-line unicorn/prefer-code-point\n hash ^= text.charCodeAt(index);\n hash = Math.imul(hash, 16_777_619); // FNV prime\n }\n // `>>> 0` reads the 32 bits as unsigned, `Math.trunc` would keep the sign\n // eslint-disable-next-line unicorn/prefer-math-trunc\n return (hash >>> 0).toString(36);\n};\n\n/** Printing a DocumentNode is the costly part, and gql documents are created once, so their fingerprint is kept */\nconst documentNodeHashes = new WeakMap<DocumentNode, string>();\n\n/** Fingerprint of the document text sent as `query`. Documents with other selections get other fingerprints. */\nconst getDocumentHash = (document: GraphQlEndpointType): string => {\n if (typeof document === \"string\") {\n return hashText(document);\n }\n\n const known = documentNodeHashes.get(document);\n if (known) {\n return known;\n }\n\n const hash = hashText(print(document));\n documentNodeHashes.set(document, hash);\n return hash;\n};\n\n/**\n * Name identifying the request in the cache, query and abort keys.\n * With the `document` option the same operation can be sent to many paths, so the path is a part of the name.\n */\nexport const gqlRequestNameMapper = (request: RequestInstance): string => {\n const name = gqlEndpointNameMapper(getGqlDocument(request));\n\n return hasDocumentOption(request) ? `${name}${request.requestOptions.endpoint}` : name;\n};\n\n/**\n * Cache and query key of a request. The document fingerprint and the variables are a part of it: two documents with\n * one operation name but other selections, or the same operation with other variables, are other queries - with their\n * own cached data and their own place in the queue.\n */\nexport const gqlRequestKeyMapper = (request: RequestInstance): string => {\n const name = `${gqlRequestNameMapper(request)}@${getDocumentHash(getGqlDocument(request))}`;\n const key = `${request.method}_${name}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n const variables = stringifyKey(request.payload);\n\n return variables ? `${key}-${variables}` : key;\n};\n\nconst escapeRegExp = (text: string) => text.replaceAll(/[$()*+.?[\\\\\\]^{|}]/g, String.raw`\\$&`);\n\n/**\n * Matches the cache keys of every request of a GraphQL operation - with any variables, params, query params and\n * method. Pass it to `client.cache.invalidate()` after a mutation, so the active queries of the operation refetch, like\n * `refetchQueries` in Apollo.\n *\n * - A document matches its requests on every url path of the `document` option.\n * - A request matches the requests of its document on its own url path.\n * - Documents with the same operation name but other selections are other operations, they do not match.\n *\n * @example\n * ```ts\n * await updateUser.send({ payload: { id: \"1\", name: \"Ann\" } });\n * client.cache.invalidate(matchGqlOperation(GetUserDocument));\n * ```\n */\nexport const matchGqlOperation = (operation: GraphQlEndpointType | RequestInstance): RegExp => {\n if (operation instanceof Request) {\n const name = escapeRegExp(gqlRequestNameMapper(operation));\n return new RegExp(`^[A-Z]+_${name}@${getDocumentHash(getGqlDocument(operation))}-`);\n }\n\n const name = escapeRegExp(gqlEndpointNameMapper(operation));\n // The path of the `document` option follows the name and never holds the fingerprint separator\n return new RegExp(`^[A-Z]+_${name}(?:/[^@]*)?@${getDocumentHash(operation)}-`);\n};\n\n/**\n * SHA-256 hash of the query for automatic persisted queries, as lowercase hex.\n * `null` when the runtime has no working Web Crypto - the full query is sent then.\n */\nexport const getPersistedQueryHash = async (query: string): Promise<string | null> => {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) {\n return null;\n }\n\n try {\n const digest = await subtle.digest(\"SHA-256\", new TextEncoder().encode(query));\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n } catch {\n // A runtime that refuses the digest is one without working Web Crypto - the full query is sent instead\n return null;\n }\n};\n\n/**\n * How the server answered a hashed request it could not run: it does not know the hash yet (`\"not-found\"`), or it does\n * not support persisted queries (`\"not-supported\"`). `null` for every other response. Servers report it by the message\n * or by the error code.\n */\nexport const getPersistedQueryMiss = (body: unknown): \"not-found\" | \"not-supported\" | null => {\n const errors: unknown[] = Array.isArray((body as { errors?: unknown })?.errors)\n ? (body as { errors: unknown[] }).errors\n : [];\n\n for (const error of errors) {\n const { message, extensions } = (error ?? {}) as { message?: unknown; extensions?: { code?: unknown } };\n if (message === \"PersistedQueryNotSupported\" || extensions?.code === \"PERSISTED_QUERY_NOT_SUPPORTED\") {\n return \"not-supported\";\n }\n if (message === \"PersistedQueryNotFound\" || extensions?.code === \"PERSISTED_QUERY_NOT_FOUND\") {\n return \"not-found\";\n }\n }\n\n return null;\n};\n","import type { DefaultMapperType, QueryParamsType } from \"@hyper-fetch/core\";\nimport { parseResponse, getErrorMessage, Adapter, stringifyQueryParams } from \"@hyper-fetch/core\";\n\nimport { gqlExtra, defaultTimeout, gqlAcceptHeader } from \"./adapter.constants\";\nimport type {\n GraphqlAdapterType,\n GraphQlExtraType,\n GraphQlEndpointType,\n FetchGraphqlAdapterOptionsType,\n GraphqlRequestOptionsType,\n} from \"./adapter.types\";\nimport { GraphqlMethod } from \"./adapter.types\";\nimport {\n getGqlDocument,\n getGqlHeaders,\n getPersistedQueryHash,\n getPersistedQueryMiss,\n getRequestValues,\n gqlEndpointMapper,\n gqlEndpointNameMapper,\n gqlRequestKeyMapper,\n gqlRequestNameMapper,\n} from \"./adapter.utils\";\n\nexport const getGqlAdapter = (): GraphqlAdapterType => {\n // Turned off for this adapter once the server reports that it does not support persisted queries\n let persistedQueriesSupported = true;\n\n return new Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n QueryParamsType | string | undefined,\n GraphQlEndpointType,\n DefaultMapperType,\n DefaultMapperType,\n DefaultMapperType,\n DefaultMapperType,\n GraphqlRequestOptionsType\n >({\n name: \"graphql\",\n defaultMethod: GraphqlMethod.POST,\n defaultExtra: gqlExtra,\n systemErrorStatus: 0,\n systemErrorExtra: gqlExtra,\n })\n .onInitialize(({ client }) => {\n client.setCacheKeyMapper(gqlRequestKeyMapper);\n client.setQueryKeyMapper(gqlRequestKeyMapper);\n client.setAbortKeyMapper((request) => {\n return `${request.method}_${gqlRequestNameMapper(request)}-${request.cancelable}`;\n });\n })\n .setInternalErrorMapping((error) => [error])\n .setDevtoolsEndpointGetter((endpoint, requestOptions) =>\n gqlEndpointNameMapper(requestOptions?.document ?? endpoint),\n )\n .setEndpointMapper(gqlEndpointMapper)\n .setHeaderMapper(getGqlHeaders)\n .setQueryParamsMapper(stringifyQueryParams)\n .setFetcher(\n async ({\n request,\n queryParams,\n adapterOptions,\n headers,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n getAbortController,\n onResponseProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onSuccess,\n }) => {\n const controller = getAbortController();\n const {\n timeout: timeoutMs = defaultTimeout,\n errorPolicy = \"none\",\n persistedQueries = false,\n ...restOptions\n } = adapterOptions || {};\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const unmountListener = createAbortListener({\n status: 0,\n extra: gqlExtra,\n });\n\n // One timeout for the whole operation - a persisted query miss and the request that registers it\n if (timeoutMs > 0 && controller) {\n timeoutId = setTimeout(() => {\n timedOut = true;\n unmountListener();\n controller.abort();\n }, timeoutMs);\n }\n\n // The hashed request goes first. Without Web Crypto the hash is null and the full query is sent.\n const sha256Hash =\n persistedQueries && persistedQueriesSupported\n ? await getPersistedQueryHash(gqlEndpointMapper(getGqlDocument(request)))\n : null;\n const persistedQuery = sha256Hash ? ({ version: 1, sha256Hash } as const) : null;\n const firstValues = getRequestValues(\n request,\n queryParams,\n persistedQuery ? { persistedQuery, withQuery: false } : undefined,\n );\n const total = firstValues.payload ? new Blob([firstValues.payload]).size : 0;\n\n onBeforeRequest();\n onRequestStart(total ? { total, loaded: 0 } : undefined);\n\n try {\n const requestHeaders = headers as Record<string, string>;\n const hasAcceptHeader = Object.keys(requestHeaders).some((key) => key.toLowerCase() === \"accept\");\n const init: RequestInit = {\n method: request.method,\n headers: hasAcceptHeader ? requestHeaders : { Accept: gqlAcceptHeader, ...requestHeaders },\n signal: controller?.signal,\n ...restOptions,\n };\n\n const sendAttempt = (values: { fullUrl: string; payload: string | null }) => {\n return fetch(values.fullUrl, values.payload ? { ...init, body: values.payload } : init);\n };\n\n const clearTimer = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n };\n\n /** Reads the body. Without `reportProgress` it reports the whole body at once, after reading it. */\n const readBody = async (response: Response, reportProgress: boolean) => {\n if (!response.body || typeof response.body.getReader !== \"function\") {\n return response.text();\n }\n\n const reader = response.body.getReader();\n const contentLength = parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n let receivedLength = 0;\n const chunks: Uint8Array[] = [];\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n chunks.push(value);\n receivedLength += value.length;\n if (reportProgress) {\n onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);\n }\n }\n\n if (!reportProgress) {\n onResponseProgress({ total: receivedLength, loaded: receivedLength } as ProgressEvent);\n }\n\n const allChunks = new Uint8Array(receivedLength);\n let position = 0;\n // eslint-disable-next-line no-restricted-syntax\n for (const chunk of chunks) {\n allChunks.set(chunk, position);\n position += chunk.length;\n }\n return new TextDecoder().decode(allChunks);\n };\n\n let response = await sendAttempt(firstValues);\n // Fetch has no upload events. The response is the first sign that the whole body was sent.\n onRequestEnd();\n // The timeout covers the time to the response headers. A hashed request can still be a miss, so it waits.\n if (!persistedQuery) {\n clearTimer();\n }\n onResponseStart();\n\n // A hashed request can be a miss, so its body is reported only once it is known to be the answer\n let body = await readBody(response, !persistedQuery);\n\n const miss = persistedQuery ? getPersistedQueryMiss(parseResponse(body)) : null;\n if (persistedQuery && miss) {\n if (miss === \"not-supported\") {\n persistedQueriesSupported = false;\n }\n const persisted = miss === \"not-found\" ? { persistedQuery, withQuery: true } : undefined;\n response = await sendAttempt(getRequestValues(request, queryParams, persisted));\n clearTimer();\n body = await readBody(response, true);\n } else {\n clearTimer();\n }\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n onResponseEnd();\n unmountListener();\n\n const { status } = response;\n const parsed = parseResponse(body);\n const data = parsed?.data ?? null;\n // An empty `errors` list is not a failure\n const errors = Array.isArray(parsed?.errors) && parsed.errors.length === 0 ? null : parsed?.errors || null;\n const extensions = parsed?.extensions || {};\n const extra = errors\n ? { headers: responseHeaders, extensions, errors }\n : { headers: responseHeaders, extensions };\n const failedStatus = status > 399 || status === 0;\n const keepsPartialData = errorPolicy === \"all\" && data !== null;\n const failure = failedStatus || (errors && !keepsPartialData);\n\n if (failure) {\n const error = errors || [getErrorMessage()];\n onError({ error, status, extra });\n } else {\n onSuccess({ data, status, extra });\n }\n } catch (error: any) {\n if (timeoutId) clearTimeout(timeoutId);\n unmountListener();\n\n if (controller?.signal?.aborted) {\n if (timedOut) {\n onTimeoutError({ status: 0, extra: gqlExtra });\n }\n return;\n }\n\n // Errors are always a list, like the GraphQL `errors` and the abort and timeout errors\n onError({ error: [error], status: 0, extra: gqlExtra });\n }\n },\n );\n};\n","import type { GraphqlAdapterType } from \"./adapter.types\";\nimport { getGqlAdapter } from \"./http-adapter.fetch\";\n\nexport const GraphqlAdapter = (): GraphqlAdapterType => {\n return getGqlAdapter();\n};\n","import { Time } from \"@hyper-fetch/core\";\n\n/** Subprotocol of GraphQL over WebSocket, the protocol of `graphql-ws` */\nexport const GRAPHQL_TRANSPORT_WS_PROTOCOL = \"graphql-transport-ws\";\n\n/** Message types of the `graphql-transport-ws` protocol */\nexport const GraphqlWsMessageType = {\n CONNECTION_INIT: \"connection_init\",\n CONNECTION_ACK: \"connection_ack\",\n PING: \"ping\",\n PONG: \"pong\",\n SUBSCRIBE: \"subscribe\",\n NEXT: \"next\",\n ERROR: \"error\",\n COMPLETE: \"complete\",\n} as const;\n\n/** Close codes of the `graphql-transport-ws` protocol */\nexport const GraphqlWsCloseCode = {\n INTERNAL_SERVER_ERROR: 4500,\n INTERNAL_CLIENT_ERROR: 4005,\n BAD_REQUEST: 4400,\n BAD_RESPONSE: 4004,\n UNAUTHORIZED: 4401,\n FORBIDDEN: 4403,\n SUBPROTOCOL_NOT_ACCEPTABLE: 4406,\n CONNECTION_INITIALISATION_TIMEOUT: 4408,\n CONNECTION_ACKNOWLEDGEMENT_TIMEOUT: 4504,\n SUBSCRIBER_ALREADY_EXISTS: 4409,\n TOO_MANY_INITIALISATION_REQUESTS: 4429,\n} as const;\n\n/**\n * Close codes that a retry can't fix - the same ones the `graphql-ws` client gives up on. Forbidden (4403) and the\n * timeouts (4408, 4504) are retried, as access may be granted and the server may answer in time on the next attempt.\n */\nexport const fatalGraphqlWsCloseCodes: ReadonlySet<number> = new Set([\n GraphqlWsCloseCode.INTERNAL_SERVER_ERROR,\n GraphqlWsCloseCode.INTERNAL_CLIENT_ERROR,\n GraphqlWsCloseCode.BAD_REQUEST,\n GraphqlWsCloseCode.BAD_RESPONSE,\n GraphqlWsCloseCode.UNAUTHORIZED,\n GraphqlWsCloseCode.SUBPROTOCOL_NOT_ACCEPTABLE,\n GraphqlWsCloseCode.SUBSCRIBER_ALREADY_EXISTS,\n GraphqlWsCloseCode.TOO_MANY_INITIALISATION_REQUESTS,\n]);\n\n/**\n * Close codes of the WebSocket standard (1001-1999) that a retry can fix: going away, no status, abnormal closure,\n * service restart, try again later and bad gateway. The other ones report a broken client or server, e.g. 1002\n * (protocol error) or 1003 (unsupported data). A normal closure (1000) stays closed, as with every socket adapter.\n */\nexport const retriedStandardCloseCodes: ReadonlySet<number> = new Set([1001, 1005, 1006, 1012, 1013, 1014]);\n\n/** Defaults of the keep-alive */\nexport const defaultKeepAlive = {\n intervalMs: Time.SEC * 10,\n pongTimeoutMs: Time.SEC * 5,\n};\n","import type { ShouldReconnectType } from \"@hyper-fetch/sockets\";\nimport { defaultShouldReconnect } from \"@hyper-fetch/sockets\";\nimport type { GraphQLFormattedError } from \"graphql\";\n\nimport { GraphqlWsMessageType, fatalGraphqlWsCloseCodes, retriedStandardCloseCodes } from \"./socket.constants\";\nimport type { GraphqlSubscriptionErrorOptionsType } from \"./socket.types\";\n\n/** The object check of the `graphql-ws` client, so both accept the same messages */\nexport const isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === \"object\" && value !== null;\n};\n\nexport const toError = (value: unknown): Error => {\n return value instanceof Error ? value : new Error(String(value));\n};\n\n/** A message the server may send - every other one breaks the protocol */\nexport type GraphqlWsServerMessageType =\n | { type: typeof GraphqlWsMessageType.CONNECTION_ACK; payload?: Record<string, unknown> | null }\n | { type: typeof GraphqlWsMessageType.PING; payload?: Record<string, unknown> | null }\n | { type: typeof GraphqlWsMessageType.PONG; payload?: Record<string, unknown> | null }\n | { type: typeof GraphqlWsMessageType.NEXT; id: string; payload: Record<string, unknown> }\n | { type: typeof GraphqlWsMessageType.ERROR; id: string; payload: GraphQLFormattedError[] }\n | { type: typeof GraphqlWsMessageType.COMPLETE; id: string };\n\nconst isFormattedErrors = (value: unknown): value is GraphQLFormattedError[] => {\n return Array.isArray(value) && value.length > 0 && value.every((error) => isRecord(error) && \"message\" in error);\n};\n\nconst hasId = (message: Record<string, unknown>): message is Record<string, unknown> & { id: string } => {\n return typeof message.id === \"string\" && message.id.length > 0;\n};\n\n/**\n * Reads a frame of the server. Throws when it breaks the protocol - the same checks the `graphql-ws` client makes, so\n * a server that works with it works with the adapter.\n */\nexport const parseServerMessage = (data: unknown): GraphqlWsServerMessageType => {\n if (typeof data !== \"string\") {\n throw new TypeError(\"Expected a text frame\");\n }\n const message: unknown = JSON.parse(data);\n if (!isRecord(message) || typeof message.type !== \"string\") {\n throw new TypeError(\"Expected a message object with a string 'type'\");\n }\n\n switch (message.type) {\n case GraphqlWsMessageType.CONNECTION_ACK:\n case GraphqlWsMessageType.PING:\n case GraphqlWsMessageType.PONG: {\n if (message.payload !== undefined && message.payload !== null && !isRecord(message.payload)) {\n throw new TypeError(`\"${message.type}\" expects the payload to be an object or nullish`);\n }\n return message as GraphqlWsServerMessageType;\n }\n case GraphqlWsMessageType.NEXT: {\n if (!hasId(message) || !isRecord(message.payload)) {\n throw new TypeError(`\"next\" expects a non-empty string 'id' and an object payload`);\n }\n return message as GraphqlWsServerMessageType;\n }\n case GraphqlWsMessageType.ERROR: {\n if (!hasId(message) || !isFormattedErrors(message.payload)) {\n throw new TypeError(`\"error\" expects a non-empty string 'id' and an array of GraphQL errors as the payload`);\n }\n return message as GraphqlWsServerMessageType;\n }\n case GraphqlWsMessageType.COMPLETE: {\n if (!hasId(message)) {\n throw new TypeError(`\"complete\" expects a non-empty string 'id'`);\n }\n return message as GraphqlWsServerMessageType;\n }\n default: {\n throw new TypeError(`Unexpected message type \"${message.type}\"`);\n }\n }\n};\n\n/** Reported to `onError` when the server breaks the protocol - the connection is closed with 4004 */\nexport const getBadResponseError = (cause: unknown): Error => {\n return new Error(\"Received a malformed GraphQL over WebSocket message\", { cause });\n};\n\n/**\n * The close reason may hold at most 123 bytes. Longer reasons are cut by the `graphql-ws` client the same way:\n * replaced with a short generic one.\n */\nexport const limitCloseReason = (reason: string, fallback: string) => {\n return new TextEncoder().encode(reason).byteLength <= 123 ? reason : fallback;\n};\n\n/**\n * The default `shouldReconnect` of the GraphQL WebSocket adapter. It gives up on the close codes a retry can't fix -\n * bad requests, unauthorized, a missing subprotocol, protocol errors and the like, the same ones the `graphql-ws` client\n * gives up on - and on a normal closure (1000), as every socket adapter does. Everything else is retried. The socket's\n * own `shouldReconnect` replaces it, so call this one from yours to keep these rules.\n *\n * @example\n * const socket = new Socket({\n * url,\n * adapter: GraphqlWsAdapter(),\n * // Retry after a normal closure too\n * shouldReconnect: (loss) => loss.code === 1000 || shouldReconnectGraphqlWs(loss),\n * });\n */\nexport const shouldReconnectGraphqlWs: ShouldReconnectType = (loss) => {\n const { code } = loss;\n if (code === undefined) {\n return true;\n }\n if (fatalGraphqlWsCloseCodes.has(code)) {\n return false;\n }\n if (code > 1000 && code <= 1999 && !retriedStandardCloseCodes.has(code)) {\n return false;\n }\n return defaultShouldReconnect(loss);\n};\n\n/**\n * Error of a GraphQL subscription, reported to the `socket.onError` callbacks and to the `onEnd` of its listeners.\n * The server ended the subscription with the `error` message - its validation or its source failed. `errors` holds what\n * it sent.\n *\n * Errors of a single event do not end the subscription and come with the event in `extra.errors`.\n *\n * @example\n * socket.onError(({ error }) => {\n * if (error instanceof GraphqlSubscriptionError && error.errors[0].extensions?.code === \"UNAUTHENTICATED\") {\n * logout();\n * }\n * });\n */\nexport class GraphqlSubscriptionError extends Error {\n /** Errors sent by the server with the `error` message */\n readonly errors: GraphQLFormattedError[];\n /** Topic of the failed subscription */\n readonly topic: string;\n /** Variables of the failed subscription */\n readonly payload: unknown;\n\n constructor({ errors, topic, payload }: GraphqlSubscriptionErrorOptionsType) {\n super(errors.map((error) => error.message).join(\"\\n\"));\n this.name = \"GraphqlSubscriptionError\";\n this.errors = errors;\n this.topic = topic;\n this.payload = payload;\n }\n}\n","import type { ListenerCallbackType, SocketAdapterInstance } from \"@hyper-fetch/sockets\";\nimport type { GraphQLFormattedError } from \"graphql\";\n\nimport { getGqlOperationName, gqlEndpointMapper } from \"../adapter/adapter.utils\";\nimport type { GraphqlWsExtraType, GraphqlWsListenerOptionsType } from \"./socket.types\";\nimport { toError } from \"./socket.utils\";\n\ntype CallbackType = ListenerCallbackType<SocketAdapterInstance, any>;\n\n/** One server subscription: a document with one set of variables, shared by every callback listening to it */\nexport type GraphqlSubscriptionType = {\n /** Topic, document and encoded variables - one server subscription per key */\n key: string;\n topic: string;\n /** Printed document, sent as `query` */\n query: string;\n operationName: string | undefined;\n /** Variables as the listener has them, sent with the subscription and passed to the callbacks in `extra` */\n payload: unknown;\n callbacks: Set<CallbackType>;\n /** The subscription was sent over the current acknowledged connection */\n started: boolean;\n};\n\n/** What the subscriptions need from the listener - the topic, the document and the variables */\ntype GraphqlListenerType = { topic: string; payload?: unknown; options?: GraphqlWsListenerOptionsType };\n\n/** The adapter bindings used by the subscriptions */\ntype GraphqlBindingsType = {\n onListen: (options: {\n listener: GraphqlListenerType;\n callback: CallbackType;\n onUnmount?: VoidFunction;\n }) => () => void;\n onEvent: (options: {\n topic: string;\n data: unknown;\n extra: GraphqlWsExtraType;\n callbacks?: ReadonlySet<CallbackType>;\n }) => void;\n onError: (options: { error: Error }) => void;\n onListenerStart: (options: { topic: string; callbacks: ReadonlySet<CallbackType> }) => void;\n onListenerEnd: (options: { topic: string; callbacks: ReadonlySet<CallbackType>; error: Error | null }) => void;\n};\n\n/**\n * Keeps one server subscription per topic, document and variables. Callbacks with the same ones share it, the first\n * one starts it and the last one to leave stops it. The adapter only moves the subscriptions over its transport.\n */\nexport const createGraphqlSubscriptions = ({\n bindings: { onListen, onEvent, onError, onListenerStart, onListenerEnd },\n onStart,\n onStop,\n}: {\n bindings: GraphqlBindingsType;\n /** The first callback joined - start the subscription when the connection is acknowledged */\n onStart: (subscription: GraphqlSubscriptionType) => void;\n /** The last callback left - stop the subscription on the server */\n onStop: (subscription: GraphqlSubscriptionType) => void;\n}) => {\n const subscriptions = new Map<string, GraphqlSubscriptionType>();\n\n const leave = (subscription: GraphqlSubscriptionType, callback: CallbackType) => {\n if (!subscription.callbacks.delete(callback) || subscription.callbacks.size > 0) {\n return;\n }\n // A subscription ended by the server is not running anymore - its listeners leave on their own, nothing to stop\n if (subscriptions.get(subscription.key) === subscription) {\n subscriptions.delete(subscription.key);\n onStop(subscription);\n }\n };\n\n const listen = (listener: GraphqlListenerType, callback: CallbackType) => {\n const document = listener.options?.document ?? listener.topic;\n let query: string;\n let key: string;\n try {\n query = gqlEndpointMapper(document);\n // `undefined` variables are not sent - the subscription has none\n key = `${listener.topic}\\n${query}\\n${JSON.stringify(listener.payload) ?? \"\"}`;\n } catch (error) {\n // Nothing can be sent to the server - the callback is registered, so unsubscribing still works\n onError({ error: toError(error) });\n return onListen({ listener, callback });\n }\n\n const existing = subscriptions.get(key);\n const subscription: GraphqlSubscriptionType = existing ?? {\n key,\n topic: listener.topic,\n query,\n operationName: getGqlOperationName(document),\n payload: listener.payload,\n callbacks: new Set(),\n started: false,\n };\n subscription.callbacks.add(callback);\n\n const removeListener = onListen({ listener, callback, onUnmount: () => leave(subscription, callback) });\n\n if (!existing) {\n subscriptions.set(key, subscription);\n onStart(subscription);\n } else if (existing.started) {\n // Joined a subscription that is running already - only this callback has to hear about it\n onListenerStart({ topic: subscription.topic, callbacks: new Set([callback]) });\n }\n\n return removeListener;\n };\n\n /** Delivers an event to the callbacks of the subscription only */\n const deliver = (\n subscription: GraphqlSubscriptionType,\n { data, errors, extensions }: { data: unknown; errors: GraphQLFormattedError[] | undefined; extensions: unknown },\n ) => {\n const extra: GraphqlWsExtraType = {\n errors,\n extensions: (extensions as Record<string, unknown> | undefined) ?? {},\n payload: subscription.payload,\n };\n try {\n onEvent({ topic: subscription.topic, data, extra, callbacks: subscription.callbacks });\n } catch (error) {\n // A throwing callback must not break the transport, the other callbacks got the event already\n onError({ error: toError(error) });\n }\n };\n\n /** The subscription was sent over an acknowledged connection - after the first start and after every restart */\n const confirm = (subscription: GraphqlSubscriptionType) => {\n // eslint-disable-next-line no-param-reassign\n subscription.started = true;\n onListenerStart({ topic: subscription.topic, callbacks: subscription.callbacks });\n };\n\n /** The connection of the subscription dropped - it has to be sent again */\n const unconfirm = (subscription: GraphqlSubscriptionType) => {\n // eslint-disable-next-line no-param-reassign\n subscription.started = false;\n };\n\n /**\n * The server ended the subscription - it completed (`error: null`) or failed. Its listeners deliver what is pending\n * and unsubscribe, and a later `listen()` with the same variables starts a new subscription from scratch.\n */\n const end = (subscription: GraphqlSubscriptionType, error: Error | null) => {\n // Only running subscriptions can be ended, and a running one is always the subscription of its key.\n // It is removed first, so the listeners leaving below don't stop it again.\n subscriptions.delete(subscription.key);\n unconfirm(subscription);\n onListenerEnd({ topic: subscription.topic, callbacks: subscription.callbacks, error });\n };\n\n /** Subscriptions with at least one callback, the ones to start when the connection is acknowledged */\n const getAll = () => [...subscriptions.values()];\n\n return { listen, deliver, confirm, unconfirm, end, getAll };\n};\n","/* eslint-disable @typescript-eslint/no-use-before-define */\nimport type { EmptyTypes, QueryParamsType } from \"@hyper-fetch/core\";\nimport { stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { ConnectionAttemptType, ConnectionLossType } from \"@hyper-fetch/sockets\";\nimport {\n SocketAdapter,\n WebsocketReadyState,\n createReconnectingConnection,\n getSocketError,\n getSocketUrl,\n getWebsocketConstructor,\n} from \"@hyper-fetch/sockets\";\n\nimport {\n GRAPHQL_TRANSPORT_WS_PROTOCOL,\n GraphqlWsCloseCode,\n GraphqlWsMessageType,\n defaultKeepAlive,\n} from \"./socket.constants\";\nimport type { GraphqlSubscriptionType } from \"./socket.subscriptions\";\nimport { createGraphqlSubscriptions } from \"./socket.subscriptions\";\nimport type {\n GraphqlWsAdapterOptionsType,\n GraphqlWsAdapterType,\n GraphqlWsExtraType,\n GraphqlWsListenerOptionsType,\n} from \"./socket.types\";\nimport type { GraphqlWsServerMessageType } from \"./socket.utils\";\nimport {\n GraphqlSubscriptionError,\n getBadResponseError,\n limitCloseReason,\n parseServerMessage,\n shouldReconnectGraphqlWs,\n toError,\n} from \"./socket.utils\";\n\n/** A close the client starts because of the protocol - sent to the server with its code */\ntype ProtocolCloseType = { code: number; reason: string };\n\ntype CloseEventLikeType = Pick<CloseEvent, \"code\"> & Partial<Pick<CloseEvent, \"reason\">> & Event;\n\n/** Explains a lost connection - the protocol codes (4000+) carry the server's reason */\nconst getCloseError = (event: CloseEventLikeType) => {\n if (event.code >= 4000) {\n return new Error(`The server closed the connection with ${event.code}: ${event.reason || \"no reason given\"}`);\n }\n return new Error(getSocketError(event));\n};\n\n/**\n * Socket adapter for GraphQL subscriptions over WebSocket. It speaks `graphql-transport-ws`, the protocol of the\n * `graphql-ws` library - supported by Apollo Server, GraphQL Yoga, Mercurius, Hot Chocolate, Hasura and most others.\n *\n * - The connection counts as open once the server acknowledged `connection_init`, so the socket's\n * `connectionTimeout` covers the whole handshake. `connectionParams` are sent with it, a function runs on every\n * connection attempt.\n * - Every document with one set of variables is one server subscription, shared by the listeners with those\n * variables. Subscriptions started before the connection is acknowledged wait for it, and after a reconnect they are\n * sent again.\n * - The server's `ping` is answered, and `keepAlive` pings a quiet connection to notice when it died.\n * - Reconnecting follows the socket's reconnection options. Close codes a retry can't fix (4400, 4401, 4409...) stop\n * it - see {@link shouldReconnectGraphqlWs}.\n * - With `lazy`, the connection is open only while there are subscriptions.\n *\n * Queries and mutations are sent with the `GraphqlAdapter` - `emit` throws.\n *\n * @example\n * const socket = new Socket({\n * url: \"ws://localhost:4000/graphql\",\n * adapter: GraphqlWsAdapter(),\n * adapterOptions: { connectionParams: () => ({ token: getToken() }) },\n * });\n *\n * const onMessage = socket.createListener()({ topic: \"OnMessage\", options: { document: OnMessageDocument } });\n * onMessage.listen(({ data, extra }) => {}, { payload: { room: \"general\" } });\n */\nexport const GraphqlWsAdapter = (): GraphqlWsAdapterType =>\n new SocketAdapter<\n GraphqlWsExtraType,\n GraphqlWsAdapterOptionsType,\n GraphqlWsListenerOptionsType,\n undefined,\n QueryParamsType | string,\n typeof stringifyQueryParams\n >({\n name: \"graphql-ws\",\n // A subscription counts as started once it was sent over an acknowledged connection - the protocol has no\n // confirmation of its own, and before the acknowledgement nothing can be sent\n confirmsSubscriptions: true,\n })\n .setQueryParamsMapper(stringifyQueryParams)\n .setConnector((bindings) => {\n const { adapter, getQueryParams, onConnectFailed, onError } = bindings;\n\n // The transport of the current attempt - `undefined` once it is detached\n let websocket: WebSocket | undefined;\n // The server acknowledged the current transport - only then subscriptions can be sent\n let acknowledged = false;\n // Options of the current connection attempt (after onConnect interceptors)\n let options: GraphqlWsAdapterOptionsType | EmptyTypes = adapter.adapterOptions;\n // Ends the current attempt - the keep-alive and the protocol checks use it\n let loseCurrent: ((loss: ConnectionLossType) => void) | undefined;\n // The code to close the current transport with, when the client ends it because of the protocol\n let protocolClose: ProtocolCloseType | undefined;\n\n let pingTimer: ReturnType<typeof setTimeout> | undefined;\n let pongTimer: ReturnType<typeof setTimeout> | undefined;\n let lazyCloseTimer: ReturnType<typeof setTimeout> | undefined;\n // With `lazy`, the connection is closed because no subscription needs it - the next subscription opens it\n let lazyIdle = true;\n\n // Ids are never reused, so a late message of a stopped subscription can't reach a new one\n let lastId = 0;\n // Subscriptions running on the current connection, by their id\n const running = new Map<string, GraphqlSubscriptionType>();\n const ids = new Map<GraphqlSubscriptionType, string>();\n\n const subscriptions = createGraphqlSubscriptions({\n bindings,\n onStart: (subscription) => startSubscription(subscription),\n onStop: (subscription) => stopSubscription(subscription),\n });\n\n const isLazy = () => !!adapter.adapterOptions?.lazy;\n\n /** Sends a message. Returns the error instead of throwing, so callers decide how to report it. */\n const send = (message: Record<string, unknown>): Error | null => {\n try {\n // Messages are sent only while there is a transport - a closed one throws and the error is returned\n websocket?.send(JSON.stringify(message));\n return null;\n } catch (error) {\n return toError(error);\n }\n };\n\n const sendOrReport = (message: Record<string, unknown>) => {\n const error = send(message);\n if (error) {\n onError({ error });\n }\n return !error;\n };\n\n /**\n * Ends the current connection because of the protocol, e.g. a malformed message. The transport is closed with\n * the protocol `code`, so the server learns why, and the engine decides about the next attempt with it.\n */\n const failConnection = (\n attempt: ConnectionAttemptType<GraphqlWsAdapterType>,\n close: ProtocolCloseType,\n error: Error,\n ) => {\n protocolClose = close;\n // The socket is reported as disconnected first, then the error that explains why\n attempt.lost({ code: close.code, reason: close.reason, error });\n onError({ error });\n };\n\n /**\n * Lazy connection\n */\n\n const cancelLazyClose = () => {\n clearTimeout(lazyCloseTimer);\n lazyCloseTimer = undefined;\n };\n\n /** With `lazy`, the first subscription opens the connection */\n const connectLazily = () => {\n cancelLazyClose();\n if (!isLazy() || !lazyIdle) {\n return;\n }\n lazyIdle = false;\n connection.connect();\n };\n\n /** With `lazy`, the connection closes once no subscription needs it anymore */\n const closeLazily = () => {\n if (!isLazy() || subscriptions.getAll().length > 0) {\n return;\n }\n cancelLazyClose();\n // Every subscription that starts cancels the timer, so it only fires while there are none\n const close = () => {\n lazyCloseTimer = undefined;\n lazyIdle = true;\n connection.disconnect();\n };\n const timeout = adapter.adapterOptions?.lazyCloseTimeout ?? 0;\n if (timeout > 0) {\n lazyCloseTimer = setTimeout(close, timeout);\n } else {\n close();\n }\n };\n\n /**\n * Subscriptions\n */\n\n const startSubscription = (subscription: GraphqlSubscriptionType) => {\n // Not acknowledged yet - every subscription is sent once the server acknowledges the connection\n if (!websocket || !acknowledged) {\n connectLazily();\n return;\n }\n cancelLazyClose();\n lastId += 1;\n const id = String(lastId);\n const message = {\n id,\n type: GraphqlWsMessageType.SUBSCRIBE,\n payload: {\n query: subscription.query,\n operationName: subscription.operationName,\n variables: subscription.payload,\n },\n };\n if (sendOrReport(message)) {\n running.set(id, subscription);\n ids.set(subscription, id);\n subscriptions.confirm(subscription);\n }\n };\n\n /** The server forgets the subscription - after `complete`, an error or when the connection closes */\n const forget = (subscription: GraphqlSubscriptionType) => {\n const id = ids.get(subscription);\n if (id !== undefined) {\n running.delete(id);\n }\n ids.delete(subscription);\n };\n\n /** The connection is gone, and the server stopped every subscription of it - they are sent again on reconnect */\n const forgetAll = () => {\n running.forEach(subscriptions.unconfirm);\n running.clear();\n ids.clear();\n };\n\n const stopSubscription = (subscription: GraphqlSubscriptionType) => {\n const id = ids.get(subscription);\n forget(subscription);\n if (id !== undefined) {\n sendOrReport({ id, type: GraphqlWsMessageType.COMPLETE });\n }\n closeLazily();\n };\n\n /** The server ended the subscription - with `complete` (`error: null`) or the `error` message */\n const endSubscription = (subscription: GraphqlSubscriptionType, error: Error | null) => {\n forget(subscription);\n if (error) {\n onError({ error });\n }\n subscriptions.end(subscription, error);\n closeLazily();\n };\n\n /**\n * Messages\n */\n\n const onAcknowledged = (attempt: ConnectionAttemptType<GraphqlWsAdapterType>) => {\n acknowledged = true;\n attempt.ready();\n // A connected callback may have closed the connection already\n if (!attempt.isCurrent()) {\n return;\n }\n subscriptions.getAll().forEach(startSubscription);\n onHeartbeat();\n };\n\n const onSubscriptionMessage = (message: Extract<GraphqlWsServerMessageType, { id: string }>) => {\n const subscription = running.get(message.id);\n // Late messages of a subscription stopped by the client\n if (!subscription) {\n return;\n }\n switch (message.type) {\n case GraphqlWsMessageType.NEXT: {\n const { data, errors, extensions } = message.payload;\n subscriptions.deliver(subscription, {\n data: data ?? null,\n errors: Array.isArray(errors) ? errors : undefined,\n extensions,\n });\n return;\n }\n case GraphqlWsMessageType.ERROR: {\n const error = new GraphqlSubscriptionError({\n errors: message.payload,\n topic: subscription.topic,\n payload: subscription.payload,\n });\n endSubscription(subscription, error);\n return;\n }\n default: {\n endSubscription(subscription, null);\n }\n }\n };\n\n const onMessage = (event: MessageEvent, attempt: ConnectionAttemptType<GraphqlWsAdapterType>) => {\n // Any message proves the connection is alive\n onHeartbeat();\n\n let message: GraphqlWsServerMessageType;\n try {\n message = parseServerMessage(event.data);\n } catch (error) {\n const reason = limitCloseReason(toError(error).message, \"Bad response\");\n failConnection(attempt, { code: GraphqlWsCloseCode.BAD_RESPONSE, reason }, getBadResponseError(error));\n return;\n }\n\n switch (message.type) {\n case GraphqlWsMessageType.PING: {\n sendOrReport(\n message.payload\n ? { type: GraphqlWsMessageType.PONG, payload: message.payload }\n : { type: GraphqlWsMessageType.PONG },\n );\n return;\n }\n case GraphqlWsMessageType.PONG: {\n return;\n }\n case GraphqlWsMessageType.CONNECTION_ACK: {\n // A repeated acknowledgement changes nothing\n if (!acknowledged) {\n onAcknowledged(attempt);\n }\n return;\n }\n default: {\n if (!acknowledged) {\n const reason = `First message cannot be of type ${message.type}`;\n failConnection(\n attempt,\n { code: GraphqlWsCloseCode.BAD_RESPONSE, reason },\n getBadResponseError(new Error(reason)),\n );\n return;\n }\n onSubscriptionMessage(message);\n }\n }\n };\n\n /**\n * Connection\n */\n\n /** Sends `connection_init` with the connection params of the attempt */\n const initialize = async (attempt: ConnectionAttemptType<GraphqlWsAdapterType>, transport: WebSocket) => {\n const connectionParams = options?.connectionParams;\n let payload: Record<string, unknown> | undefined;\n try {\n payload = typeof connectionParams === \"function\" ? await connectionParams() : connectionParams;\n } catch (error) {\n if (attempt.isCurrent()) {\n const cause = toError(error);\n const reason = limitCloseReason(cause.message, \"Internal client error\");\n failConnection(\n attempt,\n { code: GraphqlWsCloseCode.INTERNAL_CLIENT_ERROR, reason },\n new Error(\"Could not get the connection params\", { cause }),\n );\n }\n return;\n }\n // The connection may be gone while the params were prepared\n if (!attempt.isCurrent() || transport.readyState !== WebsocketReadyState.OPEN) {\n return;\n }\n sendOrReport(\n payload\n ? { type: GraphqlWsMessageType.CONNECTION_INIT, payload }\n : { type: GraphqlWsMessageType.CONNECTION_INIT },\n );\n };\n\n /** Creates the transport, reporting a failed attempt when the environment or the connection details are invalid */\n const createWebsocket = (url: string) => {\n try {\n const WebsocketConstructor = getWebsocketConstructor(options);\n if (!WebsocketConstructor) {\n onConnectFailed({ error: new Error(\"WebSocket is not available in this environment\") });\n return null;\n }\n return new WebsocketConstructor(url, GRAPHQL_TRANSPORT_WS_PROTOCOL);\n } catch (error) {\n onConnectFailed({ error: toError(error) });\n return null;\n }\n };\n\n /**\n * Closes a detached transport. The server stops every subscription of a closed connection on its own, so they\n * are sent again on the next one. Resolves on the close - or on an error, as a transport that fails while\n * closing may report only `error` (Node.js 22).\n */\n const closeWebsocket = (transport: WebSocket): Promise<void> => {\n // The engine closes an attempt before it opens the next one, so this is always the current transport\n const { code, reason } = protocolClose ?? { code: 1000, reason: \"Normal Closure\" };\n websocket = undefined;\n acknowledged = false;\n loseCurrent = undefined;\n protocolClose = undefined;\n clearTimers();\n forgetAll();\n if (transport.readyState === WebsocketReadyState.CLOSED) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n transport.addEventListener(\"close\", () => resolve(), { once: true });\n transport.addEventListener(\"error\", () => resolve(), { once: true });\n try {\n transport.close(code, reason);\n } catch {\n // Closing a transport that never connected may throw in some runtimes - it is detached already\n resolve();\n }\n });\n };\n\n const connection = createReconnectingConnection({\n bindings,\n // A lazy connection waits for its first subscription\n autoConnect: !adapter.adapterOptions?.lazy && (adapter.adapterOptions?.autoConnect ?? true),\n shouldReconnect: shouldReconnectGraphqlWs,\n open: (attempt) => {\n options = attempt.connection.adapterOptions;\n const url = getSocketUrl(attempt.connection.url, getQueryParams(attempt.connection.queryParams));\n const transport = createWebsocket(url);\n if (!transport) {\n return null;\n }\n websocket = transport;\n acknowledged = false;\n\n // Ignored by the engine once the attempt was replaced\n loseCurrent = attempt.lost;\n\n /** The transport is gone - report it and let the engine decide about the next attempt */\n const onTransportClosed = (event: CloseEventLikeType) => {\n // The socket is reported as disconnected first, then the error that explains why\n attempt.lost({ code: event.code, reason: event.reason || undefined });\n onError({ error: getCloseError(event) });\n };\n\n transport.addEventListener(\"open\", () => {\n if (attempt.isCurrent()) {\n initialize(attempt, transport);\n }\n });\n\n transport.addEventListener(\"close\", (event) => {\n if (attempt.isCurrent()) {\n onTransportClosed(event);\n }\n });\n\n // Node.js 22 reports a failed handshake with `error` only - no `close` follows and the transport stays\n // CONNECTING. Browsers set CLOSED before the error and send the close event, which handles it as usual.\n // Here it is treated as an abnormally closed transport (1006).\n transport.addEventListener(\"error\", () => {\n if (!attempt.isCurrent() || transport.readyState !== WebsocketReadyState.CONNECTING) {\n return;\n }\n onTransportClosed(Object.assign(new Event(\"close\"), { code: 1006 }));\n });\n\n transport.addEventListener(\"message\", (event) => {\n if (attempt.isCurrent()) {\n onMessage(event, attempt);\n }\n });\n\n return { close: () => closeWebsocket(transport) };\n },\n });\n\n /**\n * Keep-alive\n */\n\n const clearTimers = () => {\n clearTimeout(pingTimer);\n clearTimeout(pongTimer);\n };\n\n const onHeartbeat = () => {\n const { enabled = false, ...keepAlive } = options?.keepAlive ?? {};\n const { intervalMs, pongTimeoutMs } = { ...defaultKeepAlive, ...keepAlive };\n\n if (!acknowledged || !enabled) {\n return;\n }\n clearTimers();\n pingTimer = setTimeout(() => {\n sendOrReport({ type: GraphqlWsMessageType.PING });\n pongTimer = setTimeout(() => {\n onHeartbeatTimeout();\n }, pongTimeoutMs);\n }, intervalMs);\n };\n\n /**\n * The server did not answer the ping - the connection is dead. Its closing handshake may never finish, so the\n * engine detaches the transport right away instead of waiting for its `close` event.\n */\n const onHeartbeatTimeout = () => {\n const error = new Error(\"Keep-alive timeout - the server did not answer the ping in time\");\n // The socket is reported as disconnected first, then the error that explains why\n loseCurrent?.({ error });\n onError({ error });\n };\n\n // Subscriptions only - queries and mutations are sent with the GraphqlAdapter. Throwing synchronously makes\n // `emitter.emit()` fail right at the call site, the same way the SSE adapter does it.\n const emit = () => {\n throw new Error(\"Cannot emit events with the GraphQL WebSocket adapter, it supports subscriptions only\");\n };\n\n return {\n connect: () => {\n lazyIdle = false;\n return connection.connect();\n },\n reconnect: () => {\n lazyIdle = false;\n return connection.reconnect();\n },\n disconnect: () => {\n cancelLazyClose();\n return connection.disconnect();\n },\n listen: subscriptions.listen,\n emit,\n // The socket is destroyed or the adapter moves to another socket - stop following the network state\n dispose: () => {\n connection.dispose();\n clearTimers();\n cancelLazyClose();\n },\n };\n });\n"],"mappings":";;;;AAIA,IAAa,iBAAi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,kBAAkB;GAAE,GAAG;GAAkB,GAAG;GAAW;AAE3E,MAAI,CAAC,gBAAgB,CAAC,QACpB;AAEF,eAAa;AACb,cAAY,iBAAiB;AAC3B,gBAAa,EAAE,MAAM,qBAAqB,MAAM,CAAC;AACjD,eAAY,iBAAiB;AAC3B,wBAAoB;MACnB,cAAc;KAChB,WAAW;;;;;;CAOhB,MAAM,2BAA2B;EAC/B,MAAM,wBAAQ,IAAI,MAAM,kEAAkE;AAE1F,gBAAc,EAAE,OAAO,CAAC;AACxB,UAAQ,EAAE,OAAO,CAAC;;CAKpB,MAAM,aAAa;AACjB,QAAM,IAAI,MAAM,wFAAwF;;AAG1G,QAAO;EACL,eAAe;AACb,cAAW;AACX,UAAO,WAAW,SAAS;;EAE7B,iBAAiB;AACf,cAAW;AACX,UAAO,WAAW,WAAW;;EAE/B,kBAAkB;AAChB,oBAAiB;AACjB,UAAO,WAAW,YAAY;;EAEhC,QAAQ,cAAc;EACtB;EAEA,eAAe;AACb,cAAW,SAAS;AACpB,gBAAa;AACb,oBAAiB;;EAEpB;EACD"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export * from './socket.types';
|
|
2
|
+
export * from './socket.websocket';
|
|
3
|
+
export { GRAPHQL_TRANSPORT_WS_PROTOCOL, GraphqlWsCloseCode } from './socket.constants';
|
|
4
|
+
export { GraphqlSubscriptionError, shouldReconnectGraphqlWs } from './socket.utils';
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/socket/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,oBAAoB,CAAC;AACnC,OAAO,EAAE,6BAA6B,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACvF,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Subprotocol of GraphQL over WebSocket, the protocol of `graphql-ws` */
|
|
2
|
+
export declare const GRAPHQL_TRANSPORT_WS_PROTOCOL = "graphql-transport-ws";
|
|
3
|
+
/** Message types of the `graphql-transport-ws` protocol */
|
|
4
|
+
export declare const GraphqlWsMessageType: {
|
|
5
|
+
readonly CONNECTION_INIT: "connection_init";
|
|
6
|
+
readonly CONNECTION_ACK: "connection_ack";
|
|
7
|
+
readonly PING: "ping";
|
|
8
|
+
readonly PONG: "pong";
|
|
9
|
+
readonly SUBSCRIBE: "subscribe";
|
|
10
|
+
readonly NEXT: "next";
|
|
11
|
+
readonly ERROR: "error";
|
|
12
|
+
readonly COMPLETE: "complete";
|
|
13
|
+
};
|
|
14
|
+
/** Close codes of the `graphql-transport-ws` protocol */
|
|
15
|
+
export declare const GraphqlWsCloseCode: {
|
|
16
|
+
readonly INTERNAL_SERVER_ERROR: 4500;
|
|
17
|
+
readonly INTERNAL_CLIENT_ERROR: 4005;
|
|
18
|
+
readonly BAD_REQUEST: 4400;
|
|
19
|
+
readonly BAD_RESPONSE: 4004;
|
|
20
|
+
readonly UNAUTHORIZED: 4401;
|
|
21
|
+
readonly FORBIDDEN: 4403;
|
|
22
|
+
readonly SUBPROTOCOL_NOT_ACCEPTABLE: 4406;
|
|
23
|
+
readonly CONNECTION_INITIALISATION_TIMEOUT: 4408;
|
|
24
|
+
readonly CONNECTION_ACKNOWLEDGEMENT_TIMEOUT: 4504;
|
|
25
|
+
readonly SUBSCRIBER_ALREADY_EXISTS: 4409;
|
|
26
|
+
readonly TOO_MANY_INITIALISATION_REQUESTS: 4429;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Close codes that a retry can't fix - the same ones the `graphql-ws` client gives up on. Forbidden (4403) and the
|
|
30
|
+
* timeouts (4408, 4504) are retried, as access may be granted and the server may answer in time on the next attempt.
|
|
31
|
+
*/
|
|
32
|
+
export declare const fatalGraphqlWsCloseCodes: ReadonlySet<number>;
|
|
33
|
+
/**
|
|
34
|
+
* Close codes of the WebSocket standard (1001-1999) that a retry can fix: going away, no status, abnormal closure,
|
|
35
|
+
* service restart, try again later and bad gateway. The other ones report a broken client or server, e.g. 1002
|
|
36
|
+
* (protocol error) or 1003 (unsupported data). A normal closure (1000) stays closed, as with every socket adapter.
|
|
37
|
+
*/
|
|
38
|
+
export declare const retriedStandardCloseCodes: ReadonlySet<number>;
|
|
39
|
+
/** Defaults of the keep-alive */
|
|
40
|
+
export declare const defaultKeepAlive: {
|
|
41
|
+
intervalMs: number;
|
|
42
|
+
pongTimeoutMs: number;
|
|
43
|
+
};
|
|
44
|
+
//# sourceMappingURL=socket.constants.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket.constants.d.ts","sourceRoot":"","sources":["../../src/socket/socket.constants.ts"],"names":[],"mappings":"AAEA,0EAA0E;AAC1E,eAAO,MAAM,6BAA6B,yBAAyB,CAAC;AAEpE,2DAA2D;AAC3D,eAAO,MAAM,oBAAoB;;;;;;;;;CASvB,CAAC;AAEX,yDAAyD;AACzD,eAAO,MAAM,kBAAkB;;;;;;;;;;;;CAYrB,CAAC;AAEX;;;GAGG;AACH,eAAO,MAAM,wBAAwB,EAAE,WAAW,CAAC,MAAM,CASvD,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,EAAE,WAAW,CAAC,MAAM,CAAiD,CAAC;AAE5G,iCAAiC;AACjC,eAAO,MAAM,gBAAgB;;;CAG5B,CAAC"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { ListenerCallbackType, SocketAdapterInstance } from '@hyper-fetch/sockets';
|
|
2
|
+
import { GraphQLFormattedError } from 'graphql';
|
|
3
|
+
import { GraphqlWsExtraType, GraphqlWsListenerOptionsType } from './socket.types';
|
|
4
|
+
type CallbackType = ListenerCallbackType<SocketAdapterInstance, any>;
|
|
5
|
+
/** One server subscription: a document with one set of variables, shared by every callback listening to it */
|
|
6
|
+
export type GraphqlSubscriptionType = {
|
|
7
|
+
/** Topic, document and encoded variables - one server subscription per key */
|
|
8
|
+
key: string;
|
|
9
|
+
topic: string;
|
|
10
|
+
/** Printed document, sent as `query` */
|
|
11
|
+
query: string;
|
|
12
|
+
operationName: string | undefined;
|
|
13
|
+
/** Variables as the listener has them, sent with the subscription and passed to the callbacks in `extra` */
|
|
14
|
+
payload: unknown;
|
|
15
|
+
callbacks: Set<CallbackType>;
|
|
16
|
+
/** The subscription was sent over the current acknowledged connection */
|
|
17
|
+
started: boolean;
|
|
18
|
+
};
|
|
19
|
+
/** What the subscriptions need from the listener - the topic, the document and the variables */
|
|
20
|
+
type GraphqlListenerType = {
|
|
21
|
+
topic: string;
|
|
22
|
+
payload?: unknown;
|
|
23
|
+
options?: GraphqlWsListenerOptionsType;
|
|
24
|
+
};
|
|
25
|
+
/** The adapter bindings used by the subscriptions */
|
|
26
|
+
type GraphqlBindingsType = {
|
|
27
|
+
onListen: (options: {
|
|
28
|
+
listener: GraphqlListenerType;
|
|
29
|
+
callback: CallbackType;
|
|
30
|
+
onUnmount?: VoidFunction;
|
|
31
|
+
}) => () => void;
|
|
32
|
+
onEvent: (options: {
|
|
33
|
+
topic: string;
|
|
34
|
+
data: unknown;
|
|
35
|
+
extra: GraphqlWsExtraType;
|
|
36
|
+
callbacks?: ReadonlySet<CallbackType>;
|
|
37
|
+
}) => void;
|
|
38
|
+
onError: (options: {
|
|
39
|
+
error: Error;
|
|
40
|
+
}) => void;
|
|
41
|
+
onListenerStart: (options: {
|
|
42
|
+
topic: string;
|
|
43
|
+
callbacks: ReadonlySet<CallbackType>;
|
|
44
|
+
}) => void;
|
|
45
|
+
onListenerEnd: (options: {
|
|
46
|
+
topic: string;
|
|
47
|
+
callbacks: ReadonlySet<CallbackType>;
|
|
48
|
+
error: Error | null;
|
|
49
|
+
}) => void;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Keeps one server subscription per topic, document and variables. Callbacks with the same ones share it, the first
|
|
53
|
+
* one starts it and the last one to leave stops it. The adapter only moves the subscriptions over its transport.
|
|
54
|
+
*/
|
|
55
|
+
export declare const createGraphqlSubscriptions: ({ bindings: { onListen, onEvent, onError, onListenerStart, onListenerEnd }, onStart, onStop, }: {
|
|
56
|
+
bindings: GraphqlBindingsType;
|
|
57
|
+
/** The first callback joined - start the subscription when the connection is acknowledged */
|
|
58
|
+
onStart: (subscription: GraphqlSubscriptionType) => void;
|
|
59
|
+
/** The last callback left - stop the subscription on the server */
|
|
60
|
+
onStop: (subscription: GraphqlSubscriptionType) => void;
|
|
61
|
+
}) => {
|
|
62
|
+
listen: (listener: GraphqlListenerType, callback: CallbackType) => () => void;
|
|
63
|
+
deliver: (subscription: GraphqlSubscriptionType, { data, errors, extensions }: {
|
|
64
|
+
data: unknown;
|
|
65
|
+
errors: GraphQLFormattedError[] | undefined;
|
|
66
|
+
extensions: unknown;
|
|
67
|
+
}) => void;
|
|
68
|
+
confirm: (subscription: GraphqlSubscriptionType) => void;
|
|
69
|
+
unconfirm: (subscription: GraphqlSubscriptionType) => void;
|
|
70
|
+
end: (subscription: GraphqlSubscriptionType, error: Error | null) => void;
|
|
71
|
+
getAll: () => GraphqlSubscriptionType[];
|
|
72
|
+
};
|
|
73
|
+
export {};
|
|
74
|
+
//# sourceMappingURL=socket.subscriptions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket.subscriptions.d.ts","sourceRoot":"","sources":["../../src/socket/socket.subscriptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AACxF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAGrD,OAAO,KAAK,EAAE,kBAAkB,EAAE,4BAA4B,EAAE,MAAM,gBAAgB,CAAC;AAGvF,KAAK,YAAY,GAAG,oBAAoB,CAAC,qBAAqB,EAAE,GAAG,CAAC,CAAC;AAErE,8GAA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EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;QAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAA;KAAE,KAAK,IAAI,CAAC;CAChH,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,0BAA0B,GAAI,gGAIxC;IACD,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,6FAA6F;IAC7F,OAAO,EAAE,CAAC,YAAY,EAAE,uBAAuB,KAAK,IAAI,CAAC;IACzD,mEAAmE;IACnE,MAAM,EAAE,CAAC,YAAY,EAAE,uBAAuB,KAAK,IAAI,CAAC;CACzD;uBAc2B,mBAAmB,YAAY,YAAY,WAxCzD,IAAI;4BAiFA,uBAAuB,gCACP;QAAE,IAAI,EAAE,OAAO,CAAC;QAAC,MAAM,EAAE,qBAAqB,EAAE,GAAG,SAAS,CAAC;QAAC,UAAU,EAAE,OAAO,CAAA;KAAE;4BAgBpF,uBAAuB;8BAOrB,uBAAuB;wBAS7B,uBAAuB,SAAS,KAAK,GAAG,IAAI;;CAYxE,CAAC"}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { QueryParamsType, stringifyQueryParams } from '@hyper-fetch/core';
|
|
2
|
+
import { SocketAdapter } from '@hyper-fetch/sockets';
|
|
3
|
+
import { GraphQLFormattedError } from 'graphql';
|
|
4
|
+
import { GraphQlEndpointType } from '../adapter/adapter.types';
|
|
5
|
+
/**
|
|
6
|
+
* The `extra` of every subscription event, received by `listen` callbacks next to the `data`.
|
|
7
|
+
*/
|
|
8
|
+
export type GraphqlWsExtraType = {
|
|
9
|
+
/**
|
|
10
|
+
* Errors of the event. The server sends them next to the `data` when resolving the event failed in part - the
|
|
11
|
+
* subscription keeps running. `undefined` when the event has none.
|
|
12
|
+
*
|
|
13
|
+
* A subscription the server can't execute at all, e.g. with missing variables, gets one event with these errors and
|
|
14
|
+
* `null` data, and then it completes.
|
|
15
|
+
*/
|
|
16
|
+
errors?: GraphQLFormattedError[];
|
|
17
|
+
/** The `extensions` of the event, `{}` when the server sent none */
|
|
18
|
+
extensions: Record<string, unknown>;
|
|
19
|
+
/**
|
|
20
|
+
* Variables of the subscription the event belongs to. Listeners of one topic with other variables are separate
|
|
21
|
+
* subscriptions, so it tells them apart where events of every subscription meet, like `socket.events.onListenerEvent`.
|
|
22
|
+
*/
|
|
23
|
+
payload: unknown;
|
|
24
|
+
};
|
|
25
|
+
/** Payload of `connection_init`, read by the server in `onConnect` as `ctx.connectionParams`, e.g. an auth token */
|
|
26
|
+
export type GraphqlWsConnectionParamsType = Record<string, unknown>;
|
|
27
|
+
/**
|
|
28
|
+
* Keep-alive of the connection. The client sends `ping` when the connection is quiet and treats it as lost when the
|
|
29
|
+
* `pong` does not arrive in time - the only way to notice a connection that died without a close, e.g. behind a proxy.
|
|
30
|
+
*/
|
|
31
|
+
export type GraphqlWsKeepAliveOptionsType = {
|
|
32
|
+
enabled: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* How long the connection can be quiet before the client sends `ping`, in milliseconds.
|
|
35
|
+
* @default 10000
|
|
36
|
+
*/
|
|
37
|
+
intervalMs?: number;
|
|
38
|
+
/**
|
|
39
|
+
* How long the client waits for `pong` before it reconnects, in milliseconds.
|
|
40
|
+
* @default 5000
|
|
41
|
+
*/
|
|
42
|
+
pongTimeoutMs?: number;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Options of the GraphQL WebSocket connection, passed as `adapterOptions` to the `Socket`.
|
|
46
|
+
* They can be changed per connection attempt with `socket.onConnect`.
|
|
47
|
+
*/
|
|
48
|
+
export type GraphqlWsAdapterOptionsType = {
|
|
49
|
+
/**
|
|
50
|
+
* Connect when the socket is created. Only the first connection depends on it - a socket connected by hand also
|
|
51
|
+
* reconnects after a lost connection and when the app goes back online. Ignored with `lazy`.
|
|
52
|
+
* @default true
|
|
53
|
+
*/
|
|
54
|
+
autoConnect?: boolean;
|
|
55
|
+
/**
|
|
56
|
+
* Connect when the first subscription starts and close the connection when the last one stops, after
|
|
57
|
+
* `lazyCloseTimeout`. A socket without subscriptions holds no connection.
|
|
58
|
+
* @default false
|
|
59
|
+
*/
|
|
60
|
+
lazy?: boolean;
|
|
61
|
+
/**
|
|
62
|
+
* With `lazy`, how long the connection stays open after the last subscription stopped, in milliseconds. A
|
|
63
|
+
* subscription started in this time reuses the connection.
|
|
64
|
+
* @default 0
|
|
65
|
+
*/
|
|
66
|
+
lazyCloseTimeout?: number;
|
|
67
|
+
/**
|
|
68
|
+
* The `WebSocket` class to use, for example from the `ws` package. Defaults to the global one
|
|
69
|
+
* (browsers, Node.js 22+, Bun, Deno).
|
|
70
|
+
*/
|
|
71
|
+
WebSocket?: typeof WebSocket;
|
|
72
|
+
/**
|
|
73
|
+
* Sent with `connection_init` on every connection, before any subscription starts. A function runs on every
|
|
74
|
+
* connection attempt, so a reconnect sends a fresh token. When it throws or rejects, the connection is closed with
|
|
75
|
+
* 4005 and not retried.
|
|
76
|
+
*/
|
|
77
|
+
connectionParams?: GraphqlWsConnectionParamsType | (() => GraphqlWsConnectionParamsType | undefined | Promise<GraphqlWsConnectionParamsType | undefined>);
|
|
78
|
+
/** Sends `ping` on a quiet connection and reconnects when the server does not answer */
|
|
79
|
+
keepAlive?: GraphqlWsKeepAliveOptionsType;
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* Options of a listener, set with `options` in `createListener` or with `listener.setOptions()`.
|
|
83
|
+
*/
|
|
84
|
+
export type GraphqlWsListenerOptionsType = {
|
|
85
|
+
/**
|
|
86
|
+
* The subscription document. A typed document (graphql-codegen, gql.tada) types the listener's data and variables.
|
|
87
|
+
* When it is omitted, the `topic` is sent as the document.
|
|
88
|
+
*/
|
|
89
|
+
document?: GraphQlEndpointType;
|
|
90
|
+
};
|
|
91
|
+
/** Socket adapter speaking the GraphQL over WebSocket protocol (`graphql-transport-ws`) */
|
|
92
|
+
export type GraphqlWsAdapterType = SocketAdapter<GraphqlWsExtraType, GraphqlWsAdapterOptionsType, GraphqlWsListenerOptionsType, undefined, QueryParamsType | string, typeof stringifyQueryParams>;
|
|
93
|
+
/** Details of the subscription a {@link GraphqlSubscriptionError} belongs to */
|
|
94
|
+
export type GraphqlSubscriptionErrorOptionsType = {
|
|
95
|
+
/** Errors sent by the server with the `error` message */
|
|
96
|
+
errors: GraphQLFormattedError[];
|
|
97
|
+
/** Topic of the failed subscription */
|
|
98
|
+
topic: string;
|
|
99
|
+
/** Variables of the failed subscription */
|
|
100
|
+
payload: unknown;
|
|
101
|
+
};
|
|
102
|
+
//# sourceMappingURL=socket.types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket.types.d.ts","sourceRoot":"","sources":["../../src/socket/socket.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAErD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAEpE;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,qBAAqB,EAAE,CAAC;IACjC,oEAAoE;IACpE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpC;;;OAGG;IACH,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF,oHAAoH;AACpH,MAAM,MAAM,6BAA6B,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEpE;;;GAGG;AACH,MAAM,MAAM,6BAA6B,GAAG;IAC1C,OAAO,EAAE,OAAO,CAAC;IACjB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,2BAA2B,GAAG;IACxC;;;;OAIG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;OAIG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;IACf;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,SAAS,CAAC;IAC7B;;;;OAIG;IACH,gBAAgB,CAAC,EACb,6BAA6B,GAC7B,CAAC,MAAM,6BAA6B,GAAG,SAAS,GAAG,OAAO,CAAC,6BAA6B,GAAG,SAAS,CAAC,CAAC,CAAC;IAC3G,wFAAwF;IACxF,SAAS,CAAC,EAAE,6BAA6B,CAAC;CAC3C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,4BAA4B,GAAG;IACzC;;;OAGG;IACH,QAAQ,CAAC,EAAE,mBAAmB,CAAC;CAChC,CAAC;AAEF,2FAA2F;AAC3F,MAAM,MAAM,oBAAoB,GAAG,aAAa,CAC9C,kBAAkB,EAClB,2BAA2B,EAC3B,4BAA4B,EAC5B,SAAS,EACT,eAAe,GAAG,MAAM,EACxB,OAAO,oBAAoB,CAC5B,CAAC;AAEF,gFAAgF;AAChF,MAAM,MAAM,mCAAmC,GAAG;IAChD,yDAAyD;IACzD,MAAM,EAAE,qBAAqB,EAAE,CAAC;IAChC,uCAAuC;IACvC,KAAK,EAAE,MAAM,CAAC;IACd,2CAA2C;IAC3C,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { ShouldReconnectType } from '@hyper-fetch/sockets';
|
|
2
|
+
import { GraphQLFormattedError } from 'graphql';
|
|
3
|
+
import { GraphqlWsMessageType } from './socket.constants';
|
|
4
|
+
import { GraphqlSubscriptionErrorOptionsType } from './socket.types';
|
|
5
|
+
/** The object check of the `graphql-ws` client, so both accept the same messages */
|
|
6
|
+
export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
|
|
7
|
+
export declare const toError: (value: unknown) => Error;
|
|
8
|
+
/** A message the server may send - every other one breaks the protocol */
|
|
9
|
+
export type GraphqlWsServerMessageType = {
|
|
10
|
+
type: typeof GraphqlWsMessageType.CONNECTION_ACK;
|
|
11
|
+
payload?: Record<string, unknown> | null;
|
|
12
|
+
} | {
|
|
13
|
+
type: typeof GraphqlWsMessageType.PING;
|
|
14
|
+
payload?: Record<string, unknown> | null;
|
|
15
|
+
} | {
|
|
16
|
+
type: typeof GraphqlWsMessageType.PONG;
|
|
17
|
+
payload?: Record<string, unknown> | null;
|
|
18
|
+
} | {
|
|
19
|
+
type: typeof GraphqlWsMessageType.NEXT;
|
|
20
|
+
id: string;
|
|
21
|
+
payload: Record<string, unknown>;
|
|
22
|
+
} | {
|
|
23
|
+
type: typeof GraphqlWsMessageType.ERROR;
|
|
24
|
+
id: string;
|
|
25
|
+
payload: GraphQLFormattedError[];
|
|
26
|
+
} | {
|
|
27
|
+
type: typeof GraphqlWsMessageType.COMPLETE;
|
|
28
|
+
id: string;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Reads a frame of the server. Throws when it breaks the protocol - the same checks the `graphql-ws` client makes, so
|
|
32
|
+
* a server that works with it works with the adapter.
|
|
33
|
+
*/
|
|
34
|
+
export declare const parseServerMessage: (data: unknown) => GraphqlWsServerMessageType;
|
|
35
|
+
/** Reported to `onError` when the server breaks the protocol - the connection is closed with 4004 */
|
|
36
|
+
export declare const getBadResponseError: (cause: unknown) => Error;
|
|
37
|
+
/**
|
|
38
|
+
* The close reason may hold at most 123 bytes. Longer reasons are cut by the `graphql-ws` client the same way:
|
|
39
|
+
* replaced with a short generic one.
|
|
40
|
+
*/
|
|
41
|
+
export declare const limitCloseReason: (reason: string, fallback: string) => string;
|
|
42
|
+
/**
|
|
43
|
+
* The default `shouldReconnect` of the GraphQL WebSocket adapter. It gives up on the close codes a retry can't fix -
|
|
44
|
+
* bad requests, unauthorized, a missing subprotocol, protocol errors and the like, the same ones the `graphql-ws` client
|
|
45
|
+
* gives up on - and on a normal closure (1000), as every socket adapter does. Everything else is retried. The socket's
|
|
46
|
+
* own `shouldReconnect` replaces it, so call this one from yours to keep these rules.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* const socket = new Socket({
|
|
50
|
+
* url,
|
|
51
|
+
* adapter: GraphqlWsAdapter(),
|
|
52
|
+
* // Retry after a normal closure too
|
|
53
|
+
* shouldReconnect: (loss) => loss.code === 1000 || shouldReconnectGraphqlWs(loss),
|
|
54
|
+
* });
|
|
55
|
+
*/
|
|
56
|
+
export declare const shouldReconnectGraphqlWs: ShouldReconnectType;
|
|
57
|
+
/**
|
|
58
|
+
* Error of a GraphQL subscription, reported to the `socket.onError` callbacks and to the `onEnd` of its listeners.
|
|
59
|
+
* The server ended the subscription with the `error` message - its validation or its source failed. `errors` holds what
|
|
60
|
+
* it sent.
|
|
61
|
+
*
|
|
62
|
+
* Errors of a single event do not end the subscription and come with the event in `extra.errors`.
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* socket.onError(({ error }) => {
|
|
66
|
+
* if (error instanceof GraphqlSubscriptionError && error.errors[0].extensions?.code === "UNAUTHENTICATED") {
|
|
67
|
+
* logout();
|
|
68
|
+
* }
|
|
69
|
+
* });
|
|
70
|
+
*/
|
|
71
|
+
export declare class GraphqlSubscriptionError extends Error {
|
|
72
|
+
/** Errors sent by the server with the `error` message */
|
|
73
|
+
readonly errors: GraphQLFormattedError[];
|
|
74
|
+
/** Topic of the failed subscription */
|
|
75
|
+
readonly topic: string;
|
|
76
|
+
/** Variables of the failed subscription */
|
|
77
|
+
readonly payload: unknown;
|
|
78
|
+
constructor({ errors, topic, payload }: GraphqlSubscriptionErrorOptionsType);
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=socket.utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket.utils.d.ts","sourceRoot":"","sources":["../../src/socket/socket.utils.ts"],"names":[],"mappings":"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AE,MAAM,CAAA;CAAE,CAAC;AAU/D;;;GAGG;AACH,eAAO,MAAM,kBAAkB,GAAI,MAAM,OAAO,KAAG,0BAwClD,CAAC;AAEF,qGAAqG;AACrG,eAAO,MAAM,mBAAmB,GAAI,OAAO,OAAO,KAAG,KAEpD,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,GAAI,QAAQ,MAAM,EAAE,UAAU,MAAM,WAEhE,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,wBAAwB,EAAE,mBAYtC,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,qBAAa,wBAAyB,SAAQ,KAAK;IACjD,yDAAyD;IACzD,QAAQ,CAAC,MAAM,EAAE,qBAAqB,EAAE,CAAC;IACzC,uCAAuC;IACvC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,2CAA2C;IAC3C,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;gBAEd,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,mCAAmC;CAO5E"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { GraphqlWsAdapterType } from './socket.types';
|
|
2
|
+
/**
|
|
3
|
+
* Socket adapter for GraphQL subscriptions over WebSocket. It speaks `graphql-transport-ws`, the protocol of the
|
|
4
|
+
* `graphql-ws` library - supported by Apollo Server, GraphQL Yoga, Mercurius, Hot Chocolate, Hasura and most others.
|
|
5
|
+
*
|
|
6
|
+
* - The connection counts as open once the server acknowledged `connection_init`, so the socket's
|
|
7
|
+
* `connectionTimeout` covers the whole handshake. `connectionParams` are sent with it, a function runs on every
|
|
8
|
+
* connection attempt.
|
|
9
|
+
* - Every document with one set of variables is one server subscription, shared by the listeners with those
|
|
10
|
+
* variables. Subscriptions started before the connection is acknowledged wait for it, and after a reconnect they are
|
|
11
|
+
* sent again.
|
|
12
|
+
* - The server's `ping` is answered, and `keepAlive` pings a quiet connection to notice when it died.
|
|
13
|
+
* - Reconnecting follows the socket's reconnection options. Close codes a retry can't fix (4400, 4401, 4409...) stop
|
|
14
|
+
* it - see {@link shouldReconnectGraphqlWs}.
|
|
15
|
+
* - With `lazy`, the connection is open only while there are subscriptions.
|
|
16
|
+
*
|
|
17
|
+
* Queries and mutations are sent with the `GraphqlAdapter` - `emit` throws.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* const socket = new Socket({
|
|
21
|
+
* url: "ws://localhost:4000/graphql",
|
|
22
|
+
* adapter: GraphqlWsAdapter(),
|
|
23
|
+
* adapterOptions: { connectionParams: () => ({ token: getToken() }) },
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* const onMessage = socket.createListener()({ topic: "OnMessage", options: { document: OnMessageDocument } });
|
|
27
|
+
* onMessage.listen(({ data, extra }) => {}, { payload: { room: "general" } });
|
|
28
|
+
*/
|
|
29
|
+
export declare const GraphqlWsAdapter: () => GraphqlWsAdapterType;
|
|
30
|
+
//# sourceMappingURL=socket.websocket.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket.websocket.d.ts","sourceRoot":"","sources":["../../src/socket/socket.websocket.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAEV,oBAAoB,EAGrB,MAAM,gBAAgB,CAAC;AAwBxB;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,eAAO,MAAM,gBAAgB,QAAO,oBA6d9B,CAAC"}
|