@typeonce/effect-machine 0.33.0 → 0.35.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.
Files changed (137) hide show
  1. package/README.md +272 -628
  2. package/dist/Machine.d.ts +1076 -896
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +141 -90
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/childRegistry.d.ts +1 -1
  7. package/dist/internal/machine/childRegistry.d.ts.map +1 -1
  8. package/dist/internal/machine/cluster.d.ts +2 -50
  9. package/dist/internal/machine/cluster.d.ts.map +1 -1
  10. package/dist/internal/machine/cluster.js +4 -27
  11. package/dist/internal/machine/cluster.js.map +1 -1
  12. package/dist/internal/machine/clusterProtocol.d.ts +35 -0
  13. package/dist/internal/machine/clusterProtocol.d.ts.map +1 -0
  14. package/dist/internal/machine/clusterProtocol.js +28 -0
  15. package/dist/internal/machine/clusterProtocol.js.map +1 -0
  16. package/dist/internal/machine/commandRuntime.d.ts +1 -1
  17. package/dist/internal/machine/commandRuntime.d.ts.map +1 -1
  18. package/dist/internal/machine/configuration.d.ts +2 -2
  19. package/dist/internal/machine/configuration.d.ts.map +1 -1
  20. package/dist/internal/machine/configuration.js +38 -64
  21. package/dist/internal/machine/configuration.js.map +1 -1
  22. package/dist/internal/machine/declaration.d.ts +17 -0
  23. package/dist/internal/machine/declaration.d.ts.map +1 -0
  24. package/dist/internal/machine/declaration.js +120 -0
  25. package/dist/internal/machine/declaration.js.map +1 -0
  26. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  27. package/dist/internal/machine/executionPlan.js +15 -22
  28. package/dist/internal/machine/executionPlan.js.map +1 -1
  29. package/dist/internal/machine/implementation.d.ts +34 -0
  30. package/dist/internal/machine/implementation.d.ts.map +1 -0
  31. package/dist/internal/machine/implementation.js +3 -0
  32. package/dist/internal/machine/implementation.js.map +1 -0
  33. package/dist/internal/machine/initialDeclaration.d.ts +14 -0
  34. package/dist/internal/machine/initialDeclaration.d.ts.map +1 -0
  35. package/dist/internal/machine/initialDeclaration.js +137 -0
  36. package/dist/internal/machine/initialDeclaration.js.map +1 -0
  37. package/dist/internal/machine/invocation.d.ts +1 -1
  38. package/dist/internal/machine/invocation.d.ts.map +1 -1
  39. package/dist/internal/machine/invocation.js +1 -1
  40. package/dist/internal/machine/invocation.js.map +1 -1
  41. package/dist/internal/machine/invocationDefinition.d.ts +1 -1
  42. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  43. package/dist/internal/machine/machine.d.ts +13 -4
  44. package/dist/internal/machine/machine.d.ts.map +1 -1
  45. package/dist/internal/machine/machine.js +169 -388
  46. package/dist/internal/machine/machine.js.map +1 -1
  47. package/dist/internal/machine/planner.d.ts +8 -0
  48. package/dist/internal/machine/planner.d.ts.map +1 -1
  49. package/dist/internal/machine/planner.js +37 -78
  50. package/dist/internal/machine/planner.js.map +1 -1
  51. package/dist/internal/machine/process.d.ts +8 -7
  52. package/dist/internal/machine/process.d.ts.map +1 -1
  53. package/dist/internal/machine/process.js +16 -12
  54. package/dist/internal/machine/process.js.map +1 -1
  55. package/dist/internal/machine/protocol.d.ts +1 -1
  56. package/dist/internal/machine/protocol.d.ts.map +1 -1
  57. package/dist/internal/machine/protocol.js.map +1 -1
  58. package/dist/internal/machine/runtime.d.ts +2 -230
  59. package/dist/internal/machine/runtime.d.ts.map +1 -1
  60. package/dist/internal/machine/runtime.js +8 -1857
  61. package/dist/internal/machine/runtime.js.map +1 -1
  62. package/dist/internal/machine/runtimeCompiled.d.ts +5 -0
  63. package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -0
  64. package/dist/internal/machine/runtimeCompiled.js +867 -0
  65. package/dist/internal/machine/runtimeCompiled.js.map +1 -0
  66. package/dist/internal/machine/runtimeGeneric.d.ts +3 -0
  67. package/dist/internal/machine/runtimeGeneric.d.ts.map +1 -0
  68. package/dist/internal/machine/runtimeGeneric.js +471 -0
  69. package/dist/internal/machine/runtimeGeneric.js.map +1 -0
  70. package/dist/internal/machine/runtimeProtocol.d.ts +312 -0
  71. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -0
  72. package/dist/internal/machine/runtimeProtocol.js +561 -0
  73. package/dist/internal/machine/runtimeProtocol.js.map +1 -0
  74. package/dist/internal/machine/stateDefinition.d.ts +1 -1
  75. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  76. package/dist/internal/machine/stateDefinition.js +1 -13
  77. package/dist/internal/machine/stateDefinition.js.map +1 -1
  78. package/dist/internal/machine/targetReference.d.ts +15 -0
  79. package/dist/internal/machine/targetReference.d.ts.map +1 -0
  80. package/dist/internal/machine/targetReference.js +41 -0
  81. package/dist/internal/machine/targetReference.js.map +1 -0
  82. package/dist/internal/machine/topology.d.ts.map +1 -1
  83. package/dist/internal/machine/topology.js +5 -3
  84. package/dist/internal/machine/topology.js.map +1 -1
  85. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  86. package/dist/internal/testing/machine/finiteModel.js +53 -46
  87. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  88. package/dist/internal/testing/machine/probe.js +1 -1
  89. package/dist/internal/testing/machine/probe.js.map +1 -1
  90. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  91. package/dist/internal/testing/machine/verification.js +7 -1
  92. package/dist/internal/testing/machine/verification.js.map +1 -1
  93. package/dist/testing/MachineTest.d.ts +105 -73
  94. package/dist/testing/MachineTest.d.ts.map +1 -1
  95. package/dist/testing/MachineTest.js +105 -73
  96. package/dist/testing/MachineTest.js.map +1 -1
  97. package/dist/unstable/cluster/ClusterMachine.d.ts +18 -13
  98. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  99. package/dist/unstable/cluster/ClusterMachine.js +18 -25
  100. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  101. package/dist/unstable/reactivity/AtomMachine.d.ts +41 -24
  102. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  103. package/dist/unstable/reactivity/AtomMachine.js +41 -24
  104. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  105. package/docs/agent-guide.md +66 -91
  106. package/docs/machine-review.md +19 -49
  107. package/docs/root-api.md +62 -62
  108. package/package.json +1 -1
  109. package/src/Machine.ts +1836 -2907
  110. package/src/internal/machine/childRegistry.ts +1 -1
  111. package/src/internal/machine/cluster.ts +7 -73
  112. package/src/internal/machine/clusterProtocol.ts +56 -0
  113. package/src/internal/machine/commandRuntime.ts +1 -1
  114. package/src/internal/machine/configuration.ts +53 -65
  115. package/src/internal/machine/declaration.ts +140 -0
  116. package/src/internal/machine/executionPlan.ts +16 -22
  117. package/src/internal/machine/implementation.ts +41 -0
  118. package/src/internal/machine/initialDeclaration.ts +157 -0
  119. package/src/internal/machine/invocation.ts +3 -3
  120. package/src/internal/machine/invocationDefinition.ts +1 -1
  121. package/src/internal/machine/machine.ts +225 -576
  122. package/src/internal/machine/planner.ts +84 -118
  123. package/src/internal/machine/process.ts +40 -33
  124. package/src/internal/machine/protocol.ts +3 -3
  125. package/src/internal/machine/runtime.ts +20 -3037
  126. package/src/internal/machine/runtimeCompiled.ts +1166 -0
  127. package/src/internal/machine/runtimeGeneric.ts +799 -0
  128. package/src/internal/machine/runtimeProtocol.ts +1213 -0
  129. package/src/internal/machine/stateDefinition.ts +1 -15
  130. package/src/internal/machine/targetReference.ts +55 -0
  131. package/src/internal/machine/topology.ts +5 -3
  132. package/src/internal/testing/machine/finiteModel.ts +58 -53
  133. package/src/internal/testing/machine/probe.ts +1 -1
  134. package/src/internal/testing/machine/verification.ts +7 -1
  135. package/src/testing/MachineTest.ts +105 -73
  136. package/src/unstable/cluster/ClusterMachine.ts +22 -25
  137. package/src/unstable/reactivity/AtomMachine.ts +41 -24
@@ -28,24 +28,22 @@ import type {
28
28
  } from "../../Machine.js"
29
29
  import * as Activities from "./activities.js"
30
30
  import * as Configuration from "./configuration.js"
31
+ import * as Declaration from "./declaration.js"
31
32
  import type { ChildAlreadyExistsError, InfiniteTransitionError, StartupError } from "./errors.js"
33
+ import type { CapturedStateConfig } from "./implementation.js"
34
+ import * as InitialDeclaration from "./initialDeclaration.js"
32
35
  import * as InvocationDefinition from "./invocationDefinition.js"
33
36
  import * as internalPlanner from "./planner.js"
34
37
  import * as internalProcess from "./process.js"
35
38
  import * as Protocol from "./protocol.js"
36
39
  import type { EnsureExecutable } from "./readiness.js"
37
40
  import type { ExcludeCompatibleRuntime } from "./requirements.js"
38
- import * as internalRuntime from "./runtime.js"
41
+ import * as internalRuntime from "./runtimeProtocol.js"
39
42
  import * as Serialization from "./serialization.js"
40
43
  import * as StateDefinition from "./stateDefinition.js"
41
44
  import { ChildMachineLogicTypeId } from "./symbols.js"
42
- import {
43
- getLocalTargetScope,
44
- getTargetBuilderNode,
45
- makeSnapshotBuilder,
46
- makeTargetBuilder,
47
- withFrom
48
- } from "./targetBuilder.js"
45
+ import { getLocalTargetScope, makeTargetBuilder, withFrom } from "./targetBuilder.js"
46
+ import * as TargetReference from "./targetReference.js"
49
47
  import * as Topology from "./topology.js"
50
48
 
51
49
  export {
@@ -59,11 +57,14 @@ export {
59
57
  } from "./errors.js"
60
58
  export { ChildMachineLogicTypeId, InitialEventTypeId, SnapshotBuilderStateTypeId } from "./symbols.js"
61
59
 
60
+ /** Internal seam for the public target-reference factory and its opaque brand. */
61
+ export const TargetReferenceTypeId: typeof TargetReference.TypeId = TargetReference.TypeId
62
+ export const targets: (root: State<Machine.StateNodeConfig>) => { readonly root: TargetReference.Reference } =
63
+ TargetReference.make
64
+
62
65
  const TypeId = "~effect/Machine"
63
66
  const ParentTypeId = "~effect/Machine/Parent"
64
67
  export const InvokeTypeId: unique symbol = Symbol.for("effect/Machine/Invoke")
65
- export const TransitionTypeId: unique symbol = Symbol.for("effect/Machine/Transition")
66
- const InvokeBuilderDescriptorTypeId: unique symbol = Symbol("effect/Machine/InvokeBuilderDescriptor")
67
68
  const ChildMachineTypeId = "~effect/Machine/ChildMachine"
68
69
  type MachineRuntimeRequirement = internalRuntime.MachineRuntime
69
70
 
@@ -91,8 +92,8 @@ const Proto = {
91
92
  }
92
93
 
93
94
  const makeWithHandlers = (
94
- self: Definition.Any,
95
- handlers: Machine.StateConfigs<any, any, any, any, any, any, any>
95
+ self: Machine.Any,
96
+ handlers: Readonly<Record<string, CapturedStateConfig>>
96
97
  ): Machine.Any => {
97
98
  const machine = Object.create(Proto)
98
99
  machine.states = self.states
@@ -133,69 +134,11 @@ type CapturedNamedBranch = {
133
134
  readonly selection: Topology.TargetSelection
134
135
  }
135
136
 
136
- const TransitionBuilderDescriptorTypeId: unique symbol = Symbol("effect/Machine/TransitionBuilderDescriptor")
137
-
138
- type DirectTransitionDescriptor = {
139
- readonly [TransitionBuilderDescriptorTypeId]: typeof TransitionBuilderDescriptorTypeId
140
- readonly type: "direct"
141
- readonly selection: Topology.TargetSelection
142
- readonly resolver?: (context: any, enqueue: unknown) => unknown
143
- readonly reenterSource: boolean
144
- readonly declinable: boolean
145
- }
146
-
147
- type BranchesTransitionDescriptor = {
148
- readonly [TransitionBuilderDescriptorTypeId]: typeof TransitionBuilderDescriptorTypeId
149
- readonly type: "branches"
150
- readonly declarations: unknown
151
- readonly resolve: (context: any, enqueue: unknown) => unknown
152
- readonly reenterSource: boolean
153
- readonly declinable: boolean
154
- }
155
-
156
- type TransitionBuilderDescriptor = DirectTransitionDescriptor | BranchesTransitionDescriptor
157
-
158
- const InitialBuilderDescriptorTypeId: unique symbol = Symbol("effect/Machine/InitialBuilderDescriptor")
159
-
160
- type InitialBuilderDescriptor = {
161
- readonly [InitialBuilderDescriptorTypeId]: typeof InitialBuilderDescriptorTypeId
162
- readonly selection: Topology.TargetSelection
163
- readonly resolve: (context: any) => unknown
164
- }
165
-
166
137
  const plainTargetSelection = (selection: Topology.TargetSelection): Topology.TargetSelection =>
167
138
  selection.kind === "none"
168
139
  ? Topology.noneTargetSelection
169
140
  : Topology.makeTargetSelection(selection.kind, selection.path, selection.scope, selection.updatePath)
170
141
 
171
- const transitionOptions = (options: unknown): { readonly declinable: boolean } => {
172
- const configuration = typeof options === "object" && options !== null
173
- ? options as { readonly declinable?: unknown }
174
- : {}
175
- if (hasProperty(configuration, "reenter")) {
176
- throw new Error("Use .reenter() before construction instead of the resolver reenter option")
177
- }
178
- return { declinable: configuration.declinable === true }
179
- }
180
-
181
- const makeDirectTransitionDescriptor = (
182
- selection: Topology.TargetSelection,
183
- resolve: ((context: any, enqueue: unknown) => unknown) | undefined,
184
- options: unknown,
185
- reenterSource = false
186
- ): DirectTransitionDescriptor => {
187
- const shared: Omit<DirectTransitionDescriptor, "resolver"> = {
188
- [TransitionBuilderDescriptorTypeId]: TransitionBuilderDescriptorTypeId,
189
- type: "direct",
190
- selection: plainTargetSelection(selection),
191
- reenterSource,
192
- ...transitionOptions(options)
193
- }
194
- return resolve === undefined
195
- ? Object.freeze(shared)
196
- : Object.freeze({ ...shared, resolver: resolve })
197
- }
198
-
199
142
  // The authored callback crosses an erased schema boundary here. Each builder
200
143
  // retains its construction mode, and planning validates both resulting values.
201
144
  const constructSelectionValue = (
@@ -210,197 +153,6 @@ const constructSelectionValue = (
210
153
  return context.target[method](values.target).update(context.owner[method](values.update))
211
154
  }
212
155
 
213
- const guardedSelection = (
214
- selection: Topology.TargetSelection,
215
- predicate: (context: any) => boolean,
216
- reenterSource: boolean
217
- ): object => {
218
- const wrap = (resolve: (context: any, enqueue: unknown) => unknown, options?: unknown) =>
219
- makeDirectTransitionDescriptor(
220
- selection,
221
- (context, enqueue) => predicate(context) ? resolve(context, enqueue) : Topology.makeDeclined(),
222
- { ...transitionOptions(options), declinable: true },
223
- reenterSource
224
- )
225
- return Object.freeze({
226
- ...wrap((context) => selection.kind === "none" ? undefined : constructSelectedTarget(context.target)),
227
- from: (value: (context: any) => unknown) =>
228
- wrap((context) => constructSelectionValue(selection, context, "from", value(context))),
229
- decoded: (value: (context: any) => unknown) =>
230
- wrap((context) => constructSelectionValue(selection, context, "decoded", value(context))),
231
- resolve: wrap
232
- })
233
- }
234
-
235
- const decorateTransitionSelection = (
236
- selection: Topology.TargetSelection,
237
- reenterSource = false
238
- ): Topology.TargetSelection =>
239
- Object.freeze({
240
- ...selection,
241
- ...(reenterSource ? makeDirectTransitionDescriptor(selection, undefined, undefined, true) : {}),
242
- guard: (predicate: (context: any) => boolean) => guardedSelection(selection, predicate, reenterSource),
243
- from: (value: (context: any) => unknown) =>
244
- makeDirectTransitionDescriptor(
245
- selection,
246
- (context) => constructSelectionValue(selection, context, "from", value(context)),
247
- undefined,
248
- reenterSource
249
- ),
250
- decoded: (value: (context: any) => unknown) =>
251
- makeDirectTransitionDescriptor(
252
- selection,
253
- (context) => constructSelectionValue(selection, context, "decoded", value(context)),
254
- undefined,
255
- reenterSource
256
- ),
257
- resolve: (resolve: (context: any, enqueue: unknown) => unknown, options?: unknown) =>
258
- makeDirectTransitionDescriptor(selection, resolve, options, reenterSource),
259
- reenter: () => decorateTransitionSelection(selection, true),
260
- updating: (owner: unknown) => {
261
- if (typeof owner !== "function") {
262
- throw new Error("Machine updating owner must be a state selector")
263
- }
264
- const ownerSelection = owner()
265
- if (
266
- !Topology.isTargetSelection(ownerSelection) || ownerSelection.kind !== "state" ||
267
- ownerSelection.scope !== "branch"
268
- ) {
269
- throw new Error("Machine updating owner must be addressed by one branch state selector")
270
- }
271
- return decorateTransitionSelection(
272
- Topology.makeTargetSelection(selection.kind, selection.path, selection.scope, ownerSelection.path),
273
- reenterSource
274
- )
275
- }
276
- })
277
-
278
- const noneTransitionSelection = decorateTransitionSelection(Topology.noneTargetSelection)
279
-
280
- const makeInitialBuilderDescriptor = (
281
- selection: Topology.TargetSelection,
282
- resolve: (context: any) => unknown
283
- ): InitialBuilderDescriptor =>
284
- Object.freeze({
285
- [InitialBuilderDescriptorTypeId]: InitialBuilderDescriptorTypeId,
286
- selection: plainTargetSelection(selection),
287
- resolve
288
- })
289
-
290
- const decorateInitialSelection = (selection: Topology.TargetSelection): Topology.TargetSelection =>
291
- Object.freeze({
292
- ...selection,
293
- from: (value: (context: any) => unknown) =>
294
- makeInitialBuilderDescriptor(selection, (context) => context.target.from(value(context))),
295
- decoded: (value: (context: any) => unknown) =>
296
- makeInitialBuilderDescriptor(selection, (context) => context.target.decoded(value(context))),
297
- resolve: (resolve: (context: any) => unknown) => makeInitialBuilderDescriptor(selection, resolve)
298
- })
299
-
300
- const decorateInitialSelectorNode = (node: unknown): unknown => {
301
- if (Topology.isTargetSelection(node)) return decorateInitialSelection(node)
302
- if (typeof node === "function") {
303
- const wrapped = ((...args: ReadonlyArray<unknown>) => decorateInitialSelection(node(...args))) as
304
- & ((...args: ReadonlyArray<unknown>) => unknown)
305
- & Record<string, unknown>
306
- for (const key of Object.keys(node)) {
307
- wrapped[key] = decorateInitialSelectorNode((node as unknown as Record<string, unknown>)[key])
308
- }
309
- return Object.freeze(wrapped)
310
- }
311
- if (typeof node === "object" && node !== null) {
312
- const wrapped: Record<string, unknown> = {}
313
- for (const key of Object.keys(node)) {
314
- wrapped[key] = decorateInitialSelectorNode((node as Record<string, unknown>)[key])
315
- }
316
- return Object.freeze(wrapped)
317
- }
318
- return node
319
- }
320
-
321
- const decorateTransitionSelectorNode = (node: unknown): unknown => {
322
- if (Topology.isTargetSelection(node)) {
323
- if (node.kind === "state" && node.scope === "full" && hasProperty(node, "initial")) {
324
- return Object.freeze({
325
- ...decorateTransitionSelection(node),
326
- initial: decorateTransitionSelection(node.initial as Topology.TargetSelection)
327
- })
328
- }
329
- return node === Topology.noneTargetSelection ? noneTransitionSelection : decorateTransitionSelection(node)
330
- }
331
- if (typeof node === "function") {
332
- const wrapped = ((...args: ReadonlyArray<unknown>) => decorateTransitionSelection(node(...args))) as
333
- & ((...args: ReadonlyArray<unknown>) => unknown)
334
- & Record<string, unknown>
335
- for (const key of Object.keys(node)) {
336
- wrapped[key] = decorateTransitionSelectorNode((node as unknown as Record<string, unknown>)[key])
337
- }
338
- return Object.freeze(wrapped)
339
- }
340
- if (typeof node === "object" && node !== null) {
341
- const wrapped: Record<string, unknown> = {}
342
- for (const key of Object.keys(node)) {
343
- wrapped[key] = decorateTransitionSelectorNode((node as Record<string, unknown>)[key])
344
- }
345
- return Object.freeze(wrapped)
346
- }
347
- return node
348
- }
349
-
350
- const decorateBranches = (declarations: unknown, reenterSource = false): object =>
351
- Object.freeze({
352
- reenter: () => decorateBranches(declarations, true),
353
- resolve: (
354
- resolve: (context: any, enqueue: unknown) => unknown,
355
- options?: unknown
356
- ): BranchesTransitionDescriptor =>
357
- Object.freeze({
358
- [TransitionBuilderDescriptorTypeId]: TransitionBuilderDescriptorTypeId,
359
- type: "branches",
360
- declarations,
361
- resolve,
362
- reenterSource,
363
- ...transitionOptions(options)
364
- })
365
- })
366
-
367
- const makeTransitionSelector = (
368
- stateNodes: Machine.StateNodes,
369
- source: string
370
- ): unknown =>
371
- Object.freeze({
372
- ...decorateTransitionSelectorNode(makeTargetSelector(stateNodes, source)) as Record<string, unknown>,
373
- branches: (declarations: unknown) => decorateBranches(declarations)
374
- })
375
-
376
- const normalizeTransitionBuilder = (
377
- transition: (selector: unknown) => unknown,
378
- stateNodes: Machine.StateNodes,
379
- path: string
380
- ): unknown => {
381
- const result = transition(makeTransitionSelector(stateNodes, path))
382
- if (Topology.isTargetSelection(result) && !hasProperty(result, TransitionBuilderDescriptorTypeId)) {
383
- const selection = plainTargetSelection(result)
384
- return { target: () => selection }
385
- }
386
- if (!hasProperty(result, TransitionBuilderDescriptorTypeId)) return result
387
- const descriptor = result as TransitionBuilderDescriptor
388
- if (descriptor.type === "branches") {
389
- return {
390
- branches: () => descriptor.declarations,
391
- resolve: descriptor.resolve,
392
- reenter: descriptor.reenterSource,
393
- declinable: descriptor.declinable
394
- }
395
- }
396
- return {
397
- target: () => descriptor.selection,
398
- resolve: descriptor.resolver,
399
- reenter: descriptor.reenterSource,
400
- declinable: descriptor.declinable
401
- }
402
- }
403
-
404
156
  const transitionTargetSelection = (
405
157
  selection: Topology.TargetSelection
406
158
  ): Machine.TransitionTargetSelection =>
@@ -415,124 +167,11 @@ const selectionUpdates = (selection: Topology.TargetSelection): ReadonlyArray<st
415
167
  selection.kind === "update" && selection.path !== undefined ? [selection.path] : []
416
168
  : [selection.updatePath]
417
169
 
418
- const makeSelectionMethod = (
419
- kind: Topology.TargetSelectionKind,
420
- path: string | undefined,
421
- scope: Topology.TargetSelectionScope
422
- ): () => Topology.TargetSelection =>
423
- () => Topology.makeTargetSelection(kind, path, scope)
424
-
425
- const makeSelectionValue = (
426
- kind: Topology.TargetSelectionKind,
427
- path: string | undefined,
428
- scope: Topology.TargetSelectionScope
429
- ): Topology.TargetSelection => Topology.makeTargetSelection(kind, path, scope)
430
-
431
170
  const makeStateUpdateSelection = (
432
171
  path: string,
433
172
  scope: "local" | "branch"
434
173
  ): Topology.TargetSelection => Topology.makeTargetSelection("update", path, scope)
435
174
 
436
- const addSelectionChildren = (
437
- builder: Record<string, unknown>,
438
- stateNodes: Machine.StateNodes,
439
- parent: string,
440
- scope: "local" | "branch",
441
- source?: string
442
- ): void => {
443
- for (const node of stateNodes.byPath.values()) {
444
- if (node.parent !== parent || node.type === "history") continue
445
- builder[node.key] = makeSelectionNode(stateNodes, node.path, scope, source)
446
- }
447
- }
448
-
449
- const makeSelectionNode = (
450
- stateNodes: Machine.StateNodes,
451
- path: string,
452
- scope: Topology.TargetSelectionScope,
453
- source?: string
454
- ): unknown => {
455
- const node = getTargetBuilderNode(stateNodes, path)
456
- const kind: Topology.TargetSelectionKind = node.type === "choice" ? "choice" : "state"
457
- const method = makeSelectionMethod(kind, path, scope) as unknown as Record<string, unknown>
458
- if (node.type !== "atomic" && node.type !== "final" && node.type !== "choice" && node.type !== "history") {
459
- Object.defineProperty(method, "initial", {
460
- value: makeSelectionValue("initial", path, scope),
461
- enumerable: true
462
- })
463
- if (scope === "local" || scope === "branch") {
464
- addSelectionChildren(method, stateNodes, path, scope, source)
465
- }
466
- if (
467
- scope === "branch" && source !== undefined && node.schema !== undefined &&
468
- (source === path || Configuration.isDescendantOf(source, path)) &&
469
- getTargetBuilderNode(stateNodes, source).type !== "choice"
470
- ) {
471
- Object.defineProperty(method, "update", {
472
- value: makeStateUpdateSelection(path, "branch"),
473
- enumerable: true
474
- })
475
- }
476
- }
477
- if (node.type === "atomic" && scope === "branch" && source === path && node.schema !== undefined) {
478
- Object.defineProperty(method, "update", { value: makeStateUpdateSelection(path, "branch"), enumerable: true })
479
- }
480
- return method
481
- }
482
-
483
- const makeHistorySelectionTree = (
484
- stateNodes: Machine.StateNodes,
485
- parent: string | undefined
486
- ): Record<string, unknown> => {
487
- const builder: Record<string, unknown> = {}
488
- for (const node of stateNodes.byPath.values()) {
489
- if (node.parent !== parent) continue
490
- if (node.type === "history") {
491
- builder[node.key] = makeSelectionValue("history", node.path, "full")
492
- } else if (node.type !== "choice") {
493
- const children = makeHistorySelectionTree(stateNodes, node.path)
494
- if (Object.keys(children).length > 0) builder[node.key] = children
495
- }
496
- }
497
- return builder
498
- }
499
-
500
- const makeTargetSelector = (
501
- stateNodes: Machine.StateNodes,
502
- source: string
503
- ): unknown => {
504
- const full = Object.assign({}, makeSelectionValue("state", "", "full"), {
505
- initial: makeSelectionValue("initial", "", "full")
506
- })
507
- const branch: Record<string, unknown> = {}
508
- const root = getTargetBuilderNode(stateNodes, stateNodes.roots[0]!)
509
- addSelectionChildren(branch, stateNodes, root.path, "branch", source)
510
- const local: Record<string, unknown> = {}
511
- const localScope = getLocalTargetScope(stateNodes, source)
512
- if (localScope !== undefined) {
513
- const localScopeNode = getTargetBuilderNode(stateNodes, localScope)
514
- if (localScopeNode.schema !== undefined) {
515
- local.with = makeSelectionValue("state", localScope, "local")
516
- if (getTargetBuilderNode(stateNodes, source).type !== "choice") {
517
- local.update = makeStateUpdateSelection(localScope, "local")
518
- }
519
- }
520
- addSelectionChildren(local, stateNodes, localScope, "local")
521
- }
522
- return {
523
- none: Topology.noneTargetSelection,
524
- self: getTargetBuilderNode(stateNodes, source).schema === undefined ||
525
- getTargetBuilderNode(stateNodes, source).type === "final"
526
- ? {}
527
- : { update: makeStateUpdateSelection(source, "branch") },
528
- root: makeSelectionNode(stateNodes, root.path, "branch", source),
529
- local,
530
- branch,
531
- full,
532
- history: makeHistorySelectionTree(stateNodes, "")
533
- }
534
- }
535
-
536
175
  const captureDefinitionBranch = (
537
176
  branch: unknown,
538
177
  selector: unknown,
@@ -704,7 +343,12 @@ const runCapturedBranch = (
704
343
  ): unknown => {
705
344
  const selectedTarget = getSelectionBuilder(context.target, branch.selection, stateNodes, source)
706
345
  if (branch.resolve === undefined) return constructSelectedTarget(selectedTarget)
707
- const resolverContext = { ...context }
346
+ // This fresh context is owned by this evaluation and can be retained by user callbacks.
347
+ const resolverContext: Record<string, any> = {
348
+ ...context,
349
+ root: source === "" ? context.state : context.ancestors[""],
350
+ decline: Topology.makeDeclined
351
+ }
708
352
  if (branch.selection.kind === "none") delete resolverContext.target
709
353
  else resolverContext.target = selectedTarget
710
354
  if (branch.selection.kind === "update") {
@@ -727,7 +371,6 @@ const runCapturedBranch = (
727
371
  source
728
372
  )
729
373
  }
730
- if (branch.declinable === true) resolverContext.decline = Topology.makeDeclined
731
374
  const resolved = branch.resolve(resolverContext, enqueue)
732
375
  if (Topology.isDeclined(resolved)) {
733
376
  if (branch.declinable !== true) {
@@ -776,14 +419,6 @@ const captureNamedBranches = (
776
419
  if (!Topology.isTargetSelection(target)) {
777
420
  throw new Error(`Machine transition branch "${key}" must select exactly one target`)
778
421
  }
779
- if (target.updatePath !== undefined) {
780
- throw new Error(`Machine transition branch "${key}" cannot declare an updating target`)
781
- }
782
- if (hasProperty(target, TransitionBuilderDescriptorTypeId)) {
783
- throw new Error(
784
- `Machine transition branch "${key}" requires a topology selection; apply .reenter() to .branches(...)`
785
- )
786
- }
787
422
  if (title !== undefined && (typeof title !== "string" || title.length === 0)) {
788
423
  throw new Error(`Machine transition branch "${key}" title must be a non-empty string`)
789
424
  }
@@ -795,11 +430,32 @@ const wrapSelectedBranchBuilder = (
795
430
  builder: unknown,
796
431
  owner: object,
797
432
  branchIndex: number,
798
- branchKey: string
433
+ branchKey: string,
434
+ updateBuilder?: Record<string, (value: unknown) => unknown>
799
435
  ): unknown => {
800
436
  if (typeof builder === "function") {
801
- const wrapped = (...args: ReadonlyArray<unknown>) =>
802
- Topology.makeSelectedBranch(owner, branchIndex, branchKey, builder(...args))
437
+ const wrapped = (...args: ReadonlyArray<unknown>) => {
438
+ const result = builder(...args)
439
+ if (updateBuilder !== undefined) {
440
+ return Object.freeze({
441
+ update: Object.freeze(
442
+ Object.fromEntries(
443
+ Object.getOwnPropertyNames(updateBuilder).map((
444
+ method
445
+ ) => [method, (value: unknown) =>
446
+ Topology.makeSelectedBranch(
447
+ owner,
448
+ branchIndex,
449
+ branchKey,
450
+ result.update(updateBuilder[method]!(value))
451
+ )]
452
+ )
453
+ )
454
+ )
455
+ })
456
+ }
457
+ return Topology.makeSelectedBranch(owner, branchIndex, branchKey, result)
458
+ }
803
459
  for (const property of Reflect.ownKeys(builder)) {
804
460
  if (
805
461
  property === "length" || property === "name" || property === "prototype" || property === "caller" ||
@@ -808,7 +464,7 @@ const wrapSelectedBranchBuilder = (
808
464
  const descriptor = Object.getOwnPropertyDescriptor(builder, property)
809
465
  if (descriptor === undefined) continue
810
466
  if ("value" in descriptor && typeof descriptor.value === "function") {
811
- descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey)
467
+ descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey, updateBuilder)
812
468
  }
813
469
  Object.defineProperty(wrapped, property, descriptor)
814
470
  }
@@ -820,7 +476,7 @@ const wrapSelectedBranchBuilder = (
820
476
  const descriptor = Object.getOwnPropertyDescriptor(builder, property)
821
477
  if (descriptor === undefined) continue
822
478
  if ("value" in descriptor && typeof descriptor.value === "function") {
823
- descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey)
479
+ descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey, updateBuilder)
824
480
  }
825
481
  Object.defineProperty(wrapped, property, descriptor)
826
482
  }
@@ -843,7 +499,15 @@ const makeBranchSelectors = (
843
499
  getSelectionBuilder(context.target, branch.selection, stateNodes, source),
844
500
  owner,
845
501
  branchIndex,
846
- branch.key
502
+ branch.key,
503
+ branch.selection.updatePath === undefined
504
+ ? undefined
505
+ : getSelectionBuilder(
506
+ context.target,
507
+ makeStateUpdateSelection(branch.selection.updatePath, "branch"),
508
+ stateNodes,
509
+ source
510
+ ) as Record<string, (value: unknown) => unknown>
847
511
  )
848
512
  }
849
513
  return Object.freeze(select)
@@ -866,23 +530,119 @@ const validateSelectedBranchResult = (
866
530
  validateResolvedSelection(result, selection, stateNodes)
867
531
  }
868
532
 
533
+ // Invocation input contexts do not pass through captured transition evaluation.
534
+ const objectContext = (context: Record<string, any>, path: string): Record<string, any> => ({
535
+ ...context,
536
+ root: path === "" ? context.state : context.ancestors[""]
537
+ })
538
+
539
+ const normalizeObjectTransition = (
540
+ raw: unknown,
541
+ declaration: Declaration.Declaration,
542
+ path: string,
543
+ stateNodes: Machine.StateNodes
544
+ ): Record<string, unknown> => {
545
+ if (typeof raw !== "object" || raw === null) throw new Error(`Machine transition for "${path}" must be an object`)
546
+ const config = { ...raw } as Record<string, unknown>
547
+ const allowed = [
548
+ "target",
549
+ "update",
550
+ "initial",
551
+ "history",
552
+ "none",
553
+ "branches",
554
+ "data",
555
+ "decoded",
556
+ "resolve",
557
+ "guard",
558
+ "reenter",
559
+ "declinable"
560
+ ]
561
+ for (const key of Reflect.ownKeys(config)) {
562
+ if (typeof key !== "string" || !allowed.includes(key)) {
563
+ throw new Error("Machine transition contains an unknown field")
564
+ }
565
+ }
566
+ for (const key of ["resolve", "guard"]) {
567
+ if (config[key] !== undefined && typeof config[key] !== "function") {
568
+ throw new Error(`Machine transition ${key} must be a function`)
569
+ }
570
+ }
571
+ const guard = typeof config.guard === "function" ? config.guard : undefined
572
+ const resolve = typeof config.resolve === "function" ? config.resolve : undefined
573
+ if (config.decoded !== undefined && typeof config.decoded !== "boolean") {
574
+ throw new Error("Machine decoded must be a boolean construction flag")
575
+ }
576
+ const hasData = Object.prototype.hasOwnProperty.call(config, "data")
577
+ if (config.decoded === true && !hasData) throw new Error("Machine decoded construction requires data")
578
+ if (hasData && resolve !== undefined) throw new Error("Machine data and resolve are mutually exclusive")
579
+ const data = config.data
580
+ const construct = typeof data === "function" ? data : () => data
581
+ const guarded = guard !== undefined
582
+ const declinable = guarded || config.declinable === true
583
+ if (typeof config.branches === "string") {
584
+ const group = declaration.branches.get(config.branches)
585
+ if (group === undefined || resolve === undefined) {
586
+ throw new Error("Machine branching transition requires a registered group and resolver")
587
+ }
588
+ if (
589
+ ["target", "update", "initial", "history", "none", "data", "decoded"].some((key) => config[key] !== undefined)
590
+ ) throw new Error("Machine branching transition cannot redeclare its destination")
591
+ const entries = Object.fromEntries(
592
+ Object.entries(group).map(([key, spec]) => [key, {
593
+ title: spec.title,
594
+ target: captureDefinitionBranch(
595
+ { target: () => Declaration.selection(declaration, spec) },
596
+ undefined,
597
+ stateNodes,
598
+ path,
599
+ key
600
+ ).selection
601
+ }])
602
+ )
603
+ return {
604
+ branches: () => entries,
605
+ reenter: config.reenter,
606
+ declinable,
607
+ resolve: (context: Record<string, any>, enqueue: unknown) => {
608
+ return guarded && !guard(context) ? Topology.makeDeclined() : resolve(context, enqueue)
609
+ }
610
+ }
611
+ }
612
+ const selection = Declaration.selection(declaration, config)
613
+ if (resolve !== undefined && selection.kind !== "none") {
614
+ throw new Error("Machine advanced construction requires a declared branch group")
615
+ }
616
+ const method = hasData ? config.decoded === true ? "decoded" : "from" : undefined
617
+ return {
618
+ target: () => selection,
619
+ reenter: config.reenter,
620
+ declinable,
621
+ ...(!guarded && method === undefined && resolve === undefined ? {} : {
622
+ resolve: (context: Record<string, any>, enqueue: unknown) => {
623
+ if (guarded && !guard(context)) return Topology.makeDeclined()
624
+ if (method !== undefined && construct !== undefined) {
625
+ return constructSelectionValue(selection, context, method, construct(context))
626
+ }
627
+ if (resolve !== undefined) return resolve(context, enqueue)
628
+ return selection.kind === "none" ? undefined : constructSelectedTarget(context.target)
629
+ }
630
+ })
631
+ }
632
+ }
633
+
869
634
  const captureTransition = (
870
635
  rawTransition: unknown,
871
636
  stateNodes: Machine.StateNodes,
872
637
  path: string,
638
+ declaration: Declaration.Declaration,
873
639
  trigger: PropertyKey
874
640
  ): unknown => {
875
- if (typeof rawTransition !== "function") {
876
- throw new Error(
877
- `Machine transition for state "${path}" on "${String(trigger)}" must be a target-first callback`
878
- )
879
- }
880
- const transition = normalizeTransitionBuilder(rawTransition as (selector: unknown) => unknown, stateNodes, path)
641
+ const transition = normalizeObjectTransition(rawTransition, declaration, path, stateNodes)
881
642
  if (typeof transition !== "object" || transition === null) {
882
643
  throw new Error(`Machine transition for state "${path}" on "${String(trigger)}" must be an object`)
883
644
  }
884
645
  const definition = transition as Record<PropertyKey, unknown>
885
- const selector = makeTargetSelector(stateNodes, path)
886
646
  const reenter = definition.reenter === true
887
647
  const declinable = definition.declinable === true
888
648
  if (hasProperty(definition, "branches")) {
@@ -893,13 +653,16 @@ const captureTransition = (
893
653
  )
894
654
  }
895
655
  const resolve = branching.resolve
896
- const branches = captureNamedBranches(branching.branches(selector), path, trigger)
656
+ const branches = captureNamedBranches(branching.branches(), path, trigger)
897
657
  const owner = Object.freeze({})
898
658
  const evaluate = (context: Record<string, any>, enqueue: unknown) => {
899
- const resolverContext = { ...context }
659
+ const resolverContext: Record<string, any> = {
660
+ ...context,
661
+ root: path === "" ? context.state : context.ancestors[""],
662
+ decline: Topology.makeDeclined
663
+ }
900
664
  delete resolverContext.target
901
665
  resolverContext.select = makeBranchSelectors(context, branches, owner, stateNodes, path)
902
- if (declinable) resolverContext.decline = Topology.makeDeclined
903
666
  const selected = resolve(resolverContext, enqueue)
904
667
  if (Topology.isDeclined(selected)) {
905
668
  if (!declinable) {
@@ -951,7 +714,7 @@ const captureTransition = (
951
714
  transition: (context: Record<string, any>, enqueue: unknown) => evaluate(context, enqueue).result
952
715
  }
953
716
  }
954
- const branch = captureDefinitionBranch(transition, selector, stateNodes, path, trigger)
717
+ const branch = captureDefinitionBranch(transition, undefined, stateNodes, path, trigger)
955
718
  const evaluate = (context: Record<string, any>, enqueue: unknown) => ({
956
719
  result: runCapturedBranch(branch, context, enqueue, stateNodes, path),
957
720
  branchIndex: 0,
@@ -975,94 +738,56 @@ const captureTransition = (
975
738
  const captureEventHandlers = (
976
739
  on: object,
977
740
  stateNodes: Machine.StateNodes,
978
- path: string
741
+ path: string,
742
+ declaration: Declaration.Declaration
979
743
  ): Record<PropertyKey, unknown> => {
980
744
  // The machine owns its dispatch table. Compiled plans may snapshot these
981
745
  // definitions, so retaining caller-owned containers would let strategies
982
746
  // observe different handlers after an unsafe external mutation.
983
747
  const captured: Record<PropertyKey, unknown> = Object.create(null)
984
748
  for (const event of Reflect.ownKeys(on)) {
985
- captured[event] = captureTransition((on as Record<PropertyKey, unknown>)[event], stateNodes, path, event)
749
+ captured[event] = captureTransition(
750
+ (on as Record<PropertyKey, unknown>)[event],
751
+ stateNodes,
752
+ path,
753
+ declaration,
754
+ event
755
+ )
986
756
  }
987
757
  return captured
988
758
  }
989
759
 
990
- interface InvokeBuilderDescriptor {
991
- readonly [InvokeBuilderDescriptorTypeId]: typeof InvokeBuilderDescriptorTypeId
992
- readonly config: Readonly<Record<PropertyKey, unknown>>
993
- }
994
-
995
- type InvokeBuilderChannel = "onDone" | "onFailure" | "onElement" | "onSnapshot"
996
-
997
- const makeInvokeBuilder = (
998
- config: Readonly<Record<PropertyKey, unknown>>,
999
- channels: ReadonlyArray<InvokeBuilderChannel>
1000
- ): InvokeBuilderDescriptor => {
1001
- const builder: Record<PropertyKey, unknown> = {
1002
- [InvokeBuilderDescriptorTypeId]: InvokeBuilderDescriptorTypeId as typeof InvokeBuilderDescriptorTypeId,
1003
- config
1004
- }
1005
- for (const channel of channels) {
1006
- if (!hasProperty(config, channel)) {
1007
- builder[channel] = (handler: unknown) => makeInvokeBuilder({ ...config, [channel]: handler }, channels)
1008
- }
1009
- }
1010
- return Object.freeze(builder) as unknown as InvokeBuilderDescriptor
1011
- }
1012
-
1013
- const invokeSelector = Object.freeze({
1014
- effect: (id: string, effect: unknown) => makeInvokeBuilder({ id, effect }, ["onDone", "onFailure"]),
1015
- stream: (id: string, stream: unknown) => makeInvokeBuilder({ id, stream }, ["onElement", "onDone", "onFailure"]),
1016
- timer: (id: string, after: unknown) => makeInvokeBuilder({ id, after }, ["onDone"]),
1017
- logic: (id: string, options: Readonly<Record<PropertyKey, unknown>>) =>
1018
- makeInvokeBuilder({ id, ...options }, ["onSnapshot", "onDone", "onFailure"]),
1019
- child: (child: unknown, options?: Readonly<Record<PropertyKey, unknown>>) =>
1020
- makeInvokeBuilder(options === undefined ? { child } : { child, ...options }, [
1021
- "onSnapshot",
1022
- "onDone",
1023
- "onFailure"
1024
- ])
1025
- })
1026
-
1027
- const invokeBuilderConfig = (value: unknown, path: string): Readonly<Record<PropertyKey, unknown>> => {
1028
- if (
1029
- typeof value !== "object" || value === null ||
1030
- !hasProperty(value, InvokeBuilderDescriptorTypeId) ||
1031
- value[InvokeBuilderDescriptorTypeId] !== InvokeBuilderDescriptorTypeId
1032
- ) {
1033
- throw new Error(`Machine invocation for state "${path}" must be constructed from its source selector`)
1034
- }
1035
- return (value as unknown as InvokeBuilderDescriptor).config
1036
- }
1037
-
1038
760
  const captureInvokeDefinition = (
1039
761
  invoke: unknown,
1040
762
  stateNodes: Machine.StateNodes,
1041
- path: string
763
+ path: string,
764
+ declaration: Declaration.Declaration
1042
765
  ): unknown => {
1043
- if (typeof invoke !== "function") {
1044
- throw new Error(`Machine invocation for state "${path}" must be a source-first callback`)
1045
- }
1046
- const authored = invoke(invokeSelector)
1047
- const definitions = Array.isArray(authored) ? authored : [authored]
766
+ const definitions = Array.isArray(invoke) ? invoke : [invoke]
1048
767
  const capturedDefinitions = definitions.map((definition) => {
1049
- const captured = { ...invokeBuilderConfig(definition, path) }
768
+ const captured = Declaration.invocation(
769
+ declaration,
770
+ definition,
771
+ path,
772
+ (context) => objectContext(context as Record<string, any>, path)
773
+ )
1050
774
  for (const key of ["onElement", "onDone", "onFailure", "onSnapshot"] as const) {
1051
775
  if (captured[key] !== undefined) {
1052
- captured[key] = captureTransition(captured[key], stateNodes, path, key)
776
+ captured[key] = captureTransition(captured[key], stateNodes, path, declaration, key)
1053
777
  }
1054
778
  }
1055
779
  return InvocationDefinition.capture(captured, path)
1056
780
  })
1057
- if (Array.isArray(authored)) return Object.freeze(capturedDefinitions)
781
+ if (Array.isArray(invoke)) return Object.freeze(capturedDefinitions)
1058
782
  return capturedDefinitions[0]
1059
783
  }
1060
784
 
1061
785
  const flattenHandlers = (
1062
- handlers: Record<PropertyKey, Machine.AnyStateConfig>,
786
+ handlers: Record<PropertyKey, CapturedStateConfig>,
1063
787
  stateNodes: Machine.StateNodes,
1064
788
  states: Machine.StateTree,
1065
789
  prefix: string,
790
+ declaration: Declaration.Declaration,
1066
791
  config: Record<string, unknown>
1067
792
  ): void => {
1068
793
  for (const key of Object.keys(config)) {
@@ -1085,20 +810,20 @@ const flattenHandlers = (
1085
810
  }
1086
811
  const on = stateConfig.on
1087
812
  if (typeof on === "object" && on !== null) {
1088
- const capturedOn = captureEventHandlers(on, stateNodes, path)
813
+ const capturedOn = captureEventHandlers(on, stateNodes, path, declaration)
1089
814
  stateConfig.on = capturedOn
1090
815
  }
1091
816
  if (stateConfig.always !== undefined) {
1092
- stateConfig.always = captureTransition(stateConfig.always, stateNodes, path, "always")
817
+ stateConfig.always = captureTransition(stateConfig.always, stateNodes, path, declaration, "always")
1093
818
  }
1094
819
  if (stateConfig.onDone !== undefined) {
1095
- stateConfig.onDone = captureTransition(stateConfig.onDone, stateNodes, path, "done")
820
+ stateConfig.onDone = captureTransition(stateConfig.onDone, stateNodes, path, declaration, "done")
1096
821
  }
1097
822
  if (stateConfig.choice !== undefined) {
1098
- stateConfig.choice = captureTransition(stateConfig.choice, stateNodes, path, "choice")
823
+ stateConfig.choice = captureTransition(stateConfig.choice, stateNodes, path, declaration, "choice")
1099
824
  }
1100
825
  if (stateConfig.invoke !== undefined) {
1101
- stateConfig.invoke = captureInvokeDefinition(stateConfig.invoke, stateNodes, path)
826
+ stateConfig.invoke = captureInvokeDefinition(stateConfig.invoke, stateNodes, path, declaration)
1102
827
  }
1103
828
  const node = stateNodes.byPath.get(path)
1104
829
  if (node?.type === "choice") {
@@ -1111,7 +836,7 @@ const flattenHandlers = (
1111
836
  throw new Error(`Machine choice state "${path}" requires a transition`)
1112
837
  }
1113
838
  }
1114
- handlers[path] = stateConfig as Machine.AnyStateConfig
839
+ handlers[path] = stateConfig as CapturedStateConfig
1115
840
  if (childConfig !== undefined) {
1116
841
  const node = Topology.getStateNodeDefinition(path, states[key]!)
1117
842
  if (node.states === undefined) {
@@ -1120,16 +845,33 @@ const flattenHandlers = (
1120
845
  if (typeof childConfig !== "object" || childConfig === null) {
1121
846
  throw new Error(`Machine expected state "${path}" child handlers to be an object`)
1122
847
  }
1123
- flattenHandlers(handlers, stateNodes, node.states, path, childConfig as Record<string, unknown>)
848
+ flattenHandlers(handlers, stateNodes, node.states, path, declaration, childConfig as Record<string, unknown>)
1124
849
  }
1125
850
  }
1126
851
  }
1127
852
 
1128
- const makeHandle = (self: Definition.Any): Definition.Any["handle"] =>
853
+ const makeHandle = (self: Definition.Any, declaration: Declaration.Declaration): Definition.Any["handle"] =>
1129
854
  ((config: Record<string, unknown>) => {
1130
- const handlers: Record<PropertyKey, Machine.AnyStateConfig> = Object.create(null)
1131
- flattenHandlers(handlers, self.stateNodes, self.states, "", { "": config })
1132
- return makeWithHandlers(self, handlers)
855
+ const captured = InitialDeclaration.capture(declaration.root, config)
856
+ const compiled = Object.assign(Object.create(Proto), self)
857
+ Protocol.copyProtocol(self, compiled)
858
+ compiled.states = Object.freeze({ "": captured.node })
859
+ compiled.stateNodes = Topology.compileStateNodes(compiled.states)
860
+ if (compiled.stateNodes.byPath.get("").schema === undefined && config.root !== undefined) {
861
+ throw new Error("Machine schema-less root cannot construct data")
862
+ }
863
+ const constructRoot = compiled.stateNodes.byPath.get("").schema === undefined
864
+ ? () => undefined
865
+ : InitialDeclaration.construction(config.root)
866
+ compiled.initial = (input: unknown) => Topology.makeInitialTarget("", constructRoot({ input }))
867
+ compiled.initialDefinition = Object.freeze({
868
+ target: "",
869
+ selection: Object.freeze({ path: "", kind: "initial", scope: "initial" })
870
+ })
871
+ compiled.makeTargetBuilder = makeTargetBuilder(compiled.states, compiled.stateNodes)
872
+ const handlers: Record<PropertyKey, CapturedStateConfig> = Object.create(null)
873
+ flattenHandlers(handlers, compiled.stateNodes, compiled.states, "", declaration, { "": captured.handlers })
874
+ return makeWithHandlers(compiled, handlers)
1133
875
  }) as Definition.Any["handle"]
1134
876
 
1135
877
  export const isMachine = (
@@ -1169,96 +911,6 @@ export const isFinal = <
1169
911
  state: Machine.Snapshot<States>
1170
912
  ): state is Machine.SnapshotContainingFinal<States, FinalStates> => internalPlanner.isFinal(machine as any, state)
1171
913
 
1172
- const getInitialSelectionBuilder = (
1173
- initialBuilder: Record<string, any>,
1174
- selection: Topology.TargetSelection
1175
- ): Record<string, any> => {
1176
- const path = selection.path
1177
- if (path === undefined || path.includes(".")) {
1178
- throw new Error("Machine initial target must select one top-level state")
1179
- }
1180
- const builder = initialBuilder[path]
1181
- if (typeof builder !== "object" || builder === null || typeof builder.from !== "function") {
1182
- throw new Error(`Machine could not construct selected initial state "${path}"`)
1183
- }
1184
- return builder
1185
- }
1186
-
1187
- const captureInitialBranch = (
1188
- definition: unknown,
1189
- initialBuilder: Record<string, any>,
1190
- configuration: boolean
1191
- ): {
1192
- readonly selection: Topology.TargetSelection
1193
- readonly resolve?: (context: any) => unknown
1194
- readonly builder: Record<string, any>
1195
- } => {
1196
- if (definition !== undefined && typeof definition !== "function") {
1197
- throw new Error("Machine initial definition must be a target-first callback")
1198
- }
1199
- const selector = decorateInitialSelection(makeSelectionValue(configuration ? "state" : "initial", "", "initial"))
1200
- const result = definition === undefined ? selector : definition(selector)
1201
- let selection: Topology.TargetSelection
1202
- let resolve: ((context: any) => unknown) | undefined
1203
- if (Topology.isTargetSelection(result)) {
1204
- selection = plainTargetSelection(result)
1205
- } else if (hasProperty(result, InitialBuilderDescriptorTypeId)) {
1206
- const descriptor = result as InitialBuilderDescriptor
1207
- selection = descriptor.selection
1208
- resolve = descriptor.resolve
1209
- } else {
1210
- throw new Error("Machine initial definition must select exactly one target")
1211
- }
1212
- if (selection.kind !== "state" && selection.kind !== "initial") {
1213
- throw new Error("Machine initial target must select a top-level state or its declared initial entry")
1214
- }
1215
- const captured = {
1216
- selection,
1217
- builder: getInitialSelectionBuilder(initialBuilder, selection)
1218
- }
1219
- return resolve === undefined ? Object.freeze(captured) : Object.freeze({ ...captured, resolve })
1220
- }
1221
-
1222
- const validateInitialSelection = (result: unknown, selection: Topology.TargetSelection): void => {
1223
- if (
1224
- typeof result !== "object" || result === null || !hasProperty(result, "path") || result.path !== selection.path
1225
- ) {
1226
- const resultPath = typeof result === "object" && result !== null && hasProperty(result, "path")
1227
- ? String(result.path)
1228
- : "<invalid>"
1229
- throw new Error(`Machine initial resolver selected "${selection.path}" but constructed "${resultPath}"`)
1230
- }
1231
- }
1232
-
1233
- const compileInitial = (
1234
- definition: unknown,
1235
- states: Machine.StateTree,
1236
- stateNodes: Machine.StateNodes,
1237
- configuration = false
1238
- ): {
1239
- readonly initial: (input?: unknown) => unknown
1240
- readonly definition: Machine.InitialDefinition
1241
- } => {
1242
- const rootNode = getTargetBuilderNode(stateNodes, "")
1243
- const initialBuilder = configuration ?
1244
- makeSnapshotBuilder(states, { mode: "full", prefix: "" }) as Record<string, any>
1245
- : { "": withFrom((value: unknown) => Topology.makeInitialTarget("", value), "leaf", rootNode.schema !== undefined) }
1246
- const branch = captureInitialBranch(definition, initialBuilder, configuration)
1247
- return {
1248
- initial: (input?: unknown) => {
1249
- const result = branch.resolve === undefined
1250
- ? constructSelectedTarget(branch.builder)
1251
- : branch.resolve({ input, target: branch.builder })
1252
- validateInitialSelection(result, branch.selection)
1253
- return result
1254
- },
1255
- definition: Object.freeze({
1256
- target: branch.selection.path!,
1257
- selection: transitionTargetSelection(branch.selection) as Machine.InitialDefinition["selection"]
1258
- })
1259
- }
1260
- }
1261
-
1262
914
  export const state = (node: unknown): State<Machine.StateNodeConfig> => {
1263
915
  const captured = StateDefinition.captureRoot(node) as Machine.StateNodeConfig
1264
916
  const access = makeStateHelpers()
@@ -1325,17 +977,24 @@ export const make = <
1325
977
  config: {
1326
978
  readonly id?: string
1327
979
  readonly root: State<Machine.StateNodeConfig>
1328
- readonly initialConfiguration?: unknown
980
+ readonly effects?: unknown
981
+ readonly streams?: unknown
982
+ readonly timers?: unknown
983
+ readonly logic?: unknown
984
+ readonly children?: unknown
985
+ readonly branches?: unknown
1329
986
  readonly events: Machine.EventProtocol<"public", InputEvents>
1330
987
  readonly internalEvents?: Machine.EventProtocol<"internal", InternalEvents>
1331
988
  readonly emittedEvents?: Machine.EventProtocol<"emitted", Emits>
1332
989
  readonly parent?: ParentDeclaration
1333
990
  readonly input?: Input
1334
- readonly initial: unknown
1335
991
  }
1336
992
  ): MakeResult<States, InputEvents, Emits, Input, InitialE, InitialR, InternalEvents, ParentDeclaration> => {
993
+ if (Object.hasOwn(config, "initial") || Object.hasOwn(config, "initialConfiguration")) {
994
+ throw new Error("Machine initial edges and root data belong in handle")
995
+ }
1337
996
  const states = Object.freeze({ "": config.root.node })
1338
- const self = Object.create(Proto)
997
+ const self = Object.create(PipeablePrototype)
1339
998
  self.states = states
1340
999
  self.root = config.root
1341
1000
  self.events = config.events
@@ -1344,18 +1003,8 @@ export const make = <
1344
1003
  self.parent = config.parent
1345
1004
  self.input = config.input
1346
1005
  self.id = config.id
1347
- self.stateNodes = Topology.compileStateNodes(states)
1348
- const compiledInitial = compileInitial(
1349
- config.initialConfiguration ?? config.initial,
1350
- states,
1351
- self.stateNodes,
1352
- config.initialConfiguration !== undefined
1353
- )
1354
- self.initial = compiledInitial.initial
1355
- self.initialDefinition = compiledInitial.definition
1356
- self.makeTargetBuilder = makeTargetBuilder(states, self.stateNodes)
1357
1006
  self.handlers = Object.create(null)
1358
- self.handle = makeHandle(self)
1007
+ self.handle = makeHandle(self, Declaration.capture(config.root, config))
1359
1008
  Protocol.setProtocol(self)
1360
1009
  return self
1361
1010
  }