@inglorious/store 12.2.0 → 12.4.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
@@ -558,8 +558,60 @@ Two things to keep in mind:
558
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
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
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"])] }
607
+ ```
608
+
609
+ The handlers and events are those of `handleAsync`, below, so `optimistic` wraps a request too.
610
+
561
611
  ### `handleAsync`
562
612
 
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.
614
+
563
615
  The `handleAsync` helper generates a set of event handlers representing the lifecycle of an async operation.
564
616
 
565
617
  ```ts
@@ -1659,7 +1711,52 @@ interface SalesEntity extends ChartEntity {
1659
1711
  // types: { Router, Sales: Chart }
1660
1712
  ```
1661
1713
 
1662
- **5. Test your handlers**
1714
+ **5. Check the events you send**
1715
+
1716
+ 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:
1717
+
1718
+ ```typescript
1719
+ // types/index.d.ts
1720
+ import type { EventsOf } from "@inglorious/store"
1721
+
1722
+ export type AppEvents = EventsOf<CounterType | LabelType>
1723
+ // { increment: void; add: number; copyLabel: void; ...the label's events }
1724
+
1725
+ export type AppApi = Api<AppEntity, AppState, AppEvents>
1726
+ ```
1727
+
1728
+ Now every handler's `api.notify` checks the event's name, wherever it is sent (`"add"`, `"Counter:add"`, `` `#${entity.id}:add` ``), and its payload:
1729
+
1730
+ ```typescript
1731
+ api.notify(`#${entity.id}:add`, 2) // fine
1732
+ api.notify(`#${entity.id}:ad`, 2) // error: no type answers `ad`
1733
+ api.notify(`#${entity.id}:add`, "2") // error: `add` takes a number
1734
+ api.notify(`#${entity.id}:increment`, 1) // error: `increment` takes no payload
1735
+ ```
1736
+
1737
+ 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.
1738
+
1739
+ Without the third type argument, `notify` takes any name and any payload, as before.
1740
+
1741
+ **6. Give sub-renderers their props**
1742
+
1743
+ 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:
1744
+
1745
+ ```typescript
1746
+ import { defineType } from "@inglorious/store"
1747
+
1748
+ export const Scoreboard = defineType<ScoreboardEntity, AppApi>()({
1749
+ ...template, // renderScoreboard(props, api), renderContender(props, speaker, api), ...
1750
+ render(props, api) {
1751
+ const debate = api.getEntity("debate")
1752
+ return this.renderScoreboard({ ...props, memory: debate?.memory }, api)
1753
+ },
1754
+ })
1755
+ ```
1756
+
1757
+ 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 })]`.
1758
+
1759
+ **7. Test your handlers**
1663
1760
 
1664
1761
  ```typescript
1665
1762
  import { trigger } from "@inglorious/store/test"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/store",
3
- "version": "12.2.0",
3
+ "version": "12.4.0",
4
4
  "description": "A state manager for real-time, collaborative apps, inspired by game development patterns and compatible with Redux.",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
@@ -75,19 +75,19 @@
75
75
  },
76
76
  "sideEffects": false,
77
77
  "dependencies": {
78
- "mutative": "^1.3.0"
78
+ "mutative": "^2.0.2"
79
79
  },
80
80
  "peerDependencies": {
81
- "@inglorious/utils": "^5.1.0"
81
+ "@inglorious/utils": "^5.3.0"
82
82
  },
83
83
  "devDependencies": {
84
84
  "@inglorious/eslint-config": "1.2.0",
85
- "@inglorious/utils": "5.1.0",
86
- "@reduxjs/toolkit": "^2.12.0",
87
- "prettier": "^3.9.6",
85
+ "@inglorious/utils": "5.3.0",
86
+ "@reduxjs/toolkit": "^2.14.0",
87
+ "prettier": "^3.9.10",
88
88
  "typescript": "~7.0.2",
89
- "vite": "^8.2.2",
90
- "vitest": "^5.0.0"
89
+ "vite": "^8.3.7",
90
+ "vitest": "^5.1.0"
91
91
  },
92
92
  "engines": {
93
93
  "node": ">= 26"
@@ -1,9 +1,122 @@
1
+ /**
2
+ * The handlers of a request: a call whose progress the entity shows. The
3
+ * entity's `status` is `"loading"` from the start, then `"success"` or
4
+ * `"error"`, and its `error` holds what went wrong. Only the latest call
5
+ * counts: the answer of a call that a newer one replaced is dropped, so a slow
6
+ * search never overwrites a quicker, later one. Prefer it to `handleAsync`
7
+ * whenever the entity shows that something is happening.
8
+ *
9
+ * @template {import('../store').BaseEntity} TEntity
10
+ * @template TPayload
11
+ * @template TResult
12
+ *
13
+ * @param {string} type The event that starts the request, which `withDebounce`
14
+ * can wrap. Its lifecycle events are those of `handleAsync`.
15
+ * @param {Object} handlers As `handleAsync`'s. `error` receives the error as
16
+ * `toError` turns it, after `error` is set: it can change what the entity
17
+ * shows, such as moving to another step for an error it expects.
18
+ * @param {Object} [options]
19
+ * @param {string} [options.status="status"] The field for the status, when
20
+ * the entity has several requests, such as `"saveStatus"`.
21
+ * @param {string} [options.error="error"] The field for the error.
22
+ * @param {(error: unknown) => unknown} [options.toError] What to store as the
23
+ * error, such as a translation key. Defaults to the error's message.
24
+ * @param {boolean} [options.isLatestOnly=true] Whether a call replaced by a
25
+ * newer one is ignored. Turn it off for calls that all count, such as saving
26
+ * several items at once.
27
+ * @param {"entity" | "type" | "global"} [options.scope="entity"] Where the
28
+ * lifecycle events go, as in `handleAsync`.
29
+ *
30
+ * @example
31
+ * const JobList = {
32
+ * ...handleRequest("search", {
33
+ * run: (query) => api.searchJobs(query),
34
+ * success(entity, jobs) {
35
+ * entity.jobs = jobs
36
+ * },
37
+ * }),
38
+ * }
39
+ *
40
+ * const types = { JobList: [JobList, withDebounce(300, ["search"])] }
41
+ */
42
+ export function handleRequest(type, handlers, options = {}) {
43
+ const {
44
+ status = "status",
45
+ error: errorField = "error",
46
+ toError = messageOf,
47
+ isLatestOnly = true,
48
+ scope = "entity",
49
+ } = options
50
+
51
+ const base = handleAsync(
52
+ type,
53
+ {
54
+ start(entity, payload, api) {
55
+ entity[status] = "loading"
56
+ entity[errorField] = null
57
+ handlers.start?.(entity, payload, api)
58
+ },
59
+ run: handlers.run,
60
+ success(entity, result, api) {
61
+ entity[status] = "success"
62
+ handlers.success?.(entity, result, api)
63
+ },
64
+ error(entity, error, api) {
65
+ const value = toError(error)
66
+ entity[status] = "error"
67
+ entity[errorField] = value
68
+ handlers.error?.(entity, value, api)
69
+ },
70
+ finally: handlers.finally,
71
+ },
72
+ { scope },
73
+ )
74
+ if (!isLatestOnly) return base
75
+
76
+ /** The latest call of each entity. */
77
+ const latest = new Map()
78
+ const startEvent = `${type}Start`
79
+ const isCurrent = (entity, { callId }) => latest.get(entity.id) === callId
80
+ const unlessStale = (event) => (entity, payload, api) => {
81
+ if (isCurrent(entity, payload)) base[event](entity, payload, api)
82
+ }
83
+ const finallyEvent = `${type}Finally`
84
+
85
+ const request = {
86
+ ...base,
87
+
88
+ [startEvent](entity, event, api) {
89
+ latest.set(entity.id, event.callId)
90
+ base[startEvent](entity, event, api)
91
+ },
92
+
93
+ [`${type}Success`]: unlessStale(`${type}Success`),
94
+ [`${type}Error`]: unlessStale(`${type}Error`),
95
+
96
+ [finallyEvent](entity, event, api) {
97
+ if (!isCurrent(entity, event)) return
98
+ latest.delete(entity.id)
99
+ base[finallyEvent](entity, event, api)
100
+ },
101
+ }
102
+
103
+ Object.defineProperty(request, ASYNC_META, {
104
+ value: { type, scope },
105
+ enumerable: false,
106
+ })
107
+
108
+ return request
109
+ }
110
+
1
111
  /**
2
112
  * Creates a set of event handlers for managing an asynchronous operation lifecycle.
3
113
  *
4
114
  * This helper generates handlers for all stages of an async operation: start, run,
5
115
  * success, error, and finally. The lifecycle events are automatically scoped based
6
- * on the provided options.
116
+ * on the provided options. For a call whose progress the entity shows, use
117
+ * `handleRequest`, which keeps the status and error and drops outdated answers;
118
+ * `handleAsync` is for the rest, such as saving in the background or calls whose
119
+ * failure only gets logged.
7
120
  *
8
121
  * @template {import('../store').BaseEntity} TEntity - The entity type
9
122
  * @template TPayload - The payload type passed to the operation
@@ -14,8 +127,7 @@
14
127
  *
15
128
  * @param {Object} handlers - The handler functions for each lifecycle stage.
16
129
  * @param {(entity: TEntity, payload: TPayload, api: import('../store').Api) => void} [handlers.start]
17
- * Called synchronously before the async operation starts.
18
- * Use for setting loading states. Receives: (entity, payload, api)
130
+ * Called synchronously before the async operation starts. Receives: (entity, payload, api)
19
131
  * @param {(payload: TPayload, api: import('../store').Api) => Promise<TResult> | TResult} handlers.run
20
132
  * The async operation to perform. Must return a Promise or value.
21
133
  * **Note:** Receives (payload, api) - NOT entity. Entity state should be modified in other handlers.
@@ -26,15 +138,14 @@
26
138
  * Called when the operation fails.
27
139
  * Receives: (entity, error, api) where error is the caught exception
28
140
  * @param {(entity: TEntity, api: import('../store').Api) => void} [handlers.finally]
29
- * Called after the operation completes (success or failure).
30
- * Use for cleanup, resetting loading states. Receives: (entity, api)
141
+ * Called after the operation completes (success or failure). Receives: (entity, api)
31
142
  *
32
143
  * @param {Object} [options] - Configuration options.
33
144
  * @param {"entity" | "type" | "global"} [options.scope="entity"]
34
145
  * Controls how lifecycle events are routed:
35
146
  * - "entity": notify `#entityId:event` (default, safest - events only affect the triggering entity)
36
147
  * - "type": notify `typeName:event` (broadcasts to all entities of this type)
37
- * - "global": notify `event` (global broadcast to any listener)
148
+ * - "global": notify `event` (global broadcast to any listener, as games often want)
38
149
  *
39
150
  * Each call gets a `callId`, and every event of that call carries it: `Start`
40
151
  * and `Run` get `{ payload, callId }`, `Success` gets `{ result, callId }`,
@@ -50,37 +161,20 @@
50
161
  * - `[typeFinally]`: Executes the finally handler
51
162
  *
52
163
  * @example
53
- * // Basic usage - fetch todos with loading state
54
- * const todoList = {
55
- * init(entity) {
56
- * entity.todos = []
57
- * entity.status = 'idle'
58
- * },
59
- *
60
- * ...handleAsync('fetchTodos', {
61
- * start(entity) {
62
- * entity.status = 'loading'
164
+ * // Saves in the background: a failure is only logged
165
+ * const preferences = {
166
+ * ...handleAsync('localeSave', {
167
+ * run(locale) {
168
+ * return api.savePreferences({ locale })
63
169
  * },
64
- * async run(payload, api) {
65
- * const response = await fetch('/api/todos')
66
- * return response.json()
170
+ * error(_, error) {
171
+ * console.warn('Language not saved:', error)
67
172
  * },
68
- * success(entity, todos) {
69
- * entity.status = 'success'
70
- * entity.todos = todos
71
- * },
72
- * error(entity, error) {
73
- * entity.status = 'error'
74
- * entity.error = error.message
75
- * },
76
- * finally(entity) {
77
- * entity.lastFetched = Date.now()
78
- * }
79
- * })
173
+ * }),
80
174
  * }
81
175
  *
82
176
  * // Trigger from UI
83
- * api.notify('#todoList:fetchTodos')
177
+ * api.notify('#preferences:localeSave', 'it')
84
178
  *
85
179
  * @example
86
180
  * // With type scope - affects all entities of this type
@@ -99,40 +193,6 @@
99
193
  *
100
194
  * // Triggers sync for ALL counter entities
101
195
  * api.notify('counter:sync')
102
- *
103
- * @example
104
- * // Minimal - just run and success
105
- * const user = {
106
- * ...handleAsync('login', {
107
- * async run({ username, password }, api) {
108
- * const response = await fetch('/api/login', {
109
- * method: 'POST',
110
- * body: JSON.stringify({ username, password })
111
- * })
112
- * return response.json()
113
- * },
114
- * success(entity, user) {
115
- * entity.currentUser = user
116
- * entity.isAuthenticated = true
117
- * }
118
- * })
119
- * }
120
- *
121
- * @example
122
- * // Without start handler
123
- * const data = {
124
- * ...handleAsync('fetch', {
125
- * async run(payload, api) {
126
- * return fetch(`/api/data/${payload.id}`).then(r => r.json())
127
- * },
128
- * success(entity, result) {
129
- * entity.data = result
130
- * },
131
- * error(entity, error) {
132
- * console.error('Fetch failed:', error)
133
- * }
134
- * })
135
- * }
136
196
  */
137
197
  export function handleAsync(type, handlers, options = {}) {
138
198
  const { scope = "entity" } = options
@@ -216,3 +276,7 @@ export function nextCallId() {
216
276
  }
217
277
 
218
278
  export const ASYNC_META = Symbol.for("@inglorious/store/asyncMeta")
279
+
280
+ function messageOf(error) {
281
+ return error instanceof Error ? error.message : String(error)
282
+ }
package/src/store.js CHANGED
@@ -515,6 +515,22 @@ export function createStore({
515
515
  }
516
516
  }
517
517
 
518
+ /**
519
+ * Defines a behavior for an entity. It does nothing at runtime: it hands back
520
+ * the behavior it is given, and JavaScript apps never need it.
521
+ *
522
+ * It is for TypeScript apps, like Vue's `defineComponent` or Vite's
523
+ * `defineConfig`: its declaration in `types/store.d.ts` checks each member of
524
+ * the behavior by its name, so that a template's sub-renderers can take props
525
+ * while the handlers still get the entity, which a plain annotation cannot
526
+ * express. See that declaration for why.
527
+ *
528
+ * @returns {(behavior: object) => object} A function that returns the behavior it is given.
529
+ */
530
+ export function defineType() {
531
+ return (behavior) => behavior
532
+ }
533
+
518
534
  /**
519
535
  * A draft that writes straight into the entities it is given.
520
536
  *
package/types/api.d.ts CHANGED
@@ -7,6 +7,7 @@ import type {
7
7
  Store,
8
8
  Stored,
9
9
  } from "./store"
10
+ import type { AnyEvents, Notify } from "./events"
10
11
 
11
12
  /**
12
13
  * API object exposed to handlers.
@@ -14,10 +15,14 @@ import type {
14
15
  * An app's own `Api<AppEntity, AppState>` is an `Api`: a component typed with
15
16
  * the plain `Api` accepts it. So the members that read types give the plain
16
17
  * `EntityType`, rather than one typed for the app's entities.
18
+ *
19
+ * Told the app's events, `Api<AppEntity, AppState, AppEvents>` checks what
20
+ * `notify` sends (see `EventsOf`), and is still an `Api`.
17
21
  */
18
22
  export interface Api<
19
23
  TEntity extends BaseEntity = BaseEntity,
20
24
  TState extends EntitiesState<TEntity> = EntitiesState<TEntity>,
25
+ TEvents = AnyEvents,
21
26
  > {
22
27
  getTypes: () => Record<string, EntityType>
23
28
  getType: (typeName: string) => EntityType
@@ -35,7 +40,7 @@ export interface Api<
35
40
  }
36
41
  select: <TResult>(selector: (state: TState) => TResult) => TResult
37
42
  dispatch: (event: Event) => void
38
- notify: (type: string, payload?: any) => void
43
+ notify: Notify<TEvents, TEntity>
39
44
  [key: string]: any
40
45
  }
41
46
 
@@ -45,7 +50,8 @@ export interface Api<
45
50
  export function createApi<
46
51
  TEntity extends BaseEntity = BaseEntity,
47
52
  TState extends EntitiesState<TEntity> = EntitiesState<TEntity>,
53
+ TEvents = AnyEvents,
48
54
  >(
49
- store: Store<TEntity, TState>,
55
+ store: Store<TEntity, TState, TEvents>,
50
56
  extras?: Record<string, any>,
51
- ): Api<TEntity, TState>
57
+ ): Api<TEntity, TState, TEvents>
@@ -194,3 +194,66 @@ export function handleAsync<
194
194
  handlers: AsyncHandlers<TEntity, TPayload, TResult, TApi>,
195
195
  options?: AsyncOptions,
196
196
  ): AsyncEvents<TType, TEntity, TPayload, TResult, TApi>
197
+
198
+ /** Where a request is: `"loading"`, then `"success"` or `"error"`. */
199
+ export type RequestStatus = "loading" | "success" | "error"
200
+
201
+ export interface RequestOptions<TError = string> extends AsyncOptions {
202
+ /** The field for the status, when the entity has several requests. @default "status" */
203
+ status?: string
204
+ /** The field for the error. @default "error" */
205
+ error?: string
206
+ /** What to store as the error, such as a translation key. Defaults to its message. */
207
+ toError?: (error: unknown) => TError
208
+ /** Whether a call replaced by a newer one is ignored. @default true */
209
+ isLatestOnly?: boolean
210
+ }
211
+
212
+ /**
213
+ * Handler functions for a request: those of `handleAsync`, whose `error`
214
+ * receives the error as `toError` turned it, after the entity's error field is
215
+ * set.
216
+ */
217
+ export interface RequestHandlers<
218
+ TEntity extends BaseEntity = BaseEntity,
219
+ TPayload = any,
220
+ TResult = any,
221
+ TApi extends Api = Api,
222
+ TError = string,
223
+ > extends Omit<AsyncHandlers<TEntity, TPayload, TResult, TApi>, "error"> {
224
+ error?: (entity: TEntity, error: TError, api: TApi) => void
225
+ }
226
+
227
+ /**
228
+ * The handlers of a request: a call whose progress the entity shows. The
229
+ * entity's `status` is `"loading"` from the start, then `"success"` or
230
+ * `"error"`, and its `error` holds what went wrong. Only the latest call
231
+ * counts: the answer of a call that a newer one replaced is dropped. Prefer it
232
+ * to `handleAsync` whenever the entity shows that something is happening.
233
+ *
234
+ * @example
235
+ * ```typescript
236
+ * const JobList = {
237
+ * ...handleRequest("search", {
238
+ * run: (query: string) => searchJobs(query),
239
+ * success(entity, jobs) {
240
+ * entity.jobs = jobs
241
+ * },
242
+ * }),
243
+ * } satisfies EntityType<JobListEntity, AppApi>
244
+ *
245
+ * const types = { JobList: [JobList, withDebounce(300, ["search"])] }
246
+ * ```
247
+ */
248
+ export function handleRequest<
249
+ TEntity extends BaseEntity = BaseEntity,
250
+ TPayload = any,
251
+ TResult = any,
252
+ TApi extends Api = Api,
253
+ TType extends string = string,
254
+ TError = string,
255
+ >(
256
+ type: TType,
257
+ handlers: RequestHandlers<TEntity, TPayload, TResult, TApi, TError>,
258
+ options?: RequestOptions<TError>,
259
+ ): AsyncEvents<TType, TEntity, TPayload, TResult, TApi>
@@ -0,0 +1,149 @@
1
+ // The events a store answers, so that `notify` can check them: the event's
2
+ // name, wherever it is sent, and its payload.
3
+
4
+ import type { BaseEntity, Stored } from "./store"
5
+
6
+ declare const anyEvents: unique symbol
7
+
8
+ /**
9
+ * The events of an api or a store that has not been told its events: any
10
+ * name, any payload. It is the default, so an untyped app type-checks as
11
+ * before.
12
+ */
13
+ export type AnyEvents = { readonly [anyEvents]: true }
14
+
15
+ /**
16
+ * The events a store's types answer, by name, with their payloads, read from
17
+ * the types' own declarations: the second parameter of each handler is its
18
+ * payload, and a handler that takes none has no payload. `render` and the
19
+ * other `render…` members are renderers, not events, so they are left out.
20
+ *
21
+ * ```ts
22
+ * type CounterType = {
23
+ * add: (entity: CounterEntity, amount: number) => void
24
+ * reset: (entity: CounterEntity) => void
25
+ * }
26
+ *
27
+ * type AppEvents = EventsOf<CounterType | LabelType>
28
+ * // { add: number; reset: void; ...the label's events }
29
+ *
30
+ * type AppApi = Api<AppEntity, AppState, AppEvents>
31
+ * ```
32
+ *
33
+ * An event two types answer takes either type's payload.
34
+ */
35
+ export type EventsOf<TTypes> = {
36
+ [TEvent in HandlerName<TTypes>]: TTypes extends unknown
37
+ ? TEvent extends keyof TTypes
38
+ ? PayloadOf<TTypes[TEvent]>
39
+ : never
40
+ : never
41
+ }
42
+
43
+ /**
44
+ * The events the store answers itself, whatever its types: an entity
45
+ * arriving, leaving or changing, and the world pausing and resuming.
46
+ */
47
+ export type BuiltInEvents<TEntity extends BaseEntity = BaseEntity> = {
48
+ add: TEntity & { id: string }
49
+ remove: string
50
+ patch: Partial<TEntity> & { id: string }
51
+ replace: Stored<TEntity>
52
+ pause: void
53
+ resume: void
54
+ update: number | undefined
55
+ }
56
+
57
+ /**
58
+ * How an event is sent: by its name alone, broadcast to whoever answers it,
59
+ * or after a target that narrows it down to a type (`Type:event`), an entity
60
+ * (`#id:event`) or both (`Type#id:event`). Only the event's name is checked:
61
+ * the target is usually built at runtime, such as `` `#${entity.id}:submit` ``.
62
+ */
63
+ export type EventType<TEvents> =
64
+ EventName<TEvents> | `${string}:${EventName<TEvents>}`
65
+
66
+ /**
67
+ * Sends an event. Told the store's events, it checks the event's name and
68
+ * its payload: `notify("#debate:lineAdd", line)` must name an event the
69
+ * store's types answer, and `line` must be that event's payload. An event
70
+ * with no payload takes none. Otherwise any name and payload go.
71
+ */
72
+ export type Notify<
73
+ TEvents = AnyEvents,
74
+ TEntity extends BaseEntity = BaseEntity,
75
+ > = AnyEvents extends TEvents
76
+ ? (type: string, payload?: any) => void
77
+ : TypedNotify<WithBuiltIns<TEvents, BuiltInEvents<TEntity>>>
78
+
79
+ type EventName<TEvents> = keyof TEvents & string
80
+
81
+ /**
82
+ * The app's events and the store's own, by name. An app event named like a
83
+ * built-in one, such as an `add` that takes an amount, takes either payload,
84
+ * because its handlers hear both: the store broadcasts entities as `add` too.
85
+ */
86
+ type WithBuiltIns<TEvents, TBuiltIns> = {
87
+ [K in keyof TEvents | keyof TBuiltIns]:
88
+ | (K extends keyof TEvents ? TEvents[K] : never)
89
+ | (K extends keyof TBuiltIns ? TBuiltIns[K] : never)
90
+ }
91
+
92
+ /** The event a sent type names: what follows its target, if it has one. */
93
+ type EventOf<TType extends string> = TType extends `${string}:${infer TEvent}`
94
+ ? TEvent
95
+ : TType
96
+
97
+ /** The payload as `notify`'s last parameters: none, optional or required. */
98
+ type PayloadArgs<TPayload> = [TPayload] extends [void]
99
+ ? [payload?: undefined]
100
+ : undefined extends TPayload
101
+ ? [payload?: TPayload]
102
+ : [payload: TPayload]
103
+
104
+ /**
105
+ * A typed `notify`, declared as a method and taken out by name, with an
106
+ * overload that nothing can call: it only lets a typed api or store fit
107
+ * where a plain one is expected, such as a component that takes any app's
108
+ * api. It comes first, so that a call that fits neither is explained by the
109
+ * typed one.
110
+ */
111
+ type TypedNotify<TEvents> = {
112
+ notify(type: never, payload: never): void
113
+ notify<TType extends EventType<TEvents>>(
114
+ type: TType,
115
+ ...payload: PayloadArgs<TEvents[EventOf<TType> & keyof TEvents]>
116
+ ): void
117
+ }["notify"]
118
+
119
+ /**
120
+ * The handlers' names of each type: every function but the renderers. Only
121
+ * named members count: a type that also takes any handler, through an index
122
+ * signature such as `[handler: string]: unknown`, keeps its named events.
123
+ */
124
+ type HandlerName<TTypes> = TTypes extends unknown
125
+ ? keyof {
126
+ [
127
+ K in keyof TTypes as string extends K
128
+ ? never
129
+ : number extends K
130
+ ? never
131
+ : K extends `render${string}`
132
+ ? never
133
+ : TTypes[K] extends (...args: never[]) => unknown
134
+ ? K
135
+ : never
136
+ ]: true
137
+ } &
138
+ string
139
+ : never
140
+
141
+ /** A handler's payload: its second parameter, or none if it takes only the entity. */
142
+ type PayloadOf<THandler> = THandler extends (
143
+ entity: never,
144
+ ...rest: infer TRest
145
+ ) => unknown
146
+ ? TRest extends []
147
+ ? void
148
+ : TRest[0]
149
+ : never
package/types/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./api"
2
2
  export * from "./behaviors/async"
3
+ export * from "./events"
3
4
  export * from "./select"
4
5
  export * from "./store"
5
6
  export * from "./test"
package/types/store.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Api } from "./api"
2
+ import type { AnyEvents, Notify } from "./events"
2
3
 
3
4
  /**
4
5
  * What every entity has. Declare an entity's other fields on its own interface:
@@ -111,6 +112,68 @@ export type TypeDefinition<
111
112
  */
112
113
  export type AnyTypeDefinition = TypeDefinition<never, never>
113
114
 
115
+ /**
116
+ * What each member of a type must be, told by its name: `render(props, api)`
117
+ * draws the type, and a type's props are its entity; any other `render…` is
118
+ * a sub-renderer, `renderX(props, ownProps, api)`, which keeps the types it
119
+ * declares; every other member handles an event.
120
+ */
121
+ export type CheckedType<
122
+ TType,
123
+ TEntity extends BaseEntity = BaseEntity,
124
+ TApi extends Api = Api,
125
+ > = {
126
+ [K in keyof TType]: K extends "render"
127
+ ? Renderer<TEntity, TApi>
128
+ : K extends `render${string}`
129
+ ? TType[K]
130
+ : EventHandler<TEntity, TApi>
131
+ }
132
+
133
+ /**
134
+ * For TypeScript only. At runtime it hands back the behavior it is given, and
135
+ * JavaScript apps never need it: it exists so that TypeScript can check a
136
+ * behavior that a plain annotation cannot describe, the same trick as Vue's
137
+ * `defineComponent` or Vite's `defineConfig`.
138
+ *
139
+ * Why it is needed: an annotation such as `EntityType<ScoreboardEntity, AppApi>`
140
+ * checks every member as an event handler, `(entity, payload, api)`. That is
141
+ * wrong for a template's sub-renderers, `renderX(props, ownProps, api)`,
142
+ * whose first parameter is the component's props rather than the entity, so
143
+ * the annotation rejects them. TypeScript cannot exempt members by their name
144
+ * in an annotation; it can only check them one by one after inferring the
145
+ * object, which takes a generic function. This is that function.
146
+ *
147
+ * What it checks, member by member: `render(props, api)` takes the entity as
148
+ * its props; any other `render…` keeps the types it declares; every other
149
+ * member is an event handler, whose entity and api are inferred. Inside its
150
+ * methods, `this` is the behavior itself.
151
+ *
152
+ * Use it only for a behavior whose sub-renderers take props; otherwise an
153
+ * annotation is enough. It takes the entity and the api first, then the
154
+ * behavior, because TypeScript cannot infer the behavior while being told
155
+ * the rest:
156
+ *
157
+ * ```ts
158
+ * export const Scoreboard = defineType<ScoreboardEntity, AppApi>()({
159
+ * ...template, // renderScoreboard(props, api), renderContender(props, speaker, api), ...
160
+ * render(props, api) {
161
+ * return this.renderScoreboard({ ...props, memory: readMemory(api) }, api)
162
+ * },
163
+ * })
164
+ * ```
165
+ *
166
+ * The result is an `EntityType` for the entity, so it goes wherever a
167
+ * behavior goes: in the store's `types`, or in a list of behaviors such as
168
+ * `[Chat, handlers, fsm(states), defineType<DebateEntity, AppApi>()({ ... })]`.
169
+ */
170
+ export function defineType<
171
+ TEntity extends BaseEntity,
172
+ TApi extends Api = Api,
173
+ >(): <TType>(
174
+ behavior: CheckedType<TType, TEntity, TApi> & ThisType<TType>,
175
+ ) => EntityType<TEntity, TApi>
176
+
114
177
  /**
115
178
  * System definition with event handlers
116
179
  */
@@ -134,12 +197,13 @@ export type EntitiesState<TEntity extends BaseEntity = BaseEntity> = {
134
197
  export type TypesConfig<
135
198
  TEntity extends BaseEntity = BaseEntity,
136
199
  TState extends EntitiesState<TEntity> = EntitiesState<TEntity>,
200
+ TEvents = AnyEvents,
137
201
  > = string extends TEntity["type"]
138
202
  ? { [typeName: string]: AnyTypeDefinition }
139
203
  : {
140
204
  [TName in TEntity["type"]]?: TypeDefinition<
141
205
  Extract<TEntity, { type: TName }>,
142
- Api<TEntity, TState>
206
+ Api<TEntity, TState, TEvents>
143
207
  >
144
208
  } & { [typeName: string]: unknown }
145
209
 
@@ -172,10 +236,11 @@ export type UpdateStrategy = "structural-sharing" | "copy-on-dispatch"
172
236
  export interface StoreConfig<
173
237
  TEntity extends BaseEntity = BaseEntity,
174
238
  TState extends EntitiesState<TEntity> = EntitiesState<TEntity>,
239
+ TEvents = AnyEvents,
175
240
  > {
176
241
  // The entity type comes from the type arguments, `entities` or
177
242
  // `middlewares`, never from `types`, which are checked against it.
178
- types?: NoInfer<TypesConfig<TEntity, TState>>
243
+ types?: NoInfer<TypesConfig<TEntity, TState, TEvents>>
179
244
  /** The initial entities. With `autoCreateEntities`, those the store creates itself can be left out. */
180
245
  entities?: Partial<TState>
181
246
  systems?: System<TState>[]
@@ -201,10 +266,12 @@ export type Unsubscribe = () => void
201
266
  export interface Store<
202
267
  TEntity extends BaseEntity = BaseEntity,
203
268
  TState extends EntitiesState<TEntity> = EntitiesState<TEntity>,
269
+ TEvents = AnyEvents,
204
270
  > {
205
271
  subscribe: (listener: Listener) => Unsubscribe
206
272
  update: () => Event[]
207
- notify: (type: string, payload?: any) => void
273
+ /** Sends an event; told the store's events, it checks them (see `Notify`). */
274
+ notify: Notify<TEvents, TEntity>
208
275
  dispatch: (event: Event) => void
209
276
  getTypes: () => Record<string, EntityType>
210
277
  getType: (typeName: string) => EntityType
@@ -218,7 +285,7 @@ export interface Store<
218
285
  }
219
286
  setState: (nextState: TState) => void
220
287
  reset: () => void
221
- _api?: Api<TEntity, TState>
288
+ _api?: Api<TEntity, TState, TEvents>
222
289
  extras?: Record<string, any>
223
290
  }
224
291
 
@@ -248,9 +315,14 @@ export type AddEventPayload<TEntity extends BaseEntity = BaseEntity> =
248
315
  export type RemoveEventPayload = string
249
316
 
250
317
  /**
251
- * Creates a store to manage state and events
318
+ * Creates a store to manage state and events. Told the app's events as a
319
+ * third type argument, its `notify` and its handlers' api check them:
320
+ * `createStore<AppEntity, AppState, AppEvents>({ ... })`.
252
321
  */
253
322
  export function createStore<
254
323
  TEntity extends BaseEntity = BaseEntity,
255
324
  TState extends EntitiesState<TEntity> = EntitiesState<TEntity>,
256
- >(config: StoreConfig<TEntity, TState>): Store<TEntity, TState>
325
+ TEvents = AnyEvents,
326
+ >(
327
+ config: StoreConfig<TEntity, TState, TEvents>,
328
+ ): Store<TEntity, TState, TEvents>