enlace 0.0.1-beta.1 → 0.0.1-beta.10

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,349 +1,73 @@
1
1
  // src/index.ts
2
2
  export * from "enlace-core";
3
3
 
4
- // src/react/createEnlaceHook.ts
4
+ // src/next/index.ts
5
5
  import {
6
- createEnlace
6
+ createProxyHandler
7
7
  } from "enlace-core";
8
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;
50
- }
51
- }
9
+ // src/next/fetch.ts
10
+ import {
11
+ executeFetch
12
+ } from "enlace-core";
52
13
 
53
14
  // src/utils/generateTags.ts
54
15
  function generateTags(path) {
55
16
  return path.map((_, i) => path.slice(0, i + 1).join("/"));
56
17
  }
57
18
 
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
- );
69
- }
70
-
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;
19
+ // src/next/fetch.ts
20
+ async function executeNextFetch(baseUrl, path, method, combinedOptions, requestOptions) {
21
+ const {
22
+ autoGenerateTags = true,
23
+ autoRevalidateTags = true,
24
+ revalidator,
25
+ onSuccess,
26
+ ...coreOptions
27
+ } = combinedOptions;
28
+ const isGet = method === "GET";
29
+ const autoTags = generateTags(path);
30
+ const nextOnSuccess = (payload) => {
31
+ if (!isGet && !requestOptions?.skipRevalidator) {
32
+ const revalidateTags = requestOptions?.revalidateTags ?? (autoRevalidateTags ? autoTags : []);
33
+ const revalidatePaths = requestOptions?.revalidatePaths ?? [];
34
+ if (revalidateTags.length || revalidatePaths.length) {
35
+ revalidator?.(revalidateTags, revalidatePaths);
36
+ }
90
37
  }
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);
38
+ onSuccess?.(payload);
121
39
  };
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();
133
- }
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;
40
+ const nextRequestOptions = { ...requestOptions };
41
+ if (isGet) {
42
+ const tags = requestOptions?.tags ?? (autoGenerateTags ? autoTags : void 0);
43
+ const nextFetchOptions = {};
44
+ if (tags) {
45
+ nextFetchOptions.tags = tags;
144
46
  }
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;
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() });
220
- } else {
221
- doFetch();
47
+ if (requestOptions?.revalidate !== void 0) {
48
+ nextFetchOptions.revalidate = requestOptions.revalidate;
222
49
  }
223
- return () => {
224
- mountedRef.current = false;
225
- fetchRef.current = null;
226
- unsubscribe();
227
- };
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
- });
269
- };
270
- return createProxy();
271
- }
272
-
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 });
297
- }
298
- return res;
299
- });
50
+ nextRequestOptions.next = nextFetchOptions;
300
51
  }
301
- return {
302
- trigger: triggerRef.current,
303
- ...state
304
- };
52
+ return executeFetch(
53
+ baseUrl,
54
+ path,
55
+ method,
56
+ { ...coreOptions, onSuccess: nextOnSuccess },
57
+ nextRequestOptions
58
+ );
305
59
  }
306
60
 
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;
61
+ // src/next/index.ts
62
+ function createEnlaceNext(baseUrl, defaultOptions = {}, nextOptions = {}) {
63
+ const combinedOptions = { ...defaultOptions, ...nextOptions };
64
+ return createProxyHandler(
65
+ baseUrl,
66
+ combinedOptions,
67
+ [],
68
+ executeNextFetch
69
+ );
342
70
  }
343
71
  export {
344
- HTTP_METHODS,
345
- clearCache,
346
- createEnlaceHook,
347
- invalidateTags,
348
- onRevalidate
72
+ createEnlaceNext
349
73
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "enlace",
3
- "version": "0.0.1-beta.1",
3
+ "version": "0.0.1-beta.10",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist"
@@ -11,19 +11,14 @@
11
11
  "import": "./dist/index.mjs",
12
12
  "require": "./dist/index.js"
13
13
  },
14
- "./next": {
15
- "types": "./dist/next/index.d.ts",
16
- "import": "./dist/next/index.mjs",
17
- "require": "./dist/next/index.js"
18
- },
19
- "./next/hook": {
20
- "types": "./dist/next/hook/index.d.ts",
21
- "import": "./dist/next/hook/index.mjs",
22
- "require": "./dist/next/hook/index.js"
14
+ "./hook": {
15
+ "types": "./dist/hook/index.d.ts",
16
+ "import": "./dist/hook/index.mjs",
17
+ "require": "./dist/hook/index.js"
23
18
  }
24
19
  },
25
20
  "dependencies": {
26
- "enlace-core": "0.0.1-beta.1"
21
+ "enlace-core": "0.0.1-beta.8"
27
22
  },
28
23
  "peerDependencies": {
29
24
  "react": "^19"
@@ -1,124 +0,0 @@
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 };
@@ -1,124 +0,0 @@
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 };