@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/src/store.js CHANGED
@@ -1,55 +1,67 @@
1
1
  import { clone } from "@inglorious/utils/data-structures/object.js"
2
- import { toCamelCase } from "@inglorious/utils/data-structures/string.js"
3
- import { create } from "mutative"
2
+ import {
3
+ namesNear,
4
+ toCamelCase,
5
+ } from "@inglorious/utils/data-structures/string.js"
6
+ import { create, current, isDraft, original } from "mutative"
4
7
 
5
8
  import { createApi } from "./api.js"
6
9
  import { augmentEntities, augmentEntity } from "./entities.js"
7
10
  import { EventMap, parseEvent } from "./event-map.js"
8
11
  import { applyMiddlewares } from "./middlewares.js"
12
+ import { compute, createSelector } from "./select.js"
9
13
  import { augmentType, augmentTypes } from "./types.js"
10
14
 
11
- /** Copies only the entities that change, using a draft proxy. */
15
+ /** Copies only the entities that change, through a draft proxy. */
12
16
  const STRUCTURAL_SHARING = "structural-sharing"
13
17
 
14
- /** Deep-copies each entity as it is handed out, and applies events to the copy, without a proxy. */
18
+ /** Deep-copies each entity as it is handed out, with no proxy. */
15
19
  const COPY_ON_DISPATCH = "copy-on-dispatch"
16
20
 
17
21
  const UPDATE_STRATEGIES = [STRUCTURAL_SHARING, COPY_ON_DISPATCH]
18
22
 
23
+ /** Every engine's message for touching a revoked proxy says "revoked". */
24
+ const REVOKED = /revoked/i
25
+
26
+ /** What engines say when code writes to a frozen object. */
27
+ const FROZEN = /read[- ]only|not extensible|cannot (assign|delete|define)/i
28
+
29
+ /** Events every entity gets, whether or not its type answers them. */
30
+ const LIFECYCLE_EVENTS = ["create", "destroy"]
31
+
19
32
  /**
20
33
  * Creates a store to manage state and events.
21
34
  *
22
- * Events are queued and drained by {@link createStore|update}. The `updateStrategy` option
23
- * controls how the state is copied before the queued events are applied:
35
+ * Events are queued and applied one at a time, each in a transaction of its own:
36
+ * the handlers of one event all see the state as it was before that event, through
37
+ * `api.getEntity()` and `api.getEntities()`, and the next event in the queue sees what
38
+ * the previous one changed. Subscribers are notified once the queue is empty.
24
39
  *
25
- * - `"structural-sharing"` (default) - Applies events to a draft proxy, so only the entities
26
- * that actually changed are copied. Unchanged entities keep their previous reference, which
27
- * makes change detection cheap for consumers that rely on reference equality. This is the
28
- * right choice for UI stores, where a small number of entities change at a time.
29
- * - `"copy-on-dispatch"` - Deep-copies each entity the first time it is handed to a handler or read by
30
- * a system, and applies events directly to the copy, without a proxy. Entities nothing touches
31
- * are not copied, and there is no per-entity proxy overhead, so it scales better when
32
- * thousands of entities change every frame, as in a game simulation.
40
+ * The `updateStrategy` option controls how an event's changes are copied:
33
41
  *
34
- * Under both strategies the current state is kept intact while the queued events are applied to a
35
- * separate draft, and the two are swapped only once every event has been processed. Handlers and
36
- * systems therefore always receive the draft as their first argument and mutate it directly, and
37
- * subscribers are notified only after the swap. This also means that, during an update,
38
- * `api.getEntity()` and `api.getEntities()` read the *previous* state rather than the in-flight
39
- * changes, under either strategy.
42
+ * - `"structural-sharing"` (default) - Applies the event to a draft proxy, so only the
43
+ * entities that actually changed are copied. Unchanged entities keep their previous
44
+ * reference, which makes reference-equality change detection cheap. The right choice
45
+ * for UI stores, where a few entities change at a time.
46
+ * - `"copy-on-dispatch"` - Deep-copies each entity the first time the event hands it to a
47
+ * handler or a system, and applies the event to the copy, without a proxy. It scales
48
+ * better when thousands of entities change every frame, as in a game simulation.
40
49
  *
41
50
  * @param {StoreConfig} config - Configuration options for the store.
42
51
  * @param {Types} [config.types] - The initial types configuration.
43
52
  * @param {Entities} [config.entities] - The initial entities configuration.
44
- * @param {Object[]} [config.systems] - The initial systems configuration.
53
+ * @param {Object[]} [config.systems] - Handlers that receive every entity at once, run after the entities' own handlers.
45
54
  * @param {Function[]} [config.middlewares] - Functions that each take the store and return it,
46
55
  * changed or wrapped. The first wraps all the others, so events pass through them in order.
47
- * @param {boolean} [config.autoCreateEntities=false] - Creates entities if not defined in `config.entities`.
56
+ * @param {boolean} [config.autoCreateEntities=false] - Creates an entity for each type that has none.
48
57
  * @param {"auto" | "manual"} [config.updateMode="auto"] - Whether each event triggers an update, or updates are batched until `update()` is called.
49
- * @param {UpdateStrategy} [config.updateStrategy="structural-sharing"] - How the state is copied before events are applied.
58
+ * @param {UpdateStrategy} [config.updateStrategy="structural-sharing"] - How an event's changes are copied.
59
+ * @param {boolean} [config.devMode=false] - Under structural sharing, freezes the state, so a write to an entity a handler was not given throws an error that says so.
50
60
  * @returns {Store} The store with methods to interact with state and events.
51
61
  * @throws {TypeError} If `updateStrategy` is not a supported strategy.
52
62
  */
63
+ export { compute, createSelector }
64
+
53
65
  export function createStore({
54
66
  types: originalTypes = {},
55
67
  entities: originalEntities = {},
@@ -58,14 +70,17 @@ export function createStore({
58
70
  autoCreateEntities = false,
59
71
  updateMode = "auto",
60
72
  updateStrategy = STRUCTURAL_SHARING,
73
+ devMode = false,
61
74
  } = {}) {
62
75
  assertUpdateStrategy(updateStrategy)
63
76
 
64
77
  const listeners = new Set()
78
+ const warned = new Set()
65
79
 
66
80
  const types = augmentTypes(originalTypes)
67
81
 
68
- let state, eventMap, incomingEvents, isProcessing, isHalted
82
+ let state, activeDraft, eventMap, incomingEvents, isProcessing, isNotifying
83
+ let isHalted
69
84
  reset()
70
85
 
71
86
  const baseStore = {
@@ -106,155 +121,164 @@ export function createStore({
106
121
  }
107
122
 
108
123
  /**
109
- * Updates the state based on elapsed time and processes events.
110
- *
111
- * The current state is left untouched while the queued events are applied to a separate
112
- * draft, according to the configured `updateStrategy`. The draft only replaces the current
113
- * state once every queued event has been processed, and subscribers are notified afterwards.
124
+ * Applies the queued events and notifies subscribers once. Each event is a
125
+ * transaction: its handlers see, through the api, the state as the previous
126
+ * event left it, and the next event sees what they changed. An event notified
127
+ * by a subscriber is queued and applied after the subscribers have run, so a
128
+ * render never nests inside another.
114
129
  *
115
130
  * @returns {Event[]} The events processed during this update.
116
131
  */
117
132
  function update() {
118
- if (isProcessing) {
119
- return []
120
- }
121
-
122
- if (!incomingEvents.length) {
133
+ if (isProcessing || !incomingEvents.length) {
123
134
  return []
124
135
  }
125
136
 
126
137
  isProcessing = true
127
138
  const processedEvents = []
128
- let nextState
129
-
130
- if (updateStrategy === STRUCTURAL_SHARING) {
131
- nextState = create(state, (draft) => patch(writeThrough(draft)), {
132
- enableAutoFreeze: state.game?.devMode,
133
- })
134
- } else {
135
- const draft = copyOnDispatch(state)
136
139
 
137
- patch(draft)
138
- nextState = draft.entities
140
+ try {
141
+ if (updateStrategy === STRUCTURAL_SHARING) {
142
+ state = create(state, (root) => drain(writeThrough(root)), {
143
+ enableAutoFreeze: devMode,
144
+ })
145
+ } else {
146
+ const draft = copyOnDispatch(state)
147
+ drain(draft)
148
+ state = draft.entities
149
+ }
150
+ } catch (error) {
151
+ // The update is rolled back whole, and the events still queued with it.
152
+ incomingEvents = []
153
+ throw error
154
+ } finally {
155
+ activeDraft = null
156
+ isProcessing = false
139
157
  }
140
158
 
141
- state = nextState
142
- isProcessing = false
143
-
159
+ isNotifying = true
144
160
  listeners.forEach((onUpdate) => onUpdate())
161
+ isNotifying = false
162
+
163
+ if (updateMode === "auto" && incomingEvents.length) {
164
+ update()
165
+ }
145
166
 
146
167
  return processedEvents
147
168
 
148
- /**
149
- * Applies every queued event to the given draft.
150
- *
151
- * The draft wraps either the proxy returned by `create` (structural sharing) or a
152
- * copy of the entity map whose entities are copied as they are handed out (copy on
153
- * dispatch). The current state is not modified, and only becomes the new state once
154
- * this function returns.
155
- *
156
- * A change made by a handler is not visible to the next handler in the same pass:
157
- * `getState` still returns the state as it was before the pass began. This is on
158
- * purpose -- every event in the pass sees one consistent world, rather than some
159
- * changes having landed and others not -- and it means a handler that asks what is
160
- * left is asking about the past. Anything reacting to a change should be told the
161
- * change rather than go looking for it.
162
- *
163
- * @param {Draft} draft - The draft to apply the queued events to.
164
- * @returns {void}
165
- */
166
- function patch(draft) {
169
+ function drain(draft) {
170
+ activeDraft = draft
167
171
  while (incomingEvents.length) {
168
172
  const event = incomingEvents.shift()
169
173
  processedEvents.push(event)
174
+ handle(draft, event)
175
+ draft.commit()
176
+ }
177
+ }
178
+ }
170
179
 
171
- if (event.type === "pause") {
172
- isHalted = true
173
- }
174
-
175
- if (event.type === "resume") {
176
- isHalted = false
177
- }
178
-
179
- if (event.type === "add") {
180
- addEntity(draft, event.payload)
181
- }
182
-
183
- if (event.type === "remove") {
184
- removeEntity(draft, event.payload)
185
- }
186
-
187
- if (event.type === "patch") {
188
- patchEntity(draft, event.payload)
189
- }
190
-
191
- if (event.type === "replace") {
192
- replaceEntity(draft, event.payload)
193
- }
194
-
195
- const { event: handlerName } = parseEvent(event.type)
196
-
197
- const entityIds = eventMap.getEntitiesForEvent(event.type)
198
-
199
- // A halted world stops handing out updates, because anything that moves by
200
- // integrating a delta time would otherwise carry on regardless. An entity that
201
- // sets `updatesWhilePaused` is exempt, which is how an overlay, a button or the
202
- // thing that takes the pause back off keeps working while the rest stands still.
203
- //
204
- // It is read off the entity rather than the type so that the type stays an index
205
- // signature of handlers, which is what lets it be called and indexed freely.
206
- const halted = isHalted && handlerName === "update"
207
-
208
- for (const id of entityIds) {
209
- const entity = draft.entities[id]
210
- const type = types[entity.type]
180
+ /**
181
+ * Hands one event to the store's own handling, then to the entities that answer
182
+ * it, then to the systems.
183
+ * @param {Draft} draft - The draft to apply the event to.
184
+ * @param {Event} event - The event.
185
+ * @returns {void}
186
+ */
187
+ function handle(draft, event) {
188
+ if (event.type === "pause") isHalted = true
189
+ if (event.type === "resume") isHalted = false
190
+ if (event.type === "add") addEntity(draft, event.payload)
191
+ if (event.type === "remove") removeEntity(event.payload)
192
+ if (event.type === "patch") patchEntity(draft, event.payload)
193
+ if (event.type === "replace") replaceEntity(draft, event.payload)
194
+
195
+ const {
196
+ type: targetType,
197
+ entityId: targetId,
198
+ event: handlerName,
199
+ } = parseEvent(event.type)
200
+ const entityIds = eventMap.getEntitiesForEvent(event.type)
201
+
202
+ if (!entityIds.length) {
203
+ warnIfUnanswered(draft, targetType, targetId, handlerName)
204
+ }
211
205
 
212
- if (halted && !entity.updatesWhilePaused) continue
206
+ // A halted world hands out no `update`, so anything that integrates a delta
207
+ // time stops. An entity with `updatesWhilePaused` is exempt. It is read off the
208
+ // entity rather than the type, so that a type stays an index signature of handlers.
209
+ const halted = isHalted && handlerName === "update"
213
210
 
214
- const handle = type[handlerName]
211
+ for (const id of entityIds) {
212
+ const entity = draft.entities[id]
213
+ if (halted && !entity.updatesWhilePaused) continue
215
214
 
216
- handle?.(draft.take(id), event.payload, api)
217
- }
215
+ const handler = types[entity.type][handlerName]
216
+ if (!handler) continue
218
217
 
219
- if (event.type.endsWith(":destroy")) {
220
- const [target] = event.type.split(":")
221
- const [, id] = target.split("#")
222
- const entity = draft.entities[id]
223
- if (entity) {
224
- const type = types[entity.type]
225
- const typeName = entity.type
226
- delete draft.entities[id]
227
-
228
- eventMap.removeEntity(id, type, typeName)
229
- }
230
- }
218
+ const result = callHandler(
219
+ () => handler(draft.take(id), event.payload, api),
220
+ `${entity.type}.${handlerName}`,
221
+ )
222
+ explainLateAccess(result, entity.type, handlerName)
223
+ }
231
224
 
232
- systems.forEach((system) => {
233
- const handle = system[handlerName]
234
- handle?.(draft.forSystems, event.payload, api)
235
- })
225
+ if (handlerName === "destroy" && targetId) {
226
+ const entity = draft.entities[targetId]
227
+ if (entity) {
228
+ draft.remove(targetId)
229
+ eventMap.removeEntity(targetId, types[entity.type], entity.type)
236
230
  }
237
231
  }
232
+
233
+ systems.forEach((system) => {
234
+ if (!system[handlerName]) return
235
+ callHandler(
236
+ () => system[handlerName](draft.forSystems, event.payload, api),
237
+ `A system's ${handlerName}`,
238
+ )
239
+ })
238
240
  }
239
241
 
240
242
  /**
241
- * Notifies the store of a new event.
242
- * Supports scoped events:
243
- * - 'submit' - broadcast to all entities with submit handler
244
- * - 'form:submit' - only form entities
245
- * - 'form[loginForm]:submit' - only loginForm entity
243
+ * Notifies the store of a new event. Supports scoped events:
244
+ * - 'submit' - broadcast to all entities with a submit handler
245
+ * - 'Form:submit' - only Form entities
246
+ * - '#loginForm:submit' - only the loginForm entity
246
247
  *
247
- * Two of these are the store's own. 'pause' stops the store handing out 'update'
248
- * events, and 'resume' starts it again, which is how anything that moves by
249
- * integrating a delta time stops without being told about it. A type declares
250
- * `updatesWhilePaused` to keep updating regardless. Both keep dispatching to types
248
+ * `pause` stops the store handing out `update` events and `resume` starts it again;
249
+ * an entity with `updatesWhilePaused` keeps updating. Both still reach the types
250
+ * that handle them.
251
251
  *
252
252
  * @param {string} type - The event type to notify.
253
253
  * @param {any} payload - The event payload. Carries the least that can be had
254
254
  * about what happened.
255
255
  */
256
+ /**
257
+ * Calls a handler. In dev mode, where the state is frozen, a write to a
258
+ * frozen object can only be a write to an entity the handler was not given,
259
+ * such as one read through the api: say so.
260
+ * @param {() => unknown} call - The handler, called.
261
+ * @param {string} name - Who the handler is, for the message.
262
+ * @returns {unknown} What the handler returned.
263
+ */
264
+ function callHandler(call, name) {
265
+ if (!devMode) return call()
266
+
267
+ try {
268
+ return call()
269
+ } catch (error) {
270
+ if (!(error instanceof TypeError) || !FROZEN.test(error.message)) {
271
+ throw error
272
+ }
273
+ throw new TypeError(
274
+ `${name} wrote to an entity it was not given, such as one read with api.getEntity() or api.getEntities(). Those are the state as the previous event left it, and are read-only: notify an event to that entity instead.`,
275
+ { cause: error },
276
+ )
277
+ }
278
+ }
279
+
256
280
  function notify(type, payload) {
257
- // NOTE: it's important to invoke store.dispatch instead of dispatch, otherwise we cannot override it
281
+ // Through store.dispatch rather than dispatch, so that middlewares see it.
258
282
  store.dispatch({ type, payload })
259
283
  }
260
284
 
@@ -266,14 +290,13 @@ export function createStore({
266
290
  */
267
291
  function dispatch(event) {
268
292
  incomingEvents.push(event)
269
- if (updateMode === "auto") {
293
+ if (updateMode === "auto" && !isNotifying) {
270
294
  update()
271
295
  }
272
296
  }
273
297
 
274
298
  /**
275
299
  * Retrieves the augmented types configuration.
276
- * This includes composed behaviors and event handlers wrapped for immutability.
277
300
  * @returns {Object} The augmented types configuration.
278
301
  */
279
302
  function getTypes() {
@@ -314,12 +337,8 @@ export function createStore({
314
337
  }
315
338
  }
316
339
 
317
- const entityId = toCamelCase(typeName)
318
- if (autoCreateEntities && !state[entityId]) {
319
- notify("add", {
320
- id: entityId,
321
- type: typeName,
322
- })
340
+ if (autoCreateEntities && !hasEntityOfType(typeName)) {
341
+ notify("add", { id: toCamelCase(typeName), type: typeName })
323
342
  }
324
343
 
325
344
  if (oldType) {
@@ -332,32 +351,29 @@ export function createStore({
332
351
  * @returns {Object} The current state.
333
352
  */
334
353
  function getState() {
335
- return state
354
+ return activeDraft ? activeDraft.readAll() : state
336
355
  }
337
356
 
338
357
  /**
339
- * One entity by its id, or `undefined` if there is no such entity.
340
- *
341
- * This is what `api.getEntity` answers with during a handler, exposed here for the
342
- * code that runs outside one: a test looking at a world it is driving, or anything else
343
- * holding the store rather than an event's `api`.
358
+ * One entity by its id, or `undefined` if there is no such entity. During an
359
+ * update, as the previous event left it.
344
360
  *
345
361
  * @param {string} id - The entity's id.
346
- * @returns {Object|undefined} The entity, as the last finished pass left it.
362
+ * @returns {Object|undefined} The entity.
347
363
  */
348
364
  function getEntity(id) {
349
- return state?.[id]
365
+ return activeDraft ? activeDraft.read(id) : state?.[id]
350
366
  }
351
367
 
352
368
  /**
353
- * Sets the entire state of the store.
354
- * This is useful for importing state or setting initial state from a server.
369
+ * Sets the entire state of the store, such as state coming from a server.
370
+ * Entities that are new get `create`, entities that are gone get `destroy`.
355
371
  * @param {Entities} nextState - The new state to set.
356
372
  * @returns {void}
357
373
  */
358
374
  function setState(nextState) {
359
375
  const oldEntities = state ?? {}
360
- let newEntities = augmentEntities(nextState)
376
+ const newEntities = augmentEntities(nextState)
361
377
 
362
378
  const oldEntityIds = new Set(Object.keys(oldEntities))
363
379
  const newEntityIds = new Set(Object.keys(newEntities))
@@ -372,13 +388,15 @@ export function createStore({
372
388
  oldEntityIds.has(id),
373
389
  )
374
390
 
375
- state = oldEntities
391
+ state = { ...oldEntities }
376
392
  eventMap = new EventMap(types, oldEntities)
393
+ activeDraft = null
377
394
  incomingEvents = []
378
395
  isProcessing = false
396
+ isNotifying = false
379
397
 
380
398
  entitiesToDestroy.forEach((id) => {
381
- removeEntity(state, id)
399
+ removeEntity(id)
382
400
  })
383
401
 
384
402
  entitiesToCreate.forEach((id) => {
@@ -399,16 +417,16 @@ export function createStore({
399
417
 
400
418
  if (autoCreateEntities) {
401
419
  for (const typeName of Object.keys(types)) {
402
- const entityId = toCamelCase(typeName)
403
- const hasEntity = Object.values(state).some(
404
- (entity) => entity.type === typeName,
405
- )
406
-
407
- if (!hasEntity) {
408
- addEntity(writeThrough(state), { id: entityId, type: typeName })
420
+ if (!hasEntityOfType(typeName)) {
421
+ addEntity(writeThrough(state), {
422
+ id: toCamelCase(typeName),
423
+ type: typeName,
424
+ })
409
425
  }
410
426
  }
411
427
  }
428
+
429
+ if (devMode && updateStrategy === STRUCTURAL_SHARING) deepFreeze(state)
412
430
  }
413
431
 
414
432
  /**
@@ -429,26 +447,20 @@ export function createStore({
429
447
  function addEntity(draft, payload) {
430
448
  const { id, ...entity } = payload
431
449
  draft.put(id, augmentEntity(id, entity))
432
- const type = types[entity.type]
450
+ warnIfUndeclared(id, entity.type)
433
451
 
434
- eventMap.addEntity(id, type, entity.type)
452
+ eventMap.addEntity(id, types[entity.type], entity.type)
435
453
  incomingEvents.unshift({ type: `#${id}:create` })
436
454
  }
437
455
 
438
456
  /**
439
- * Moves a standing thing onto the handlers of whatever type it now names.
440
- *
441
- * A type is the only thing about a thing that cannot be merged: there is no such thing
442
- * as being half a sort, so naming a different one means taking the thing out of the old
443
- * one's list of entities before putting it in the new one.
444
- *
445
- * @param {Draft} draft - The draft it stands in.
446
- * @param {string} id - The thing being moved.
457
+ * Moves an entity onto the handlers of the type it now names, if it changed.
458
+ * @param {string} id - The entity.
447
459
  * @param {string} previousType - The type it was under.
448
- * @param {string|undefined} type - The type it is under now, if it has named one.
460
+ * @param {string|undefined} type - The type it is under now, if it named one.
449
461
  * @returns {void}
450
462
  */
451
- function moveToType(draft, id, previousType, type) {
463
+ function moveToType(id, previousType, type) {
452
464
  if (!type || type === previousType) return
453
465
 
454
466
  eventMap.removeEntity(id, types[previousType], previousType)
@@ -456,40 +468,29 @@ export function createStore({
456
468
  }
457
469
 
458
470
  /**
459
- * Merges a new configuration into a thing that is already standing.
460
- *
461
- * Only the fields the configuration names are touched, so anything the world has done
462
- * to the thing since it was made survives unless the
463
- * new configuration says otherwise. A field named as `undefined` is set to nothing,
464
- * which is what taking a key off a mapping means.
465
- *
471
+ * Merges a configuration into an existing entity. Only the fields it names
472
+ * change; a field set to `undefined` is cleared.
466
473
  * @param {Draft} draft - The draft to change it in.
467
- * @param {Entity} payload - The thing and the fields to merge into it.
474
+ * @param {Entity} payload - The entity's id and the fields to merge.
468
475
  * @returns {void}
469
476
  */
470
477
  function patchEntity(draft, payload) {
471
478
  const { id, ...config } = payload
472
- // Taken rather than looked at, because the merge keeps whatever the configuration
473
- // does not mention, and what it keeps must not be shared with the previous state.
479
+ // Taken rather than read, so that what the merge keeps is not shared with the
480
+ // previous state.
474
481
  const existing = draft.take(id)
475
482
 
476
483
  if (!existing) return
477
484
 
478
485
  draft.put(id, augmentEntity(id, { ...existing, ...config }))
479
486
 
480
- moveToType(draft, id, existing.type, config.type)
487
+ moveToType(id, existing.type, config.type)
481
488
  }
482
489
 
483
490
  /**
484
- * Installs a new configuration on a standing thing, dropping what it does not mention.
485
- *
486
- * The thing keeps its place in the world and its name; everything else is whatever it
487
- * is told, and anything it is not told is gone. A field set to `undefined` is set to
488
- * nothing here as much as it is in a patch -- the difference between the two is what
489
- * happens to the fields neither mentions.
490
- *
491
+ * Replaces an existing entity with a configuration, dropping what it does not name.
491
492
  * @param {Draft} draft - The draft to change it in.
492
- * @param {Entity} payload - The thing and the fields it is to be.
493
+ * @param {Entity} payload - The entity's id and the fields it is to have.
493
494
  * @returns {void}
494
495
  */
495
496
  function replaceEntity(draft, payload) {
@@ -500,19 +501,94 @@ export function createStore({
500
501
 
501
502
  draft.put(id, augmentEntity(id, config))
502
503
 
503
- moveToType(draft, id, existing.type, config.type)
504
+ moveToType(id, existing.type, config.type)
504
505
  }
505
506
 
506
507
  /**
507
- * Queues the destruction of an entity. The entity is removed by the `#id:destroy` event.
508
- * @param {Draft|Entities} draft - Where it stands. The removal itself is queued, so
509
- * nothing is written to it here.
508
+ * Queues the destruction of an entity: the `#id:destroy` event removes it.
510
509
  * @param {string} id - The id of the entity to remove.
511
510
  * @returns {void}
512
511
  */
513
- function removeEntity(draft, id) {
512
+ function removeEntity(id) {
514
513
  incomingEvents.unshift({ type: `#${id}:destroy` })
515
514
  }
515
+
516
+ function hasEntityOfType(typeName) {
517
+ return Object.values(state).some((entity) => entity.type === typeName)
518
+ }
519
+
520
+ /**
521
+ * Warns once about an entity whose type looks like a misspelling of a declared
522
+ * one. A type with no declared name near it may still be registered later, as
523
+ * a lazily loaded page's is, so nothing is said about it.
524
+ * @param {string} id - The entity.
525
+ * @param {string} typeName - The type it names.
526
+ * @returns {void}
527
+ */
528
+ function warnIfUndeclared(id, typeName) {
529
+ if (types[typeName]) return
530
+
531
+ const near = namesNear(typeName, Object.keys(types))
532
+ if (!near.length) return
533
+
534
+ warnOnce(
535
+ `undeclared:${typeName}`,
536
+ `Entity "${id}" has type "${typeName}", which is not declared: did you mean ${near.map((name) => `"${name}"`).join(" or ")}?`,
537
+ )
538
+ }
539
+
540
+ /**
541
+ * Warns once about a targeted event that nothing answers: an entity whose type
542
+ * has no such handler, or a type name that is not declared. A broadcast that
543
+ * nobody answers is fine, and so is an entity that is gone or whose type is
544
+ * still to come.
545
+ * @param {Draft} draft - The draft the event was applied to.
546
+ * @param {string|null} targetType - The type the event names.
547
+ * @param {string|null} targetId - The entity the event names.
548
+ * @param {string} handlerName - The event.
549
+ * @returns {void}
550
+ */
551
+ function warnIfUnanswered(draft, targetType, targetId, handlerName) {
552
+ if (LIFECYCLE_EVENTS.includes(handlerName)) return
553
+ if (systems.some((system) => system[handlerName])) return
554
+
555
+ if (targetId) {
556
+ const entity = draft.entities[targetId]
557
+ const type = entity && types[entity.type]
558
+ if (!type || type[handlerName]) return
559
+
560
+ warnOnce(
561
+ `${entity.type}:${handlerName}`,
562
+ `"${handlerName}" reached "${targetId}", whose type "${entity.type}" has no such handler.`,
563
+ )
564
+ return
565
+ }
566
+
567
+ if (!targetType) return
568
+
569
+ const type = types[targetType]
570
+ if (!type) {
571
+ const near = namesNear(targetType, Object.keys(types))
572
+ warnOnce(
573
+ `type:${targetType}`,
574
+ `"${targetType}:${handlerName}" names a type that is not declared${near.length ? `: did you mean ${near.map((name) => `"${name}"`).join(" or ")}?` : "."}`,
575
+ )
576
+ return
577
+ }
578
+
579
+ if (type[handlerName]) return
580
+
581
+ warnOnce(
582
+ `${targetType}:${handlerName}`,
583
+ `"${targetType}:${handlerName}" reached no entity: the type has no such handler.`,
584
+ )
585
+ }
586
+
587
+ function warnOnce(key, message) {
588
+ if (warned.has(key)) return
589
+ warned.add(key)
590
+ console.warn(`[store] ${message}`)
591
+ }
516
592
  }
517
593
 
518
594
  /**
@@ -532,64 +608,102 @@ export function defineType() {
532
608
  }
533
609
 
534
610
  /**
535
- * A draft that writes straight into the entities it is given.
536
- *
537
- * This is the whole of structural sharing's draft, because Mutative's proxy already copies
538
- * an entity the moment it is written to, and of the state being built by `setState`,
539
- * which has no previous state to protect.
611
+ * A draft over Mutative's proxy, which copies an entity the moment it is written
612
+ * to. What an event reads through the api is what stood before the event: an
613
+ * entity no earlier event of the pass wrote to is read from the original state,
614
+ * and the value of one that an earlier event wrote to is kept when this event
615
+ * writes to it again.
540
616
  *
541
617
  * @param {Entities} entities - The entities to write into.
542
618
  * @returns {Draft} The draft.
543
619
  */
544
620
  function writeThrough(entities) {
621
+ const base = isDraft(entities) ? original(entities) : entities
622
+ const writtenEarlier = new Set()
623
+ const before = new Map()
624
+ let all = null
625
+
626
+ function remember(id) {
627
+ if (before.has(id)) return
628
+ before.set(id, writtenEarlier.has(id) ? plain(entities[id]) : base[id])
629
+ }
630
+
545
631
  return {
546
632
  entities,
547
633
  forSystems: entities,
548
- take: (id) => entities[id],
634
+ take(id) {
635
+ remember(id)
636
+ return entities[id]
637
+ },
549
638
  put(id, entity) {
639
+ remember(id)
550
640
  entities[id] = entity
551
641
  },
642
+ remove(id) {
643
+ remember(id)
644
+ delete entities[id]
645
+ },
646
+ read(id) {
647
+ if (before.has(id)) return before.get(id)
648
+ return writtenEarlier.has(id) ? plain(entities[id]) : base[id]
649
+ },
650
+ readAll() {
651
+ if (!all) {
652
+ all = { ...base }
653
+ for (const id of writtenEarlier) {
654
+ if (Object.hasOwn(entities, id)) all[id] = plain(entities[id])
655
+ else delete all[id]
656
+ }
657
+ all = overlay(all, before)
658
+ }
659
+ return all
660
+ },
661
+ commit() {
662
+ for (const id of before.keys()) writtenEarlier.add(id)
663
+ before.clear()
664
+ all = null
665
+ },
552
666
  }
553
667
  }
554
668
 
555
669
  /**
556
- * A draft that copies an entity the first time it is handed to anything that could
557
- * write to it.
558
- *
559
- * This is what `copy-on-dispatch` is named after: an entity is copied when an event is
560
- * dispatched to it, and the entities that nothing touches are never paid for. The map is
561
- * copied straight away, which is cheap -- a reference for every entity -- and an entity
562
- * is deep-copied only when it is taken: handed to one of its handlers, merged by a
563
- * `patch`, or read by a system. A frame on which only the pointer moves copies the
564
- * pointer, and a frame on which nothing at all happens copies nothing but the map.
565
- *
566
- * There is no proxy on the entities themselves, which is what still sets this apart
567
- * from structural sharing: a handler is given a plain object, and pays nothing for
568
- * writing to it however many times it does. The one proxy is over the map handed to
569
- * systems, which have no single entity to be given and so have to be given all of them.
570
- * Each entity a system reads through it is taken, which means a system that walks every
571
- * entity copies every entity: one that only needs to know how things stood can ask
572
- * `api.getEntities()` instead, and take only what it writes to.
670
+ * A draft that copies an entity the first time an event hands it to anything
671
+ * that could write to it: one of its handlers, a `patch`, or a system. The map
672
+ * is copied once, which costs a reference per entity, and the entities nothing
673
+ * touches are never copied. The copy an earlier event made is what a later
674
+ * event reads, and is copied again if that event writes to it. A system that
675
+ * only reads should go through `api.getEntities()`, since each entity it reads
676
+ * through its first argument is copied.
573
677
  *
574
678
  * @param {Entities} state - The state to leave as it is.
575
679
  * @returns {Draft} The draft.
576
680
  */
577
681
  function copyOnDispatch(state) {
578
682
  const entities = { ...state }
579
- const taken = new Set()
683
+ const before = new Map()
684
+ let all = null
685
+
686
+ function remember(id) {
687
+ if (!before.has(id)) before.set(id, entities[id])
688
+ }
580
689
 
581
690
  function take(id) {
582
- if (!taken.has(id) && Object.hasOwn(entities, id)) {
691
+ if (!before.has(id) && Object.hasOwn(entities, id)) {
692
+ before.set(id, entities[id])
583
693
  entities[id] = clone(entities[id])
584
- taken.add(id)
585
694
  }
586
695
 
587
696
  return entities[id]
588
697
  }
589
698
 
590
699
  function put(id, entity) {
700
+ remember(id)
591
701
  entities[id] = entity
592
- taken.add(id)
702
+ }
703
+
704
+ function remove(id) {
705
+ remember(id)
706
+ delete entities[id]
593
707
  }
594
708
 
595
709
  const forSystems = new Proxy(entities, {
@@ -603,9 +717,92 @@ function copyOnDispatch(state) {
603
717
  put(key, value)
604
718
  return true
605
719
  },
720
+
721
+ deleteProperty(target, key) {
722
+ remove(key)
723
+ return true
724
+ },
606
725
  })
607
726
 
608
- return { entities, forSystems, take, put }
727
+ return {
728
+ entities,
729
+ forSystems,
730
+ take,
731
+ put,
732
+ remove,
733
+ read(id) {
734
+ return before.has(id) ? before.get(id) : entities[id]
735
+ },
736
+ readAll() {
737
+ all ??= overlay(entities, before)
738
+ return all
739
+ },
740
+ commit() {
741
+ before.clear()
742
+ all = null
743
+ },
744
+ }
745
+ }
746
+
747
+ /**
748
+ * The value of a draft as it stands, or the value itself if it is not a draft.
749
+ * @param {any} value - A draft or a plain value.
750
+ * @returns {any} A plain value.
751
+ */
752
+ function plain(value) {
753
+ return isDraft(value) ? current(value) : value
754
+ }
755
+
756
+ /**
757
+ * The entities with the values kept from before the event put back.
758
+ * @param {Entities} entities - The entities as they stand.
759
+ * @param {Map<string, Entity|undefined>} before - The values from before the event.
760
+ * @returns {Entities} The entities as they stood before the event.
761
+ */
762
+ function overlay(entities, before) {
763
+ const all = { ...entities }
764
+ for (const [id, entity] of before) {
765
+ if (entity === undefined) delete all[id]
766
+ else all[id] = entity
767
+ }
768
+ return all
769
+ }
770
+
771
+ /**
772
+ * Freezes an object and everything it holds.
773
+ * @param {unknown} value
774
+ * @returns {unknown} The value.
775
+ */
776
+ function deepFreeze(value) {
777
+ if (value === null || typeof value !== "object" || Object.isFrozen(value)) {
778
+ return value
779
+ }
780
+ Object.freeze(value)
781
+ for (const child of Object.values(value)) deepFreeze(child)
782
+ return value
783
+ }
784
+
785
+ /**
786
+ * Gives a clearer error when an async handler touches its entity after an
787
+ * `await`: the entity is a draft of the update, revoked once the update ends.
788
+ * @param {unknown} result - What the handler returned.
789
+ * @param {string} typeName - The handler's type.
790
+ * @param {string} handlerName - The handler.
791
+ * @returns {void}
792
+ */
793
+ function explainLateAccess(result, typeName, handlerName) {
794
+ if (typeof result?.then !== "function") return
795
+
796
+ result.then(undefined, (error) => {
797
+ if (!(error instanceof TypeError) || !REVOKED.test(error.message)) {
798
+ throw error
799
+ }
800
+
801
+ throw new TypeError(
802
+ `${typeName}.${handlerName} accessed its entity after an async operation, when the update it belonged to had ended. Read what you need from the entity into a variable before the first await, or notify a new event after it and let that event's handler change the entity.`,
803
+ { cause: error },
804
+ )
805
+ })
609
806
  }
610
807
 
611
808
  /**
@@ -625,17 +822,22 @@ function assertUpdateStrategy(updateStrategy) {
625
822
  }
626
823
 
627
824
  /**
628
- * @typedef {"structural-sharing" | "copy-on-dispatch"} UpdateStrategy - How the state is copied before events are applied.
825
+ * @typedef {"structural-sharing" | "copy-on-dispatch"} UpdateStrategy - How an event's changes are copied.
629
826
  * @typedef {Object} StoreConfig - Configuration options accepted by {@link createStore}.
630
827
  * @typedef {Object.<string, any>} Type - An augmented entity type.
631
828
  * @typedef {Object.<string, Type>} Types - A collection of augmented types.
632
829
  * @typedef {Object.<string, any>} Entity - An object representing an entity.
633
830
  * @typedef {Object.<string, Entity>} Entities - A collection of entities indexed by id.
634
- * @typedef {Object} Draft - The entities an update writes to, and how it gets at them.
831
+ * @typedef {{ type: string, payload?: any }} Event - An event.
832
+ * @typedef {Object} Draft - The entities an event writes to, and how it gets at them.
635
833
  * @property {Entities} Draft.entities - The entities being built, read without copying.
636
834
  * @property {Entities} Draft.forSystems - The entities as handed to systems.
637
835
  * @property {(id: string) => Entity|undefined} Draft.take - The entity to write to.
638
836
  * @property {(id: string, entity: Entity) => void} Draft.put - Sets an entity outright.
837
+ * @property {(id: string) => void} Draft.remove - Deletes an entity.
838
+ * @property {(id: string) => Entity|undefined} Draft.read - An entity as it stood before the event.
839
+ * @property {() => Entities} Draft.readAll - The entities as they stood before the event.
840
+ * @property {() => void} Draft.commit - Ends the event: what it changed is what the next one reads.
639
841
  * @typedef {(listener: () => void) => () => void} Listener - Subscribes to state updates and returns an unsubscribe function.
640
842
  * @typedef {Object} Store - The store returned by {@link createStore}.
641
843
  */