@jsenv/navi 0.29.10 → 0.29.12

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.
@@ -0,0 +1,250 @@
1
+ /\*\*
2
+
3
+ - # Actions System - Declarative Resource Management for Frontend Applications
4
+ -
5
+ - This module provides a comprehensive system for managing asynchronous resources (API calls, data fetching)
6
+ - in a declarative, signal-based architecture. It's designed for complex frontend applications that need
7
+ - fine-grained control over loading states, caching, and resource lifecycle management.
8
+ -
9
+ - ## Core Concepts
10
+ -
11
+ - ### 🔧 **Action Templates**
12
+ - Factory functions that define how to load resources. Templates are pure and reusable.
13
+ - ```js
14
+
15
+ ```
16
+
17
+ - const getUserTemplate = createActionTemplate(async ({ userId }) => {
18
+ - const response = await fetch(`/api/users/${userId}`);
19
+ - return response.json();
20
+ - });
21
+ - ```
22
+
23
+ ```
24
+
25
+ -
26
+ - ### 🎯 **Action Instances**
27
+ - Stateful objects created from templates with specific parameters. Each unique parameter set
28
+ - gets its own cached instance (automatic memoization).
29
+ - ```js
30
+
31
+ ```
32
+
33
+ - const userAction = getUserTemplate.instantiate({ userId: 123 });
34
+ - const status = useActionStatus(userAction); // { pending, data, error, ... }
35
+ - ```
36
+
37
+ ```
38
+
39
+ -
40
+ - ### 🔄 **Action Proxies**
41
+ - Dynamic actions that react to signal changes, automatically reloading when parameters change.
42
+ - ```js
43
+
44
+ ```
45
+
46
+ - const userProxy = createActionProxy(getUserTemplate, {
47
+ - userId: userIdSignal, // Signal - reactive
48
+ - includeProfile: true // Static - not reactive
49
+ - });
50
+ - // Automatically reloads when userIdSignal changes
51
+ - ```
52
+
53
+ ```
54
+
55
+ -
56
+ - ## Loading States & Lifecycle
57
+ -
58
+ - ### 📊 **State Management**
59
+ - Each action has a well-defined state machine:
60
+ - - `IDLE` → `LOADING` → `LOADED` (success)
61
+ - - `IDLE` → `LOADING` → `FAILED` (error)
62
+ - - `IDLE` → `LOADING` → `ABORTED` (cancelled)
63
+ -
64
+ - ### ⚡ **Load Types**
65
+ - - **`.load()`** - Load with user intent (sets `loadRequested: true`)
66
+ - - **`.preload()`** - Background loading (sets `loadRequested: false`)
67
+ - - **`.reload()`** - Force reload even if already loaded
68
+ - - **`.unload()`** - Cancel loading and reset state
69
+ -
70
+ - ### 🛡️ **Preload Protection**
71
+ - Preloaded actions are protected from garbage collection for 5 minutes to ensure
72
+ - they remain available for components that may load later (e.g., via dynamic imports).
73
+ -
74
+ - ## Key Features
75
+ -
76
+ - ### 🧠 **Intelligent Memoization**
77
+ - - Actions with identical parameters share the same instance
78
+ - - Uses deep equality comparison with `compareTwoJsValues`
79
+ - - Supports `SYMBOL_IDENTITY` for fast recognition of "conceptually same" objects
80
+ - - Memory-efficient with automatic garbage collection
81
+ -
82
+ - ### 🔗 **Parameter Binding & Composition**
83
+ - ```js
84
+
85
+ ```
86
+
87
+ - const baseAction = getUserTemplate.instantiate({ userId: 123 });
88
+ - const enrichedAction = baseAction.bindParams({ includeProfile: true });
89
+ - // Result: { userId: 123, includeProfile: true }
90
+ -
91
+ - // Supports objects, primitives, and signals
92
+ - const dynamicAction = baseAction.bindParams(filtersSignal);
93
+ - ```
94
+
95
+ ```
96
+
97
+ -
98
+ - ### 🎮 **Concurrent Loading Control**
99
+ - - Prevents duplicate requests for same resource
100
+ - - Smart request deduplication and racing condition handling
101
+ - - Coordinated loading/unloading of multiple actions via `updateActions()`
102
+ -
103
+ - ### 🔧 **Side Effects & Cleanup**
104
+ - ```js
105
+
106
+ ```
107
+
108
+ - const actionTemplate = createActionTemplate(callback, {
109
+ - sideEffect: (params, loadParams) => {
110
+ - // Setup logic (analytics, subscriptions, etc.)
111
+ - return () => {
112
+ - // Cleanup logic - called on unload/abort
113
+ - };
114
+ - }
115
+ - });
116
+ - ```
117
+
118
+ ```
119
+
120
+ -
121
+ - ## Usage Patterns
122
+ -
123
+ - ### 🏗️ **Basic Resource Loading**
124
+ - ```js
125
+
126
+ ```
127
+
128
+ - const getUserAction = createActionTemplate(async ({ userId }) => {
129
+ - return await api.getUser(userId);
130
+ - });
131
+ -
132
+ - // In component
133
+ - const userAction = getUserAction.instantiate({ userId: 123 });
134
+ - const { pending, data, error } = useActionStatus(userAction);
135
+ -
136
+ - useEffect(() => {
137
+ - userAction.load();
138
+ - }, []);
139
+ - ```
140
+
141
+ ```
142
+
143
+ -
144
+ - ### 🔄 **Reactive Data Loading**
145
+ - ```js
146
+
147
+ ```
148
+
149
+ - const searchProxy = createActionProxy(searchTemplate, {
150
+ - query: searchSignal,
151
+ - filters: filtersSignal
152
+ - });
153
+ - // Automatically reloads when signals change
154
+ - ```
155
+
156
+ ```
157
+
158
+ -
159
+ - ### 📋 **Master-Detail Pattern**
160
+ - ```js
161
+
162
+ ```
163
+
164
+ - const usersAction = getUsersTemplate.instantiate();
165
+ - const selectedUser = signal(null);
166
+ -
167
+ - const userDetailsProxy = createActionProxy(getUserTemplate, {
168
+ - userId: computed(() => selectedUser.value?.id)
169
+ - });
170
+ - ```
171
+
172
+ ```
173
+
174
+ -
175
+ - ### 🏃 **Progressive Loading**
176
+ - ```js
177
+
178
+ ```
179
+
180
+ - // Preload on hover, load on click
181
+ - <button
182
+ - onMouseEnter={() => action.preload()}
183
+ - onClick={() => action.load()}
184
+ - >
185
+ - Load User
186
+ - </button>
187
+ - ```
188
+
189
+ ```
190
+
191
+ -
192
+ - ## Advanced Features
193
+ -
194
+ - ### 🎭 **Custom Data Transformation**
195
+ - ```js
196
+
197
+ ```
198
+
199
+ - const actionTemplate = createActionTemplate(fetchUser, {
200
+ - computedDataSignal: computed(() => {
201
+ - const rawData = dataSignal.value;
202
+ - return rawData ? transformUser(rawData) : null;
203
+ - })
204
+ - });
205
+ - ```
206
+
207
+ ```
208
+
209
+ -
210
+ - ### 🎨 **Async Rendering Support**
211
+ - ```js
212
+
213
+ ```
214
+
215
+ - const actionTemplate = createActionTemplate(fetchData, {
216
+ - renderLoadedAsync: async () => {
217
+ - const { UserComponent } = await import('./UserComponent.js');
218
+ - return (user) => <UserComponent user={user} />;
219
+ - }
220
+ - });
221
+ - ```
222
+
223
+ ```
224
+
225
+ -
226
+ - ### 🛠️ **Debugging & Observability**
227
+ - Built-in debug mode with detailed logging of state transitions, loading coordination,
228
+ - and memory management. Enable with `debug = true`.
229
+ -
230
+ - ## Integration Points
231
+ -
232
+ - - **Signals**: Built on @preact/signals for reactive state management
233
+ - - **Navigation**: Integrates with navigation systems for route-based loading
234
+ - - **Components**: Use `useActionStatus()` hook for component integration
235
+ - - **Memory Management**: Automatic cleanup with WeakMap-based private properties
236
+ -
237
+ - ## Performance Characteristics
238
+ -
239
+ - - **Memory Efficient**: Weak references prevent memory leaks
240
+ - - **Request Deduplication**: Identical requests are automatically merged
241
+ - - **Minimal Re-renders**: Signal-based updates only trigger when data actually changes
242
+ - - **Lazy Loading**: Actions only created when needed, with intelligent memoization
243
+ -
244
+ - This system is particularly well-suited for:
245
+ - - SPAs with complex data fetching requirements
246
+ - - Applications needing fine-grained loading state control
247
+ - - Systems requiring request coordination and deduplication
248
+ - - Progressive loading and preloading scenarios
249
+ - - Master-detail interfaces with dynamic parameter binding
250
+ \*/
@@ -0,0 +1,267 @@
1
+ # resource()
2
+
3
+ `resource()` models REST state: a reactive store of items, one action per REST
4
+ callback, and — this is the part most often missed — parent/child relations.
5
+
6
+ ```js
7
+ import { resource } from "@jsenv/navi";
8
+
9
+ const GAME = resource("game", {
10
+ GET: ({ id }) => fetchJson(`/games/${id}`),
11
+ GET_MANY: () => fetchJson(`/games`),
12
+ POST: (game) => fetchJson(`/games`, { method: "POST", body: game }),
13
+ PUT: ({ id, ...game }) =>
14
+ fetchJson(`/games/${id}`, { method: "PUT", body: game }),
15
+ PATCH: ({ id, ...props }) =>
16
+ fetchJson(`/games/${id}`, { method: "PATCH", body: props }),
17
+ DELETE: ({ id }) => fetchJson(`/games/${id}`, { method: "DELETE" }),
18
+ });
19
+ ```
20
+
21
+ Each callback returns the data to upsert into the store:
22
+
23
+ | Callback | Returns |
24
+ | ------------------------ | --------------------------------- |
25
+ | GET / POST / PUT / PATCH | the full item object, `{ id, … }` |
26
+ | DELETE | the id, or `{ id }` |
27
+ | GET_MANY / POST_MANY / … | an array of item objects |
28
+
29
+ Actions are read in components through the action system (`useAsyncData`,
30
+ `<Button action>`, …) — see [actions.md](./actions.md).
31
+
32
+ ## Relations: pick one of the four methods
33
+
34
+ A backend sub-route (`/games/:id/candidates`, `/games/:id/candidates/:userId/seen`)
35
+ is a relation. Model it with a relationship method. Do **not** encode it as an
36
+ `op`/`type` discriminator inside a single verb's callback:
37
+
38
+ ```js
39
+ // ✗ the anti-pattern this page exists to prevent
40
+ PATCH: ({ id, op, ...rest }) => {
41
+ if (op === "candidate") return fetchJson(`/games/${id}/candidates`, …);
42
+ if (op === "score") return fetchJson(`/games/${id}/score`, …);
43
+
44
+ };
45
+ ```
46
+
47
+ One verb dispatching on a string gives up everything the store does for you:
48
+ per-operation action state (loading/error per button), per-relation autorerun,
49
+ and a child collection that other components can read.
50
+
51
+ | Situation | Use |
52
+ | ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
53
+ | The child is a first-class entity with its own store, shared across parents (a user referenced by many games) | `.one()` / `.many()` |
54
+ | The child only exists inside its owner, with no identity outside it (a game's candidates, a table's columns) | `.scopedOne()` / `.scopedMany()` |
55
+ | The relation itself carries fields (`candidate_since`, `seen_at`, `slot`) | `.scopedMany()` — those fields belong to the pair; putting them in a shared child store corrupts that entity for every other reader |
56
+ | The backend answers every sub-route with the whole refreshed parent | still model the relation; absorb the response with a plural callback (see below) |
57
+ | A genuine partial update of the parent itself (cancel a game) | plain `PATCH` on the parent |
58
+
59
+ Singular vs plural is about the relation, not the verb: `.one`/`.scopedOne` for a
60
+ single sub-object, `.many`/`.scopedMany` for a collection.
61
+
62
+ ## Callback return contracts
63
+
64
+ These are not guessable — each relationship method has its own shape.
65
+
66
+ ### `.one(propertyName, childResource, { GET, PUT, DELETE })`
67
+
68
+ The callback returns the **parent** object with the child nested inside:
69
+
70
+ ```js
71
+ const USER_SESSION = USER.one("session", SESSION, {
72
+ GET: async ({ id }) => {
73
+ const session = await fetchJson(`/users/${id}/session`);
74
+ return { id, session }; // { id, session: { id: 10, token: "abc" } }
75
+ },
76
+ DELETE: async ({ id }) => {
77
+ await fetchJson(`/users/${id}/session`, { method: "DELETE" });
78
+ return id; // property becomes null
79
+ },
80
+ });
81
+ ```
82
+
83
+ `session: null` in the returned parent means "no relation". A parent GET/POST
84
+ that embeds the child inline works too — the property setter upserts it.
85
+
86
+ ### `.many(propertyName, childResource, restCallbacks)`
87
+
88
+ GET_MANY returns the **parent** object with the array nested inside; DELETE
89
+ returns the pair of ids:
90
+
91
+ ```js
92
+ const USER_FRIENDS = USER.many("friends", USER, {
93
+ GET_MANY: async ({ id }) => {
94
+ const friends = await fetchJson(`/users/${id}/friends`);
95
+ return { id, friends }; // { id, friends: [{ id: 2 }, { id: 3 }] }
96
+ },
97
+ POST: async ({ id, friendId }) =>
98
+ fetchJson(`/users/${id}/friends`, { method: "POST", body: { friendId } }),
99
+ DELETE: async ({ id, friendId }) => {
100
+ await fetchJson(`/users/${id}/friends/${friendId}`, { method: "DELETE" });
101
+ return [id, friendId]; // [parentId, childId]
102
+ },
103
+ DELETE_MANY: async ({ id, friendIds }) => {
104
+ await fetchJson(`/users/${id}/friends`, {
105
+ method: "DELETE",
106
+ body: { friendIds },
107
+ });
108
+ return [id, friendIds]; // [parentId, [childId, …]]
109
+ },
110
+ });
111
+ ```
112
+
113
+ The singular POST/PUT/PATCH callbacks return the **child** object. It is upserted
114
+ into the child store, but it does not join the parent's array on its own: the
115
+ array is the backend's, and only a GET_MANY refresh rewrites it.
116
+
117
+ ### `.scopedOne(propertyName, { idKey, GET, POST, PUT, PATCH, DELETE })`
118
+
119
+ Every callback returns `[ownerId, props | null]`:
120
+
121
+ ```js
122
+ const USER_PROFILE = USER.scopedOne("profile", {
123
+ GET: async ({ id }) => [id, await fetchJson(`/users/${id}/profile`)],
124
+ PATCH: async ({ id, ...props }) => [
125
+ id,
126
+ await fetchJson(`/users/${id}/profile`, { method: "PATCH", body: props }),
127
+ ],
128
+ DELETE: async ({ id }) => {
129
+ await fetchJson(`/users/${id}/profile`, { method: "DELETE" });
130
+ return [id, null];
131
+ },
132
+ });
133
+ ```
134
+
135
+ The property is `null` until a callback provides data. `ownerId` may be
136
+ `{ [uniqueKey]: value }` when the owner is known by an alternate key rather than
137
+ its id.
138
+
139
+ ### `.scopedMany(propertyName, { idKey, GET, GET_MANY, POST, PUT, PATCH, DELETE, … })`
140
+
141
+ Every callback returns `[ownerId, ...rest]`:
142
+
143
+ ```js
144
+ const GAME_CANDIDATES = GAME.scopedMany("candidates", {
145
+ idKey: "user_id",
146
+ GET_MANY: async ({ id }) => [id, await fetchJson(`/games/${id}/candidates`)],
147
+ POST: async ({ id, ...body }) => [
148
+ id,
149
+ await fetchJson(`/games/${id}/candidates`, { method: "POST", body }),
150
+ ],
151
+ PUT: async ({ id, oldUserId, ...props }) => [id, oldUserId, props], // id rename
152
+ DELETE: async ({ id, user_id }) => {
153
+ await fetchJson(`/games/${id}/candidates/${user_id}`, { method: "DELETE" });
154
+ return [id, user_id];
155
+ },
156
+ });
157
+ ```
158
+
159
+ | Callback | Returns |
160
+ | ------------------ | ------------------------------------------------------ |
161
+ | GET / POST / PATCH | `[ownerId, props]` |
162
+ | PUT (id rename) | `[ownerId, oldId, props]` |
163
+ | DELETE | `[ownerId, childId]` |
164
+ | any `*_MANY` | `[ownerId, itemArray]` — replaces the whole collection |
165
+ | DELETE_MANY | `[ownerId, [childId, …]]` |
166
+
167
+ `idKey` names the child's own key inside its owner (`user_id` above); it defaults
168
+ to `"id"`.
169
+
170
+ ## When the backend answers a sub-route with the whole parent
171
+
172
+ This is the common REST shape, and it is the reason `op` dispatch feels
173
+ attractive: a full-parent response absorbs into a parent `PATCH` with no
174
+ thinking. Model the relation anyway and absorb the response in the callback —
175
+ `resource()` gives a plural callback for exactly this: **any `*_MANY` callback
176
+ replaces the collection wholesale**.
177
+
178
+ ```js
179
+ const GAME_CANDIDATES = GAME.scopedMany("candidates", {
180
+ idKey: "user_id",
181
+ GET_MANY: async ({ id }) => {
182
+ const game = await fetchJson(`/games/${id}/candidates`);
183
+ return [game.id, game.candidates];
184
+ },
185
+ // the backend returns the refreshed game, not the created candidate:
186
+ // POST_MANY resyncs the collection from it in one shot
187
+ POST_MANY: async ({ id, ...body }) => {
188
+ const game = await fetchJson(`/games/${id}/candidates`, {
189
+ method: "POST",
190
+ body,
191
+ });
192
+ return [game.id, game.candidates];
193
+ },
194
+ });
195
+ ```
196
+
197
+ For `.many()`, the equivalent is its GET_MANY callback, which already takes the
198
+ parent object with the array nested inside — return the response untouched.
199
+
200
+ Deletion is the exception: `DELETE`/`DELETE_MANY` drop by id rather than replace,
201
+ so return `[ownerId, deletedId]` using the id you already have in the params,
202
+ and ignore the full parent the backend sent back.
203
+
204
+ Fields of the parent that come back in such a response (a `status`, a `score`)
205
+ are not applied by the relation callback — it only writes the relation. If the
206
+ parent's own fields change too, either let the parent GET rerun (see below) or
207
+ `store.upsert()` the parent explicitly.
208
+
209
+ ## Relations and autorerun
210
+
211
+ Relationship mutations do **not** invalidate their parent by default. The exact
212
+ rules, verified by `src/state/rest/tests/resource_graph_parent_rerun.test.js`:
213
+
214
+ - `.scopedMany` child **POST** reruns the owner's singular `GET` — but only when
215
+ the last GET response actually embedded that property. GET_MANY on the parent
216
+ is never rerun by a child POST (a list of parents is not stale because one of
217
+ them gained a child).
218
+ - `.scopedMany` child **PUT / PATCH / DELETE** rerun nothing: the callback result
219
+ already carries the updated child.
220
+ - `.scopedOne` mutations rerun nothing, ever — the result is the new value.
221
+ - `.one` / `.many` children live in an independent store; mutating them never
222
+ reruns the parent. Declare it explicitly with `dependencies` if you need it
223
+ (see [resource_dependencies.md](./resource_dependencies.md)).
224
+ - Within a relationship resource, the usual defaults still apply: its own
225
+ `GET_MANY` reruns after its own `POST`; its `GET` is reset (not rerun) by its
226
+ `DELETE`. Override per relation with `rerunOn`/`dependencies`, which every
227
+ relationship method accepts.
228
+
229
+ Splitting a sub-resource out of a parent `PATCH` therefore changes the refresh
230
+ graph: what used to be refreshed by the parent's own response is now refreshed
231
+ only by these rules. When a parent field genuinely depends on a child mutation,
232
+ say so with `dependencies` rather than relying on a rerun that will not happen.
233
+
234
+ ## Binding params instead of wrapping in an arrow
235
+
236
+ Every action exposes `bindParams()`, which returns an action instance with its
237
+ own state. Pass that instance to a component:
238
+
239
+ ```jsx
240
+ // ✓ loading, error and disabled states come for free
241
+ <Button action={GAME_CANDIDATES.POST.bindParams({ id: game.id, user_id })}>
242
+ Accept
243
+ </Button>
244
+ ```
245
+
246
+ ```jsx
247
+ // ✗ an inline arrow throws away the per-params action state
248
+ <Button
249
+ action={async () => {
250
+ await acceptCandidate(game.id, user_id);
251
+ }}
252
+ >
253
+ Accept
254
+ </Button>
255
+ ```
256
+
257
+ The arrow works, but nothing tracks it: no per-row spinner, no error surfaced on
258
+ the button that caused it, no deduplication of concurrent runs, no autorerun of
259
+ the actions this mutation should invalidate. See [actions.md](./actions.md).
260
+
261
+ ## See also
262
+
263
+ - [resource_with_params.md](./resource_with_params.md) — `withParams()` and
264
+ isolated lifecycles
265
+ - [resource_dependencies.md](./resource_dependencies.md) — cross-resource
266
+ autorerun
267
+ - [actions.md](./actions.md) — action lifecycle, `bindParams`, `useAsyncData`
@@ -0,0 +1,103 @@
1
+ # Resource Dependencies Documentation
2
+
3
+ The `withParams` method now supports cross-resource dependencies, allowing you to set up autoreload relationships between different resources.
4
+
5
+ ## Basic Usage
6
+
7
+ ```js
8
+ const role = resource("role", {
9
+ GET_MANY: () => fetchRoles(),
10
+ POST: (data) => createRole(data),
11
+ DELETE: (id) => deleteRole(id),
12
+ });
13
+
14
+ const database = resource("database", {
15
+ GET_MANY: () => fetchDatabases(),
16
+ POST: (data) => createDatabase(data),
17
+ DELETE: (id) => deleteDatabase(id),
18
+ });
19
+
20
+ const tables = resource("tables", {
21
+ GET_MANY: () => fetchTables(),
22
+ POST: (data) => createTable(data),
23
+ DELETE: (id) => deleteTable(id),
24
+ });
25
+
26
+ // Create a parameterized resource with cross-resource dependencies
27
+ const ROLE_WITH_OWNERSHIP = role.withParams(
28
+ { owners: true },
29
+ {
30
+ dependencies: [role, database, tables],
31
+ },
32
+ );
33
+ ```
34
+
35
+ ## How It Works
36
+
37
+ When you specify `dependencies`, any non-GET action (POST, PUT, PATCH, DELETE) on the dependency resources will trigger an autoreload of the GET_MANY actions in the parameterized resource.
38
+
39
+ ### Autoreload Behavior
40
+
41
+ - **Triggering Actions**: Any POST, PUT, PATCH, or DELETE on dependency resources
42
+ - **Target Actions**: GET_MANY actions in the parameterized resource (same param scope only)
43
+ - **Scope Isolation**: Only actions with the same parameter scope are affected
44
+
45
+ ### Example Scenarios
46
+
47
+ 1. **Creating a table**: `tables.POST.load(newTableData)` → triggers `ROLE_WITH_OWNERSHIP.GET_MANY` reload
48
+ 2. **Deleting a database**: `database.DELETE.load(dbId)` → triggers `ROLE_WITH_OWNERSHIP.GET_MANY` reload
49
+ 3. **Updating a role**: `role.PUT.load(roleData)` → triggers `ROLE_WITH_OWNERSHIP.GET_MANY` reload
50
+
51
+ ## Advanced Usage
52
+
53
+ ### Parameterized Dependencies
54
+
55
+ You can also use parameterized resources as dependencies:
56
+
57
+ ```js
58
+ const recentTables = tables.withParams({ recent: true });
59
+ const adminTables = tables.withParams({ owner: "admin" });
60
+
61
+ const ROLE_WITH_RECENT_OWNERSHIP = role.withParams(
62
+ { owners: true },
63
+ {
64
+ dependencies: [recentTables], // Only affected by recent tables
65
+ },
66
+ );
67
+
68
+ const ROLE_WITH_ADMIN_OWNERSHIP = role.withParams(
69
+ { owners: true },
70
+ {
71
+ dependencies: [adminTables], // Only affected by admin tables
72
+ },
73
+ );
74
+ ```
75
+
76
+ ### Custom Autoreload Settings
77
+
78
+ You can also customize the autoreload behavior:
79
+
80
+ ```js
81
+ const ROLE_WITH_OWNERSHIP = role.withParams(
82
+ { owners: true },
83
+ {
84
+ dependencies: [role, database, tables],
85
+ autoreloadGetManyAfter: ["POST", "DELETE", "PUT"], // Custom trigger verbs
86
+ autoreloadGetAfter: false, // Disable GET autoreload
87
+ },
88
+ );
89
+ ```
90
+
91
+ ## Implementation Details
92
+
93
+ - **Global Registry**: Dependencies are tracked in a global registry to enable cross-resource communication
94
+ - **Memory Management**: The system uses WeakSets to avoid memory leaks
95
+ - **Async Execution**: Autoreloads are triggered asynchronously with `setTimeout` to ensure proper sequencing
96
+ - **Parameter Isolation**: Each parameter scope maintains its own autoreload behavior
97
+
98
+ ## Benefits
99
+
100
+ 1. **Reactive Updates**: Automatically keep related data in sync across different resources
101
+ 2. **Parameter Isolation**: Avoid unwanted cross-contamination between different parameter sets
102
+ 3. **Flexible Dependencies**: Mix and match regular and parameterized resources as dependencies
103
+ 4. **Performance**: Only reload what's actually needed based on the dependency graph
@@ -0,0 +1,80 @@
1
+ # Resource `withParams()` Method
2
+
3
+ Creates a parameterized version of a resource with isolated autoreload behavior. Solves cross-contamination where actions with different parameters incorrectly trigger each other's autoreload.
4
+
5
+ ## Problem & Solution
6
+
7
+ Without `withParams()`:
8
+
9
+ ```javascript
10
+ const ROLE = resource("role", {
11
+ GET_MANY: (params) => fetchRoles(params),
12
+ DELETE: (params) => deleteRole(params),
13
+ });
14
+
15
+ // These actions interfere with each other
16
+ await ROLE.GET_MANY.bindParams({ admin: true });
17
+ await ROLE.DELETE.bindParams({ id: 123 }); // ❌ Reloads both admin and non-admin queries
18
+ ```
19
+
20
+ With `withParams()`:
21
+
22
+ ```javascript
23
+ const adminRoles = ROLE.withParams({ admin: true });
24
+ const guestRoles = ROLE.withParams({ admin: false });
25
+
26
+ await adminRoles.DELETE({ id: 123 }); // ✅ Only reloads admin queries
27
+ ```
28
+
29
+ ## API
30
+
31
+ ### `resource.withParams(params)`
32
+
33
+ **Parameters:** `params` (Object, required) - Parameters to bind to all actions
34
+
35
+ **Returns:** New resource instance with parameter-bound actions and isolated autoreload
36
+
37
+ **Throws:** Error if params is empty
38
+
39
+ ## Autoreload Hierarchy
40
+
41
+ Actions follow a parent-child hierarchy where child scopes reload their parents:
42
+
43
+ ```javascript
44
+ const ROLE = resource("role", { GET_MANY: () => fetch("/roles") });
45
+ const ROLE_ADMIN = ROLE.withParams({ type: "admin" });
46
+ const ROLE_ADMIN_MALE = ROLE_ADMIN.withParams({ gender: "male" });
47
+
48
+ // Si ROLE_ADMIN_MALE.POST() est exécuté, il recharge :
49
+ // ✅ ROLE_ADMIN_MALE.GET_MANY (même scope: { type: "admin", gender: "male" })
50
+ // ✅ ROLE_ADMIN.GET_MANY (parent scope: { type: "admin" })
51
+ // ✅ ROLE.GET_MANY (root parent: {})
52
+ // ❌ Ne recharge PAS femaleAdmin.GET_MANY ({ type: "admin", gender: "female" })
53
+
54
+ // Si ROLE_ADMIN.POST() est exécuté, il recharge :
55
+ // ✅ ROLE_ADMIN.GET_MANY (même scope: { type: "admin" })
56
+ // ✅ ROLE.GET_MANY (root parent: {})
57
+ // ❌ Ne recharge PAS ROLE_ADMIN_MALE.GET_MANY (enfant, pas parent)
58
+
59
+ // Si ROLE.POST() est exécuté, il recharge :
60
+ // ✅ ROLE.GET_MANY (même scope: {})
61
+ // ❌ Ne recharge PAS ROLE_ADMIN.GET_MANY ni ROLE_ADMIN_MALE.GET_MANY (enfants, pas parents)
62
+ ```
63
+
64
+ ## Chaining
65
+
66
+ ```javascript
67
+ const maleAdmins = USER.withParams({ role: "admin" }).withParams({
68
+ gender: "male",
69
+ });
70
+
71
+ // Equivalent to:
72
+ const maleAdmins = USER.withParams({ role: "admin", gender: "male" });
73
+ ```
74
+
75
+ ## Key Features
76
+
77
+ - **Isolation**: Different parameter sets have separate autoreload behavior
78
+ - **Hierarchy**: Child scopes reload parent scopes automatically
79
+ - **Shared Store**: All parameterized resources use the same data store
80
+ - **Efficient**: Parameter comparison is cached for performance