@hyper-fetch/graphql 8.1.1 โ†’ 8.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,10 @@
1
1
  # ๐ŸŽก Hyper Fetch GraphQL
2
2
 
3
- <p>
3
+ <p align="center">
4
+ <b>GraphQL adapter for HyperFetch. Typed queries, mutations, and subscriptions.</b>
5
+ </p>
6
+
7
+ <p align="center">
4
8
  <a href="https://bettertyped.com/">
5
9
  <img src="https://custom-icon-badges.demolab.com/static/v1?label=&message=BetterTyped&color=333&logo=BT" />
6
10
  </a>
@@ -13,58 +17,139 @@
13
17
  <a href="https://www.npmjs.com/package/@hyper-fetch/graphql">
14
18
  <img src="https://custom-icon-badges.demolab.com/npm/v/@hyper-fetch/graphql.svg?logo=npm&color=e76f51" />
15
19
  </a>
16
- <a href="https://github.com/BetterTyped/hyper-fetch">
17
- <img src="https://custom-icon-badges.demolab.com/badge/typescript-%23007ACC.svg?logo=typescript&logoColor=white" />
20
+ <a href="https://www.npmjs.com/package/@hyper-fetch/graphql">
21
+ <img src="https://custom-icon-badges.demolab.com/npm/dm/@hyper-fetch/graphql?logoColor=fff&logo=trending-up" />
18
22
  </a>
19
23
  <a href="https://github.com/BetterTyped/hyper-fetch">
20
- <img src="https://custom-icon-badges.demolab.com/badge/-GraphQL-E10098?logo=graphql&logoColor=white" />
24
+ <img src="https://custom-icon-badges.demolab.com/badge/typescript-%23007ACC.svg?logo=typescript&logoColor=white" />
21
25
  </a>
22
- <a href="https://www.npmjs.com/package/@hyper-fetch/graphql">
26
+ <a href="https://bundlephobia.com/package/@hyper-fetch/graphql">
23
27
  <img src="https://custom-icon-badges.demolab.com/bundlephobia/minzip/@hyper-fetch/graphql?color=64BC4B&logo=package" />
24
28
  </a>
29
+ <a href="https://github.com/BetterTyped/hyper-fetch">
30
+ <img src="https://img.shields.io/badge/graphql-e10098?logo=graphql&logoColor=white" alt="GraphQL" />
31
+ </a>
25
32
  </p>
26
33
 
27
- ## About
28
-
29
- **`Hyper Fetch GraphQL`** is adapter for Hyper Fetch. It enables seamless communication with GraphQL APIs in Node.js and
30
- browser environments, simplifying the retrieval and manipulation of data. Benefit from the convenience and efficiency of
31
- Hyper Fetch for your GraphQL-powered projects.
32
-
33
- ## Features
34
-
35
- ๐Ÿ”ฎ **Simple setup** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/basic/setup)
36
-
37
- ๐ŸŽฏ **Request cancellation** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/advanced/cancellation)
38
-
39
- โœจ **Window Focus/Blur Events** -
40
- [Read more](https://hyperfetch.bettertyped.com/docs/guides/react/core/window-focus-blur)
41
-
42
- ๐Ÿš€ **Queueing** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/advanced/queueing)
43
-
44
- ๐Ÿ’Ž **Automatic caching** - [Read more](https://hyperfetch.bettertyped.com/docs/core/cache)
45
-
46
- ๐Ÿช„ **Persistence** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/advanced/persistence)
47
-
48
- ๐ŸŽŠ **SSR Support** - [Read more](https://hyperfetch.bettertyped.com/docs/getting-started/environment)
49
-
50
- ๐Ÿ”‹ **Offline First** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/advanced/offline)
51
-
52
- ๐Ÿ“ก **Built-in adapter** - [Read more](https://hyperfetch.bettertyped.com/docs/core/adapter)
53
-
54
- ๐Ÿงช **Easy to test** - [Read more](https://hyperfetch.bettertyped.com/docs/getting-started/testing)
55
-
56
- ๐ŸŽŸ **Authentication** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/basic/authentication)
57
-
58
- ๐Ÿ’ก **Prefetching** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/advanced/prefetching)
59
-
60
- ## Help me keep working on this project โค๏ธ
61
-
62
- - [Become a Sponsor on GitHub](https://github.com/sponsors/prc5)
63
-
64
- ## Sources
65
-
66
- - #### [Installation](https://hyperfetch.bettertyped.com/docs/getting-started/installation)
67
- - #### [Docs](https://hyperfetch.bettertyped.com/)
68
- - #### [API](https://hyperfetch.bettertyped.com/api/)
69
- - #### [NPM](https://www.npmjs.com/package/@hyper-fetch/graphql)
70
- - #### [Guides](https://hyperfetch.bettertyped.com/guides/Basic/Setup)
34
+ ## ๐Ÿ“– About
35
+
36
+ This adapter connects HyperFetch to GraphQL APIs. You get typed queries, mutations, and subscriptions that work with
37
+ HyperFetch's caching, queuing, and React hooks โ€” the same request patterns you use for REST, but with GraphQL
38
+ operations.
39
+
40
+ ## ๐ŸŽฏ Key Capabilities
41
+
42
+ - ๐ŸŽก **GraphQL meets HyperFetch** โ€” Typed queries, mutations, and subscriptions with cache and queue support
43
+ - ๐Ÿ”ฎ **End-to-end types** โ€” Full TypeScript types for operations, variables, and responses
44
+ - ๐Ÿ“ก **Any GraphQL server** โ€” Compatible with Apollo, Yoga, Hasura, and any spec-compliant endpoint
45
+ - โš›๏ธ **React-ready** โ€” Use `useFetch` and `useSubmit` for GraphQL operations in components
46
+ - ๐Ÿ’พ **Smart caching included** โ€” Cache and offline support work the same as REST โ€” no extra config
47
+
48
+ ## ๐Ÿš€ Quick Start
49
+
50
+ ```bash
51
+ npm install @hyper-fetch/core @hyper-fetch/graphql
52
+ ```
53
+
54
+ ```ts
55
+ import { createClient } from "@hyper-fetch/core";
56
+ import { GraphQLAdapter } from "@hyper-fetch/graphql";
57
+
58
+ const client = createClient({ url: "https://api.example.com/graphql" }).setAdapter(GraphQLAdapter());
59
+ ```
60
+
61
+ ## ๐Ÿ“š Documentation
62
+
63
+ - [GraphQL Adapter Docs](https://hyperfetch.bettertyped.com/docs/integrations/adapter-graphql)
64
+ - [Getting Started](https://hyperfetch.bettertyped.com/docs/getting-started/quick-start)
65
+ - [API Reference](https://hyperfetch.bettertyped.com/api/)
66
+
67
+ ## ๐Ÿ’ก Examples
68
+
69
+ ### Query
70
+
71
+ ```ts
72
+ interface UsersResponse {
73
+ users: { id: string; name: string; email: string }[];
74
+ }
75
+
76
+ const getUsers = client.createRequest<{ response: UsersResponse }>()({
77
+ endpoint: "",
78
+ method: "POST",
79
+ });
80
+
81
+ const { data } = await getUsers
82
+ .setData({
83
+ query: `
84
+ query GetUsers($limit: Int) {
85
+ users(limit: $limit) {
86
+ id
87
+ name
88
+ email
89
+ }
90
+ }
91
+ `,
92
+ variables: { limit: 10 },
93
+ })
94
+ .send();
95
+
96
+ console.log(data.users);
97
+ ```
98
+
99
+ ### Mutation
100
+
101
+ ```ts
102
+ interface CreateUserResponse {
103
+ createUser: { id: string; name: string };
104
+ }
105
+
106
+ const createUser = client.createRequest<{
107
+ response: CreateUserResponse;
108
+ }>()({
109
+ endpoint: "",
110
+ method: "POST",
111
+ });
112
+
113
+ const { data } = await createUser
114
+ .setData({
115
+ query: `
116
+ mutation CreateUser($name: String!, $email: String!) {
117
+ createUser(name: $name, email: $email) {
118
+ id
119
+ name
120
+ }
121
+ }
122
+ `,
123
+ variables: { name: "Jane", email: "jane@example.com" },
124
+ })
125
+ .send();
126
+
127
+ console.log("Created:", data.createUser.name);
128
+ ```
129
+
130
+ ### With React hooks
131
+
132
+ ```tsx
133
+ import { useFetch } from "@hyper-fetch/react";
134
+
135
+ const UserList = () => {
136
+ const { data, loading } = useFetch(
137
+ getUsers.setData({
138
+ query: `{ users { id name } }`,
139
+ }),
140
+ );
141
+
142
+ if (loading) return <p>Loading...</p>;
143
+ return (
144
+ <ul>
145
+ {data?.users.map((u) => (
146
+ <li key={u.id}>{u.name}</li>
147
+ ))}
148
+ </ul>
149
+ );
150
+ };
151
+ ```
152
+
153
+ ## License
154
+
155
+ [MIT](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
@@ -1,6 +1,6 @@
1
- import http from "http";
2
1
  import type { GraphQLSchema } from "graphql";
3
2
  import { graphql, buildSchema } from "graphql";
3
+ import http from "http";
4
4
 
5
5
  export type GraphQLServerOptions = {
6
6
  typeDefs: string;
@@ -1,11 +1,11 @@
1
1
  import { Client, getErrorMessage } from "@hyper-fetch/core";
2
2
  import { createGraphqlMockingServer } from "@hyper-fetch/testing";
3
-
4
3
  import { GraphqlAdapter } from "adapter";
5
- import type { GetUserQueryResponse } from "../../constants/queries.constants";
6
- import { getUserQuery, getUserQueryString } from "../../constants/queries.constants";
4
+
7
5
  import type { LoginMutationVariables } from "../../constants/mutations.constants";
8
6
  import { loginMutation } from "../../constants/mutations.constants";
7
+ import type { GetUserQueryResponse } from "../../constants/queries.constants";
8
+ import { getUserQuery, getUserQueryString } from "../../constants/queries.constants";
9
9
 
10
10
  const { startServer, stopServer, resetMocks, mockRequest } = createGraphqlMockingServer();
11
11
 
@@ -5,10 +5,10 @@ import { Client, getErrorMessage } from "@hyper-fetch/core";
5
5
  import { createGraphqlMockingServer } from "@hyper-fetch/testing";
6
6
 
7
7
  import { GraphqlAdapter, GraphqlMethod } from "../../../src/adapter";
8
- import type { GetUserQueryResponse } from "../../constants/queries.constants";
9
- import { getUserQuery, getUserQueryString } from "../../constants/queries.constants";
10
8
  import type { LoginMutationVariables } from "../../constants/mutations.constants";
11
9
  import { loginMutation } from "../../constants/mutations.constants";
10
+ import type { GetUserQueryResponse } from "../../constants/queries.constants";
11
+ import { getUserQuery, getUserQueryString } from "../../constants/queries.constants";
12
12
 
13
13
  const { startServer, stopServer, resetMocks, mockRequest } = createGraphqlMockingServer();
14
14
 
@@ -1,6 +1,6 @@
1
1
  import { Client } from "@hyper-fetch/core";
2
-
3
2
  import { GraphqlMethod, getRequestValues, GraphqlAdapter } from "adapter";
3
+
4
4
  import { gqlEndpointNameMapper } from "../../../src/adapter/adapter.utils";
5
5
  import { getUserQuery, getUserQueryString } from "../../constants/queries.constants";
6
6
 
@@ -1,23 +1,16 @@
1
1
  {
2
+ "extends": "../tsconfig.json",
2
3
  "compilerOptions": {
3
- "target": "esnext",
4
- "module": "esnext",
5
- "moduleResolution": "bundler",
6
- "lib": ["dom", "dom.iterable", "ESNext"],
7
- "strict": true,
8
4
  "noEmit": true,
9
- "skipLibCheck": true,
10
- "esModuleInterop": true,
11
- "allowSyntheticDefaultImports": true,
12
- "resolveJsonModule": true,
13
- "isolatedModules": true,
14
5
  "noUnusedLocals": false,
15
6
  "noUnusedParameters": false,
16
7
  "types": ["vitest/globals", "jest-extended", "@types/node"],
17
- "baseUrl": "../src",
18
8
  "paths": {
9
+ "adapter": ["../src/adapter"],
10
+ "adapter/*": ["../src/adapter/*"],
19
11
  "@hyper-fetch/graphql": ["../src"]
20
12
  }
21
13
  },
22
- "include": ["**/*.ts", "**/*.tsx", "../../../global.d.ts", "../../../vitest.d.ts"]
14
+ "include": ["**/*.ts", "**/*.tsx", "../../../global.d.ts", "../../../vitest.d.ts"],
15
+ "exclude": ["node_modules"]
23
16
  }
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../src/adapter/adapter.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,eAAO,MAAM,cAAc,QAAO,kBAEjC,CAAC"}
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../src/adapter/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAG1D,eAAO,MAAM,cAAc,QAAO,kBAEjC,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { RequestInstance } from '@hyper-fetch/core';
2
- import { GraphQlEndpointType } from '.';
2
+ import { GraphQlEndpointType } from './adapter.types';
3
3
  export declare const getRequestValues: <R extends RequestInstance>(request: R) => {
4
4
  fullUrl: string;
5
5
  payload: string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.utils.d.ts","sourceRoot":"","sources":["../../src/adapter/adapter.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAKzD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAEnD,eAAO,MAAM,gBAAgB,GAAI,CAAC,SAAS,eAAe,EAAE,SAAS,CAAC;;;CAgBrE,CAAC;AAEF,eAAO,MAAM,iBAAiB,GAAI,CAAC,SAAS,mBAAmB,EAAE,UAAU,CAAC,KAAG,MAK9E,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAAI,UAAU,MAAM,KAAG,MAgCxD,CAAC"}
1
+ {"version":3,"file":"adapter.utils.d.ts","sourceRoot":"","sources":["../../src/adapter/adapter.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAKzD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAE3D,eAAO,MAAM,gBAAgB,GAAI,CAAC,SAAS,eAAe,EAAE,SAAS,CAAC;;;CAgBrE,CAAC;AAEF,eAAO,MAAM,iBAAiB,GAAI,CAAC,SAAS,mBAAmB,EAAE,UAAU,CAAC,KAAG,MAK9E,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAAI,UAAU,MAAM,KAAG,MAgCxD,CAAC"}
@@ -1,3 +1,3 @@
1
- import { GraphqlAdapterType } from '.';
1
+ import { GraphqlAdapterType } from './adapter.types';
2
2
  export declare const getGqlAdapter: () => GraphqlAdapterType;
3
3
  //# sourceMappingURL=http-adapter.fetch.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"http-adapter.fetch.d.ts","sourceRoot":"","sources":["../../src/adapter/http-adapter.fetch.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,kBAAkB,EAInB,MAAM,SAAS,CAAC;AAUjB,eAAO,MAAM,aAAa,QAAO,kBAuK5B,CAAC"}
1
+ {"version":3,"file":"http-adapter.fetch.d.ts","sourceRoot":"","sources":["../../src/adapter/http-adapter.fetch.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,kBAAkB,EAInB,MAAM,iBAAiB,CAAC;AAIzB,eAAO,MAAM,aAAa,QAAO,kBA2K5B,CAAC"}
package/dist/index.mjs CHANGED
@@ -1,5 +1,53 @@
1
1
  import { Adapter, HttpMethods, Time, getErrorMessage, parseResponse, stringifyKey, stringifyQueryParams } from "@hyper-fetch/core";
2
2
  import { parse, print } from "graphql";
3
+ //#region src/adapter/adapter.constants.ts
4
+ var defaultTimeout = Time.SEC * 5;
5
+ var gqlExtra = {
6
+ headers: {},
7
+ extensions: {}
8
+ };
9
+ //#endregion
10
+ //#region src/adapter/adapter.types.ts
11
+ var GraphqlMethod = /* @__PURE__ */ function(GraphqlMethod) {
12
+ GraphqlMethod["POST"] = "POST";
13
+ GraphqlMethod["GET"] = "GET";
14
+ return GraphqlMethod;
15
+ }({});
16
+ //#endregion
17
+ //#region src/adapter/adapter.utils.ts
18
+ var getRequestValues = (request) => {
19
+ const isPostRequest = request.method === HttpMethods.POST;
20
+ const query = request.endpoint;
21
+ const variables = request.payload;
22
+ return {
23
+ fullUrl: isPostRequest ? request.client.url : request.client.url + stringifyQueryParams({
24
+ query,
25
+ variables
26
+ }),
27
+ payload: isPostRequest ? JSON.stringify({
28
+ query,
29
+ variables
30
+ }) : null
31
+ };
32
+ };
33
+ var gqlEndpointMapper = (endpoint) => {
34
+ if (typeof endpoint === "string") return endpoint;
35
+ return print(endpoint);
36
+ };
37
+ var gqlEndpointNameMapper = (endpoint) => {
38
+ try {
39
+ const operationDefinition = parse(endpoint).definitions.find((def) => def.kind === "OperationDefinition");
40
+ if (operationDefinition) {
41
+ if (operationDefinition.name?.value) return operationDefinition.name.value;
42
+ const selection = operationDefinition.selectionSet.selections[0];
43
+ if (selection?.kind === "Field") return selection.name.value;
44
+ if (selection?.kind === "InlineFragment" && selection.typeCondition) return selection.typeCondition.name.value;
45
+ }
46
+ } catch {}
47
+ const [name] = endpoint.replace(/(query|mutation|subscription)/, "").replaceAll(/[{}().,:]/g, " ").trim().split(" ");
48
+ return name || "graphql-request";
49
+ };
50
+ //#endregion
3
51
  //#region src/adapter/http-adapter.fetch.ts
4
52
  var getGqlAdapter = () => new Adapter({
5
53
  name: "graphql",
@@ -107,7 +155,7 @@ var getGqlAdapter = () => new Adapter({
107
155
  extensions
108
156
  }
109
157
  });
110
- } catch (err) {
158
+ } catch (error) {
111
159
  if (timeoutId) clearTimeout(timeoutId);
112
160
  unmountListener();
113
161
  if (controller?.signal?.aborted) {
@@ -118,7 +166,7 @@ var getGqlAdapter = () => new Adapter({
118
166
  return;
119
167
  }
120
168
  onError({
121
- error: err,
169
+ error,
122
170
  status: 0,
123
171
  extra: gqlExtra
124
172
  });
@@ -130,54 +178,6 @@ var GraphqlAdapter = () => {
130
178
  return getGqlAdapter();
131
179
  };
132
180
  //#endregion
133
- //#region src/adapter/adapter.types.ts
134
- var GraphqlMethod = /* @__PURE__ */ function(GraphqlMethod) {
135
- GraphqlMethod["POST"] = "POST";
136
- GraphqlMethod["GET"] = "GET";
137
- return GraphqlMethod;
138
- }({});
139
- //#endregion
140
- //#region src/adapter/adapter.utils.ts
141
- var getRequestValues = (request) => {
142
- const isPostRequest = request.method === HttpMethods.POST;
143
- const query = request.endpoint;
144
- const variables = request.payload;
145
- return {
146
- fullUrl: isPostRequest ? request.client.url : request.client.url + stringifyQueryParams({
147
- query,
148
- variables
149
- }),
150
- payload: isPostRequest ? JSON.stringify({
151
- query,
152
- variables
153
- }) : null
154
- };
155
- };
156
- var gqlEndpointMapper = (endpoint) => {
157
- if (typeof endpoint === "string") return endpoint;
158
- return print(endpoint);
159
- };
160
- var gqlEndpointNameMapper = (endpoint) => {
161
- try {
162
- const operationDefinition = parse(endpoint).definitions.find((def) => def.kind === "OperationDefinition");
163
- if (operationDefinition) {
164
- if (operationDefinition.name?.value) return operationDefinition.name.value;
165
- const selection = operationDefinition.selectionSet.selections[0];
166
- if (selection?.kind === "Field") return selection.name.value;
167
- if (selection?.kind === "InlineFragment" && selection.typeCondition) return selection.typeCondition.name.value;
168
- }
169
- } catch (error) {}
170
- const [name] = endpoint.replace(/(query|mutation|subscription)/, "").replace(/[{}().,:]/g, " ").trim().split(" ");
171
- return name || "graphql-request";
172
- };
173
- //#endregion
174
- //#region src/adapter/adapter.constants.ts
175
- var defaultTimeout = Time.SEC * 5;
176
- var gqlExtra = {
177
- headers: {},
178
- extensions: {}
179
- };
180
- //#endregion
181
181
  export { GraphqlAdapter, GraphqlMethod, defaultTimeout, getGqlAdapter, getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper, gqlExtra };
182
182
 
183
183
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/adapter/http-adapter.fetch.ts","../src/adapter/adapter.ts","../src/adapter/adapter.types.ts","../src/adapter/adapter.utils.ts","../src/adapter/adapter.constants.ts"],"sourcesContent":["import type { QueryParamsType } from \"@hyper-fetch/core\";\nimport { parseResponse, getErrorMessage, Adapter, stringifyKey } from \"@hyper-fetch/core\";\n\nimport type {\n GraphqlAdapterType,\n GraphQlExtraType,\n GraphQlEndpointType,\n FetchGraphqlAdapterOptionsType,\n} from \"adapter\";\nimport {\n gqlExtra,\n defaultTimeout,\n getRequestValues,\n GraphqlMethod,\n gqlEndpointMapper,\n gqlEndpointNameMapper,\n} from \"adapter\";\n\nexport const getGqlAdapter = (): GraphqlAdapterType =>\n new Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n undefined,\n GraphQlEndpointType\n >({\n name: \"graphql\",\n defaultMethod: GraphqlMethod.POST,\n defaultExtra: gqlExtra,\n systemErrorStatus: 0,\n systemErrorExtra: gqlExtra,\n })\n .onInitialize(({ client }) => {\n client.setCacheKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n });\n client.setQueryKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n });\n client.setAbortKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;\n });\n })\n .setInternalErrorMapping((error) => [error])\n .setDevtoolsEndpointGetter(gqlEndpointNameMapper)\n .setEndpointMapper(gqlEndpointMapper)\n .setFetcher(\n async ({\n request,\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);\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) clearTimeout(timeoutId);\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) break;\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 const errors = 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 (err: 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 onError({ error: err, status: 0, extra: gqlExtra });\n }\n },\n );\n","import { getGqlAdapter } from \"./http-adapter.fetch\";\nimport type { GraphqlAdapterType } from \"./adapter.types\";\n\nexport const GraphqlAdapter = (): GraphqlAdapterType => {\n return getGqlAdapter();\n};\n","import type { Adapter, EmptyTypes, QueryParamsType } 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 GraphqlAdapterType = Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n undefined,\n GraphQlEndpointType,\n (endpoint: GraphQlEndpointType) => string\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 { RequestInstance } from \"@hyper-fetch/core\";\nimport { HttpMethods, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { OperationDefinitionNode } from \"graphql\";\nimport { print, parse } from \"graphql\";\n\nimport type { GraphQlEndpointType } from \"adapter\";\n\nexport const getRequestValues = <R extends RequestInstance>(request: R) => {\n const isPostRequest = request.method === HttpMethods.POST;\n\n const query = request.endpoint;\n const variables = request.payload;\n\n const fullUrl = isPostRequest ? request.client.url : request.client.url + stringifyQueryParams({ query, variables });\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\nexport const gqlEndpointNameMapper = (endpoint: string): string => {\n try {\n const ast = parse(endpoint);\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 } catch (error) {\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 .replace(/[{}().,:]/g, \" \")\n .trim();\n const [name] = clearedQuery.split(\" \");\n\n return name || \"graphql-request\";\n};\n","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"],"mappings":";;;AAkBA,IAAa,sBACX,IAAI,QAQF;CACA,MAAM;CACN,eAAe,cAAc;CAC7B,cAAc;CACd,mBAAmB;CACnB,kBAAkB;CACnB,CAAC,CACC,cAAc,EAAE,aAAa;AAC5B,QAAO,mBAAmB,YAAY;AACpC,SAAO,GAAG,QAAQ,OAAO,GAAG,sBAAsB,QAAQ,SAAS,CAAC,GAAG,aAAa,QAAQ,OAAO,CAAC,GAAG,aAAa,QAAQ,YAAY;GACxI;AACF,QAAO,mBAAmB,YAAY;AACpC,SAAO,GAAG,QAAQ,OAAO,GAAG,sBAAsB,QAAQ,SAAS,CAAC,GAAG,aAAa,QAAQ,O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Aa,uBAA2C;AACtD,QAAO,eAAe;;;;ACDxB,IAAY,gBAAL,yBAAA,eAAA;AACL,eAAA,UAAA;AACA,eAAA,SAAA;;KACD;;;ACCD,IAAa,oBAA+C,YAAe;CACzE,MAAM,gBAAgB,QAAQ,WAAW,YAAY;CAErD,MAAM,QAAQ,QAAQ;CACtB,MAAM,YAAY,QAAQ;AAW1B,QAAO;EAAE,SATO,gBAAgB,QAAQ,OAAO,MAAM,QAAQ,OAAO,MAAM,qBAAqB;GAAE;GAAO;GAAW,CAAC;EASlG,SAPF,gBACZ,KAAK,UAAU;GACb;GACA;GACD,CAAC,GACF;EAEuB;;AAG7B,IAAa,qBAAoD,aAAwB;AACvF,KAAI,OAAO,aAAa,SACtB,QAAO;AAET,QAAO,MAAM,SAAS;;AAGxB,IAAa,yBAAyB,aAA6B;AACjE,KAAI;EAEF,MAAM,sBADM,MAAM,SAAS,CACK,YAAY,MACzC,QAAwC,IAAI,SAAS,sBACvD;AAED,MAAI,qBAAqB;AACvB,OAAI,oBAAoB,MAAM,MAC5B,QAAO,oBAAoB,KAAK;GAGlC,MAAM,YAAY,oBAAoB,aAAa,WAAW;AAC9D,OAAI,WAAW,SAAS,QACtB,QAAO,UAAU,KAAK;AAExB,OAAI,WAAW,SAAS,oBAAoB,UAAU,cACpD,QAAO,UAAU,cAAc,KAAK;;UAGjC,OAAO;CAShB,MAAM,CAAC,QAJc,SAClB,QAAQ,iCAAiC,GAAG,CAC5C,QAAQ,cAAc,IAAI,CAC1B,MAAM,CACmB,MAAM,IAAI;AAEtC,QAAO,QAAQ;;;;AC3DjB,IAAa,iBAAiB,KAAK,MAAM;AAEzC,IAAa,WAA6B;CACxC,SAAS,EAAE;CACX,YAAY,EAAE;CACf"}
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, EmptyTypes, QueryParamsType } 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 GraphqlAdapterType = Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n undefined,\n GraphQlEndpointType,\n (endpoint: GraphQlEndpointType) => string\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 { RequestInstance } from \"@hyper-fetch/core\";\nimport { HttpMethods, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { OperationDefinitionNode } from \"graphql\";\nimport { print, parse } from \"graphql\";\n\nimport type { GraphQlEndpointType } from \"./adapter.types\";\n\nexport const getRequestValues = <R extends RequestInstance>(request: R) => {\n const isPostRequest = request.method === HttpMethods.POST;\n\n const query = request.endpoint;\n const variables = request.payload;\n\n const fullUrl = isPostRequest ? request.client.url : request.client.url + stringifyQueryParams({ query, variables });\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\nexport const gqlEndpointNameMapper = (endpoint: string): string => {\n try {\n const ast = parse(endpoint);\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 } 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","import type { QueryParamsType } from \"@hyper-fetch/core\";\nimport { parseResponse, getErrorMessage, Adapter, stringifyKey } from \"@hyper-fetch/core\";\n\nimport { gqlExtra, defaultTimeout } from \"./adapter.constants\";\nimport type {\n GraphqlAdapterType,\n GraphQlExtraType,\n GraphQlEndpointType,\n FetchGraphqlAdapterOptionsType,\n} from \"./adapter.types\";\nimport { GraphqlMethod } from \"./adapter.types\";\nimport { getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper } from \"./adapter.utils\";\n\nexport const getGqlAdapter = (): GraphqlAdapterType =>\n new Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n undefined,\n GraphQlEndpointType\n >({\n name: \"graphql\",\n defaultMethod: GraphqlMethod.POST,\n defaultExtra: gqlExtra,\n systemErrorStatus: 0,\n systemErrorExtra: gqlExtra,\n })\n .onInitialize(({ client }) => {\n client.setCacheKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n });\n client.setQueryKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n });\n client.setAbortKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;\n });\n })\n .setInternalErrorMapping((error) => [error])\n .setDevtoolsEndpointGetter(gqlEndpointNameMapper)\n .setEndpointMapper(gqlEndpointMapper)\n .setFetcher(\n async ({\n request,\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);\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 const errors = 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 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,IAAa,oBAA+C,YAAe;CACzE,MAAM,gBAAgB,QAAQ,WAAW,YAAY;CAErD,MAAM,QAAQ,QAAQ;CACtB,MAAM,YAAY,QAAQ;AAW1B,QAAO;EAAE,SATO,gBAAgB,QAAQ,OAAO,MAAM,QAAQ,OAAO,MAAM,qBAAqB;GAAE;GAAO;GAAW,CAAC;EASlG,SAPF,gBACZ,KAAK,UAAU;GACb;GACA;GACD,CAAC,GACF;EAEuB;;AAG7B,IAAa,qBAAoD,aAAwB;AACvF,KAAI,OAAO,aAAa,SACtB,QAAO;AAET,QAAO,MAAM,SAAS;;AAGxB,IAAa,yBAAyB,aAA6B;AACjE,KAAI;EAEF,MAAM,sBADM,MAAM,SAAS,CACK,YAAY,MACzC,QAAwC,IAAI,SAAS,sBACvD;AAED,MAAI,qBAAqB;AACvB,OAAI,oBAAoB,MAAM,MAC5B,QAAO,oBAAoB,KAAK;GAGlC,MAAM,YAAY,oBAAoB,aAAa,WAAW;AAC9D,OAAI,WAAW,SAAS,QACtB,QAAO,UAAU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AAE,WAAW;EACnB,MAAM,SAAS,cAAc,KAAK;EAClC,MAAM,OAAO,QAAQ,QAAQ;EAC7B,MAAM,SAAS,QAAQ,UAAU;EACjC,MAAM,aAAa,QAAQ,cAAc,EAAE;AAG3C,MAFgB,UAAU,SAAS,OAAO,WAAW,EAInD,SAAQ;GAAE,OADI,UAAU,CAAC,iBAAiB,CAAC;GAC1B;GAAQ,OAAO;IAAE,SAAS;IAAiB;IAAY;GAAE,CAAC;MAE3E,WAAU;GACR;GACA,OAAO;GACP;GACA,OAAO;IAAE,SAAS;IAAiB;IAAY;GAChD,CAAC;UAEG,OAAY;AACnB,MAAI,UAAW,cAAa,UAAU;AACtC,mBAAiB;AAEjB,MAAI,YAAY,QAAQ,SAAS;AAC/B,OAAI,SACF,gBAAe;IAAE,QAAQ;IAAG,OAAO;IAAU,CAAC;AAEhD;;AAGF,UAAQ;GAAS;GAAO,QAAQ;GAAG,OAAO;GAAU,CAAC;;EAG1D;;;ACrLL,IAAa,uBAA2C;AACtD,QAAO,eAAe"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyper-fetch/graphql",
3
- "version": "8.1.1",
3
+ "version": "8.2.2",
4
4
  "description": "Simple graphql adapter",
5
5
  "author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
6
6
  "homepage": "https://hyperfetch.bettertyped.com/",
@@ -23,17 +23,17 @@
23
23
  },
24
24
  "scripts": {
25
25
  "test": "vitest run",
26
- "start": "yarn build && npx run-when-changed --watch 'src/**/*.ts' --exec 'yarn build'",
26
+ "start": "pnpm build && npx run-when-changed --watch 'src/**/*.ts' --exec 'pnpm build'",
27
27
  "build": "vite build",
28
- "lint": "eslint . --ext .js,.jsx,.tsx,.ts --fix",
29
- "format": "prettier --write .",
30
- "typecheck": "tsc --noEmit --emitDeclarationOnly false && tsc --noEmit -p __tests__/tsconfig.json",
31
- "tests": "yarn lint-staged",
32
- "release": "yarn semantic-release --extends ../../release.config.js -t 'hyper-fetch-graphql-v${version}'"
28
+ "lint": "oxlint .",
29
+ "format": "oxfmt --write .",
30
+ "typecheck": "tsgo --noEmit --emitDeclarationOnly false && tsgo --noEmit -p __tests__/tsconfig.json",
31
+ "tests": "pnpm lint-staged",
32
+ "release": "pnpm semantic-release --extends ../../release.config.js -t 'hyper-fetch-graphql-v${version}'"
33
33
  },
34
34
  "publishConfig": {
35
35
  "access": "public",
36
- "registry": "https://registry.npmjs.com/"
36
+ "registry": "https://registry.npmjs.org/"
37
37
  },
38
38
  "repository": {
39
39
  "type": "git",
@@ -1,5 +1,5 @@
1
- import { getGqlAdapter } from "./http-adapter.fetch";
2
1
  import type { GraphqlAdapterType } from "./adapter.types";
2
+ import { getGqlAdapter } from "./http-adapter.fetch";
3
3
 
4
4
  export const GraphqlAdapter = (): GraphqlAdapterType => {
5
5
  return getGqlAdapter();
@@ -3,7 +3,7 @@ import { HttpMethods, stringifyQueryParams } from "@hyper-fetch/core";
3
3
  import type { OperationDefinitionNode } from "graphql";
4
4
  import { print, parse } from "graphql";
5
5
 
6
- import type { GraphQlEndpointType } from "adapter";
6
+ import type { GraphQlEndpointType } from "./adapter.types";
7
7
 
8
8
  export const getRequestValues = <R extends RequestInstance>(request: R) => {
9
9
  const isPostRequest = request.method === HttpMethods.POST;
@@ -50,14 +50,14 @@ export const gqlEndpointNameMapper = (endpoint: string): string => {
50
50
  return selection.typeCondition.name.value;
51
51
  }
52
52
  }
53
- } catch (error) {
53
+ } catch {
54
54
  // We can ignore this error and just return some fallback
55
55
  }
56
56
 
57
57
  // Fallback for invalid gql queries or something else
58
58
  const clearedQuery = endpoint
59
59
  .replace(/(query|mutation|subscription)/, "")
60
- .replace(/[{}().,:]/g, " ")
60
+ .replaceAll(/[{}().,:]/g, " ")
61
61
  .trim();
62
62
  const [name] = clearedQuery.split(" ");
63
63
 
@@ -1,20 +1,15 @@
1
1
  import type { QueryParamsType } from "@hyper-fetch/core";
2
2
  import { parseResponse, getErrorMessage, Adapter, stringifyKey } from "@hyper-fetch/core";
3
3
 
4
+ import { gqlExtra, defaultTimeout } from "./adapter.constants";
4
5
  import type {
5
6
  GraphqlAdapterType,
6
7
  GraphQlExtraType,
7
8
  GraphQlEndpointType,
8
9
  FetchGraphqlAdapterOptionsType,
9
- } from "adapter";
10
- import {
11
- gqlExtra,
12
- defaultTimeout,
13
- getRequestValues,
14
- GraphqlMethod,
15
- gqlEndpointMapper,
16
- gqlEndpointNameMapper,
17
- } from "adapter";
10
+ } from "./adapter.types";
11
+ import { GraphqlMethod } from "./adapter.types";
12
+ import { getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper } from "./adapter.utils";
18
13
 
19
14
  export const getGqlAdapter = (): GraphqlAdapterType =>
20
15
  new Adapter<
@@ -109,7 +104,9 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
109
104
 
110
105
  const response = await fetch(fullUrl, init);
111
106
 
112
- if (timeoutId) clearTimeout(timeoutId);
107
+ if (timeoutId) {
108
+ clearTimeout(timeoutId);
109
+ }
113
110
 
114
111
  onResponseStart();
115
112
 
@@ -130,7 +127,9 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
130
127
  while (true) {
131
128
  // eslint-disable-next-line no-await-in-loop
132
129
  const { done, value } = await reader.read();
133
- if (done) break;
130
+ if (done) {
131
+ break;
132
+ }
134
133
  chunks.push(value);
135
134
  receivedLength += value.length;
136
135
  onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);
@@ -169,7 +168,7 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
169
168
  extra: { headers: responseHeaders, extensions },
170
169
  });
171
170
  }
172
- } catch (err: any) {
171
+ } catch (error: any) {
173
172
  if (timeoutId) clearTimeout(timeoutId);
174
173
  unmountListener();
175
174
 
@@ -180,7 +179,7 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
180
179
  return;
181
180
  }
182
181
 
183
- onError({ error: err, status: 0, extra: gqlExtra });
182
+ onError({ error: error, status: 0, extra: gqlExtra });
184
183
  }
185
184
  },
186
185
  );
package/tsconfig.json CHANGED
@@ -2,7 +2,11 @@
2
2
  "extends": "../../tsconfig.json",
3
3
  "compilerOptions": {
4
4
  "rootDir": ".",
5
- "baseUrl": "./src"
5
+ "types": ["node"],
6
+ "paths": {
7
+ "adapter": ["./src/adapter"],
8
+ "adapter/*": ["./src/adapter/*"]
9
+ }
6
10
  },
7
11
  "exclude": ["node_modules", "dist", "vite.config.ts", "__tests__"]
8
12
  }
package/vite.config.ts CHANGED
@@ -1,45 +1,39 @@
1
1
  /// <reference types="vitest/config" />
2
+ import path from "path";
2
3
  import { defineConfig } from "vite";
3
4
  import dts from "vite-plugin-dts";
4
5
  import tsconfigPaths from "vite-tsconfig-paths";
5
- import path from "path";
6
- import { getDtsCompilerOptionsForPackage } from "../../scripts/vite-dts-internal-paths";
6
+
7
7
  import { getRollupExternalsFromPackageJson } from "../../scripts/vite-lib-externals-from-package";
8
8
 
9
9
  export default defineConfig({
10
10
  build: {
11
11
  lib: {
12
12
  entry: "src/index.ts",
13
- formats: ["es"],
14
13
  fileName: "index",
14
+ formats: ["es"],
15
15
  },
16
- sourcemap: true,
17
16
  minify: false,
18
17
  rollupOptions: {
19
18
  external: [...getRollupExternalsFromPackageJson(__dirname), "graphql", "graphql-tag"],
20
19
  },
20
+ sourcemap: true,
21
21
  },
22
- plugins: [
23
- dts({
24
- entryRoot: "src",
25
- compilerOptions: getDtsCompilerOptionsForPackage(__dirname),
26
- }),
27
- tsconfigPaths(),
28
- ],
22
+ plugins: [tsconfigPaths(), dts({ entryRoot: "src" })],
29
23
  test: {
30
- globals: true,
31
- environment: "node",
32
- setupFiles: ["./__tests__/vitest.setup.ts"],
33
- include: ["__tests__/**/*.spec.{ts,tsx}", "src/**/*.spec.{ts,tsx}"],
34
- coverage: {
35
- provider: "v8",
36
- include: ["src/**/*.{ts,tsx}"],
37
- exclude: ["**/*.spec.*", "**/types.*", "**/constants.*", "**/index.ts"],
38
- },
39
24
  alias: {
40
25
  "@hyper-fetch/core": path.resolve(__dirname, "../core/src/index.ts"),
41
26
  "@hyper-fetch/sockets": path.resolve(__dirname, "../sockets/src/index.ts"),
42
27
  "@hyper-fetch/testing": path.resolve(__dirname, "../testing/src/index.ts"),
43
28
  },
29
+ coverage: {
30
+ exclude: ["**/*.spec.*", "**/types.*", "**/constants.*", "**/index.ts"],
31
+ include: ["src/**/*.{ts,tsx}"],
32
+ provider: "v8",
33
+ },
34
+ environment: "node",
35
+ globals: true,
36
+ include: ["__tests__/**/*.spec.{ts,tsx}", "src/**/*.spec.{ts,tsx}"],
37
+ setupFiles: ["./__tests__/vitest.setup.ts"],
44
38
  },
45
39
  });
@@ -1,11 +0,0 @@
1
- {
2
- "extends": ["plugin:@nx/react", "../../.eslintrc.js"],
3
- "parserOptions": {
4
- "project": ["./tsconfig.json"]
5
- },
6
- "rules": {
7
- "react/jsx-props-no-spreading": 0,
8
- "react/require-default-props": 0
9
- },
10
- "ignorePatterns": ["dist/", "coverage/", "vite.config.ts", "/*.js"]
11
- }
package/.eslintrc.cjs DELETED
@@ -1,12 +0,0 @@
1
- module.exports = {
2
- extends: ["plugin:@nx/react", "../../.eslintrc.js"],
3
- parserOptions: {
4
- tsconfigRootDir: __dirname,
5
- project: ["./tsconfig.json", "./__tests__/tsconfig.json"],
6
- },
7
- rules: {
8
- "react/jsx-props-no-spreading": 0,
9
- "react/require-default-props": 0,
10
- },
11
- ignorePatterns: ["dist/", "coverage/", "vite.config.ts", "/*.js"],
12
- };
@@ -1,8 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.json",
3
- "compilerOptions": {
4
- "rootDir": "./src",
5
- "baseUrl": "./src"
6
- },
7
- "exclude": ["dist", "vite.config.ts"]
8
- }