enlace 0.0.0-alpha.4 → 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/LICENSE +21 -0
- package/README.md +728 -0
- package/dist/hook/index.d.mts +173 -0
- package/dist/hook/index.d.ts +173 -0
- package/dist/hook/index.js +516 -0
- package/dist/hook/index.mjs +498 -0
- package/dist/index.d.mts +75 -113
- package/dist/index.d.ts +75 -113
- package/dist/index.js +55 -101
- package/dist/index.mjs +60 -91
- package/package.json +14 -28
- package/dist/next/index.d.mts +0 -121
- package/dist/next/index.d.ts +0 -121
- package/dist/next/index.js +0 -191
- package/dist/next/index.mjs +0 -158
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
"use client";
|
|
3
|
+
|
|
4
|
+
// src/react/createEnlaceHookReact.ts
|
|
5
|
+
import { createEnlace } from "enlace-core";
|
|
6
|
+
|
|
7
|
+
// src/react/useQueryMode.ts
|
|
8
|
+
import { useRef, useReducer, useEffect } from "react";
|
|
9
|
+
|
|
10
|
+
// src/react/reducer.ts
|
|
11
|
+
var initialState = {
|
|
12
|
+
loading: false,
|
|
13
|
+
fetching: false,
|
|
14
|
+
data: void 0,
|
|
15
|
+
error: void 0
|
|
16
|
+
};
|
|
17
|
+
function hookReducer(state, action) {
|
|
18
|
+
switch (action.type) {
|
|
19
|
+
case "RESET":
|
|
20
|
+
return action.state ?? initialState;
|
|
21
|
+
case "FETCH_START":
|
|
22
|
+
return {
|
|
23
|
+
...state,
|
|
24
|
+
loading: state.data === void 0,
|
|
25
|
+
fetching: true
|
|
26
|
+
};
|
|
27
|
+
case "FETCH_SUCCESS":
|
|
28
|
+
return {
|
|
29
|
+
loading: false,
|
|
30
|
+
fetching: false,
|
|
31
|
+
data: action.data,
|
|
32
|
+
error: void 0
|
|
33
|
+
};
|
|
34
|
+
case "FETCH_ERROR":
|
|
35
|
+
return {
|
|
36
|
+
loading: false,
|
|
37
|
+
fetching: false,
|
|
38
|
+
data: void 0,
|
|
39
|
+
error: action.error
|
|
40
|
+
};
|
|
41
|
+
case "SYNC_CACHE":
|
|
42
|
+
return action.state;
|
|
43
|
+
default:
|
|
44
|
+
return state;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// src/utils/generateTags.ts
|
|
49
|
+
function generateTags(path) {
|
|
50
|
+
return path.map((_, i) => path.slice(0, i + 1).join("/"));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/utils/sortObjectKeys.ts
|
|
54
|
+
function sortObjectKeys(obj) {
|
|
55
|
+
if (obj === null || typeof obj !== "object") return obj;
|
|
56
|
+
if (Array.isArray(obj)) return obj.map(sortObjectKeys);
|
|
57
|
+
return Object.keys(obj).sort().reduce(
|
|
58
|
+
(sorted, key) => {
|
|
59
|
+
sorted[key] = sortObjectKeys(obj[key]);
|
|
60
|
+
return sorted;
|
|
61
|
+
},
|
|
62
|
+
{}
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// src/react/cache.ts
|
|
67
|
+
var cache = /* @__PURE__ */ new Map();
|
|
68
|
+
function createQueryKey(tracked) {
|
|
69
|
+
return JSON.stringify(
|
|
70
|
+
sortObjectKeys({
|
|
71
|
+
path: tracked.path,
|
|
72
|
+
method: tracked.method,
|
|
73
|
+
options: tracked.options
|
|
74
|
+
})
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
function getCache(key) {
|
|
78
|
+
return cache.get(key);
|
|
79
|
+
}
|
|
80
|
+
function setCache(key, entry) {
|
|
81
|
+
const existing = cache.get(key);
|
|
82
|
+
if (existing) {
|
|
83
|
+
if ("data" in entry || "error" in entry) {
|
|
84
|
+
delete existing.promise;
|
|
85
|
+
}
|
|
86
|
+
Object.assign(existing, entry);
|
|
87
|
+
existing.subscribers.forEach((cb) => cb());
|
|
88
|
+
} else {
|
|
89
|
+
cache.set(key, {
|
|
90
|
+
data: void 0,
|
|
91
|
+
error: void 0,
|
|
92
|
+
timestamp: 0,
|
|
93
|
+
tags: [],
|
|
94
|
+
subscribers: /* @__PURE__ */ new Set(),
|
|
95
|
+
...entry
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function subscribeCache(key, callback) {
|
|
100
|
+
let entry = cache.get(key);
|
|
101
|
+
if (!entry) {
|
|
102
|
+
cache.set(key, {
|
|
103
|
+
data: void 0,
|
|
104
|
+
error: void 0,
|
|
105
|
+
timestamp: 0,
|
|
106
|
+
tags: [],
|
|
107
|
+
subscribers: /* @__PURE__ */ new Set()
|
|
108
|
+
});
|
|
109
|
+
entry = cache.get(key);
|
|
110
|
+
}
|
|
111
|
+
entry.subscribers.add(callback);
|
|
112
|
+
return () => {
|
|
113
|
+
entry.subscribers.delete(callback);
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function isStale(key, staleTime) {
|
|
117
|
+
const entry = cache.get(key);
|
|
118
|
+
if (!entry) return true;
|
|
119
|
+
return Date.now() - entry.timestamp > staleTime;
|
|
120
|
+
}
|
|
121
|
+
function clearCacheByTags(tags) {
|
|
122
|
+
cache.forEach((entry) => {
|
|
123
|
+
const hasMatch = entry.tags.some((tag) => tags.includes(tag));
|
|
124
|
+
if (hasMatch) {
|
|
125
|
+
entry.data = void 0;
|
|
126
|
+
entry.error = void 0;
|
|
127
|
+
entry.timestamp = 0;
|
|
128
|
+
delete entry.promise;
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// src/react/revalidator.ts
|
|
134
|
+
var listeners = /* @__PURE__ */ new Set();
|
|
135
|
+
function invalidateTags(tags) {
|
|
136
|
+
clearCacheByTags(tags);
|
|
137
|
+
listeners.forEach((listener) => listener(tags));
|
|
138
|
+
}
|
|
139
|
+
function onRevalidate(callback) {
|
|
140
|
+
listeners.add(callback);
|
|
141
|
+
return () => listeners.delete(callback);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// src/react/useQueryMode.ts
|
|
145
|
+
function resolvePath(path, pathParams) {
|
|
146
|
+
if (!pathParams) return path;
|
|
147
|
+
return path.map((segment) => {
|
|
148
|
+
if (segment.startsWith(":")) {
|
|
149
|
+
const paramName = segment.slice(1);
|
|
150
|
+
const value = pathParams[paramName];
|
|
151
|
+
if (value === void 0) {
|
|
152
|
+
throw new Error(`Missing path parameter: ${paramName}`);
|
|
153
|
+
}
|
|
154
|
+
return String(value);
|
|
155
|
+
}
|
|
156
|
+
return segment;
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
function useQueryMode(api, trackedCall, options) {
|
|
160
|
+
const { autoGenerateTags, staleTime, enabled } = options;
|
|
161
|
+
const queryKey = createQueryKey(trackedCall);
|
|
162
|
+
const requestOptions = trackedCall.options;
|
|
163
|
+
const resolvedPath = resolvePath(
|
|
164
|
+
trackedCall.path,
|
|
165
|
+
requestOptions?.pathParams
|
|
166
|
+
);
|
|
167
|
+
const queryTags = requestOptions?.tags ?? (autoGenerateTags ? generateTags(resolvedPath) : []);
|
|
168
|
+
const getCacheState = (includeNeedsFetch = false) => {
|
|
169
|
+
const cached = getCache(queryKey);
|
|
170
|
+
const hasCachedData = cached?.data !== void 0;
|
|
171
|
+
const isFetching = !!cached?.promise;
|
|
172
|
+
const needsFetch = includeNeedsFetch && (!hasCachedData || isStale(queryKey, staleTime));
|
|
173
|
+
return {
|
|
174
|
+
loading: !hasCachedData && (isFetching || needsFetch),
|
|
175
|
+
fetching: isFetching || needsFetch,
|
|
176
|
+
data: cached?.data,
|
|
177
|
+
error: cached?.error
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
const [state, dispatch] = useReducer(
|
|
181
|
+
hookReducer,
|
|
182
|
+
null,
|
|
183
|
+
() => getCacheState(true)
|
|
184
|
+
);
|
|
185
|
+
const mountedRef = useRef(true);
|
|
186
|
+
const fetchRef = useRef(null);
|
|
187
|
+
useEffect(() => {
|
|
188
|
+
mountedRef.current = true;
|
|
189
|
+
if (!enabled) {
|
|
190
|
+
dispatch({ type: "RESET" });
|
|
191
|
+
return () => {
|
|
192
|
+
mountedRef.current = false;
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
dispatch({ type: "RESET", state: getCacheState(true) });
|
|
196
|
+
const doFetch = () => {
|
|
197
|
+
const cached2 = getCache(queryKey);
|
|
198
|
+
if (cached2?.promise) {
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
dispatch({ type: "FETCH_START" });
|
|
202
|
+
let current = api;
|
|
203
|
+
for (const segment of resolvedPath) {
|
|
204
|
+
current = current[segment];
|
|
205
|
+
}
|
|
206
|
+
const method = current[trackedCall.method];
|
|
207
|
+
const fetchPromise = method(trackedCall.options).then((res) => {
|
|
208
|
+
if (mountedRef.current) {
|
|
209
|
+
setCache(queryKey, {
|
|
210
|
+
data: res.error ? void 0 : res.data,
|
|
211
|
+
error: res.error,
|
|
212
|
+
timestamp: Date.now(),
|
|
213
|
+
tags: queryTags
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
setCache(queryKey, {
|
|
218
|
+
promise: fetchPromise,
|
|
219
|
+
tags: queryTags
|
|
220
|
+
});
|
|
221
|
+
};
|
|
222
|
+
fetchRef.current = doFetch;
|
|
223
|
+
const cached = getCache(queryKey);
|
|
224
|
+
if (cached?.data !== void 0 && !isStale(queryKey, staleTime)) {
|
|
225
|
+
dispatch({ type: "SYNC_CACHE", state: getCacheState() });
|
|
226
|
+
} else {
|
|
227
|
+
doFetch();
|
|
228
|
+
}
|
|
229
|
+
const unsubscribe = subscribeCache(queryKey, () => {
|
|
230
|
+
if (mountedRef.current) {
|
|
231
|
+
dispatch({ type: "SYNC_CACHE", state: getCacheState() });
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
return () => {
|
|
235
|
+
mountedRef.current = false;
|
|
236
|
+
fetchRef.current = null;
|
|
237
|
+
unsubscribe();
|
|
238
|
+
};
|
|
239
|
+
}, [queryKey, enabled]);
|
|
240
|
+
useEffect(() => {
|
|
241
|
+
if (queryTags.length === 0) return;
|
|
242
|
+
return onRevalidate((invalidatedTags) => {
|
|
243
|
+
const hasMatch = invalidatedTags.some((tag) => queryTags.includes(tag));
|
|
244
|
+
if (hasMatch && mountedRef.current && fetchRef.current) {
|
|
245
|
+
fetchRef.current();
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
}, [JSON.stringify(queryTags)]);
|
|
249
|
+
return state;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// src/react/types.ts
|
|
253
|
+
var HTTP_METHODS = ["get", "post", "put", "patch", "delete"];
|
|
254
|
+
|
|
255
|
+
// src/react/trackingProxy.ts
|
|
256
|
+
function createTrackingProxy(onTrack) {
|
|
257
|
+
const createProxy = (path = []) => {
|
|
258
|
+
return new Proxy(() => {
|
|
259
|
+
}, {
|
|
260
|
+
get(_, prop) {
|
|
261
|
+
if (HTTP_METHODS.includes(prop)) {
|
|
262
|
+
const methodFn = (options) => {
|
|
263
|
+
onTrack({
|
|
264
|
+
trackedCall: { path, method: prop, options },
|
|
265
|
+
selectorPath: null,
|
|
266
|
+
selectorMethod: null
|
|
267
|
+
});
|
|
268
|
+
return Promise.resolve({ status: 200, data: void 0, error: void 0 });
|
|
269
|
+
};
|
|
270
|
+
onTrack({
|
|
271
|
+
trackedCall: null,
|
|
272
|
+
selectorPath: path,
|
|
273
|
+
selectorMethod: prop
|
|
274
|
+
});
|
|
275
|
+
return methodFn;
|
|
276
|
+
}
|
|
277
|
+
return createProxy([...path, prop]);
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
};
|
|
281
|
+
return createProxy();
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// src/react/useSelectorMode.ts
|
|
285
|
+
import { useRef as useRef2, useReducer as useReducer2 } from "react";
|
|
286
|
+
function resolvePath2(path, pathParams) {
|
|
287
|
+
if (!pathParams) return path;
|
|
288
|
+
return path.map((segment) => {
|
|
289
|
+
if (segment.startsWith(":")) {
|
|
290
|
+
const paramName = segment.slice(1);
|
|
291
|
+
const value = pathParams[paramName];
|
|
292
|
+
if (value === void 0) {
|
|
293
|
+
throw new Error(`Missing path parameter: ${paramName}`);
|
|
294
|
+
}
|
|
295
|
+
return String(value);
|
|
296
|
+
}
|
|
297
|
+
return segment;
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
function hasPathParams(path) {
|
|
301
|
+
return path.some((segment) => segment.startsWith(":"));
|
|
302
|
+
}
|
|
303
|
+
function useSelectorMode(config) {
|
|
304
|
+
const { method, api, path, methodName, autoRevalidateTags } = config;
|
|
305
|
+
const [state, dispatch] = useReducer2(hookReducer, initialState);
|
|
306
|
+
const methodRef = useRef2(method);
|
|
307
|
+
const apiRef = useRef2(api);
|
|
308
|
+
const triggerRef = useRef2(null);
|
|
309
|
+
const pathRef = useRef2(path);
|
|
310
|
+
const methodNameRef = useRef2(methodName);
|
|
311
|
+
const autoRevalidateRef = useRef2(autoRevalidateTags);
|
|
312
|
+
methodRef.current = method;
|
|
313
|
+
apiRef.current = api;
|
|
314
|
+
pathRef.current = path;
|
|
315
|
+
methodNameRef.current = methodName;
|
|
316
|
+
autoRevalidateRef.current = autoRevalidateTags;
|
|
317
|
+
if (!triggerRef.current) {
|
|
318
|
+
triggerRef.current = (async (...args) => {
|
|
319
|
+
dispatch({ type: "FETCH_START" });
|
|
320
|
+
const options = args[0];
|
|
321
|
+
const resolvedPath = resolvePath2(pathRef.current, options?.pathParams);
|
|
322
|
+
let res;
|
|
323
|
+
if (hasPathParams(pathRef.current)) {
|
|
324
|
+
let current = apiRef.current;
|
|
325
|
+
for (const segment of resolvedPath) {
|
|
326
|
+
current = current[segment];
|
|
327
|
+
}
|
|
328
|
+
const resolvedMethod = current[methodNameRef.current];
|
|
329
|
+
res = await resolvedMethod(...args);
|
|
330
|
+
} else {
|
|
331
|
+
res = await methodRef.current(...args);
|
|
332
|
+
}
|
|
333
|
+
if (!res.error) {
|
|
334
|
+
dispatch({ type: "FETCH_SUCCESS", data: res.data });
|
|
335
|
+
const tagsToInvalidate = options?.revalidateTags ?? (autoRevalidateRef.current ? generateTags(resolvedPath) : []);
|
|
336
|
+
if (tagsToInvalidate.length > 0) {
|
|
337
|
+
invalidateTags(tagsToInvalidate);
|
|
338
|
+
}
|
|
339
|
+
} else {
|
|
340
|
+
dispatch({ type: "FETCH_ERROR", error: res.error });
|
|
341
|
+
}
|
|
342
|
+
return res;
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
return {
|
|
346
|
+
trigger: triggerRef.current,
|
|
347
|
+
...state
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// src/react/createEnlaceHookReact.ts
|
|
352
|
+
function createEnlaceHookReact(baseUrl, defaultOptions = {}, hookOptions = {}) {
|
|
353
|
+
const {
|
|
354
|
+
autoGenerateTags = true,
|
|
355
|
+
autoRevalidateTags = true,
|
|
356
|
+
staleTime = 0,
|
|
357
|
+
onSuccess,
|
|
358
|
+
onError
|
|
359
|
+
} = hookOptions;
|
|
360
|
+
const api = createEnlace(baseUrl, defaultOptions, { onSuccess, onError });
|
|
361
|
+
function useEnlaceHook(selectorOrQuery, queryOptions) {
|
|
362
|
+
let trackingResult = {
|
|
363
|
+
trackedCall: null,
|
|
364
|
+
selectorPath: null,
|
|
365
|
+
selectorMethod: null
|
|
366
|
+
};
|
|
367
|
+
const trackingProxy = createTrackingProxy((result2) => {
|
|
368
|
+
trackingResult = result2;
|
|
369
|
+
});
|
|
370
|
+
const result = selectorOrQuery(
|
|
371
|
+
trackingProxy
|
|
372
|
+
);
|
|
373
|
+
if (typeof result === "function") {
|
|
374
|
+
const actualResult = selectorOrQuery(api);
|
|
375
|
+
return useSelectorMode({
|
|
376
|
+
method: actualResult,
|
|
377
|
+
api,
|
|
378
|
+
path: trackingResult.selectorPath ?? [],
|
|
379
|
+
methodName: trackingResult.selectorMethod ?? "",
|
|
380
|
+
autoRevalidateTags
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
return useQueryMode(
|
|
384
|
+
api,
|
|
385
|
+
trackingResult.trackedCall,
|
|
386
|
+
{ autoGenerateTags, staleTime, enabled: queryOptions?.enabled ?? true }
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
return useEnlaceHook;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// src/next/index.ts
|
|
393
|
+
import {
|
|
394
|
+
createProxyHandler
|
|
395
|
+
} from "enlace-core";
|
|
396
|
+
|
|
397
|
+
// src/next/fetch.ts
|
|
398
|
+
import {
|
|
399
|
+
executeFetch
|
|
400
|
+
} from "enlace-core";
|
|
401
|
+
async function executeNextFetch(baseUrl, path, method, combinedOptions, requestOptions) {
|
|
402
|
+
const {
|
|
403
|
+
autoGenerateTags = true,
|
|
404
|
+
autoRevalidateTags = true,
|
|
405
|
+
revalidator,
|
|
406
|
+
onSuccess,
|
|
407
|
+
...coreOptions
|
|
408
|
+
} = combinedOptions;
|
|
409
|
+
const isGet = method === "GET";
|
|
410
|
+
const autoTags = generateTags(path);
|
|
411
|
+
const nextOnSuccess = (payload) => {
|
|
412
|
+
if (!isGet && !requestOptions?.skipRevalidator) {
|
|
413
|
+
const revalidateTags = requestOptions?.revalidateTags ?? (autoRevalidateTags ? autoTags : []);
|
|
414
|
+
const revalidatePaths = requestOptions?.revalidatePaths ?? [];
|
|
415
|
+
if (revalidateTags.length || revalidatePaths.length) {
|
|
416
|
+
revalidator?.(revalidateTags, revalidatePaths);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
onSuccess?.(payload);
|
|
420
|
+
};
|
|
421
|
+
const nextRequestOptions = { ...requestOptions };
|
|
422
|
+
if (isGet) {
|
|
423
|
+
const tags = requestOptions?.tags ?? (autoGenerateTags ? autoTags : void 0);
|
|
424
|
+
const nextFetchOptions = {};
|
|
425
|
+
if (tags) {
|
|
426
|
+
nextFetchOptions.tags = tags;
|
|
427
|
+
}
|
|
428
|
+
if (requestOptions?.revalidate !== void 0) {
|
|
429
|
+
nextFetchOptions.revalidate = requestOptions.revalidate;
|
|
430
|
+
}
|
|
431
|
+
nextRequestOptions.next = nextFetchOptions;
|
|
432
|
+
}
|
|
433
|
+
return executeFetch(
|
|
434
|
+
baseUrl,
|
|
435
|
+
path,
|
|
436
|
+
method,
|
|
437
|
+
{ ...coreOptions, onSuccess: nextOnSuccess },
|
|
438
|
+
nextRequestOptions
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// src/next/index.ts
|
|
443
|
+
function createEnlaceNext(baseUrl, defaultOptions = {}, nextOptions = {}) {
|
|
444
|
+
const combinedOptions = { ...defaultOptions, ...nextOptions };
|
|
445
|
+
return createProxyHandler(
|
|
446
|
+
baseUrl,
|
|
447
|
+
combinedOptions,
|
|
448
|
+
[],
|
|
449
|
+
executeNextFetch
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// src/next/createEnlaceHookNext.ts
|
|
454
|
+
function createEnlaceHookNext(baseUrl, defaultOptions = {}, hookOptions = {}) {
|
|
455
|
+
const {
|
|
456
|
+
autoGenerateTags = true,
|
|
457
|
+
autoRevalidateTags = true,
|
|
458
|
+
staleTime = 0,
|
|
459
|
+
...nextOptions
|
|
460
|
+
} = hookOptions;
|
|
461
|
+
const api = createEnlaceNext(baseUrl, defaultOptions, {
|
|
462
|
+
autoGenerateTags,
|
|
463
|
+
autoRevalidateTags,
|
|
464
|
+
...nextOptions
|
|
465
|
+
});
|
|
466
|
+
function useEnlaceHook(selectorOrQuery, queryOptions) {
|
|
467
|
+
let trackedCall = null;
|
|
468
|
+
let selectorPath = null;
|
|
469
|
+
let selectorMethod = null;
|
|
470
|
+
const trackingProxy = createTrackingProxy((result2) => {
|
|
471
|
+
trackedCall = result2.trackedCall;
|
|
472
|
+
selectorPath = result2.selectorPath;
|
|
473
|
+
selectorMethod = result2.selectorMethod;
|
|
474
|
+
});
|
|
475
|
+
const result = selectorOrQuery(trackingProxy);
|
|
476
|
+
if (typeof result === "function") {
|
|
477
|
+
const actualResult = selectorOrQuery(api);
|
|
478
|
+
return useSelectorMode({
|
|
479
|
+
method: actualResult,
|
|
480
|
+
api,
|
|
481
|
+
path: selectorPath ?? [],
|
|
482
|
+
methodName: selectorMethod ?? "",
|
|
483
|
+
autoRevalidateTags
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
return useQueryMode(
|
|
487
|
+
api,
|
|
488
|
+
trackedCall,
|
|
489
|
+
{ autoGenerateTags, staleTime, enabled: queryOptions?.enabled ?? true }
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
return useEnlaceHook;
|
|
493
|
+
}
|
|
494
|
+
export {
|
|
495
|
+
HTTP_METHODS,
|
|
496
|
+
createEnlaceHookNext,
|
|
497
|
+
createEnlaceHookReact
|
|
498
|
+
};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,121 +1,83 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
1
|
+
import { EnlaceCallbackPayload, EnlaceErrorCallbackPayload, EnlaceCallbacks, EnlaceOptions, WildcardClient, EnlaceClient } from 'enlace-core';
|
|
2
|
+
export * from 'enlace-core';
|
|
3
|
+
|
|
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
|
+
* Path parameters for dynamic URL segments.
|
|
16
|
+
* Used to replace :paramName placeholders in the URL path.
|
|
17
|
+
* @example
|
|
18
|
+
* // With path api.products[':id'].delete
|
|
19
|
+
* trigger({ pathParams: { id: '123' } }) // → DELETE /products/123
|
|
20
|
+
*/
|
|
21
|
+
pathParams?: Record<string, string | number>;
|
|
21
22
|
};
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
/** Options for createEnlaceHookReact factory */
|
|
24
|
+
type EnlaceHookOptions = {
|
|
25
|
+
/**
|
|
26
|
+
* Auto-generate cache tags from URL path for GET requests.
|
|
27
|
+
* e.g., `/posts/1` generates tags `['posts', 'posts/1']`
|
|
28
|
+
* @default true
|
|
29
|
+
*/
|
|
30
|
+
autoGenerateTags?: boolean;
|
|
31
|
+
/** Auto-revalidate generated tags after successful mutations. @default true */
|
|
32
|
+
autoRevalidateTags?: boolean;
|
|
33
|
+
/** Time in ms before cached data is considered stale. @default 0 (always stale) */
|
|
34
|
+
staleTime?: number;
|
|
35
|
+
/** Callback called on successful API responses */
|
|
36
|
+
onSuccess?: (payload: EnlaceCallbackPayload<unknown>) => void;
|
|
37
|
+
/** Callback called on error responses (HTTP errors or network failures) */
|
|
38
|
+
onError?: (payload: EnlaceErrorCallbackPayload<unknown>) => void;
|
|
26
39
|
};
|
|
40
|
+
|
|
27
41
|
/**
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
* @example
|
|
32
|
-
* type MyApi = {
|
|
33
|
-
* posts: {
|
|
34
|
-
* $get: Endpoint<Post[], ApiError>;
|
|
35
|
-
* $post: Endpoint<Post, ApiError, CreatePost>; // with body
|
|
36
|
-
* _: {
|
|
37
|
-
* $get: Endpoint<Post, NotFoundError>;
|
|
38
|
-
* };
|
|
39
|
-
* };
|
|
40
|
-
* };
|
|
42
|
+
* Handler function called after successful mutations to trigger server-side revalidation.
|
|
43
|
+
* @param tags - Cache tags to revalidate
|
|
44
|
+
* @param paths - URL paths to revalidate
|
|
41
45
|
*/
|
|
42
|
-
type
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
type ExtractError<TSchema, TMethod extends SchemaMethod> = ExtractMethodDef<TSchema, TMethod> extends {
|
|
57
|
-
error: infer E;
|
|
58
|
-
} ? E : never;
|
|
59
|
-
type ExtractBody<TSchema, TMethod extends SchemaMethod> = ExtractMethodDef<TSchema, TMethod> extends {
|
|
60
|
-
body: infer B;
|
|
61
|
-
} ? B : never;
|
|
62
|
-
type HasMethod<TSchema, TMethod extends SchemaMethod> = TSchema extends {
|
|
63
|
-
[K in TMethod]: MethodDefinition;
|
|
64
|
-
} ? true : false;
|
|
65
|
-
type MethodFn<TSchema, TMethod extends SchemaMethod, TRequestOptionsBase = object> = HasMethod<TSchema, TMethod> extends true ? ExtractBody<TSchema, TMethod> extends never ? (options?: RequestOptions<never> & TRequestOptionsBase) => Promise<EnlaceResponse<ExtractData<TSchema, TMethod>, ExtractError<TSchema, TMethod>>> : (options: RequestOptions<ExtractBody<TSchema, TMethod>> & TRequestOptionsBase) => Promise<EnlaceResponse<ExtractData<TSchema, TMethod>, ExtractError<TSchema, TMethod>>> : never;
|
|
66
|
-
type IsSpecialKey<K> = K extends SchemaMethod | "_" ? true : false;
|
|
67
|
-
type StaticPathKeys<TSchema> = {
|
|
68
|
-
[K in keyof TSchema as IsSpecialKey<K> extends true ? never : K extends string ? K : never]: TSchema[K];
|
|
46
|
+
type RevalidateHandler = (tags: string[], paths: string[]) => void | Promise<void>;
|
|
47
|
+
/** Next.js-specific options (third argument for createEnlaceNext) */
|
|
48
|
+
type NextOptions = Pick<EnlaceHookOptions, "autoGenerateTags" | "autoRevalidateTags"> & EnlaceCallbacks & {
|
|
49
|
+
/**
|
|
50
|
+
* Handler called after successful mutations to trigger server-side revalidation.
|
|
51
|
+
* Receives auto-generated or manually specified tags and paths.
|
|
52
|
+
* @example
|
|
53
|
+
* ```ts
|
|
54
|
+
* createEnlaceNext("http://localhost:3000/api/", {}, {
|
|
55
|
+
* revalidator: (tags, paths) => revalidateServerAction(tags, paths)
|
|
56
|
+
* });
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
revalidator?: RevalidateHandler;
|
|
69
60
|
};
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
61
|
+
/** Per-request options for Next.js fetch - extends React's base options */
|
|
62
|
+
type NextRequestOptionsBase = ReactRequestOptionsBase & {
|
|
63
|
+
/** Time in seconds to revalidate, or false to disable */
|
|
64
|
+
revalidate?: number | false;
|
|
65
|
+
/**
|
|
66
|
+
* URL paths to revalidate after mutation
|
|
67
|
+
* This doesn't do anything on the client by itself - it's passed to the revalidator handler.
|
|
68
|
+
* You must implement the revalidation logic in the revalidator.
|
|
69
|
+
*/
|
|
70
|
+
revalidatePaths?: string[];
|
|
71
|
+
/**
|
|
72
|
+
* Skip server-side revalidation for this request.
|
|
73
|
+
* Useful when autoRevalidateTags is enabled but you want to opt-out for specific mutations.
|
|
74
|
+
* You can still pass empty [] to revalidateTags to skip triggering revalidation.
|
|
75
|
+
* But this flag can be used if you want to revalidate client-side and skip server-side entirely.
|
|
76
|
+
* Eg. you don't fetch any data on server component and you might want to skip the overhead of revalidation.
|
|
77
|
+
*/
|
|
78
|
+
skipRevalidator?: boolean;
|
|
80
79
|
};
|
|
81
|
-
type DynamicAccess<TSchema, TRequestOptionsBase = object> = ExtractDynamicSchema<TSchema> extends never ? object : {
|
|
82
|
-
[key: string]: EnlaceClient<ExtractDynamicSchema<TSchema>, TRequestOptionsBase>;
|
|
83
|
-
[key: number]: EnlaceClient<ExtractDynamicSchema<TSchema>, TRequestOptionsBase>;
|
|
84
|
-
};
|
|
85
|
-
type MethodNameKeys = "get" | "post" | "put" | "patch" | "delete";
|
|
86
|
-
type EnlaceClient<TSchema, TRequestOptionsBase = object> = HttpMethods<TSchema, TRequestOptionsBase> & DynamicAccess<TSchema, TRequestOptionsBase> & {
|
|
87
|
-
[K in keyof StaticPathKeys<TSchema> as K extends MethodNameKeys ? never : K]: EnlaceClient<TSchema[K], TRequestOptionsBase>;
|
|
88
|
-
};
|
|
89
|
-
type WildcardMethodFn<TRequestOptionsBase = object> = (options?: RequestOptions<unknown> & TRequestOptionsBase) => Promise<EnlaceResponse<unknown, unknown>>;
|
|
90
|
-
/**
|
|
91
|
-
* Wildcard client type - allows any path access when no schema is provided.
|
|
92
|
-
* All methods are available at every level and return unknown types.
|
|
93
|
-
*/
|
|
94
|
-
type WildcardClient<TRequestOptionsBase = object> = {
|
|
95
|
-
get: WildcardMethodFn<TRequestOptionsBase>;
|
|
96
|
-
post: WildcardMethodFn<TRequestOptionsBase>;
|
|
97
|
-
put: WildcardMethodFn<TRequestOptionsBase>;
|
|
98
|
-
patch: WildcardMethodFn<TRequestOptionsBase>;
|
|
99
|
-
delete: WildcardMethodFn<TRequestOptionsBase>;
|
|
100
|
-
} & {
|
|
101
|
-
[key: string]: WildcardClient<TRequestOptionsBase>;
|
|
102
|
-
[key: number]: WildcardClient<TRequestOptionsBase>;
|
|
103
|
-
};
|
|
104
|
-
|
|
105
|
-
declare function createProxyHandler<TSchema extends object, TOptions = EnlaceOptions>(baseUrl: string, defaultOptions: TOptions, path?: string[], fetchExecutor?: FetchExecutor<TOptions, RequestOptions<unknown>>): TSchema;
|
|
106
80
|
|
|
107
|
-
declare function
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Creates an API client.
|
|
111
|
-
*
|
|
112
|
-
* @example
|
|
113
|
-
* // Typed mode - with schema
|
|
114
|
-
* const api = createEnlace<MyApi>('https://api.example.com');
|
|
115
|
-
*
|
|
116
|
-
* // Untyped mode - no schema
|
|
117
|
-
* const api = createEnlace('https://api.example.com');
|
|
118
|
-
*/
|
|
119
|
-
declare function createEnlace<TSchema = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions): unknown extends TSchema ? WildcardClient : EnlaceClient<TSchema>;
|
|
81
|
+
declare function createEnlaceNext<TSchema = unknown, TDefaultError = unknown>(baseUrl: string, defaultOptions?: EnlaceOptions | null, nextOptions?: NextOptions): unknown extends TSchema ? WildcardClient<NextRequestOptionsBase> : EnlaceClient<TSchema, TDefaultError, NextRequestOptionsBase>;
|
|
120
82
|
|
|
121
|
-
export { type
|
|
83
|
+
export { type NextOptions, type NextRequestOptionsBase, createEnlaceNext };
|