enlace 0.0.1-beta.5 → 0.0.1-beta.7
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 +26 -21
- package/dist/{next/hook → hook}/index.d.mts +43 -9
- package/dist/{next/hook → hook}/index.d.ts +43 -9
- package/dist/{next/hook → hook}/index.js +141 -103
- package/dist/{next/hook → hook}/index.mjs +142 -121
- package/dist/index.d.mts +41 -78
- package/dist/index.d.ts +41 -78
- package/dist/index.js +48 -391
- package/dist/index.mjs +52 -391
- package/package.json +6 -11
- package/dist/next/index.d.mts +0 -133
- package/dist/next/index.d.ts +0 -133
- package/dist/next/index.js +0 -89
- package/dist/next/index.mjs +0 -71
package/dist/index.mjs
CHANGED
|
@@ -1,412 +1,73 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
2
|
export * from "enlace-core";
|
|
3
3
|
|
|
4
|
-
// src/
|
|
5
|
-
import {
|
|
4
|
+
// src/next/index.ts
|
|
5
|
+
import {
|
|
6
|
+
createProxyHandler
|
|
7
|
+
} from "enlace-core";
|
|
6
8
|
|
|
7
|
-
// src/
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
var initialState = {
|
|
12
|
-
loading: false,
|
|
13
|
-
fetching: false,
|
|
14
|
-
ok: void 0,
|
|
15
|
-
data: void 0,
|
|
16
|
-
error: void 0
|
|
17
|
-
};
|
|
18
|
-
function hookReducer(state, action) {
|
|
19
|
-
switch (action.type) {
|
|
20
|
-
case "RESET":
|
|
21
|
-
return action.state ?? initialState;
|
|
22
|
-
case "FETCH_START":
|
|
23
|
-
return {
|
|
24
|
-
...state,
|
|
25
|
-
loading: state.data === void 0,
|
|
26
|
-
fetching: true
|
|
27
|
-
};
|
|
28
|
-
case "FETCH_SUCCESS":
|
|
29
|
-
return {
|
|
30
|
-
loading: false,
|
|
31
|
-
fetching: false,
|
|
32
|
-
ok: true,
|
|
33
|
-
data: action.data,
|
|
34
|
-
error: void 0
|
|
35
|
-
};
|
|
36
|
-
case "FETCH_ERROR":
|
|
37
|
-
return {
|
|
38
|
-
loading: false,
|
|
39
|
-
fetching: false,
|
|
40
|
-
ok: false,
|
|
41
|
-
data: void 0,
|
|
42
|
-
error: action.error
|
|
43
|
-
};
|
|
44
|
-
case "SYNC_CACHE":
|
|
45
|
-
return action.state;
|
|
46
|
-
default:
|
|
47
|
-
return state;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
9
|
+
// src/next/fetch.ts
|
|
10
|
+
import {
|
|
11
|
+
executeFetch
|
|
12
|
+
} from "enlace-core";
|
|
50
13
|
|
|
51
14
|
// src/utils/generateTags.ts
|
|
52
15
|
function generateTags(path) {
|
|
53
16
|
return path.map((_, i) => path.slice(0, i + 1).join("/"));
|
|
54
17
|
}
|
|
55
18
|
|
|
56
|
-
// src/
|
|
57
|
-
function
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
);
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
sortObjectKeys({
|
|
74
|
-
path: tracked.path,
|
|
75
|
-
method: tracked.method,
|
|
76
|
-
options: tracked.options
|
|
77
|
-
})
|
|
78
|
-
);
|
|
79
|
-
}
|
|
80
|
-
function getCache(key) {
|
|
81
|
-
return cache.get(key);
|
|
82
|
-
}
|
|
83
|
-
function setCache(key, entry) {
|
|
84
|
-
const existing = cache.get(key);
|
|
85
|
-
if (existing) {
|
|
86
|
-
if ("ok" in entry) {
|
|
87
|
-
delete existing.promise;
|
|
88
|
-
}
|
|
89
|
-
Object.assign(existing, entry);
|
|
90
|
-
existing.subscribers.forEach((cb) => cb());
|
|
91
|
-
} else {
|
|
92
|
-
cache.set(key, {
|
|
93
|
-
data: void 0,
|
|
94
|
-
error: void 0,
|
|
95
|
-
ok: void 0,
|
|
96
|
-
timestamp: 0,
|
|
97
|
-
tags: [],
|
|
98
|
-
subscribers: /* @__PURE__ */ new Set(),
|
|
99
|
-
...entry
|
|
100
|
-
});
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
function subscribeCache(key, callback) {
|
|
104
|
-
let entry = cache.get(key);
|
|
105
|
-
if (!entry) {
|
|
106
|
-
cache.set(key, {
|
|
107
|
-
data: void 0,
|
|
108
|
-
error: void 0,
|
|
109
|
-
ok: void 0,
|
|
110
|
-
timestamp: 0,
|
|
111
|
-
tags: [],
|
|
112
|
-
subscribers: /* @__PURE__ */ new Set()
|
|
113
|
-
});
|
|
114
|
-
entry = cache.get(key);
|
|
115
|
-
}
|
|
116
|
-
entry.subscribers.add(callback);
|
|
117
|
-
return () => {
|
|
118
|
-
entry.subscribers.delete(callback);
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
function isStale(key, staleTime) {
|
|
122
|
-
const entry = cache.get(key);
|
|
123
|
-
if (!entry) return true;
|
|
124
|
-
return Date.now() - entry.timestamp > staleTime;
|
|
125
|
-
}
|
|
126
|
-
function clearCache(key) {
|
|
127
|
-
if (key) {
|
|
128
|
-
cache.delete(key);
|
|
129
|
-
} else {
|
|
130
|
-
cache.clear();
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
function clearCacheByTags(tags) {
|
|
134
|
-
cache.forEach((entry) => {
|
|
135
|
-
const hasMatch = entry.tags.some((tag) => tags.includes(tag));
|
|
136
|
-
if (hasMatch) {
|
|
137
|
-
entry.data = void 0;
|
|
138
|
-
entry.error = void 0;
|
|
139
|
-
entry.ok = void 0;
|
|
140
|
-
entry.timestamp = 0;
|
|
141
|
-
delete entry.promise;
|
|
142
|
-
}
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
// src/react/revalidator.ts
|
|
147
|
-
var listeners = /* @__PURE__ */ new Set();
|
|
148
|
-
function invalidateTags(tags) {
|
|
149
|
-
clearCacheByTags(tags);
|
|
150
|
-
listeners.forEach((listener) => listener(tags));
|
|
151
|
-
}
|
|
152
|
-
function onRevalidate(callback) {
|
|
153
|
-
listeners.add(callback);
|
|
154
|
-
return () => listeners.delete(callback);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// src/react/useQueryMode.ts
|
|
158
|
-
function resolvePath(path, pathParams) {
|
|
159
|
-
if (!pathParams) return path;
|
|
160
|
-
return path.map((segment) => {
|
|
161
|
-
if (segment.startsWith(":")) {
|
|
162
|
-
const paramName = segment.slice(1);
|
|
163
|
-
const value = pathParams[paramName];
|
|
164
|
-
if (value === void 0) {
|
|
165
|
-
throw new Error(`Missing path parameter: ${paramName}`);
|
|
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);
|
|
166
36
|
}
|
|
167
|
-
return String(value);
|
|
168
37
|
}
|
|
169
|
-
|
|
170
|
-
});
|
|
171
|
-
}
|
|
172
|
-
function useQueryMode(api, trackedCall, options) {
|
|
173
|
-
const { autoGenerateTags, staleTime, enabled } = options;
|
|
174
|
-
const queryKey = createQueryKey(trackedCall);
|
|
175
|
-
const requestOptions = trackedCall.options;
|
|
176
|
-
const resolvedPath = resolvePath(
|
|
177
|
-
trackedCall.path,
|
|
178
|
-
requestOptions?.pathParams
|
|
179
|
-
);
|
|
180
|
-
const queryTags = requestOptions?.tags ?? (autoGenerateTags ? generateTags(resolvedPath) : []);
|
|
181
|
-
const getCacheState = (includeNeedsFetch = false) => {
|
|
182
|
-
const cached = getCache(queryKey);
|
|
183
|
-
const hasCachedData = cached?.data !== void 0;
|
|
184
|
-
const isFetching = !!cached?.promise;
|
|
185
|
-
const needsFetch = includeNeedsFetch && (!hasCachedData || isStale(queryKey, staleTime));
|
|
186
|
-
return {
|
|
187
|
-
loading: !hasCachedData && (isFetching || needsFetch),
|
|
188
|
-
fetching: isFetching || needsFetch,
|
|
189
|
-
ok: cached?.ok,
|
|
190
|
-
data: cached?.data,
|
|
191
|
-
error: cached?.error
|
|
192
|
-
};
|
|
38
|
+
onSuccess?.(payload);
|
|
193
39
|
};
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
const fetchRef = useRef(null);
|
|
201
|
-
useEffect(() => {
|
|
202
|
-
mountedRef.current = true;
|
|
203
|
-
if (!enabled) {
|
|
204
|
-
dispatch({ type: "RESET" });
|
|
205
|
-
return () => {
|
|
206
|
-
mountedRef.current = false;
|
|
207
|
-
};
|
|
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;
|
|
208
46
|
}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
const cached2 = getCache(queryKey);
|
|
212
|
-
if (cached2?.promise) {
|
|
213
|
-
return;
|
|
214
|
-
}
|
|
215
|
-
dispatch({ type: "FETCH_START" });
|
|
216
|
-
let current = api;
|
|
217
|
-
for (const segment of resolvedPath) {
|
|
218
|
-
current = current[segment];
|
|
219
|
-
}
|
|
220
|
-
const method = current[trackedCall.method];
|
|
221
|
-
const fetchPromise = method(trackedCall.options).then((res) => {
|
|
222
|
-
if (mountedRef.current) {
|
|
223
|
-
setCache(queryKey, {
|
|
224
|
-
data: res.ok ? res.data : void 0,
|
|
225
|
-
error: res.ok || res.status === 0 ? void 0 : res.error,
|
|
226
|
-
ok: res.ok,
|
|
227
|
-
timestamp: Date.now(),
|
|
228
|
-
tags: queryTags
|
|
229
|
-
});
|
|
230
|
-
}
|
|
231
|
-
});
|
|
232
|
-
setCache(queryKey, {
|
|
233
|
-
promise: fetchPromise,
|
|
234
|
-
tags: queryTags
|
|
235
|
-
});
|
|
236
|
-
};
|
|
237
|
-
fetchRef.current = doFetch;
|
|
238
|
-
const cached = getCache(queryKey);
|
|
239
|
-
if (cached?.data !== void 0 && !isStale(queryKey, staleTime)) {
|
|
240
|
-
dispatch({ type: "SYNC_CACHE", state: getCacheState() });
|
|
241
|
-
} else {
|
|
242
|
-
doFetch();
|
|
47
|
+
if (requestOptions?.revalidate !== void 0) {
|
|
48
|
+
nextFetchOptions.revalidate = requestOptions.revalidate;
|
|
243
49
|
}
|
|
244
|
-
|
|
245
|
-
if (mountedRef.current) {
|
|
246
|
-
dispatch({ type: "SYNC_CACHE", state: getCacheState() });
|
|
247
|
-
}
|
|
248
|
-
});
|
|
249
|
-
return () => {
|
|
250
|
-
mountedRef.current = false;
|
|
251
|
-
fetchRef.current = null;
|
|
252
|
-
unsubscribe();
|
|
253
|
-
};
|
|
254
|
-
}, [queryKey, enabled]);
|
|
255
|
-
useEffect(() => {
|
|
256
|
-
if (queryTags.length === 0) return;
|
|
257
|
-
return onRevalidate((invalidatedTags) => {
|
|
258
|
-
const hasMatch = invalidatedTags.some((tag) => queryTags.includes(tag));
|
|
259
|
-
if (hasMatch && mountedRef.current && fetchRef.current) {
|
|
260
|
-
fetchRef.current();
|
|
261
|
-
}
|
|
262
|
-
});
|
|
263
|
-
}, [JSON.stringify(queryTags)]);
|
|
264
|
-
return state;
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
// src/react/types.ts
|
|
268
|
-
var HTTP_METHODS = ["get", "post", "put", "patch", "delete"];
|
|
269
|
-
|
|
270
|
-
// src/react/trackingProxy.ts
|
|
271
|
-
function createTrackingProxy(onTrack) {
|
|
272
|
-
const createProxy = (path = []) => {
|
|
273
|
-
return new Proxy(() => {
|
|
274
|
-
}, {
|
|
275
|
-
get(_, prop) {
|
|
276
|
-
if (HTTP_METHODS.includes(prop)) {
|
|
277
|
-
const methodFn = (options) => {
|
|
278
|
-
onTrack({
|
|
279
|
-
trackedCall: { path, method: prop, options },
|
|
280
|
-
selectorPath: null,
|
|
281
|
-
selectorMethod: null
|
|
282
|
-
});
|
|
283
|
-
return Promise.resolve({ ok: true, data: void 0 });
|
|
284
|
-
};
|
|
285
|
-
onTrack({
|
|
286
|
-
trackedCall: null,
|
|
287
|
-
selectorPath: path,
|
|
288
|
-
selectorMethod: prop
|
|
289
|
-
});
|
|
290
|
-
return methodFn;
|
|
291
|
-
}
|
|
292
|
-
return createProxy([...path, prop]);
|
|
293
|
-
}
|
|
294
|
-
});
|
|
295
|
-
};
|
|
296
|
-
return createProxy();
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// src/react/useSelectorMode.ts
|
|
300
|
-
import { useRef as useRef2, useReducer as useReducer2 } from "react";
|
|
301
|
-
function resolvePath2(path, pathParams) {
|
|
302
|
-
if (!pathParams) return path;
|
|
303
|
-
return path.map((segment) => {
|
|
304
|
-
if (segment.startsWith(":")) {
|
|
305
|
-
const paramName = segment.slice(1);
|
|
306
|
-
const value = pathParams[paramName];
|
|
307
|
-
if (value === void 0) {
|
|
308
|
-
throw new Error(`Missing path parameter: ${paramName}`);
|
|
309
|
-
}
|
|
310
|
-
return String(value);
|
|
311
|
-
}
|
|
312
|
-
return segment;
|
|
313
|
-
});
|
|
314
|
-
}
|
|
315
|
-
function hasPathParams(path) {
|
|
316
|
-
return path.some((segment) => segment.startsWith(":"));
|
|
317
|
-
}
|
|
318
|
-
function useSelectorMode(config) {
|
|
319
|
-
const { method, api, path, methodName, autoRevalidateTags } = config;
|
|
320
|
-
const [state, dispatch] = useReducer2(hookReducer, initialState);
|
|
321
|
-
const methodRef = useRef2(method);
|
|
322
|
-
const apiRef = useRef2(api);
|
|
323
|
-
const triggerRef = useRef2(null);
|
|
324
|
-
const pathRef = useRef2(path);
|
|
325
|
-
const methodNameRef = useRef2(methodName);
|
|
326
|
-
const autoRevalidateRef = useRef2(autoRevalidateTags);
|
|
327
|
-
methodRef.current = method;
|
|
328
|
-
apiRef.current = api;
|
|
329
|
-
pathRef.current = path;
|
|
330
|
-
methodNameRef.current = methodName;
|
|
331
|
-
autoRevalidateRef.current = autoRevalidateTags;
|
|
332
|
-
if (!triggerRef.current) {
|
|
333
|
-
triggerRef.current = (async (...args) => {
|
|
334
|
-
dispatch({ type: "FETCH_START" });
|
|
335
|
-
const options = args[0];
|
|
336
|
-
const resolvedPath = resolvePath2(pathRef.current, options?.pathParams);
|
|
337
|
-
let res;
|
|
338
|
-
if (hasPathParams(pathRef.current)) {
|
|
339
|
-
let current = apiRef.current;
|
|
340
|
-
for (const segment of resolvedPath) {
|
|
341
|
-
current = current[segment];
|
|
342
|
-
}
|
|
343
|
-
const resolvedMethod = current[methodNameRef.current];
|
|
344
|
-
res = await resolvedMethod(...args);
|
|
345
|
-
} else {
|
|
346
|
-
res = await methodRef.current(...args);
|
|
347
|
-
}
|
|
348
|
-
if (res.ok) {
|
|
349
|
-
dispatch({ type: "FETCH_SUCCESS", data: res.data });
|
|
350
|
-
const tagsToInvalidate = options?.revalidateTags ?? (autoRevalidateRef.current ? generateTags(resolvedPath) : []);
|
|
351
|
-
if (tagsToInvalidate.length > 0) {
|
|
352
|
-
invalidateTags(tagsToInvalidate);
|
|
353
|
-
}
|
|
354
|
-
} else {
|
|
355
|
-
dispatch({ type: "FETCH_ERROR", error: res.error });
|
|
356
|
-
}
|
|
357
|
-
return res;
|
|
358
|
-
});
|
|
50
|
+
nextRequestOptions.next = nextFetchOptions;
|
|
359
51
|
}
|
|
360
|
-
return
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
52
|
+
return executeFetch(
|
|
53
|
+
baseUrl,
|
|
54
|
+
path,
|
|
55
|
+
method,
|
|
56
|
+
{ ...coreOptions, onSuccess: nextOnSuccess },
|
|
57
|
+
nextRequestOptions
|
|
58
|
+
);
|
|
364
59
|
}
|
|
365
60
|
|
|
366
|
-
// src/
|
|
367
|
-
function
|
|
368
|
-
const {
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
const api = createEnlace(baseUrl, defaultOptions, { onSuccess, onError });
|
|
376
|
-
function useEnlaceHook(selectorOrQuery, queryOptions) {
|
|
377
|
-
let trackingResult = {
|
|
378
|
-
trackedCall: null,
|
|
379
|
-
selectorPath: null,
|
|
380
|
-
selectorMethod: null
|
|
381
|
-
};
|
|
382
|
-
const trackingProxy = createTrackingProxy((result2) => {
|
|
383
|
-
trackingResult = result2;
|
|
384
|
-
});
|
|
385
|
-
const result = selectorOrQuery(
|
|
386
|
-
trackingProxy
|
|
387
|
-
);
|
|
388
|
-
if (typeof result === "function") {
|
|
389
|
-
const actualResult = selectorOrQuery(api);
|
|
390
|
-
return useSelectorMode({
|
|
391
|
-
method: actualResult,
|
|
392
|
-
api,
|
|
393
|
-
path: trackingResult.selectorPath ?? [],
|
|
394
|
-
methodName: trackingResult.selectorMethod ?? "",
|
|
395
|
-
autoRevalidateTags
|
|
396
|
-
});
|
|
397
|
-
}
|
|
398
|
-
return useQueryMode(
|
|
399
|
-
api,
|
|
400
|
-
trackingResult.trackedCall,
|
|
401
|
-
{ autoGenerateTags, staleTime, enabled: queryOptions?.enabled ?? true }
|
|
402
|
-
);
|
|
403
|
-
}
|
|
404
|
-
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
|
+
);
|
|
405
70
|
}
|
|
406
71
|
export {
|
|
407
|
-
|
|
408
|
-
clearCache,
|
|
409
|
-
createEnlaceHook,
|
|
410
|
-
invalidateTags,
|
|
411
|
-
onRevalidate
|
|
72
|
+
createEnlaceNext
|
|
412
73
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "enlace",
|
|
3
|
-
"version": "0.0.1-beta.
|
|
3
|
+
"version": "0.0.1-beta.7",
|
|
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
|
-
"./
|
|
15
|
-
"types": "./dist/
|
|
16
|
-
"import": "./dist/
|
|
17
|
-
"require": "./dist/
|
|
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.
|
|
21
|
+
"enlace-core": "0.0.1-beta.5"
|
|
27
22
|
},
|
|
28
23
|
"peerDependencies": {
|
|
29
24
|
"react": "^19"
|
package/dist/next/index.d.mts
DELETED
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
import { EnlaceCallbackPayload, EnlaceErrorCallbackPayload, WildcardClient, EnlaceClient, EnlaceResponse, EnlaceCallbacks, EnlaceOptions } from 'enlace-core';
|
|
2
|
-
export * from 'enlace-core';
|
|
3
|
-
export { EnlaceCallbacks, EnlaceOptions } from 'enlace-core';
|
|
4
|
-
|
|
5
|
-
/** Per-request options for React hooks */
|
|
6
|
-
type ReactRequestOptionsBase = {
|
|
7
|
-
/**
|
|
8
|
-
* Cache tags for caching (GET requests only)
|
|
9
|
-
* This will auto generate tags from the URL path if not provided and autoGenerateTags is enabled.
|
|
10
|
-
* But can be manually specified to override auto-generation.
|
|
11
|
-
* */
|
|
12
|
-
tags?: string[];
|
|
13
|
-
/** Tags to invalidate after mutation (triggers refetch in matching queries) */
|
|
14
|
-
revalidateTags?: string[];
|
|
15
|
-
/**
|
|
16
|
-
* Path parameters for dynamic URL segments.
|
|
17
|
-
* Used to replace :paramName placeholders in the URL path.
|
|
18
|
-
* @example
|
|
19
|
-
* // With path api.products[':id'].delete
|
|
20
|
-
* trigger({ pathParams: { id: '123' } }) // → DELETE /products/123
|
|
21
|
-
*/
|
|
22
|
-
pathParams?: Record<string, string | number>;
|
|
23
|
-
};
|
|
24
|
-
/** Options for query mode hooks */
|
|
25
|
-
type UseEnlaceQueryOptions = {
|
|
26
|
-
/**
|
|
27
|
-
* Whether the query should execute.
|
|
28
|
-
* Set to false to skip fetching (useful when ID is "new" or undefined).
|
|
29
|
-
* @default true
|
|
30
|
-
*/
|
|
31
|
-
enabled?: boolean;
|
|
32
|
-
};
|
|
33
|
-
type ApiClient<TSchema, TOptions = ReactRequestOptionsBase> = unknown extends TSchema ? WildcardClient<TOptions> : EnlaceClient<TSchema, TOptions>;
|
|
34
|
-
type QueryFn<TSchema, TData, TError, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TOptions>) => Promise<EnlaceResponse<TData, TError>>;
|
|
35
|
-
type SelectorFn<TSchema, TMethod, TOptions = ReactRequestOptionsBase> = (api: ApiClient<TSchema, TOptions>) => TMethod;
|
|
36
|
-
type ExtractData<T> = T extends (...args: any[]) => Promise<EnlaceResponse<infer D, unknown>> ? D : never;
|
|
37
|
-
type ExtractError<T> = T extends (...args: any[]) => Promise<EnlaceResponse<unknown, infer E>> ? E : never;
|
|
38
|
-
/** Discriminated union for hook response state - enables type narrowing on ok check */
|
|
39
|
-
type HookResponseState<TData, TError> = {
|
|
40
|
-
ok: undefined;
|
|
41
|
-
data: undefined;
|
|
42
|
-
error: undefined;
|
|
43
|
-
} | {
|
|
44
|
-
ok: true;
|
|
45
|
-
data: TData;
|
|
46
|
-
error: undefined;
|
|
47
|
-
} | {
|
|
48
|
-
ok: false;
|
|
49
|
-
data: undefined;
|
|
50
|
-
error: TError;
|
|
51
|
-
};
|
|
52
|
-
/** Result when hook is called with query function (auto-fetch mode) */
|
|
53
|
-
type UseEnlaceQueryResult<TData, TError> = {
|
|
54
|
-
loading: boolean;
|
|
55
|
-
fetching: boolean;
|
|
56
|
-
} & HookResponseState<TData, TError>;
|
|
57
|
-
/** Result when hook is called with method selector (trigger mode) */
|
|
58
|
-
type UseEnlaceSelectorResult<TMethod> = {
|
|
59
|
-
trigger: TMethod;
|
|
60
|
-
loading: boolean;
|
|
61
|
-
fetching: boolean;
|
|
62
|
-
} & HookResponseState<ExtractData<TMethod>, ExtractError<TMethod>>;
|
|
63
|
-
/** Options for createEnlaceHook factory */
|
|
64
|
-
type EnlaceHookOptions = {
|
|
65
|
-
/**
|
|
66
|
-
* Auto-generate cache tags from URL path for GET requests.
|
|
67
|
-
* e.g., `/posts/1` generates tags `['posts', 'posts/1']`
|
|
68
|
-
* @default true
|
|
69
|
-
*/
|
|
70
|
-
autoGenerateTags?: boolean;
|
|
71
|
-
/** Auto-revalidate generated tags after successful mutations. @default true */
|
|
72
|
-
autoRevalidateTags?: boolean;
|
|
73
|
-
/** Time in ms before cached data is considered stale. @default 0 (always stale) */
|
|
74
|
-
staleTime?: number;
|
|
75
|
-
/** Callback called on successful API responses */
|
|
76
|
-
onSuccess?: (payload: EnlaceCallbackPayload<unknown>) => void;
|
|
77
|
-
/** Callback called on error responses (HTTP errors or network failures) */
|
|
78
|
-
onError?: (payload: EnlaceErrorCallbackPayload<unknown>) => void;
|
|
79
|
-
};
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* Handler function called after successful mutations to trigger server-side revalidation.
|
|
83
|
-
* @param tags - Cache tags to revalidate
|
|
84
|
-
* @param paths - URL paths to revalidate
|
|
85
|
-
*/
|
|
86
|
-
type RevalidateHandler = (tags: string[], paths: string[]) => void | Promise<void>;
|
|
87
|
-
/** Next.js-specific options (third argument for createEnlace) */
|
|
88
|
-
type NextOptions = Pick<EnlaceHookOptions, "autoGenerateTags" | "autoRevalidateTags"> & EnlaceCallbacks & {
|
|
89
|
-
/**
|
|
90
|
-
* Handler called after successful mutations to trigger server-side revalidation.
|
|
91
|
-
* Receives auto-generated or manually specified tags and paths.
|
|
92
|
-
* @example
|
|
93
|
-
* ```ts
|
|
94
|
-
* createEnlace("http://localhost:3000/api/", {}, {
|
|
95
|
-
* revalidator: (tags, paths) => revalidateServerAction(tags, paths)
|
|
96
|
-
* });
|
|
97
|
-
* ```
|
|
98
|
-
*/
|
|
99
|
-
revalidator?: RevalidateHandler;
|
|
100
|
-
};
|
|
101
|
-
/** Next.js hook options (third argument for createEnlaceHook) - extends React's EnlaceHookOptions */
|
|
102
|
-
type NextHookOptions = EnlaceHookOptions & Pick<NextOptions, "revalidator">;
|
|
103
|
-
/** Per-request options for Next.js fetch - extends React's base options */
|
|
104
|
-
type NextRequestOptionsBase = ReactRequestOptionsBase & {
|
|
105
|
-
/** Time in seconds to revalidate, or false to disable */
|
|
106
|
-
revalidate?: number | false;
|
|
107
|
-
/**
|
|
108
|
-
* URL paths to revalidate after mutation
|
|
109
|
-
* This doesn't do anything on the client by itself - it's passed to the revalidator handler.
|
|
110
|
-
* You must implement the revalidation logic in the revalidator.
|
|
111
|
-
*/
|
|
112
|
-
revalidatePaths?: string[];
|
|
113
|
-
/**
|
|
114
|
-
* Skip server-side revalidation for this request.
|
|
115
|
-
* Useful when autoRevalidateTags is enabled but you want to opt-out for specific mutations.
|
|
116
|
-
* You can still pass empty [] to revalidateTags to skip triggering revalidation.
|
|
117
|
-
* But this flag can be used if you want to revalidate client-side and skip server-side entirely.
|
|
118
|
-
* Eg. you don't fetch any data on server component and you might want to skip the overhead of revalidation.
|
|
119
|
-
*/
|
|
120
|
-
skipRevalidator?: boolean;
|
|
121
|
-
};
|
|
122
|
-
type NextApiClient<TSchema> = ApiClient<TSchema, NextRequestOptionsBase>;
|
|
123
|
-
type NextQueryFn<TSchema, TData, TError> = QueryFn<TSchema, TData, TError, NextRequestOptionsBase>;
|
|
124
|
-
type NextSelectorFn<TSchema, TMethod> = SelectorFn<TSchema, TMethod, NextRequestOptionsBase>;
|
|
125
|
-
/** Hook type returned by Next.js createEnlaceHook */
|
|
126
|
-
type NextEnlaceHook<TSchema> = {
|
|
127
|
-
<TMethod extends (...args: any[]) => Promise<EnlaceResponse<unknown, unknown>>>(selector: NextSelectorFn<TSchema, TMethod>): UseEnlaceSelectorResult<TMethod>;
|
|
128
|
-
<TData, TError>(queryFn: NextQueryFn<TSchema, TData, TError>, options?: UseEnlaceQueryOptions): UseEnlaceQueryResult<TData, TError>;
|
|
129
|
-
};
|
|
130
|
-
|
|
131
|
-
declare function createEnlace<TSchema = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions | null, nextOptions?: NextOptions): unknown extends TSchema ? WildcardClient<NextRequestOptionsBase> : EnlaceClient<TSchema, NextRequestOptionsBase>;
|
|
132
|
-
|
|
133
|
-
export { type NextApiClient, type NextEnlaceHook, type NextHookOptions, type NextOptions, type NextQueryFn, type NextRequestOptionsBase, type NextSelectorFn, type RevalidateHandler, createEnlace };
|