stunk 2.8.0 → 3.0.0-beta.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.
package/LICENSE CHANGED
@@ -1,27 +1,27 @@
1
- ---
2
-
3
- ### **`LICENSE`**
4
-
5
- ```text
6
- MIT License
7
-
8
- Copyright (c) 2025 AbdulAzeez
9
-
10
- Permission is hereby granted, free of charge, to any person obtaining a copy
11
- of this software and associated documentation files (the "Software"), to deal
12
- in the Software without restriction, including without limitation the rights
13
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
- copies of the Software, and to permit persons to whom the Software is
15
- furnished to do so, subject to the following conditions:
16
-
17
- The above copyright notice and this permission notice shall be included in all
18
- copies or substantial portions of the Software.
19
-
20
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
- SOFTWARE.
27
- ```
1
+ ---
2
+
3
+ ### **`LICENSE`**
4
+
5
+ ```text
6
+ MIT License
7
+
8
+ Copyright (c) 2025 AbdulAzeez
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ ```
package/README.md CHANGED
@@ -1,204 +1,408 @@
1
- # Stunk
2
-
3
- Stunk is a lightweight, framework-agnostic state management library built on atomic state principles. It simplifies state management by breaking state into manageable "chunks", ensuring efficient updates and reactivity.
4
-
5
- - **Pronunciation**: _Stunk_ (A playful blend of "state" and "chunk")
6
-
7
- **Stunk** is like dividing your jar into many smaller containers, each holding a single piece of state. These smaller containers are called **chunks**. Each **chunk** can be updated and accessed easily, and any part of your app can subscribe to changes in a chunk so it gets updated automatically.
8
-
9
- ## Features
10
-
11
- - 🚀 **Lightweight and Fast**: No dependencies, minimal overhead
12
- - 🔄 **Reactive**: Automatic updates when state changes
13
- - 📦 **Batch Updates**: Group multiple state updates together
14
- - 🎯 **Atomic State Management**: Break down state into manageable chunks
15
- - 🎭 **State Selection**: Select and derive specific parts of the state
16
- - 🔄 **Async Support**: Handle async state with built-in loading and error states
17
- - 🔌 **Middleware Support**: Extend functionality with custom middleware
18
- - ⏱️ **Time Travel**: Undo/redo state changes
19
- - 🔍 **Type-Safe**: Written in TypeScript with full type inference
20
-
21
- ## Installation
22
-
23
- ```bash
24
- npm install stunk
25
- # or
26
- yarn add stunk
27
- # or
28
- pnpm install stunk
29
- ```
30
-
31
- Read Docs:
32
-
33
- [Stunk](https://stunk.vercel.app/)
34
-
35
- ## Creating a Chunk
36
-
37
- ```typescript
38
- import { chunk } from "stunk";
39
-
40
- // Create a chunk holding a number
41
- const count = chunk(0);
42
-
43
- // Create a chunk holding a string
44
- const name = chunk("Stunky, chunky");
45
- ```
46
-
47
- 👉 [See full explanation in docs](https://stunk.vercel.app/chunk.html)
48
-
49
- ## Interacting with a Chunk
50
-
51
- ```typescript
52
- // Get value
53
- console.log(count.get()); // 0
54
-
55
- // Set a new value
56
- count.set(10);
57
-
58
- // Update based on the previous value
59
- count.set((prev) => prev + 1);
60
-
61
- // Reset to the initial value
62
- count.reset();
63
-
64
- // Destroy the chunk and all its subscribers.
65
- count.destroy();
66
- ```
67
-
68
- 👉 [See full explanation in docs](https://stunk.vercel.app/chunk.html)
69
-
70
- ## React via useChunk
71
-
72
- The `useChunk` hook, enables components to reactively read and update state from a Chunk. The counter example below depicts
73
-
74
- ```typescript
75
- import { chunk } from "stunk";
76
- import { useChunk } from "stunk/react";
77
-
78
- const count = chunk(0);
79
-
80
- const Counter = () => {
81
- const [value, set, reset] = useChunk(count);
82
-
83
- return (
84
- <div>
85
- <p>Count: {value}</p>
86
- <button onClick={() => set((prev) => prev + 1)}>Increment</button>
87
- <button onClick={() => reset()}>Reset</button>
88
- </div>
89
- );
90
- };
91
- ```
92
-
93
- 👉 [See full explanation in docs](https://stunk.vercel.app/useChunk.html)
94
-
95
- ## React via useDerive
96
-
97
- Hook that lets you create a read-only derived state from a Chunk. It keeps the derived value reactive, automatically updating whenever the source Chunk changes.
98
-
99
- ```typescript
100
- import { chunk } from "stunk";
101
- import { useDerive } from "stunk/react";
102
-
103
- const count = chunk(0);
104
-
105
- const DoubledCount = () => {
106
- const double = useDerive(count, (value) => value * 2);
107
-
108
- return <p>Double: {double}</p>;
109
- };
110
- ```
111
-
112
- 👉 [See full explanation in docs](https://stunk.vercel.app/useDerive.html)
113
-
114
- ## React via useComputed
115
-
116
- Hook that derives a computed value from one or more Chunks. It automatically re-evaluates whenever any of its dependencies change, ensuring efficient and reactive updates.
117
-
118
- ```typescript
119
- import { chunk } from "stunk";
120
- import { useComputed } from "stunk/react";
121
-
122
- const count = chunk(2);
123
- const multiplier = chunk(3);
124
-
125
- const ComputedExample = () => {
126
- const product = useComputed([count, multiplier], (c, m) => c * m);
127
-
128
- return <p>Product: {product}</p>;
129
- };
130
- ```
131
-
132
- 👉 [See full explanation in docs](https://stunk.vercel.app/useComputed.html)
133
-
134
- ## React via useAsyncChunk
135
-
136
- Hook that manages that manages asynchronous state. It offers built-in reactivity, handling loading, error, and data states, ensuring the UI stays in sync with asynchronous operations.
137
-
138
- ```typescript
139
- import { asyncChunk } from "stunk";
140
- import { useAsyncChunk } from "stunk/react";
141
-
142
- const fetchUser = asyncChunk(async () => {
143
- const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
144
- return res.json();
145
- });
146
-
147
- const UserProfile = () => {
148
- const { data, loading, error, reload } = useAsyncChunk(fetchUser);
149
-
150
- if (loading) return <p>Loading...</p>;
151
- if (error) return <p>Error: {error.message}</p>;
152
-
153
- return (
154
- <div>
155
- <h2>{data.name}</h2>
156
- <p>{data.email}</p>
157
- <button onClick={reload}>Reload</button>
158
- </div>
159
- );
160
- };
161
- ```
162
-
163
- 👉 [See full explanation in docs](https://stunk.vercel.app/useAysncChunk.html)
164
-
165
- ## React via useChunkValue
166
-
167
- Hook that subscribes to a Chunk and returns its current value. It is useful for read-only components that don’t need to modify the state.
168
-
169
- ```typescript
170
- import { chunk } from "stunk";
171
- import { useChunkValue } from "stunk/react";
172
-
173
- const count = chunk(0);
174
-
175
- const CounterDisplay = () => {
176
- const value = useChunkValue(count);
177
-
178
- return <p>Count: {value}</p>;
179
- };
180
- ```
181
-
182
- 👉 [See full explanation in docs](https://stunk.vercel.app/read-only-values.html)
183
-
184
- Live Examples:
185
-
186
- 👉 [Visit](https://stunk-examples.vercel.app/)
187
-
188
- Coding Examples:
189
-
190
- 👉 [Visit](https://stunk.vercel.app/examples.html)
191
-
192
- Further Examples:
193
-
194
- 👉 [Visit](https://github.com/I-am-abdulazeez/stunk-examples/)
195
-
196
- ## Contributing
197
-
198
- Contributions are welcome! Please feel free to submit a Pull Request.
199
-
200
- [Pull Request](https://github.com/I-am-abdulazeez/stunk/pulls)
201
-
202
- ## License
203
-
204
- This is licence under MIT
1
+ # Stunk
2
+
3
+ Stunk is a lightweight, framework-agnostic state management library built on atomic state principles. Break state into independent **chunks** each one reactive, composable, and self-contained.
4
+
5
+ - **Pronunciation**: _Stunk_ (a playful blend of "state" and "chunk")
6
+
7
+ ## Features
8
+
9
+ - 🚀 **Lightweight** — 3.32kB gzipped, zero dependencies
10
+ - ⚛️ **Atomic** — break state into independent chunks
11
+ - 🔄 **Reactive** fine-grained updates, only affected components re-render
12
+ - 🧮 **Auto-tracking computed** no dependency arrays, just call `.get()`
13
+ - 🌐 **Async & Query layer** loading, error, caching, deduplication, pagination built in
14
+ - 🔁 **Mutations** reactive POST/PUT/DELETE with automatic cache invalidation
15
+ - 📦 **Batch updates** group multiple updates into one render
16
+ - 🔌 **Middleware** logging, persistence, validation plug anything in
17
+ - ⏱️ **Time travel** undo/redo state changes
18
+ - 🔍 **TypeScript first** full type inference, no annotations needed
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install stunk
24
+ # or
25
+ yarn add stunk
26
+ # or
27
+ pnpm add stunk
28
+ ```
29
+
30
+ 📖 [Read the docs](https://stunk.dev)
31
+
32
+ <<<<<<< HEAD
33
+ [Stunk](https://stunk.dev/)
34
+ =======
35
+ ---
36
+ >>>>>>> v3
37
+
38
+ ## Core State
39
+
40
+ ```ts
41
+ import { chunk } from "stunk";
42
+
43
+ <<<<<<< HEAD
44
+ // Create a chunk holding a number
45
+ const count = chunk<number>(0);
46
+
47
+ // Create a chunk holding a string
48
+ const name = chunk<string>("Stunky, chunky");
49
+ ```
50
+
51
+ 👉 [See full explanation in docs](https://stunk.dev/chunk.html)
52
+
53
+ ## Interacting with a Chunk
54
+
55
+ ```typescript
56
+ // Get value
57
+ console.log(count.get()); // 0
58
+
59
+ // Set a new value
60
+ count.set(10);
61
+
62
+ // Update based on the previous value
63
+ count.set((prev: number) => prev + 1);
64
+
65
+ // Reset to the initial value
66
+ count.reset();
67
+
68
+ // Destroy the chunk and all its subscribers.
69
+ count.destroy();
70
+ ```
71
+
72
+ 👉 [See full explanation in docs](https://stunk.dev/chunk.html)
73
+
74
+ ## React via useChunk
75
+
76
+ The `useChunk` hook, enables components to reactively read and update state from a Chunk. The counter example below depicts
77
+
78
+ ```typescript
79
+ import { chunk } from "stunk";
80
+ import { useChunk } from "stunk/react";
81
+
82
+ const count = chunk<number>(0);
83
+
84
+ const Counter = () => {
85
+ const [value, set, reset] = useChunk(count);
86
+
87
+ return (
88
+ <div>
89
+ <p>Count: {value}</p>
90
+ <button onClick={() => set((prev: number) => prev + 1)}>Increment</button>
91
+ <button onClick={() => reset()}>Reset</button>
92
+ </div>
93
+ );
94
+ };
95
+ ```
96
+
97
+ 👉 [See full explanation in docs](https://stunk.dev/useChunk.html)
98
+ =======
99
+ const count = chunk(0);
100
+
101
+ count.get(); // 0
102
+ count.set(10); // set directly
103
+ count.set((prev) => prev + 1); // updater function
104
+ count.peek(); // read without tracking dependencies
105
+ count.reset(); // back to 0
106
+ count.destroy(); // clear all subscribers
107
+ ```
108
+
109
+ ---
110
+ >>>>>>> v3
111
+
112
+ ## Computed auto dependency tracking
113
+
114
+ No dependency arrays. Any chunk whose `.get()` is called inside the function is tracked automatically:
115
+
116
+ ```ts
117
+ import { chunk, computed } from "stunk";
118
+
119
+ const price = chunk(100);
120
+ const quantity = chunk(3);
121
+
122
+ const total = computed(() => price.get() * quantity.get());
123
+
124
+ total.get(); // 300
125
+
126
+ price.set(200);
127
+ total.get(); // 600 — recomputed automatically
128
+ ```
129
+
130
+ Use `.peek()` to read without tracking:
131
+
132
+ ```ts
133
+ const taxRate = chunk(0.1);
134
+ const subtotal = computed(() => price.get() * (1 + taxRate.peek()));
135
+ // only recomputes when price changes
136
+ ```
137
+
138
+ ---
139
+
140
+ ## Async & Query
141
+
142
+ ```ts
143
+ import { asyncChunk } from "stunk/query";
144
+
145
+ const userChunk = asyncChunk(
146
+ async ({ id }: { id: number }) => fetchUser(id),
147
+ {
148
+ key: "user", // deduplicates concurrent requests
149
+ keepPreviousData: true, // no UI flicker on param changes
150
+ staleTime: 30_000,
151
+ onError: (err) => toast.error(err.message),
152
+ }
153
+ );
154
+
155
+ userChunk.setParams({ id: 1 });
156
+ // { loading: true, data: null, error: null }
157
+ // { loading: false, data: { id: 1, name: "..." }, error: null }
158
+ ```
159
+
160
+ ---
161
+
162
+ ## Mutations
163
+
164
+ Reactive POST/PUT/DELETE — one function, always safe to await or fire and forget:
165
+
166
+ ```ts
167
+ import { mutation } from "stunk/query";
168
+
169
+ const createPost = mutation(
170
+ async (data: NewPost) => fetchAPI("/posts", { method: "POST", body: data }),
171
+ {
172
+ invalidates: [postsChunk], // auto-reloads on success
173
+ onSuccess: () => toast.success("Created!"),
174
+ onError: (err) => toast.error(err.message),
175
+ }
176
+ );
177
+
178
+ // Fire and forget — safe
179
+ createPost.mutate({ title: "Hello" });
180
+
181
+ // Await for local control — no try/catch needed
182
+ const { data, error } = await createPost.mutate({ title: "Hello" });
183
+ if (!error) router.push("/posts");
184
+ ```
185
+
186
+ ---
187
+
188
+ ## Global Query Config
189
+
190
+ Set defaults once for all async chunks and mutations:
191
+
192
+ ```ts
193
+ import { configureQuery } from "stunk/query";
194
+
195
+ configureQuery({
196
+ query: {
197
+ staleTime: 30_000,
198
+ retryCount: 3,
199
+ onError: (err) => toast.error(err.message),
200
+ },
201
+ mutation: {
202
+ onError: (err) => toast.error(err.message),
203
+ },
204
+ });
205
+ ```
206
+
207
+ ---
208
+
209
+ ## Middleware
210
+
211
+ ```ts
212
+ import { chunk } from "stunk";
213
+ import { logger, nonNegativeValidator } from "stunk/middleware";
214
+
215
+ <<<<<<< HEAD
216
+ const count = chunk<number>(0);
217
+
218
+ const DoubledCount = () => {
219
+ const double = useDerive(count, (value: number) => value * 2);
220
+
221
+ return <p>Double: {double}</p>;
222
+ };
223
+ ```
224
+
225
+ 👉 [See full explanation in docs](https://stunk.dev/useDerive.html)
226
+
227
+ ## React via useComputed
228
+
229
+ Hook that derives a computed value from one or more Chunks. It automatically re-evaluates whenever any of its dependencies change, ensuring efficient and reactive updates.
230
+
231
+ ```typescript
232
+ import { chunk } from "stunk";
233
+ import { useComputed } from "stunk/react";
234
+
235
+ const count = chunk<number>(2);
236
+ const multiplier = chunk<number>(3);
237
+
238
+ const ComputedExample = () => {
239
+ const product = useComputed(
240
+ [count, multiplier],
241
+ (c: number, m: number) => c * m
242
+ );
243
+
244
+ return <p>Product: {product}</p>;
245
+ };
246
+ ```
247
+
248
+ 👉 [See full explanation in docs](https://stunk.dev/useComputed.html)
249
+
250
+ ## React via useAsyncChunk
251
+
252
+ Hook that manages that manages asynchronous state. It offers built-in reactivity, handling loading, error, and data states, ensuring the UI stays in sync with asynchronous operations.
253
+
254
+ ```typescript
255
+ import { asyncChunk } from "stunk";
256
+ import { useAsyncChunk } from "stunk/react";
257
+
258
+ interface User {
259
+ name: string;
260
+ email: string;
261
+ }
262
+
263
+ const fetchUser = asyncChunk<User>(async () => {
264
+ const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
265
+ return res.json();
266
+ =======
267
+ const score = chunk(0, {
268
+ middleware: [logger(), nonNegativeValidator]
269
+ >>>>>>> v3
270
+ });
271
+
272
+ score.set(10); // logs: "Setting value: 10"
273
+ score.set(-1); // throws: "Value must be non-negative!"
274
+ ```
275
+
276
+ ---
277
+
278
+ ## History (undo/redo)
279
+
280
+ ```ts
281
+ import { chunk } from "stunk";
282
+ import { history } from "stunk/middleware";
283
+
284
+ const count = chunk(0);
285
+ const tracked = history(count);
286
+
287
+ tracked.set(1);
288
+ tracked.set(2);
289
+ tracked.undo(); // 1
290
+ tracked.redo(); // 2
291
+ tracked.reset(); // 0 — clears history too
292
+ ```
293
+
294
+ ---
295
+
296
+ ## Persist
297
+
298
+ ```ts
299
+ import { chunk } from "stunk";
300
+ import { persist } from "stunk/middleware";
301
+
302
+ const theme = chunk<"light" | "dark">("light");
303
+ const saved = persist(theme, { key: "theme" });
304
+
305
+ saved.set("dark"); // saved to localStorage
306
+ saved.clearStorage(); // remove from localStorage
307
+ ```
308
+
309
+ ---
310
+
311
+ ## React
312
+
313
+ ```tsx
314
+ import { chunk, computed } from "stunk";
315
+ import { useChunk, useChunkValue, useAsyncChunk, useMutation } from "stunk/react";
316
+
317
+ const counter = chunk(0);
318
+ const double = computed(() => counter.get() * 2);
319
+
320
+ function Counter() {
321
+ const [count, setCount] = useChunk(counter);
322
+ const doubled = useChunkValue(double);
323
+
324
+ return (
325
+ <div>
326
+ <<<<<<< HEAD
327
+ <h2>{data?.name}</h2>
328
+ <p>{data?.email}</p>
329
+ <button onClick={reload}>Reload</button>
330
+ =======
331
+ <p>Count: {count} — Doubled: {doubled}</p>
332
+ <button onClick={() => setCount((n) => n + 1)}>+</button>
333
+ >>>>>>> v3
334
+ </div>
335
+ );
336
+ }
337
+
338
+ // Async
339
+ function PostList() {
340
+ const { data, loading, error } = useAsyncChunk(postsChunk);
341
+ if (loading) return <p>Loading...</p>;
342
+ return <ul>{data?.map(p => <li key={p.id}>{p.title}</li>)}</ul>;
343
+ }
344
+
345
+ // Mutation
346
+ function CreatePostForm() {
347
+ const { mutate, loading, error } = useMutation(createPost);
348
+
349
+ const handleSubmit = async (data: NewPost) => {
350
+ const { error } = await mutate(data);
351
+ if (!error) router.push("/posts");
352
+ };
353
+ }
354
+ ```
355
+
356
+ <<<<<<< HEAD
357
+ 👉 [See full explanation in docs](https://stunk.dev/useAysncChunk.html)
358
+ =======
359
+ ---
360
+ >>>>>>> v3
361
+
362
+ ## Package exports
363
+
364
+ | Import | Contents |
365
+ | ------------------ | --------------------------------------------------------------- |
366
+ | `stunk` | `chunk`, `computed`, `select`, `batch`, `isChunk`, and more |
367
+ | `stunk/react` | `useChunk`, `useChunkValue`, `useAsyncChunk`, `useInfiniteAsyncChunk`, `useMutation` |
368
+ | `stunk/query` | `asyncChunk`, `infiniteAsyncChunk`, `combineAsyncChunks`, `mutation`, `configureQuery` |
369
+ | `stunk/middleware` | `history`, `persist`, `logger`, `nonNegativeValidator` |
370
+
371
+ <<<<<<< HEAD
372
+ ```typescript
373
+ import { chunk } from "stunk";
374
+ import { useChunkValue } from "stunk/react";
375
+
376
+ const count = chunk<number>(0);
377
+
378
+ const CounterDisplay = () => {
379
+ const value = useChunkValue(count);
380
+
381
+ return <p>Count: {value}</p>;
382
+ };
383
+ ```
384
+
385
+ 👉 [See full explanation in docs](https://stunk.dev/read-only-values.html)
386
+
387
+ Live Examples:
388
+
389
+ 👉 [Visit](https://stunk-examples.dev/)
390
+
391
+ Coding Examples:
392
+
393
+ 👉 [Visit](https://stunk.dev/examples.html)
394
+
395
+ Further Examples:
396
+
397
+ 👉 [Visit](https://github.com/I-am-abdulazeez/stunk-examples/)
398
+ =======
399
+ ---
400
+ >>>>>>> v3
401
+
402
+ ## Contributing
403
+
404
+ Contributions are welcome — open a [pull request](https://github.com/I-am-abdulazeez/stunk/pulls) or [issue](https://github.com/I-am-abdulazeez/stunk/issues).
405
+
406
+ ## License
407
+
408
+ MIT