mutts 1.0.8 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/README.md +77 -35
  2. package/dist/browser.cjs +2144 -5355
  3. package/dist/browser.cjs.map +1 -1
  4. package/dist/browser.d.ts +2 -1655
  5. package/dist/browser.dev.cjs +110 -0
  6. package/dist/browser.dev.cjs.map +1 -0
  7. package/dist/browser.dev.d.ts +2 -0
  8. package/dist/browser.dev.esm.js +5 -0
  9. package/dist/browser.dev.esm.js.map +1 -0
  10. package/dist/browser.esm.js +20 -107
  11. package/dist/browser.esm.js.map +1 -1
  12. package/dist/chunks/{async-browser-CA0jPWIi.cjs → async-browser-BU_IfxYD.cjs} +19 -107
  13. package/dist/chunks/async-browser-BU_IfxYD.cjs.map +1 -0
  14. package/dist/chunks/{async-core-UqHzvJ-S.cjs → async-core-CRLKP3l-.cjs} +8 -4
  15. package/dist/chunks/async-core-CRLKP3l-.cjs.map +1 -0
  16. package/dist/chunks/{async-node-BYHuGTni.cjs → async-node-3PrbVAbB.cjs} +7 -12
  17. package/dist/chunks/async-node-3PrbVAbB.cjs.map +1 -0
  18. package/dist/chunks/index-CaaQQlPJ.esm.js +3174 -0
  19. package/dist/chunks/index-CaaQQlPJ.esm.js.map +1 -0
  20. package/dist/chunks/node-nKJBk8iJ.esm.js +96 -0
  21. package/dist/chunks/node-nKJBk8iJ.esm.js.map +1 -0
  22. package/dist/chunks/proxy-Dtg-bJ3T.cjs +3763 -0
  23. package/dist/chunks/proxy-Dtg-bJ3T.cjs.map +1 -0
  24. package/dist/chunks/proxy-r7lARftl.esm.js +3701 -0
  25. package/dist/chunks/proxy-r7lARftl.esm.js.map +1 -0
  26. package/dist/debug.cjs +980 -0
  27. package/dist/debug.cjs.map +1 -0
  28. package/dist/debug.d.ts +208 -0
  29. package/dist/debug.esm.js +950 -0
  30. package/dist/debug.esm.js.map +1 -0
  31. package/dist/devtools/manifest.json +1 -1
  32. package/dist/devtools/panel.html +1 -1
  33. package/dist/devtools/panel.js +107 -94
  34. package/dist/devtools/panel.js.map +1 -1
  35. package/dist/index.d.ts +1447 -13
  36. package/dist/mutts.umd.js +7167 -1
  37. package/dist/mutts.umd.js.map +1 -1
  38. package/dist/mutts.umd.min.js +1 -1
  39. package/dist/mutts.umd.min.js.map +1 -1
  40. package/dist/node.cjs +70 -66
  41. package/dist/node.cjs.map +1 -1
  42. package/dist/node.d.ts +2 -1
  43. package/dist/node.dev.cjs +110 -0
  44. package/dist/node.dev.cjs.map +1 -0
  45. package/dist/node.dev.d.ts +2 -0
  46. package/dist/node.dev.esm.js +6 -0
  47. package/dist/node.dev.esm.js.map +1 -0
  48. package/dist/node.esm.js +4 -103
  49. package/dist/node.esm.js.map +1 -1
  50. package/dist/{reactive/types.d.ts → types-W5vD6m2n.d.ts} +186 -93
  51. package/docs/ai/api-reference.md +12 -19
  52. package/docs/ai/manual.md +521 -17
  53. package/docs/events.md +57 -2
  54. package/docs/flavored.md +210 -0
  55. package/docs/reactive/advanced.md +314 -5
  56. package/docs/reactive/attend.md +142 -0
  57. package/docs/reactive/collections.md +76 -39
  58. package/docs/reactive/core.md +100 -14
  59. package/docs/reactive/debugging.md +123 -18
  60. package/docs/reactive/error-handling.md +121 -0
  61. package/docs/reactive/resource.md +125 -0
  62. package/docs/reactive/scan.md +247 -1
  63. package/docs/reactive.md +4 -1
  64. package/docs/std-decorators.md +102 -51
  65. package/docs/utils.md +70 -0
  66. package/docs/zone.md +3 -7
  67. package/package.json +64 -30
  68. package/dist/async/browser.d.ts +0 -2
  69. package/dist/async/browser.d.ts.map +0 -1
  70. package/dist/async/index.d.ts +0 -18
  71. package/dist/async/index.d.ts.map +0 -1
  72. package/dist/async/node.d.ts +0 -2
  73. package/dist/async/node.d.ts.map +0 -1
  74. package/dist/chunks/async-browser-CA0jPWIi.cjs.map +0 -1
  75. package/dist/chunks/async-core-UqHzvJ-S.cjs.map +0 -1
  76. package/dist/chunks/async-node-BYHuGTni.cjs.map +0 -1
  77. package/dist/chunks/index-DhaOVusv.esm.js +0 -6411
  78. package/dist/chunks/index-DhaOVusv.esm.js.map +0 -1
  79. package/dist/decorator.d.ts +0 -106
  80. package/dist/decorator.d.ts.map +0 -1
  81. package/dist/destroyable.d.ts +0 -87
  82. package/dist/destroyable.d.ts.map +0 -1
  83. package/dist/entry-browser.d.ts +0 -3
  84. package/dist/entry-browser.d.ts.map +0 -1
  85. package/dist/entry-node.d.ts +0 -3
  86. package/dist/entry-node.d.ts.map +0 -1
  87. package/dist/eventful.d.ts +0 -18
  88. package/dist/eventful.d.ts.map +0 -1
  89. package/dist/index.d.ts.map +0 -1
  90. package/dist/indexable.d.ts +0 -243
  91. package/dist/indexable.d.ts.map +0 -1
  92. package/dist/introspection.d.ts +0 -27
  93. package/dist/introspection.d.ts.map +0 -1
  94. package/dist/iterableWeak.d.ts +0 -53
  95. package/dist/iterableWeak.d.ts.map +0 -1
  96. package/dist/mixins.d.ts +0 -25
  97. package/dist/mixins.d.ts.map +0 -1
  98. package/dist/promiseChain.d.ts +0 -20
  99. package/dist/promiseChain.d.ts.map +0 -1
  100. package/dist/reactive/array.d.ts +0 -49
  101. package/dist/reactive/array.d.ts.map +0 -1
  102. package/dist/reactive/buffer.d.ts +0 -44
  103. package/dist/reactive/buffer.d.ts.map +0 -1
  104. package/dist/reactive/change.d.ts +0 -29
  105. package/dist/reactive/change.d.ts.map +0 -1
  106. package/dist/reactive/debug.d.ts +0 -111
  107. package/dist/reactive/debug.d.ts.map +0 -1
  108. package/dist/reactive/deep-touch.d.ts +0 -28
  109. package/dist/reactive/deep-touch.d.ts.map +0 -1
  110. package/dist/reactive/deep-watch-state.d.ts +0 -25
  111. package/dist/reactive/deep-watch-state.d.ts.map +0 -1
  112. package/dist/reactive/deep-watch.d.ts +0 -19
  113. package/dist/reactive/deep-watch.d.ts.map +0 -1
  114. package/dist/reactive/effect-context.d.ts +0 -7
  115. package/dist/reactive/effect-context.d.ts.map +0 -1
  116. package/dist/reactive/effects.d.ts +0 -151
  117. package/dist/reactive/effects.d.ts.map +0 -1
  118. package/dist/reactive/index.d.ts +0 -20
  119. package/dist/reactive/index.d.ts.map +0 -1
  120. package/dist/reactive/interface.d.ts +0 -64
  121. package/dist/reactive/interface.d.ts.map +0 -1
  122. package/dist/reactive/map.d.ts +0 -30
  123. package/dist/reactive/map.d.ts.map +0 -1
  124. package/dist/reactive/memoize.d.ts +0 -5
  125. package/dist/reactive/memoize.d.ts.map +0 -1
  126. package/dist/reactive/non-reactive-state.d.ts +0 -9
  127. package/dist/reactive/non-reactive-state.d.ts.map +0 -1
  128. package/dist/reactive/non-reactive.d.ts +0 -11
  129. package/dist/reactive/non-reactive.d.ts.map +0 -1
  130. package/dist/reactive/project.d.ts +0 -41
  131. package/dist/reactive/project.d.ts.map +0 -1
  132. package/dist/reactive/proxy-state.d.ts +0 -8
  133. package/dist/reactive/proxy-state.d.ts.map +0 -1
  134. package/dist/reactive/proxy.d.ts +0 -23
  135. package/dist/reactive/proxy.d.ts.map +0 -1
  136. package/dist/reactive/record.d.ts +0 -116
  137. package/dist/reactive/record.d.ts.map +0 -1
  138. package/dist/reactive/register.d.ts +0 -64
  139. package/dist/reactive/register.d.ts.map +0 -1
  140. package/dist/reactive/registry.d.ts +0 -20
  141. package/dist/reactive/registry.d.ts.map +0 -1
  142. package/dist/reactive/set.d.ts +0 -28
  143. package/dist/reactive/set.d.ts.map +0 -1
  144. package/dist/reactive/tracking.d.ts +0 -7
  145. package/dist/reactive/tracking.d.ts.map +0 -1
  146. package/dist/reactive/types.d.ts.map +0 -1
  147. package/dist/std-decorators.d.ts +0 -50
  148. package/dist/std-decorators.d.ts.map +0 -1
  149. package/dist/utils.d.ts +0 -49
  150. package/dist/utils.d.ts.map +0 -1
  151. package/dist/zone.d.ts +0 -40
  152. package/dist/zone.d.ts.map +0 -1
  153. package/docs/reactive/project.md +0 -93
  154. package/src/async/browser.ts +0 -319
  155. package/src/async/index.ts +0 -23
  156. package/src/async/node.ts +0 -104
  157. package/src/decorator.ts +0 -272
  158. package/src/destroyable.ts +0 -199
  159. package/src/entry-browser.ts +0 -5
  160. package/src/entry-node.ts +0 -5
  161. package/src/eventful.ts +0 -77
  162. package/src/index.d.ts +0 -12
  163. package/src/index.ts +0 -64
  164. package/src/indexable.ts +0 -526
  165. package/src/introspection.ts +0 -59
  166. package/src/iterableWeak.ts +0 -233
  167. package/src/mixins.ts +0 -123
  168. package/src/promiseChain.ts +0 -110
  169. package/src/reactive/array.ts +0 -507
  170. package/src/reactive/buffer.ts +0 -168
  171. package/src/reactive/change.ts +0 -138
  172. package/src/reactive/debug.ts +0 -517
  173. package/src/reactive/deep-touch.ts +0 -268
  174. package/src/reactive/deep-watch-state.ts +0 -82
  175. package/src/reactive/deep-watch.ts +0 -168
  176. package/src/reactive/effect-context.ts +0 -18
  177. package/src/reactive/effects.ts +0 -1382
  178. package/src/reactive/index.ts +0 -75
  179. package/src/reactive/interface.ts +0 -210
  180. package/src/reactive/map.ts +0 -158
  181. package/src/reactive/memoize.ts +0 -163
  182. package/src/reactive/non-reactive-state.ts +0 -49
  183. package/src/reactive/non-reactive.ts +0 -43
  184. package/src/reactive/project.ts +0 -453
  185. package/src/reactive/proxy-state.ts +0 -27
  186. package/src/reactive/proxy.ts +0 -264
  187. package/src/reactive/record.ts +0 -196
  188. package/src/reactive/register.ts +0 -419
  189. package/src/reactive/registry.ts +0 -59
  190. package/src/reactive/set.ts +0 -130
  191. package/src/reactive/tracking.ts +0 -44
  192. package/src/reactive/types.ts +0 -440
  193. package/src/std-decorators.ts +0 -217
  194. package/src/utils.ts +0 -301
  195. package/src/zone.ts +0 -138
@@ -25,7 +25,7 @@ These hooks are called during the execution of effects and computed values.
25
25
 
26
26
  - **`beginChain(targets: Function[]) / endChain()`**: Called when a batch of effects starts and ends its execution.
27
27
  - **`maxEffectChain`**: (Default: `100`) Limits the depth of synchronous effect triggering to prevent stack overflows.
28
- - **`maxTriggerPerBatch`**: (Default: `10`) Limits how many times a single effect can be triggered within the same batch. Useful for detecting aggressive re-computation or infinite cycles in `cycleHandling: 'none'` mode.
28
+ - **`maxTriggerPerBatch`**: (Default: `10`) Limits how many times a single effect can be triggered within the same batch. Useful for detecting aggressive re-computation or infinite cycles in `cycleHandling: 'production'` mode.
29
29
 
30
30
  ## Cycle Detection
31
31
 
@@ -35,22 +35,45 @@ These hooks are called during the execution of effects and computed values.
35
35
 
36
36
  You can control how cycles are handled via `reactiveOptions.cycleHandling`:
37
37
 
38
- - **`'none'`** (Default): High-performance FIFO mode. Disables the dependency graph and topological sorting.
39
- - **`'throw'`**: Throws a `ReactiveError` with a detailed path.
40
- - **`'warn'`**: Logs a warning but breaks the cycle to allow the application to continue.
41
- - **`'break'`**: Silently breaks the cycle.
42
- - **`'strict'`**: Performs a graph check *before* execution to prevent cycles from even starting. This has the highest overhead.
38
+ - **`'production'`**: High-performance FIFO mode. Disables the dependency graph and topological sorting. Uses heuristic detection via `maxEffectChain`.
39
+ - **`'development'`** (Default): Maintains direct dependency graph for early cycle detection during edge creation. Throws immediately with basic path information.
40
+ - **`'debug'`**: Full diagnostic mode with transitive closures and topological sorting. Provides detailed cycle path reporting.
43
41
 
44
42
  ### Topological vs. Flat Mode Detection
43
+ - **Detection**: Cycles are detected when the execution depth exceeds `maxEffectChain` (default 100).
44
+ - **Diagnostics**: The resulting `ReactiveError` includes a `trace` property (the recent execution sequence) and attempts to identify a repeating `cycle`.
45
+ - **Recommendation**: Use this mode only for production to minimize performance overhead.
45
46
 
46
- | Mode | `cycleHandling` | Detection Method | Error Code |
47
- | :--- | :--- | :--- | :--- |
48
- | **Topological** | `'throw'` (or other) | **Mathematical**: Analyzes the dependency graph. | `CYCLE_DETECTED` |
49
- | **Flat Mode** | `'none'` (Default) | **Heuristic**: Counts executions per batch. | `MAX_REACTION_EXCEEDED` |
47
+ ### Cycle Handling Modes
50
48
 
51
- In **Topological mode**, the system maintains a transitive closure of all effects, allowing it to know instantly if an effect is its own cause. In **Flat mode**, the system is "blind" to the graph and relies on the execution threshold (`maxTriggerPerBatch`) to interrupt infinite loops.
49
+ You can configure how the system handles cycles via `reactiveOptions.cycleHandling`:
52
50
 
53
- ## Memoization Discrepancy Detection
51
+ | Mode | Detection Timing | Cycle Information | Performance |
52
+ |------|-----------------|-------------------|-------------|
53
+ | `'production'` | Late (Heuristic) | Trace of last N effects | Fastest |
54
+ | `'development'` | Eager (On edge) | Exact path (DFS) | Moderate |
55
+ | `'debug'` | Structural | Transitive closures | Slowest |
56
+
57
+ #### Finding Cycle Information
58
+
59
+ When a cycle is detected, a `ReactiveError` is thrown. You can find detailed path information in the error object:
60
+
61
+ ```typescript
62
+ try {
63
+ atom(() => { /* cycle logic */ });
64
+ } catch (error) {
65
+ if (error.code === 'Cycle detected') {
66
+ console.log('Cycle Path:', error.cycle.join(' → '));
67
+ console.log('Trigger Chain:', error.causalChain);
68
+ }
69
+ }
70
+ ```
71
+
72
+ - **`error.cycle`**: An array of effect names forming the cycle.
73
+ - **`error.causalChain`**: The sequence of triggers that led to the current effect.
74
+ - **`error.lineage`**: The creation stack of the effect (available in `development` or `debug` modes).
75
+
76
+ ### Memoization Discrepancy Detection
54
77
 
55
78
  The most powerful debugging tool in `mutts` is the **Discrepancy Detector**. It helps identify "missing dependencies"—reactive values used inside a computation that the system isn't tracking.
56
79
 
@@ -127,10 +150,12 @@ When the reactive system encounters a critical failure (like a cycle or max dept
127
150
  ### `ReactiveErrorCode`
128
151
 
129
152
  Always check `error.debugInfo.code` to identify the failure type:
130
- - `CYCLE_DETECTED`: A circular dependency was found.
131
- - `MAX_DEPTH_EXCEEDED`: The synchronous effect chain reached `maxEffectChain`.
132
- - `MAX_REACTION_EXCEEDED`: An effect was triggered too many times in a single batch.
133
- - `WRITE_IN_COMPUTED`: An attempt was made to modify reactive state inside a `memoize` or `derived` function.
153
+ - `Cycle detected`: A circular dependency was found.
154
+ - `Max depth exceeded`: The synchronous effect chain reached `maxEffectChain`.
155
+ - `Max reaction exceeded`: An effect was triggered too many times in a single batch.
156
+ - `Write in computed`: An attempt was made to modify reactive state inside a `memoize` function.
157
+ - `Tracking error`: Internal inconsistency detected in the active dependency stack.
158
+ - `Broken effects`: The system has entered an unrecoverable "broken" state after a root-level panic. Call `reset()` to recover.
134
159
 
135
160
  ### Rich Debug Info
136
161
 
@@ -138,6 +163,7 @@ The `debugInfo` property on `ReactiveError` includes:
138
163
  - **`causalChain`**: A string array describing the logical path of modifications leading to the error.
139
164
  - **`creationStack`**: The stack trace of where the effect was originally created, helping you locate the source in your code.
140
165
  - **`cycle`**: (For `CYCLE_DETECTED`) The names of the effects that form the loop.
166
+ - **`lineage`**: Detailed source-to-sink dependency traces for debugging (requires `lineages` introspection).
141
167
 
142
168
  ## Best Practices for Debugging
143
169
 
@@ -149,20 +175,99 @@ Always provide a name for your effects to make debug logs and error messages rea
149
175
  effect(() => {
150
176
  // ...
151
177
  }, { name: 'UpdateSidebarCounter' });
178
+
179
+ // Or
180
+
181
+ effect.named('UpdateSidebarCounter')(() => {
182
+ // ...
183
+ });
152
184
  ```
153
185
 
186
+
154
187
  ### Activation & Deactivation
155
188
 
156
189
  Since these are runtime options, you can toggle them based on your environment:
157
190
 
158
191
  ```typescript
159
192
  if (process.env.NODE_ENV === 'development') {
160
- reactiveOptions.cycleHandling = 'throw';
193
+ reactiveOptions.cycleHandling = 'debug';
161
194
  reactiveOptions.onMemoizationDiscrepancy = myHandler;
162
195
  enableIntrospection();
163
196
  } else {
164
197
  // Ensure they are off in production for performance
165
198
  reactiveOptions.onMemoizationDiscrepancy = undefined;
166
- reactiveOptions.cycleHandling = 'break';
199
+ reactiveOptions.cycleHandling = 'production';
167
200
  }
168
201
  ```
202
+
203
+ ## Advanced Debugging (`mutts/debug`)
204
+
205
+ For a deeper look into the reactivity graph and execution flow, you can import the `mutts/debug` module. Simply importing it enables several background tracking features.
206
+
207
+ ```typescript
208
+ import 'mutts/debug';
209
+ ```
210
+
211
+ ### Reaction Reasons (`CleanupReason`)
212
+
213
+ When an effect or watcher re-runs, it receives a `reaction` property (in `EffectAccess`) that describes *why* it was triggered. This is also passed to the `cleanup` function.
214
+
215
+ ```typescript
216
+ effect(({ reaction }) => {
217
+ if (reaction && typeof reaction === 'object') {
218
+ if (reaction.type === 'propChange') {
219
+ console.log('Triggered by:', reaction.triggers.map(t => t.evolution.prop));
220
+ }
221
+ }
222
+
223
+ return (reason) => {
224
+ // reason is also a CleanupReason
225
+ if (reason?.type === 'stopped') console.log('Effect manually stopped');
226
+ };
227
+ });
228
+ ```
229
+
230
+ #### `formatCleanupReason`
231
+
232
+ A built-in utility to turn a `CleanupReason` into an inspectable console log array.
233
+
234
+ ```typescript
235
+ import { formatCleanupReason } from 'mutts';
236
+
237
+ effect(()=> {
238
+ ...
239
+ return (reason)=> {
240
+ if (reason) console.log(...formatCleanupReason(reason));
241
+ }
242
+ });
243
+ ```
244
+
245
+ ### Lineage Tracking
246
+
247
+ Lineage tracking allows you to see the "causal path" of an effect—not just the current stack trace, but the stack traces of all parent effects that created the current execution.
248
+
249
+ When an effect is created, it is assigned a `lineage` property that contains the stack traces of all parent effects that lead to its creation.
250
+
251
+ - **`logLineage()`**: Prints a formatted, interactive tree of the current effect's lineage to the console.
252
+ - **`captureLineage()`**: Captures the current lineage as a structured object.
253
+
254
+ #### Lineage Options
255
+
256
+ You can control how lineages are captured via `reactiveOptions.introspection.gatherReasons.lineages`:
257
+ - `'none'`: Disable lineage capture.
258
+ - `'touch'`: Capture lineage when a property is accessed (default).
259
+ - `'dependency'`: Capture lineage when a dependency is recorded.
260
+ - `'both'`: Capture both.
261
+
262
+ ### The `__MUTTS_DEBUG__` Global
263
+
264
+ When `mutts/debug` is active (or after calling `enableDevTools()`), a global `__MUTTS_DEBUG__` object is exposed in the environment (Node.js `global` or Browser `window`).
265
+
266
+ This object provides low-level access to the graph, lineage capture, and renaming utilities:
267
+ - `__MUTTS_DEBUG__.getGraph()`: Returns the full reactivity graph.
268
+ - `__MUTTS_DEBUG__.logLineage()`: logs the current lineage.
269
+ - `__MUTTS_DEBUG__.browserLineage`: captures lineage for the DevTools panel.
270
+
271
+ ### Custom DevTools Formatters
272
+
273
+ `mutts/debug` automatically registers [Custom Formatters](https://bit.ly/chrome-extension-custom-formatters) in Chrome. This makes lineage objects and reactive proxies appear as clean, structured trees in the console instead of opaque Proxy objects.
@@ -0,0 +1,121 @@
1
+ # Effect Error Handling
2
+
3
+ The `caught` function allows you to catch and handle errors within reactive effects.
4
+
5
+ ## Basic Usage
6
+
7
+ Register an error handler inside an effect using `caught`:
8
+
9
+ ```typescript
10
+ import { effect, caught, reactive } from 'mutts'
11
+
12
+ const state = reactive({ value: 0 })
13
+
14
+ effect(() => {
15
+ caught((error) => {
16
+ console.error('Effect failed:', error)
17
+ })
18
+
19
+ // Your effect logic that might throw
20
+ if (state.value < 0) throw new Error('Negative value not allowed')
21
+ })
22
+ ```
23
+
24
+ ## Multiple Handlers
25
+
26
+ You can register multiple handlers. They are tried in order until one succeeds:
27
+
28
+ ```typescript
29
+ effect(() => {
30
+ // First handler - try to recover
31
+ caught((error) => {
32
+ if (error.message === 'Retryable') {
33
+ retryOperation()
34
+ return // Success - stops here
35
+ }
36
+ throw error // Re-throw to try next handler
37
+ })
38
+
39
+ // Second handler - log and continue
40
+ caught((error) => {
41
+ console.log('Operation failed:', error)
42
+ })
43
+ })
44
+ ```
45
+
46
+ ## Parent-Child Error Propagation
47
+
48
+ Errors in child effects propagate to parent effects:
49
+
50
+ ```typescript
51
+ effect(() => {
52
+ // Parent catches child's error
53
+ caught((error) => {
54
+ console.log('Child failed:', error.message)
55
+ })
56
+
57
+ effect(() => {
58
+ // This error propagates to parent, even if a reactive re-evaluation
59
+ throw new Error('Child error')
60
+ })
61
+ })
62
+ ```
63
+
64
+ If no handler catches the error, it propagates up the effect chain until caught or thrown at the root.
65
+
66
+ ## Cleanup from Handler
67
+
68
+ Handlers can return cleanup functions:
69
+
70
+ ```typescript
71
+ effect(() => {
72
+ caught((error) => {
73
+ console.log('Handling error:', error)
74
+
75
+ return () => {
76
+ // Cleanup when effect is destroyed
77
+ cleanupResources()
78
+ }
79
+ })
80
+ })
81
+ ```
82
+
83
+ ## API
84
+
85
+ ### `caught(handler)`
86
+
87
+ Registers an error handler for the current effect.
88
+
89
+ **Parameters:**
90
+ - `handler: (error: any) => (() => void) | undefined | void` - Function called when an error occurs in the effect
91
+
92
+ **Returns:** Nothing
93
+
94
+ **Throws:** Error if called outside of an effect
95
+
96
+ **Handler behavior:**
97
+ - Returns without throwing → error is considered handled
98
+ - Throws → next handler is tried
99
+ - Returns a function → used as cleanup when effect stops
100
+
101
+ ## Error Propagation Flow
102
+
103
+ ```
104
+ Effect throws
105
+
106
+ Try handlers in order
107
+
108
+ Handler succeeds → effect continues
109
+
110
+ All handlers fail → propagate to parent
111
+
112
+ Parent's handlers try
113
+
114
+ ...continue until caught or root reached
115
+ ```
116
+
117
+ ## Notes
118
+
119
+ - Handlers must be registered **before** the code that might throw
120
+ - Handlers are cleared on each effect re-run (re-register if needed)
121
+ - Errors in async effects (Promises) are not caught by `caught` - use `.catch()` on the Promise
@@ -0,0 +1,125 @@
1
+ # Reactive Resource (`resource`)
2
+
3
+ The `resource` utility creates a reactive object that automatically tracks the state of an asynchronous operation (loading, value, error). It is designed to simplify data fetching and async state management in a reactive environment.
4
+
5
+ ## Overview
6
+
7
+ `resource` wraps an async function (the "fetcher") and returns a reactive object that:
8
+ - **Tracks dependencies**: Automatically re-runs the fetcher when reactive dependencies accessed within it change.
9
+ - **Manages state**: Provides `loading`, `value`, `error`, and `latest` properties that update automatically.
10
+ - **Handles race conditions**: Ensures that only the result of the latest fetch is applied, discarding results from stale requests.
11
+ - **Supports manual reload**: Exposes a `reload()` method to force a refresh.
12
+
13
+ ## API
14
+
15
+ ```typescript
16
+ function resource<T>(
17
+ fetcher: (dep: EffectAccess) => Promise<T> | T,
18
+ options?: { initialValue?: T }
19
+ ): Resource<T>
20
+
21
+ interface Resource<T> {
22
+ value: T | undefined // The current successful value
23
+ loading: boolean // True if a fetch is in progress
24
+ error: any // Error from the last failed fetch
25
+ latest: T | undefined // The latest successful value (preserved during loading)
26
+ reload: () => void // Function to manually trigger a re-fetch
27
+ }
28
+ ```
29
+
30
+ ### Parameters
31
+
32
+ - **`fetcher`**: A function that returns a value `T` or a `Promise<T>`. It receives an `EffectAccess` object, allowing for dependency tracking control (e.g., `dep.tracked()`). Reactive properties accessed synchronously or within tracked scopes are dependencies.
33
+ - **`options`**: Optional configuration object.
34
+ - `initialValue`: Initial value for `value` and `latest` before the first fetch completes (or if the first fetch is async).
35
+
36
+ ### Returns
37
+
38
+ A reactive object implementing the `Resource<T>` interface.
39
+
40
+ ## Usage
41
+
42
+ ### Basic Async Fetch
43
+
44
+ ```typescript
45
+ import { reactive, resource } from 'mutts/reactive'
46
+
47
+ // ID usually comes from another reactive source
48
+ const state = reactive({ userId: 1 })
49
+
50
+ // Create a resource that fetches user data based on state.userId
51
+ const user = resource(async () => {
52
+ const response = await fetch(`/api/users/${state.userId}`)
53
+ return response.json()
54
+ })
55
+
56
+ // Use the resource in your view
57
+ effect(() => {
58
+ if (user.loading) {
59
+ console.log('Loading...')
60
+ } else if (user.error) {
61
+ console.error('Error:', user.error)
62
+ } else {
63
+ console.log('User:', user.value)
64
+ }
65
+ })
66
+
67
+ // Changing state.userId automatically triggers a new fetch
68
+ state.userId = 2
69
+ ```
70
+
71
+ ### Handling Race Conditions
72
+
73
+ `resource` automatically handles race conditions. If `state.userId` changes quickly from 1 to 2, and the request for user 1 takes longer than user 2, the result for user 1 will be ignored when it arrives, preventing inconsistent state.
74
+
75
+ ### Using `latest` for Smooth Transitions
76
+
77
+ The `value` property becomes `undefined` (or `initialValue`) when a new fetch starts if the previous value is not preserved (current implementation resets `value` only on success? No, `value` is kept from previous success? - *Clarification: In the implementation, `value` is NOT reset to undefined on new fetch start, it retains the old value until new value arrives, unless `initialValue` was used? Let's check implementation behavior.*)
78
+
79
+ *Correction based on implementation:*
80
+ The current implementation:
81
+ ```typescript
82
+ state.loading = true
83
+ state.error = undefined
84
+ // ... fetcher executes ...
85
+ // on success:
86
+ state.value = val
87
+ state.latest = val
88
+ state.loading = false
89
+ ```
90
+ It does **NOT** reset `value` to `undefined` when a new fetch starts. So `value` acts like `latest`. The distinction is primarily semantic or for future behavior where `value` might be reset. Currently `value` and `latest` behave similarly regarding preservation of old data during loading.
91
+
92
+ ```typescript
93
+ effect(() => {
94
+ // Show old data while loading new data
95
+ if (user.loading) {
96
+ console.log('Reloading... showing cached version:', user.latest)
97
+ } else {
98
+ console.log('Current:', user.value)
99
+ }
100
+ })
101
+ ```
102
+
103
+ ### Manual Reload
104
+
105
+ You can trigger a re-fetch without changing dependencies:
106
+
107
+ ```typescript
108
+ // Refresh the data (e.g., user clicked a "Refresh" button)
109
+ user.reload()
110
+ ```
111
+
112
+ ### Synchronous Resources
113
+
114
+ `resource` can also wrap synchronous calculations, essentially behaving like a computed property but with the `Resource` interface structure.
115
+
116
+ ```typescript
117
+ const count = reactive({ value: 1 })
118
+
119
+ const doubled = resource(() => {
120
+ return count.value * 2
121
+ })
122
+
123
+ console.log(doubled.value) // 2
124
+ console.log(doubled.loading) // false
125
+ ```