enlace 0.0.0-alpha.4 → 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.mjs CHANGED
@@ -1,104 +1,349 @@
1
- // src/utils/buildUrl.ts
2
- import qs from "query-string";
3
- function buildUrl(baseUrl, path, query) {
4
- const normalizedBase = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
5
- const url = new URL(path.join("/"), normalizedBase);
6
- if (query) {
7
- url.search = qs.stringify(query, { skipNull: true, skipEmptyString: true });
1
+ // src/index.ts
2
+ export * from "enlace-core";
3
+
4
+ // src/react/createEnlaceHook.ts
5
+ import {
6
+ createEnlace
7
+ } from "enlace-core";
8
+
9
+ // src/react/useQueryMode.ts
10
+ import { useRef, useReducer, useEffect } from "react";
11
+
12
+ // src/react/reducer.ts
13
+ var initialState = {
14
+ loading: false,
15
+ fetching: false,
16
+ ok: void 0,
17
+ data: void 0,
18
+ error: void 0
19
+ };
20
+ function hookReducer(state, action) {
21
+ switch (action.type) {
22
+ case "RESET":
23
+ return action.state;
24
+ case "FETCH_START":
25
+ return {
26
+ ...state,
27
+ loading: state.data === void 0,
28
+ fetching: true
29
+ };
30
+ case "FETCH_SUCCESS":
31
+ return {
32
+ loading: false,
33
+ fetching: false,
34
+ ok: true,
35
+ data: action.data,
36
+ error: void 0
37
+ };
38
+ case "FETCH_ERROR":
39
+ return {
40
+ loading: false,
41
+ fetching: false,
42
+ ok: false,
43
+ data: void 0,
44
+ error: action.error
45
+ };
46
+ case "SYNC_CACHE":
47
+ return action.state;
48
+ default:
49
+ return state;
8
50
  }
9
- return url.toString();
10
51
  }
11
52
 
12
- // src/utils/isJsonBody.ts
13
- function isJsonBody(body) {
14
- if (body === null || body === void 0) return false;
15
- if (body instanceof FormData) return false;
16
- if (body instanceof Blob) return false;
17
- if (body instanceof ArrayBuffer) return false;
18
- if (body instanceof URLSearchParams) return false;
19
- if (body instanceof ReadableStream) return false;
20
- if (typeof body === "string") return false;
21
- return typeof body === "object";
53
+ // src/utils/generateTags.ts
54
+ function generateTags(path) {
55
+ return path.map((_, i) => path.slice(0, i + 1).join("/"));
22
56
  }
23
57
 
24
- // src/utils/mergeHeaders.ts
25
- function mergeHeaders(defaultHeaders, requestHeaders) {
26
- if (!defaultHeaders && !requestHeaders) return void 0;
27
- if (!defaultHeaders) return requestHeaders;
28
- if (!requestHeaders) return defaultHeaders;
29
- return {
30
- ...Object.fromEntries(new Headers(defaultHeaders)),
31
- ...Object.fromEntries(new Headers(requestHeaders))
32
- };
58
+ // src/utils/sortObjectKeys.ts
59
+ function sortObjectKeys(obj) {
60
+ if (obj === null || typeof obj !== "object") return obj;
61
+ if (Array.isArray(obj)) return obj.map(sortObjectKeys);
62
+ return Object.keys(obj).sort().reduce(
63
+ (sorted, key) => {
64
+ sorted[key] = sortObjectKeys(obj[key]);
65
+ return sorted;
66
+ },
67
+ {}
68
+ );
33
69
  }
34
70
 
35
- // src/core/fetch.ts
36
- async function executeFetch(baseUrl, path, method, defaultOptions, requestOptions) {
37
- const url = buildUrl(baseUrl, path, requestOptions?.query);
38
- let headers = mergeHeaders(defaultOptions.headers, requestOptions?.headers);
39
- const fetchOptions = {
40
- ...defaultOptions,
41
- method
71
+ // src/react/cache.ts
72
+ var cache = /* @__PURE__ */ new Map();
73
+ function createQueryKey(tracked) {
74
+ return JSON.stringify(
75
+ sortObjectKeys({
76
+ path: tracked.path,
77
+ method: tracked.method,
78
+ options: tracked.options
79
+ })
80
+ );
81
+ }
82
+ function getCache(key) {
83
+ return cache.get(key);
84
+ }
85
+ function setCache(key, entry) {
86
+ const existing = cache.get(key);
87
+ if (existing) {
88
+ if ("ok" in entry) {
89
+ delete existing.promise;
90
+ }
91
+ Object.assign(existing, entry);
92
+ existing.subscribers.forEach((cb) => cb());
93
+ } else {
94
+ cache.set(key, {
95
+ data: void 0,
96
+ error: void 0,
97
+ ok: void 0,
98
+ timestamp: 0,
99
+ tags: [],
100
+ subscribers: /* @__PURE__ */ new Set(),
101
+ ...entry
102
+ });
103
+ }
104
+ }
105
+ function subscribeCache(key, callback) {
106
+ let entry = cache.get(key);
107
+ if (!entry) {
108
+ cache.set(key, {
109
+ data: void 0,
110
+ error: void 0,
111
+ ok: void 0,
112
+ timestamp: 0,
113
+ tags: [],
114
+ subscribers: /* @__PURE__ */ new Set()
115
+ });
116
+ entry = cache.get(key);
117
+ }
118
+ entry.subscribers.add(callback);
119
+ return () => {
120
+ entry.subscribers.delete(callback);
42
121
  };
43
- if (headers) {
44
- fetchOptions.headers = headers;
122
+ }
123
+ function isStale(key, staleTime) {
124
+ const entry = cache.get(key);
125
+ if (!entry) return true;
126
+ return Date.now() - entry.timestamp > staleTime;
127
+ }
128
+ function clearCache(key) {
129
+ if (key) {
130
+ cache.delete(key);
131
+ } else {
132
+ cache.clear();
45
133
  }
46
- if (requestOptions?.body !== void 0) {
47
- if (isJsonBody(requestOptions.body)) {
48
- fetchOptions.body = JSON.stringify(requestOptions.body);
49
- headers = mergeHeaders(headers, { "Content-Type": "application/json" });
50
- if (headers) {
51
- fetchOptions.headers = headers;
134
+ }
135
+ function clearCacheByTags(tags) {
136
+ cache.forEach((entry) => {
137
+ const hasMatch = entry.tags.some((tag) => tags.includes(tag));
138
+ if (hasMatch) {
139
+ entry.data = void 0;
140
+ entry.error = void 0;
141
+ entry.ok = void 0;
142
+ entry.timestamp = 0;
143
+ delete entry.promise;
144
+ }
145
+ });
146
+ }
147
+
148
+ // src/react/revalidator.ts
149
+ var listeners = /* @__PURE__ */ new Set();
150
+ function invalidateTags(tags) {
151
+ clearCacheByTags(tags);
152
+ listeners.forEach((listener) => listener(tags));
153
+ }
154
+ function onRevalidate(callback) {
155
+ listeners.add(callback);
156
+ return () => listeners.delete(callback);
157
+ }
158
+
159
+ // src/react/useQueryMode.ts
160
+ function useQueryMode(api, trackedCall, options) {
161
+ const { autoGenerateTags, staleTime } = options;
162
+ const queryKey = createQueryKey(trackedCall);
163
+ const requestOptions = trackedCall.options;
164
+ const queryTags = requestOptions?.tags ?? (autoGenerateTags ? generateTags(trackedCall.path) : []);
165
+ const getCacheState = (includeNeedsFetch = false) => {
166
+ const cached = getCache(queryKey);
167
+ const hasCachedData = cached?.data !== void 0;
168
+ const isFetching = !!cached?.promise;
169
+ const needsFetch = includeNeedsFetch && (!hasCachedData || isStale(queryKey, staleTime));
170
+ return {
171
+ loading: !hasCachedData && (isFetching || needsFetch),
172
+ fetching: isFetching || needsFetch,
173
+ ok: cached?.ok,
174
+ data: cached?.data,
175
+ error: cached?.error
176
+ };
177
+ };
178
+ const [state, dispatch] = useReducer(hookReducer, null, () => getCacheState(true));
179
+ const mountedRef = useRef(true);
180
+ const fetchRef = useRef(null);
181
+ useEffect(() => {
182
+ mountedRef.current = true;
183
+ dispatch({ type: "RESET", state: getCacheState(true) });
184
+ const unsubscribe = subscribeCache(queryKey, () => {
185
+ if (mountedRef.current) {
186
+ dispatch({ type: "SYNC_CACHE", state: getCacheState() });
187
+ }
188
+ });
189
+ const doFetch = () => {
190
+ const cached2 = getCache(queryKey);
191
+ if (cached2?.promise) {
192
+ return;
52
193
  }
194
+ dispatch({ type: "FETCH_START" });
195
+ let current = api;
196
+ for (const segment of trackedCall.path) {
197
+ current = current[segment];
198
+ }
199
+ const method = current[trackedCall.method];
200
+ const fetchPromise = method(trackedCall.options).then((res) => {
201
+ if (mountedRef.current) {
202
+ setCache(queryKey, {
203
+ data: res.ok ? res.data : void 0,
204
+ error: res.ok ? void 0 : res.error,
205
+ ok: res.ok,
206
+ timestamp: Date.now(),
207
+ tags: queryTags
208
+ });
209
+ }
210
+ });
211
+ setCache(queryKey, {
212
+ promise: fetchPromise,
213
+ tags: queryTags
214
+ });
215
+ };
216
+ fetchRef.current = doFetch;
217
+ const cached = getCache(queryKey);
218
+ if (cached?.data !== void 0 && !isStale(queryKey, staleTime)) {
219
+ dispatch({ type: "SYNC_CACHE", state: getCacheState() });
53
220
  } else {
54
- fetchOptions.body = requestOptions.body;
221
+ doFetch();
55
222
  }
56
- }
57
- const response = await fetch(url, fetchOptions);
58
- const contentType = response.headers.get("content-type");
59
- const isJson = contentType?.includes("application/json");
60
- if (response.ok) {
61
- return {
62
- ok: true,
63
- status: response.status,
64
- data: isJson ? await response.json() : response
223
+ return () => {
224
+ mountedRef.current = false;
225
+ fetchRef.current = null;
226
+ unsubscribe();
65
227
  };
66
- }
67
- return {
68
- ok: false,
69
- status: response.status,
70
- error: isJson ? await response.json() : response
228
+ }, [queryKey]);
229
+ useEffect(() => {
230
+ if (queryTags.length === 0) return;
231
+ return onRevalidate((invalidatedTags) => {
232
+ const hasMatch = invalidatedTags.some((tag) => queryTags.includes(tag));
233
+ if (hasMatch && mountedRef.current && fetchRef.current) {
234
+ fetchRef.current();
235
+ }
236
+ });
237
+ }, [JSON.stringify(queryTags)]);
238
+ return state;
239
+ }
240
+
241
+ // src/react/types.ts
242
+ var HTTP_METHODS = ["get", "post", "put", "patch", "delete"];
243
+
244
+ // src/react/trackingProxy.ts
245
+ function createTrackingProxy(onTrack) {
246
+ const createProxy = (path = []) => {
247
+ return new Proxy(() => {
248
+ }, {
249
+ get(_, prop) {
250
+ if (HTTP_METHODS.includes(prop)) {
251
+ const methodFn = (options) => {
252
+ onTrack({
253
+ trackedCall: { path, method: prop, options },
254
+ selectorPath: null,
255
+ selectorMethod: null
256
+ });
257
+ return Promise.resolve({ ok: true, data: void 0 });
258
+ };
259
+ onTrack({
260
+ trackedCall: null,
261
+ selectorPath: path,
262
+ selectorMethod: prop
263
+ });
264
+ return methodFn;
265
+ }
266
+ return createProxy([...path, prop]);
267
+ }
268
+ });
71
269
  };
270
+ return createProxy();
72
271
  }
73
272
 
74
- // src/core/proxy.ts
75
- var HTTP_METHODS = {
76
- get: "GET",
77
- post: "POST",
78
- put: "PUT",
79
- patch: "PATCH",
80
- delete: "DELETE"
81
- };
82
- function createProxyHandler(baseUrl, defaultOptions, path = [], fetchExecutor = executeFetch) {
83
- const handler = {
84
- get(_target, prop) {
85
- if (typeof prop === "symbol") return void 0;
86
- const method = HTTP_METHODS[prop];
87
- if (method) {
88
- return (options) => fetchExecutor(baseUrl, path, method, defaultOptions, options);
273
+ // src/react/useSelectorMode.ts
274
+ import { useRef as useRef2, useReducer as useReducer2 } from "react";
275
+ function useSelectorMode(method, path, autoRevalidateTags) {
276
+ const [state, dispatch] = useReducer2(hookReducer, initialState);
277
+ const methodRef = useRef2(method);
278
+ const triggerRef = useRef2(null);
279
+ const pathRef = useRef2(path);
280
+ const autoRevalidateRef = useRef2(autoRevalidateTags);
281
+ methodRef.current = method;
282
+ pathRef.current = path;
283
+ autoRevalidateRef.current = autoRevalidateTags;
284
+ if (!triggerRef.current) {
285
+ triggerRef.current = (async (...args) => {
286
+ dispatch({ type: "FETCH_START" });
287
+ const res = await methodRef.current(...args);
288
+ if (res.ok) {
289
+ dispatch({ type: "FETCH_SUCCESS", data: res.data });
290
+ const options = args[0];
291
+ const tagsToInvalidate = options?.revalidateTags ?? (autoRevalidateRef.current ? generateTags(pathRef.current) : []);
292
+ if (tagsToInvalidate.length > 0) {
293
+ invalidateTags(tagsToInvalidate);
294
+ }
295
+ } else {
296
+ dispatch({ type: "FETCH_ERROR", error: res.error });
89
297
  }
90
- return createProxyHandler(baseUrl, defaultOptions, [...path, prop], fetchExecutor);
91
- }
298
+ return res;
299
+ });
300
+ }
301
+ return {
302
+ trigger: triggerRef.current,
303
+ ...state
92
304
  };
93
- return new Proxy({}, handler);
94
305
  }
95
306
 
96
- // src/core/index.ts
97
- function createEnlace(baseUrl, defaultOptions = {}) {
98
- return createProxyHandler(baseUrl, defaultOptions);
307
+ // src/react/createEnlaceHook.ts
308
+ function createEnlaceHook(baseUrl, defaultOptions = {}, hookOptions = {}) {
309
+ const api = createEnlace(baseUrl, defaultOptions);
310
+ const {
311
+ autoGenerateTags = true,
312
+ autoRevalidateTags = true,
313
+ staleTime = 0
314
+ } = hookOptions;
315
+ function useEnlaceHook(selectorOrQuery) {
316
+ let trackingResult = {
317
+ trackedCall: null,
318
+ selectorPath: null,
319
+ selectorMethod: null
320
+ };
321
+ const trackingProxy = createTrackingProxy((result2) => {
322
+ trackingResult = result2;
323
+ });
324
+ const result = selectorOrQuery(
325
+ trackingProxy
326
+ );
327
+ if (typeof result === "function") {
328
+ const actualResult = selectorOrQuery(api);
329
+ return useSelectorMode(
330
+ actualResult,
331
+ trackingResult.selectorPath ?? [],
332
+ autoRevalidateTags
333
+ );
334
+ }
335
+ return useQueryMode(
336
+ api,
337
+ trackingResult.trackedCall,
338
+ { autoGenerateTags, staleTime }
339
+ );
340
+ }
341
+ return useEnlaceHook;
99
342
  }
100
343
  export {
101
- createEnlace,
102
- createProxyHandler,
103
- executeFetch
344
+ HTTP_METHODS,
345
+ clearCache,
346
+ createEnlaceHook,
347
+ invalidateTags,
348
+ onRevalidate
104
349
  };
@@ -0,0 +1,124 @@
1
+ import { WildcardClient, EnlaceClient, EnlaceResponse, EnlaceOptions } from 'enlace-core';
2
+
3
+ /** Per-request options for React hooks */
4
+ type ReactRequestOptionsBase = {
5
+ /**
6
+ * Cache tags for caching (GET requests only)
7
+ * This will auto generate tags from the URL path if not provided and autoGenerateTags is enabled.
8
+ * But can be manually specified to override auto-generation.
9
+ * */
10
+ tags?: string[];
11
+ /** Tags to invalidate after mutation (triggers refetch in matching queries) */
12
+ revalidateTags?: string[];
13
+ };
14
+ type ApiClient<TSchema, TOptions = ReactRequestOptionsBase> = unknown extends TSchema ? WildcardClient<TOptions> : EnlaceClient<TSchema, TOptions>;
15
+ type QueryFn<TSchema, TData, TError, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TOptions>) => Promise<EnlaceResponse<TData, TError>>;
16
+ type SelectorFn<TSchema, TMethod, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TOptions>) => TMethod;
17
+ type ExtractData<T> = T extends (...args: any[]) => Promise<EnlaceResponse<infer D, unknown>> ? D : never;
18
+ type ExtractError<T> = T extends (...args: any[]) => Promise<EnlaceResponse<unknown, infer E>> ? E : never;
19
+ /** Discriminated union for hook response state - enables type narrowing on ok check */
20
+ type HookResponseState<TData, TError> = {
21
+ ok: undefined;
22
+ data: undefined;
23
+ error: undefined;
24
+ } | {
25
+ ok: true;
26
+ data: TData;
27
+ error: undefined;
28
+ } | {
29
+ ok: false;
30
+ data: undefined;
31
+ error: TError;
32
+ };
33
+ /** Result when hook is called with query function (auto-fetch mode) */
34
+ type UseEnlaceQueryResult<TData, TError> = {
35
+ loading: boolean;
36
+ fetching: boolean;
37
+ } & HookResponseState<TData, TError>;
38
+ /** Result when hook is called with method selector (trigger mode) */
39
+ type UseEnlaceSelectorResult<TMethod> = {
40
+ trigger: TMethod;
41
+ loading: boolean;
42
+ fetching: boolean;
43
+ } & HookResponseState<ExtractData<TMethod>, ExtractError<TMethod>>;
44
+
45
+ type EnlaceHookOptions = {
46
+ /**
47
+ * Auto-generate cache tags from URL path for GET requests.
48
+ * e.g., `/posts/1` generates tags `['posts', 'posts/1']`
49
+ * @default true
50
+ */
51
+ autoGenerateTags?: boolean;
52
+ /** Auto-revalidate generated tags after successful mutations. @default true */
53
+ autoRevalidateTags?: boolean;
54
+ /** Time in ms before cached data is considered stale. @default 0 (always stale) */
55
+ staleTime?: number;
56
+ };
57
+
58
+ /**
59
+ * Handler function called after successful mutations to trigger server-side revalidation.
60
+ * @param tags - Cache tags to revalidate
61
+ * @param paths - URL paths to revalidate
62
+ */
63
+ type RevalidateHandler = (tags: string[], paths: string[]) => void | Promise<void>;
64
+ /** Next.js-specific options (third argument for createEnlace) */
65
+ type NextOptions = Pick<EnlaceHookOptions, "autoGenerateTags" | "autoRevalidateTags"> & {
66
+ /**
67
+ * Handler called after successful mutations to trigger server-side revalidation.
68
+ * Receives auto-generated or manually specified tags and paths.
69
+ * @example
70
+ * ```ts
71
+ * createEnlace("http://localhost:3000/api/", {}, {
72
+ * revalidator: (tags, paths) => revalidateServerAction(tags, paths)
73
+ * });
74
+ * ```
75
+ */
76
+ revalidator?: RevalidateHandler;
77
+ };
78
+ /** Next.js hook options (third argument for createEnlaceHook) - extends React's EnlaceHookOptions */
79
+ type NextHookOptions = EnlaceHookOptions & Pick<NextOptions, "revalidator">;
80
+ /** Per-request options for Next.js fetch - extends React's base options */
81
+ type NextRequestOptionsBase = ReactRequestOptionsBase & {
82
+ /** Time in seconds to revalidate, or false to disable */
83
+ revalidate?: number | false;
84
+ /**
85
+ * URL paths to revalidate after mutation
86
+ * This doesn't do anything on the client by itself - it's passed to the revalidator handler.
87
+ * You must implement the revalidation logic in the revalidator.
88
+ */
89
+ revalidatePaths?: string[];
90
+ /**
91
+ * Skip server-side revalidation for this request.
92
+ * Useful when autoRevalidateTags is enabled but you want to opt-out for specific mutations.
93
+ * You can still pass empty [] to revalidateTags to skip triggering revalidation.
94
+ * But this flag can be used if you want to revalidate client-side and skip server-side entirely.
95
+ * Eg. you don't fetch any data on server component and you might want to skip the overhead of revalidation.
96
+ */
97
+ skipRevalidator?: boolean;
98
+ };
99
+
100
+ type NextQueryFn<TSchema, TData, TError> = QueryFn<TSchema, TData, TError, NextRequestOptionsBase>;
101
+ type NextSelectorFn<TSchema, TMethod> = SelectorFn<TSchema, TMethod, NextRequestOptionsBase>;
102
+ type NextEnlaceHook<TSchema> = {
103
+ <TMethod extends (...args: any[]) => Promise<EnlaceResponse<unknown, unknown>>>(selector: NextSelectorFn<TSchema, TMethod>): UseEnlaceSelectorResult<TMethod>;
104
+ <TData, TError>(queryFn: NextQueryFn<TSchema, TData, TError>): UseEnlaceQueryResult<TData, TError>;
105
+ };
106
+ /**
107
+ * Creates a React hook for making API calls in Next.js Client Components.
108
+ * Uses Next.js-specific features like revalidator for server-side cache invalidation.
109
+ *
110
+ * @example
111
+ * const useAPI = createEnlaceHook<ApiSchema>('https://api.com', {}, {
112
+ * revalidator: (tags) => revalidateTagsAction(tags),
113
+ * staleTime: 5000,
114
+ * });
115
+ *
116
+ * // Query mode - auto-fetch
117
+ * const { loading, data, error } = useAPI((api) => api.posts.get());
118
+ *
119
+ * // Selector mode - trigger for mutations
120
+ * const { trigger } = useAPI((api) => api.posts.delete);
121
+ */
122
+ declare function createEnlaceHook<TSchema = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions, hookOptions?: NextHookOptions): NextEnlaceHook<TSchema>;
123
+
124
+ export { createEnlaceHook };
@@ -0,0 +1,124 @@
1
+ import { WildcardClient, EnlaceClient, EnlaceResponse, EnlaceOptions } from 'enlace-core';
2
+
3
+ /** Per-request options for React hooks */
4
+ type ReactRequestOptionsBase = {
5
+ /**
6
+ * Cache tags for caching (GET requests only)
7
+ * This will auto generate tags from the URL path if not provided and autoGenerateTags is enabled.
8
+ * But can be manually specified to override auto-generation.
9
+ * */
10
+ tags?: string[];
11
+ /** Tags to invalidate after mutation (triggers refetch in matching queries) */
12
+ revalidateTags?: string[];
13
+ };
14
+ type ApiClient<TSchema, TOptions = ReactRequestOptionsBase> = unknown extends TSchema ? WildcardClient<TOptions> : EnlaceClient<TSchema, TOptions>;
15
+ type QueryFn<TSchema, TData, TError, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TOptions>) => Promise<EnlaceResponse<TData, TError>>;
16
+ type SelectorFn<TSchema, TMethod, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TOptions>) => TMethod;
17
+ type ExtractData<T> = T extends (...args: any[]) => Promise<EnlaceResponse<infer D, unknown>> ? D : never;
18
+ type ExtractError<T> = T extends (...args: any[]) => Promise<EnlaceResponse<unknown, infer E>> ? E : never;
19
+ /** Discriminated union for hook response state - enables type narrowing on ok check */
20
+ type HookResponseState<TData, TError> = {
21
+ ok: undefined;
22
+ data: undefined;
23
+ error: undefined;
24
+ } | {
25
+ ok: true;
26
+ data: TData;
27
+ error: undefined;
28
+ } | {
29
+ ok: false;
30
+ data: undefined;
31
+ error: TError;
32
+ };
33
+ /** Result when hook is called with query function (auto-fetch mode) */
34
+ type UseEnlaceQueryResult<TData, TError> = {
35
+ loading: boolean;
36
+ fetching: boolean;
37
+ } & HookResponseState<TData, TError>;
38
+ /** Result when hook is called with method selector (trigger mode) */
39
+ type UseEnlaceSelectorResult<TMethod> = {
40
+ trigger: TMethod;
41
+ loading: boolean;
42
+ fetching: boolean;
43
+ } & HookResponseState<ExtractData<TMethod>, ExtractError<TMethod>>;
44
+
45
+ type EnlaceHookOptions = {
46
+ /**
47
+ * Auto-generate cache tags from URL path for GET requests.
48
+ * e.g., `/posts/1` generates tags `['posts', 'posts/1']`
49
+ * @default true
50
+ */
51
+ autoGenerateTags?: boolean;
52
+ /** Auto-revalidate generated tags after successful mutations. @default true */
53
+ autoRevalidateTags?: boolean;
54
+ /** Time in ms before cached data is considered stale. @default 0 (always stale) */
55
+ staleTime?: number;
56
+ };
57
+
58
+ /**
59
+ * Handler function called after successful mutations to trigger server-side revalidation.
60
+ * @param tags - Cache tags to revalidate
61
+ * @param paths - URL paths to revalidate
62
+ */
63
+ type RevalidateHandler = (tags: string[], paths: string[]) => void | Promise<void>;
64
+ /** Next.js-specific options (third argument for createEnlace) */
65
+ type NextOptions = Pick<EnlaceHookOptions, "autoGenerateTags" | "autoRevalidateTags"> & {
66
+ /**
67
+ * Handler called after successful mutations to trigger server-side revalidation.
68
+ * Receives auto-generated or manually specified tags and paths.
69
+ * @example
70
+ * ```ts
71
+ * createEnlace("http://localhost:3000/api/", {}, {
72
+ * revalidator: (tags, paths) => revalidateServerAction(tags, paths)
73
+ * });
74
+ * ```
75
+ */
76
+ revalidator?: RevalidateHandler;
77
+ };
78
+ /** Next.js hook options (third argument for createEnlaceHook) - extends React's EnlaceHookOptions */
79
+ type NextHookOptions = EnlaceHookOptions & Pick<NextOptions, "revalidator">;
80
+ /** Per-request options for Next.js fetch - extends React's base options */
81
+ type NextRequestOptionsBase = ReactRequestOptionsBase & {
82
+ /** Time in seconds to revalidate, or false to disable */
83
+ revalidate?: number | false;
84
+ /**
85
+ * URL paths to revalidate after mutation
86
+ * This doesn't do anything on the client by itself - it's passed to the revalidator handler.
87
+ * You must implement the revalidation logic in the revalidator.
88
+ */
89
+ revalidatePaths?: string[];
90
+ /**
91
+ * Skip server-side revalidation for this request.
92
+ * Useful when autoRevalidateTags is enabled but you want to opt-out for specific mutations.
93
+ * You can still pass empty [] to revalidateTags to skip triggering revalidation.
94
+ * But this flag can be used if you want to revalidate client-side and skip server-side entirely.
95
+ * Eg. you don't fetch any data on server component and you might want to skip the overhead of revalidation.
96
+ */
97
+ skipRevalidator?: boolean;
98
+ };
99
+
100
+ type NextQueryFn<TSchema, TData, TError> = QueryFn<TSchema, TData, TError, NextRequestOptionsBase>;
101
+ type NextSelectorFn<TSchema, TMethod> = SelectorFn<TSchema, TMethod, NextRequestOptionsBase>;
102
+ type NextEnlaceHook<TSchema> = {
103
+ <TMethod extends (...args: any[]) => Promise<EnlaceResponse<unknown, unknown>>>(selector: NextSelectorFn<TSchema, TMethod>): UseEnlaceSelectorResult<TMethod>;
104
+ <TData, TError>(queryFn: NextQueryFn<TSchema, TData, TError>): UseEnlaceQueryResult<TData, TError>;
105
+ };
106
+ /**
107
+ * Creates a React hook for making API calls in Next.js Client Components.
108
+ * Uses Next.js-specific features like revalidator for server-side cache invalidation.
109
+ *
110
+ * @example
111
+ * const useAPI = createEnlaceHook<ApiSchema>('https://api.com', {}, {
112
+ * revalidator: (tags) => revalidateTagsAction(tags),
113
+ * staleTime: 5000,
114
+ * });
115
+ *
116
+ * // Query mode - auto-fetch
117
+ * const { loading, data, error } = useAPI((api) => api.posts.get());
118
+ *
119
+ * // Selector mode - trigger for mutations
120
+ * const { trigger } = useAPI((api) => api.posts.delete);
121
+ */
122
+ declare function createEnlaceHook<TSchema = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions, hookOptions?: NextHookOptions): NextEnlaceHook<TSchema>;
123
+
124
+ export { createEnlaceHook };