@web-ts-toolkit/access-router-react 0.38.0 → 0.40.0

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.
Files changed (6) hide show
  1. package/README.md +29 -13
  2. package/index.d.mts +42 -39
  3. package/index.d.ts +42 -39
  4. package/index.js +213 -167
  5. package/index.mjs +213 -167
  6. package/package.json +3 -3
package/index.mjs CHANGED
@@ -4,43 +4,58 @@ import { ServiceError } from "@web-ts-toolkit/access-router-client";
4
4
 
5
5
  // src/fetch.ts
6
6
  import { useEffect, useRef, useCallback } from "react";
7
- function composeAbortSignals(callerSignal, internalSignal) {
8
- if (!callerSignal) {
9
- return { signal: internalSignal, release: () => {
10
- } };
11
- }
12
- if (callerSignal.aborted) {
13
- return { signal: callerSignal, release: () => {
14
- } };
15
- }
16
- if (internalSignal.aborted) {
17
- return { signal: internalSignal, release: () => {
18
- } };
7
+ function composeAbortSignals(internalSignal, ...otherSignals) {
8
+ const uniqueSignals = [];
9
+ for (const signal of [internalSignal, ...otherSignals]) {
10
+ if (!signal || uniqueSignals.includes(signal)) {
11
+ continue;
12
+ }
13
+ if (signal.aborted) {
14
+ return { signal, release: () => {
15
+ } };
16
+ }
17
+ uniqueSignals.push(signal);
19
18
  }
20
- if (callerSignal === internalSignal) {
21
- return { signal: internalSignal, release: () => {
19
+ if (uniqueSignals.length === 1) {
20
+ return { signal: uniqueSignals[0], release: () => {
22
21
  } };
23
22
  }
24
23
  const composed = new AbortController();
25
- const detach = () => {
26
- callerSignal.removeEventListener("abort", onCallerAbort);
27
- internalSignal.removeEventListener("abort", onInternalAbort);
24
+ let released = false;
25
+ const listeners = /* @__PURE__ */ new Map();
26
+ const release = () => {
27
+ if (released) {
28
+ return;
29
+ }
30
+ released = true;
31
+ for (const [signal, onAbort] of listeners) {
32
+ signal.removeEventListener("abort", onAbort);
33
+ }
34
+ listeners.clear();
28
35
  };
29
36
  const settle = (source) => {
30
- composed.abort(source.reason);
31
- detach();
37
+ if (!composed.signal.aborted) {
38
+ composed.abort(source.reason);
39
+ }
40
+ release();
32
41
  };
33
- const onCallerAbort = () => settle(callerSignal);
34
- const onInternalAbort = () => settle(internalSignal);
35
- callerSignal.addEventListener("abort", onCallerAbort, { once: true });
36
- internalSignal.addEventListener("abort", onInternalAbort, { once: true });
42
+ for (const signal of uniqueSignals) {
43
+ const onAbort = () => settle(signal);
44
+ listeners.set(signal, onAbort);
45
+ signal.addEventListener("abort", onAbort, { once: true });
46
+ }
37
47
  return {
38
48
  signal: composed.signal,
39
- // Idempotent: detach is safe to call even after the listeners already
40
- // fired and detached on abort.
41
- release: detach
49
+ release
42
50
  };
43
51
  }
52
+ function requestConfigKeyInput(requestConfig) {
53
+ if (!requestConfig) {
54
+ return void 0;
55
+ }
56
+ const { signal: _signal, ...rest } = requestConfig;
57
+ return Object.keys(rest).length === 0 ? void 0 : rest;
58
+ }
44
59
  function mergeRequestConfig(requestConfig, signal) {
45
60
  if (signal === void 0) {
46
61
  return { ...requestConfig ?? {} };
@@ -71,23 +86,45 @@ var RequestKeyError = class extends Error {
71
86
  this.name = "RequestKeyError";
72
87
  }
73
88
  };
89
+ var REQUEST_KEY_MAX_DEPTH = 64;
90
+ var REQUEST_KEY_MAX_NODES = 2e4;
91
+ var REQUEST_KEY_MAX_OUTPUT_LENGTH = 2e5;
74
92
  function requestKeyFor(value) {
75
- return requestKeyForImpl(value, { stack: /* @__PURE__ */ new WeakSet() });
93
+ return requestKeyForImpl(value, { stack: /* @__PURE__ */ new WeakSet(), cache: /* @__PURE__ */ new WeakMap(), nodesVisited: 0, outputLength: 0 }, 0);
76
94
  }
77
- function requestKeyForImpl(value, ctx) {
78
- if (value === null) return "n:";
79
- if (value === void 0) return "u:";
95
+ function requestKeyForImpl(value, ctx, depth) {
96
+ if (depth > REQUEST_KEY_MAX_DEPTH) {
97
+ throw new RequestKeyError(
98
+ `requestKeyFor: request input exceeds the maximum depth of ${REQUEST_KEY_MAX_DEPTH} nested arrays/objects; flatten or normalize the structure before passing it to a query hook.`
99
+ );
100
+ }
101
+ if (value === null) {
102
+ noteRequestKeyNode(ctx);
103
+ return finalizePrimitiveRequestKey(ctx, "n:");
104
+ }
105
+ if (value === void 0) {
106
+ noteRequestKeyNode(ctx);
107
+ return finalizePrimitiveRequestKey(ctx, "u:");
108
+ }
109
+ if (typeof value === "object") {
110
+ const cached = ctx.cache.get(value);
111
+ if (cached !== void 0) {
112
+ reserveRequestKeyOutput(ctx, cached.length);
113
+ return cached;
114
+ }
115
+ }
116
+ noteRequestKeyNode(ctx);
80
117
  const t = typeof value;
81
118
  switch (t) {
82
119
  case "boolean":
83
- return `b:${value}`;
120
+ return finalizePrimitiveRequestKey(ctx, `b:${value}`);
84
121
  case "number": {
85
- if (Number.isNaN(value)) return "n:NaN";
86
- if (Object.is(value, -0)) return "n:-0";
87
- return `n:${String(value)}`;
122
+ if (Number.isNaN(value)) return finalizePrimitiveRequestKey(ctx, "n:NaN");
123
+ if (Object.is(value, -0)) return finalizePrimitiveRequestKey(ctx, "n:-0");
124
+ return finalizePrimitiveRequestKey(ctx, `n:${String(value)}`);
88
125
  }
89
126
  case "string":
90
- return `s:${JSON.stringify(value)}`;
127
+ return finalizePrimitiveRequestKey(ctx, `s:${JSON.stringify(value)}`);
91
128
  case "bigint":
92
129
  throw new RequestKeyError(
93
130
  "requestKeyFor: bigint is not supported in request keys; convert to a number or string before passing to a query hook."
@@ -102,7 +139,7 @@ function requestKeyForImpl(value, ctx) {
102
139
  );
103
140
  case "object": {
104
141
  if (value instanceof Date) {
105
- return `d:${value.getTime()}`;
142
+ return finalizePrimitiveRequestKey(ctx, `d:${value.getTime()}`);
106
143
  }
107
144
  if (value instanceof RegExp || value instanceof Map || value instanceof Set || typeof URL !== "undefined" && value instanceof URL || value instanceof Error) {
108
145
  throw new RequestKeyError(
@@ -114,13 +151,19 @@ function requestKeyForImpl(value, ctx) {
114
151
  throw new RequestKeyError("requestKeyFor: cycle detected in array (request key).");
115
152
  }
116
153
  ctx.stack.add(value);
154
+ reserveRequestKeyOutput(ctx, 1);
117
155
  let out2 = "[";
118
156
  for (let i = 0; i < value.length; i++) {
119
- if (i > 0) out2 += ",";
120
- out2 += requestKeyForImpl(value[i], ctx);
157
+ if (i > 0) {
158
+ reserveRequestKeyOutput(ctx, 1);
159
+ out2 += ",";
160
+ }
161
+ out2 += requestKeyForImpl(value[i], ctx, depth + 1);
121
162
  }
163
+ reserveRequestKeyOutput(ctx, 1);
122
164
  out2 += "]";
123
165
  ctx.stack.delete(value);
166
+ ctx.cache.set(value, out2);
124
167
  return out2;
125
168
  }
126
169
  const proto = Object.getPrototypeOf(value);
@@ -140,9 +183,13 @@ function requestKeyForImpl(value, ctx) {
140
183
  );
141
184
  }
142
185
  const keys = Object.keys(value).sort();
186
+ reserveRequestKeyOutput(ctx, 1);
143
187
  let out = "{";
144
188
  for (let i = 0; i < keys.length; i++) {
145
- if (i > 0) out += ",";
189
+ if (i > 0) {
190
+ reserveRequestKeyOutput(ctx, 1);
191
+ out += ",";
192
+ }
146
193
  const k = keys[i];
147
194
  const desc = Object.getOwnPropertyDescriptor(value, k);
148
195
  if (desc === void 0) {
@@ -153,16 +200,40 @@ function requestKeyForImpl(value, ctx) {
153
200
  `requestKeyFor: accessor property ${JSON.stringify(k)} is not supported in request keys; getters/setters must not run during dep-key construction.`
154
201
  );
155
202
  }
156
- out += `${JSON.stringify(k)}:${requestKeyForImpl(desc.value, ctx)}`;
203
+ const keyText = JSON.stringify(k);
204
+ reserveRequestKeyOutput(ctx, keyText.length + 1);
205
+ out += `${keyText}:${requestKeyForImpl(desc.value, ctx, depth + 1)}`;
157
206
  }
207
+ reserveRequestKeyOutput(ctx, 1);
158
208
  out += "}";
159
209
  ctx.stack.delete(value);
210
+ ctx.cache.set(value, out);
160
211
  return out;
161
212
  }
162
213
  default:
163
214
  throw new RequestKeyError(`requestKeyFor: unsupported value of type ${t}.`);
164
215
  }
165
216
  }
217
+ function noteRequestKeyNode(ctx) {
218
+ ctx.nodesVisited += 1;
219
+ if (ctx.nodesVisited > REQUEST_KEY_MAX_NODES) {
220
+ throw new RequestKeyError(
221
+ `requestKeyFor: request input exceeds the maximum traversal budget of ${REQUEST_KEY_MAX_NODES} nodes; reduce the filter, params, or requestConfig shape before passing it to a query hook.`
222
+ );
223
+ }
224
+ }
225
+ function finalizePrimitiveRequestKey(ctx, key) {
226
+ reserveRequestKeyOutput(ctx, key.length);
227
+ return key;
228
+ }
229
+ function reserveRequestKeyOutput(ctx, length) {
230
+ ctx.outputLength += length;
231
+ if (ctx.outputLength > REQUEST_KEY_MAX_OUTPUT_LENGTH) {
232
+ throw new RequestKeyError(
233
+ `requestKeyFor: request input exceeds the maximum serialized key length of ${REQUEST_KEY_MAX_OUTPUT_LENGTH} characters; reduce repeated or oversized request data before passing it to a query hook.`
234
+ );
235
+ }
236
+ }
166
237
  function useMountRef() {
167
238
  const ref = useRef(true);
168
239
  useEffect(() => {
@@ -191,11 +262,33 @@ function useEventCallback(cb) {
191
262
  }, []);
192
263
  return invoker;
193
264
  }
265
+ function useLatestRef(value) {
266
+ const ref = useRef2(value);
267
+ useLayoutEffect(() => {
268
+ ref.current = value;
269
+ }, [value]);
270
+ return ref;
271
+ }
272
+ function reportObserverError(error) {
273
+ queueMicrotask(() => {
274
+ throw error;
275
+ });
276
+ }
277
+ function runObserverSequence(invocations) {
278
+ for (const invoke of invocations) {
279
+ try {
280
+ invoke();
281
+ } catch (error) {
282
+ reportObserverError(error);
283
+ }
284
+ }
285
+ }
194
286
  function useAutoQuery({
195
287
  doFetch,
196
288
  applyResult,
197
289
  shouldFetch,
198
290
  deps,
291
+ getRequestSignal,
199
292
  onSuccess,
200
293
  onError,
201
294
  onSettled,
@@ -210,37 +303,42 @@ function useAutoQuery({
210
303
  const manager = useAbortManager();
211
304
  const mountRef = useMountRef();
212
305
  const ownerIdRef = useRef2(0);
306
+ const createAbortScope = useCallback2(
307
+ (callerSignal) => {
308
+ const controller = new AbortController();
309
+ manager.replace(controller);
310
+ const composed = composeAbortSignals(controller.signal, getRequestSignal?.(), callerSignal);
311
+ return {
312
+ controller,
313
+ effectiveSignal: composed.signal,
314
+ release: composed.release
315
+ };
316
+ },
317
+ [manager, getRequestSignal]
318
+ );
213
319
  const fireCallbacksSafely = useCallback2(
214
320
  (settle) => {
215
- try {
216
- if ("result" in settle) {
217
- onSuccess?.(settle.result);
218
- onSettled?.(settle.result, null);
219
- } else {
220
- onError?.(settle.error);
221
- onSettled?.(null, settle.error);
222
- }
223
- } catch (cbErr) {
224
- queueMicrotask(() => {
225
- throw cbErr;
226
- });
321
+ if ("result" in settle) {
322
+ runObserverSequence([() => onSuccess?.(settle.result), () => onSettled?.(settle.result, null)]);
323
+ return;
227
324
  }
325
+ runObserverSequence([() => onError?.(settle.error), () => onSettled?.(null, settle.error)]);
228
326
  },
229
327
  [onSuccess, onError, onSettled]
230
328
  );
231
329
  const runWithCallbacks = useCallback2(
232
- async (controller, doFetchOverride) => {
233
- const signal = controller.signal;
330
+ async (abortScope, doFetchOverride) => {
331
+ const { effectiveSignal, release } = abortScope;
234
332
  const myId = ++ownerIdRef.current;
235
333
  setIsFetching(true);
236
334
  setError(null);
237
335
  if (!hasDataRef.current) setIsLoading(true);
238
336
  try {
239
- const res = await doFetchOverride(signal);
337
+ const res = await doFetchOverride(effectiveSignal);
240
338
  if (myId !== ownerIdRef.current) {
241
339
  return res;
242
340
  }
243
- if (signal.aborted) {
341
+ if (effectiveSignal.aborted) {
244
342
  if (mountRef.current) {
245
343
  if (!hasDataRef.current) setIsLoading(false);
246
344
  setIsFetching(false);
@@ -258,7 +356,7 @@ function useAutoQuery({
258
356
  if (myId !== ownerIdRef.current) {
259
357
  throw err;
260
358
  }
261
- if (signal.aborted) {
359
+ if (effectiveSignal.aborted) {
262
360
  if (mountRef.current) {
263
361
  if (!hasDataRef.current) setIsLoading(false);
264
362
  setIsFetching(false);
@@ -272,6 +370,8 @@ function useAutoQuery({
272
370
  fireCallbacksSafely({ error: err });
273
371
  onFailed?.();
274
372
  throw err;
373
+ } finally {
374
+ release();
275
375
  }
276
376
  },
277
377
  [applyResult, fireCallbacksSafely, mountRef, onFailed, onAborted]
@@ -284,40 +384,35 @@ function useAutoQuery({
284
384
  return;
285
385
  }
286
386
  setIsLoading(!hasDataRef.current);
287
- const controller = new AbortController();
288
- manager.replace(controller);
289
- runWithCallbacks(controller, doFetch).catch(() => {
387
+ const abortScope = createAbortScope();
388
+ runWithCallbacks(abortScope, doFetch).catch(() => {
290
389
  });
291
390
  return () => {
292
- controller.abort();
391
+ abortScope.controller.abort();
293
392
  };
294
393
  }, deps);
295
394
  const query = useCallback2(
296
395
  (doFetchOverride, callerSignal) => {
297
- const controller = new AbortController();
298
- manager.replace(controller);
299
- const composed = callerSignal ? composeAbortSignals(callerSignal, controller.signal) : { signal: controller.signal, release: () => {
300
- } };
301
- const effectiveSignal = composed.signal;
302
- const p = runWithCallbacks(controller, () => doFetchOverride(effectiveSignal));
303
- p.finally(() => composed.release()).catch(() => {
396
+ const abortScope = createAbortScope(callerSignal);
397
+ const p = runWithCallbacks(abortScope, doFetchOverride);
398
+ p.catch(() => {
304
399
  });
305
400
  return p;
306
401
  },
307
- [runWithCallbacks, manager]
402
+ [createAbortScope, runWithCallbacks]
308
403
  );
309
404
  const refetch = useCallback2(() => {
310
- const controller = new AbortController();
311
- manager.replace(controller);
312
- const p = runWithCallbacks(controller, doFetch);
405
+ const abortScope = createAbortScope();
406
+ const p = runWithCallbacks(abortScope, doFetch);
313
407
  p.catch(() => {
314
408
  });
315
409
  return p;
316
- }, [runWithCallbacks, manager, doFetch]);
410
+ }, [createAbortScope, runWithCallbacks, doFetch]);
317
411
  const resetError = useCallback2(() => {
318
412
  setError(null);
319
413
  }, []);
320
414
  const resetLoading = useCallback2(() => {
415
+ ownerIdRef.current += 1;
321
416
  setIsLoading(false);
322
417
  setIsFetching(false);
323
418
  hasDataRef.current = false;
@@ -340,7 +435,7 @@ function useMutation(execute, applyData, options) {
340
435
  const [isPending, setIsPending] = useState(false);
341
436
  const [error, setError] = useState(null);
342
437
  const mountRef = useMountRef();
343
- const { onSuccess, onSettled } = options ?? {};
438
+ const { onSuccess, onError, onSettled } = options ?? {};
344
439
  const activeCountRef = useRef2(0);
345
440
  const latestIdRef = useRef2(0);
346
441
  const executeMutate = useCallback2(
@@ -354,14 +449,7 @@ function useMutation(execute, applyData, options) {
354
449
  try {
355
450
  const result = await execute(...args);
356
451
  if (mountRef.current) {
357
- try {
358
- onSuccess?.(result);
359
- onSettled?.(result, null);
360
- } catch (cbErr) {
361
- queueMicrotask(() => {
362
- throw cbErr;
363
- });
364
- }
452
+ runObserverSequence([() => onSuccess?.(result), () => onSettled?.(result, null)]);
365
453
  if (myId === latestIdRef.current) {
366
454
  setData(applyData(result));
367
455
  }
@@ -370,13 +458,7 @@ function useMutation(execute, applyData, options) {
370
458
  } catch (err) {
371
459
  const svcErr = err;
372
460
  if (mountRef.current) {
373
- try {
374
- onSettled?.(null, svcErr);
375
- } catch (cbErr) {
376
- queueMicrotask(() => {
377
- throw cbErr;
378
- });
379
- }
461
+ runObserverSequence([() => onError?.(svcErr), () => onSettled?.(null, svcErr)]);
380
462
  if (myId === latestIdRef.current) {
381
463
  setError(svcErr);
382
464
  }
@@ -389,7 +471,7 @@ function useMutation(execute, applyData, options) {
389
471
  }
390
472
  }
391
473
  },
392
- [execute, applyData, mountRef, onSuccess, onSettled]
474
+ [execute, applyData, mountRef, onSuccess, onError, onSettled]
393
475
  );
394
476
  const reset = useCallback2(() => {
395
477
  latestIdRef.current += 1;
@@ -419,6 +501,7 @@ function createModelHooks(config) {
419
501
  onSettled
420
502
  } = options;
421
503
  const [data, setData] = useState(initialData);
504
+ const requestConfigRef = useLatestRef(requestConfig);
422
505
  const applyResult = useCallback2((res) => {
423
506
  setData(res.data);
424
507
  }, []);
@@ -432,7 +515,7 @@ function createModelHooks(config) {
432
515
  tasks,
433
516
  basicOptions,
434
517
  advancedOptions,
435
- requestConfig
518
+ requestConfig: requestConfigKeyInput(requestConfig)
436
519
  });
437
520
  } catch (e) {
438
521
  if (e instanceof RequestKeyError) {
@@ -442,7 +525,7 @@ function createModelHooks(config) {
442
525
  }
443
526
  const doFetchById = useCallback2(
444
527
  async (targetId, signal) => {
445
- const forwardedConfig = mergeRequestConfig(requestConfig, signal);
528
+ const forwardedConfig = mergeRequestConfig(requestConfigRef.current, signal);
446
529
  if (advanced) {
447
530
  const raw2 = await modelService.readAdvanced(
448
531
  targetId,
@@ -480,6 +563,7 @@ function createModelHooks(config) {
480
563
  const onSuccessStable = useEventCallback(onSuccess);
481
564
  const onErrorStable = useEventCallback(onError);
482
565
  const onSettledStable = useEventCallback(onSettled);
566
+ const getRequestSignal = useCallback2(() => requestConfigRef.current?.signal, [requestConfigRef]);
483
567
  const {
484
568
  isLoading,
485
569
  isFetching,
@@ -493,6 +577,7 @@ function createModelHooks(config) {
493
577
  applyResult,
494
578
  shouldFetch,
495
579
  deps: [id, enabled, advanced, requestKey],
580
+ getRequestSignal,
496
581
  onSuccess: onSuccessStable,
497
582
  onError: onErrorStable,
498
583
  onSettled: onSettledStable
@@ -529,6 +614,7 @@ function createModelHooks(config) {
529
614
  onSettled
530
615
  } = options;
531
616
  const [data, setData] = useState(initialData ?? []);
617
+ const requestConfigRef = useLatestRef(requestConfig);
532
618
  const [previousData, setPreviousData] = useState(void 0);
533
619
  const [totalCount, setTotalCount] = useState(0);
534
620
  const latestDataRef = useRef2(data);
@@ -558,7 +644,7 @@ function createModelHooks(config) {
558
644
  tasks,
559
645
  basicOptions,
560
646
  advancedOptions,
561
- requestConfig
647
+ requestConfig: requestConfigKeyInput(requestConfig)
562
648
  });
563
649
  } catch (e) {
564
650
  if (e instanceof RequestKeyError) {
@@ -571,18 +657,19 @@ function createModelHooks(config) {
571
657
  if (keepPreviousData && hasSettledRef.current) {
572
658
  setPreviousData(latestDataRef.current);
573
659
  }
574
- const forwardedConfig = mergeRequestConfig(requestConfig, signal);
660
+ const forwardedConfig = mergeRequestConfig(requestConfigRef.current, signal);
661
+ const effectiveArgs = args ?? listParams;
575
662
  if (advanced) {
576
663
  const raw2 = await modelService.listAdvanced(
577
664
  filter ?? {},
578
- { sort, select, populate, include, tasks, ...args },
665
+ { sort, select, populate, include, tasks, ...effectiveArgs },
579
666
  advancedOptions,
580
667
  forwardedConfig
581
668
  ).exec();
582
669
  assertSuccess(raw2);
583
670
  return raw2;
584
671
  }
585
- const raw = await modelService.list(args ?? listParams, basicOptions, forwardedConfig).exec();
672
+ const raw = await modelService.list(effectiveArgs, basicOptions, forwardedConfig).exec();
586
673
  assertSuccess(raw);
587
674
  return raw;
588
675
  },
@@ -603,13 +690,14 @@ function createModelHooks(config) {
603
690
  // cannot see that derivation, so the missing-deps warning is
604
691
  // silenced here intentionally.
605
692
  // eslint-disable-next-line react-hooks/exhaustive-deps
606
- [modelService, advanced, filterKey, sortKey, requestKey, keepPreviousData, latestDataRef]
693
+ [modelService, advanced, listParamsKey, filterKey, sortKey, requestKey, keepPreviousData, latestDataRef]
607
694
  );
608
695
  const doFetch = useCallback2((signal) => baseFetch(listParams, signal), [baseFetch, listParamsKey]);
609
696
  const shouldFetch = Boolean((listParams || advanced) && enabled);
610
697
  const onSuccessStable = useEventCallback(onSuccess);
611
698
  const onErrorStable = useEventCallback(onError);
612
699
  const onSettledStable = useEventCallback(onSettled);
700
+ const getRequestSignal = useCallback2(() => requestConfigRef.current?.signal, [requestConfigRef]);
613
701
  const {
614
702
  isLoading,
615
703
  isFetching,
@@ -623,6 +711,7 @@ function createModelHooks(config) {
623
711
  applyResult,
624
712
  shouldFetch,
625
713
  deps: [listParamsKey, filterKey, advanced, enabled, sortKey, requestKey],
714
+ getRequestSignal,
626
715
  onSuccess: onSuccessStable,
627
716
  onError: onErrorStable,
628
717
  onSettled: onSettledStable,
@@ -662,7 +751,6 @@ function createModelHooks(config) {
662
751
  onError,
663
752
  onSettled
664
753
  } = options;
665
- const mountRef = useMountRef();
666
754
  const execute = useCallback2(
667
755
  async (createData) => {
668
756
  let res;
@@ -686,7 +774,7 @@ function createModelHooks(config) {
686
774
  // documented pattern for `createModelHooks`. The same pattern
687
775
  // is used in `useRead.useList.useCount.useDistinct` query hooks.
688
776
  // eslint-disable-next-line react-hooks/exhaustive-deps
689
- [modelService, advanced, select, populate, tasks, basicOptions, advancedOptions, requestConfig, mountRef]
777
+ [modelService, advanced, select, populate, tasks, basicOptions, advancedOptions, requestConfig]
690
778
  );
691
779
  const {
692
780
  data,
@@ -697,23 +785,20 @@ function createModelHooks(config) {
697
785
  } = useMutation(
698
786
  execute,
699
787
  (res) => res.data,
700
- { onSuccess, onSettled }
788
+ { onSuccess, onError, onSettled }
701
789
  );
702
790
  const mutate = useCallback2(
703
791
  async (createData) => {
704
- try {
705
- return await executeMutate(createData);
706
- } catch (err) {
707
- if (mountRef.current) onError?.(err);
708
- throw err;
792
+ if (Array.isArray(createData)) {
793
+ throw new TypeError(
794
+ "useCreate.mutate is single-record-only. Array input is not supported by the hook; call modelService.create(...) directly for bulk create."
795
+ );
709
796
  }
797
+ return executeMutate(createData);
710
798
  },
711
- [executeMutate, onError, mountRef]
799
+ [executeMutate]
712
800
  );
713
- const reset = useCallback2(() => {
714
- resetMutation();
715
- }, [resetMutation]);
716
- return { data, isPending, error, mutate, reset };
801
+ return { data, isPending, error, mutate, reset: resetMutation };
717
802
  }
718
803
  function useUpdate(options = {}) {
719
804
  const {
@@ -728,7 +813,6 @@ function createModelHooks(config) {
728
813
  onError,
729
814
  onSettled
730
815
  } = options;
731
- const mountRef = useMountRef();
732
816
  const execute = useCallback2(
733
817
  async (updateId, updateData) => {
734
818
  let res;
@@ -753,7 +837,7 @@ function createModelHooks(config) {
753
837
  // documented pattern for `createModelHooks`. The same pattern
754
838
  // is used in `useRead.useList.useCount.useDistinct` query hooks.
755
839
  // eslint-disable-next-line react-hooks/exhaustive-deps
756
- [modelService, advanced, select, populate, tasks, basicOptions, advancedOptions, requestConfig, mountRef]
840
+ [modelService, advanced, select, populate, tasks, basicOptions, advancedOptions, requestConfig]
757
841
  );
758
842
  const {
759
843
  data,
@@ -764,23 +848,9 @@ function createModelHooks(config) {
764
848
  } = useMutation(
765
849
  execute,
766
850
  (res) => res.data,
767
- { onSuccess, onSettled }
768
- );
769
- const mutate = useCallback2(
770
- async (updateId, updateData) => {
771
- try {
772
- return await executeMutate(updateId, updateData);
773
- } catch (err) {
774
- if (mountRef.current) onError?.(err);
775
- throw err;
776
- }
777
- },
778
- [executeMutate, onError, mountRef]
851
+ { onSuccess, onError, onSettled }
779
852
  );
780
- const reset = useCallback2(() => {
781
- resetMutation();
782
- }, [resetMutation]);
783
- return { data, isPending, error, mutate, reset };
853
+ return { data, isPending, error, mutate: executeMutate, reset: resetMutation };
784
854
  }
785
855
  function useUpsert(options = {}) {
786
856
  const {
@@ -795,7 +865,6 @@ function createModelHooks(config) {
795
865
  onError,
796
866
  onSettled
797
867
  } = options;
798
- const mountRef = useMountRef();
799
868
  const execute = useCallback2(
800
869
  async (upsertData) => {
801
870
  let res;
@@ -819,7 +888,7 @@ function createModelHooks(config) {
819
888
  // documented pattern for `createModelHooks`. The same pattern
820
889
  // is used in `useRead.useList.useCount.useDistinct` query hooks.
821
890
  // eslint-disable-next-line react-hooks/exhaustive-deps
822
- [modelService, advanced, select, populate, tasks, basicOptions, advancedOptions, requestConfig, mountRef]
891
+ [modelService, advanced, select, populate, tasks, basicOptions, advancedOptions, requestConfig]
823
892
  );
824
893
  const {
825
894
  data,
@@ -830,27 +899,12 @@ function createModelHooks(config) {
830
899
  } = useMutation(
831
900
  execute,
832
901
  (res) => res.data,
833
- { onSuccess, onSettled }
902
+ { onSuccess, onError, onSettled }
834
903
  );
835
- const mutate = useCallback2(
836
- async (upsertData) => {
837
- try {
838
- return await executeMutate(upsertData);
839
- } catch (err) {
840
- if (mountRef.current) onError?.(err);
841
- throw err;
842
- }
843
- },
844
- [executeMutate, onError, mountRef]
845
- );
846
- const reset = useCallback2(() => {
847
- resetMutation();
848
- }, [resetMutation]);
849
- return { data, isPending, error, mutate, reset };
904
+ return { data, isPending, error, mutate: executeMutate, reset: resetMutation };
850
905
  }
851
906
  function useDelete(options = {}) {
852
907
  const { requestConfig, onSuccess, onError, onSettled } = options;
853
- const mountRef = useMountRef();
854
908
  const execute = useCallback2(
855
909
  async (deleteId) => {
856
910
  const res = await modelService.delete(deleteId, requestConfig).exec();
@@ -870,27 +924,14 @@ function createModelHooks(config) {
870
924
  } = useMutation(
871
925
  execute,
872
926
  () => null,
873
- { onSuccess, onSettled }
927
+ { onSuccess, onError, onSettled }
874
928
  );
875
- const mutate = useCallback2(
876
- async (deleteId) => {
877
- try {
878
- return await executeMutate(deleteId);
879
- } catch (err) {
880
- if (mountRef.current) onError?.(err);
881
- throw err;
882
- }
883
- },
884
- [executeMutate, onError, mountRef]
885
- );
886
- const reset = useCallback2(() => {
887
- resetMutation();
888
- }, [resetMutation]);
889
- return { isPending, error, mutate, reset };
929
+ return { isPending, error, mutate: executeMutate, reset: resetMutation };
890
930
  }
891
931
  function useCount(options = {}) {
892
932
  const { advanced, filter, enabled = true, requestConfig, onSuccess, onError, onSettled } = options;
893
933
  const [data, setData] = useState(null);
934
+ const requestConfigRef = useLatestRef(requestConfig);
894
935
  const applyResult = useCallback2((res) => {
895
936
  setData(res.data);
896
937
  }, []);
@@ -898,7 +939,7 @@ function createModelHooks(config) {
898
939
  let requestKey;
899
940
  try {
900
941
  filterKey = requestKeyFor(filter);
901
- requestKey = requestKeyFor(requestConfig);
942
+ requestKey = requestKeyFor(requestConfigKeyInput(requestConfig));
902
943
  } catch (e) {
903
944
  if (e instanceof RequestKeyError) {
904
945
  throw new Error(`useCount: ${e.message}`, { cause: e });
@@ -907,7 +948,7 @@ function createModelHooks(config) {
907
948
  }
908
949
  const doFetch = useCallback2(
909
950
  async (signal) => {
910
- const forwardedConfig = mergeRequestConfig(requestConfig, signal);
951
+ const forwardedConfig = mergeRequestConfig(requestConfigRef.current, signal);
911
952
  if (advanced) {
912
953
  const raw2 = await modelService.countAdvanced(filter ?? {}, forwardedConfig).exec();
913
954
  assertSuccess(raw2);
@@ -926,6 +967,7 @@ function createModelHooks(config) {
926
967
  const onSuccessStable = useEventCallback(onSuccess);
927
968
  const onErrorStable = useEventCallback(onError);
928
969
  const onSettledStable = useEventCallback(onSettled);
970
+ const getRequestSignal = useCallback2(() => requestConfigRef.current?.signal, [requestConfigRef]);
929
971
  const {
930
972
  isLoading,
931
973
  isFetching,
@@ -939,6 +981,7 @@ function createModelHooks(config) {
939
981
  applyResult,
940
982
  shouldFetch: enabled,
941
983
  deps: [enabled, advanced, filterKey, requestKey],
984
+ getRequestSignal,
942
985
  onSuccess: onSuccessStable,
943
986
  onError: onErrorStable,
944
987
  onSettled: onSettledStable
@@ -957,6 +1000,7 @@ function createModelHooks(config) {
957
1000
  function useDistinct(options) {
958
1001
  const { field, conditions, enabled = true, requestConfig, onSuccess, onError, onSettled } = options;
959
1002
  const [data, setData] = useState(null);
1003
+ const requestConfigRef = useLatestRef(requestConfig);
960
1004
  const applyResult = useCallback2((res) => {
961
1005
  setData(res.data);
962
1006
  }, []);
@@ -964,7 +1008,7 @@ function createModelHooks(config) {
964
1008
  let requestKey;
965
1009
  try {
966
1010
  conditionsKey = requestKeyFor(conditions);
967
- requestKey = requestKeyFor(requestConfig);
1011
+ requestKey = requestKeyFor(requestConfigKeyInput(requestConfig));
968
1012
  } catch (e) {
969
1013
  if (e instanceof RequestKeyError) {
970
1014
  throw new Error(`useDistinct: ${e.message}`, { cause: e });
@@ -973,7 +1017,7 @@ function createModelHooks(config) {
973
1017
  }
974
1018
  const doFetch = useCallback2(
975
1019
  async (signal) => {
976
- const forwardedConfig = mergeRequestConfig(requestConfig, signal);
1020
+ const forwardedConfig = mergeRequestConfig(requestConfigRef.current, signal);
977
1021
  if (conditions && Object.keys(conditions).length > 0) {
978
1022
  const raw2 = await modelService.distinctAdvanced(field, conditions, forwardedConfig).exec();
979
1023
  assertSuccess(raw2);
@@ -992,6 +1036,7 @@ function createModelHooks(config) {
992
1036
  const onSuccessStable = useEventCallback(onSuccess);
993
1037
  const onErrorStable = useEventCallback(onError);
994
1038
  const onSettledStable = useEventCallback(onSettled);
1039
+ const getRequestSignal = useCallback2(() => requestConfigRef.current?.signal, [requestConfigRef]);
995
1040
  const {
996
1041
  isLoading,
997
1042
  isFetching,
@@ -1005,6 +1050,7 @@ function createModelHooks(config) {
1005
1050
  applyResult,
1006
1051
  shouldFetch: enabled,
1007
1052
  deps: [enabled, field, conditionsKey, requestKey],
1053
+ getRequestSignal,
1008
1054
  onSuccess: onSuccessStable,
1009
1055
  onError: onErrorStable,
1010
1056
  onSettled: onSettledStable