@web-ts-toolkit/access-router-react 0.32.0 → 0.33.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 +297 -16
  2. package/index.d.mts +283 -49
  3. package/index.d.ts +283 -49
  4. package/index.js +645 -188
  5. package/index.mjs +643 -188
  6. package/package.json +9 -4
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  React hooks for `@web-ts-toolkit/access-router-client` model services.
4
4
 
5
+ `createModelHooks(modelService)` binds one `ModelService` to eight hooks covering read, list, count, distinct, create, update, upsert, and delete. Each hook instance owns its own local state — there is **no shared cache, no deduplication, no invalidation, and no retry**. Two components calling `useRead({ id: '1' })` against the same `ModelService` issue two independent requests and store two independent copies of the result. If you need cache orchestration, layer these services underneath a query library.
6
+
5
7
  ## Installation
6
8
 
7
9
  ```sh
@@ -10,44 +12,61 @@ pnpm add @web-ts-toolkit/access-router-react @web-ts-toolkit/access-router-clien
10
12
 
11
13
  Peer dependencies:
12
14
 
13
- - `react ^18 || ^19`
15
+ - `react ^18 || ^19` — verified by a React 18 lane in this package's own test suite (React 19 remains the primary lane)
14
16
  - `@web-ts-toolkit/access-router-client`
15
17
 
16
- ## Highlights
17
-
18
- - `createModelHooks(...)` factory bound to one `ModelService`
19
- - query hooks for read, list, count, and distinct
20
- - mutation hooks for create, update, upsert, and delete
21
- - local request state with `isLoading`, `isFetching`, `isPending`, and `error`
18
+ ## Factory
22
19
 
23
- ## Quick Start
24
-
25
- ```tsx
20
+ ```ts
21
+ import { createAdapter } from '@web-ts-toolkit/access-router-client';
26
22
  import { createModelHooks } from '@web-ts-toolkit/access-router-react';
27
23
 
24
+ const adapter = createAdapter({ baseURL: 'https://api.example.com' });
25
+
28
26
  const organizationService = adapter.createModelService<Organization>({
29
27
  modelName: 'Organization',
30
28
  basePath: 'organizations',
31
29
  });
32
30
 
33
- const { useList, useCreate } = createModelHooks({
31
+ const { useRead, useList, useCount, useDistinct, useCreate, useUpdate, useUpsert, useDelete } = createModelHooks({
34
32
  modelService: organizationService,
35
33
  });
34
+ ```
35
+
36
+ Call the factory once, outside any component, with a `ModelService<T>` from `adapter.createModelService<T>({ modelName, basePath })`. The returned hooks are bound to that one service for their lifetime; do not call `createModelHooks` inside a component (it would re-create the hooks on every render and discard their state).
37
+
38
+ `Organization` is your own model interface extending the client's `Document`:
36
39
 
40
+ ```ts
41
+ import type { Document } from '@web-ts-toolkit/access-router-client';
42
+
43
+ interface Organization extends Document {
44
+ _id?: string;
45
+ name: string;
46
+ status?: 'active' | 'archived';
47
+ }
48
+ ```
49
+
50
+ ## Quick Start
51
+
52
+ ```tsx
37
53
  function OrganizationList() {
38
- const { data, isLoading } = useList({
54
+ const { data, isLoading, error } = useList({
39
55
  listParams: { pageSize: 20 },
40
56
  });
41
57
 
42
- const { mutate, isPending } = useCreate();
58
+ const { mutate, isPending, error: createError, reset } = useCreate();
43
59
 
44
60
  if (isLoading) return <p>Loading...</p>;
61
+ if (error) return <p>Error: {error.message}</p>;
45
62
 
46
63
  return (
47
64
  <div>
48
65
  <button disabled={isPending} onClick={() => mutate({ name: 'Northwind Labs' })}>
49
66
  Create
50
67
  </button>
68
+ {createError && <p role="alert">Create failed: {createError.message}</p>}
69
+ <button onClick={reset}>Clear create error</button>
51
70
 
52
71
  <ul>
53
72
  {data.map((org) => (
@@ -59,11 +78,273 @@ function OrganizationList() {
59
78
  }
60
79
  ```
61
80
 
81
+ ## Query Hooks
82
+
83
+ `useRead`, `useList`, `useCount`, and `useDistinct` auto-fetch when their `enabled` flag is true (the default) and the key inputs are present (`id` for `useRead`, `listParams` or `advanced` for `useList`, `field` for `useDistinct`). They each expose `query(...)`, `refetch()`, and `reset()` alongside the result state.
84
+
85
+ ### `useRead`
86
+
87
+ ```tsx
88
+ const { data, isLoading, isFetching, error, query, refetch, reset } = useRead({
89
+ id: 'org_123',
90
+ advanced: true,
91
+ select: ['name', 'status'] as const,
92
+ onSuccess: (result) => console.log(result.data?.name),
93
+ onSettled: (result, err) => console.log({ result, err }),
94
+ });
95
+ ```
96
+
97
+ - `id` controls auto-fetching. Set `enabled: false` (or remove `id`) to disable.
98
+ - `advanced: true` switches to `readAdvanced(...)`, which forwards `select`, `populate`, `sort`, `include`, and `tasks`.
99
+ - `onSuccess`, `onError`, and `onSettled` are invocation observers and are **not** part of the effect dependency key; re-rendering a parent with a fresh inline arrow every render does not refetch (see Dependency-Key Policy below).
100
+ - `query(id, { signal })` re-runs the read imperatively; `refetch()` re-runs with the current options. Both return a promise that resolves the `ServiceError` on failure.
101
+
102
+ ### `useList`
103
+
104
+ ```tsx
105
+ const { data, previousData, totalCount, isLoading, isFetching, error, query, refetch, reset } = useList({
106
+ listParams: { pageSize: 20 },
107
+ filter: { status: 'active' },
108
+ advanced: true,
109
+ sort: { name: 1 },
110
+ select: ['name', 'status'] as const,
111
+ keepPreviousData: true,
112
+ });
113
+ ```
114
+
115
+ - `listParams` drives basic lists; `filter` drives advanced lists. Set `advanced: true` to use the advanced route.
116
+ - `sort`, `select`, `populate`, `include`, `tasks`, `basicOptions`, and `advancedOptions` map directly to the client service arguments.
117
+ - `previousData` exposes the last settled list while a replacement request is in flight, but **only** when `keepPreviousData: true` is set and the hook has produced at least one previously settled result. See the Lifecycle section for the full clear-path rules.
118
+
119
+ ### `useCount`
120
+
121
+ ```tsx
122
+ const { data, isLoading, error, query, refetch, reset } = useCount({
123
+ advanced: true,
124
+ filter: { status: 'active' },
125
+ });
126
+ ```
127
+
128
+ Use `advanced: true` when you need a filtered count.
129
+
130
+ ### `useDistinct`
131
+
132
+ ```tsx
133
+ const { data, error } = useDistinct({
134
+ field: 'status',
135
+ conditions: { organizationId: 'org_123' },
136
+ });
137
+ ```
138
+
139
+ If `conditions` is empty or omitted, the hook falls back to the basic `distinct(...)` route.
140
+
141
+ ## Mutation Hooks
142
+
143
+ `useCreate`, `useUpdate`, `useUpsert`, and `useDelete` expose `mutate(...)`, `isPending`, `error`, and `reset()`. The first three also expose `data` (the last returned projected model). Each `mutate(...)` call returns a promise that resolves the response, or rejects with a `ServiceError` on failure.
144
+
145
+ ### `useCreate`
146
+
147
+ ```tsx
148
+ const { data, isPending, error, mutate, reset } = useCreate({
149
+ advanced: true,
150
+ select: ['_id', 'name'] as const,
151
+ onSuccess: (result) => console.log('created', result.data?._id),
152
+ });
153
+
154
+ await mutate({ name: 'Northwind Labs' });
155
+ ```
156
+
157
+ ### `useUpdate`
158
+
159
+ ```tsx
160
+ const { data, isPending, error, mutate } = useUpdate();
161
+
162
+ await mutate('org_123', { status: 'active' });
163
+ ```
164
+
165
+ ### `useUpsert`
166
+
167
+ ```tsx
168
+ const { data, isPending, error, mutate } = useUpsert();
169
+
170
+ await mutate({ _id: 'org_123', name: 'Northwind Labs' });
171
+ ```
172
+
173
+ ### `useDelete`
174
+
175
+ ```tsx
176
+ const { isPending, error, mutate } = useDelete();
177
+
178
+ await mutate('org_123');
179
+ ```
180
+
181
+ Shared mutation behavior:
182
+
183
+ - `advanced: true` switches to the corresponding advanced client method when available.
184
+ - `mutate(...)` performs the request and returns an awaitable promise.
185
+ - See the Concurrent Mutations section for `isPending` overlap semantics and the Lifecycle section for `reset` semantics.
186
+ - `onSuccess`, `onError`, and `onSettled` fire per invocation regardless of overlap. Per-invocation observer isolation means a superseded mutation still receives its own `onSuccess` for its own result; it simply cannot overwrite a newer invocation's exposed `data`/`error` (see Concurrent Mutations).
187
+
188
+ ## Lifecycle
189
+
190
+ The hooks share one unified query lifecycle and one unified mutation lifecycle.
191
+
192
+ ### Loading flags
193
+
194
+ - `isFetching` is true while **any** query request is in flight.
195
+ - `isLoading` is true only while no settled data exists for this hook instance. Once the first successful response lands, subsequent `refetch()` calls set `isFetching` but not `isLoading`, so you can distinguish background fetches from the first load.
196
+ - `isPending` (mutations) is true while **any** mutation invocation is in flight — overlapping mutations keep `isPending` true until the active count reaches zero.
197
+
198
+ ### Failure handling
199
+
200
+ A resolved `success: false` response is treated as a hook-level failure. The hooks never invoke `onSuccess` for a failed response, never populate `data` with a failure payload, and surface a `ServiceError` carrying `message`, `status`, `raw`, and `headers` via `error`, `onError`, and the rejected `mutate`/`query`/`refetch` promise. A thrown `onSuccess`/`onError`/`onSettled` callback is rethrown asynchronously as an uncaught microtask and never converts a successful request into a hook-level error.
201
+
202
+ ```tsx
203
+ function FailureExample() {
204
+ const { data, error, refetch } = useRead({
205
+ id: 'org_404',
206
+ onError: (svcErr) => console.error('query failed', svcErr.status, svcErr.message),
207
+ });
208
+
209
+ const { mutate, reset } = useCreate({
210
+ onError: (svcErr) => console.error('create failed', svcErr.message),
211
+ });
212
+
213
+ async function retryCreate() {
214
+ try {
215
+ await mutate({ name: '' });
216
+ } catch (svcErr) {
217
+ console.error('create rejected', (svcErr as Error).message);
218
+ reset();
219
+ }
220
+ }
221
+
222
+ void data;
223
+ void refetch;
224
+ void retryCreate;
225
+ }
226
+ ```
227
+
228
+ ### Cancellation
229
+
230
+ A dependency change, `query()`/`refetch()` invocation, or unmount aborts the in-flight request and replaces it. Cancellation is authoritative: an aborted request never writes `error`, never fires `onError` or `onSettled`, and converges `isLoading`/`isFetching`/`isPending` to false. The hooks decide cancellation on `signal.aborted` rather than `instanceof DOMException`, so axios `CanceledError`, `Error('Canceled')` with `code: 'ERR_CANCELED'`, or any other transport-specific cancellation shape is handled uniformly.
231
+
232
+ For manual `query()` calls, pass `{ signal }` to compose a caller signal with the hook's internal controller. Aborting either source cancels the effective request.
233
+
234
+ ```tsx
235
+ const controller = new AbortController();
236
+ const result = await query('org_123', { signal: controller.signal });
237
+ controller.abort(); // cancels the in-flight manual request
238
+ ```
239
+
240
+ ### `previousData` lifecycle (`useList` only)
241
+
242
+ `previousData` is opt-in via `keepPreviousData: true`. When enabled:
243
+
244
+ - Captured at the **start** of a replacement request, **only if** the hook has previously produced at least one settled list response (the first request has nothing to preserve).
245
+ - Cleared on every terminal path: success (`applyResult`), failure (`onFailed`), abort (`onAborted`), disable / id-removed (`onDisabled`), and `reset()`.
246
+ - The first request after a `reset()` is again treated as "no prior settlement" — `hasSettled` is cleared on reset — so the next pending request does not capture stale state.
247
+
248
+ ### `reset()`
249
+
250
+ `reset()` is a synchronous state-clear, not a cancellation:
251
+
252
+ - Query `reset()` clears `data`/`error`/`isLoading`/`isFetching` (and `previousData` for `useList`).
253
+ - Mutation `reset()` clears `data`/`error` and bumps the latest-invocation token. Any already-running mutation loses its claim on the shared `data`/`error` state — when it later settles, its per-invocation `onSuccess`/`onSettled` still fire, but it cannot repopulate the cleared `data`/`error`. `isPending` remains true until the active count reaches zero; `reset` does not implicitly cancel.
254
+
255
+ If you need to cancel an in-flight query, drop `id`/`listParams` or set `enabled: false` rather than calling `reset`.
256
+
257
+ ### `refetch()` and `query()`
258
+
259
+ Both reuse the unified lifecycle: shared `isLoading`/`isFetching`/`error` writes, shared callback observers, shared abort manager. They return an awaitable promise that resolves with the response or rejects with the `ServiceError`. A trailing `.catch` suppression lets fire-and-forget callers skip `await` without leaking an unhandled rejection.
260
+
261
+ ## Concurrent Mutations
262
+
263
+ A mutation hook may be invoked more than once in flight — a caller clicking "Save" twice, a list-reordering UI firing two updates, a retry button hit before the first attempt finishes. The contract:
264
+
265
+ - **Active-count `isPending`**: `isPending` is true while **any** invocation is in flight and stays true until the active count reaches zero. The first invocation's `finally` cannot clear `isPending` while a second is still pending.
266
+ - **Latest-invocation-wins for `data` and `error`**: an older invocation that settles after a newer one started (out-of-order completion) still resolves its own promise and fires its own `onSuccess`/`onSettled` observers, but cannot overwrite the newer invocation's already-written `data` or `error`.
267
+ - **No implicit cancellation**: a newer invocation does **not** abort an older one; they settle independently. The hook truthfully reports `isPending === true` until every pending mutation completes.
268
+
269
+ ```tsx
270
+ function Save() {
271
+ const { mutate, isPending } = useUpdate({ advanced: true, select: ['name'] as const });
272
+
273
+ const saveTwice = async () => {
274
+ const [second] = await Promise.all([mutate('org_1', { name: 'A' }), mutate('org_1', { name: 'B' })]);
275
+ // `second.data` reflects whoever settled last as the latest-invocation.
276
+ return second.data;
277
+ };
278
+
279
+ return (
280
+ <button disabled={isPending} onClick={saveTwice}>
281
+ Save twice
282
+ </button>
283
+ );
284
+ }
285
+ ```
286
+
287
+ ## Projection Typing
288
+
289
+ `useRead`, `useList`, `useCreate`, `useUpdate`, and `useUpsert` accept a literal `select`:
290
+
291
+ ```tsx
292
+ const { data } = useRead({
293
+ id: 'org_123',
294
+ advanced: true,
295
+ select: ['name', 'status'] as const,
296
+ });
297
+
298
+ if (data) {
299
+ const name: string = data.name; // definitely present
300
+ const status: string | undefined = data.status; // selected, still T[key] | undefined
301
+ const id: string | undefined = data._id; // omitted-key reads as possibly undefined
302
+ }
303
+ ```
304
+
305
+ Acceptable `select` forms:
306
+
307
+ ```ts
308
+ select: ['name', 'status'] as const, // literal tuple (recommended)
309
+ select: 'name', // literal string
310
+ select: { name: 1, age: -1 }, // projection-shaped object
311
+ ```
312
+
313
+ The narrowing is applied uniformly to `data`, `onSuccess(result)`/`onSettled(result, …)` callbacks, manual `query()`/`refetch()` response payloads, and mutation `mutate()` return promises — via the public `ProjectedShape`, `ProjectedShapeArray`, `ProjectedModelResponse`, and `ProjectedListModelResponse` helpers, which reuse the client's `SelectedKeys` utility.
314
+
315
+ A literal `select` requires `advanced: true` to actually reach the server's narrowing code path; the basic `read`/`list`/`create`/etc. APIs do not forward `select`. The type still narrows when you supply a literal `select` without `advanced`, but the wire payload is unchanged — you opt into the narrowed type and accept responsibility for forwarding it down the advanced path.
316
+
317
+ ## Dependency-Key Policy
318
+
319
+ The query hooks build one structural key from every request-affecting option and use that key as the React effect dependency. Inline array/object literals at the call site are safe: two `select: ['name']` arrays written at every render produce the same key, so they do not trigger an extra refetch. `Date` compares by instant (`d:<.getTime()>`) and never collides with an ISO-string filter that happens to look like the date. `requireKeyFor` throws a documented `RequestKeyError` (re-thrown by the hook as an `Error` with `cause`) for values it cannot represent deterministically: `bigint`, `function`, `symbol` (and symbol-keyed properties), cycles, accessor properties, and built-in instances such as `RegExp`, `Map`, `Set`, `URL`, `Error`, or non-`Object.prototype` class instances. `Date` and `Object.create(null)` are supported. You can import the helper to construct or validate keys yourself:
320
+
321
+ ```ts
322
+ import { requestKeyFor, RequestKeyError } from '@web-ts-toolkit/access-router-react';
323
+
324
+ const key = requestKeyFor({ filter: { status: 'active', since: new Date('2026-01-01') } });
325
+
326
+ try {
327
+ requestKeyFor(someUserSuppliedFilter);
328
+ } catch (e) {
329
+ if (e instanceof RequestKeyError) {
330
+ // handle an unsupported value before passing it to a query hook
331
+ }
332
+ }
333
+ ```
334
+
62
335
  ## Main Exports
63
336
 
64
- - `createModelHooks(...)`
65
- - hooks returned by the factory: `useRead`, `useList`, `useCreate`, `useUpdate`, `useUpsert`, `useDelete`, `useCount`, `useDistinct`
66
- - hook option and result types such as `UseReadQueryOptions` and `UseCreateMutateResult`
337
+ - `createModelHooks(...)` — the factory.
338
+ - Hooks returned by the factory: `useRead`, `useList`, `useCreate`, `useUpdate`, `useUpsert`, `useDelete`, `useCount`, `useDistinct`.
339
+ - Hook option and result types: `UseBaseOptions`, `UseReadQueryOptions`/`UseReadQueryResult`, `UseListQueryOptions`/`UseListQueryResult`, `UseCreateMutateOptions`/`UseCreateMutateResult`, `UseUpdateMutateOptions`/`UseUpdateMutateResult`, `UseUpsertMutateOptions`/`UseUpsertMutateResult`, `UseDeleteMutateOptions`/`UseDeleteMutateResult`, `UseCountQueryOptions`/`UseCountQueryResult`, `UseDistinctQueryOptions`/`UseDistinctQueryResult`.
340
+ - `RequestConfig`, `QueryCallOptions`.
341
+ - `requestKeyFor(value)` and `RequestKeyError` — the public dependency-key helper.
342
+ - Projection-aware result helpers: `ProjectedShape`, `ProjectedShapeArray`, `ProjectedModelResponse`, `ProjectedListModelResponse`.
343
+
344
+ ## Notes
345
+
346
+ - These hooks do not implement shared caching, deduplication, invalidation, retry, or background revalidation. They are thin stateful wrappers over `ModelService` from `@web-ts-toolkit/access-router-client`. If you need cache orchestration, use these services underneath a query library.
347
+ - `requestConfig` is forwarded to the underlying client request via a fresh shallow copy on every request; the caller's `requestConfig` object, its `headers`, and other fields are not mutated. The hook's internal `requestConfig.signal` is composed with the caller-supplied `query()` `options.signal` and the hook-owned controller signal — aborting any source cancels the effective request.
67
348
 
68
349
  ## Documentation
69
350