@jsenv/navi 0.0.1

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 (123) hide show
  1. package/index.js +51 -0
  2. package/package.json +38 -0
  3. package/src/action_private_properties.js +11 -0
  4. package/src/action_proxy_test.html +353 -0
  5. package/src/action_run_states.js +5 -0
  6. package/src/actions.js +1377 -0
  7. package/src/browser_integration/browser_integration.js +191 -0
  8. package/src/browser_integration/document_back_and_forward.js +17 -0
  9. package/src/browser_integration/document_loading_signal.js +100 -0
  10. package/src/browser_integration/document_state_signal.js +9 -0
  11. package/src/browser_integration/document_url_signal.js +9 -0
  12. package/src/browser_integration/use_is_visited.js +19 -0
  13. package/src/browser_integration/via_history.js +199 -0
  14. package/src/browser_integration/via_navigation.js +168 -0
  15. package/src/components/action_execution/form_context.js +8 -0
  16. package/src/components/action_execution/render_actionable_component.jsx +27 -0
  17. package/src/components/action_execution/use_action.js +330 -0
  18. package/src/components/action_execution/use_execute_action.js +161 -0
  19. package/src/components/action_renderer.jsx +136 -0
  20. package/src/components/collect_form_element_values.js +79 -0
  21. package/src/components/demos/0_button_demo.html +155 -0
  22. package/src/components/demos/1_checkbox_demo.html +257 -0
  23. package/src/components/demos/2_input_textual_demo.html +354 -0
  24. package/src/components/demos/3_radio_demo.html +222 -0
  25. package/src/components/demos/4_select_demo.html +104 -0
  26. package/src/components/demos/5_list_scrollable_demo.html +153 -0
  27. package/src/components/demos/action/0_button_demo.html +204 -0
  28. package/src/components/demos/action/10_shortcuts_demo.html +189 -0
  29. package/src/components/demos/action/11_nested_shortcuts_demo.html +401 -0
  30. package/src/components/demos/action/1_input_text_demo.html +461 -0
  31. package/src/components/demos/action/2_form_multiple.html +303 -0
  32. package/src/components/demos/action/3_details_demo.html +172 -0
  33. package/src/components/demos/action/4_input_checkbox_demo.html +611 -0
  34. package/src/components/demos/action/6_checkbox_list_demo.html +109 -0
  35. package/src/components/demos/action/7_radio_list_demo.html +217 -0
  36. package/src/components/demos/action/8_editable_text_demo.html +442 -0
  37. package/src/components/demos/action/9_link_demo.html +172 -0
  38. package/src/components/demos/demo.md +0 -0
  39. package/src/components/demos/route/basic/basic.html +14 -0
  40. package/src/components/demos/route/basic/basic_route_demo.jsx +224 -0
  41. package/src/components/demos/route/multi/multi.html +14 -0
  42. package/src/components/demos/route/multi/multi_route_demo.jsx +277 -0
  43. package/src/components/details/details.jsx +248 -0
  44. package/src/components/details/summary_marker.jsx +141 -0
  45. package/src/components/editable_text/editable_text.jsx +96 -0
  46. package/src/components/error_boundary_context.js +9 -0
  47. package/src/components/form.jsx +144 -0
  48. package/src/components/input/button.jsx +333 -0
  49. package/src/components/input/checkbox_list.jsx +294 -0
  50. package/src/components/input/field.jsx +61 -0
  51. package/src/components/input/field_css.js +118 -0
  52. package/src/components/input/input.jsx +15 -0
  53. package/src/components/input/input_checkbox.jsx +370 -0
  54. package/src/components/input/input_radio.jsx +299 -0
  55. package/src/components/input/input_textual.jsx +338 -0
  56. package/src/components/input/radio_list.jsx +283 -0
  57. package/src/components/input/select.jsx +273 -0
  58. package/src/components/input/use_form_event.js +20 -0
  59. package/src/components/input/use_on_change.js +12 -0
  60. package/src/components/link/link.jsx +291 -0
  61. package/src/components/loader/loader_background.jsx +324 -0
  62. package/src/components/loader/loading_spinner.jsx +68 -0
  63. package/src/components/loader/network_speed.js +83 -0
  64. package/src/components/loader/rectangle_loading.jsx +225 -0
  65. package/src/components/route.jsx +15 -0
  66. package/src/components/selection/selection.js +5 -0
  67. package/src/components/selection/selection_context.jsx +262 -0
  68. package/src/components/shortcut/os.js +9 -0
  69. package/src/components/shortcut/shortcut_context.jsx +390 -0
  70. package/src/components/use_action_events.js +37 -0
  71. package/src/components/use_auto_focus.js +43 -0
  72. package/src/components/use_debounce_true.js +31 -0
  73. package/src/components/use_focus_group.js +19 -0
  74. package/src/components/use_initial_value.js +104 -0
  75. package/src/components/use_is_visited.js +19 -0
  76. package/src/components/use_ref_array.js +38 -0
  77. package/src/components/use_signal_sync.js +50 -0
  78. package/src/components/use_state_array.js +40 -0
  79. package/src/docs/actions.md +228 -0
  80. package/src/docs/demos/resource/action_status.jsx +42 -0
  81. package/src/docs/demos/resource/demo.md +1 -0
  82. package/src/docs/demos/resource/resource_demo_0.html +84 -0
  83. package/src/docs/demos/resource/resource_demo_10_post_gc.html +364 -0
  84. package/src/docs/demos/resource/resource_demo_11_describe_many.html +362 -0
  85. package/src/docs/demos/resource/resource_demo_2.html +173 -0
  86. package/src/docs/demos/resource/resource_demo_3_filtered_users.html +415 -0
  87. package/src/docs/demos/resource/resource_demo_4_details.html +284 -0
  88. package/src/docs/demos/resource/resource_demo_5_renderer_lazy.html +115 -0
  89. package/src/docs/demos/resource/resource_demo_6_gc.html +217 -0
  90. package/src/docs/demos/resource/resource_demo_7_child_gc.html +240 -0
  91. package/src/docs/demos/resource/resource_demo_8_proxy_gc.html +319 -0
  92. package/src/docs/demos/resource/resource_demo_9_describe_one.html +472 -0
  93. package/src/docs/demos/resource/tata.jsx +3 -0
  94. package/src/docs/demos/resource/toto.jsx +3 -0
  95. package/src/docs/demos/user_nav/user_nav.html +12 -0
  96. package/src/docs/demos/user_nav/user_nav.jsx +330 -0
  97. package/src/docs/resource_dependencies.md +103 -0
  98. package/src/docs/resource_with_params.md +80 -0
  99. package/src/notes.md +13 -0
  100. package/src/route/route.js +518 -0
  101. package/src/route/route.test.html +228 -0
  102. package/src/store/array_signal_store.js +537 -0
  103. package/src/store/local_storage_signal.js +17 -0
  104. package/src/store/resource_graph.js +1303 -0
  105. package/src/store/tests/resource_graph_autoreload_demo.html +12 -0
  106. package/src/store/tests/resource_graph_autoreload_demo.jsx +964 -0
  107. package/src/store/tests/resource_graph_dependencies.test.js +95 -0
  108. package/src/store/value_in_local_storage.js +187 -0
  109. package/src/symbol_object_signal.js +1 -0
  110. package/src/use_action_data.js +10 -0
  111. package/src/use_action_status.js +47 -0
  112. package/src/utils/add_many_event_listeners.js +15 -0
  113. package/src/utils/array_add_remove.js +61 -0
  114. package/src/utils/array_signal.js +15 -0
  115. package/src/utils/compare_two_js_values.js +172 -0
  116. package/src/utils/execute_with_cleanup.js +21 -0
  117. package/src/utils/get_caller_info.js +85 -0
  118. package/src/utils/iterable_weak_set.js +62 -0
  119. package/src/utils/js_value_weak_map.js +162 -0
  120. package/src/utils/js_value_weak_map_demo.html +690 -0
  121. package/src/utils/merge_two_js_values.js +53 -0
  122. package/src/utils/stringify_for_display.js +150 -0
  123. package/src/utils/weak_effect.js +48 -0
@@ -0,0 +1,1303 @@
1
+ import { computed, signal } from "@preact/signals";
2
+ import { getActionPrivateProperties } from "../action_private_properties.js";
3
+ import { createAction, getActionDispatcher } from "../actions.js";
4
+ import { SYMBOL_OBJECT_SIGNAL } from "../symbol_object_signal.js";
5
+ import {
6
+ SYMBOL_IDENTITY,
7
+ compareTwoJsValues,
8
+ } from "../utils/compare_two_js_values.js";
9
+ import { getCallerInfo } from "../utils/get_caller_info.js";
10
+ import { createIterableWeakSet } from "../utils/iterable_weak_set.js";
11
+ import { arraySignalStore, primitiveCanBeId } from "./array_signal_store.js";
12
+
13
+ let DEBUG = false;
14
+
15
+ // Resource Lifecycle Manager
16
+ // This handles ALL resource lifecycle logic (rerun/reset) across all resources
17
+ const createResourceLifecycleManager = () => {
18
+ const registeredResources = new Map(); // Map<resourceInstance, lifecycleConfig>
19
+ const resourceDependencies = new Map(); // Map<resourceInstance, Set<dependentResources>>
20
+
21
+ const registerResource = (resourceInstance, config) => {
22
+ const {
23
+ rerunOn,
24
+ paramScope = null,
25
+ dependencies = [],
26
+ mutableIdKeys = [],
27
+ } = config;
28
+
29
+ registeredResources.set(resourceInstance, {
30
+ rerunOn,
31
+ paramScope,
32
+ mutableIdKeys,
33
+ httpActions: new Set(),
34
+ });
35
+
36
+ // Register dependencies
37
+ if (dependencies.length > 0) {
38
+ for (const dependency of dependencies) {
39
+ if (!resourceDependencies.has(dependency)) {
40
+ resourceDependencies.set(dependency, new Set());
41
+ }
42
+ resourceDependencies.get(dependency).add(resourceInstance);
43
+ }
44
+ }
45
+ };
46
+
47
+ const registerAction = (resourceInstance, httpAction) => {
48
+ const config = registeredResources.get(resourceInstance);
49
+ if (config) {
50
+ config.httpActions.add(httpAction);
51
+ }
52
+ };
53
+
54
+ const shouldRerunAfter = (rerunConfig, httpVerb) => {
55
+ if (rerunConfig === false) return false;
56
+ if (rerunConfig === "*") return true;
57
+ if (Array.isArray(rerunConfig)) {
58
+ const verbSet = new Set(rerunConfig.map((v) => v.toUpperCase()));
59
+ if (verbSet.has("*")) return true;
60
+ return verbSet.has(httpVerb.toUpperCase());
61
+ }
62
+ return false;
63
+ };
64
+
65
+ const isParamSubset = (parentParams, childParams) => {
66
+ if (!parentParams || !childParams) return false;
67
+ for (const [key, value] of Object.entries(parentParams)) {
68
+ if (
69
+ !(key in childParams) ||
70
+ !compareTwoJsValues(childParams[key], value)
71
+ ) {
72
+ return false;
73
+ }
74
+ }
75
+ return true;
76
+ };
77
+
78
+ const findEffectOnActions = (triggeringAction) => {
79
+ // Determines which actions to rerun/reset when an action completes.
80
+
81
+ const actionsToRerun = new Set();
82
+ const actionsToReset = new Set();
83
+ const reasonSet = new Set();
84
+
85
+ for (const [resourceInstance, config] of registeredResources) {
86
+ const shouldRerunGetMany = shouldRerunAfter(
87
+ config.rerunOn.GET_MANY,
88
+ triggeringAction.meta.httpVerb,
89
+ );
90
+ const shouldRerunGet = shouldRerunAfter(
91
+ config.rerunOn.GET,
92
+ triggeringAction.meta.httpVerb,
93
+ );
94
+
95
+ // Skip if no rerun or reset rules apply
96
+ const hasMutableIdAutorerun =
97
+ (triggeringAction.meta.httpVerb === "POST" ||
98
+ triggeringAction.meta.httpVerb === "PUT" ||
99
+ triggeringAction.meta.httpVerb === "PATCH") &&
100
+ config.mutableIdKeys.length > 0;
101
+
102
+ if (
103
+ !shouldRerunGetMany &&
104
+ !shouldRerunGet &&
105
+ triggeringAction.meta.httpVerb !== "DELETE" &&
106
+ !hasMutableIdAutorerun
107
+ ) {
108
+ continue;
109
+ }
110
+
111
+ // Parameter scope predicate for config-driven rules
112
+ // Same scope ID or no scope = compatible, subset check for different scopes
113
+ const paramScopePredicate = config.paramScope
114
+ ? (candidateAction) => {
115
+ if (candidateAction.meta.paramScope?.id === config.paramScope.id)
116
+ return true;
117
+ if (!candidateAction.meta.paramScope) return true;
118
+ const candidateParams = candidateAction.meta.paramScope.params;
119
+ const currentParams = config.paramScope.params;
120
+ return isParamSubset(candidateParams, currentParams);
121
+ }
122
+ : (candidateAction) => !candidateAction.meta.paramScope;
123
+
124
+ for (const httpAction of config.httpActions) {
125
+ // Find all instances of this action
126
+ const actionCandidateArray = httpAction.matchAllSelfOrDescendant(
127
+ (action) =>
128
+ !action.isPrerun && action.completed && action !== triggeringAction,
129
+ );
130
+
131
+ for (const actionCandidate of actionCandidateArray) {
132
+ const triggerVerb = triggeringAction.meta.httpVerb;
133
+ const candidateVerb = actionCandidate.meta.httpVerb;
134
+ const candidateIsPlural = actionCandidate.meta.httpMany;
135
+ if (triggerVerb === candidateVerb) {
136
+ continue;
137
+ }
138
+
139
+ const triggeringResource = getResourceForAction(triggeringAction);
140
+ const isSameResource = triggeringResource === resourceInstance;
141
+
142
+ // Config-driven same-resource effects (respects param scope)
143
+ config_effect: {
144
+ if (
145
+ !isSameResource ||
146
+ triggerVerb === "GET" ||
147
+ candidateVerb !== "GET"
148
+ ) {
149
+ break config_effect;
150
+ }
151
+ const shouldRerun = candidateIsPlural
152
+ ? shouldRerunGetMany
153
+ : shouldRerunGet;
154
+ if (!shouldRerun) {
155
+ break config_effect;
156
+ }
157
+ if (!paramScopePredicate(actionCandidate)) {
158
+ break config_effect;
159
+ }
160
+ actionsToRerun.add(actionCandidate);
161
+ reasonSet.add("same-resource autorerun");
162
+ continue;
163
+ }
164
+
165
+ // DELETE effects on same resource (ignores param scope)
166
+ delete_effect: {
167
+ if (!isSameResource || triggerVerb !== "DELETE") {
168
+ break delete_effect;
169
+ }
170
+ if (candidateIsPlural) {
171
+ if (!shouldRerunGetMany) {
172
+ break delete_effect;
173
+ }
174
+ actionsToRerun.add(actionCandidate);
175
+ reasonSet.add("same-resource DELETE rerun GET_MANY");
176
+ continue;
177
+ }
178
+ // Get the ID(s) that were deleted
179
+ const { dataSignal } = getActionPrivateProperties(triggeringAction);
180
+ const deleteIdSet = triggeringAction.meta.httpMany
181
+ ? new Set(dataSignal.peek())
182
+ : new Set([dataSignal.peek()]);
183
+
184
+ const candidateId = actionCandidate.data;
185
+ const isAffected = deleteIdSet.has(candidateId);
186
+ if (!isAffected) {
187
+ break delete_effect;
188
+ }
189
+ if (candidateVerb === "GET" && shouldRerunGet) {
190
+ actionsToRerun.add(actionCandidate);
191
+ reasonSet.add("same-resource DELETE rerun GET");
192
+ continue;
193
+ }
194
+ actionsToReset.add(actionCandidate);
195
+ reasonSet.add("same-resource DELETE reset");
196
+ continue;
197
+ }
198
+
199
+ // MutableId effects: rerun GET when matching resource created/updated
200
+ mutable_id_effect: {
201
+ if (
202
+ hasMutableIdAutorerun &&
203
+ candidateVerb === "GET" &&
204
+ !candidateIsPlural &&
205
+ isSameResource
206
+ ) {
207
+ const { computedDataSignal } =
208
+ getActionPrivateProperties(triggeringAction);
209
+ const modifiedData = computedDataSignal.peek();
210
+
211
+ if (modifiedData && typeof modifiedData === "object") {
212
+ for (const mutableIdKey of config.mutableIdKeys) {
213
+ const modifiedMutableId = modifiedData[mutableIdKey];
214
+ const candidateParams = actionCandidate.params;
215
+
216
+ if (
217
+ modifiedMutableId !== undefined &&
218
+ candidateParams &&
219
+ typeof candidateParams === "object" &&
220
+ candidateParams[mutableIdKey] === modifiedMutableId
221
+ ) {
222
+ actionsToRerun.add(actionCandidate);
223
+ reasonSet.add(
224
+ `${triggeringAction.meta.httpVerb}-mutableId autorerun`,
225
+ );
226
+ break;
227
+ }
228
+ }
229
+ }
230
+ }
231
+ }
232
+
233
+ // Cross-resource dependency effects: rerun dependent GET_MANY
234
+ dependency_effect: {
235
+ if (
236
+ triggeringResource &&
237
+ resourceDependencies
238
+ .get(triggeringResource)
239
+ ?.has(resourceInstance) &&
240
+ triggerVerb !== "GET" &&
241
+ candidateVerb === "GET" &&
242
+ candidateIsPlural
243
+ ) {
244
+ actionsToRerun.add(actionCandidate);
245
+ reasonSet.add("dependency autorerun");
246
+ continue;
247
+ }
248
+ }
249
+ }
250
+ }
251
+ }
252
+
253
+ return {
254
+ actionsToRerun,
255
+ actionsToReset,
256
+ reasons: Array.from(reasonSet),
257
+ };
258
+ };
259
+
260
+ const onActionComplete = (httpAction) => {
261
+ const { actionsToRerun, actionsToReset, reasons } =
262
+ findEffectOnActions(httpAction);
263
+
264
+ if (actionsToRerun.size > 0 || actionsToReset.size > 0) {
265
+ const reason = `${httpAction} triggered ${reasons.join(" and ")}`;
266
+ const dispatchActions = getActionDispatcher();
267
+ dispatchActions({
268
+ rerunSet: actionsToRerun,
269
+ resetSet: actionsToReset,
270
+ reason,
271
+ });
272
+ }
273
+ };
274
+
275
+ // Helper to find which resource an action belongs to
276
+ const getResourceForAction = (action) => {
277
+ return action.meta.resourceInstance;
278
+ };
279
+
280
+ return {
281
+ registerResource,
282
+ registerAction,
283
+ onActionComplete,
284
+ };
285
+ };
286
+
287
+ // Global resource lifecycle manager instance
288
+ const resourceLifecycleManager = createResourceLifecycleManager();
289
+
290
+ // Cache for parameter scope identifiers
291
+ const paramScopeWeakSet = createIterableWeakSet();
292
+ let paramScopeIdCounter = 0;
293
+ const getParamScope = (params) => {
294
+ for (const existingParamScope of paramScopeWeakSet) {
295
+ if (compareTwoJsValues(existingParamScope.params, params)) {
296
+ return existingParamScope;
297
+ }
298
+ }
299
+ const id = Symbol(`paramScope-${++paramScopeIdCounter}`);
300
+ const newParamScope = {
301
+ params,
302
+ id,
303
+ };
304
+ paramScopeWeakSet.add(newParamScope);
305
+ return newParamScope;
306
+ };
307
+
308
+ const createHttpHandlerForRootResource = (
309
+ name,
310
+ {
311
+ idKey,
312
+ store,
313
+ /*
314
+ Default autorerun behavior explanation:
315
+
316
+ GET: false (RECOMMENDED)
317
+ What happens:
318
+ - GET actions are reset by DELETE operations (not rerun)
319
+ - DELETE operation on the displayed item would display nothing in the UI (action is in IDLE state)
320
+ - PUT/PATCH operations update UI via signals, no rerun needed
321
+ - This approach minimizes unnecessary API calls
322
+
323
+ How to handle:
324
+ - Applications can provide custom UI for deleted items (e.g., "Item not found")
325
+ - Or redirect users to appropriate pages (e.g., back to list view)
326
+
327
+ Alternative (NOT RECOMMENDED):
328
+ - Use GET: ["DELETE"] to rerun and display 404 error received from backend
329
+ - Poor UX: users expect immediate feedback, not loading + error state
330
+
331
+ GET_MANY: ["POST"]
332
+ - POST: New items may or may not appear in lists (depends on filters, pagination, etc.)
333
+ Backend determines visibility better than client-side logic
334
+ - DELETE: Excluded by default because:
335
+ • UI handles deletions via store signals (selectAll filters out deleted items)
336
+ • DELETE operations rarely change list content beyond item removal
337
+ • Avoids unnecessary API calls (can be overridden if needed)
338
+ */
339
+ rerunOn = {
340
+ GET: false,
341
+ GET_MANY: [
342
+ "POST",
343
+ // "DELETE"
344
+ ],
345
+ },
346
+ paramScope,
347
+ dependencies = [],
348
+ resourceInstance,
349
+ mutableIdKeys = [],
350
+ },
351
+ ) => {
352
+ // Register this resource with the resource lifecycle manager
353
+ resourceLifecycleManager.registerResource(resourceInstance, {
354
+ rerunOn,
355
+ paramScope,
356
+ dependencies,
357
+ idKey,
358
+ mutableIdKeys,
359
+ });
360
+
361
+ const createActionAffectingOneItem = (httpVerb, { callback, ...options }) => {
362
+ const applyDataEffect =
363
+ httpVerb === "DELETE"
364
+ ? (itemIdOrItemProps) => {
365
+ const itemId = store.drop(itemIdOrItemProps);
366
+ return itemId;
367
+ }
368
+ : (data) => {
369
+ let item;
370
+ if (Array.isArray(data)) {
371
+ // the callback is returning something like [property, value, props]
372
+ // this is to support a case like:
373
+ // store.upsert("name", "currentName", { name: "newName" })
374
+ // where we want to update the name property of an existing item
375
+ item = store.upsert(...data);
376
+ } else {
377
+ item = store.upsert(data);
378
+ }
379
+ const itemId = item[idKey];
380
+ return itemId;
381
+ };
382
+
383
+ const callerInfo = getCallerInfo(null, 2);
384
+ // Provide more fallback options for better debugging
385
+ const locationInfo =
386
+ callerInfo.file && callerInfo.line && callerInfo.column
387
+ ? `${callerInfo.file}:${callerInfo.line}:${callerInfo.column}`
388
+ : callerInfo.raw || "unknown location";
389
+ const originalActionName = `${name}.${httpVerb}`;
390
+ const httpActionAffectingOneItem = createAction(callback, {
391
+ meta: { httpVerb, httpMany: false, paramScope, resourceInstance, store },
392
+ name: `${name}.${httpVerb}`,
393
+ dataEffect: (data, action) => {
394
+ const actionLabel = action.name;
395
+
396
+ if (httpVerb === "DELETE") {
397
+ if (!isProps(data) && !primitiveCanBeId(data)) {
398
+ throw new TypeError(
399
+ `${actionLabel} must return an object (that will be used to drop "${name}" resource), received ${data}.
400
+ ${originalActionName} source location: ${locationInfo}`,
401
+ );
402
+ }
403
+ return applyDataEffect(data);
404
+ }
405
+ if (!isProps(data)) {
406
+ throw new TypeError(
407
+ `${actionLabel} must return an object (that will be used to upsert "${name}" resource), received ${data}.
408
+ ${originalActionName} source location: ${locationInfo}`,
409
+ );
410
+ }
411
+ return applyDataEffect(data);
412
+ },
413
+ compute: (itemId) => store.select(itemId),
414
+ completeSideEffect: (actionCompleted) =>
415
+ resourceLifecycleManager.onActionComplete(actionCompleted),
416
+ ...options,
417
+ });
418
+ resourceLifecycleManager.registerAction(
419
+ resourceInstance,
420
+ httpActionAffectingOneItem,
421
+ );
422
+ return httpActionAffectingOneItem;
423
+ };
424
+ const GET = (callback, options) =>
425
+ createActionAffectingOneItem("GET", {
426
+ callback,
427
+ applyDataEffect: (data) => {
428
+ const item = store.upsert(data);
429
+ const itemId = item[idKey];
430
+ return itemId;
431
+ },
432
+ compute: (itemId) => store.select(itemId),
433
+ ...options,
434
+ });
435
+ const POST = (callback, options) =>
436
+ createActionAffectingOneItem("POST", {
437
+ callback,
438
+ applyDataEffect: (data) => {
439
+ const item = store.upsert(data);
440
+ const itemId = item[idKey];
441
+ return itemId;
442
+ },
443
+ compute: (itemId) => store.select(itemId),
444
+ ...options,
445
+ });
446
+ const PUT = (callback, options) =>
447
+ createActionAffectingOneItem("PUT", {
448
+ callback,
449
+ ...options,
450
+ });
451
+ const PATCH = (callback, options) =>
452
+ createActionAffectingOneItem("PATCH", {
453
+ callback,
454
+ ...options,
455
+ });
456
+ const DELETE = (callback, options) =>
457
+ createActionAffectingOneItem("DELETE", {
458
+ callback,
459
+ ...options,
460
+ });
461
+
462
+ const createActionAffectingManyItems = (
463
+ httpVerb,
464
+ { callback, ...options },
465
+ ) => {
466
+ const applyDataEffect =
467
+ httpVerb === "DELETE"
468
+ ? (idOrMutableIdArray) => {
469
+ const idArray = store.drop(idOrMutableIdArray);
470
+ return idArray;
471
+ }
472
+ : (dataArray) => {
473
+ const itemArray = store.upsert(dataArray);
474
+ const idArray = itemArray.map((item) => item[idKey]);
475
+ return idArray;
476
+ };
477
+
478
+ const httpActionAffectingManyItems = createAction(callback, {
479
+ meta: { httpVerb, httpMany: true, paramScope, resourceInstance, store },
480
+ name: `${name}.${httpVerb}_MANY`,
481
+ data: [],
482
+ dataEffect: applyDataEffect,
483
+ compute: (idArray) => store.selectAll(idArray),
484
+ completeSideEffect: (actionCompleted) =>
485
+ resourceLifecycleManager.onActionComplete(actionCompleted),
486
+ ...options,
487
+ });
488
+ resourceLifecycleManager.registerAction(
489
+ resourceInstance,
490
+ httpActionAffectingManyItems,
491
+ );
492
+ return httpActionAffectingManyItems;
493
+ };
494
+ const GET_MANY = (callback, options) =>
495
+ createActionAffectingManyItems("GET", { callback, ...options });
496
+ const POST_MANY = (callback, options) =>
497
+ createActionAffectingManyItems("POST", { callback, ...options });
498
+ const PUT_MANY = (callback, options) =>
499
+ createActionAffectingManyItems("PUT", { callback, ...options });
500
+ const PATCH_MANY = (callback, options) =>
501
+ createActionAffectingManyItems("PATCH", { callback, ...options });
502
+ const DELETE_MANY = (callback, options) =>
503
+ createActionAffectingManyItems("DELETE", { callback, ...options });
504
+
505
+ return {
506
+ GET,
507
+ POST,
508
+ PUT,
509
+ PATCH,
510
+ DELETE,
511
+ GET_MANY,
512
+ POST_MANY,
513
+ PUT_MANY,
514
+ PATCH_MANY,
515
+ DELETE_MANY,
516
+ };
517
+ };
518
+ const createHttpHandlerForRelationshipToOneResource = (
519
+ name,
520
+ {
521
+ idKey,
522
+ store,
523
+ propertyName,
524
+ childIdKey,
525
+ childStore,
526
+ resourceInstance,
527
+ resourceLifecycleManager,
528
+ },
529
+ ) => {
530
+ const createActionAffectingOneItem = (httpVerb, { callback, ...options }) => {
531
+ const applyDataEffect =
532
+ httpVerb === "DELETE"
533
+ ? (itemId) => {
534
+ const item = store.select(itemId);
535
+ const childItemId = item[propertyName][childIdKey];
536
+ store.upsert({
537
+ [idKey]: itemId,
538
+ [propertyName]: null,
539
+ });
540
+ return childItemId;
541
+ }
542
+ : // callback must return object with the following format:
543
+ // {
544
+ // [idKey]: 123,
545
+ // [propertyName]: {
546
+ // [childIdKey]: 456, ...childProps
547
+ // }
548
+ // }
549
+ // the following could happen too if there is no relationship
550
+ // {
551
+ // [idKey]: 123,
552
+ // [propertyName]: null
553
+ // }
554
+ (data) => {
555
+ const item = store.upsert(data);
556
+ const childItem = item[propertyName];
557
+ const childItemId = childItem ? childItem[childIdKey] : undefined;
558
+ return childItemId;
559
+ };
560
+
561
+ const callerInfo = getCallerInfo(null, 2);
562
+ // Provide more fallback options for better debugging
563
+ const locationInfo =
564
+ callerInfo.file && callerInfo.line && callerInfo.column
565
+ ? `${callerInfo.file}:${callerInfo.line}:${callerInfo.column}`
566
+ : callerInfo.raw || "unknown location";
567
+ const originalActionName = `${name}.${httpVerb}`;
568
+
569
+ const httpActionAffectingOneItem = createAction(callback, {
570
+ meta: { httpVerb, httpMany: false, resourceInstance, store },
571
+ name: `${name}.${httpVerb}`,
572
+ dataEffect: (data, action) => {
573
+ const actionLabel = action.name;
574
+
575
+ if (httpVerb === "DELETE") {
576
+ if (!isProps(data) && !primitiveCanBeId(data)) {
577
+ throw new TypeError(
578
+ `${actionLabel} must return an object (that will be used to drop "${name}" resource), received ${data}.
579
+ ${originalActionName} source location: ${locationInfo}`,
580
+ );
581
+ }
582
+ return applyDataEffect(data);
583
+ }
584
+ if (!isProps(data)) {
585
+ throw new TypeError(
586
+ `${actionLabel} must return an object (that will be used to upsert "${name}" resource), received ${data}.
587
+ ${originalActionName} source location: ${locationInfo}`,
588
+ );
589
+ }
590
+ return applyDataEffect(data);
591
+ },
592
+ compute: (childItemId) => childStore.select(childItemId),
593
+ completeSideEffect: (actionCompleted) =>
594
+ resourceLifecycleManager.onActionComplete(actionCompleted),
595
+ ...options,
596
+ });
597
+ resourceLifecycleManager.registerAction(
598
+ resourceInstance,
599
+ httpActionAffectingOneItem,
600
+ );
601
+ return httpActionAffectingOneItem;
602
+ };
603
+
604
+ const GET = (callback, options) =>
605
+ createActionAffectingOneItem("GET", {
606
+ callback,
607
+ ...options,
608
+ });
609
+ const PUT = (callback, options) =>
610
+ createActionAffectingOneItem("PUT", {
611
+ callback,
612
+ ...options,
613
+ });
614
+ const DELETE = (callback, options) =>
615
+ createActionAffectingOneItem("DELETE", {
616
+ callback,
617
+ ...options,
618
+ });
619
+
620
+ // il n'y a pas de many puisque on cible une seule resource
621
+ // genre table.owner -> c'est un seul owner qu'on peut
622
+ // GET -> recup les infos de l'objet
623
+ // PUT -> mettre a jour l'owner de la table
624
+ // DELETE -> supprimer l'owner de la table
625
+
626
+ return { GET, PUT, DELETE };
627
+ };
628
+ const createHttpHandlerRelationshipToManyResource = (
629
+ name,
630
+ {
631
+ idKey,
632
+ store,
633
+ propertyName,
634
+ childIdKey,
635
+ childStore,
636
+ resourceInstance,
637
+ resourceLifecycleManager,
638
+ } = {},
639
+ ) => {
640
+ // idéalement s'il y a un GET sur le store originel on voudrait ptet le reload
641
+ // parce que le store originel peut retourner cette liste ou etre impacté
642
+ // pour l'instant on ignore
643
+
644
+ // one item AND many child items
645
+ const createActionAffectingOneItem = (httpVerb, { callback, ...options }) => {
646
+ const applyDataEffect =
647
+ httpVerb === "DELETE"
648
+ ? ([itemId, childItemId]) => {
649
+ const item = store.select(itemId);
650
+ const childItemArray = item[propertyName];
651
+ const childItemArrayWithoutThisOne = [];
652
+ let found = false;
653
+ for (const childItemCandidate of childItemArray) {
654
+ const childItemCandidateId = childItemCandidate[childIdKey];
655
+ if (childItemCandidateId === childItemId) {
656
+ found = true;
657
+ } else {
658
+ childItemArrayWithoutThisOne.push(childItemCandidate);
659
+ }
660
+ }
661
+ if (found) {
662
+ store.upsert({
663
+ [idKey]: itemId,
664
+ [propertyName]: childItemArrayWithoutThisOne,
665
+ });
666
+ }
667
+ return childItemId;
668
+ }
669
+ : (childData) => {
670
+ const childItem = childStore.upsert(childData); // if the child item was used it will reload thanks to signals
671
+ const childItemId = childItem[childIdKey];
672
+ return childItemId;
673
+ };
674
+
675
+ const callerInfo = getCallerInfo(null, 2);
676
+ // Provide more fallback options for better debugging
677
+ const locationInfo =
678
+ callerInfo.file && callerInfo.line && callerInfo.column
679
+ ? `${callerInfo.file}:${callerInfo.line}:${callerInfo.column}`
680
+ : callerInfo.raw || "unknown location";
681
+ const originalActionName = `${name}.${httpVerb}`;
682
+
683
+ const httpActionAffectingOneItem = createAction(callback, {
684
+ meta: { httpVerb, httpMany: false, resourceInstance, store: childStore },
685
+ name: `${name}.${httpVerb}`,
686
+ dataEffect: (data, action) => {
687
+ const actionLabel = action.name;
688
+
689
+ if (httpVerb === "DELETE") {
690
+ // For DELETE in many relationship, we expect [itemId, childItemId] array
691
+ if (!Array.isArray(data) || data.length !== 2) {
692
+ throw new TypeError(
693
+ `${actionLabel} must return an array [itemId, childItemId] (that will be used to remove relationship), received ${data}.
694
+ ${originalActionName} source location: ${locationInfo}`,
695
+ );
696
+ }
697
+ return applyDataEffect(data);
698
+ }
699
+ if (!isProps(data)) {
700
+ throw new TypeError(
701
+ `${actionLabel} must return an object (that will be used to upsert child item), received ${data}.
702
+ ${originalActionName} source location: ${locationInfo}`,
703
+ );
704
+ }
705
+ return applyDataEffect(data);
706
+ },
707
+ compute: (childItemId) => childStore.select(childItemId),
708
+ completeSideEffect: (actionCompleted) =>
709
+ resourceLifecycleManager.onActionComplete(actionCompleted),
710
+ ...options,
711
+ });
712
+ resourceLifecycleManager.registerAction(
713
+ resourceInstance,
714
+ httpActionAffectingOneItem,
715
+ );
716
+ return httpActionAffectingOneItem;
717
+ };
718
+ const GET = (callback, options) =>
719
+ createActionAffectingOneItem("GET", {
720
+ callback,
721
+ ...options,
722
+ });
723
+ // le souci que je vois ici c'est que je n'ai pas la moindre idée d'ou
724
+ // inserer le childItem (ni meme s'il doit etre visible)
725
+ // je pense que la bonne chose a faire est de reload
726
+ // l'objet user.tables s'il en existe un
727
+ // TODO: find any GET action on "user" and reload it
728
+ const POST = (callback, options) =>
729
+ createActionAffectingOneItem("POST", {
730
+ callback,
731
+ ...options,
732
+ });
733
+ const PUT = (callback, options) =>
734
+ createActionAffectingOneItem("PUT", {
735
+ callback,
736
+ ...options,
737
+ });
738
+ const PATCH = (callback, options) =>
739
+ createActionAffectingOneItem("PATCH", {
740
+ callback,
741
+ ...options,
742
+ });
743
+ const DELETE = (callback, options) =>
744
+ createActionAffectingOneItem("DELETE", {
745
+ callback,
746
+ ...options,
747
+ });
748
+
749
+ const createActionAffectingManyItems = (
750
+ httpVerb,
751
+ { callback, ...options },
752
+ ) => {
753
+ const applyDataEffect =
754
+ httpVerb === "GET"
755
+ ? (data) => {
756
+ // callback must return object with the following format:
757
+ // {
758
+ // [idKey]: 123,
759
+ // [propertyName]: [
760
+ // { [childIdKey]: 456, ...childProps },
761
+ // { [childIdKey]: 789, ...childProps },
762
+ // ...
763
+ // ]
764
+ // }
765
+ // the array can be empty
766
+ const item = store.upsert(data);
767
+ const childItemArray = item[propertyName];
768
+ const childItemIdArray = childItemArray.map(
769
+ (childItem) => childItem[childIdKey],
770
+ );
771
+ return childItemIdArray;
772
+ }
773
+ : httpVerb === "DELETE"
774
+ ? ([itemIdOrMutableId, childItemIdOrMutableIdArray]) => {
775
+ const item = store.select(itemIdOrMutableId);
776
+ const childItemArray = item[propertyName];
777
+ const deletedChildItemIdArray = [];
778
+ const childItemArrayWithoutThoose = [];
779
+ let someFound = false;
780
+ const deletedChildItemArray = childStore.select(
781
+ childItemIdOrMutableIdArray,
782
+ );
783
+ for (const childItemCandidate of childItemArray) {
784
+ if (deletedChildItemArray.includes(childItemCandidate)) {
785
+ someFound = true;
786
+ deletedChildItemIdArray.push(childItemCandidate[childIdKey]);
787
+ } else {
788
+ childItemArrayWithoutThoose.push(childItemCandidate);
789
+ }
790
+ }
791
+ if (someFound) {
792
+ store.upsert({
793
+ [idKey]: item[idKey],
794
+ [propertyName]: childItemArrayWithoutThoose,
795
+ });
796
+ }
797
+ return deletedChildItemIdArray;
798
+ }
799
+ : (childDataArray) => {
800
+ // hum ici aussi on voudra reload "user" pour POST
801
+ // les autres les signals se charge de reload si visible
802
+ const childItemArray = childStore.upsert(childDataArray);
803
+ const childItemIdArray = childItemArray.map(
804
+ (childItem) => childItem[childIdKey],
805
+ );
806
+ return childItemIdArray;
807
+ };
808
+
809
+ const callerInfo = getCallerInfo(null, 2);
810
+ // Provide more fallback options for better debugging
811
+ const locationInfo =
812
+ callerInfo.file && callerInfo.line && callerInfo.column
813
+ ? `${callerInfo.file}:${callerInfo.line}:${callerInfo.column}`
814
+ : callerInfo.raw || "unknown location";
815
+ const originalActionName = `${name}.${httpVerb}[many]`;
816
+
817
+ const httpActionAffectingManyItem = createAction(callback, {
818
+ meta: { httpVerb, httpMany: true, resourceInstance, store: childStore },
819
+ name: `${name}.${httpVerb}[many]`,
820
+ data: [],
821
+ dataEffect: (data, action) => {
822
+ const actionLabel = action.name;
823
+
824
+ if (httpVerb === "GET") {
825
+ if (!isProps(data)) {
826
+ throw new TypeError(
827
+ `${actionLabel} must return an object (that will be used to upsert "${name}" resource with many relationships), received ${data}.
828
+ ${originalActionName} source location: ${locationInfo}`,
829
+ );
830
+ }
831
+ return applyDataEffect(data);
832
+ }
833
+ if (httpVerb === "DELETE") {
834
+ // For DELETE_MANY in many relationship, we expect [itemId, childItemIdArray] array
835
+ if (
836
+ !Array.isArray(data) ||
837
+ data.length !== 2 ||
838
+ !Array.isArray(data[1])
839
+ ) {
840
+ throw new TypeError(
841
+ `${actionLabel} must return an array [itemId, childItemIdArray] (that will be used to remove relationships), received ${data}.
842
+ ${originalActionName} source location: ${locationInfo}`,
843
+ );
844
+ }
845
+ return applyDataEffect(data);
846
+ }
847
+ // For POST, PUT, PATCH - expect array of objects
848
+ if (!Array.isArray(data)) {
849
+ throw new TypeError(
850
+ `${actionLabel} must return an array of objects (that will be used to upsert child items), received ${data}.
851
+ ${originalActionName} source location: ${locationInfo}`,
852
+ );
853
+ }
854
+ return applyDataEffect(data);
855
+ },
856
+ compute: (childItemIdArray) => childStore.selectAll(childItemIdArray),
857
+ completeSideEffect: (actionCompleted) =>
858
+ resourceLifecycleManager.onActionComplete(actionCompleted),
859
+ ...options,
860
+ });
861
+ resourceLifecycleManager.registerAction(
862
+ resourceInstance,
863
+ httpActionAffectingManyItem,
864
+ );
865
+ return httpActionAffectingManyItem;
866
+ };
867
+
868
+ const GET_MANY = (callback, options) =>
869
+ createActionAffectingManyItems("GET", { callback, ...options });
870
+ const POST_MANY = (callback, options) =>
871
+ createActionAffectingManyItems("POST", { callback, ...options });
872
+ const PUT_MANY = (callback, options) =>
873
+ createActionAffectingManyItems("PUT", { callback, ...options });
874
+ const PATCH_MANY = (callback, options) =>
875
+ createActionAffectingManyItems("PATCH", { callback, ...options });
876
+ const DELETE_MANY = (callback, options) =>
877
+ createActionAffectingManyItems("DELETE", { callback, ...options });
878
+
879
+ return {
880
+ GET,
881
+ POST,
882
+ PUT,
883
+ PATCH,
884
+ DELETE,
885
+ GET_MANY,
886
+ POST_MANY,
887
+ PUT_MANY,
888
+ PATCH_MANY,
889
+ DELETE_MANY,
890
+ };
891
+ };
892
+
893
+ export const resource = (
894
+ name,
895
+ { idKey, mutableIdKeys = [], rerunOn, httpHandler, ...rest } = {},
896
+ ) => {
897
+ if (idKey === undefined) {
898
+ idKey = mutableIdKeys.length === 0 ? "id" : mutableIdKeys[0];
899
+ }
900
+ const resourceInstance = {
901
+ isResource: true,
902
+ name,
903
+ idKey,
904
+ httpActions: {},
905
+ addItemSetup: undefined,
906
+ httpHandler,
907
+ };
908
+ if (!httpHandler) {
909
+ const setupCallbackSet = new Set();
910
+ const addItemSetup = (callback) => {
911
+ setupCallbackSet.add(callback);
912
+ };
913
+ resourceInstance.addItemSetup = addItemSetup;
914
+
915
+ const itemPrototype = {
916
+ [Symbol.toStringTag]: name,
917
+ toString() {
918
+ let string = `${name}`;
919
+ if (mutableIdKeys.length) {
920
+ for (const mutableIdKey of mutableIdKeys) {
921
+ const mutableId = this[mutableIdKey];
922
+ if (mutableId !== undefined) {
923
+ string += `[${mutableIdKey}=${mutableId}]`;
924
+ return string;
925
+ }
926
+ }
927
+ }
928
+ const id = this[idKey];
929
+ if (id) {
930
+ string += `[${idKey}=${id}]`;
931
+ }
932
+ return string;
933
+ },
934
+ };
935
+
936
+ const store = arraySignalStore([], idKey, {
937
+ mutableIdKeys,
938
+ name: `${name} store`,
939
+ createItem: (props) => {
940
+ const item = Object.create(itemPrototype);
941
+ Object.assign(item, props);
942
+ Object.defineProperty(item, SYMBOL_IDENTITY, {
943
+ value: item[idKey],
944
+ writable: false,
945
+ enumerable: false,
946
+ configurable: false,
947
+ });
948
+ for (const setupCallback of setupCallbackSet) {
949
+ setupCallback(item);
950
+ }
951
+ return item;
952
+ },
953
+ });
954
+ const useArray = () => {
955
+ return store.arraySignal.value;
956
+ };
957
+ const useById = (id) => {
958
+ return store.select(idKey, id);
959
+ };
960
+
961
+ Object.assign(resourceInstance, {
962
+ useArray,
963
+ useById,
964
+ store,
965
+ });
966
+
967
+ httpHandler = createHttpHandlerForRootResource(name, {
968
+ idKey,
969
+ store,
970
+ rerunOn,
971
+ resourceInstance,
972
+ mutableIdKeys,
973
+ });
974
+ }
975
+ resourceInstance.httpHandler = httpHandler;
976
+
977
+ // Store the action callback definitions for withParams to use later
978
+ resourceInstance.httpActions = rest;
979
+
980
+ // Create HTTP actions
981
+ for (const key of Object.keys(rest)) {
982
+ const method = httpHandler[key];
983
+ if (!method) {
984
+ continue;
985
+ }
986
+ const action = method(rest[key]);
987
+ resourceInstance[key] = action;
988
+ }
989
+
990
+ resourceInstance.one = (propertyName, childResource, options) => {
991
+ const childIdKey = childResource.idKey;
992
+ const childName = `${name}.${propertyName}`;
993
+ resourceInstance.addItemSetup((item) => {
994
+ const childItemIdSignal = signal();
995
+ const updateChildItemId = (value) => {
996
+ const currentChildItemId = childItemIdSignal.peek();
997
+ if (isProps(value)) {
998
+ const childItem = childResource.store.upsert(value);
999
+ const childItemId = childItem[childIdKey];
1000
+ if (currentChildItemId === childItemId) {
1001
+ return false;
1002
+ }
1003
+ childItemIdSignal.value = childItemId;
1004
+ return true;
1005
+ }
1006
+ if (primitiveCanBeId(value)) {
1007
+ const childItemProps = { [childIdKey]: value };
1008
+ const childItem = childResource.store.upsert(childItemProps);
1009
+ const childItemId = childItem[childIdKey];
1010
+ if (currentChildItemId === childItemId) {
1011
+ return false;
1012
+ }
1013
+ childItemIdSignal.value = childItemId;
1014
+ return true;
1015
+ }
1016
+ if (currentChildItemId === undefined) {
1017
+ return false;
1018
+ }
1019
+ childItemIdSignal.value = undefined;
1020
+ return true;
1021
+ };
1022
+ updateChildItemId(item[propertyName]);
1023
+
1024
+ const childItemSignal = computed(() => {
1025
+ const childItemId = childItemIdSignal.value;
1026
+ const childItem = childResource.store.select(childItemId);
1027
+ return childItem;
1028
+ });
1029
+ const childItemFacadeSignal = computed(() => {
1030
+ const childItem = childItemSignal.value;
1031
+ if (childItem) {
1032
+ const childItemCopy = Object.create(
1033
+ Object.getPrototypeOf(childItem),
1034
+ Object.getOwnPropertyDescriptors(childItem),
1035
+ );
1036
+ Object.defineProperty(childItemCopy, SYMBOL_OBJECT_SIGNAL, {
1037
+ value: childItemSignal,
1038
+ writable: false,
1039
+ enumerable: false,
1040
+ configurable: false,
1041
+ });
1042
+ return childItemCopy;
1043
+ }
1044
+ const nullItem = {
1045
+ [SYMBOL_OBJECT_SIGNAL]: childItemSignal,
1046
+ valueOf: () => null,
1047
+ };
1048
+ return nullItem;
1049
+ });
1050
+
1051
+ if (DEBUG) {
1052
+ console.debug(
1053
+ `setup ${item}.${propertyName} is one "${childResource.name}" (current value: ${childItemSignal.peek()})`,
1054
+ );
1055
+ }
1056
+
1057
+ Object.defineProperty(item, propertyName, {
1058
+ get: () => {
1059
+ const childItemFacade = childItemFacadeSignal.value;
1060
+ return childItemFacade;
1061
+ },
1062
+ set: (value) => {
1063
+ if (!updateChildItemId(value)) {
1064
+ return;
1065
+ }
1066
+ if (DEBUG) {
1067
+ console.debug(
1068
+ `${item}.${propertyName} updated to ${childItemSignal.peek()}`,
1069
+ );
1070
+ }
1071
+ },
1072
+ });
1073
+ });
1074
+ const httpHandlerForRelationshipToOneChild =
1075
+ createHttpHandlerForRelationshipToOneResource(childName, {
1076
+ idKey,
1077
+ store: resourceInstance.store,
1078
+ propertyName,
1079
+ childIdKey,
1080
+ childStore: childResource.store,
1081
+ resourceInstance,
1082
+ resourceLifecycleManager,
1083
+ });
1084
+ return resource(childName, {
1085
+ idKey: childIdKey,
1086
+ httpHandler: httpHandlerForRelationshipToOneChild,
1087
+ ...options,
1088
+ });
1089
+ };
1090
+ resourceInstance.many = (propertyName, childResource, options) => {
1091
+ const childIdKey = childResource.idKey;
1092
+ const childName = `${name}.${propertyName}`;
1093
+ resourceInstance.addItemSetup((item) => {
1094
+ const childItemIdArraySignal = signal([]);
1095
+ const updateChildItemIdArray = (valueArray) => {
1096
+ const currentIdArray = childItemIdArraySignal.peek();
1097
+
1098
+ if (!Array.isArray(valueArray)) {
1099
+ if (currentIdArray.length === 0) {
1100
+ return;
1101
+ }
1102
+ childItemIdArraySignal.value = [];
1103
+ return;
1104
+ }
1105
+
1106
+ let i = 0;
1107
+ const idArray = [];
1108
+ let modified = false;
1109
+ while (i < valueArray.length) {
1110
+ const value = valueArray[i];
1111
+ const currentIdAtIndex = currentIdArray[idArray.length];
1112
+ i++;
1113
+ if (isProps(value)) {
1114
+ const childItem = childResource.store.upsert(value);
1115
+ const childItemId = childItem[childIdKey];
1116
+ if (currentIdAtIndex !== childItemId) {
1117
+ modified = true;
1118
+ }
1119
+ idArray.push(childItemId);
1120
+ continue;
1121
+ }
1122
+ if (primitiveCanBeId(value)) {
1123
+ const childItemProps = { [childIdKey]: value };
1124
+ const childItem = childResource.store.upsert(childItemProps);
1125
+ const childItemId = childItem[childIdKey];
1126
+ if (currentIdAtIndex !== childItemId) {
1127
+ modified = true;
1128
+ }
1129
+ idArray.push(childItemId);
1130
+ continue;
1131
+ }
1132
+ }
1133
+ if (modified || currentIdArray.length !== idArray.length) {
1134
+ childItemIdArraySignal.value = idArray;
1135
+ }
1136
+ };
1137
+ updateChildItemIdArray(item[propertyName]);
1138
+
1139
+ const childItemArraySignal = computed(() => {
1140
+ const childItemIdArray = childItemIdArraySignal.value;
1141
+ const childItemArray = childResource.store.selectAll(childItemIdArray);
1142
+ Object.defineProperty(childItemArray, SYMBOL_OBJECT_SIGNAL, {
1143
+ value: childItemArraySignal,
1144
+ writable: false,
1145
+ enumerable: false,
1146
+ configurable: false,
1147
+ });
1148
+ return childItemArray;
1149
+ });
1150
+
1151
+ if (DEBUG) {
1152
+ const childItemArray = childItemArraySignal.peek();
1153
+ console.debug(
1154
+ `setup ${item}.${propertyName} is many "${childResource.name}" (current value: ${childItemArray.length ? childItemArray.join(",") : "[]"})`,
1155
+ );
1156
+ }
1157
+
1158
+ Object.defineProperty(item, propertyName, {
1159
+ get: () => {
1160
+ const childItemArray = childItemArraySignal.value;
1161
+ if (DEBUG) {
1162
+ console.debug(
1163
+ `return ${childItemArray.length ? childItemArray.join(",") : "[]"} for ${item}.${propertyName}`,
1164
+ );
1165
+ }
1166
+ return childItemArray;
1167
+ },
1168
+ set: (value) => {
1169
+ updateChildItemIdArray(value);
1170
+ if (DEBUG) {
1171
+ console.debug(
1172
+ `${item}.${propertyName} updated to ${childItemIdArraySignal.peek()}`,
1173
+ );
1174
+ }
1175
+ },
1176
+ });
1177
+ });
1178
+ const httpHandleForChildManyResource =
1179
+ createHttpHandlerRelationshipToManyResource(childName, {
1180
+ idKey,
1181
+ store: resourceInstance.store,
1182
+ propertyName,
1183
+ childIdKey,
1184
+ childStore: childResource.store,
1185
+ resourceInstance,
1186
+ resourceLifecycleManager,
1187
+ });
1188
+ return resource(childName, {
1189
+ idKey: childIdKey,
1190
+ httpHandler: httpHandleForChildManyResource,
1191
+ ...options,
1192
+ });
1193
+ };
1194
+
1195
+ /**
1196
+ * Creates a parameterized version of the resource with isolated resource lifecycle behavior.
1197
+ *
1198
+ * Actions from parameterized resources only trigger rerun/reset for other actions with
1199
+ * identical parameters, preventing cross-contamination between different parameter sets.
1200
+ *
1201
+ * @param {Object} params - Parameters to bind to all actions of this resource (required)
1202
+ * @param {Object} options - Additional options for the parameterized resource
1203
+ * @param {Array} options.dependencies - Array of resources that should trigger autorerun when modified
1204
+ * @param {Object} options.rerunOn - Configuration for when to rerun GET/GET_MANY actions
1205
+ * @param {false|Array|string} options.rerunOn.GET - HTTP verbs that trigger GET rerun (false = reset on DELETE)
1206
+ * @param {false|Array|string} options.rerunOn.GET_MANY - HTTP verbs that trigger GET_MANY rerun (false = reset on DELETE)
1207
+ * @returns {Object} A new resource instance with parameter-bound actions and isolated lifecycle
1208
+ * @see {@link ./docs/resource_with_params.md} for detailed documentation and examples
1209
+ *
1210
+ * @example
1211
+ * const ROLE = resource("role", { GET: (params) => fetchRole(params) });
1212
+ * const adminRoles = ROLE.withParams({ canlogin: true });
1213
+ * const guestRoles = ROLE.withParams({ canlogin: false });
1214
+ * // adminRoles and guestRoles have isolated autorerun behavior
1215
+ *
1216
+ * @example
1217
+ * // Cross-resource dependencies
1218
+ * const role = resource("role");
1219
+ * const database = resource("database");
1220
+ * const tables = resource("tables");
1221
+ * const ROLE_WITH_OWNERSHIP = role.withParams({ owners: true }, {
1222
+ * dependencies: [role, database, tables],
1223
+ * });
1224
+ * // ROLE_WITH_OWNERSHIP.GET_MANY will autorerun when any table/database/role is POST/DELETE
1225
+ */
1226
+ const withParams = (params, options = {}) => {
1227
+ // Require parameters
1228
+ if (!params || Object.keys(params).length === 0) {
1229
+ throw new Error(`resource(${name}).withParams() requires parameters`);
1230
+ }
1231
+
1232
+ const { dependencies = [], rerunOn: customRerunOn } = options;
1233
+
1234
+ // Generate unique param scope for these parameters
1235
+ const paramScopeObject = getParamScope(params);
1236
+
1237
+ // Use custom rerunOn settings if provided, otherwise use resource defaults
1238
+ const finalRerunOn = customRerunOn || rerunOn;
1239
+
1240
+ // Create a new httpHandler with the param scope for isolated autorerun
1241
+ const parameterizedHttpHandler = createHttpHandlerForRootResource(name, {
1242
+ idKey,
1243
+ store: resourceInstance.store,
1244
+ rerunOn: finalRerunOn,
1245
+ paramScope: paramScopeObject,
1246
+ dependencies,
1247
+ resourceInstance,
1248
+ mutableIdKeys,
1249
+ });
1250
+
1251
+ // Create parameterized resource
1252
+ const parameterizedResource = {
1253
+ isResource: true,
1254
+ name,
1255
+ idKey,
1256
+ useArray: resourceInstance.useArray,
1257
+ useById: resourceInstance.useById,
1258
+ store: resourceInstance.store,
1259
+ addItemSetup: resourceInstance.addItemSetup,
1260
+ httpHandler: parameterizedHttpHandler,
1261
+ one: resourceInstance.one,
1262
+ many: resourceInstance.many,
1263
+ dependencies, // Store dependencies for debugging/inspection
1264
+ httpActions: resourceInstance.httpActions,
1265
+ };
1266
+
1267
+ // Create HTTP actions from the parameterized handler and bind parameters
1268
+ for (const key of Object.keys(resourceInstance.httpActions)) {
1269
+ const method = parameterizedHttpHandler[key];
1270
+ if (method) {
1271
+ const action = method(resourceInstance.httpActions[key]);
1272
+ // Bind the parameters to get a parameterized action instance
1273
+ parameterizedResource[key] = action.bindParams(params);
1274
+ }
1275
+ }
1276
+
1277
+ // Add withParams method to the parameterized resource for chaining
1278
+ parameterizedResource.withParams = (newParams, newOptions = {}) => {
1279
+ if (!newParams || Object.keys(newParams).length === 0) {
1280
+ throw new Error(`resource(${name}).withParams() requires parameters`);
1281
+ }
1282
+ // Merge current params with new ones for chaining
1283
+ const mergedParams = { ...params, ...newParams };
1284
+ // Merge options, with new options taking precedence
1285
+ const mergedOptions = {
1286
+ dependencies,
1287
+ rerunOn: finalRerunOn,
1288
+ ...newOptions,
1289
+ };
1290
+ return withParams(mergedParams, mergedOptions);
1291
+ };
1292
+
1293
+ return parameterizedResource;
1294
+ };
1295
+
1296
+ resourceInstance.withParams = withParams;
1297
+
1298
+ return resourceInstance;
1299
+ };
1300
+
1301
+ const isProps = (value) => {
1302
+ return value !== null && typeof value === "object";
1303
+ };