enlace 0.0.0-alpha.3 → 0.0.1-beta.1

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/dist/index.d.mts CHANGED
@@ -1,20 +1,97 @@
1
- import { E as EnlaceOptions, F as FetchExecutor, R as RequestOptions, H as HttpMethod, a as EnlaceResponse, W as WildcardClient, b as EnlaceClient } from './types-BX5MGIgP.mjs';
2
- export { c as Endpoint, M as MethodDefinition, S as SchemaMethod } from './types-BX5MGIgP.mjs';
1
+ import { WildcardClient, EnlaceClient, EnlaceResponse, EnlaceOptions } from 'enlace-core';
2
+ export * from 'enlace-core';
3
3
 
4
- declare function createProxyHandler<TSchema extends object, TOptions = EnlaceOptions>(baseUrl: string, defaultOptions: TOptions, path?: string[], fetchExecutor?: FetchExecutor<TOptions, RequestOptions<unknown>>): TSchema;
5
-
6
- declare function executeFetch<TData, TError>(baseUrl: string, path: string[], method: HttpMethod, defaultOptions: EnlaceOptions, requestOptions?: RequestOptions<unknown>): Promise<EnlaceResponse<TData, TError>>;
4
+ /** Per-request options for React hooks */
5
+ type ReactRequestOptionsBase = {
6
+ /**
7
+ * Cache tags for caching (GET requests only)
8
+ * This will auto generate tags from the URL path if not provided and autoGenerateTags is enabled.
9
+ * But can be manually specified to override auto-generation.
10
+ * */
11
+ tags?: string[];
12
+ /** Tags to invalidate after mutation (triggers refetch in matching queries) */
13
+ revalidateTags?: string[];
14
+ };
15
+ type ApiClient<TSchema, TOptions = ReactRequestOptionsBase> = unknown extends TSchema ? WildcardClient<TOptions> : EnlaceClient<TSchema, TOptions>;
16
+ type QueryFn<TSchema, TData, TError, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TOptions>) => Promise<EnlaceResponse<TData, TError>>;
17
+ type SelectorFn<TSchema, TMethod, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TOptions>) => TMethod;
18
+ type HookState = {
19
+ loading: boolean;
20
+ fetching: boolean;
21
+ ok: boolean | undefined;
22
+ data: unknown;
23
+ error: unknown;
24
+ };
25
+ type TrackedCall = {
26
+ path: string[];
27
+ method: string;
28
+ options: unknown;
29
+ };
30
+ declare const HTTP_METHODS: readonly ["get", "post", "put", "patch", "delete"];
31
+ type ExtractData<T> = T extends (...args: any[]) => Promise<EnlaceResponse<infer D, unknown>> ? D : never;
32
+ type ExtractError<T> = T extends (...args: any[]) => Promise<EnlaceResponse<unknown, infer E>> ? E : never;
33
+ /** Discriminated union for hook response state - enables type narrowing on ok check */
34
+ type HookResponseState<TData, TError> = {
35
+ ok: undefined;
36
+ data: undefined;
37
+ error: undefined;
38
+ } | {
39
+ ok: true;
40
+ data: TData;
41
+ error: undefined;
42
+ } | {
43
+ ok: false;
44
+ data: undefined;
45
+ error: TError;
46
+ };
47
+ /** Result when hook is called with query function (auto-fetch mode) */
48
+ type UseEnlaceQueryResult<TData, TError> = {
49
+ loading: boolean;
50
+ fetching: boolean;
51
+ } & HookResponseState<TData, TError>;
52
+ /** Result when hook is called with method selector (trigger mode) */
53
+ type UseEnlaceSelectorResult<TMethod> = {
54
+ trigger: TMethod;
55
+ loading: boolean;
56
+ fetching: boolean;
57
+ } & HookResponseState<ExtractData<TMethod>, ExtractError<TMethod>>;
7
58
 
59
+ type EnlaceHookOptions = {
60
+ /**
61
+ * Auto-generate cache tags from URL path for GET requests.
62
+ * e.g., `/posts/1` generates tags `['posts', 'posts/1']`
63
+ * @default true
64
+ */
65
+ autoGenerateTags?: boolean;
66
+ /** Auto-revalidate generated tags after successful mutations. @default true */
67
+ autoRevalidateTags?: boolean;
68
+ /** Time in ms before cached data is considered stale. @default 0 (always stale) */
69
+ staleTime?: number;
70
+ };
71
+ type EnlaceHook<TSchema> = {
72
+ <TMethod extends (...args: any[]) => Promise<EnlaceResponse<unknown, unknown>>>(selector: SelectorFn<TSchema, TMethod>): UseEnlaceSelectorResult<TMethod>;
73
+ <TData, TError>(queryFn: QueryFn<TSchema, TData, TError>): UseEnlaceQueryResult<TData, TError>;
74
+ };
8
75
  /**
9
- * Creates an API client.
76
+ * Creates a React hook for making API calls.
77
+ * Called at module level to create a reusable hook.
10
78
  *
11
79
  * @example
12
- * // Typed mode - with schema
13
- * const api = createEnlace<MyApi>('https://api.example.com');
80
+ * const useAPI = createEnlaceHook<ApiSchema>('https://api.com');
81
+ *
82
+ * // Query mode - auto-fetch (auto-tracks changes, no deps array needed)
83
+ * const { loading, data, error } = useAPI((api) => api.posts.get({ query: { userId } }));
14
84
  *
15
- * // Untyped mode - no schema
16
- * const api = createEnlace('https://api.example.com');
85
+ * // Selector mode - typed trigger for lazy calls
86
+ * const { trigger, loading, data, error } = useAPI((api) => api.posts.delete);
87
+ * onClick={() => trigger({ body: { id: 1 } })}
17
88
  */
18
- declare function createEnlace<TSchema = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions): unknown extends TSchema ? WildcardClient : EnlaceClient<TSchema>;
89
+ declare function createEnlaceHook<TSchema = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions, hookOptions?: EnlaceHookOptions): EnlaceHook<TSchema>;
90
+
91
+ type Listener = (tags: string[]) => void;
92
+ declare function invalidateTags(tags: string[]): void;
93
+ declare function onRevalidate(callback: Listener): () => void;
94
+
95
+ declare function clearCache(key?: string): void;
19
96
 
20
- export { EnlaceClient, EnlaceOptions, EnlaceResponse, FetchExecutor, HttpMethod, RequestOptions, WildcardClient, createEnlace, createProxyHandler, executeFetch };
97
+ export { type ApiClient, type EnlaceHookOptions, HTTP_METHODS, type HookState, type QueryFn, type ReactRequestOptionsBase, type SelectorFn, type TrackedCall, type UseEnlaceQueryResult, type UseEnlaceSelectorResult, clearCache, createEnlaceHook, invalidateTags, onRevalidate };
package/dist/index.d.ts CHANGED
@@ -1,20 +1,97 @@
1
- import { E as EnlaceOptions, F as FetchExecutor, R as RequestOptions, H as HttpMethod, a as EnlaceResponse, W as WildcardClient, b as EnlaceClient } from './types-BX5MGIgP.js';
2
- export { c as Endpoint, M as MethodDefinition, S as SchemaMethod } from './types-BX5MGIgP.js';
1
+ import { WildcardClient, EnlaceClient, EnlaceResponse, EnlaceOptions } from 'enlace-core';
2
+ export * from 'enlace-core';
3
3
 
4
- declare function createProxyHandler<TSchema extends object, TOptions = EnlaceOptions>(baseUrl: string, defaultOptions: TOptions, path?: string[], fetchExecutor?: FetchExecutor<TOptions, RequestOptions<unknown>>): TSchema;
5
-
6
- declare function executeFetch<TData, TError>(baseUrl: string, path: string[], method: HttpMethod, defaultOptions: EnlaceOptions, requestOptions?: RequestOptions<unknown>): Promise<EnlaceResponse<TData, TError>>;
4
+ /** Per-request options for React hooks */
5
+ type ReactRequestOptionsBase = {
6
+ /**
7
+ * Cache tags for caching (GET requests only)
8
+ * This will auto generate tags from the URL path if not provided and autoGenerateTags is enabled.
9
+ * But can be manually specified to override auto-generation.
10
+ * */
11
+ tags?: string[];
12
+ /** Tags to invalidate after mutation (triggers refetch in matching queries) */
13
+ revalidateTags?: string[];
14
+ };
15
+ type ApiClient<TSchema, TOptions = ReactRequestOptionsBase> = unknown extends TSchema ? WildcardClient<TOptions> : EnlaceClient<TSchema, TOptions>;
16
+ type QueryFn<TSchema, TData, TError, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TOptions>) => Promise<EnlaceResponse<TData, TError>>;
17
+ type SelectorFn<TSchema, TMethod, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TOptions>) => TMethod;
18
+ type HookState = {
19
+ loading: boolean;
20
+ fetching: boolean;
21
+ ok: boolean | undefined;
22
+ data: unknown;
23
+ error: unknown;
24
+ };
25
+ type TrackedCall = {
26
+ path: string[];
27
+ method: string;
28
+ options: unknown;
29
+ };
30
+ declare const HTTP_METHODS: readonly ["get", "post", "put", "patch", "delete"];
31
+ type ExtractData<T> = T extends (...args: any[]) => Promise<EnlaceResponse<infer D, unknown>> ? D : never;
32
+ type ExtractError<T> = T extends (...args: any[]) => Promise<EnlaceResponse<unknown, infer E>> ? E : never;
33
+ /** Discriminated union for hook response state - enables type narrowing on ok check */
34
+ type HookResponseState<TData, TError> = {
35
+ ok: undefined;
36
+ data: undefined;
37
+ error: undefined;
38
+ } | {
39
+ ok: true;
40
+ data: TData;
41
+ error: undefined;
42
+ } | {
43
+ ok: false;
44
+ data: undefined;
45
+ error: TError;
46
+ };
47
+ /** Result when hook is called with query function (auto-fetch mode) */
48
+ type UseEnlaceQueryResult<TData, TError> = {
49
+ loading: boolean;
50
+ fetching: boolean;
51
+ } & HookResponseState<TData, TError>;
52
+ /** Result when hook is called with method selector (trigger mode) */
53
+ type UseEnlaceSelectorResult<TMethod> = {
54
+ trigger: TMethod;
55
+ loading: boolean;
56
+ fetching: boolean;
57
+ } & HookResponseState<ExtractData<TMethod>, ExtractError<TMethod>>;
7
58
 
59
+ type EnlaceHookOptions = {
60
+ /**
61
+ * Auto-generate cache tags from URL path for GET requests.
62
+ * e.g., `/posts/1` generates tags `['posts', 'posts/1']`
63
+ * @default true
64
+ */
65
+ autoGenerateTags?: boolean;
66
+ /** Auto-revalidate generated tags after successful mutations. @default true */
67
+ autoRevalidateTags?: boolean;
68
+ /** Time in ms before cached data is considered stale. @default 0 (always stale) */
69
+ staleTime?: number;
70
+ };
71
+ type EnlaceHook<TSchema> = {
72
+ <TMethod extends (...args: any[]) => Promise<EnlaceResponse<unknown, unknown>>>(selector: SelectorFn<TSchema, TMethod>): UseEnlaceSelectorResult<TMethod>;
73
+ <TData, TError>(queryFn: QueryFn<TSchema, TData, TError>): UseEnlaceQueryResult<TData, TError>;
74
+ };
8
75
  /**
9
- * Creates an API client.
76
+ * Creates a React hook for making API calls.
77
+ * Called at module level to create a reusable hook.
10
78
  *
11
79
  * @example
12
- * // Typed mode - with schema
13
- * const api = createEnlace<MyApi>('https://api.example.com');
80
+ * const useAPI = createEnlaceHook<ApiSchema>('https://api.com');
81
+ *
82
+ * // Query mode - auto-fetch (auto-tracks changes, no deps array needed)
83
+ * const { loading, data, error } = useAPI((api) => api.posts.get({ query: { userId } }));
14
84
  *
15
- * // Untyped mode - no schema
16
- * const api = createEnlace('https://api.example.com');
85
+ * // Selector mode - typed trigger for lazy calls
86
+ * const { trigger, loading, data, error } = useAPI((api) => api.posts.delete);
87
+ * onClick={() => trigger({ body: { id: 1 } })}
17
88
  */
18
- declare function createEnlace<TSchema = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions): unknown extends TSchema ? WildcardClient : EnlaceClient<TSchema>;
89
+ declare function createEnlaceHook<TSchema = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions, hookOptions?: EnlaceHookOptions): EnlaceHook<TSchema>;
90
+
91
+ type Listener = (tags: string[]) => void;
92
+ declare function invalidateTags(tags: string[]): void;
93
+ declare function onRevalidate(callback: Listener): () => void;
94
+
95
+ declare function clearCache(key?: string): void;
19
96
 
20
- export { EnlaceClient, EnlaceOptions, EnlaceResponse, FetchExecutor, HttpMethod, RequestOptions, WildcardClient, createEnlace, createProxyHandler, executeFetch };
97
+ export { type ApiClient, type EnlaceHookOptions, HTTP_METHODS, type HookState, type QueryFn, type ReactRequestOptionsBase, type SelectorFn, type TrackedCall, type UseEnlaceQueryResult, type UseEnlaceSelectorResult, clearCache, createEnlaceHook, invalidateTags, onRevalidate };
package/dist/index.js CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,120 +15,355 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
18
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
28
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
20
 
30
21
  // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- createEnlace: () => createEnlace,
34
- createProxyHandler: () => createProxyHandler,
35
- executeFetch: () => executeFetch
22
+ var src_exports = {};
23
+ __export(src_exports, {
24
+ HTTP_METHODS: () => HTTP_METHODS,
25
+ clearCache: () => clearCache,
26
+ createEnlaceHook: () => createEnlaceHook,
27
+ invalidateTags: () => invalidateTags,
28
+ onRevalidate: () => onRevalidate
36
29
  });
37
- module.exports = __toCommonJS(index_exports);
30
+ module.exports = __toCommonJS(src_exports);
31
+ __reExport(src_exports, require("enlace-core"), module.exports);
38
32
 
39
- // src/utils/buildUrl.ts
40
- var import_query_string = __toESM(require("query-string"));
41
- function buildUrl(baseUrl, path, query) {
42
- const url = new URL(path.join("/"), baseUrl);
43
- if (query) {
44
- url.search = import_query_string.default.stringify(query, { skipNull: true, skipEmptyString: true });
33
+ // src/react/createEnlaceHook.ts
34
+ var import_enlace_core = require("enlace-core");
35
+
36
+ // src/react/useQueryMode.ts
37
+ var import_react = require("react");
38
+
39
+ // src/react/reducer.ts
40
+ var initialState = {
41
+ loading: false,
42
+ fetching: false,
43
+ ok: void 0,
44
+ data: void 0,
45
+ error: void 0
46
+ };
47
+ function hookReducer(state, action) {
48
+ switch (action.type) {
49
+ case "RESET":
50
+ return action.state;
51
+ case "FETCH_START":
52
+ return {
53
+ ...state,
54
+ loading: state.data === void 0,
55
+ fetching: true
56
+ };
57
+ case "FETCH_SUCCESS":
58
+ return {
59
+ loading: false,
60
+ fetching: false,
61
+ ok: true,
62
+ data: action.data,
63
+ error: void 0
64
+ };
65
+ case "FETCH_ERROR":
66
+ return {
67
+ loading: false,
68
+ fetching: false,
69
+ ok: false,
70
+ data: void 0,
71
+ error: action.error
72
+ };
73
+ case "SYNC_CACHE":
74
+ return action.state;
75
+ default:
76
+ return state;
45
77
  }
46
- return url.toString();
47
78
  }
48
79
 
49
- // src/utils/isJsonBody.ts
50
- function isJsonBody(body) {
51
- if (body === null || body === void 0) return false;
52
- if (body instanceof FormData) return false;
53
- if (body instanceof Blob) return false;
54
- if (body instanceof ArrayBuffer) return false;
55
- if (body instanceof URLSearchParams) return false;
56
- if (body instanceof ReadableStream) return false;
57
- if (typeof body === "string") return false;
58
- return typeof body === "object";
80
+ // src/utils/generateTags.ts
81
+ function generateTags(path) {
82
+ return path.map((_, i) => path.slice(0, i + 1).join("/"));
59
83
  }
60
84
 
61
- // src/utils/mergeHeaders.ts
62
- function mergeHeaders(defaultHeaders, requestHeaders) {
63
- if (!defaultHeaders && !requestHeaders) return void 0;
64
- if (!defaultHeaders) return requestHeaders;
65
- if (!requestHeaders) return defaultHeaders;
66
- return {
67
- ...Object.fromEntries(new Headers(defaultHeaders)),
68
- ...Object.fromEntries(new Headers(requestHeaders))
69
- };
85
+ // src/utils/sortObjectKeys.ts
86
+ function sortObjectKeys(obj) {
87
+ if (obj === null || typeof obj !== "object") return obj;
88
+ if (Array.isArray(obj)) return obj.map(sortObjectKeys);
89
+ return Object.keys(obj).sort().reduce(
90
+ (sorted, key) => {
91
+ sorted[key] = sortObjectKeys(obj[key]);
92
+ return sorted;
93
+ },
94
+ {}
95
+ );
70
96
  }
71
97
 
72
- // src/core/fetch.ts
73
- async function executeFetch(baseUrl, path, method, defaultOptions, requestOptions) {
74
- const url = buildUrl(baseUrl, path, requestOptions?.query);
75
- let headers = mergeHeaders(defaultOptions.headers, requestOptions?.headers);
76
- const fetchOptions = {
77
- ...defaultOptions,
78
- method
98
+ // src/react/cache.ts
99
+ var cache = /* @__PURE__ */ new Map();
100
+ function createQueryKey(tracked) {
101
+ return JSON.stringify(
102
+ sortObjectKeys({
103
+ path: tracked.path,
104
+ method: tracked.method,
105
+ options: tracked.options
106
+ })
107
+ );
108
+ }
109
+ function getCache(key) {
110
+ return cache.get(key);
111
+ }
112
+ function setCache(key, entry) {
113
+ const existing = cache.get(key);
114
+ if (existing) {
115
+ if ("ok" in entry) {
116
+ delete existing.promise;
117
+ }
118
+ Object.assign(existing, entry);
119
+ existing.subscribers.forEach((cb) => cb());
120
+ } else {
121
+ cache.set(key, {
122
+ data: void 0,
123
+ error: void 0,
124
+ ok: void 0,
125
+ timestamp: 0,
126
+ tags: [],
127
+ subscribers: /* @__PURE__ */ new Set(),
128
+ ...entry
129
+ });
130
+ }
131
+ }
132
+ function subscribeCache(key, callback) {
133
+ let entry = cache.get(key);
134
+ if (!entry) {
135
+ cache.set(key, {
136
+ data: void 0,
137
+ error: void 0,
138
+ ok: void 0,
139
+ timestamp: 0,
140
+ tags: [],
141
+ subscribers: /* @__PURE__ */ new Set()
142
+ });
143
+ entry = cache.get(key);
144
+ }
145
+ entry.subscribers.add(callback);
146
+ return () => {
147
+ entry.subscribers.delete(callback);
79
148
  };
80
- if (headers) {
81
- fetchOptions.headers = headers;
149
+ }
150
+ function isStale(key, staleTime) {
151
+ const entry = cache.get(key);
152
+ if (!entry) return true;
153
+ return Date.now() - entry.timestamp > staleTime;
154
+ }
155
+ function clearCache(key) {
156
+ if (key) {
157
+ cache.delete(key);
158
+ } else {
159
+ cache.clear();
82
160
  }
83
- if (requestOptions?.body !== void 0) {
84
- if (isJsonBody(requestOptions.body)) {
85
- fetchOptions.body = JSON.stringify(requestOptions.body);
86
- headers = mergeHeaders(headers, { "Content-Type": "application/json" });
87
- if (headers) {
88
- fetchOptions.headers = headers;
161
+ }
162
+ function clearCacheByTags(tags) {
163
+ cache.forEach((entry) => {
164
+ const hasMatch = entry.tags.some((tag) => tags.includes(tag));
165
+ if (hasMatch) {
166
+ entry.data = void 0;
167
+ entry.error = void 0;
168
+ entry.ok = void 0;
169
+ entry.timestamp = 0;
170
+ delete entry.promise;
171
+ }
172
+ });
173
+ }
174
+
175
+ // src/react/revalidator.ts
176
+ var listeners = /* @__PURE__ */ new Set();
177
+ function invalidateTags(tags) {
178
+ clearCacheByTags(tags);
179
+ listeners.forEach((listener) => listener(tags));
180
+ }
181
+ function onRevalidate(callback) {
182
+ listeners.add(callback);
183
+ return () => listeners.delete(callback);
184
+ }
185
+
186
+ // src/react/useQueryMode.ts
187
+ function useQueryMode(api, trackedCall, options) {
188
+ const { autoGenerateTags, staleTime } = options;
189
+ const queryKey = createQueryKey(trackedCall);
190
+ const requestOptions = trackedCall.options;
191
+ const queryTags = requestOptions?.tags ?? (autoGenerateTags ? generateTags(trackedCall.path) : []);
192
+ const getCacheState = (includeNeedsFetch = false) => {
193
+ const cached = getCache(queryKey);
194
+ const hasCachedData = cached?.data !== void 0;
195
+ const isFetching = !!cached?.promise;
196
+ const needsFetch = includeNeedsFetch && (!hasCachedData || isStale(queryKey, staleTime));
197
+ return {
198
+ loading: !hasCachedData && (isFetching || needsFetch),
199
+ fetching: isFetching || needsFetch,
200
+ ok: cached?.ok,
201
+ data: cached?.data,
202
+ error: cached?.error
203
+ };
204
+ };
205
+ const [state, dispatch] = (0, import_react.useReducer)(hookReducer, null, () => getCacheState(true));
206
+ const mountedRef = (0, import_react.useRef)(true);
207
+ const fetchRef = (0, import_react.useRef)(null);
208
+ (0, import_react.useEffect)(() => {
209
+ mountedRef.current = true;
210
+ dispatch({ type: "RESET", state: getCacheState(true) });
211
+ const unsubscribe = subscribeCache(queryKey, () => {
212
+ if (mountedRef.current) {
213
+ dispatch({ type: "SYNC_CACHE", state: getCacheState() });
214
+ }
215
+ });
216
+ const doFetch = () => {
217
+ const cached2 = getCache(queryKey);
218
+ if (cached2?.promise) {
219
+ return;
89
220
  }
221
+ dispatch({ type: "FETCH_START" });
222
+ let current = api;
223
+ for (const segment of trackedCall.path) {
224
+ current = current[segment];
225
+ }
226
+ const method = current[trackedCall.method];
227
+ const fetchPromise = method(trackedCall.options).then((res) => {
228
+ if (mountedRef.current) {
229
+ setCache(queryKey, {
230
+ data: res.ok ? res.data : void 0,
231
+ error: res.ok ? void 0 : res.error,
232
+ ok: res.ok,
233
+ timestamp: Date.now(),
234
+ tags: queryTags
235
+ });
236
+ }
237
+ });
238
+ setCache(queryKey, {
239
+ promise: fetchPromise,
240
+ tags: queryTags
241
+ });
242
+ };
243
+ fetchRef.current = doFetch;
244
+ const cached = getCache(queryKey);
245
+ if (cached?.data !== void 0 && !isStale(queryKey, staleTime)) {
246
+ dispatch({ type: "SYNC_CACHE", state: getCacheState() });
90
247
  } else {
91
- fetchOptions.body = requestOptions.body;
248
+ doFetch();
92
249
  }
93
- }
94
- const response = await fetch(url, fetchOptions);
95
- const contentType = response.headers.get("content-type");
96
- const isJson = contentType?.includes("application/json");
97
- if (response.ok) {
98
- return {
99
- ok: true,
100
- status: response.status,
101
- data: isJson ? await response.json() : response
250
+ return () => {
251
+ mountedRef.current = false;
252
+ fetchRef.current = null;
253
+ unsubscribe();
102
254
  };
103
- }
104
- return {
105
- ok: false,
106
- status: response.status,
107
- error: isJson ? await response.json() : response
255
+ }, [queryKey]);
256
+ (0, import_react.useEffect)(() => {
257
+ if (queryTags.length === 0) return;
258
+ return onRevalidate((invalidatedTags) => {
259
+ const hasMatch = invalidatedTags.some((tag) => queryTags.includes(tag));
260
+ if (hasMatch && mountedRef.current && fetchRef.current) {
261
+ fetchRef.current();
262
+ }
263
+ });
264
+ }, [JSON.stringify(queryTags)]);
265
+ return state;
266
+ }
267
+
268
+ // src/react/types.ts
269
+ var HTTP_METHODS = ["get", "post", "put", "patch", "delete"];
270
+
271
+ // src/react/trackingProxy.ts
272
+ function createTrackingProxy(onTrack) {
273
+ const createProxy = (path = []) => {
274
+ return new Proxy(() => {
275
+ }, {
276
+ get(_, prop) {
277
+ if (HTTP_METHODS.includes(prop)) {
278
+ const methodFn = (options) => {
279
+ onTrack({
280
+ trackedCall: { path, method: prop, options },
281
+ selectorPath: null,
282
+ selectorMethod: null
283
+ });
284
+ return Promise.resolve({ ok: true, data: void 0 });
285
+ };
286
+ onTrack({
287
+ trackedCall: null,
288
+ selectorPath: path,
289
+ selectorMethod: prop
290
+ });
291
+ return methodFn;
292
+ }
293
+ return createProxy([...path, prop]);
294
+ }
295
+ });
108
296
  };
297
+ return createProxy();
109
298
  }
110
299
 
111
- // src/core/proxy.ts
112
- var HTTP_METHODS = {
113
- get: "GET",
114
- post: "POST",
115
- put: "PUT",
116
- patch: "PATCH",
117
- delete: "DELETE"
118
- };
119
- function createProxyHandler(baseUrl, defaultOptions, path = [], fetchExecutor = executeFetch) {
120
- const handler = {
121
- get(_target, prop) {
122
- if (typeof prop === "symbol") return void 0;
123
- const method = HTTP_METHODS[prop];
124
- if (method) {
125
- return (options) => fetchExecutor(baseUrl, path, method, defaultOptions, options);
300
+ // src/react/useSelectorMode.ts
301
+ var import_react2 = require("react");
302
+ function useSelectorMode(method, path, autoRevalidateTags) {
303
+ const [state, dispatch] = (0, import_react2.useReducer)(hookReducer, initialState);
304
+ const methodRef = (0, import_react2.useRef)(method);
305
+ const triggerRef = (0, import_react2.useRef)(null);
306
+ const pathRef = (0, import_react2.useRef)(path);
307
+ const autoRevalidateRef = (0, import_react2.useRef)(autoRevalidateTags);
308
+ methodRef.current = method;
309
+ pathRef.current = path;
310
+ autoRevalidateRef.current = autoRevalidateTags;
311
+ if (!triggerRef.current) {
312
+ triggerRef.current = (async (...args) => {
313
+ dispatch({ type: "FETCH_START" });
314
+ const res = await methodRef.current(...args);
315
+ if (res.ok) {
316
+ dispatch({ type: "FETCH_SUCCESS", data: res.data });
317
+ const options = args[0];
318
+ const tagsToInvalidate = options?.revalidateTags ?? (autoRevalidateRef.current ? generateTags(pathRef.current) : []);
319
+ if (tagsToInvalidate.length > 0) {
320
+ invalidateTags(tagsToInvalidate);
321
+ }
322
+ } else {
323
+ dispatch({ type: "FETCH_ERROR", error: res.error });
126
324
  }
127
- return createProxyHandler(baseUrl, defaultOptions, [...path, prop], fetchExecutor);
128
- }
325
+ return res;
326
+ });
327
+ }
328
+ return {
329
+ trigger: triggerRef.current,
330
+ ...state
129
331
  };
130
- return new Proxy({}, handler);
131
332
  }
132
333
 
133
- // src/core/index.ts
134
- function createEnlace(baseUrl, defaultOptions = {}) {
135
- return createProxyHandler(baseUrl, defaultOptions);
334
+ // src/react/createEnlaceHook.ts
335
+ function createEnlaceHook(baseUrl, defaultOptions = {}, hookOptions = {}) {
336
+ const api = (0, import_enlace_core.createEnlace)(baseUrl, defaultOptions);
337
+ const {
338
+ autoGenerateTags = true,
339
+ autoRevalidateTags = true,
340
+ staleTime = 0
341
+ } = hookOptions;
342
+ function useEnlaceHook(selectorOrQuery) {
343
+ let trackingResult = {
344
+ trackedCall: null,
345
+ selectorPath: null,
346
+ selectorMethod: null
347
+ };
348
+ const trackingProxy = createTrackingProxy((result2) => {
349
+ trackingResult = result2;
350
+ });
351
+ const result = selectorOrQuery(
352
+ trackingProxy
353
+ );
354
+ if (typeof result === "function") {
355
+ const actualResult = selectorOrQuery(api);
356
+ return useSelectorMode(
357
+ actualResult,
358
+ trackingResult.selectorPath ?? [],
359
+ autoRevalidateTags
360
+ );
361
+ }
362
+ return useQueryMode(
363
+ api,
364
+ trackingResult.trackedCall,
365
+ { autoGenerateTags, staleTime }
366
+ );
367
+ }
368
+ return useEnlaceHook;
136
369
  }