reactive-query-z 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,30 +1,28 @@
1
- # 📘 reactive-query-z
1
+ # 🚀 reactive-query-z
2
2
 
3
3
  [![NPM](https://img.shields.io/npm/v/reactive-query-z.svg)](https://www.npmjs.com/package/reactive-query-z)
4
4
  ![Downloads](https://img.shields.io/npm/dt/reactive-query-z.svg)
5
5
 
6
6
  ---
7
7
 
8
- **reactive-query-z** is a lightweight, reactive, and fully-featured data-fetching and state orchestration library for React.
9
- It is a **React Query alternative** with built-in support for REST, GraphQL, real-time subscriptions, caching, optimistic updates, and global query invalidation.
10
-
11
- ***Note:*** For full-featured query management, see [React Query](https://tanstack.com/query/v4)
8
+ **reactive-query-z** is a **lightweight**, reactive data-fetching library for React, built with hooks and TypeScript in mind.
9
+ Minimal API surface, predictable behavior, and production-ready features.
12
10
 
13
11
  [Live Example](https://codesandbox.io/p/sandbox/tmxkm5)
14
12
 
15
13
  ---
16
14
 
17
- ## Features
15
+ ###✨ Features
18
16
 
19
- * Lightweight and reactive, fully hook-based
20
- * Supports REST + GraphQL queries
21
- * Full CRUD support (POST/PUT/PATCH/DELETE)
22
- * Optimistic updates for smooth UI experience
23
- * Auto stale-time + background refetch
24
- * Global query invalidation
25
- * Real-time subscriptions via WebSocket / SSE
26
- * Cache + deduplication
27
- * Fully TypeScript-ready
17
+ * Lightweight & hook-based
18
+ * 🔁 REST + GraphQL support
19
+ * ✍️ Full CRUD mutations
20
+ * 💾 Cache with global invalidation
21
+ * 🚀 Optimistic UI updates
22
+ * ♻️ Stale-while-revalidate
23
+ * 📡 Real-time subscriptions (WebSocket / SSE)
24
+ * 🧩 Middleware system (auth, logging, retry, timeout…)
25
+ * 🧠 TypeScript-first API
28
26
 
29
27
  ---
30
28
 
@@ -43,60 +41,79 @@ yarn add reactive-query-z
43
41
  ### 1️⃣ Querying REST Data
44
42
 
45
43
  ```ts
46
- import { useQuery, queryRegistry } from "reactive-query-z";
44
+ import { useQuery } from "reactive-query-z";
47
45
 
48
- type User = { id: number; name: string };
46
+ type User = { id: string; title: string };
49
47
 
50
48
  function UserList() {
51
- const { data: users, loading, refetch, error } = useQuery<User[]>("/api/users", {
49
+ const {
50
+ data: users,
51
+ loading,
52
+ refetch,
53
+ error,
54
+ } = useQuery<User[]>("https://jsonplaceholder.typicode.com/posts", {
52
55
  cacheKey: "users-list",
53
- staleTime: 5000,
56
+ // staleTime: 5000,
57
+ cacheTime: 10000,
58
+ // autoFetch: true,
59
+ headers: { "Content-Type": "application/json" },
54
60
  });
55
61
 
56
62
  return (
57
63
  <div>
58
64
  {loading && <p>Loading...</p>}
59
65
  {error && <p>Error: {error.message}</p>}
66
+
67
+ <button onClick={() => refetch()}>Refetch</button>
68
+ <button onClick={() => queryRegistry.invalidate("users-list")}>
69
+ Invalidate
70
+ </button>
71
+
60
72
  <ul>
61
- {users?.map(u => (
62
- <li key={u.id}>{u.name}</li>
73
+ {users?.map((u) => (
74
+ <li key={u.id}>{u.title}</li>
63
75
  ))}
64
76
  </ul>
65
- <button onClick={refetch}>Refetch</button>
66
- <button onClick={() => queryRegistry.invalidate("users-list")}>Invalidate</button>
67
77
  </div>
68
78
  );
69
79
  }
70
-
71
80
  ```
72
81
 
73
82
  ---
74
83
 
75
- ### 2️⃣ GraphQL Queries with Real-time Subscription
84
+ ### 2️⃣ GraphQL Query
76
85
 
77
86
  ```ts
78
- import { useHybridQuery } from "reactive-query-z";
87
+ import { useGraphQLQuery } from "reactive-query-z";
88
+
89
+ type Country = { code: string; name: string; emoji: string };
90
+
91
+ export function CountriesList() {
92
+ const { data, loading, error, refetch } = useGraphQLQuery<{ countries: Country[] }>(
93
+ "https://countries.trevorblades.com/",
94
+ {
95
+ query: `
96
+ query {
97
+ countries { code name emoji }
98
+ }
99
+ `,
100
+ headers: { "Content-Type": "application/json" },
101
+ cacheKey: "countries",
102
+ // staleTime: 5000,
103
+ // autoFetch: true,
104
+ }
105
+ );
79
106
 
80
- type Message = { id: number; text: string };
81
-
82
- function MessageList() {
83
- const { data: messages } = useHybridQuery<Message[]>("/graphql", {
84
- query: `
85
- query GetMessages {
86
- messages { id text }
87
- }
88
- `,
89
- options: {
90
- cacheKey: "messages-list",
91
- subscriptionUrl: "ws://localhost:4000",
92
- optimisticUpdate: (prev, newData) => [...(prev || []), ...(newData || [])],
93
- staleTime: 3000,
94
- },
95
- });
107
+ if (loading) return <p>Loading...</p>;
108
+ if (error) return <p>{error.message}</p>;
96
109
 
97
110
  return (
98
111
  <ul>
99
- {messages?.map(m => <li key={m.id}>{m.text}</li>)}
112
+ <button disabled={loading} onClick={refetch}>Refetch</button>
113
+ <br />
114
+ {data?.countries?.map(c => (
115
+ <li key={c.code}>{c.name} {c.emoji}</li>
116
+ ))}
100
117
  </ul>
101
118
  );
102
119
  }
@@ -104,62 +121,93 @@ function MessageList() {
104
121
 
105
122
  ---
106
123
 
107
- ### 3️⃣ Mutations (CRUD)
124
+ ### 3️⃣ Mutations (REST)
108
125
 
109
126
  ```ts
110
127
  import { useMutation, queryRegistry } from "reactive-query-z";
111
128
 
112
- type User = { id: number; name: string };
129
+ type Post = {
130
+ userId: number;
131
+ id: number;
132
+ title: string;
133
+ body: string;
134
+ };
135
+
136
+ export function AddPost() {
137
+ const { mutate, loading } = useMutation<Post>(
138
+ "https://jsonplaceholder.typicode.com/posts",
139
+ {
140
+ cacheKey: "posts",
141
+ optimisticUpdate: (prev, newPost) => newPost,
142
+ onSuccess: () => queryRegistry.invalidate("posts"),
143
+ }
144
+ );
113
145
 
114
- function AddUserButton() {
115
- const { mutate: createUser } = useMutation<User>("/api/users", {
116
- cacheKey: "users-list",
117
- optimisticUpdate: (prev, newUser) => [...(prev || []), newUser],
118
- onSuccess: () => queryRegistry.invalidate("users-list"),
119
- });
146
+ const handleAdd = () => {
147
+ mutate({
148
+ title: "New Post",
149
+ body: "This is a new post",
150
+ userId: 1,
151
+ });
152
+ };
120
153
 
121
- return <button onClick={() => createUser({ name: "New User" })}>Add User</button>;
154
+ return (
155
+ <button onClick={handleAdd} disabled={loading}>
156
+ {loading ? "Adding..." : "Add Post"}
157
+ </button>
158
+ );
122
159
  }
123
160
  ```
124
161
 
125
162
  ---
126
163
 
127
- ### 4️⃣ GraphQL Mutations
164
+ ### 4️⃣ GraphQL Mutation
128
165
 
129
166
  ```ts
130
- import { useGraphQLMutation, queryRegistry } from "reactive-query-z";
131
-
132
- type Message = { id: number; text: string };
133
-
134
- function SendMessageButton() {
135
- const { mutate } = useGraphQLMutation<{ createMessage: Message }>("/graphql", {
136
- mutation: `
137
- mutation CreateMessage($text: String!) {
138
- createMessage(text: $text) { id text }
139
- }
140
- `,
141
- variables: { text: "Hello world!" },
142
- cacheKey: "messages-list",
143
- optimisticUpdate: (prev, newData) => [...(prev || []), newData.createMessage],
144
- onSuccess: () => queryRegistry.invalidate("messages-list"),
145
- });
167
+ export function AddPostGraphQL() {
168
+ const { mutate, loading, error } = useGraphQLMutation(
169
+ "https://graphqlzero.almansi.me/api",
170
+ {
171
+ mutation: `
172
+ mutation ($title: String!, $body: String!, $userId: ID!) {
173
+ createPost(input: { title: $title, body: $body, userId: $userId }) {
174
+ id
175
+ title
176
+ body
177
+ }
178
+ }
179
+ `,
180
+ variables: { title: "Hello", body: "World", userId: 122 },
181
+ headers: { "Content-Type": "application/json" },
182
+ // cacheKey: "postsGraphQL",
183
+ onSuccess: () => queryRegistry.invalidate("postsGraphQL"),
184
+ onError: (err) => console.error("Mutation error", err),
185
+ }
186
+ );
146
187
 
147
- return <button onClick={() => mutate()}>Send Message</button>;
188
+ return (
189
+ <button onClick={mutate} disabled={loading}>
190
+ {loading ? "Adding..." : "Add Post"}
191
+ </button>
192
+ );
148
193
  }
149
194
  ```
150
195
 
151
196
  ---
152
197
 
153
- ### 5️⃣ Global Query Invalidation
198
+ ### 5️⃣ Global Query Invalidation & GlobalError
154
199
 
155
200
  ```ts
156
- import { queryRegistry } from "reactive-query-z";
201
+ import { queryRegistry, setGlobalErrorHandler } from "reactive-query-z";
157
202
 
158
- // Invalidate a specific query
159
- queryRegistry.invalidate("users-list");
203
+ queryRegistry.invalidate("users"); // specific
204
+ queryRegistry.invalidate(); // all queries
160
205
 
161
- // Invalidate all queries
162
- queryRegistry.invalidate();
206
+ // Setup a global error handler
207
+ setGlobalErrorHandler((error, info) => {
208
+ console.error("Global fetch error:", error, info);
209
+ // You can show a toast, modal, or redirect to login here
210
+ });
163
211
  ```
164
212
 
165
213
  ---
@@ -169,9 +217,11 @@ queryRegistry.invalidate();
169
217
  ```ts
170
218
  import { useHybridQuery } from "reactive-query-z";
171
219
 
172
- const { data } = useHybridQuery<Message[]>('/graphql', {
220
+ const { data } = useHybridQuery("/graphql", {
173
221
  subscriptionUrl: "ws://localhost:4000",
174
- cacheKey: "messages-list",
222
+ cacheKey: "messages",
223
+ // optimisticUpdate: (prev, next) => [...(prev || []), next],
224
+ // autoFetch: true,
175
225
  });
176
226
  ```
177
227
 
@@ -179,125 +229,27 @@ const { data } = useHybridQuery<Message[]>('/graphql', {
179
229
 
180
230
  ## 🔧 API Reference
181
231
 
182
- ### `useQuery<T>(endpoint: string, options?: QueryOptions)`
183
-
184
- ```ts
185
- interface QueryOptions {
186
- cacheKey?: string;
187
- staleTime?: number; // polling interval in ms
188
- autoRefetch?: boolean;
189
- interval?: number; // auto refetch interval
190
- timeout?: number; // request timeout in ms
191
- headers?: Record<string, string>;
192
- retry?: number; // number of retries
193
- retryDelay?: number; // initial retry delay in ms
194
- optimisticUpdate?: <T>(prevData: T | null, newData: T) => T;
195
- }
196
- ```
197
- Returns:
198
-
199
- ```ts
200
- {
201
- data: T | null;
202
- error: Error | null;
203
- loading: boolean;
204
- start: () => Promise<T | null>; // initial / manual fetch
205
- refetch: () => Promise<T | null>; // with retry
206
- setData: (data: T) => void; // manual update
207
- cancel: () => void; // cancel in-flight request
208
- }
209
- ```
210
-
211
- ---
212
-
213
- ### `useHybridQuery<T>(endpoint: string, options: HybridQueryParams<T>)`
214
-
215
- ```ts
216
- interface HybridQueryParams<T> {
217
- query?: string; // GraphQL query string
218
- variables?: Record<string, any>;
219
- options?: {
220
- cacheKey?: string;
221
- staleTime?: number; // ms
222
- subscriptionUrl?: string; // WebSocket / SSE
223
- optimisticUpdate?: (prev: T | null, newData: T) => T;
224
- headers?: Record<string, string>;
225
- retry?: number;
226
- retryDelay?: number;
227
- };
228
- }
229
- ```
230
-
231
- Returns:
232
-
233
- ```ts
234
- {
235
- data: T | null;
236
- error: Error | null;
237
- loading: boolean;
238
- refetch: () => Promise<T | null>;
239
- mutate: (data: T) => void; // optimistic update
240
- cancel: () => void;
241
- }
242
- ```
243
-
244
- ---
245
-
246
- ### `useMutation<T>(endpoint: string, options?: MutationOptions<T>)`
247
-
248
- ```ts
249
- interface MutationOptions<T> {
250
- cacheKey?: string;
251
- optimisticUpdate?: (prevData: any, newData: T) => any;
252
- onSuccess?: (data: T) => void;
253
- onError?: (error: any) => void;
254
- retry?: number;
255
- retryDelay?: number;
256
- headers?: Record<string, string>;
257
- }
258
- ```
259
-
260
- Returns:
261
-
262
- ```ts
263
- {
264
- mutate: (body: any, method?: "POST" | "PUT" | "PATCH" | "DELETE") => Promise<T>;
265
- loading: boolean;
266
- error: any;
267
- cancel: () => void;
268
- }
269
- ```
270
-
271
- ---
272
-
273
- ### `useGraphQLMutation<T>(endpoint: string, options: GraphQLMutationOptions<T>)`
274
-
275
232
  ```ts
276
- interface GraphQLMutationOptions<T> {
277
- mutation: string;
278
- variables?: Record<string, any>;
279
- cacheKey?: string;
280
- optimisticUpdate?: (prev: T | undefined, newData: T) => T;
281
- retry?: number;
282
- retryDelay?: number;
283
- headers?: Record<string, string>;
284
- }
285
-
286
- ```
287
- Returns:
288
-
289
- ```ts
290
- {
291
- mutate: () => Promise<T>;
292
- cancel: () => void;
293
- }
233
+ useQuery
234
+ useMutation
235
+ useGraphQLQuery
236
+ useGraphQLMutation
237
+ useHybridQuery
238
+ queryRegistry
239
+
240
+ prefetchQuery
241
+ prefetchData
242
+ fetchWithRetry
243
+ commonFetch
244
+ prefetchQuery
245
+ setGlobalErrorHandler
294
246
  ```
295
247
 
296
248
  ---
297
249
 
298
250
  ## ⚖️ Comparison with Other Libraries
299
251
 
300
- | Feature | reactive-fetch | React Query | SWR | Apollo Client |
252
+ | Feature | reactive-query-z | React Query | SWR | Apollo Client |
301
253
  | -------------------------- | ------------------ | ----------- | ---- | ------------- |
302
254
  | REST support | ✅ | ✅ | ✅ | ⚠️ Partial |
303
255
  | GraphQL support | ✅ | ⚠️ Plugin | ❌ | ✅ |
@@ -312,6 +264,19 @@ Returns:
312
264
 
313
265
  ---
314
266
 
267
+ ## 🤔 Why reactive-query-z?
268
+
269
+ * You may want reactive-query-z if:
270
+ * You want React Query–like power but with simpler internals
271
+ * You need REST + GraphQL without separate clients
272
+ * You want middleware control over every request
273
+ * You prefer explicit cache keys & invalidation
274
+ * You want something easy to read, debug, and extend
275
+
276
+ ***Note:*** For full-featured query management, see [React Query](https://tanstack.com/query/v4)
277
+
278
+ ---
279
+
315
280
  ## 📜 License
316
281
 
317
282
  MIT
@@ -1,6 +1,6 @@
1
1
  export declare const cache: {
2
- get: <T>(key: string) => T | undefined;
3
- set: <T_1>(key: string, data: T_1) => void;
4
- delete: (key: string) => void;
5
- clear: () => void;
2
+ set<TData>(key: string, data: TData, ttl?: number): void;
3
+ get<TData_1>(key: string): TData_1 | undefined;
4
+ delete(key: string): void;
5
+ clear(): void;
6
6
  };
@@ -1,5 +1,2 @@
1
- type QueryOptions = RequestInit & {
2
- cacheKey?: string;
3
- };
4
- export declare function fetcher<T>(url: string, options?: QueryOptions): Promise<T>;
5
- export {};
1
+ import { FetchQueryOptions } from "./globalConfig";
2
+ export declare function fetcher<TData>(url: string, options?: FetchQueryOptions): Promise<TData>;
@@ -0,0 +1,23 @@
1
+ export type FetchQueryOptions = RequestInit & {
2
+ autoFetch?: boolean;
3
+ cacheKey?: string;
4
+ cacheTime?: number;
5
+ staleTime?: number;
6
+ baseURL?: string;
7
+ headers?: Record<string, string>;
8
+ isGraphQL?: boolean;
9
+ };
10
+ export interface GlobalConfig {
11
+ baseURL?: string;
12
+ headers?: Record<string, string>;
13
+ retry?: number;
14
+ retryDelay?: number;
15
+ timeout?: number;
16
+ interceptors?: {
17
+ onRequest?: (url: string, options: FetchQueryOptions) => FetchQueryOptions;
18
+ onResponse?: <TData>(data: TData) => TData;
19
+ onError?: (err: any) => void;
20
+ };
21
+ }
22
+ export declare function setGlobalConfig(newConfig: GlobalConfig): void;
23
+ export declare function getGlobalConfig(): GlobalConfig;
@@ -1,8 +1,12 @@
1
1
  export declare const queryRegistry: {
2
- register: <T = any>(cacheKey: string, refetch: () => void, setData?: ((updater: (prev?: T | undefined) => T) => void) | undefined, cancel?: () => void, initialCache?: T | undefined) => void;
3
- getCache: <T_1 = any>(cacheKey: string) => T_1 | undefined;
4
- setCache: <T_2 = any>(cacheKey: string, value: T_2) => void;
5
- setData: <T_3 = any>(cacheKey: string, updater: (prev?: T_3 | undefined) => T_3) => void;
2
+ register: <TData = any>(cacheKey: string, refetch: () => void, setData?: ((updater: (prev?: TData | undefined) => TData) => void) | undefined, cancel?: () => void, initialCache?: TData | undefined) => void;
3
+ getCache: <TData_1 = any>(cacheKey: string) => TData_1 | undefined;
4
+ setCache: <TData_2 = any>(cacheKey: string, value: TData_2, options?: {
5
+ skip?: () => void;
6
+ }) => void;
7
+ setData: <TData_3 = any>(cacheKey: string, updater: (prev?: TData_3 | undefined) => TData_3, options?: {
8
+ skip?: () => void;
9
+ }) => void;
6
10
  cancel: (cacheKey: string) => void;
7
11
  invalidate: (cacheKey?: string) => void;
8
12
  unregister: (cacheKey: string) => void;
@@ -1,11 +1,11 @@
1
- type Callback<T> = (data: T) => void;
2
- export declare class SubscriptionManager<T> {
1
+ type Callback<TData> = (data: TData) => void;
2
+ export declare class SubscriptionManager<TData> {
3
3
  private url;
4
4
  private callbacks;
5
5
  private ws;
6
6
  constructor(url: string);
7
7
  connect(): void;
8
- subscribe(cb: Callback<T>): () => boolean;
8
+ subscribe(cb: Callback<TData>): () => boolean;
9
9
  disconnect(): void;
10
10
  }
11
11
  export {};
@@ -0,0 +1,32 @@
1
+ export interface CommonOptions<TData = any, TVariables = Record<string, any>> {
2
+ cacheKey?: string;
3
+ headers?: Record<string, string>;
4
+ timeout?: number;
5
+ cacheTime?: number;
6
+ retry?: number;
7
+ retryDelay?: number;
8
+ optimisticUpdate?: (prevData: TData | null | undefined, newData: TData) => TData;
9
+ signal?: AbortSignal;
10
+ variables?: TVariables;
11
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
12
+ }
13
+ export interface QueryOptions<TData, TVariables = Record<string, any>> extends CommonOptions<TData, TVariables> {
14
+ staleTime?: number;
15
+ autoFetch?: boolean;
16
+ prefetch?: boolean;
17
+ }
18
+ export interface GraphQueryOptions<TData, TVariables = Record<string, any>> extends QueryOptions<TData, TVariables> {
19
+ query: string;
20
+ }
21
+ export interface HybridQueryOptions<TData, TVariables = Record<string, any>> extends QueryOptions<TData, TVariables> {
22
+ subscriptionUrl?: string;
23
+ onSuccess?: (data: TData) => void;
24
+ onError?: (error: any) => void;
25
+ }
26
+ export interface MutationOptions<TData, TVariables = Record<string, any>> extends CommonOptions<TData, TVariables> {
27
+ onSuccess?: (data: TData) => void;
28
+ onError?: (error: any) => void;
29
+ }
30
+ export interface GraphQLMutationOptions<TData, TVariables = Record<string, any>> extends MutationOptions<TData, TVariables> {
31
+ mutation: string;
32
+ }
@@ -1,14 +1,7 @@
1
- export interface GraphQLMutationOptions<TData, TVariables = any> {
2
- mutation: string;
3
- variables?: TVariables;
4
- cacheKey?: string;
5
- retry?: number;
6
- retryDelay?: number;
7
- headers?: Record<string, string>;
8
- timeout?: number;
9
- optimisticUpdate?: (prev: TData | undefined, newData: TData) => TData;
10
- }
11
- export declare function useGraphQLMutation<TData, TVariables = any>(endpoint: string, options: GraphQLMutationOptions<TData, TVariables>): {
12
- mutate: () => Promise<TData>;
1
+ import { GraphQLMutationOptions } from "./types";
2
+ export declare function useGraphQLMutation<TData, TVariables extends Record<string, any> = {}>(endpoint: string, options: GraphQLMutationOptions<TData, TVariables>): {
3
+ mutate: () => Promise<TData | null>;
4
+ loading: boolean;
5
+ error: Error | null;
13
6
  cancel: () => void;
14
7
  };
@@ -1,23 +1,10 @@
1
1
  /// <reference types="react" />
2
- export interface GraphQueryOptions<T> {
3
- query: string;
4
- variables?: Record<string, any>;
5
- cacheKey?: string;
6
- staleTime?: number;
7
- headers?: Record<string, string>;
8
- timeout?: number;
9
- retry?: number;
10
- retryDelay?: number;
11
- autoFetch?: boolean;
12
- prefetch?: boolean;
13
- method?: "GET" | "POST";
14
- optimisticUpdate?: (prevData: T | null, newData: T) => T;
15
- }
16
- export declare function useGraphQLQuery<T>(endpoint: string, options: GraphQueryOptions<T>): {
17
- data: T | null;
2
+ import { GraphQueryOptions } from "./types";
3
+ export declare function useGraphQLQuery<TData>(endpoint: string, options: GraphQueryOptions<TData>): {
4
+ data: TData | null;
18
5
  error: Error | null;
19
6
  loading: boolean;
20
- refetch: () => Promise<T | null>;
21
- mutate: import("react").Dispatch<import("react").SetStateAction<T | null>>;
22
- cancel: () => void | undefined;
7
+ refetch: () => Promise<TData | null>;
8
+ mutate: import("react").Dispatch<import("react").SetStateAction<TData | null>>;
9
+ cancel: () => void;
23
10
  };
@@ -1,28 +1,14 @@
1
1
  /// <reference types="react" />
2
- export interface HybridQueryOptions<T> {
3
- cacheKey?: string;
4
- optimisticUpdate?: (prevData: T | null, newData: T) => T;
5
- staleTime?: number;
6
- subscriptionUrl?: string;
7
- retry?: number;
8
- retryDelay?: number;
9
- headers?: Record<string, string>;
10
- timeout?: number;
11
- autoFetch?: boolean;
12
- prefetch?: boolean;
13
- method?: "GET" | "POST";
14
- }
15
- export interface HybridQueryParams<T> {
2
+ import { HybridQueryOptions } from "./types";
3
+ export declare function useHybridQuery<TData>(endpoint: string, { query, variables, options, }: {
16
4
  query?: string;
17
5
  variables?: Record<string, any>;
18
- options?: HybridQueryOptions<T>;
19
- }
20
- export declare function prefetchQuery<T>(endpoint: string, query?: string, variables?: Record<string, any>, cacheKey?: string, headers?: Record<string, string>, method?: "GET" | "POST"): Promise<T | null>;
21
- export declare function useHybridQuery<T>(endpoint: string, { query, variables, options }: HybridQueryParams<T>): {
22
- data: T | null;
6
+ options?: HybridQueryOptions<TData>;
7
+ }): {
8
+ data: TData | null;
23
9
  error: Error | null;
24
10
  loading: boolean;
25
- refetch: () => Promise<T | null>;
26
- mutate: import("react").Dispatch<import("react").SetStateAction<T | null>>;
27
- cancel: () => void | undefined;
11
+ refetch: () => Promise<TData | null>;
12
+ mutate: import("react").Dispatch<import("react").SetStateAction<TData | null>>;
13
+ cancel: () => void;
28
14
  };
@@ -1,16 +1,7 @@
1
- export interface MutationOptions<T> {
2
- cacheKey?: string;
3
- optimisticUpdate?: (prevData: any, newData: T) => any;
4
- onSuccess?: (data: T) => void;
5
- onError?: (error: any) => void;
6
- retry?: number;
7
- retryDelay?: number;
8
- headers?: Record<string, string>;
9
- timeout?: number;
10
- }
11
- export declare function useMutation<T = any>(endpoint: string, options?: MutationOptions<T>): {
12
- mutate: (body: any, method?: "POST" | "PUT" | "PATCH" | "DELETE") => Promise<T>;
1
+ import { MutationOptions } from "./types";
2
+ export declare function useMutation<TData = any>(endpoint: string, options?: Omit<MutationOptions<TData>, "query" | "variables">): {
3
+ mutate: (body: any, method?: "POST" | "PUT" | "PATCH" | "DELETE") => Promise<TData>;
13
4
  loading: boolean;
14
5
  error: any;
15
- cancel: () => void | undefined;
6
+ cancel: () => void;
16
7
  };
@@ -1,22 +1,10 @@
1
1
  /// <reference types="react" />
2
- export interface QueryOptions<T> {
3
- variables?: Record<string, any>;
4
- cacheKey?: string;
5
- staleTime?: number;
6
- headers?: Record<string, string>;
7
- timeout?: number;
8
- retry?: number;
9
- retryDelay?: number;
10
- autoFetch?: boolean;
11
- prefetch?: boolean;
12
- method?: "GET" | "POST";
13
- optimisticUpdate?: (prevData: T | null, newData: T) => T;
14
- }
15
- export declare function useQuery<T>(endpoint: string, options: QueryOptions<T>): {
16
- data: T | null;
2
+ import { QueryOptions } from "./types";
3
+ export declare function useQuery<TData>(endpoint: string, options: Omit<QueryOptions<TData>, "query" | "variables">): {
4
+ data: TData | null;
17
5
  error: Error | null;
18
6
  loading: boolean;
19
- refetch: () => Promise<T | null>;
20
- mutate: import("react").Dispatch<import("react").SetStateAction<T | null>>;
21
- cancel: () => void | undefined;
7
+ refetch: () => Promise<TData | null>;
8
+ mutate: import("react").Dispatch<import("react").SetStateAction<TData | null>>;
9
+ cancel: () => void;
22
10
  };
package/build/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=function(){return t=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},t.apply(this,arguments)};function r(e,t,r,n){return new(r||(r=Promise))(function(i,a){function c(e){try{o(n.next(e))}catch(e){a(e)}}function u(e){try{o(n.throw(e))}catch(e){a(e)}}function o(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(c,u)}o((n=n.apply(e,t||[])).next())})}function n(e,t){var r,n,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},c=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return c.next=u(0),c.throw=u(1),c.return=u(2),"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function u(u){return function(o){return function(u){if(r)throw new TypeError("Generator is already executing.");for(;c&&(c=0,u[0]&&(a=0)),a;)try{if(r=1,n&&(i=2&u[0]?n.return:u[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,u[1])).done)return i;switch(n=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return a.label++,{value:u[1],done:!1};case 5:a.label++,n=u[1],u=[0];continue;case 7:u=a.ops.pop(),a.trys.pop();continue;default:if(!(i=a.trys,(i=i.length>0&&i[i.length-1])||6!==u[0]&&2!==u[0])){a=0;continue}if(3===u[0]&&(!i||u[1]>i[0]&&u[1]<i[3])){a.label=u[1];break}if(6===u[0]&&a.label<i[1]){a.label=i[1],i=u;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(u);break}i[2]&&a.ops.pop(),a.trys.pop();continue}u=t.call(e,a)}catch(e){u=[6,e],n=0}finally{r=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([u,o])}}}"function"==typeof SuppressedError&&SuppressedError;var i=new Map,a={get:function(e){var t=i.get(e);if(t)return t.data},set:function(e,t){i.set(e,{data:t,timestamp:Date.now()})},delete:function(e){i.delete(e)},clear:function(){return i.clear()}},c=new Map;function u(e,t){return void 0===t&&(t={}),r(this,void 0,void 0,function(){var i,u,o,s=this;return n(this,function(l){return i=t.cacheKey||e,c.has(i)?[2,c.get(i)]:(u=a.get(i))?[2,u]:(o=fetch(e,t).then(function(e){return r(s,void 0,void 0,function(){var t;return n(this,function(r){switch(r.label){case 0:if(!e.ok)throw new Error(e.statusText);return[4,e.json()];case 1:return t=r.sent(),a.set(i,t),[2,t]}})})}).finally(function(){return c.delete(i)}),c.set(i,o),[2,o])})})}var o=new Map,s={register:function(e,t,r,n,i){o.set(e,{cacheKey:e,refetch:t,setData:r,cancel:n,cache:i})},getCache:function(e){var t;return null===(t=o.get(e))||void 0===t?void 0:t.cache},setCache:function(e,t){var r,n=o.get(e);n&&(n.cache=t,null===(r=n.setData)||void 0===r||r.call(n,function(){return t}))},setData:function(e,t){var r,n=o.get(e);if(n){var i=t(n.cache);n.cache=i,null===(r=n.setData)||void 0===r||r.call(n,function(){return i})}},cancel:function(e){var t,r;null===(r=null===(t=o.get(e))||void 0===t?void 0:t.cancel)||void 0===r||r.call(t)},invalidate:function(e){var t;e?null===(t=o.get(e))||void 0===t||t.refetch():o.forEach(function(e){return e.refetch()})},unregister:function(e){var t,r;null===(r=null===(t=o.get(e))||void 0===t?void 0:t.cancel)||void 0===r||r.call(t),o.delete(e)}},l=function(){function e(e){this.url=e,this.callbacks=new Set,this.ws=null}return e.prototype.connect=function(){var e=this;this.ws||(this.ws=new WebSocket(this.url),this.ws.onmessage=function(t){var r=JSON.parse(t.data);e.callbacks.forEach(function(e){return e(r)})})},e.prototype.subscribe=function(e){var t=this;return this.callbacks.add(e),this.connect(),function(){return t.callbacks.delete(e)}},e.prototype.disconnect=function(){var e;null===(e=this.ws)||void 0===e||e.close(),this.ws=null,this.callbacks.clear()},e}();function h(e,t,i){return r(this,void 0,void 0,function(){var r;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,4]),[4,e()];case 1:return[2,n.sent()];case 2:if(r=n.sent(),t<=0)throw r;return[4,new Promise(function(e){return setTimeout(e,i)})];case 3:return n.sent(),[2,h(e,t-1,2*i)];case 4:return[2]}})})}function d(e){var t=new AbortController,r=setTimeout(function(){return t.abort()},e);return t.signal.addEventListener("abort",function(){return clearTimeout(r)}),t.signal}function f(e,t,r){e&&(s.setData(e,function(e){return t?t(e,r):r}),s.invalidate(e))}function v(e,t,i,a,c,u){return r(this,void 0,void 0,function(){var r,o;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,y(e,t,i,{headers:c,cacheKey:a,method:u})];case 1:return r=n.sent(),a&&s.setCache(a,r),[2,r];case 2:return o=n.sent(),console.error("Prefetch failed",o),[2,null];case 3:return[2]}})})}function p(t,i){var a=this,c=i.query,u=i.variables,o=i.options,p=void 0===o?{}:o,b=e.useState(null),m=b[0],w=b[1],g=e.useState(null),K=g[0],S=g[1],x=e.useState(!1),C=x[0],T=x[1],k=e.useRef(null),U=e.useCallback(function(){return r(a,void 0,void 0,function(){var e,i,a,o,s,l=this;return n(this,function(v){switch(v.label){case 0:T(!0),S(null),null===(o=k.current)||void 0===o||o.abort(),e=new AbortController,k.current=e,i=d(null!==(s=p.timeout)&&void 0!==s?s:1e4),a=function(e,d){return void 0===e&&(e=null!==(o=p.retry)&&void 0!==o?o:3),void 0===d&&(d=null!==(s=p.retryDelay)&&void 0!==s?s:500),r(l,void 0,void 0,function(){var r,o;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,y(t,c,u,{headers:p.headers,cacheKey:p.cacheKey,method:p.method,signal:i})];case 1:return r=n.sent(),w(function(e){return p.optimisticUpdate?p.optimisticUpdate(e,r):r}),f(p.cacheKey,p.optimisticUpdate,r),[2,r];case 2:if("AbortError"===(o=n.sent()).name)throw o;return[2,h(function(){return a(e-1,2*d)},e-1,2*d)];case 3:return[2]}})})},v.label=1;case 1:return v.trys.push([1,,3,4]),[4,a()];case 2:return[2,v.sent()];case 3:return T(!1),[7];case 4:return[2]}})})},[t,c,u,p.cacheKey,p.optimisticUpdate,p.retry,p.retryDelay,p.headers,p.timeout,p.method]),D=e.useCallback(function(){var e;return null===(e=k.current)||void 0===e?void 0:e.abort()},[]);return e.useEffect(function(){var e=!0;return r(a,void 0,void 0,function(){var r;return n(this,function(n){switch(n.label){case 0:return p.prefetch&&p.cacheKey?(r=s.getCache(p.cacheKey))?(w(r),[3,3]):[3,1]:[3,3];case 1:return[4,v(t,c,u,p.cacheKey,p.headers,p.method)];case 2:n.sent(),n.label=3;case 3:return p.autoFetch&&e&&U(),[2]}})}),p.cacheKey&&s.register(p.cacheKey,U,w,D),function(){p.cacheKey&&s.unregister(p.cacheKey),D(),e=!1}},[t,c,u,p.prefetch,p.autoFetch,p.cacheKey,p.method]),e.useEffect(function(){if(p.staleTime){var e=setInterval(U,p.staleTime);return function(){return clearInterval(e)}}},[U,p.staleTime]),e.useEffect(function(){if(p.subscriptionUrl){var e=new l(p.subscriptionUrl).subscribe(function(e){w(function(t){return p.optimisticUpdate?p.optimisticUpdate(t,e):e}),f(p.cacheKey,p.optimisticUpdate,e)});return function(){return e()}}},[p.subscriptionUrl,p.optimisticUpdate,p.cacheKey]),{data:m,error:K,loading:C,refetch:U,mutate:w,cancel:D}}function y(e,i,a,c){var o;return r(this,void 0,void 0,function(){var r;return n(this,function(n){switch(n.label){case 0:return i?[4,u(e,{method:"POST",headers:t({"Content-Type":"application/json"},null==c?void 0:c.headers),body:JSON.stringify({query:i,variables:a}),cacheKey:null==c?void 0:c.cacheKey,signal:null==c?void 0:c.signal})]:[3,2];case 1:return[2,n.sent().data];case 2:return r=null!==(o=null==c?void 0:c.method)&&void 0!==o?o:"GET",[4,u(e,{method:r,headers:null==c?void 0:c.headers,cacheKey:null==c?void 0:c.cacheKey,signal:null==c?void 0:c.signal})];case 3:return[2,n.sent()]}})})}exports.SubscriptionManager=l,exports.cache=a,exports.createTimeoutSignal=d,exports.queryRegistry=s,exports.retryOperation=h,exports.updateCache=f,exports.useGraphQLMutation=function(i,a){var c=this,o=a.mutation,l=a.variables,f=a.cacheKey,v=a.optimisticUpdate,p=a.retry,y=void 0===p?3:p,b=a.retryDelay,m=void 0===b?500:b,w=a.headers,g=a.timeout,K=void 0===g?1e4:g,S=e.useRef(null),x=e.useCallback(function(){return r(c,void 0,void 0,function(){var e,a,c,p,b=this;return n(this,function(g){switch(g.label){case 0:null===(p=S.current)||void 0===p||p.abort(),e=new AbortController,S.current=e,a=d(K),c=function(e,d){return r(b,void 0,void 0,function(){var r,p;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,u(i,{method:"POST",headers:t({"Content-Type":"application/json"},w),body:JSON.stringify({query:o,variables:l}),signal:a,cacheKey:f})];case 1:return r=n.sent(),v&&f&&s.setData(f,function(e){return v(e,r.data)}),f&&s.invalidate(f),[2,r.data];case 2:if("AbortError"===(p=n.sent()).name)throw p;return[2,h(function(){return c(e-1,2*d)},e-1,2*d)];case 3:return[2]}})})},g.label=1;case 1:return g.trys.push([1,,3,4]),[4,c(y,m)];case 2:return[2,g.sent()];case 3:return[7];case 4:return[2]}})})},[i,o,l,f,v,y,m,w,K]),C=e.useCallback(function(){var e;null===(e=S.current)||void 0===e||e.abort()},[]);return{mutate:x,cancel:C}},exports.useGraphQLQuery=function(e,t){return p(e,{query:t.query,variables:t.variables,options:{cacheKey:t.cacheKey,staleTime:t.staleTime,headers:t.headers,timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay,optimisticUpdate:t.optimisticUpdate}})},exports.useHybridQuery=p,exports.useMutation=function(i,a){var c=this,o=e.useState(!1),l=o[0],f=o[1],v=e.useState(null),p=v[0],y=v[1],b=e.useRef(null),m=e.useCallback(function(e,o){return void 0===o&&(o="POST"),r(c,void 0,void 0,function(){var c,l,v,p,m,w=this;return n(this,function(g){switch(g.label){case 0:f(!0),y(null),null===(p=b.current)||void 0===p||p.abort(),c=new AbortController,b.current=c,l=d(null!==(m=null==a?void 0:a.timeout)&&void 0!==m?m:1e4),v=function(c,d){return void 0===c&&(c=null!==(p=null==a?void 0:a.retry)&&void 0!==p?p:3),void 0===d&&(d=null!==(m=null==a?void 0:a.retryDelay)&&void 0!==m?m:500),r(w,void 0,void 0,function(){var r,f,p;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,u(i,{method:o,headers:t({"Content-Type":"application/json"},null==a?void 0:a.headers),body:JSON.stringify(e),cacheKey:null==a?void 0:a.cacheKey,signal:l})];case 1:return r=n.sent(),(null==a?void 0:a.optimisticUpdate)&&a.cacheKey&&(s.setData(a.cacheKey,function(e){return a.optimisticUpdate(e,r)}),s.invalidate(a.cacheKey)),null===(p=null==a?void 0:a.onSuccess)||void 0===p||p.call(a,r),[2,r];case 2:if("AbortError"===(f=n.sent()).name)throw f;return[2,h(function(){return v(c-1,2*d)},c-1,2*d)];case 3:return[2]}})})},g.label=1;case 1:return g.trys.push([1,,3,4]),[4,v()];case 2:return[2,g.sent()];case 3:return f(!1),[7];case 4:return[2]}})})},[i,a]),w=e.useCallback(function(){var e;return null===(e=b.current)||void 0===e?void 0:e.abort()},[]);return{mutate:m,loading:l,error:p,cancel:w}},exports.useQuery=function(e,t){return p(e,t)};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=function(){return t=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},t.apply(this,arguments)};function r(e,t,r,n){return new(r||(r=Promise))(function(o,i){function u(e){try{a(n.next(e))}catch(e){i(e)}}function c(e){try{a(n.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(u,c)}a((n=n.apply(e,t||[])).next())})}function n(e,t){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},u=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return u.next=c(0),u.throw=c(1),u.return=c(2),"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function c(c){return function(a){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;u&&(u=0,c[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&c[0]?n.return:c[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,c[1])).done)return o;switch(n=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return i.label++,{value:c[1],done:!1};case 5:i.label++,n=c[1],c=[0];continue;case 7:c=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){i=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){i.label=c[1];break}if(6===c[0]&&i.label<o[1]){i.label=o[1],o=c;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(c);break}o[2]&&i.ops.pop(),i.trys.pop();continue}c=t.call(e,i)}catch(e){c=[6,e],n=0}finally{r=o=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,a])}}}"function"==typeof SuppressedError&&SuppressedError;var o=new Map,i={register:function(e,t,r,n,i){o.set(e,{cacheKey:e,refetch:t,setData:r,cancel:n,cache:i})},getCache:function(e){var t;return null===(t=o.get(e))||void 0===t?void 0:t.cache},setCache:function(e,t,r){var n,i=o.get(e);i&&(i.cache=t,(null==r?void 0:r.skip)||null===(n=i.setData)||void 0===n||n.call(i,function(){return t}))},setData:function(e,t,r){var n,i=o.get(e);if(i){var u=t(i.cache);i.cache=u,(null==r?void 0:r.skip)||null===(n=i.setData)||void 0===n||n.call(i,function(){return u})}},cancel:function(e){var t,r;null===(r=null===(t=o.get(e))||void 0===t?void 0:t.cancel)||void 0===r||r.call(t)},invalidate:function(e){var t;e?null===(t=o.get(e))||void 0===t||t.refetch():o.forEach(function(e){return e.refetch()})},unregister:function(e){var t,r;null===(r=null===(t=o.get(e))||void 0===t?void 0:t.cancel)||void 0===r||r.call(t),o.delete(e)}},u=new Map,c={set:function(e,t,r){var n=r?Date.now()+r:void 0;u.set(e,{data:t,expireAt:n})},get:function(e){var t=u.get(e);if(t){if(!(t.expireAt&&t.expireAt<Date.now()))return t.data;u.delete(e)}},delete:function(e){u.delete(e)},clear:function(){u.clear()}},a={};var l=new Map;function s(e,o){var i;return void 0===o&&(o={}),r(this,void 0,void 0,function(){var u,s,f,h,d,v=this;return n(this,function(p){if(s=t(t(t({},u=a),o),{headers:t(t({},u.headers),o.headers)}),(null===(i=u.interceptors)||void 0===i?void 0:i.onRequest)&&(s=u.interceptors.onRequest(e,s)),f=s.cacheKey,!!f&&!s.staleTime&&!s.autoFetch){if(h=c.get(f))return[2,h];if(l.has(f))return[2,l.get(f)]}return d=fetch(s.baseURL?s.baseURL+e:e,s).then(function(e){return r(v,void 0,void 0,function(){var t,r,o,i,a;return n(this,function(n){switch(n.label){case 0:if(!e.ok)throw new Error(e.statusText);return[4,e.json()];case 1:if(t=n.sent(),r=s.isGraphQL?t.data:t,s.isGraphQL&&(null===(i=t.errors)||void 0===i?void 0:i.length))throw new Error(t.errors[0].message);return o=(null===(a=u.interceptors)||void 0===a?void 0:a.onResponse)?u.interceptors.onResponse(r):r,f&&c.set(f,o,s.cacheTime),[2,o]}})})}).catch(function(e){var t,r;throw null===(r=null===(t=u.interceptors)||void 0===t?void 0:t.onError)||void 0===r||r.call(t,e),e}).finally(function(){return f&&l.delete(f)}),f&&l.set(f,d),[2,d]})})}var f=null;function h(e,t,o,i){return void 0===t&&(t=3),void 0===o&&(o=500),void 0===i&&(i=1e4),r(this,void 0,void 0,function(){var u,c,a,l=this;return n(this,function(s){return u=new AbortController,c=u.signal,i&&setTimeout(function(){return u.abort()},i),a=function(t){return r(l,void 0,void 0,function(){var r;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,5]),[4,e(c)];case 1:return[2,n.sent()];case 2:if("AbortError"===(r=n.sent()).name)throw r;return t>0?[4,new Promise(function(e){return setTimeout(e,o)})]:[3,4];case 3:return n.sent(),[2,a(t-1)];case 4:throw null==f||f(r),r;case 5:return[2]}})})},[2,a(t)]})})}function d(e,t,r){e&&(i.setData(e,function(e){return r?r(e,t):t}),i.invalidate(e))}function v(e,o){return r(this,void 0,void 0,function(){var r;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,s(e,t(t({},o),{isGraphQL:o.isGraphQL}))];case 1:return[2,n.sent()];case 2:throw r=n.sent(),null==f||f(r,{endpoint:e}),r;case 3:return[2]}})})}var p=function(){function e(e){this.url=e,this.callbacks=new Set,this.ws=null}return e.prototype.connect=function(){var e=this;this.ws||(this.ws=new WebSocket(this.url),this.ws.onmessage=function(t){var r=JSON.parse(t.data);e.callbacks.forEach(function(e){return e(r)})})},e.prototype.subscribe=function(e){var t=this;return this.callbacks.add(e),this.connect(),function(){return t.callbacks.delete(e)}},e.prototype.disconnect=function(){var e;null===(e=this.ws)||void 0===e||e.close(),this.ws=null,this.callbacks.clear()},e}();function b(t,o){var i=this,u=o.query,c=o.variables,a=o.options,l=e.useState(null),s=l[0],f=l[1],b=e.useState(null),y=b[0],w=b[1],m=e.useState(!1),g=m[0],x=m[1],S=e.useRef(null),E=e.useRef(!1),T=e.useMemo(function(){return a||{}},[JSON.stringify(a)]),k=e.useCallback(function(){return r(i,void 0,void 0,function(){var e,r,o,i,a,l,s,p,b;return n(this,function(n){switch(n.label){case 0:null===(i=S.current)||void 0===i||i.abort(),e=new AbortController,S.current=e,x(!0),w(null),n.label=1;case 1:return n.trys.push([1,3,4,5]),[4,h(function(e){var r;return v(t,{query:u,variables:c,body:u?JSON.stringify({query:u,variables:c}):void 0,headers:T.headers,method:u?"POST":null!==(r=T.method)&&void 0!==r?r:"GET",signal:e,cacheKey:T.cacheKey,cacheTime:T.cacheTime,staleTime:T.staleTime,isGraphQL:!!u})},null!==(a=T.retry)&&void 0!==a?a:0,null!==(l=T.retryDelay)&&void 0!==l?l:500,null!==(s=T.timeout)&&void 0!==s?s:1e4)];case 2:return r=n.sent(),T.optimisticUpdate&&T.cacheKey&&d(T.cacheKey,r,T.optimisticUpdate),f(r),null===(p=T.onSuccess)||void 0===p||p.call(T,r),[2,r];case 3:if("AbortError"===(o=n.sent()).name)return[2,null];throw w(o),null===(b=T.onError)||void 0===b||b.call(T,o),o;case 4:return x(!1),[7];case 5:return[2]}})})},[t,u,c,T]),K=e.useCallback(function(){var e;null===(e=S.current)||void 0===e||e.abort()},[]);return e.useEffect(function(){return T.autoFetch&&!E.current&&(E.current=!0,k()),function(){return K()}},[]),e.useEffect(function(){if(T.staleTime){var e=setInterval(function(){return k()},T.staleTime);return function(){return clearInterval(e)}}},[k,T.staleTime]),e.useEffect(function(){if(T.subscriptionUrl){var e=new p(T.subscriptionUrl).subscribe(function(e){f(function(t){return T.optimisticUpdate?T.optimisticUpdate(t,e):e}),T.cacheKey&&d(T.cacheKey,e,T.optimisticUpdate)});return function(){return e()}}},[T.subscriptionUrl,T.optimisticUpdate,T.cacheKey]),{data:s,error:y,loading:g,refetch:k,mutate:f,cancel:K}}exports.SubscriptionManager=p,exports.applyOptimisticUpdate=d,exports.cache=c,exports.clearAllCache=function(){c.clear()},exports.commonFetch=v,exports.fetchWithRetry=h,exports.hasCache=function(e){return void 0!==c.get(e)},exports.invalidateCache=function(e){c.delete(e)},exports.prefetchData=function(e,t,r){e().then(function(e){r.setData(t,function(){return e})}).catch(function(e){console.error("Prefetch error:",e),null==f||f(e)})},exports.prefetchQuery=function(e,o){return void 0===o&&(o={}),r(this,void 0,void 0,function(){var r;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,s(e,t(t({},o),{isGraphQL:!!o.query||o.isGraphQL}))];case 1:return[2,n.sent()];case 2:return r=n.sent(),console.error("Prefetch failed",r),[2,null];case 3:return[2]}})})},exports.queryRegistry=i,exports.setGlobalErrorHandler=function(e){f=e},exports.useGraphQLMutation=function(t,o){var i=this,u=e.useState(!1),c=u[0],a=u[1],l=e.useState(null),s=l[0],f=l[1],p=e.useRef(null),b=e.useCallback(function(){return r(i,void 0,void 0,function(){var e,r,i,u,c,l,s,b,y;return n(this,function(n){switch(n.label){case 0:null===(u=p.current)||void 0===u||u.abort(),e=new AbortController,p.current=e,a(!0),f(null),n.label=1;case 1:return n.trys.push([1,3,4,5]),[4,h(function(e){return v(t,{query:o.mutation,variables:o.variables,headers:null==o?void 0:o.headers,signal:e,cacheKey:o.cacheKey,cacheTime:o.cacheTime,isGraphQL:!0})},null!==(c=o.retry)&&void 0!==c?c:0,null!==(l=o.retryDelay)&&void 0!==l?l:500,null!==(s=o.timeout)&&void 0!==s?s:1e4)];case 2:return r=n.sent(),o.optimisticUpdate&&o.cacheKey&&d(o.cacheKey,r,o.optimisticUpdate),null===(b=o.onSuccess)||void 0===b||b.call(o,r),[2,r];case 3:if("AbortError"===(i=n.sent()).name)throw i;throw null===(y=o.onError)||void 0===y||y.call(o,i),f(i),i;case 4:return a(!1),[7];case 5:return[2]}})})},[t,o]),y=e.useCallback(function(){var e;null===(e=p.current)||void 0===e||e.abort(),a(!1)},[]);return{mutate:b,loading:c,error:s,cancel:y}},exports.useGraphQLQuery=function(e,t){return b(e,{query:t.query,variables:t.variables,options:t})},exports.useHybridQuery=b,exports.useMutation=function(t,o){var i=this,u=e.useState(!1),c=u[0],a=u[1],l=e.useState(null),s=l[0],f=l[1],p=e.useRef(null),b=e.useCallback(function(e,u){return void 0===u&&(u="POST"),r(i,void 0,void 0,function(){var r,i,c,l,s,b,y,w,m;return n(this,function(n){switch(n.label){case 0:null===(l=p.current)||void 0===l||l.abort(),r=new AbortController,p.current=r,a(!0),f(null),n.label=1;case 1:return n.trys.push([1,3,4,5]),[4,h(function(r){return v(t,{method:u,headers:null==o?void 0:o.headers,body:e,signal:r,cacheKey:null==o?void 0:o.cacheKey,cacheTime:null==o?void 0:o.cacheTime})},null!==(s=null==o?void 0:o.retry)&&void 0!==s?s:0,null!==(b=null==o?void 0:o.retryDelay)&&void 0!==b?b:500,null!==(y=null==o?void 0:o.timeout)&&void 0!==y?y:1e4)];case 2:return i=n.sent(),(null==o?void 0:o.optimisticUpdate)&&o.cacheKey&&d(o.cacheKey,i,o.optimisticUpdate),null===(w=null==o?void 0:o.onSuccess)||void 0===w||w.call(o,i),[2,i];case 3:if("AbortError"===(c=n.sent()).name)throw c;throw null===(m=null==o?void 0:o.onError)||void 0===m||m.call(o,c),f(c),c;case 4:return a(!1),[7];case 5:return[2]}})})},[t,o]),y=e.useCallback(function(){var e;null===(e=p.current)||void 0===e||e.abort(),a(!1)},[]);return{mutate:b,loading:c,error:s,cancel:y}},exports.useQuery=function(e,t){return b(e,{options:t})};
package/build/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from "./hooks/types";
1
2
  export { useHybridQuery } from "./hooks/useHybridQuery";
2
3
  export { useQuery } from "./hooks/useQuery";
3
4
  export { useMutation } from "./hooks/useMutation";
@@ -6,6 +7,5 @@ export { useGraphQLMutation } from "./hooks/useGraphQLMutation";
6
7
  export { SubscriptionManager } from "./core/subscription";
7
8
  export { queryRegistry } from "./core/globalQuery";
8
9
  export { cache } from "./core/cache";
9
- export { updateCache } from "./utils/cacheUtils";
10
- export { retryOperation } from "./utils/retryUtils";
11
- export { createTimeoutSignal } from "./utils/timeoutUtils";
10
+ export * from "./utils/cacheUtils";
11
+ export * from "./utils/prefetchUtils";
@@ -1 +1 @@
1
- import{useState as e,useRef as t,useCallback as n,useEffect as r}from"react";var i=function(){return i=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},i.apply(this,arguments)};function a(e,t,n,r){return new(n||(n=Promise))(function(i,a){function c(e){try{u(r.next(e))}catch(e){a(e)}}function o(e){try{u(r.throw(e))}catch(e){a(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(c,o)}u((r=r.apply(e,t||[])).next())})}function c(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},c=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return c.next=o(0),c.throw=o(1),c.return=o(2),"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function o(o){return function(u){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;c&&(c=0,o[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=a.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,u])}}}"function"==typeof SuppressedError&&SuppressedError;var o=new Map,u={get:function(e){var t=o.get(e);if(t)return t.data},set:function(e,t){o.set(e,{data:t,timestamp:Date.now()})},delete:function(e){o.delete(e)},clear:function(){return o.clear()}},s=new Map;function l(e,t){return void 0===t&&(t={}),a(this,void 0,void 0,function(){var n,r,i,o=this;return c(this,function(l){return n=t.cacheKey||e,s.has(n)?[2,s.get(n)]:(r=u.get(n))?[2,r]:(i=fetch(e,t).then(function(e){return a(o,void 0,void 0,function(){var t;return c(this,function(r){switch(r.label){case 0:if(!e.ok)throw new Error(e.statusText);return[4,e.json()];case 1:return t=r.sent(),u.set(n,t),[2,t]}})})}).finally(function(){return s.delete(n)}),s.set(n,i),[2,i])})})}var h=new Map,d={register:function(e,t,n,r,i){h.set(e,{cacheKey:e,refetch:t,setData:n,cancel:r,cache:i})},getCache:function(e){var t;return null===(t=h.get(e))||void 0===t?void 0:t.cache},setCache:function(e,t){var n,r=h.get(e);r&&(r.cache=t,null===(n=r.setData)||void 0===n||n.call(r,function(){return t}))},setData:function(e,t){var n,r=h.get(e);if(r){var i=t(r.cache);r.cache=i,null===(n=r.setData)||void 0===n||n.call(r,function(){return i})}},cancel:function(e){var t,n;null===(n=null===(t=h.get(e))||void 0===t?void 0:t.cancel)||void 0===n||n.call(t)},invalidate:function(e){var t;e?null===(t=h.get(e))||void 0===t||t.refetch():h.forEach(function(e){return e.refetch()})},unregister:function(e){var t,n;null===(n=null===(t=h.get(e))||void 0===t?void 0:t.cancel)||void 0===n||n.call(t),h.delete(e)}},f=function(){function e(e){this.url=e,this.callbacks=new Set,this.ws=null}return e.prototype.connect=function(){var e=this;this.ws||(this.ws=new WebSocket(this.url),this.ws.onmessage=function(t){var n=JSON.parse(t.data);e.callbacks.forEach(function(e){return e(n)})})},e.prototype.subscribe=function(e){var t=this;return this.callbacks.add(e),this.connect(),function(){return t.callbacks.delete(e)}},e.prototype.disconnect=function(){var e;null===(e=this.ws)||void 0===e||e.close(),this.ws=null,this.callbacks.clear()},e}();function v(e,t,n){return a(this,void 0,void 0,function(){var r;return c(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,4]),[4,e()];case 1:return[2,i.sent()];case 2:if(r=i.sent(),t<=0)throw r;return[4,new Promise(function(e){return setTimeout(e,n)})];case 3:return i.sent(),[2,v(e,t-1,2*n)];case 4:return[2]}})})}function y(e){var t=new AbortController,n=setTimeout(function(){return t.abort()},e);return t.signal.addEventListener("abort",function(){return clearTimeout(n)}),t.signal}function p(e,t,n){e&&(d.setData(e,function(e){return t?t(e,n):n}),d.invalidate(e))}function b(e,t,n,r,i,o){return a(this,void 0,void 0,function(){var a,u;return c(this,function(c){switch(c.label){case 0:return c.trys.push([0,2,,3]),[4,w(e,t,n,{headers:i,cacheKey:r,method:o})];case 1:return a=c.sent(),r&&d.setCache(r,a),[2,a];case 2:return u=c.sent(),console.error("Prefetch failed",u),[2,null];case 3:return[2]}})})}function m(i,o){var u=this,s=o.query,l=o.variables,h=o.options,m=void 0===h?{}:h,g=e(null),K=g[0],T=g[1],U=e(null),D=U[0],S=U[1],O=e(!1),k=O[0],C=O[1],E=t(null),j=n(function(){return a(u,void 0,void 0,function(){var e,t,n,r,o,u=this;return c(this,function(h){switch(h.label){case 0:C(!0),S(null),null===(r=E.current)||void 0===r||r.abort(),e=new AbortController,E.current=e,t=y(null!==(o=m.timeout)&&void 0!==o?o:1e4),n=function(e,h){return void 0===e&&(e=null!==(r=m.retry)&&void 0!==r?r:3),void 0===h&&(h=null!==(o=m.retryDelay)&&void 0!==o?o:500),a(u,void 0,void 0,function(){var r,a;return c(this,function(c){switch(c.label){case 0:return c.trys.push([0,2,,3]),[4,w(i,s,l,{headers:m.headers,cacheKey:m.cacheKey,method:m.method,signal:t})];case 1:return r=c.sent(),T(function(e){return m.optimisticUpdate?m.optimisticUpdate(e,r):r}),p(m.cacheKey,m.optimisticUpdate,r),[2,r];case 2:if("AbortError"===(a=c.sent()).name)throw a;return[2,v(function(){return n(e-1,2*h)},e-1,2*h)];case 3:return[2]}})})},h.label=1;case 1:return h.trys.push([1,,3,4]),[4,n()];case 2:return[2,h.sent()];case 3:return C(!1),[7];case 4:return[2]}})})},[i,s,l,m.cacheKey,m.optimisticUpdate,m.retry,m.retryDelay,m.headers,m.timeout,m.method]),x=n(function(){var e;return null===(e=E.current)||void 0===e?void 0:e.abort()},[]);return r(function(){var e=!0;return a(u,void 0,void 0,function(){var t;return c(this,function(n){switch(n.label){case 0:return m.prefetch&&m.cacheKey?(t=d.getCache(m.cacheKey))?(T(t),[3,3]):[3,1]:[3,3];case 1:return[4,b(i,s,l,m.cacheKey,m.headers,m.method)];case 2:n.sent(),n.label=3;case 3:return m.autoFetch&&e&&j(),[2]}})}),m.cacheKey&&d.register(m.cacheKey,j,T,x),function(){m.cacheKey&&d.unregister(m.cacheKey),x(),e=!1}},[i,s,l,m.prefetch,m.autoFetch,m.cacheKey,m.method]),r(function(){if(m.staleTime){var e=setInterval(j,m.staleTime);return function(){return clearInterval(e)}}},[j,m.staleTime]),r(function(){if(m.subscriptionUrl){var e=new f(m.subscriptionUrl).subscribe(function(e){T(function(t){return m.optimisticUpdate?m.optimisticUpdate(t,e):e}),p(m.cacheKey,m.optimisticUpdate,e)});return function(){return e()}}},[m.subscriptionUrl,m.optimisticUpdate,m.cacheKey]),{data:K,error:D,loading:k,refetch:j,mutate:T,cancel:x}}function w(e,t,n,r){var o;return a(this,void 0,void 0,function(){var a;return c(this,function(c){switch(c.label){case 0:return t?[4,l(e,{method:"POST",headers:i({"Content-Type":"application/json"},null==r?void 0:r.headers),body:JSON.stringify({query:t,variables:n}),cacheKey:null==r?void 0:r.cacheKey,signal:null==r?void 0:r.signal})]:[3,2];case 1:return[2,c.sent().data];case 2:return a=null!==(o=null==r?void 0:r.method)&&void 0!==o?o:"GET",[4,l(e,{method:a,headers:null==r?void 0:r.headers,cacheKey:null==r?void 0:r.cacheKey,signal:null==r?void 0:r.signal})];case 3:return[2,c.sent()]}})})}function g(e,t){return m(e,t)}function K(r,o){var u=this,s=e(!1),h=s[0],f=s[1],p=e(null),b=p[0],m=p[1],w=t(null),g=n(function(e,t){return void 0===t&&(t="POST"),a(u,void 0,void 0,function(){var n,u,s,h,p,b=this;return c(this,function(g){switch(g.label){case 0:f(!0),m(null),null===(h=w.current)||void 0===h||h.abort(),n=new AbortController,w.current=n,u=y(null!==(p=null==o?void 0:o.timeout)&&void 0!==p?p:1e4),s=function(n,f){return void 0===n&&(n=null!==(h=null==o?void 0:o.retry)&&void 0!==h?h:3),void 0===f&&(f=null!==(p=null==o?void 0:o.retryDelay)&&void 0!==p?p:500),a(b,void 0,void 0,function(){var a,h,y;return c(this,function(c){switch(c.label){case 0:return c.trys.push([0,2,,3]),[4,l(r,{method:t,headers:i({"Content-Type":"application/json"},null==o?void 0:o.headers),body:JSON.stringify(e),cacheKey:null==o?void 0:o.cacheKey,signal:u})];case 1:return a=c.sent(),(null==o?void 0:o.optimisticUpdate)&&o.cacheKey&&(d.setData(o.cacheKey,function(e){return o.optimisticUpdate(e,a)}),d.invalidate(o.cacheKey)),null===(y=null==o?void 0:o.onSuccess)||void 0===y||y.call(o,a),[2,a];case 2:if("AbortError"===(h=c.sent()).name)throw h;return[2,v(function(){return s(n-1,2*f)},n-1,2*f)];case 3:return[2]}})})},g.label=1;case 1:return g.trys.push([1,,3,4]),[4,s()];case 2:return[2,g.sent()];case 3:return f(!1),[7];case 4:return[2]}})})},[r,o]),K=n(function(){var e;return null===(e=w.current)||void 0===e?void 0:e.abort()},[]);return{mutate:g,loading:h,error:b,cancel:K}}function T(e,t){return m(e,{query:t.query,variables:t.variables,options:{cacheKey:t.cacheKey,staleTime:t.staleTime,headers:t.headers,timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay,optimisticUpdate:t.optimisticUpdate}})}function U(e,r){var o=this,u=r.mutation,s=r.variables,h=r.cacheKey,f=r.optimisticUpdate,p=r.retry,b=void 0===p?3:p,m=r.retryDelay,w=void 0===m?500:m,g=r.headers,K=r.timeout,T=void 0===K?1e4:K,U=t(null),D=n(function(){return a(o,void 0,void 0,function(){var t,n,r,o,p=this;return c(this,function(m){switch(m.label){case 0:null===(o=U.current)||void 0===o||o.abort(),t=new AbortController,U.current=t,n=y(T),r=function(t,o){return a(p,void 0,void 0,function(){var a,y;return c(this,function(c){switch(c.label){case 0:return c.trys.push([0,2,,3]),[4,l(e,{method:"POST",headers:i({"Content-Type":"application/json"},g),body:JSON.stringify({query:u,variables:s}),signal:n,cacheKey:h})];case 1:return a=c.sent(),f&&h&&d.setData(h,function(e){return f(e,a.data)}),h&&d.invalidate(h),[2,a.data];case 2:if("AbortError"===(y=c.sent()).name)throw y;return[2,v(function(){return r(t-1,2*o)},t-1,2*o)];case 3:return[2]}})})},m.label=1;case 1:return m.trys.push([1,,3,4]),[4,r(b,w)];case 2:return[2,m.sent()];case 3:return[7];case 4:return[2]}})})},[e,u,s,h,f,b,w,g,T]),S=n(function(){var e;null===(e=U.current)||void 0===e||e.abort()},[]);return{mutate:D,cancel:S}}export{f as SubscriptionManager,u as cache,y as createTimeoutSignal,d as queryRegistry,v as retryOperation,p as updateCache,U as useGraphQLMutation,T as useGraphQLQuery,m as useHybridQuery,K as useMutation,g as useQuery};
1
+ import{useState as e,useRef as t,useMemo as n,useCallback as r,useEffect as i}from"react";var o=function(){return o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},o.apply(this,arguments)};function c(e,t,n,r){return new(n||(n=Promise))(function(i,o){function c(e){try{a(r.next(e))}catch(e){o(e)}}function u(e){try{a(r.throw(e))}catch(e){o(e)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(c,u)}a((r=r.apply(e,t||[])).next())})}function u(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},c=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return c.next=u(0),c.throw=u(1),c.return=u(2),"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function u(u){return function(a){return function(u){if(n)throw new TypeError("Generator is already executing.");for(;c&&(c=0,u[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&u[0]?r.return:u[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,u[1])).done)return i;switch(r=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==u[0]&&2!==u[0])){o=0;continue}if(3===u[0]&&(!i||u[1]>i[0]&&u[1]<i[3])){o.label=u[1];break}if(6===u[0]&&o.label<i[1]){o.label=i[1],i=u;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(u);break}i[2]&&o.ops.pop(),o.trys.pop();continue}u=t.call(e,o)}catch(e){u=[6,e],r=0}finally{n=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([u,a])}}}"function"==typeof SuppressedError&&SuppressedError;var a=new Map,l={register:function(e,t,n,r,i){a.set(e,{cacheKey:e,refetch:t,setData:n,cancel:r,cache:i})},getCache:function(e){var t;return null===(t=a.get(e))||void 0===t?void 0:t.cache},setCache:function(e,t,n){var r,i=a.get(e);i&&(i.cache=t,(null==n?void 0:n.skip)||null===(r=i.setData)||void 0===r||r.call(i,function(){return t}))},setData:function(e,t,n){var r,i=a.get(e);if(i){var o=t(i.cache);i.cache=o,(null==n?void 0:n.skip)||null===(r=i.setData)||void 0===r||r.call(i,function(){return o})}},cancel:function(e){var t,n;null===(n=null===(t=a.get(e))||void 0===t?void 0:t.cancel)||void 0===n||n.call(t)},invalidate:function(e){var t;e?null===(t=a.get(e))||void 0===t||t.refetch():a.forEach(function(e){return e.refetch()})},unregister:function(e){var t,n;null===(n=null===(t=a.get(e))||void 0===t?void 0:t.cancel)||void 0===n||n.call(t),a.delete(e)}},s=new Map,f={set:function(e,t,n){var r=n?Date.now()+n:void 0;s.set(e,{data:t,expireAt:r})},get:function(e){var t=s.get(e);if(t){if(!(t.expireAt&&t.expireAt<Date.now()))return t.data;s.delete(e)}},delete:function(e){s.delete(e)},clear:function(){s.clear()}},h={};var v=new Map;function d(e,t){var n;return void 0===t&&(t={}),c(this,void 0,void 0,function(){var r,i,a,l,s,d=this;return u(this,function(p){if(i=o(o(o({},r=h),t),{headers:o(o({},r.headers),t.headers)}),(null===(n=r.interceptors)||void 0===n?void 0:n.onRequest)&&(i=r.interceptors.onRequest(e,i)),a=i.cacheKey,!!a&&!i.staleTime&&!i.autoFetch){if(l=f.get(a))return[2,l];if(v.has(a))return[2,v.get(a)]}return s=fetch(i.baseURL?i.baseURL+e:e,i).then(function(e){return c(d,void 0,void 0,function(){var t,n,o,c,l;return u(this,function(u){switch(u.label){case 0:if(!e.ok)throw new Error(e.statusText);return[4,e.json()];case 1:if(t=u.sent(),n=i.isGraphQL?t.data:t,i.isGraphQL&&(null===(c=t.errors)||void 0===c?void 0:c.length))throw new Error(t.errors[0].message);return o=(null===(l=r.interceptors)||void 0===l?void 0:l.onResponse)?r.interceptors.onResponse(n):n,a&&f.set(a,o,i.cacheTime),[2,o]}})})}).catch(function(e){var t,n;throw null===(n=null===(t=r.interceptors)||void 0===t?void 0:t.onError)||void 0===n||n.call(t,e),e}).finally(function(){return a&&v.delete(a)}),a&&v.set(a,s),[2,s]})})}var p=null;function b(e){p=e}function y(e,t,n){e().then(function(e){n.setData(t,function(){return e})}).catch(function(e){console.error("Prefetch error:",e),null==p||p(e)})}function w(e,t,n,r){return void 0===t&&(t=3),void 0===n&&(n=500),void 0===r&&(r=1e4),c(this,void 0,void 0,function(){var i,o,a,l=this;return u(this,function(s){return i=new AbortController,o=i.signal,r&&setTimeout(function(){return i.abort()},r),a=function(t){return c(l,void 0,void 0,function(){var r;return u(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,e(o)];case 1:return[2,i.sent()];case 2:if("AbortError"===(r=i.sent()).name)throw r;return t>0?[4,new Promise(function(e){return setTimeout(e,n)})]:[3,4];case 3:return i.sent(),[2,a(t-1)];case 4:throw null==p||p(r),r;case 5:return[2]}})})},[2,a(t)]})})}function m(e,t,n){e&&(l.setData(e,function(e){return n?n(e,t):t}),l.invalidate(e))}function g(e,t){return c(this,void 0,void 0,function(){var n;return u(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,d(e,o(o({},t),{isGraphQL:t.isGraphQL}))];case 1:return[2,r.sent()];case 2:throw n=r.sent(),null==p||p(n,{endpoint:e}),n;case 3:return[2]}})})}function T(e,t){return void 0===t&&(t={}),c(this,void 0,void 0,function(){var n;return u(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,d(e,o(o({},t),{isGraphQL:!!t.query||t.isGraphQL}))];case 1:return[2,r.sent()];case 2:return n=r.sent(),console.error("Prefetch failed",n),[2,null];case 3:return[2]}})})}var K=function(){function e(e){this.url=e,this.callbacks=new Set,this.ws=null}return e.prototype.connect=function(){var e=this;this.ws||(this.ws=new WebSocket(this.url),this.ws.onmessage=function(t){var n=JSON.parse(t.data);e.callbacks.forEach(function(e){return e(n)})})},e.prototype.subscribe=function(e){var t=this;return this.callbacks.add(e),this.connect(),function(){return t.callbacks.delete(e)}},e.prototype.disconnect=function(){var e;null===(e=this.ws)||void 0===e||e.close(),this.ws=null,this.callbacks.clear()},e}();function E(o,a){var l=this,s=a.query,f=a.variables,h=a.options,v=e(null),d=v[0],p=v[1],b=e(null),y=b[0],T=b[1],E=e(!1),U=E[0],S=E[1],k=t(null),A=t(!1),D=n(function(){return h||{}},[JSON.stringify(h)]),x=r(function(){return c(l,void 0,void 0,function(){var e,t,n,r,i,c,a,l,h;return u(this,function(u){switch(u.label){case 0:null===(r=k.current)||void 0===r||r.abort(),e=new AbortController,k.current=e,S(!0),T(null),u.label=1;case 1:return u.trys.push([1,3,4,5]),[4,w(function(e){var t;return g(o,{query:s,variables:f,body:s?JSON.stringify({query:s,variables:f}):void 0,headers:D.headers,method:s?"POST":null!==(t=D.method)&&void 0!==t?t:"GET",signal:e,cacheKey:D.cacheKey,cacheTime:D.cacheTime,staleTime:D.staleTime,isGraphQL:!!s})},null!==(i=D.retry)&&void 0!==i?i:0,null!==(c=D.retryDelay)&&void 0!==c?c:500,null!==(a=D.timeout)&&void 0!==a?a:1e4)];case 2:return t=u.sent(),D.optimisticUpdate&&D.cacheKey&&m(D.cacheKey,t,D.optimisticUpdate),p(t),null===(l=D.onSuccess)||void 0===l||l.call(D,t),[2,t];case 3:if("AbortError"===(n=u.sent()).name)return[2,null];throw T(n),null===(h=D.onError)||void 0===h||h.call(D,n),n;case 4:return S(!1),[7];case 5:return[2]}})})},[o,s,f,D]),G=r(function(){var e;null===(e=k.current)||void 0===e||e.abort()},[]);return i(function(){return D.autoFetch&&!A.current&&(A.current=!0,x()),function(){return G()}},[]),i(function(){if(D.staleTime){var e=setInterval(function(){return x()},D.staleTime);return function(){return clearInterval(e)}}},[x,D.staleTime]),i(function(){if(D.subscriptionUrl){var e=new K(D.subscriptionUrl).subscribe(function(e){p(function(t){return D.optimisticUpdate?D.optimisticUpdate(t,e):e}),D.cacheKey&&m(D.cacheKey,e,D.optimisticUpdate)});return function(){return e()}}},[D.subscriptionUrl,D.optimisticUpdate,D.cacheKey]),{data:d,error:y,loading:U,refetch:x,mutate:p,cancel:G}}function U(e,t){return E(e,{options:t})}function S(n,i){var o=this,a=e(!1),l=a[0],s=a[1],f=e(null),h=f[0],v=f[1],d=t(null),p=r(function(e,t){return void 0===t&&(t="POST"),c(o,void 0,void 0,function(){var r,o,c,a,l,f,h,p,b;return u(this,function(u){switch(u.label){case 0:null===(a=d.current)||void 0===a||a.abort(),r=new AbortController,d.current=r,s(!0),v(null),u.label=1;case 1:return u.trys.push([1,3,4,5]),[4,w(function(r){return g(n,{method:t,headers:null==i?void 0:i.headers,body:e,signal:r,cacheKey:null==i?void 0:i.cacheKey,cacheTime:null==i?void 0:i.cacheTime})},null!==(l=null==i?void 0:i.retry)&&void 0!==l?l:0,null!==(f=null==i?void 0:i.retryDelay)&&void 0!==f?f:500,null!==(h=null==i?void 0:i.timeout)&&void 0!==h?h:1e4)];case 2:return o=u.sent(),(null==i?void 0:i.optimisticUpdate)&&i.cacheKey&&m(i.cacheKey,o,i.optimisticUpdate),null===(p=null==i?void 0:i.onSuccess)||void 0===p||p.call(i,o),[2,o];case 3:if("AbortError"===(c=u.sent()).name)throw c;throw null===(b=null==i?void 0:i.onError)||void 0===b||b.call(i,c),v(c),c;case 4:return s(!1),[7];case 5:return[2]}})})},[n,i]),b=r(function(){var e;null===(e=d.current)||void 0===e||e.abort(),s(!1)},[]);return{mutate:p,loading:l,error:h,cancel:b}}function k(e,t){return E(e,{query:t.query,variables:t.variables,options:t})}function A(n,i){var o=this,a=e(!1),l=a[0],s=a[1],f=e(null),h=f[0],v=f[1],d=t(null),p=r(function(){return c(o,void 0,void 0,function(){var e,t,r,o,c,a,l,f,h;return u(this,function(u){switch(u.label){case 0:null===(o=d.current)||void 0===o||o.abort(),e=new AbortController,d.current=e,s(!0),v(null),u.label=1;case 1:return u.trys.push([1,3,4,5]),[4,w(function(e){return g(n,{query:i.mutation,variables:i.variables,headers:null==i?void 0:i.headers,signal:e,cacheKey:i.cacheKey,cacheTime:i.cacheTime,isGraphQL:!0})},null!==(c=i.retry)&&void 0!==c?c:0,null!==(a=i.retryDelay)&&void 0!==a?a:500,null!==(l=i.timeout)&&void 0!==l?l:1e4)];case 2:return t=u.sent(),i.optimisticUpdate&&i.cacheKey&&m(i.cacheKey,t,i.optimisticUpdate),null===(f=i.onSuccess)||void 0===f||f.call(i,t),[2,t];case 3:if("AbortError"===(r=u.sent()).name)throw r;throw null===(h=i.onError)||void 0===h||h.call(i,r),v(r),r;case 4:return s(!1),[7];case 5:return[2]}})})},[n,i]),b=r(function(){var e;null===(e=d.current)||void 0===e||e.abort(),s(!1)},[]);return{mutate:p,loading:l,error:h,cancel:b}}function D(e){f.delete(e)}function x(){f.clear()}function G(e){return void 0!==f.get(e)}export{K as SubscriptionManager,m as applyOptimisticUpdate,f as cache,x as clearAllCache,g as commonFetch,w as fetchWithRetry,G as hasCache,D as invalidateCache,y as prefetchData,T as prefetchQuery,l as queryRegistry,b as setGlobalErrorHandler,A as useGraphQLMutation,k as useGraphQLQuery,E as useHybridQuery,S as useMutation,U as useQuery};
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactiveQuery={},e.React)}(this,function(e,t){"use strict";var n=function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};function r(e,t,n,r){return new(n||(n=Promise))(function(i,a){function c(e){try{o(r.next(e))}catch(e){a(e)}}function u(e){try{o(r.throw(e))}catch(e){a(e)}}function o(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(c,u)}o((r=r.apply(e,t||[])).next())})}function i(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},c=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return c.next=u(0),c.throw=u(1),c.return=u(2),"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function u(u){return function(o){return function(u){if(n)throw new TypeError("Generator is already executing.");for(;c&&(c=0,u[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&u[0]?r.return:u[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,u[1])).done)return i;switch(r=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return a.label++,{value:u[1],done:!1};case 5:a.label++,r=u[1],u=[0];continue;case 7:u=a.ops.pop(),a.trys.pop();continue;default:if(!(i=a.trys,(i=i.length>0&&i[i.length-1])||6!==u[0]&&2!==u[0])){a=0;continue}if(3===u[0]&&(!i||u[1]>i[0]&&u[1]<i[3])){a.label=u[1];break}if(6===u[0]&&a.label<i[1]){a.label=i[1],i=u;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(u);break}i[2]&&a.ops.pop(),a.trys.pop();continue}u=t.call(e,a)}catch(e){u=[6,e],r=0}finally{n=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([u,o])}}}"function"==typeof SuppressedError&&SuppressedError;var a=new Map,c={get:function(e){var t=a.get(e);if(t)return t.data},set:function(e,t){a.set(e,{data:t,timestamp:Date.now()})},delete:function(e){a.delete(e)},clear:function(){return a.clear()}},u=new Map;function o(e,t){return void 0===t&&(t={}),r(this,void 0,void 0,function(){var n,a,o,s=this;return i(this,function(l){return n=t.cacheKey||e,u.has(n)?[2,u.get(n)]:(a=c.get(n))?[2,a]:(o=fetch(e,t).then(function(e){return r(s,void 0,void 0,function(){var t;return i(this,function(r){switch(r.label){case 0:if(!e.ok)throw new Error(e.statusText);return[4,e.json()];case 1:return t=r.sent(),c.set(n,t),[2,t]}})})}).finally(function(){return u.delete(n)}),u.set(n,o),[2,o])})})}var s=new Map,l={register:function(e,t,n,r,i){s.set(e,{cacheKey:e,refetch:t,setData:n,cancel:r,cache:i})},getCache:function(e){var t;return null===(t=s.get(e))||void 0===t?void 0:t.cache},setCache:function(e,t){var n,r=s.get(e);r&&(r.cache=t,null===(n=r.setData)||void 0===n||n.call(r,function(){return t}))},setData:function(e,t){var n,r=s.get(e);if(r){var i=t(r.cache);r.cache=i,null===(n=r.setData)||void 0===n||n.call(r,function(){return i})}},cancel:function(e){var t,n;null===(n=null===(t=s.get(e))||void 0===t?void 0:t.cancel)||void 0===n||n.call(t)},invalidate:function(e){var t;e?null===(t=s.get(e))||void 0===t||t.refetch():s.forEach(function(e){return e.refetch()})},unregister:function(e){var t,n;null===(n=null===(t=s.get(e))||void 0===t?void 0:t.cancel)||void 0===n||n.call(t),s.delete(e)}},f=function(){function e(e){this.url=e,this.callbacks=new Set,this.ws=null}return e.prototype.connect=function(){var e=this;this.ws||(this.ws=new WebSocket(this.url),this.ws.onmessage=function(t){var n=JSON.parse(t.data);e.callbacks.forEach(function(e){return e(n)})})},e.prototype.subscribe=function(e){var t=this;return this.callbacks.add(e),this.connect(),function(){return t.callbacks.delete(e)}},e.prototype.disconnect=function(){var e;null===(e=this.ws)||void 0===e||e.close(),this.ws=null,this.callbacks.clear()},e}();function h(e,t,n){return r(this,void 0,void 0,function(){var r;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,4]),[4,e()];case 1:return[2,i.sent()];case 2:if(r=i.sent(),t<=0)throw r;return[4,new Promise(function(e){return setTimeout(e,n)})];case 3:return i.sent(),[2,h(e,t-1,2*n)];case 4:return[2]}})})}function d(e){var t=new AbortController,n=setTimeout(function(){return t.abort()},e);return t.signal.addEventListener("abort",function(){return clearTimeout(n)}),t.signal}function v(e,t,n){e&&(l.setData(e,function(e){return t?t(e,n):n}),l.invalidate(e))}function y(e,t,n,a,c,u){return r(this,void 0,void 0,function(){var r,o;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,b(e,t,n,{headers:c,cacheKey:a,method:u})];case 1:return r=i.sent(),a&&l.setCache(a,r),[2,r];case 2:return o=i.sent(),console.error("Prefetch failed",o),[2,null];case 3:return[2]}})})}function p(e,n){var a=this,c=n.query,u=n.variables,o=n.options,s=void 0===o?{}:o,p=t.useState(null),m=p[0],w=p[1],g=t.useState(null),K=g[0],S=g[1],T=t.useState(!1),C=T[0],k=T[1],U=t.useRef(null),D=t.useCallback(function(){return r(a,void 0,void 0,function(){var t,n,a,o,l,f=this;return i(this,function(y){switch(y.label){case 0:k(!0),S(null),null===(o=U.current)||void 0===o||o.abort(),t=new AbortController,U.current=t,n=d(null!==(l=s.timeout)&&void 0!==l?l:1e4),a=function(t,d){return void 0===t&&(t=null!==(o=s.retry)&&void 0!==o?o:3),void 0===d&&(d=null!==(l=s.retryDelay)&&void 0!==l?l:500),r(f,void 0,void 0,function(){var r,o;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,b(e,c,u,{headers:s.headers,cacheKey:s.cacheKey,method:s.method,signal:n})];case 1:return r=i.sent(),w(function(e){return s.optimisticUpdate?s.optimisticUpdate(e,r):r}),v(s.cacheKey,s.optimisticUpdate,r),[2,r];case 2:if("AbortError"===(o=i.sent()).name)throw o;return[2,h(function(){return a(t-1,2*d)},t-1,2*d)];case 3:return[2]}})})},y.label=1;case 1:return y.trys.push([1,,3,4]),[4,a()];case 2:return[2,y.sent()];case 3:return k(!1),[7];case 4:return[2]}})})},[e,c,u,s.cacheKey,s.optimisticUpdate,s.retry,s.retryDelay,s.headers,s.timeout,s.method]),E=t.useCallback(function(){var e;return null===(e=U.current)||void 0===e?void 0:e.abort()},[]);return t.useEffect(function(){var t=!0;return r(a,void 0,void 0,function(){var n;return i(this,function(r){switch(r.label){case 0:return s.prefetch&&s.cacheKey?(n=l.getCache(s.cacheKey))?(w(n),[3,3]):[3,1]:[3,3];case 1:return[4,y(e,c,u,s.cacheKey,s.headers,s.method)];case 2:r.sent(),r.label=3;case 3:return s.autoFetch&&t&&D(),[2]}})}),s.cacheKey&&l.register(s.cacheKey,D,w,E),function(){s.cacheKey&&l.unregister(s.cacheKey),E(),t=!1}},[e,c,u,s.prefetch,s.autoFetch,s.cacheKey,s.method]),t.useEffect(function(){if(s.staleTime){var e=setInterval(D,s.staleTime);return function(){return clearInterval(e)}}},[D,s.staleTime]),t.useEffect(function(){if(s.subscriptionUrl){var e=new f(s.subscriptionUrl).subscribe(function(e){w(function(t){return s.optimisticUpdate?s.optimisticUpdate(t,e):e}),v(s.cacheKey,s.optimisticUpdate,e)});return function(){return e()}}},[s.subscriptionUrl,s.optimisticUpdate,s.cacheKey]),{data:m,error:K,loading:C,refetch:D,mutate:w,cancel:E}}function b(e,t,a,c){var u;return r(this,void 0,void 0,function(){var r;return i(this,function(i){switch(i.label){case 0:return t?[4,o(e,{method:"POST",headers:n({"Content-Type":"application/json"},null==c?void 0:c.headers),body:JSON.stringify({query:t,variables:a}),cacheKey:null==c?void 0:c.cacheKey,signal:null==c?void 0:c.signal})]:[3,2];case 1:return[2,i.sent().data];case 2:return r=null!==(u=null==c?void 0:c.method)&&void 0!==u?u:"GET",[4,o(e,{method:r,headers:null==c?void 0:c.headers,cacheKey:null==c?void 0:c.cacheKey,signal:null==c?void 0:c.signal})];case 3:return[2,i.sent()]}})})}e.SubscriptionManager=f,e.cache=c,e.createTimeoutSignal=d,e.queryRegistry=l,e.retryOperation=h,e.updateCache=v,e.useGraphQLMutation=function(e,a){var c=this,u=a.mutation,s=a.variables,f=a.cacheKey,v=a.optimisticUpdate,y=a.retry,p=void 0===y?3:y,b=a.retryDelay,m=void 0===b?500:b,w=a.headers,g=a.timeout,K=void 0===g?1e4:g,S=t.useRef(null),T=t.useCallback(function(){return r(c,void 0,void 0,function(){var t,a,c,y,b=this;return i(this,function(g){switch(g.label){case 0:null===(y=S.current)||void 0===y||y.abort(),t=new AbortController,S.current=t,a=d(K),c=function(t,d){return r(b,void 0,void 0,function(){var r,y;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,o(e,{method:"POST",headers:n({"Content-Type":"application/json"},w),body:JSON.stringify({query:u,variables:s}),signal:a,cacheKey:f})];case 1:return r=i.sent(),v&&f&&l.setData(f,function(e){return v(e,r.data)}),f&&l.invalidate(f),[2,r.data];case 2:if("AbortError"===(y=i.sent()).name)throw y;return[2,h(function(){return c(t-1,2*d)},t-1,2*d)];case 3:return[2]}})})},g.label=1;case 1:return g.trys.push([1,,3,4]),[4,c(p,m)];case 2:return[2,g.sent()];case 3:return[7];case 4:return[2]}})})},[e,u,s,f,v,p,m,w,K]),C=t.useCallback(function(){var e;null===(e=S.current)||void 0===e||e.abort()},[]);return{mutate:T,cancel:C}},e.useGraphQLQuery=function(e,t){return p(e,{query:t.query,variables:t.variables,options:{cacheKey:t.cacheKey,staleTime:t.staleTime,headers:t.headers,timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay,optimisticUpdate:t.optimisticUpdate}})},e.useHybridQuery=p,e.useMutation=function(e,a){var c=this,u=t.useState(!1),s=u[0],f=u[1],v=t.useState(null),y=v[0],p=v[1],b=t.useRef(null),m=t.useCallback(function(t,u){return void 0===u&&(u="POST"),r(c,void 0,void 0,function(){var c,s,v,y,m,w=this;return i(this,function(g){switch(g.label){case 0:f(!0),p(null),null===(y=b.current)||void 0===y||y.abort(),c=new AbortController,b.current=c,s=d(null!==(m=null==a?void 0:a.timeout)&&void 0!==m?m:1e4),v=function(c,f){return void 0===c&&(c=null!==(y=null==a?void 0:a.retry)&&void 0!==y?y:3),void 0===f&&(f=null!==(m=null==a?void 0:a.retryDelay)&&void 0!==m?m:500),r(w,void 0,void 0,function(){var r,d,y;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,o(e,{method:u,headers:n({"Content-Type":"application/json"},null==a?void 0:a.headers),body:JSON.stringify(t),cacheKey:null==a?void 0:a.cacheKey,signal:s})];case 1:return r=i.sent(),(null==a?void 0:a.optimisticUpdate)&&a.cacheKey&&(l.setData(a.cacheKey,function(e){return a.optimisticUpdate(e,r)}),l.invalidate(a.cacheKey)),null===(y=null==a?void 0:a.onSuccess)||void 0===y||y.call(a,r),[2,r];case 2:if("AbortError"===(d=i.sent()).name)throw d;return[2,h(function(){return v(c-1,2*f)},c-1,2*f)];case 3:return[2]}})})},g.label=1;case 1:return g.trys.push([1,,3,4]),[4,v()];case 2:return[2,g.sent()];case 3:return f(!1),[7];case 4:return[2]}})})},[e,a]),w=t.useCallback(function(){var e;return null===(e=b.current)||void 0===e?void 0:e.abort()},[]);return{mutate:m,loading:s,error:y,cancel:w}},e.useQuery=function(e,t){return p(e,t)},Object.defineProperty(e,"__esModule",{value:!0})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactiveQuery={},e.React)}(this,function(e,t){"use strict";var n=function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};function r(e,t,n,r){return new(n||(n=Promise))(function(i,o){function u(e){try{a(r.next(e))}catch(e){o(e)}}function c(e){try{a(r.throw(e))}catch(e){o(e)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(u,c)}a((r=r.apply(e,t||[])).next())})}function i(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},u=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return u.next=c(0),u.throw=c(1),u.return=c(2),"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function c(c){return function(a){return function(c){if(n)throw new TypeError("Generator is already executing.");for(;u&&(u=0,c[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&c[0]?r.return:c[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,c[1])).done)return i;switch(r=0,i&&(c=[2&c[0],i.value]),c[0]){case 0:case 1:i=c;break;case 4:return o.label++,{value:c[1],done:!1};case 5:o.label++,r=c[1],c=[0];continue;case 7:c=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==c[0]&&2!==c[0])){o=0;continue}if(3===c[0]&&(!i||c[1]>i[0]&&c[1]<i[3])){o.label=c[1];break}if(6===c[0]&&o.label<i[1]){o.label=i[1],i=c;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(c);break}i[2]&&o.ops.pop(),o.trys.pop();continue}c=t.call(e,o)}catch(e){c=[6,e],r=0}finally{n=i=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,a])}}}"function"==typeof SuppressedError&&SuppressedError;var o=new Map,u={register:function(e,t,n,r,i){o.set(e,{cacheKey:e,refetch:t,setData:n,cancel:r,cache:i})},getCache:function(e){var t;return null===(t=o.get(e))||void 0===t?void 0:t.cache},setCache:function(e,t,n){var r,i=o.get(e);i&&(i.cache=t,(null==n?void 0:n.skip)||null===(r=i.setData)||void 0===r||r.call(i,function(){return t}))},setData:function(e,t,n){var r,i=o.get(e);if(i){var u=t(i.cache);i.cache=u,(null==n?void 0:n.skip)||null===(r=i.setData)||void 0===r||r.call(i,function(){return u})}},cancel:function(e){var t,n;null===(n=null===(t=o.get(e))||void 0===t?void 0:t.cancel)||void 0===n||n.call(t)},invalidate:function(e){var t;e?null===(t=o.get(e))||void 0===t||t.refetch():o.forEach(function(e){return e.refetch()})},unregister:function(e){var t,n;null===(n=null===(t=o.get(e))||void 0===t?void 0:t.cancel)||void 0===n||n.call(t),o.delete(e)}},c=new Map,a={set:function(e,t,n){var r=n?Date.now()+n:void 0;c.set(e,{data:t,expireAt:r})},get:function(e){var t=c.get(e);if(t){if(!(t.expireAt&&t.expireAt<Date.now()))return t.data;c.delete(e)}},delete:function(e){c.delete(e)},clear:function(){c.clear()}},l={};var s=new Map;function f(e,t){var o;return void 0===t&&(t={}),r(this,void 0,void 0,function(){var u,c,f,h,d,v=this;return i(this,function(p){if(c=n(n(n({},u=l),t),{headers:n(n({},u.headers),t.headers)}),(null===(o=u.interceptors)||void 0===o?void 0:o.onRequest)&&(c=u.interceptors.onRequest(e,c)),f=c.cacheKey,!!f&&!c.staleTime&&!c.autoFetch){if(h=a.get(f))return[2,h];if(s.has(f))return[2,s.get(f)]}return d=fetch(c.baseURL?c.baseURL+e:e,c).then(function(e){return r(v,void 0,void 0,function(){var t,n,r,o,l;return i(this,function(i){switch(i.label){case 0:if(!e.ok)throw new Error(e.statusText);return[4,e.json()];case 1:if(t=i.sent(),n=c.isGraphQL?t.data:t,c.isGraphQL&&(null===(o=t.errors)||void 0===o?void 0:o.length))throw new Error(t.errors[0].message);return r=(null===(l=u.interceptors)||void 0===l?void 0:l.onResponse)?u.interceptors.onResponse(n):n,f&&a.set(f,r,c.cacheTime),[2,r]}})})}).catch(function(e){var t,n;throw null===(n=null===(t=u.interceptors)||void 0===t?void 0:t.onError)||void 0===n||n.call(t,e),e}).finally(function(){return f&&s.delete(f)}),f&&s.set(f,d),[2,d]})})}var h=null;function d(e,t,n,o){return void 0===t&&(t=3),void 0===n&&(n=500),void 0===o&&(o=1e4),r(this,void 0,void 0,function(){var u,c,a,l=this;return i(this,function(s){return u=new AbortController,c=u.signal,o&&setTimeout(function(){return u.abort()},o),a=function(t){return r(l,void 0,void 0,function(){var r;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,e(c)];case 1:return[2,i.sent()];case 2:if("AbortError"===(r=i.sent()).name)throw r;return t>0?[4,new Promise(function(e){return setTimeout(e,n)})]:[3,4];case 3:return i.sent(),[2,a(t-1)];case 4:throw null==h||h(r),r;case 5:return[2]}})})},[2,a(t)]})})}function v(e,t,n){e&&(u.setData(e,function(e){return n?n(e,t):t}),u.invalidate(e))}function p(e,t){return r(this,void 0,void 0,function(){var r;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,f(e,n(n({},t),{isGraphQL:t.isGraphQL}))];case 1:return[2,i.sent()];case 2:throw r=i.sent(),null==h||h(r,{endpoint:e}),r;case 3:return[2]}})})}var y=function(){function e(e){this.url=e,this.callbacks=new Set,this.ws=null}return e.prototype.connect=function(){var e=this;this.ws||(this.ws=new WebSocket(this.url),this.ws.onmessage=function(t){var n=JSON.parse(t.data);e.callbacks.forEach(function(e){return e(n)})})},e.prototype.subscribe=function(e){var t=this;return this.callbacks.add(e),this.connect(),function(){return t.callbacks.delete(e)}},e.prototype.disconnect=function(){var e;null===(e=this.ws)||void 0===e||e.close(),this.ws=null,this.callbacks.clear()},e}();function b(e,n){var o=this,u=n.query,c=n.variables,a=n.options,l=t.useState(null),s=l[0],f=l[1],h=t.useState(null),b=h[0],m=h[1],w=t.useState(!1),g=w[0],S=w[1],T=t.useRef(null),E=t.useRef(!1),k=t.useMemo(function(){return a||{}},[JSON.stringify(a)]),K=t.useCallback(function(){return r(o,void 0,void 0,function(){var t,n,r,o,a,l,s,h,y;return i(this,function(i){switch(i.label){case 0:null===(o=T.current)||void 0===o||o.abort(),t=new AbortController,T.current=t,S(!0),m(null),i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,d(function(t){var n;return p(e,{query:u,variables:c,body:u?JSON.stringify({query:u,variables:c}):void 0,headers:k.headers,method:u?"POST":null!==(n=k.method)&&void 0!==n?n:"GET",signal:t,cacheKey:k.cacheKey,cacheTime:k.cacheTime,staleTime:k.staleTime,isGraphQL:!!u})},null!==(a=k.retry)&&void 0!==a?a:0,null!==(l=k.retryDelay)&&void 0!==l?l:500,null!==(s=k.timeout)&&void 0!==s?s:1e4)];case 2:return n=i.sent(),k.optimisticUpdate&&k.cacheKey&&v(k.cacheKey,n,k.optimisticUpdate),f(n),null===(h=k.onSuccess)||void 0===h||h.call(k,n),[2,n];case 3:if("AbortError"===(r=i.sent()).name)return[2,null];throw m(r),null===(y=k.onError)||void 0===y||y.call(k,r),r;case 4:return S(!1),[7];case 5:return[2]}})})},[e,u,c,k]),U=t.useCallback(function(){var e;null===(e=T.current)||void 0===e||e.abort()},[]);return t.useEffect(function(){return k.autoFetch&&!E.current&&(E.current=!0,K()),function(){return U()}},[]),t.useEffect(function(){if(k.staleTime){var e=setInterval(function(){return K()},k.staleTime);return function(){return clearInterval(e)}}},[K,k.staleTime]),t.useEffect(function(){if(k.subscriptionUrl){var e=new y(k.subscriptionUrl).subscribe(function(e){f(function(t){return k.optimisticUpdate?k.optimisticUpdate(t,e):e}),k.cacheKey&&v(k.cacheKey,e,k.optimisticUpdate)});return function(){return e()}}},[k.subscriptionUrl,k.optimisticUpdate,k.cacheKey]),{data:s,error:b,loading:g,refetch:K,mutate:f,cancel:U}}e.SubscriptionManager=y,e.applyOptimisticUpdate=v,e.cache=a,e.clearAllCache=function(){a.clear()},e.commonFetch=p,e.fetchWithRetry=d,e.hasCache=function(e){return void 0!==a.get(e)},e.invalidateCache=function(e){a.delete(e)},e.prefetchData=function(e,t,n){e().then(function(e){n.setData(t,function(){return e})}).catch(function(e){console.error("Prefetch error:",e),null==h||h(e)})},e.prefetchQuery=function(e,t){return void 0===t&&(t={}),r(this,void 0,void 0,function(){var r;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,f(e,n(n({},t),{isGraphQL:!!t.query||t.isGraphQL}))];case 1:return[2,i.sent()];case 2:return r=i.sent(),console.error("Prefetch failed",r),[2,null];case 3:return[2]}})})},e.queryRegistry=u,e.setGlobalErrorHandler=function(e){h=e},e.useGraphQLMutation=function(e,n){var o=this,u=t.useState(!1),c=u[0],a=u[1],l=t.useState(null),s=l[0],f=l[1],h=t.useRef(null),y=t.useCallback(function(){return r(o,void 0,void 0,function(){var t,r,o,u,c,l,s,y,b;return i(this,function(i){switch(i.label){case 0:null===(u=h.current)||void 0===u||u.abort(),t=new AbortController,h.current=t,a(!0),f(null),i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,d(function(t){return p(e,{query:n.mutation,variables:n.variables,headers:null==n?void 0:n.headers,signal:t,cacheKey:n.cacheKey,cacheTime:n.cacheTime,isGraphQL:!0})},null!==(c=n.retry)&&void 0!==c?c:0,null!==(l=n.retryDelay)&&void 0!==l?l:500,null!==(s=n.timeout)&&void 0!==s?s:1e4)];case 2:return r=i.sent(),n.optimisticUpdate&&n.cacheKey&&v(n.cacheKey,r,n.optimisticUpdate),null===(y=n.onSuccess)||void 0===y||y.call(n,r),[2,r];case 3:if("AbortError"===(o=i.sent()).name)throw o;throw null===(b=n.onError)||void 0===b||b.call(n,o),f(o),o;case 4:return a(!1),[7];case 5:return[2]}})})},[e,n]),b=t.useCallback(function(){var e;null===(e=h.current)||void 0===e||e.abort(),a(!1)},[]);return{mutate:y,loading:c,error:s,cancel:b}},e.useGraphQLQuery=function(e,t){return b(e,{query:t.query,variables:t.variables,options:t})},e.useHybridQuery=b,e.useMutation=function(e,n){var o=this,u=t.useState(!1),c=u[0],a=u[1],l=t.useState(null),s=l[0],f=l[1],h=t.useRef(null),y=t.useCallback(function(t,u){return void 0===u&&(u="POST"),r(o,void 0,void 0,function(){var r,o,c,l,s,y,b,m,w;return i(this,function(i){switch(i.label){case 0:null===(l=h.current)||void 0===l||l.abort(),r=new AbortController,h.current=r,a(!0),f(null),i.label=1;case 1:return i.trys.push([1,3,4,5]),[4,d(function(r){return p(e,{method:u,headers:null==n?void 0:n.headers,body:t,signal:r,cacheKey:null==n?void 0:n.cacheKey,cacheTime:null==n?void 0:n.cacheTime})},null!==(s=null==n?void 0:n.retry)&&void 0!==s?s:0,null!==(y=null==n?void 0:n.retryDelay)&&void 0!==y?y:500,null!==(b=null==n?void 0:n.timeout)&&void 0!==b?b:1e4)];case 2:return o=i.sent(),(null==n?void 0:n.optimisticUpdate)&&n.cacheKey&&v(n.cacheKey,o,n.optimisticUpdate),null===(m=null==n?void 0:n.onSuccess)||void 0===m||m.call(n,o),[2,o];case 3:if("AbortError"===(c=i.sent()).name)throw c;throw null===(w=null==n?void 0:n.onError)||void 0===w||w.call(n,c),f(c),c;case 4:return a(!1),[7];case 5:return[2]}})})},[e,n]),b=t.useCallback(function(){var e;null===(e=h.current)||void 0===e||e.abort(),a(!1)},[]);return{mutate:y,loading:c,error:s,cancel:b}},e.useQuery=function(e,t){return b(e,{options:t})},Object.defineProperty(e,"__esModule",{value:!0})});
@@ -1 +1,13 @@
1
- export declare function updateCache<T>(cacheKey: string | undefined, optimisticUpdate: ((prevData: T | null, newData: T) => T) | undefined, newData: T): void;
1
+ /**
2
+ * Remove a single cache entry by key
3
+ * @param key - the cache key to delete
4
+ */
5
+ export declare function invalidateCache(key: string): void;
6
+ /**
7
+ * Clear all cache entries
8
+ */
9
+ export declare function clearAllCache(): void;
10
+ /**
11
+ * Check if a cache key exists and is valid
12
+ */
13
+ export declare function hasCache(key: string): boolean;
@@ -1 +1,29 @@
1
- export declare function prefetchData<T>(fetchData: () => Promise<T>, cacheKey: string, cacheRegistry: any): void;
1
+ import { queryRegistry } from "../core/globalQuery";
2
+ import { QueryOptions } from "../hooks/types";
3
+ interface PrefetchParams<TData, TVariables = Record<string, any>> {
4
+ query?: string;
5
+ variables?: TVariables;
6
+ headers?: Record<string, string>;
7
+ body?: any;
8
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
9
+ signal?: AbortSignal;
10
+ }
11
+ type ErrorHandler = (error: any, info?: {
12
+ endpoint: string;
13
+ }) => void;
14
+ export declare function setGlobalErrorHandler(handler: ErrorHandler): void;
15
+ export declare function prefetchData<T>(fetchData: () => Promise<T>, cacheKey: string, cacheRegistry: typeof queryRegistry): void;
16
+ export declare function fetchWithRetry<TData>(fn: (signal: AbortSignal) => Promise<TData>, retries?: number, retryDelay?: number, timeout?: number): Promise<TData>;
17
+ export declare function applyOptimisticUpdate<TData>(cacheKey: string | undefined, newData: TData, optimisticUpdate?: (prev: TData | null | undefined, next: TData) => TData): void;
18
+ export declare function commonFetch<TData>(endpoint: string, options: PrefetchParams<TData> & {
19
+ autoFetch?: boolean;
20
+ staleTime?: number;
21
+ cacheKey?: string;
22
+ cacheTime?: number;
23
+ isGraphQL?: boolean;
24
+ }): Promise<TData>;
25
+ export declare function prefetchQuery<TData>(endpoint: string, options?: QueryOptions<TData, any> & {
26
+ isGraphQL?: boolean;
27
+ query?: string;
28
+ }): Promise<TData | null>;
29
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reactive-query-z",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "Query is a lightweight, reactive library for data fetching and state orchestration in React.",
5
5
  "license": "MIT",
6
6
  "author": "Delpi.Kye",
@@ -1,9 +0,0 @@
1
- export declare function useReactive<T>(initial: T): [T, (v: T) => void];
2
- export declare class ReactiveValue<T> {
3
- private _value;
4
- private listeners;
5
- constructor(value: T);
6
- get(): T;
7
- set(value: T): void;
8
- subscribe(cb: (v: T) => void): () => boolean;
9
- }
@@ -1 +0,0 @@
1
- export declare function retryOperation<T>(operation: () => Promise<T>, retries: number, delay: number): Promise<T>;
@@ -1 +0,0 @@
1
- export declare function createTimeoutSignal(timeout: number): AbortSignal;