@inglorious/store 12.6.2 → 12.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,1890 +3,64 @@
3
3
  [![NPM version](https://img.shields.io/npm/v/@inglorious/store.svg)](https://www.npmjs.com/package/@inglorious/store)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
 
6
- A Redux-compatible, ECS-inspired state library that makes state management as elegant as game logic.
6
+ An entity-based state store, inspired by game engines and compatible with Redux's tooling. State is a map of plain entities, behavior lives in types, and everything that happens is an event.
7
7
 
8
- **Drop-in replacement for Redux.** Works with `react-redux` and Redux DevTools. Borrows concepts from Entity-Component-System architectures and Functional Programming to provide an environment where you can write simple, predictable, and testable code.
8
+ **[Documentation](https://inglorious.dev/store/)**
9
9
 
10
- ```javascript
11
- // from redux
12
- import { createStore } from "redux"
13
- // to
14
- import { createStore } from "@inglorious/store"
15
- ```
16
-
17
- ---
18
-
19
- ## Why Inglorious Store?
20
-
21
- Redux is powerful but verbose. You need action creators, reducers, middleware for async operations, and a bunch of decisions about where logic should live. Redux Toolkit cuts the boilerplate, but you're still writing a lot of ceremony.
22
-
23
- Inglorious Store eliminates the boilerplate entirely with an **entity-based architecture** inspired by game engines. Some of the patterns that power AAA games now power your state management.
24
-
25
- Game engines solved state complexity years ago — Inglorious Store brings those lessons to web development.
26
-
27
- **Key benefits:**
28
-
29
- - ✅ Drop-in Redux replacement (same API with `react-redux`)
30
- - ✅ Entity-based state (manage multiple instances effortlessly)
31
- - ✅ No action creators, thunks, or slices
32
- - ✅ Predictable, testable, purely functional code
33
- - ✅ Built-in lifecycle events (`add`, `remove`, `patch`, `replace`)
34
- - ✅ 10x faster immutability than Redux Toolkit (Mutative vs Immer)
35
-
36
- ---
37
-
38
- ## Quick Comparison: Redux vs RTK vs Inglorious Store
39
-
40
- ### Redux
41
-
42
- ```javascript
43
- // Action creators
44
- const addTodo = (text) => ({ type: "ADD_TODO", payload: text })
45
-
46
- // Reducer
47
- const todosReducer = (state = [], action) => {
48
- switch (action.type) {
49
- case "ADD_TODO":
50
- return [...state, { id: Date.now(), text: action.payload }]
10
+ ## Install
51
11
 
52
- case "OTHER_ACTION":
53
- // Handle other action
54
-
55
- default:
56
- return state
57
- }
58
- }
59
-
60
- // Store setup
61
- const store = configureStore({
62
- reducer: {
63
- work: todosReducer,
64
- personal: todosReducer,
65
- },
66
- })
67
-
68
- store.dispatch({ type: "ADD_TODO", payload: "Buy groceries" })
69
- store.dispatch({ type: "OTHER_ACTION" })
12
+ ```bash
13
+ pnpm add @inglorious/store
70
14
  ```
71
15
 
72
- ### Redux Toolkit
16
+ ## In a few lines
73
17
 
74
18
  ```javascript
75
- const otherAction = createAction("app:otherAction")
76
-
77
- const todosSlice = createSlice({
78
- name: "todos",
79
- initialState: [],
80
- reducers: {
81
- addTodo: (state, action) => {
82
- state.push({ id: Date.now(), text: action.payload })
83
- },
84
- },
85
- extraReducers: (builder) => {
86
- builder.addCase(otherAction, (state, action) => {
87
- // Handle external action
88
- })
89
- },
90
- })
91
-
92
- const store = configureStore({
93
- reducer: {
94
- work: todosSlice.reducer,
95
- personal: todosSlice.reducer,
96
- },
97
- })
98
-
99
- store.dispatch(slice.actions.addTodo("Buy groceries"))
100
- store.dispatch(otherAction())
101
- ```
102
-
103
- ### Inglorious Store
19
+ import { createStore } from "@inglorious/store"
104
20
 
105
- ```javascript
106
- // Define entity types and their behavior
107
21
  const types = {
108
- todoList: {
109
- addTodo(entity, text) {
110
- entity.todos.push({ id: Date.now(), text })
111
- },
112
-
113
- otherAction(entity) {
114
- // Handle other action
22
+ TodoList: {
23
+ todoAdd(entity, text) {
24
+ entity.todos.push({ id: Date.now(), text, isDone: false })
115
25
  },
116
26
  },
117
27
  }
118
28
 
119
- // Define initial entities
120
29
  const entities = {
121
30
  work: { type: "TodoList", todos: [] },
122
31
  personal: { type: "TodoList", todos: [] },
123
32
  }
124
33
 
125
- // Create store
126
- const store = createStore({ types, entities })
127
-
128
- store.dispatch({ type: "addTodo", payload: "Buy groceries" })
129
- store.dispatch({ type: "otherAction" })
130
-
131
- // or, even better:
132
- store.notify("addTodo", "Buy groceries")
133
- store.notify("otherAction")
134
-
135
- // same result, 10x simpler
136
- ```
137
-
138
- **Key differences:**
139
-
140
- - ❌ No action creators
141
- - ❌ No switch statements or cases
142
- - ❌ No slice definitions with extraReducers
143
- - ✅ Define what each entity type can do
144
- - ✅ Add multiple instances by adding entities, not code
145
-
146
- ---
147
-
148
- ## Core Concepts
149
-
150
- ### 🎮 Entities and Types
151
-
152
- State consists of **entities** (instances) that have a **type** (behavior definition). Think of a type as a class and entities as instances:
153
-
154
- ```javascript
155
- const types = {
156
- todoList: {
157
- addTodo(entity, text) {
158
- entity.todos.push({ id: Date.now(), text })
159
- },
160
- toggle(entity, id) {
161
- const todo = entity.todos.find((t) => t.id === id)
162
- if (todo) todo.completed = !todo.completed
163
- },
164
- },
165
-
166
- settings: {
167
- setTheme(entity, theme) {
168
- entity.theme = theme
169
- },
170
- },
171
- }
172
-
173
- const entities = {
174
- workTodos: { type: "TodoList", todos: [], priority: "high" },
175
- personalTodos: { type: "TodoList", todos: [], priority: "low" },
176
- settings: { type: "Settings", theme: "dark", language: "en" },
177
- }
178
- ```
179
-
180
- **Why this matters:**
181
-
182
- - Same behavior applies to all instances of that type
183
- - No need to write separate code for each instance
184
- - Your mental model matches your code structure
185
-
186
- ### 🔄 Event Handlers (Not Methods)
187
-
188
- Even though it looks like types expose methods, they are actually **event handlers**, very similar to Redux reducers. There are a few differences though:
189
-
190
- 1. Just like RTK reducers, you can mutate the entity directly since event handlers are using an immutability library under the hood. Not Immer, but Mutative — which claims to be 10x faster than Immer.
191
-
192
- ```javascript
193
- const types = {
194
- counter: {
195
- increment(counter) {
196
- counter.value++ // Looks like mutation, immutable in reality
197
- },
198
- },
199
- }
200
- ```
201
-
202
- 2. Event handlers accept as arguments the current entity, the event payload, and an API object that exposes a few convenient methods:
203
-
204
- ```javascript
205
- const types = {
206
- counter: {
207
- increment(counter, value, api) {
208
- api.getEntities() // access the whole state in read-only mode
209
- api.getEntity(id) // access some other entity in read-only mode
210
- api.select(selector) // run a selector against the whole state
211
- api.notify(type, payload) // similar to dispatch. Yes, you can dispatch inside of a reducer!
212
- api.dispatch(action) // optional, if you prefer Redux-style dispatching
213
- },
214
- },
215
- }
216
- ```
217
-
218
- ---
219
-
220
- ## Installation & Setup
221
-
222
- The Inglorious store, just like Redux, can be used standalone. However, it's commonly used together with component libraries such as React.
223
-
224
- ### Basic Setup with `react-redux`
225
-
226
- ```javascript
227
- import { createStore } from "@inglorious/store"
228
- import { Provider, useSelector, useDispatch } from "react-redux"
229
-
230
- // 1. Define entity types
231
- const types = {
232
- counter: {
233
- increment(counter) {
234
- counter.value++
235
- },
236
- decrement(counter) {
237
- counter.value--
238
- },
239
- },
240
- }
241
-
242
- // 2. Define initial entities
243
- const entities = {
244
- counter1: { type: "Counter", value: 0 },
245
- }
246
-
247
- // 3. Create the store
248
34
  const store = createStore({ types, entities })
249
35
 
250
- // 4. Provide the store with react-redux
251
- function App() {
252
- return (
253
- <Provider store={store}>
254
- <Counter />
255
- </Provider>
256
- )
257
- }
258
-
259
- // 5. Wire components to the store
260
- function Counter() {
261
- const dispatch = useDispatch()
262
- const count = useSelector((state) => state.counter1.value)
263
-
264
- return (
265
- <div>
266
- <p>{count}</p>
267
- <button onClick={() => dispatch({ type: "increment" })}>+</button>
268
- <button onClick={() => dispatch({ type: "decrement" })}>-</button>
269
- </div>
270
- )
271
- }
272
- ```
273
-
274
- ### With `@inglorious/react-store` (Recommended)
275
-
276
- For React applications, `@inglorious/react-store` provides a set of hooks and a Provider that are tightly integrated with the store. It's a lightweight wrapper around `react-redux` that offers a more ergonomic API.
277
-
278
- ```javascript
279
- import { createStore } from "@inglorious/store"
280
- import { createReactStore } from "@inglorious/react-store"
281
-
282
- const store = createStore({ types, entities })
283
-
284
- export const { Provider, useSelector, useNotify } = createReactStore(store)
285
-
286
- function App() {
287
- return (
288
- // No store prop needed!
289
- <Provider>
290
- <Counter />
291
- </Provider>
292
- )
293
- }
294
-
295
- function Counter() {
296
- const notify = useNotify() // less verbose than dispatch
297
- const count = useSelector((state) => state.counter1.value)
298
-
299
- return (
300
- <div>
301
- <p>{count}</p>
302
- <button onClick={() => notify("increment")}>+</button> // simplified
303
- syntax
304
- <button onClick={() => notify("decrement")}>-</button>
305
- </div>
306
- )
307
- }
308
- ```
309
-
310
- The package is fully typed, providing a great developer experience with TypeScript.
311
-
312
- ---
313
-
314
- ## Core Features
315
-
316
- ### 🎮 Entity-Based State
317
-
318
- The real power: add entities dynamically without code changes.
319
-
320
- **Redux/RTK:** To manage three counters, you can reuse a reducer. But what if you want to add a new counter at runtime? Your best option is probably to reshape the whole state.
321
-
322
- ```javascript
323
- // The original list of counters:
324
- const store = configureStore({
325
- reducer: {
326
- counter1: counterReducer,
327
- counter2: counterReducer,
328
- counter3: counterReducer,
329
- },
330
- })
331
-
332
- // becomes:
333
- const store = configureStore({
334
- reducer: {
335
- counters: countersReducer,
336
- },
337
- })
338
-
339
- // with extra actions to manage adding/removing counters:
340
- store.dispatch({ type: "addCounter", payload: "counter4" })
341
- ```
342
-
343
- **Inglorious Store** makes it trivial:
344
-
345
- ```javascript
346
- const types = {
347
- counter: {
348
- increment(entity) {
349
- entity.value++
350
- },
351
- },
352
- }
353
-
354
- const entities = {
355
- counter1: { type: "Counter", value: 0 },
356
- counter2: { type: "Counter", value: 0 },
357
- counter3: { type: "Counter", value: 0 },
358
- }
359
-
360
- store.notify("add", { id: "counter4", type: "Counter", value: 0 })
361
- ```
362
-
363
- Inglorious Store has a few built-in events that you can use:
364
-
365
- - `add`: adds a new entity to the state. Triggers a `create` lifecycle event.
366
- - `remove`: removes an entity from the state. Triggers a `destroy` lifecycle event.
367
- - `patch`: changes some of a standing entity and leaves the rest alone.
368
- - `replace`: installs a new configuration on a standing entity, dropping what it does
369
- not mention.
370
-
371
- `patch` and `replace` cover the case `add` and `remove` do not: changing something that is
372
- already in the world without taking it out of it. They are the same pair the web settled
373
- long ago — `POST`, `DELETE`, `PUT`, `PATCH` — for the same reason:
374
-
375
- ```javascript
376
- // A patch touches only what it names. Anything else the entity already had survives,
377
- // which is what makes it safe to nudge part of something mid-flight.
378
- store.notify("patch", { id: "counter1", value: 10 })
379
-
380
- // A replace says the whole of it is different, so anything it does not name is gone.
381
- store.notify("replace", { id: "counter1", type: "Counter", value: 10 })
382
- ```
383
-
384
- A field set to `undefined` is set to _nothing_ in either, rather than being left alone:
385
-
386
- ```javascript
387
- // The key stops being mapped. This is not the same as saying nothing about it, which
388
- // would leave whatever it was mapped to last time standing.
389
- store.notify("patch", {
390
- id: "keyboard",
391
- mapping: { Escape: "pause", ArrowUp: undefined },
392
- })
393
- ```
394
-
395
- Neither runs `create` or `destroy`: the entity never stopped standing, and something that
396
- was never removed cannot have been destroyed. Naming a different `type` in either moves
397
- the entity onto that type's handlers.
398
-
399
- The practical use is a world whose rules change with its state — a keyboard whose keys
400
- mean one thing on a menu and another in play:
401
-
402
- ```javascript
403
- import { fsm } from "@inglorious/store/fsm"
404
- import { scenes } from "@inglorious/store/scenes"
405
-
406
- const types = {
407
- Keyboard: { keyDown: (entity, key) => report(key) },
408
- Game: [
409
- scenes({
410
- menu: () => [{ id: "keyboard", type: "Keyboard", mapping: MENU_KEYS }],
411
- play: () => [{ id: "keyboard", type: "Keyboard", mapping: PLAY_KEYS }],
412
- }),
413
- fsm({/* … */}),
414
- ],
415
- }
416
- ```
417
-
418
- The keyboard is one keyboard, not two: the mapping is patched when the state moves, and
419
- `isDeepEqual` from `@inglorious/utils` is what tells the two apart.
420
-
421
- The lifecycle events can be used to define event handlers similar to constructor and destructor methods in OOP:
422
-
423
- > Note: these special lifecycle events are not broadcast: they are visible only to the added/removed entity!
424
-
425
- ```javascript
426
- const types = {
427
- counter: {
428
- create(entity) {
429
- entity.createdAt = Date.now()
430
- },
431
-
432
- destroy(entity) {
433
- entity.destroyedAt = Date.now()
434
- },
435
- },
436
- }
437
- ```
438
-
439
- ### 🔊 Event Broadcasting
440
-
441
- Events are broadcast to all entities via pub/sub. Every entity handler receives every event of that type, just like it does in Redux.
442
-
443
- ```javascript
444
- const types = {
445
- todoList: {
446
- taskCompleted(entity, taskId) {
447
- const task = entity.tasks.find((t) => t.id === taskId)
448
- if (task) task.completed = true
449
- },
450
- },
451
- stats: {
452
- taskCompleted(entity, taskId) {
453
- entity.completedCount++
454
- },
455
- },
456
- notifications: {
457
- taskCompleted(entity, taskId) {
458
- entity.messages.push("Nice! Task completed.")
459
- },
460
- },
461
- }
462
-
463
- // One notify call, all three entity types respond
464
- store.notify("taskCompleted", "task123")
465
- ```
466
-
467
- In RTK, such action would have be to be defined outside of the slice with `createAction` and then processed with the builder callback notation inside of the `extraReducers` section.
468
-
469
- - What if you want to notify the event only to entities of one specific type? Define an event handler for that event only on that type.
470
- - What if you want to notify the event only on one entity of that type? Add an if that checks if the entity should be bothered or not by it.
471
-
472
- ```javascript
473
- const types = {
474
- todoList: {
475
- toggle(entity, id) {
476
- // This runs for EVERY todoList entity, but only acts if it's the right one
477
- if (entity.id !== id) return
478
-
479
- const todo = entity.todos.find((t) => t.id === id)
480
- if (todo) todo.completed = !todo.completed
481
- },
482
- },
483
- }
484
-
485
- // Broadcast to all todo lists
486
- store.notify("toggle", "todo1")
487
- // Each list's toggle handler runs; only the one with todo1 actually updates
488
- ```
489
-
490
- Alternatively, you can use the **targeted notification syntax** to filter events at the dispatch level:
491
-
492
- - `notify("type:event")`: notifies only entities of a specific type.
493
- - `notify("#id:event")`: notifies only a specific entity by ID.
494
- - `notify("type#id:event")`: notifies a specific entity of a specific type.
495
-
496
- ```javascript
497
- const types = {
498
- todoList: {
499
- toggle(entity) {
500
- const todo = entity.todos.find((t) => t.id === entity.id)
501
- if (todo) todo.completed = !todo.completed
502
- },
503
- },
504
- }
505
-
506
- // Notify only the entity with ID 'work'
507
- store.notify("#todo1:toggle")
508
- ```
509
-
510
- ### ⚡ Async Operations
511
-
512
- In **Redux/RTK**, logic should be written inside pure functions as much as possible — specifically in reducers, not action creators. But what if I need to access some other part of the state that is not visible to the reducer? What if I need to combine async behavior with sync behavior? This is where the choice of "where does my logic live?" matters.
513
-
514
- In **Inglorious Store:** your event handlers can be async, and you get deterministic behavior automatically. Inside an async handler, you can access other parts of state (read-only), and you can trigger other events via `api.notify()`. Even if we give up on some purity, everything still maintains predictability because of the underlying **event queue**:
515
-
516
- ```javascript
517
- const types = {
518
- todoList: {
519
- async loadTodos(entity, payload, api) {
520
- try {
521
- entity.loading = true
522
- const { name } = api.getEntity("user")
523
- const response = await fetch(`/api/todos/${name}`)
524
- const data = await response.json()
525
- api.notify("todosLoaded", data)
526
- } catch (error) {
527
- api.notify("loadFailed", error.message)
528
- }
529
- },
530
-
531
- todosLoaded(entity, todos) {
532
- entity.todos = todos
533
- entity.loading = false
534
- },
535
-
536
- loadFailed(entity, error) {
537
- entity.error = error
538
- entity.loading = false
539
- },
540
- },
541
- }
542
- ```
543
-
544
- Notice: you don't need pending/fulfilled/rejected actions. You stay in control of the flow — no hidden action chains. The `api` object passed to handlers provides:
545
-
546
- - **`api.getEntities()`** - read entire state
547
- - **`api.getEntity(id)`** - read one entity
548
- - **`api.select(selector)`** - run a selector against the state
549
- - **`api.notify(type, payload)`** - trigger other events (queued, not immediate)
550
- - **`api.dispatch(action)`** - optional, if you prefer Redux-style dispatching
551
- - **`api.getTypes()`** - access type definitions (mainly for middleware/plugins)
552
- - **`api.getType(typeName)`** - access type definition (mainly for overrides)
553
-
554
- All events triggered via `api.notify()` enter the queue and process together, maintaining predictability and testability.
555
-
556
- Two things to keep in mind:
557
-
558
- - **`entity` ends at the first `await`.** `entity`, and every object or array read from it, is a draft of the current update, revoked when the update ends, and the update does not wait for your `await`. After it, writing to `entity` or reading anything taken from it throws. Write before the first `await`, then notify an event that does the rest, as `todosLoaded` does above. The same goes for payloads: pass a copy (`{ ...entity.values }`), not the draft, to a handler that reads it after an `await`.
559
- - **`api.getEntity()` reads the state from before the update.** A handler cannot see what an earlier handler in the same chain of events changed: see [State swapping](#state-swapping).
560
-
561
- ### `handleRequest`
562
-
563
- Most async work is a request whose progress the entity shows: loading, then the result or what went wrong. `handleRequest` does that bookkeeping, and it's the one to reach for first:
564
-
565
- ```ts
566
- import { handleRequest } from "@inglorious/store/async"
567
-
568
- const JobList = {
569
- ...handleRequest("search", {
570
- run: (query) => api.searchJobs(query),
571
- success(entity, jobs) {
572
- entity.jobs = jobs
573
- },
574
- }),
575
- }
576
-
577
- api.notify("#jobList:search", "photographer")
578
- ```
579
-
580
- - **Status**: `entity.status` is `"loading"` from the start, then `"success"` or `"error"`. Set its first value, such as `"idle"`, in `create`.
581
- - **Error**: `entity.error` is cleared when a call starts and set when it fails, to the error's message by default. `toError` turns it into what the screen needs, such as a translation key. The `error` handler receives that value after it is set, and can change what the entity shows, such as moving to another step for an error it expects.
582
- - **Only the latest call counts**: the answer of a call that a newer one replaced is dropped, success and failure alike, so a slow search never overwrites a quicker, later one. `isLatestOnly: false` lets every call count, as when saving several items at once.
583
- - **Several requests on one entity**: give each its own fields.
584
- - **Scope**: `scope` sends the lifecycle events to the entity (the default), its type or everyone, as in `handleAsync` (see [Event scoping](#event-scoping)).
585
-
586
- ```ts
587
- const Profile = {
588
- ...handleRequest(
589
- "save",
590
- {
591
- run: (profile) => api.saveProfile(profile),
592
- },
593
- { status: "saveStatus", error: "saveError", toError: errorKey },
594
- ),
595
- ...handleRequest(
596
- "avatarUpload",
597
- { run: uploadAvatar },
598
- { status: "avatarStatus", error: "avatarError" },
599
- ),
600
- }
601
- ```
602
-
603
- To wait until someone stops typing, debounce the event that starts the request with `withDebounce` from `@inglorious/web`. Debouncing starts fewer calls; dropping outdated answers covers the ones that still overlap:
604
-
605
- ```ts
606
- const types = { JobList: [JobList, withDebounce(300, ["search"])] }
36
+ store.notify("todoAdd", "Buy milk") // every TodoList
37
+ store.notify("#work:todoAdd", "Finish report") // only `work`
607
38
  ```
608
39
 
609
- The handlers and events are those of `handleAsync`, below, so `optimistic` wraps a request too.
40
+ - An **entity** is a plain object with an `id` and a `type`. A **type** is an object of event handlers, `handler(entity, payload, api)`, which mutate the entity they are given; [Mutative](https://github.com/unadlib/mutative) turns the mutation into a new immutable state.
41
+ - An **event** reaches every entity whose type handles it, or one type (`"TodoList:todoAdd"`), or one entity (`"#work:todoAdd"`). Handlers notify further events through `api.notify`, and the queue applies them in order, one transaction each.
42
+ - Entities have a lifecycle: `add` and `remove` run their `create` and `destroy`, where a type opens and closes what it needs from the outside world.
610
43
 
611
- ### `handleAsync`
44
+ ## What's in it
612
45
 
613
- `handleAsync` is the lower level `handleRequest` is built on: it keeps no status and no error, and lets every call's answer through. Use it for async work the entity doesn't show, such as saving a preference in the background, a call whose failure is only logged, or a check that must keep its last answer when it fails.
46
+ - [`handleRequest` and `handleAsync`](https://inglorious.dev/store/advanced/async-operations): the lifecycle of an async call as events, with status and error kept on the entity, outdated answers dropped, and `optimistic` updates.
47
+ - [`fsm` and `scenes`](https://inglorious.dev/store/advanced/state-machines): a type that answers events by state, and the entities that stand in each state.
48
+ - [`withStorage`](https://inglorious.dev/store/api/reference#withstorage-fields-options): fields kept in local storage as a byproduct of the entity.
49
+ - [Systems and middlewares](https://inglorious.dev/store/guide/core-concepts#composition): handlers that see every entity at once, and functions that wrap the store.
50
+ - [`compute`](https://inglorious.dev/store/api/reference#compute-fn-selectors): memoized derived state, with `createSelector` as its Redux-compatible alias.
51
+ - [Redux DevTools](https://inglorious.dev/web/advanced/devtools) and `react-redux`: the store has `subscribe`, `getState` and `dispatch`, so a React app can adopt it as its Redux store first and move its components to [Inglorious Web](https://inglorious.dev/web/) later. [`@inglorious/react-store`](https://www.npmjs.com/package/@inglorious/react-store) adds `useEntity` and `useNotify`.
52
+ - [Testing](https://inglorious.dev/store/advanced/testing): `trigger(entity, handler, payload)` runs a handler and returns the new entity and the events it notified, with no store.
53
+ - [TypeScript](https://inglorious.dev/store/api/reference#type-safety-typescript): typed entities, handlers, payloads and events, with no casts.
614
54
 
615
- The `handleAsync` helper generates a set of event handlers representing the lifecycle of an async operation.
55
+ ## Two rules
616
56
 
617
- ```ts
618
- handleAsync(type, handlers, options?)
619
- ```
620
-
621
- Think of the flow like a newspaper article:
622
-
623
- - `start` writes the headline and sets the scene
624
- - `run` gathers the reporting
625
- - `success` publishes the story
626
- - `error` prints the correction
627
- - `finally` archives the notes
628
-
629
- Example:
630
-
631
- ```ts
632
- import { handleAsync } from "@inglorious/store/async"
633
-
634
- const todoList = {
635
- ...handleAsync("fetchTodos", {
636
- async run(payload) {
637
- const res = await fetch("/api/todos")
638
- return res.json()
639
- },
640
-
641
- success(entity, todos) {
642
- entity.todos = todos
643
- },
644
-
645
- error(entity, error) {
646
- entity.error = error.message
647
- },
648
-
649
- finally(entity) {
650
- entity.loading = false
651
- },
652
- }),
653
- }
654
- ```
57
+ - **A handler writes to the entity it is given, before its first `await`.** The entity is a draft that lives until the update ends; after an `await`, notify an event that does the writing, or use `handleRequest`.
58
+ - **An event's handlers read the state as the previous event left it.** Whatever order they run in, they see the same world, and the next event sees what they changed.
655
59
 
656
- ---
60
+ ## Where it goes
657
61
 
658
- ### Lifecycle events
62
+ Standalone, in a React app through `react-redux` or `@inglorious/react-store`, under [Inglorious Web](https://inglorious.dev/web/) for the DOM, under [Inglorious Engine](https://inglorious.dev/engine/) for games, or on a server with [`@inglorious/server`](https://www.npmjs.com/package/@inglorious/server) for multiplayer.
659
63
 
660
- Triggering `fetchTodos` emits the following events:
661
-
662
- ```
663
- fetchTodos
664
- fetchTodosRun
665
- fetchTodosSuccess | fetchTodosError
666
- fetchTodosFinally
667
- ```
668
-
669
- Each step is an **event handler**, not an implicit callback.
670
-
671
- Each call gets a `callId`, and every event of that call carries it: `Start` and `Run` get `{ payload, callId }`, `Success` gets `{ result, callId }`, `Error` gets `{ error, callId }` and `Finally` gets `{ callId }`. The `start`, `run`, `success`, `error` and `finally` handlers still receive the payload, result or error alone; the `callId` matters to code that listens to the events directly, such as `optimistic`.
672
-
673
- ---
674
-
675
- ### Optional `start` handler
676
-
677
- Use `start` for synchronous setup (loading flags, resets, optimistic state):
678
-
679
- ```ts
680
- handleAsync("save", {
681
- start(entity) {
682
- entity.loading = true
683
- },
684
- async run(payload) {
685
- return api.save(payload)
686
- },
687
- })
688
- ```
689
-
690
- If omitted, no `Start` event is generated.
691
-
692
- ### `optimistic`
693
-
694
- Wrap an async behavior to apply a shallow optimistic patch on `Start` and roll it back on `Error`.
695
-
696
- This helper lives at `@inglorious/store/optimistic`, so only users who need it import it.
697
-
698
- ```ts
699
- import { handleAsync } from "@inglorious/store/async"
700
- import { optimistic } from "@inglorious/store/optimistic"
701
-
702
- const saveItem = optimistic(
703
- handleAsync("saveItem", {
704
- async run(payload) {
705
- const res = await fetch("/api/items", {
706
- method: "POST",
707
- body: JSON.stringify(payload),
708
- })
709
- if (!res.ok) throw new Error("Failed")
710
- return res.json()
711
- },
712
- success(entity, result) {
713
- entity.items = entity.items.map((item) =>
714
- item.id === result.tempId ? result : item,
715
- )
716
- },
717
- }),
718
- (entity, payload) => ({
719
- items: [
720
- ...entity.items,
721
- {
722
- id: payload.tempId,
723
- title: payload.title,
724
- completed: payload.completed,
725
- pending: true,
726
- },
727
- ],
728
- }),
729
- )
730
- ```
731
-
732
- If the optimistic state does not depend on the payload, use a static patch instead:
733
-
734
- ```ts
735
- const saveSettings = optimistic(
736
- handleAsync("saveSettings", {
737
- async run(payload) {
738
- return api.save(payload)
739
- },
740
- }),
741
- { status: "saving" },
742
- )
743
- ```
744
-
745
- The wrapper snapshots the keys in the patch, applies them in `Start`, restores the previous values in `Error`, and leaves `Success`/`Finally` handlers in control of cleanup.
746
-
747
- Each call keeps its own snapshot, so saves on the same entity can overlap. A failed call restores the keys it patched, except those a later pending call patched too: those go back to what they were before both once that call fails as well, or stay as that call left them.
748
-
749
- A patch built on the current value, such as a list with a temporary item added, cannot be undone key by key when two calls change the same list. Give `rollback` to undo the call's own change in place of restoring the snapshot:
750
-
751
- ```ts
752
- const addTodo = optimistic(
753
- handleAsync("addTodo", {
754
- async run(todo) {
755
- return api.add(todo)
756
- },
757
- }),
758
- (entity, todo) => ({ todos: [...entity.todos, { ...todo, pending: true }] }),
759
- {
760
- rollback(entity, todo) {
761
- entity.todos = entity.todos.filter(({ id }) => id !== todo.id)
762
- },
763
- },
764
- )
765
- ```
766
-
767
- ---
768
-
769
- ### Reading a store from outside a handler
770
-
771
- `api.getEntity` is the answer during a handler. Outside one — a test driving a world, or
772
- anything else holding the store rather than an event — the store says the same thing
773
- itself:
774
-
775
- ```javascript
776
- store.getEntity("user") // one entity, or undefined
777
- store.getState() // the lot
778
- ```
779
-
780
- There is one lookup rather than two spellings of it: `api.getEntity` asks the store.
781
-
782
- ### Event scoping
783
-
784
- By default, lifecycle events are **scoped to the triggering entity**:
785
-
786
- ```
787
- #entityId:fetchTodosSuccess
788
- ```
789
-
790
- You can override this behavior:
791
-
792
- ```ts
793
- handleAsync("bootstrap", handlers, { scope: "global" })
794
- ```
795
-
796
- Available scopes:
797
-
798
- - `"entity"` (default)
799
- - `"type"`
800
- - `"global"`
801
-
802
- ---
803
-
804
- > **Key rule:** Async code must not access entities after `await`. All updates happen in event handlers.
805
-
806
- ---
807
-
808
- ### `withStorage`
809
-
810
- The entity is the one source of truth; keeping some of it between visits is a byproduct. `withStorage` brings the fields back when the entity is created, before the type's own `create`, and writes them back after any handler that changes them:
811
-
812
- ```ts
813
- import { withStorage } from "@inglorious/store/storage"
814
-
815
- const Settings = {
816
- create(entity) {
817
- entity.theme ??= "light" // kept from last time, else light
818
- },
819
- themeSet(entity, theme) {
820
- entity.theme = theme // saved along the way
821
- },
822
- }
823
-
824
- const types = {
825
- Settings: [Settings, withStorage(["theme"])],
826
- Draft: [
827
- Draft,
828
- withStorage(["text"], { key: "draft", storage: () => sessionStorage }),
829
- ],
830
- }
831
- ```
832
-
833
- - Nothing reads storage but `withStorage`: the app reads the entity, and the rest follows.
834
- - Put it last in the type's array: it saves after the handlers before it.
835
- - `key` names where the fields go (the entity's id by default), or derives it from the entity. `storage` is any Web Storage, `localStorage` by default.
836
- - Storage that is missing, full or refusing, as in a private window, only means nothing is kept.
837
- - A storage whose `getItem` returns a promise works too, such as Capacitor Preferences through `createNativeStorage` from `@inglorious/web/mobile`. The entity then starts with the type's defaults, and once the storage answers, a `storageRestore` event brings the stored fields back. Nothing is written before that. A type with its own `storageRestore(entity, restored, api)` hears what came back, to announce it. Several `withStorage` on one type each restore their own fields:
838
-
839
- ```javascript
840
- const Session = [
841
- {
842
- create(entity) {
843
- entity.user ??= null
844
- },
845
- storageRestore(entity, restored, api) {
846
- api.notify("sessionChange", { user: entity.user })
847
- },
848
- },
849
- withStorage(["user"], { storage: () => preferences }),
850
- ]
851
- ```
852
-
853
- ---
854
-
855
- ## 🧩 Migrating from Redux Toolkit (RTK)
856
-
857
- Inglorious Store now provides utilities to **gradually migrate from RTK slices and thunks**, leveraging `handleAsync` to simplify async logic.
858
-
859
- ### Converting Async Thunks
860
-
861
- ```javascript
862
- import { convertAsyncThunk } from "@inglorious/store/migration/rtk"
863
-
864
- const fetchTodos = async (userId) => {
865
- const res = await fetch(`/api/users/${userId}/todos`)
866
- return res.json()
867
- }
868
-
869
- const todoHandlers = convertAsyncThunk("fetchTodos", fetchTodos, {
870
- onPending: (entity) => {
871
- entity.status = "loading"
872
- },
873
- onFulfilled: (entity, todos) => {
874
- entity.status = "success"
875
- entity.todos = todos
876
- },
877
- onRejected: (entity, error) => {
878
- entity.status = "error"
879
- entity.error = error.message
880
- },
881
- })
882
- ```
883
-
884
- ```javascript
885
- const todoList = {
886
- init(entity) {
887
- entity.todos = []
888
- entity.status = "idle"
889
- },
890
- ...todoHandlers,
891
- }
892
- ```
893
-
894
- ### Converting Slices
895
-
896
- ```javascript
897
- import { convertSlice } from "@inglorious/store/migration/rtk"
898
-
899
- const todoListType = convertSlice(todosSlice, {
900
- asyncThunks: {
901
- fetchTodos: {
902
- onPending: (entity) => {
903
- entity.status = "loading"
904
- },
905
- onFulfilled: (entity, todos) => {
906
- entity.items = todos
907
- },
908
- onRejected: (entity, error) => {
909
- entity.error = error.message
910
- },
911
- },
912
- },
913
- })
914
- ```
915
-
916
- - Reducers become event handlers automatically.
917
- - Async thunks become `handleAsync` events.
918
- - Initial state is applied via an `init` handler.
919
- - Extra handlers can be added if needed.
920
-
921
- ---
922
-
923
- ### RTK-Style Dispatch Compatibility
924
-
925
- ```javascript
926
- const dispatch = createRTKCompatDispatch(api, "todos")
927
- dispatch({ type: "todos/addTodo", payload: "Buy milk" })
928
- // becomes: api.notify('#todos:addTodo', 'Buy milk')
929
- ```
930
-
931
- > Thunks are **not supported** in compat mode; convert them using `convertAsyncThunk`.
932
-
933
- ---
934
-
935
- ### Migration Guide
936
-
937
- ```javascript
938
- import { createMigrationGuide } from "@inglorious/store/migration/rtk"
939
-
940
- const guide = createMigrationGuide(todosSlice)
941
- console.log(guide)
942
- ```
943
-
944
- Outputs a readable guide mapping RTK calls to Inglorious events.
945
-
946
- ---
947
-
948
- ### 🧪 Testing
949
-
950
- Event handlers are pure functions (or can be treated as such), making them easy to test in isolation, much like Redux reducers. The `@inglorious/store/test` module provides utility functions to make this even simpler.
951
-
952
- #### `trigger(entity, handler, payload, api?)`
953
-
954
- The `trigger` function executes an event handler on a single entity and returns the new state and any events that were dispatched.
955
-
956
- ```javascript
957
- import { trigger } from "@inglorious/store/test"
958
-
959
- // Define your entity handler
960
- function increment(entity, payload, api) {
961
- entity.value += payload.amount
962
- if (entity.value > 100) {
963
- api.notify("overflow", { id: entity.id })
964
- }
965
- }
966
-
967
- // Test it
968
- const { entity, events } = trigger(
969
- { type: "Counter", id: "counter1", value: 99 },
970
- increment,
971
- { amount: 5 },
972
- )
973
-
974
- expect(entity.value).toBe(104)
975
- expect(events).toEqual([{ type: "overflow", payload: { id: "counter1" } }])
976
- ```
977
-
978
- #### `createMockApi(entities)`
979
-
980
- If your handler needs to interact with other entities via the `api`, you can create a mock API. This is useful for testing handlers that read from other parts of the state.
981
-
982
- ```javascript
983
- import { createMockApi, trigger } from "@inglorious/store/test"
984
-
985
- // Create a mock API with some initial entities
986
- const api = createMockApi({
987
- counter1: { type: "Counter", value: 10 },
988
- counter2: { type: "Counter", value: 20 },
989
- })
990
-
991
- // A handler that copies a value from another entity
992
- function copyValue(entity, payload, api) {
993
- const source = api.getEntity(payload.sourceId)
994
- entity.value = source.value
995
- }
996
-
997
- // Trigger the handler with the custom mock API
998
- const { entity } = trigger(
999
- { type: "Counter", id: "counter2", value: 20 },
1000
- copyValue,
1001
- { sourceId: "counter1" },
1002
- api,
1003
- )
1004
-
1005
- expect(entity.value).toBe(10)
1006
- ```
1007
-
1008
- The mock API provides:
1009
-
1010
- - `getEntities()`: Returns all entities (frozen).
1011
- - `getEntity(id)`: Returns a specific entity by ID (frozen).
1012
- - `select(selector)`: Runs a selector against the entities.
1013
- - `dispatch(event)`: Records an event for later assertions.
1014
- - `notify(type, payload)`: A convenience wrapper around `dispatch`.
1015
- - `getEvents()`: Returns all events that were dispatched.
1016
-
1017
- ### 🌍 Systems for Global Logic
1018
-
1019
- When you need to coordinate updates across multiple entities (not just respond to individual events), use systems. Systems run after all entity handlers for the same event, ensuring global consistency, and have write access to the entire state. This concept is the 'S' in the ECS Architecture (Entity-Component-System)!
1020
-
1021
- ```javascript
1022
- const systems = [
1023
- {
1024
- taskCompleted(state, taskId) {
1025
- // Read from multiple todo lists
1026
- const allTodos = Object.values(state)
1027
- .filter((e) => e.type === "todoList")
1028
- .flatMap((e) => e.todos)
1029
-
1030
- // Update global stats
1031
- state.stats.total = allTodos.length
1032
- state.stats.completed = allTodos.filter((t) => t.completed).length
1033
- },
1034
- },
1035
- ]
1036
-
1037
- const store = createStore({ types, entities, systems })
1038
- ```
1039
-
1040
- Systems receive the entire state and can modify any entity. They're useful for cross-cutting concerns, maintaining derived state, or coordinating complex state updates that can't be expressed as individual entity handlers.
1041
-
1042
- ### 🔗 Behavior Composition
1043
-
1044
- A type can be a single behavior object, or an array of behaviors.
1045
-
1046
- ```javascript
1047
- // single-behavior type
1048
- const counter = {
1049
- increment(entity) {
1050
- entity.value++
1051
- },
1052
-
1053
- decrement(entity) {
1054
- entity.value--
1055
- },
1056
- }
1057
-
1058
- // multiple behavior type
1059
- const resettableCounter = [
1060
- counter,
1061
- {
1062
- reset(entity) {
1063
- entity.value = 0
1064
- },
1065
- },
1066
- ]
1067
- ```
1068
-
1069
- A behavior is defined as either an object with event handlers, or a function that takes a type and returns an enhanced behavior (decorator pattern):
1070
-
1071
- ```javascript
1072
- // Base behavior
1073
- const resettable = {
1074
- submit(entity, value) {
1075
- entity.value = ""
1076
- },
1077
- }
1078
-
1079
- // Function that wraps and enhances a behavior
1080
- const validated = (type) => ({
1081
- submit(entity, value, api) {
1082
- if (!value.trim()) return
1083
- type.submit?.(entity, value, api) // remember to always pass all args!
1084
- },
1085
- })
1086
-
1087
- // Another wrapper
1088
- const withLoading = (type) => ({
1089
- submit(entity, value, api) {
1090
- entity.loading = true
1091
- type.submit?.(entity, value, api)
1092
- entity.loading = false
1093
- },
1094
- })
1095
-
1096
- // Compose them together to form a type
1097
- const form = [resettable, validated, withLoading]
1098
- ```
1099
-
1100
- When multiple behaviors define the same event, the later one replaces the earlier: a type has one handler per event. That is why a wrapper like `validated` receives the type built so far and calls `type.submit?.(...)` itself, which is how you build middleware-like patterns: validation, logging, error handling, loading states, etc.
1101
-
1102
- ### 🚦 State Machines
1103
-
1104
- Some entities answer the same event differently depending on the state they are in: a door
1105
- opens when it is closed and does nothing when it is locked. `fsm()` turns a type into a
1106
- finite state machine in the manner of the OOP State pattern, where each state says what it
1107
- answers and the entity's `state` field says which state is in charge:
1108
-
1109
- ```javascript
1110
- import { fsm } from "@inglorious/store/fsm"
1111
-
1112
- const types = {
1113
- Door: [
1114
- {
1115
- // What every state does, unless a state says otherwise
1116
- knock(entity) {
1117
- entity.knocks++
1118
- },
1119
- },
1120
- fsm({
1121
- closed: {
1122
- open(entity) {
1123
- entity.state = "open"
1124
- },
1125
- lock(entity) {
1126
- entity.state = "locked"
1127
- },
1128
- },
1129
- open: {
1130
- close(entity) {
1131
- entity.state = "closed"
1132
- },
1133
- },
1134
- locked: {
1135
- // Takes over knock while locked
1136
- knock(entity, _, api) {
1137
- api.notify("bark")
1138
- },
1139
- unlock(entity) {
1140
- entity.state = "closed"
1141
- },
1142
- },
1143
- }),
1144
- ],
1145
- }
1146
-
1147
- const entities = { door: { type: "Door", state: "closed", knocks: 0 } }
1148
- ```
1149
-
1150
- - A state's handler **replaces** the type's handler for the same event, so the type's
1151
- handler is the default and a state takes it over by naming the event. An event that
1152
- neither the current state nor the type answers is ignored.
1153
- - A handler moves the entity by assigning `entity.state`. An entity with no `state` starts
1154
- in `"default"`.
1155
- - When a handler has actually moved the entity, `fsm` broadcasts
1156
- `stateChange` with `{ entityId, from, to }`. It is broadcast rather than addressed to the
1157
- entity, because what wants to hear it is usually something else, so a listener checks
1158
- `entityId`.
1159
-
1160
- Typical uses: request and connection status, wizards, editors that are viewing, editing or
1161
- saving, media players, drag and drop, and the screens of a game.
1162
-
1163
- #### Scenes
1164
-
1165
- `scenes()` is the usual partner of `fsm()`: the machine says when it moves, and `scenes()`
1166
- says which entities stand in each state. On `create` and on its own `stateChange` it `add`s
1167
- what the new state has, `remove`s what only the old one had, and `patch`es what both have
1168
- but configure differently, comparing entities by `id`:
1169
-
1170
- ```javascript
1171
- import { fsm } from "@inglorious/store/fsm"
1172
- import { scenes } from "@inglorious/store/scenes"
1173
-
1174
- const types = {
1175
- Wizard: [
1176
- scenes({
1177
- account: () => [{ id: "accountForm", type: "AccountForm" }],
1178
- billing: (wizard) => [
1179
- { id: "billingForm", type: "BillingForm", plan: wizard.plan },
1180
- ],
1181
- }),
1182
- fsm({
1183
- account: {
1184
- next(entity) {
1185
- entity.state = "billing"
1186
- },
1187
- },
1188
- }),
1189
- ],
1190
- }
1191
-
1192
- const entities = { wizard: { type: "Wizard", state: "account", plan: "pro" } }
1193
- ```
1194
-
1195
- The entity running the machine keeps what it has up in `scene`.
1196
-
1197
- The name comes from games, where each screen is a scene, but nothing about it is game-specific.
1198
- In a web app it gives entities a lifetime tied to a state: a page's forms and lists exist only
1199
- while you are on it (their `create` and `destroy` can open and close subscriptions), each wizard
1200
- step has its own form, and a logged-out app has a `loginForm` that a logged-in one does not —
1201
- while anything both states share, like a header or a cart, survives the move untouched.
1202
-
1203
- ### ⏱️ Batched Mode
1204
-
1205
- The Inglorious Store features an **event queue**. In the default `auto` update mode, each notified event will trigger and update of the state (same as Redux). But in `manual` update mode, you can process multiple events together before re-rendering:
1206
-
1207
- ```javascript
1208
- const store = createStore({ types, entities, updateMode: "manual" })
1209
-
1210
- // add events to the event queue
1211
- store.notify("playerMoved", { x: 100, y: 50 })
1212
- store.notify("enemyAttacked", { damage: 10 })
1213
- store.notify("particleCreated", { type: "explosion" })
1214
-
1215
- // process them all in batch
1216
- store.update()
1217
- ```
1218
-
1219
- Instead of re-rendering after each event, you can batch them and re-render once. This is what powers high-performance game engines and smooth animations.
1220
-
1221
- ---
1222
-
1223
- ## 🧮 Derived State with `compute`
1224
-
1225
- Inglorious Store is fully compatible with Redux selectors, but it also provides a simpler, more explicit primitive for derived state: **`compute`**.
1226
-
1227
- `compute` lets you derive values from the store state in a predictable and memoized way, without hidden reactivity or dependency graphs.
1228
-
1229
- ### Basic example
1230
-
1231
- ```js
1232
- import { compute } from "@inglorious/store"
1233
-
1234
- const selectCounter = (state) => state.counter1.value
1235
- const selectMultiplier = (state) => state.settings.multiplier
1236
-
1237
- const selectResult = compute(
1238
- (count, multiplier) => count * multiplier,
1239
- [selectCounter, selectMultiplier],
1240
- )
1241
- ```
1242
-
1243
- The returned function is a standard selector:
1244
-
1245
- ```js
1246
- const result = api.select(selectResult)
1247
- ```
1248
-
1249
- And it works seamlessly with `react-redux` or `@inglorious/react-store`:
1250
-
1251
- ```js
1252
- const value = useSelector(selectResult)
1253
- ```
1254
-
1255
- ---
1256
-
1257
- ### How `compute` works
1258
-
1259
- - Each **input selector** is called with the current state
1260
- - The results are compared using **strict equality (`===`)**
1261
- - If none of the inputs changed, the **previous result is reused**
1262
- - If at least one input changed, the result is recomputed
1263
-
1264
- There is:
1265
-
1266
- - ❌ no deep comparison
1267
- - ❌ no proxy-based reactivity
1268
- - ❌ no implicit dependency tracking
1269
-
1270
- Memoization is **explicit and predictable**, based purely on the values returned by your selectors.
1271
-
1272
- ---
1273
-
1274
- ### Why `compute` instead of magic reactivity?
1275
-
1276
- `compute` matches the core philosophy of Inglorious Store:
1277
-
1278
- - derived state is just a function
1279
- - updates are explicit
1280
- - behavior is easy to reason about
1281
- - performance characteristics are obvious
1282
-
1283
- If an input selector returns a new reference, the computation runs again.
1284
- If it doesn’t, it won’t.
1285
-
1286
- No surprises.
1287
-
1288
- ---
1289
-
1290
- ### Zero or single input selectors
1291
-
1292
- `compute` supports any number of inputs — including zero:
1293
-
1294
- ```js
1295
- const selectConstant = compute(() => 42)
1296
- ```
1297
-
1298
- Or just one:
1299
-
1300
- ```js
1301
- const selectDouble = compute(
1302
- (count) => count * 2,
1303
- [(entities) => entities.counter1.value],
1304
- )
1305
- ```
1306
-
1307
- ---
1308
-
1309
- ### `createSelector` (Redux compatibility)
1310
-
1311
- For migration and familiarity, Inglorious Store also exports `createSelector`, which is fully compatible with Redux:
1312
-
1313
- ```js
1314
- import { createSelector } from "@inglorious/store"
1315
-
1316
- const selectResult = createSelector(
1317
- [(state) => state.counter1.value],
1318
- (count) => count * 2,
1319
- )
1320
- ```
1321
-
1322
- Internally, `createSelector` is just an alias for `compute`.
1323
-
1324
- > **Note:** `compute` is the preferred API for new code.
1325
- > `createSelector` exists mainly for Redux compatibility and migration.
1326
-
1327
- ---
1328
-
1329
- ### When to use `compute`
1330
-
1331
- Use `compute` when:
1332
-
1333
- - you need derived or aggregated state
1334
- - you want memoization without magic
1335
- - you want selectors that are easy to test
1336
- - you want predictable recomputation rules
1337
-
1338
- If you already know Redux selectors, you already know how to use `compute` — just with fewer rules and less ceremony.
1339
-
1340
- ---
1341
-
1342
- ## Comparison with Other State Libraries
1343
-
1344
- | Feature | Redux | RTK | Zustand | Jotai | Pinia | MobX | Inglorious Store |
1345
- | ------------------------- | ------------ | ------------ | ---------- | ---------- | ---------- | ---------- | ---------------- |
1346
- | **Boilerplate** | 🔴 High | 🟡 Medium | 🟢 Low | 🟢 Low | 🟡 Medium | 🟢 Low | 🟢 Low |
1347
- | **Multiple instances** | 🔴 Manual | 🔴 Manual | 🔴 Manual | 🔴 Manual | 🟡 Medium | 🟡 Medium | 🟢 Built-in |
1348
- | **Lifecycle events** | 🔴 No | 🔴 No | 🔴 No | 🔴 No | 🔴 No | 🔴 No | 🟢 Yes |
1349
- | **Async logic placement** | 🟡 Thunks | 🟡 Complex | 🟢 Free | 🟢 Free | 🟢 Free | 🟢 Free | 🟢 In handlers |
1350
- | **Redux DevTools** | 🟢 Yes | 🟢 Yes | 🟡 Partial | 🟡 Partial | 🟡 Partial | 🟢 Yes | 🟢 Yes |
1351
- | **Time-travel debugging** | 🟢 Yes | 🟢 Yes | 🔴 No | 🔴 No | 🔴 No | 🟡 Limited | 🟢 Yes |
1352
- | **Testability** | 🟢 Excellent | 🟢 Excellent | 🟡 Good | 🟡 Good | 🟡 Good | 🟡 Medium | 🟢 Excellent |
1353
- | **Immutability** | 🔴 Manual | 🟢 Immer | 🔴 Manual | 🔴 Manual | 🔴 Manual | 🔴 Manual | 🟢 Mutative |
1354
-
1355
- ---
1356
-
1357
- ## API Reference
1358
-
1359
- ### `createStore(options)`
1360
-
1361
- ```javascript
1362
- const store = createStore({
1363
- types, // Object: entity type definitions
1364
- entities, // Object: initial entities
1365
- systems, // Array (optional): global state handlers
1366
- autoCreateEntities, // Boolean (optional): false (default) or true
1367
- updateMode, // String (optional): 'auto' (default) or 'manual'
1368
- updateStrategy, // String (optional): 'structural-sharing' (default) or 'copy-on-dispatch'
1369
- })
1370
- ```
1371
-
1372
- **Returns:** A Redux-compatible store
1373
-
1374
- **Options:**
1375
-
1376
- - **`types`** (required) - Object defining entity type behaviors
1377
- - **`entities`** (required) - Object containing initial entity instances
1378
- - **`systems`** (optional) - Array of global state handlers
1379
- - **`autoCreateEntities`** (optional) - Automatically create singleton entities for types not defined in `entities`:
1380
- - `false` (default) - Only use explicitly defined entities
1381
- - `true` - Auto-create entities matching their type name
1382
- - **`updateMode`** (optional) - Controls when React components re-render:
1383
- - `'auto'` (default) - Automatic updates after each event
1384
- - `'manual'` - Manual control via `api.update()`
1385
- - **`updateStrategy`** (optional) - Controls how the state is copied before queued events are applied:
1386
- - `'structural-sharing'` (default) - Only the entities that actually changed are copied
1387
- - `'copy-on-dispatch'` - Each entity is deep-copied as it is handed out, and updated without a proxy
1388
-
1389
- #### Update Strategy
1390
-
1391
- `updateStrategy` decides how much copying work each update does. It exists because the right
1392
- answer depends on how many entities change per update.
1393
-
1394
- **`'structural-sharing'`** (default) applies events to a draft proxy (via
1395
- [Mutative](https://github.com/pmndrs/mutative)), so only the entities that actually changed
1396
- get copied. Untouched entities keep their previous object reference, which makes
1397
- reference-equality change detection nearly free. This is what you want for UI stores, where a
1398
- handful of entities change per interaction.
1399
-
1400
- **`'copy-on-dispatch'`** deep-copies an entity the first time it is handed to one of its handlers, or read
1401
- by a system, and applies events directly to the copy, with no proxy involved. Entities that nothing
1402
- touches during an update are not copied and keep their previous reference. Writing to a copy costs
1403
- nothing however often it happens, so it scales much better when thousands of entities change every
1404
- frame — the typical case for a game simulation.
1405
-
1406
- Systems receive every entity at once, so each entity a system reads through its first argument is
1407
- copied in case it is written to. A system that only needs to know how things stood should read
1408
- them from `api.getEntities()` and go through its first argument only for what it writes:
1409
-
1410
- ```javascript
1411
- const readouts = {
1412
- update(entities, dt, api) {
1413
- const current = api.getEntities() // read without copying
1414
- const count = Object.keys(current).length
1415
-
1416
- entities.readout.value = `${count} entities` // copies only the readout
1417
- },
1418
- }
1419
- ```
1420
-
1421
- ```javascript
1422
- // A UI store: few entities change, reference equality matters
1423
- const store = createStore({
1424
- types,
1425
- entities,
1426
- updateStrategy: "structural-sharing",
1427
- })
1428
-
1429
- // A game simulation: thousands of entities change every frame
1430
- const store = createStore({
1431
- types,
1432
- entities,
1433
- updateStrategy: "copy-on-dispatch",
1434
- })
1435
- ```
1436
-
1437
- #### State swapping
1438
-
1439
- Both strategies keep the current state intact while the queued events are applied to a separate
1440
- draft, and swap the two only once every event has been processed. Handlers and systems always
1441
- receive that draft as their first argument and mutate it directly, and subscribers are notified
1442
- only after the swap.
1443
-
1444
- A consequence worth knowing: during an update, `api.getEntity()` and `api.getEntities()` read the
1445
- **previous** state, not the in-flight changes. This holds under both strategies, so code that
1446
- needs to read another entity's up-to-date value must go through the event payload, or read it in
1447
- a system that runs after the entity handlers.
1448
-
1449
- ```javascript
1450
- const types = {
1451
- Counter: {
1452
- // Reads the previous value of `other`, not the value set earlier in this same update.
1453
- increment(entity, payload, api) {
1454
- entity.previous = api.getEntity("other").count
1455
- },
1456
- },
1457
- }
1458
- ```
1459
-
1460
- **Caveats for `'copy-on-dispatch'`:**
1461
-
1462
- - Plain objects, arrays, vectors and primitives are copied directly. Anything else must be
1463
- [structured-cloneable](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm):
1464
- DOM nodes and class instances with non-cloneable internals throw a `DataCloneError`. Keep such values in module scope or in a closure inside a behavior factory
1465
- (as the `images()` and `audio()` engine behaviors do) rather than in the state.
1466
- - The state is not frozen, even in `devMode`.
1467
- - Writing to an entity obtained from `api.getEntity()` during an update mutates the _previous_
1468
- state. Whether the write also survives depends on whether that entity has been copied yet, under
1469
- either strategy. Always mutate the entity passed to your handler rather than one fetched through
1470
- the api.
1471
-
1472
- An unsupported strategy throws a `TypeError` at store creation:
1473
-
1474
- ```javascript
1475
- createStore({ types, entities, updateStrategy: "immutable" })
1476
- // TypeError: Unsupported update strategy: immutable. Expected one of: structural-sharing, copy-on-dispatch.
1477
- ```
1478
-
1479
- #### Auto-Create Entities
1480
-
1481
- When `autoCreateEntities: true`, the store automatically creates singleton entities for any type that doesn't have a corresponding entity defined. This is particularly useful for singleton-type entities that behave like components, eliminating the need to switch between type definitions and entity declarations.
1482
-
1483
- ```javascript
1484
- const types = {
1485
- settings: {
1486
- setTheme(entity, theme) {
1487
- entity.theme = theme
1488
- },
1489
- },
1490
- analytics: {
1491
- track(entity, event) {
1492
- entity.events.push(event)
1493
- },
1494
- },
1495
- }
1496
-
1497
- // Without autoCreateEntities (default)
1498
- const entities = {
1499
- settings: { type: "Settings", theme: "dark" },
1500
- analytics: { type: "Analytics", events: [] },
1501
- }
1502
-
1503
- // With autoCreateEntities: true
1504
- const entities = {
1505
- // settings and analytics will be auto-created as:
1506
- // settings: { type: "Settings" }
1507
- // analytics: { type: "Analytics" }
1508
- }
1509
-
1510
- const store = createStore({
1511
- types,
1512
- entities,
1513
- autoCreateEntities: true,
1514
- })
1515
-
1516
- // Both approaches work the same way
1517
- store.notify("settings:setTheme", "light")
1518
- store.notify("analytics:track", { action: "click" })
1519
- ```
1520
-
1521
- **When to use `autoCreateEntities`:**
1522
-
1523
- - ✅ Building web applications with singleton services (settings, auth, analytics)
1524
- - ✅ Component-like entities that only need one instance
1525
- - ✅ Rapid prototyping where you want to add types without ceremony
1526
- - ❌ Game development with multiple entity instances (players, enemies, items)
1527
- - ❌ When you need fine control over initial entity state
1528
-
1529
- ### Types Definition
1530
-
1531
- ```javascript
1532
- const types = {
1533
- entityType: [
1534
- // Behavior objects
1535
- {
1536
- eventName(entity, payload, api) {
1537
- entity.value = payload
1538
- api.notify("otherEvent", data)
1539
- },
1540
- },
1541
- // Behavior functions (decorators)
1542
- (behavior) => ({
1543
- eventName(entity, payload, api) {
1544
- // Wrap the behavior
1545
- behavior.eventName?.(entity, payload, api)
1546
- },
1547
- }),
1548
- ],
1549
- }
1550
- ```
1551
-
1552
- ### Event Handler API
1553
-
1554
- Each handler receives three arguments:
1555
-
1556
- - **`entity`** - the entity instance (mutate freely, immutability guaranteed)
1557
- - **`payload`** - data passed with the event
1558
- - **`api`** - access to store methods:
1559
- - `getEntities()` - entire state (read-only)
1560
- - `getEntity(id)` - single entity (read-only)
1561
- - `select(selector)` - run a selector against the state
1562
- - `notify(type, payload)` - trigger other events
1563
- - `dispatch(action)` - optional, if you prefer Redux-style dispatching
1564
- - `getTypes()` - type definitions (for middleware)
1565
- - `getType(typeName)` - type definition (for overriding)
1566
- - `setType(typeName, type)` - change the behavior of a type
1567
-
1568
- ### Built-in Events
1569
-
1570
- - **`create(entity)`** - triggered when entity added via `add` event, visible only to that entity
1571
- - **`destroy(entity)`** - triggered when entity removed via `remove` event, visible only to that entity
1572
- - **`pause`** - halts the world, see below
1573
- - **`resume`** - unhalts it
1574
- - **`add` / `remove`** - put a thing into the world or take it out, triggering `create` / `destroy`
1575
- - **`patch` / `replace`** - change a thing that is already standing, the first touching only
1576
- what it names and the second installing all of it
1577
- - **`update`** - the frame tick, disabled while the world is paused
1578
- - **`stateChange`** - broadcast by `fsm()` when an entity moves, with `{ entityId, from, to }`
1579
-
1580
- #### Pausing the world
1581
-
1582
- `notify("pause")` stops the store handing out `update` events, and `notify("resume")` starts it again:
1583
-
1584
- ```javascript
1585
- store.notify("pause")
1586
- store.notify("update")
1587
- store.update() // nothing updated
1588
-
1589
- store.notify("resume")
1590
- store.notify("update")
1591
- store.update() // updated as normal
1592
- ```
1593
-
1594
- This is for anything that moves by integrating a delta time. Those entities do not need to know about pausing at all: their `update` is simply never called, so they cannot drift.
1595
-
1596
- Everything else keeps flowing. Input handlers, custom events and rendering are untouched, which is what lets a pause screen take itself back off:
1597
-
1598
- ```javascript
1599
- // Still works while the world is halted
1600
- pauseMenu.pause(entity, _, api) {
1601
- api.notify("resume")
1602
- }
1603
- ```
1604
-
1605
- An entity opts out by setting `updatesWhilePaused`, which is for overlays and menus rather than for gameplay:
1606
-
1607
- ```javascript
1608
- const Overlay = [{ update(entity, dt) { entity.ticks++ } }]
1609
-
1610
- // in entities
1611
- overlay: { type: "Overlay", updatesWhilePaused: true }
1612
- ```
1613
-
1614
- It is a property of the entity rather than of the type so that a type stays a plain index signature of handlers, which is what keeps it freely callable and indexable from TypeScript.
1615
-
1616
- The default is to **stop**. Anything that keeps updating has to say so, so forgetting a flag pauses the thing you meant to pause rather than freezing the menu.
1617
-
1618
- `reset()` clears the halt, so replacing the entities does not leave the world frozen.
1619
-
1620
- Note that `pause` and `resume` keep dispatching like any other event, unlike `add` and `remove`. The store acts on them _and_ every type that handles them still gets called, so one notification can both halt the world and let the game record why.
1621
-
1622
- ### Notify vs Dispatch
1623
-
1624
- Both work (`dispatch` is provided just for Redux compatibility), but `notify` is cleaner (and uses `dispatch` internally):
1625
-
1626
- ```javascript
1627
- store.notify("eventName", payload)
1628
- store.dispatch({ type: "eventName", payload }) // Redux-compatible alternative
1629
- ```
1630
-
1631
- ---
1632
-
1633
- ### 🧩 Type Safety
1634
-
1635
- Inglorious Store is written in JavaScript but comes with TypeScript types that check your whole app with no casts: each type against its entity, each handler's parameters, and every entity read through the api.
1636
-
1637
- **1. Describe your entities and state**
1638
-
1639
- ```typescript
1640
- // types/index.d.ts
1641
- import type {
1642
- Api,
1643
- BaseEntity,
1644
- EntitiesState,
1645
- EntityType,
1646
- } from "@inglorious/store"
1647
-
1648
- export interface CounterEntity extends BaseEntity {
1649
- type: "Counter"
1650
- value: number
1651
- }
1652
-
1653
- export interface LabelEntity extends BaseEntity {
1654
- type: "Label"
1655
- text: string
1656
- }
1657
-
1658
- export type AppEntity = CounterEntity | LabelEntity
1659
-
1660
- // The entities by id
1661
- export interface AppState extends EntitiesState<AppEntity> {
1662
- counter: CounterEntity
1663
- label: LabelEntity
1664
- }
1665
-
1666
- export type AppApi = Api<AppEntity, AppState>
1667
-
1668
- // A type for one of the app's entities
1669
- export type AppType<TEntity extends AppEntity> = EntityType<TEntity, AppApi>
1670
- ```
1671
-
1672
- Every field of an entity is declared, so a misspelled one is an error. The store gives each entity its key in the state as `id`: leave it out of the initial entities, and handlers receive it as a `string`. With `@inglorious/web`, import `Api` from there instead: it is the same type, with `render`.
1673
-
1674
- **2. Write your types**
1675
-
1676
- Declare each type's events and their payloads, then write the type against that declaration:
1677
-
1678
- ```typescript
1679
- // types/index.d.ts
1680
- export type CounterType = {
1681
- increment: (entity: CounterEntity) => void
1682
- add: (entity: CounterEntity, amount: number) => void
1683
- copyLabel: (entity: CounterEntity, payload: void, api: AppApi) => void
1684
- }
1685
- ```
1686
-
1687
- ```typescript
1688
- // src/store/counter.ts
1689
- import type { CounterType } from "../../types"
1690
-
1691
- export const Counter: CounterType = {
1692
- increment(entity) {
1693
- entity.value++
1694
- },
1695
-
1696
- add(entity, amount) {
1697
- entity.value += amount
1698
- },
1699
-
1700
- copyLabel(entity, _payload, api) {
1701
- entity.value = api.getEntity("label")?.text.length ?? 0
1702
- },
1703
- }
1704
- ```
1705
-
1706
- The parameters are inferred from `CounterType`, and TypeScript checks the type against it: a misspelled or missing handler is an error, and so is `Counter.add(counter, "2")`. Declare it with `type`, not `interface`: an interface does not fit the store's `types`.
1707
-
1708
- For less rigour with less to write, skip the declaration and use the shorthand, `satisfies`. It still infers the entity and the api, but it neither lists the events nor types a payload you do not annotate:
1709
-
1710
- ```typescript
1711
- export const Counter = {
1712
- increment(entity) {
1713
- entity.value++
1714
- },
1715
- add(entity, amount: number) {
1716
- entity.value += amount
1717
- },
1718
- } satisfies AppType<CounterEntity>
1719
- ```
1720
-
1721
- **3. Create the store**
1722
-
1723
- ```typescript
1724
- // src/store/index.ts
1725
- import { createStore } from "@inglorious/store"
1726
-
1727
- import type { AppEntity, AppState } from "../../types"
1728
- import { Counter } from "./counter"
1729
- import { Label } from "./label"
1730
-
1731
- export const store = createStore<AppEntity, AppState>({
1732
- types: { Counter, Label },
1733
- entities: {
1734
- counter: { type: "Counter", value: 0 },
1735
- label: { type: "Label", text: "Hello" },
1736
- },
1737
- })
1738
- ```
1739
-
1740
- Each type is checked against the entities of its name: `Counter` against `CounterEntity`. A name no entity has, such as a page rendered by name, takes any type. Behaviors type the same way: `Live: [Chart, withRealtime]`.
1741
-
1742
- **4. Use types from libraries**
1743
-
1744
- An entity drawn by a library type extends that type's entity interface:
1745
-
1746
- ```typescript
1747
- import type { ChartEntity } from "@inglorious/charts"
1748
- import type { RouterEntity } from "@inglorious/web/router"
1749
-
1750
- interface AppRouterEntity extends RouterEntity {
1751
- type: "Router"
1752
- }
1753
-
1754
- interface SalesEntity extends ChartEntity {
1755
- type: "Sales"
1756
- }
1757
-
1758
- // types: { Router, Sales: Chart }
1759
- ```
1760
-
1761
- **5. Check the events you send**
1762
-
1763
- The type declarations already list every event and its payload, so the api can check what `notify` sends. Read the events from them with `EventsOf`, and give them to the api as its third type argument:
1764
-
1765
- ```typescript
1766
- // types/index.d.ts
1767
- import type { EventsOf } from "@inglorious/store"
1768
-
1769
- export type AppEvents = EventsOf<CounterType | LabelType>
1770
- // { increment: void; add: number; copyLabel: void; ...the label's events }
1771
-
1772
- export type AppApi = Api<AppEntity, AppState, AppEvents>
1773
- ```
1774
-
1775
- Now every handler's `api.notify` checks the event's name, wherever it is sent (`"add"`, `"Counter:add"`, `` `#${entity.id}:add` ``), and its payload:
1776
-
1777
- ```typescript
1778
- api.notify(`#${entity.id}:add`, 2) // fine
1779
- api.notify(`#${entity.id}:ad`, 2) // error: no type answers `ad`
1780
- api.notify(`#${entity.id}:add`, "2") // error: `add` takes a number
1781
- api.notify(`#${entity.id}:increment`, 1) // error: `increment` takes no payload
1782
- ```
1783
-
1784
- The store's own events (`add`, `remove`, `patch`, `replace`, `pause`, `resume`, `update`) are always there. Only the event's name is checked, not the target before it, because the target is usually built at runtime. Pass the events to `createStore<AppEntity, AppState, AppEvents>` too, so that `store.notify` checks them, and `mount` gives them to the root render. A typed api is still an `Api`: components that take any app's api accept it.
1785
-
1786
- Without the third type argument, `notify` takes any name and any payload, as before.
1787
-
1788
- **6. Give sub-renderers their props**
1789
-
1790
- Every render method takes props first: `render(props, api)`, where a type's props are its entity, and sub-renderers that draw one item, `renderX(props, ownProps, api)`, which get the component's props, then the item's own (`renderLine(props, line, api)`). `EntityType` reads every member as a handler, whose first parameter is the entity, so it rejects sub-renderers whose props are not the entity. `defineType` checks each member by its name instead: `render` takes the entity as its props, a sub-renderer keeps the types it declares, and every other member is a handler, whose entity and api are inferred:
1791
-
1792
- ```typescript
1793
- import { defineType } from "@inglorious/store"
1794
-
1795
- export const Scoreboard = defineType<ScoreboardEntity, AppApi>()({
1796
- ...template, // renderScoreboard(props, api), renderContender(props, speaker, api), ...
1797
- render(props, api) {
1798
- const debate = api.getEntity("debate")
1799
- return this.renderScoreboard({ ...props, memory: debate?.memory }, api)
1800
- },
1801
- })
1802
- ```
1803
-
1804
- Inside its methods, `this` is the behavior, so `this.renderScoreboard` is checked too. It takes the entity and the api first, then the behavior, because TypeScript cannot infer one while being told the others. The result is an `EntityType`, so it goes in `types` or in a list of behaviors like any other: `[Chat, handlers, fsm(states), defineType<DebateEntity, AppApi>()({ ...template, render })]`.
1805
-
1806
- **7. Test your handlers**
1807
-
1808
- ```typescript
1809
- import { trigger } from "@inglorious/store/test"
1810
-
1811
- const { entity, events } = trigger(counter, Counter.add, 2)
1812
- ```
1813
-
1814
- `trigger` checks the payload against the handler, and returns the updated entity, typed.
1815
-
1816
- **Upgrading from casts**
1817
-
1818
- Older apps passed `types` as `types as unknown as TypesConfig<AppEntity>` and described each type with an interface. Drop the cast, turn each `interface CounterType {` into `type CounterType = {`, and declare every entity field, which `BaseEntity` no longer allows by default. An entity that extended `BaseEntity, Omit<RouterEntity, "id">` now just extends `RouterEntity`.
1819
-
1820
- ---
1821
-
1822
- ## Use Cases
1823
-
1824
- ### Perfect For
1825
-
1826
- - 🎮 Apps with multiple instances of the same entity type
1827
- - 🎯 Real-time collaborative features
1828
- - ⚡ Complex state coordination and async operations
1829
- - 📊 High-frequency updates (animations, games)
1830
- - 🔄 Undo/redo, time-travel debugging
1831
-
1832
- ### Still Great For
1833
-
1834
- - Any Redux use case (true drop-in replacement)
1835
- - Migration path from Redux (keep using react-redux)
1836
-
1837
- ---
1838
-
1839
- ### Demos
1840
-
1841
- Check out the following demos to see the Inglorious Store in action on real-case scenarios:
1842
-
1843
- **React Examples:**
1844
-
1845
- - **[React TodoMVC](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/react-todomvc)** - An (ugly) clone of Kent Dodds' [TodoMVC](https://todomvc.com/) experiments, showing the full compatibility with react-redux and The Redux DevTools.
1846
- - **[React TodoMVC-CS](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/react-todomvc-cs)** - A client-server version of the TodoMVC, which showcases the use of `notify` as a cleaner alternative to `dispatch` and async event handlers.
1847
- - **[React TodoMVC-RT](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/react-todomvc-rt)** - A "multiplayer" version, in which multiple clients are able to synchronize through a real-time server.
1848
- - **[React TodoMVC-TS](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/react-todomvc-ts)** - A typesafe version of the base TodoMVC.
1849
-
1850
- For more demos and examples with `@inglorious/web`, see the [`@inglorious/web` README](../web/README.md).
1851
-
1852
- ---
1853
-
1854
- ## Frequently Unsolicited Complaints (FUCs)
1855
-
1856
- It's hard to accept the new, especially on Reddit. Here are the main objections to the Inglorious Store.
1857
-
1858
- **"This is not ECS."**
1859
-
1860
- It's not. The Inglorious Store is _inspired_ by ECS, but doesn't strictly follow ECS. Heck, not even the major game engines out there follow ECS by the book!
1861
-
1862
- Let's compare the two:
1863
-
1864
- | ECS Architecture | Inglorious Store |
1865
- | ------------------------------------- | -------------------------------------- |
1866
- | Entities are ids | Entities have an id |
1867
- | Components are pure, consecutive data | Entities are pure bags of related data |
1868
- | Data and behavior are separated | Data and behavior are separated |
1869
- | Systems operate on the whole state | Systems operate on the whole state |
1870
- | Usually written in an OOP environment | Written in an FP environment |
1871
-
1872
- **"This is not FP."**
1873
-
1874
- It looks like it's not, and that's a feature. If you're used to classes and instances, the Inglorious Store will feel natural to you. Even behavior composition looks like inheritance, but it's actually function composition. The same [Three Principles](https://redux.js.org/understanding/thinking-in-redux/three-principles) that describe Redux are applied here (with some degree of freedom on function purity).
1875
-
1876
- **"This is not Data-Oriented Design."**
1877
-
1878
- It's not. Please grep this README and count how many occurrences of DoD you can find. This is not [Data-Oriented Design](https://en.wikipedia.org/wiki/Data-oriented_design), which is related to low-level CPU cache optimization. It's more similar to [Data-Driven Programming](https://en.wikipedia.org/wiki/Data-driven_programming), which is related to separating data and behavior. The Inglorious Store separates behavior in... behaviors (grouped into so-called types), while the data is stored in plain objects called entities.
1879
-
1880
- ---
1881
-
1882
- ## License
64
+ ## License
1883
65
 
1884
66
  MIT © [Matteo Antony Mistretta](https://github.com/IngloriousCoderz)
1885
-
1886
- Free to use, modify, and distribute.
1887
-
1888
- ---
1889
-
1890
- ## Contributing
1891
-
1892
- Contributions welcome! Please read our [Contributing Guidelines](../../CONTRIBUTING.md) first.