@typeonce/effect-machine 0.45.1 → 0.47.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 (148) hide show
  1. package/AGENTS.md +1823 -0
  2. package/CLAUDE.md +1823 -0
  3. package/README.md +100 -77
  4. package/ai-docs/README.md +18 -0
  5. package/ai-docs/src/10_modeling/01_create-a-machine.ts +51 -0
  6. package/ai-docs/src/10_modeling/02_branch-on-an-event.ts +55 -0
  7. package/ai-docs/src/10_modeling/03_update-retained-state.ts +58 -0
  8. package/ai-docs/src/10_modeling/04_verify-after-changing.ts +29 -0
  9. package/{docs/agent-guide.md → ai-docs/src/10_modeling/index.md} +254 -155
  10. package/{docs/root-api.md → ai-docs/src/20_root-api/index.md} +29 -57
  11. package/{docs/effect-atom-react.md → ai-docs/src/30_react/index.md} +49 -49
  12. package/{docs/machine-review.md → ai-docs/src/40_review/index.md} +42 -40
  13. package/ai-docs/src/index.md +7 -0
  14. package/ai-docs/tsconfig.json +22 -0
  15. package/dist/Machine.d.ts +1205 -1478
  16. package/dist/Machine.d.ts.map +1 -1
  17. package/dist/Machine.js +366 -214
  18. package/dist/Machine.js.map +1 -1
  19. package/dist/internal/machine/atom.js.map +1 -1
  20. package/dist/internal/machine/cluster.js.map +1 -1
  21. package/dist/internal/machine/command.d.ts +8 -0
  22. package/dist/internal/machine/command.d.ts.map +1 -1
  23. package/dist/internal/machine/command.js +2 -2
  24. package/dist/internal/machine/command.js.map +1 -1
  25. package/dist/internal/machine/configuration.d.ts +21 -5
  26. package/dist/internal/machine/configuration.d.ts.map +1 -1
  27. package/dist/internal/machine/configuration.js +1 -0
  28. package/dist/internal/machine/configuration.js.map +1 -1
  29. package/dist/internal/machine/construction.js.map +1 -1
  30. package/dist/internal/machine/declaration.d.ts +2 -1
  31. package/dist/internal/machine/declaration.d.ts.map +1 -1
  32. package/dist/internal/machine/declaration.js +28 -46
  33. package/dist/internal/machine/declaration.js.map +1 -1
  34. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  35. package/dist/internal/machine/executionPlan.js +23 -16
  36. package/dist/internal/machine/executionPlan.js.map +1 -1
  37. package/dist/internal/machine/implementation.d.ts +2 -0
  38. package/dist/internal/machine/implementation.d.ts.map +1 -1
  39. package/dist/internal/machine/implementation.js.map +1 -1
  40. package/dist/internal/machine/initialDeclaration.d.ts +2 -0
  41. package/dist/internal/machine/initialDeclaration.d.ts.map +1 -1
  42. package/dist/internal/machine/initialDeclaration.js +15 -0
  43. package/dist/internal/machine/initialDeclaration.js.map +1 -1
  44. package/dist/internal/machine/invocation.d.ts.map +1 -1
  45. package/dist/internal/machine/invocation.js +32 -21
  46. package/dist/internal/machine/invocation.js.map +1 -1
  47. package/dist/internal/machine/invocationEvent.d.ts +34 -17
  48. package/dist/internal/machine/invocationEvent.d.ts.map +1 -1
  49. package/dist/internal/machine/invocationEvent.js +16 -4
  50. package/dist/internal/machine/invocationEvent.js.map +1 -1
  51. package/dist/internal/machine/machine.d.ts +5 -22
  52. package/dist/internal/machine/machine.d.ts.map +1 -1
  53. package/dist/internal/machine/machine.js +157 -119
  54. package/dist/internal/machine/machine.js.map +1 -1
  55. package/dist/internal/machine/planner.d.ts +15 -4
  56. package/dist/internal/machine/planner.d.ts.map +1 -1
  57. package/dist/internal/machine/planner.js +18 -21
  58. package/dist/internal/machine/planner.js.map +1 -1
  59. package/dist/internal/machine/process.d.ts +2 -0
  60. package/dist/internal/machine/process.d.ts.map +1 -1
  61. package/dist/internal/machine/process.js +2 -0
  62. package/dist/internal/machine/process.js.map +1 -1
  63. package/dist/internal/machine/protocol.js.map +1 -1
  64. package/dist/internal/machine/runtime.d.ts.map +1 -1
  65. package/dist/internal/machine/runtime.js.map +1 -1
  66. package/dist/internal/machine/runtimeCompiled.js.map +1 -1
  67. package/dist/internal/machine/runtimeGeneric.js +5 -3
  68. package/dist/internal/machine/runtimeGeneric.js.map +1 -1
  69. package/dist/internal/machine/runtimeProtocol.d.ts +26 -0
  70. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -1
  71. package/dist/internal/machine/runtimeProtocol.js +71 -0
  72. package/dist/internal/machine/runtimeProtocol.js.map +1 -1
  73. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  74. package/dist/internal/machine/stateDefinition.js +0 -14
  75. package/dist/internal/machine/stateDefinition.js.map +1 -1
  76. package/dist/internal/machine/symbols.d.ts +9 -0
  77. package/dist/internal/machine/symbols.d.ts.map +1 -1
  78. package/dist/internal/machine/symbols.js.map +1 -1
  79. package/dist/internal/machine/topology.d.ts +18 -9
  80. package/dist/internal/machine/topology.d.ts.map +1 -1
  81. package/dist/internal/machine/topology.js +16 -1
  82. package/dist/internal/machine/topology.js.map +1 -1
  83. package/dist/internal/testing/machine/arbitrary.d.ts.map +1 -1
  84. package/dist/internal/testing/machine/arbitrary.js +2 -0
  85. package/dist/internal/testing/machine/arbitrary.js.map +1 -1
  86. package/dist/internal/testing/machine/check.d.ts +17 -0
  87. package/dist/internal/testing/machine/check.d.ts.map +1 -0
  88. package/dist/internal/testing/machine/check.js +371 -0
  89. package/dist/internal/testing/machine/check.js.map +1 -0
  90. package/dist/internal/testing/machine/exploration.d.ts.map +1 -1
  91. package/dist/internal/testing/machine/exploration.js.map +1 -1
  92. package/dist/internal/testing/machine/finiteModel.d.ts +14 -13
  93. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  94. package/dist/internal/testing/machine/finiteModel.js +21 -23
  95. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  96. package/dist/internal/testing/machine/runtime.d.ts +19 -88
  97. package/dist/internal/testing/machine/runtime.d.ts.map +1 -1
  98. package/dist/internal/testing/machine/runtime.js +0 -19
  99. package/dist/internal/testing/machine/runtime.js.map +1 -1
  100. package/dist/internal/testing/machine/runtimeInvariant.js.map +1 -1
  101. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  102. package/dist/internal/testing/machine/verification.js.map +1 -1
  103. package/dist/testing/MachineTest.d.ts +349 -139
  104. package/dist/testing/MachineTest.d.ts.map +1 -1
  105. package/dist/testing/MachineTest.js +201 -136
  106. package/dist/testing/MachineTest.js.map +1 -1
  107. package/dist/unstable/cluster/ClusterMachine.d.ts +9 -14
  108. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  109. package/dist/unstable/cluster/ClusterMachine.js +9 -14
  110. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  111. package/dist/unstable/reactivity/AtomMachine.d.ts +169 -80
  112. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  113. package/dist/unstable/reactivity/AtomMachine.js +165 -76
  114. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  115. package/package.json +11 -9
  116. package/src/Machine.ts +1149 -2134
  117. package/src/internal/machine/atom.ts +3 -3
  118. package/src/internal/machine/cluster.ts +2 -2
  119. package/src/internal/machine/command.ts +10 -4
  120. package/src/internal/machine/configuration.ts +16 -17
  121. package/src/internal/machine/construction.ts +1 -1
  122. package/src/internal/machine/declaration.ts +25 -50
  123. package/src/internal/machine/executionPlan.ts +90 -56
  124. package/src/internal/machine/implementation.ts +3 -1
  125. package/src/internal/machine/initialDeclaration.ts +16 -0
  126. package/src/internal/machine/invocation.ts +73 -70
  127. package/src/internal/machine/invocationEvent.ts +46 -20
  128. package/src/internal/machine/machine.ts +217 -243
  129. package/src/internal/machine/planner.ts +72 -106
  130. package/src/internal/machine/process.ts +12 -0
  131. package/src/internal/machine/protocol.ts +6 -6
  132. package/src/internal/machine/runtime.ts +1 -5
  133. package/src/internal/machine/runtimeCompiled.ts +2 -2
  134. package/src/internal/machine/runtimeGeneric.ts +7 -7
  135. package/src/internal/machine/runtimeProtocol.ts +80 -4
  136. package/src/internal/machine/stateDefinition.ts +0 -39
  137. package/src/internal/machine/symbols.ts +11 -0
  138. package/src/internal/machine/topology.ts +40 -18
  139. package/src/internal/testing/machine/arbitrary.ts +2 -0
  140. package/src/internal/testing/machine/check.ts +460 -0
  141. package/src/internal/testing/machine/exploration.ts +4 -5
  142. package/src/internal/testing/machine/finiteModel.ts +40 -42
  143. package/src/internal/testing/machine/runtime.ts +31 -170
  144. package/src/internal/testing/machine/runtimeInvariant.ts +3 -3
  145. package/src/internal/testing/machine/verification.ts +14 -14
  146. package/src/testing/MachineTest.ts +366 -145
  147. package/src/unstable/cluster/ClusterMachine.ts +9 -14
  148. package/src/unstable/reactivity/AtomMachine.ts +167 -78
package/dist/Machine.d.ts CHANGED
@@ -15,11 +15,10 @@ import type * as Stream from "effect/Stream";
15
15
  import type * as Types from "effect/Types";
16
16
  import type * as Activities from "./internal/machine/activities.js";
17
17
  import type { ChildAlreadyExistsError, InfiniteTransitionError, MachineSchemaDecodeError, MachineSchemaEncodeError, StartupError, StoppedError } from "./internal/machine/machine.js";
18
- import * as internal from "./internal/machine/machine.js";
19
18
  import { InitialEventTypeId } from "./internal/machine/machine.js";
20
19
  import type { EnsureExecutable } from "./internal/machine/readiness.js";
21
20
  import type { ExcludeCompatibleRuntime } from "./internal/machine/requirements.js";
22
- import type * as internalRuntime from "./internal/machine/runtimeProtocol.js";
21
+ import type { MachineRuntime } from "./internal/machine/runtimeProtocol.js";
23
22
  import type * as StateDefinition from "./internal/machine/stateDefinition.js";
24
23
  import type * as Topology from "./internal/machine/topology.js";
25
24
  /**
@@ -37,14 +36,25 @@ export type TypeId = "~effect/Machine";
37
36
  * @since 0.4.0
38
37
  */
39
38
  export declare const TypeId: TypeId;
40
- declare const MachineOutputStatesTypeId: unique symbol;
41
- declare const MachineTypeId: unique symbol;
42
- declare const EventConstructionTypeId: unique symbol;
43
- declare const EmittedEventConstructionTypeId: unique symbol;
44
- declare const EventProtocolTypeId: unique symbol;
45
- declare const ParentModeTypeId: unique symbol;
39
+ declare const MachineOutputStatesTypeId: "~effect/Machine/OutputStates";
40
+ declare const MachineTypeId: "~effect/Machine/TypeCarrier";
41
+ declare const EventConstructionTypeId: "~effect/Machine/EventConstruction";
42
+ declare const EmittedEventConstructionTypeId: "~effect/Machine/EmittedEventConstruction";
43
+ declare const EventProtocolTypeId: "~effect/Machine/EventProtocol";
44
+ declare const ParentModeTypeId: "~effect/Machine/ParentMode";
45
+ declare const ChildMachineLogicTypeId: "~effect/Machine/ChildMachineLogic";
46
+ declare const InvokeTypeId: "~effect/Machine/Invoke";
47
+ declare const StateConstructionTypeId: "~effect/Machine/StateConstruction";
48
+ declare const TargetSnapshotTypeId: "~effect/Machine/TargetSnapshot";
49
+ declare const HistoryTargetTypeId: "~effect/Machine/HistoryTarget";
50
+ declare const InitialTargetTypeId: "~effect/Machine/InitialTarget";
51
+ declare const ChoiceTargetTypeId: "~effect/Machine/ChoiceTarget";
52
+ declare const NoTargetTypeId: "~effect/Machine/NoTarget";
53
+ declare const DeclinedTypeId: "~effect/Machine/Declined";
54
+ declare const StateUpdateTypeId: "~effect/Machine/StateUpdate";
55
+ declare const CombinedTargetTypeId: "~effect/Machine/CombinedTarget";
56
+ declare const SelectedBranchTypeId: "~effect/Machine/SelectedBranch";
46
57
  declare const ParentTypeId = "~effect/Machine/Parent";
47
- declare const ChildMachineLogicTypeId: typeof internal.ChildMachineLogicTypeId;
48
58
  /**
49
59
  * Type identifier used for the synthetic event passed to startup lifecycle
50
60
  * actions.
@@ -92,29 +102,38 @@ type IsAny<A> = 0 extends (1 & A) ? true : false;
92
102
  * **Gotchas**
93
103
  *
94
104
  * Use `guard` to decline a transition before constructing its next state.
95
- * Use `declinable: true` when a named branch resolver may return `decline()`.
105
+ * List `{ decline: true }` in `branches` when `resolve` may return `select.decline()`.
96
106
  * Register cancellable state-scoped delays in `make({ timers })`.
97
107
  *
98
- * **Example**
108
+ * **Example** (Declining an event with a guard)
99
109
  *
100
- * ```ts
110
+ * ```ts import.meta.vitest
101
111
  * import { Machine } from "@typeonce/effect-machine"
102
- * import { Schema } from "effect"
112
+ * import { Effect, Schema } from "effect"
113
+ *
103
114
  * const events = Machine.events({ Add: { by: Schema.Number } })
104
115
  * const Root = Machine.state({ fields: { count: Schema.Number } })
105
- * export const counter = Machine.make({
116
+ * const counter = Machine.make({
106
117
  * root: Root,
107
118
  * events
108
119
  * }).handle({
109
120
  * root: () => ({ count: 0 }),
110
121
  * on: {
111
122
  * Add: {
112
- * update: "root",
113
- * guard: ({ event }) => event.by > 0,
114
- * data: ({ root, event }) => ({ count: root.count + event.by })
123
+ * update: { root: ({ root, event }) => ({ count: root.count + event.by }) },
124
+ * guard: ({ event }) => event.by > 0
115
125
  * }
116
126
  * }
117
127
  * })
128
+ *
129
+ * const accepts = (by: number) =>
130
+ * Effect.gen(function*() {
131
+ * const initial = yield* Machine.planInitial(counter)
132
+ * return yield* Machine.can(counter, initial.state, events.Add({ by }))
133
+ * })
134
+ *
135
+ * await Effect.runPromise(accepts(1)) // => true
136
+ * await Effect.runPromise(accepts(0)) // => false
118
137
  * ```
119
138
  *
120
139
  * @category models
@@ -206,19 +225,27 @@ export interface Definition<States extends Machine.StateSchemas, Events extends
206
225
  * captured by value, so later mutation of the supplied objects cannot alter
207
226
  * the resulting machine.
208
227
  *
209
- * **Example**
210
- *
211
- * ```ts
212
- * const counter = definition.handle({ states: {
213
- * Count: {
214
- * on: {
215
- * Increment: {
216
- * update: "Count",
217
- * decoded: ({ event, state }) => new Count({ value: state.value + event.by })
218
- * }
219
- * }
220
- * }
221
- * } })
228
+ * **Example** (Adding handlers to a definition)
229
+ *
230
+ * ```ts import.meta.vitest
231
+ * import { Machine } from "@typeonce/effect-machine"
232
+ * import { Effect, Schema } from "effect"
233
+ *
234
+ * const Events = Machine.events({ Increment: { by: Schema.Number } })
235
+ * const definition = Machine.make({ root: Machine.state({ fields: { count: Schema.Number } }), events: Events })
236
+ *
237
+ * const counter = definition.handle({
238
+ * root: { count: 0 },
239
+ * on: { Increment: { update: { root: ({ root, event }) => ({ count: root.count + event.by }) } } }
240
+ * })
241
+ *
242
+ * const count = Effect.gen(function*() {
243
+ * const initial = yield* Machine.planInitial(counter)
244
+ * const planned = yield* Machine.plan(counter, initial.state, Events.Increment({ by: 2 }))
245
+ * return planned.next.value.count
246
+ * })
247
+ *
248
+ * await Effect.runPromise(count) // => 2
222
249
  * ```
223
250
  *
224
251
  * @since 0.4.0
@@ -299,9 +326,29 @@ StartupError,
299
326
  * @since 0.4.0
300
327
  */
301
328
  StoppedError } from "./internal/machine/machine.js";
329
+ export type {
330
+ /**
331
+ * Service required by operations that act on the machine executing them,
332
+ * such as `sendTo`, `stopChild`, and `spawn`.
333
+ *
334
+ * **When to use**
335
+ *
336
+ * Name this requirement when annotating a reusable helper built from those
337
+ * operations, or when exporting a value whose inferred type includes it.
338
+ *
339
+ * **Details**
340
+ *
341
+ * A running machine provides this service to the effects it executes, so it
342
+ * never appears in the requirements of the machine itself. Only the type is
343
+ * public: the service cannot be constructed or provided outside a running
344
+ * machine.
345
+ *
346
+ * @category services
347
+ * @since 0.47.0
348
+ */
349
+ MachineRuntime } from "./internal/machine/runtimeProtocol.js";
302
350
  declare const RuntimeRequirementTypeId = "~effect/Machine/RuntimeRequirement";
303
351
  declare const ActionRequirementTypeId = "~effect/Machine/ActionRequirement";
304
- type MachineRuntimeRequirement = internalRuntime.MachineRuntime;
305
352
  /**
306
353
  * Opaque marker used to keep staged action errors and services separate from
307
354
  * the Effect that plans a machine step.
@@ -342,7 +389,7 @@ export type PlanningServices<Requirements> = Exclude<Requirements, ActionRequire
342
389
  * @category utility types
343
390
  * @since 0.4.0
344
391
  */
345
- export type ExecutionServices<Requirements> = Exclude<PlanningServices<Requirements>, MachineRuntimeRequirement> | Exclude<ActionServices<Requirements>, MachineRuntimeRequirement>;
392
+ export type ExecutionServices<Requirements> = Exclude<PlanningServices<Requirements>, MachineRuntime> | Exclude<ActionServices<Requirements>, MachineRuntime>;
346
393
  /**
347
394
  * Managed runtime capability used to deliver raised events and publish
348
395
  * emitted notifications.
@@ -472,34 +519,6 @@ export type Command = {
472
519
  * @since 0.4.0
473
520
  */
474
521
  export declare namespace Runtime {
475
- /**
476
- * Protocol annotation for managed event delivery.
477
- *
478
- * @category models
479
- * @since 0.4.0
480
- */
481
- interface Protocol {
482
- readonly events?: unknown;
483
- readonly emits?: unknown;
484
- }
485
- /**
486
- * Extracts the events required by a runtime protocol annotation.
487
- *
488
- * @category utility types
489
- * @since 0.4.0
490
- */
491
- type Events<Protocol> = Protocol extends {
492
- readonly events: infer Events;
493
- } ? Events : never;
494
- /**
495
- * Extracts the emitted events required by a runtime protocol annotation.
496
- *
497
- * @category utility types
498
- * @since 0.4.0
499
- */
500
- type Emits<Protocol> = Protocol extends {
501
- readonly emits: infer Emits;
502
- } ? Emits : never;
503
522
  /**
504
523
  * Opaque service requirement for a machine runtime capability.
505
524
  *
@@ -514,7 +533,6 @@ export declare namespace Runtime {
514
533
  }
515
534
  }
516
535
  type IncompatibleRuntime<Requirements, Events, Emits> = Requirements extends Runtime.Requirement<infer RequiredEvents, infer RequiredEmits> ? IsAny<Requirements> extends true ? never : [RequiredEvents] extends [Events] ? [RequiredEmits] extends [Emits] ? never : Requirements : Requirements : never;
517
- declare const InvokeTypeId: typeof internal.InvokeTypeId;
518
536
  type StateDefinitionError<Message extends string, Path extends PropertyKey = never, Details extends PropertyKey = never> = {
519
537
  readonly "~effect/Machine/DefinitionError": Message;
520
538
  readonly path: Path;
@@ -535,7 +553,6 @@ type RootCompatibilityError<Message extends string> = {
535
553
  };
536
554
  type ActiveStateKey<States extends Machine.StateSchemas> = Machine.ActiveStateKey<States>;
537
555
  type HistoryStateKey<States extends Machine.StateSchemas> = Machine.HistoryStateKey<States>;
538
- type ChoiceStateKey<States extends Machine.StateSchemas> = Machine.ChoiceStateKey<States>;
539
556
  type StateDefinitionPath<Prefix extends string, Key extends PropertyKey> = Key extends string ? Key extends "" ? Prefix extends "" ? "<empty>" : `${Prefix}.<empty>` : Prefix extends "" ? Key : `${Prefix}.${Key}` : Key extends number ? Prefix extends "" ? `${Key}` : `${Prefix}.${Key}` : Prefix extends "" ? "<symbol>" : `${Prefix}.<symbol>`;
540
557
  type ValidateStateKey<Key extends PropertyKey, Prefix extends string> = Key extends symbol ? StateDefinitionError<"State keys must be strings, not symbols", StateDefinitionPath<Prefix, Key>, Key> : Key extends number ? StateDefinitionError<"State keys cannot use numeric forms", StateDefinitionPath<Prefix, Key>, Key> : Key extends "" ? StateDefinitionError<"State keys cannot be empty", StateDefinitionPath<Prefix, Key>, Key> : Key extends "__proto__" ? StateDefinitionError<"The state key \"__proto__\" is not allowed", StateDefinitionPath<Prefix, Key>, Key> : Key extends `${string}.${string}` ? StateDefinitionError<"State keys cannot contain \".\"", StateDefinitionPath<Prefix, Key>, Key> : Key extends `${number}` ? StateDefinitionError<"State keys cannot use numeric forms", StateDefinitionPath<Prefix, Key>, Key> : unknown;
541
558
  type ValidateStateTree<States extends Machine.StateSchemas, AllowHistory extends boolean = false, Prefix extends string = ""> = {
@@ -568,19 +585,14 @@ type ValidateStateNodeConfig<Node extends Machine.StateNodeConfig, Path extends
568
585
  type ValidateOutputSchema<Node> = "output" extends keyof Node ? Node extends {
569
586
  readonly output: Schema.Top;
570
587
  } ? unknown : StateDefinitionError<"State output must be a schema"> : unknown;
571
- type SelectorChildKey<Children extends Machine.StateSchemas> = ActiveStateKey<Children> | ChoiceStateKey<Children>;
572
- type ValidateInitialSelectorChild<Children extends Machine.StateSchemas, Path extends PropertyKey> = "initial" extends SelectorChildKey<Children> ? StateDefinitionError<"Active and choice child states cannot use the reserved target selector key \"initial\"", StateDefinitionPath<Extract<Path, string>, "initial">, "initial"> : unknown;
573
- type ValidateWithSelectorChild<Node extends Machine.StateNodeConfig, Children extends Machine.StateSchemas, Path extends PropertyKey> = Node extends {
574
- readonly schema: Machine.TaggedSchema;
575
- } ? "with" extends SelectorChildKey<Children> ? StateDefinitionError<"Schema-backed compound child states cannot use the reserved local target selector key \"with\"", StateDefinitionPath<Extract<Path, string>, "with">, "with"> : unknown : unknown;
576
588
  type ValidateStateNodeWithChildren<Node extends Machine.StateNodeConfig, Children, Path extends PropertyKey> = Children extends Machine.StateSchemas ? Node extends {
577
589
  readonly type: "final";
578
590
  } ? StateDefinitionError<"Final states cannot declare child states"> : Node extends {
579
591
  readonly type: "parallel";
580
- } ? ValidateInitialSelectorChild<Children, Path> & ("initial" extends keyof Node ? StateDefinitionError<"Parallel states cannot declare an initial child"> : {
592
+ } ? "initial" extends keyof Node ? StateDefinitionError<"Parallel states cannot declare an initial child"> : {
581
593
  readonly states: ValidateStateTree<Children, true, Extract<Path, string>>;
582
- } & ValidateOutputSchema<Node>) : "output" extends keyof Node ? StateDefinitionError<"Only final and parallel states can declare output"> : ValidateCompoundStateNode<Node, Children, Path> : StateDefinitionError<"Child states must be a state tree">;
583
- type ValidateCompoundStateNode<Node extends Machine.StateNodeConfig, Children extends Machine.StateSchemas, Path extends PropertyKey> = "initial" extends keyof Node ? StateDefinitionError<"Declare initial edges in handle", Path> : ValidateInitialSelectorChild<Children, Path> & ValidateWithSelectorChild<Node, Children, Path> & {
594
+ } & ValidateOutputSchema<Node> : "output" extends keyof Node ? StateDefinitionError<"Only final and parallel states can declare output"> : ValidateCompoundStateNode<Node, Children, Path> : StateDefinitionError<"Child states must be a state tree">;
595
+ type ValidateCompoundStateNode<Node extends Machine.StateNodeConfig, Children extends Machine.StateSchemas, Path extends PropertyKey> = "initial" extends keyof Node ? StateDefinitionError<"Declare initial edges in handle", Path> : {
584
596
  readonly states: ValidateStateTree<Children, true, Extract<Path, string>>;
585
597
  };
586
598
  type ValidateStateNodeWithoutChildren<Node extends Machine.StateNodeConfig> = "initial" extends keyof Node ? StateDefinitionError<"Atomic states cannot declare an initial child"> : Node extends {
@@ -623,12 +635,32 @@ type StateFieldsValidation<Node> = Node extends {
623
635
  readonly [Key in keyof Children]: StateFieldsValidation<Children[Key]>;
624
636
  };
625
637
  } : unknown);
626
- interface StateInput {
638
+ /**
639
+ * Declaration of one state node accepted by {@link state}: its schema or
640
+ * fields, its kind, and its nested child states.
641
+ *
642
+ * **When to use**
643
+ *
644
+ * Name this type when a declaration you emit includes the signature of
645
+ * `Machine.state`. Build state trees with `Machine.state` itself, which checks
646
+ * the declaration further.
647
+ *
648
+ * **Details**
649
+ *
650
+ * Each entry of `states` is a tagged schema, a nested declaration, or a
651
+ * descriptor returned by `Machine.state`. `Machine.state` validates the whole
652
+ * tree further, so satisfying this type alone does not make a declaration
653
+ * valid.
654
+ *
655
+ * @category models
656
+ * @since 0.47.0
657
+ */
658
+ export interface StateDeclaration {
627
659
  readonly schema?: Machine.TaggedSchema;
628
660
  readonly fields?: Schema.Struct.Fields;
629
661
  readonly type?: "active" | "parallel" | "final" | "history" | "choice";
630
662
  readonly initial?: string;
631
- readonly states?: Readonly<Record<string, Machine.TaggedSchema | StateInput | {
663
+ readonly states?: Readonly<Record<string, Machine.TaggedSchema | StateDeclaration | {
632
664
  readonly [StateTypeId]: typeof StateTypeId;
633
665
  readonly node: Machine.StateNodeConfig;
634
666
  }>>;
@@ -636,9 +668,9 @@ interface StateInput {
636
668
  readonly output?: Schema.Top;
637
669
  readonly annotations?: Machine.SchemaLessStateAnnotations;
638
670
  }
639
- interface StateConstructor {
640
- <const Node extends StateInput>(node: Node & StateFieldsValidation<NoInfer<Node>>, ..._validation: ValidateDefinedState<NormalizeState<NoInfer<Node>>>): State<NormalizedState<Node>>;
641
- }
671
+ type StateConstructor = {
672
+ <const Node extends StateDeclaration>(node: Node & StateFieldsValidation<NoInfer<Node>>, ..._validation: ValidateDefinedState<NormalizeState<NoInfer<Node>>>): State<NormalizedState<Node>>;
673
+ };
642
674
  type EventProtocolError<Message extends string, Tag extends PropertyKey = never> = {
643
675
  readonly "~effect/Machine/EventProtocolError": Message;
644
676
  readonly tag: Tag;
@@ -650,121 +682,9 @@ type DuplicateEventTag<Events extends ReadonlyArray<Machine.TaggedSchema>, Seen
650
682
  type ValidateInputEventProtocol<InputEvents extends ReadonlyArray<Machine.TaggedSchema>, DuplicateInput extends PropertyKey = DuplicateEventTag<InputEvents>> = [DuplicateInput] extends [never] ? unknown : EventProtocolError<"Public event tags must be unique", DuplicateInput>;
651
683
  type ValidateInternalEventProtocol<InputEvents extends ReadonlyArray<Machine.TaggedSchema>, InternalEvents extends ReadonlyArray<Machine.TaggedSchema>, DuplicateInternal extends PropertyKey = DuplicateEventTag<InternalEvents>, Overlap extends PropertyKey = Extract<Machine.TagOf<InputEvents[number]>, Machine.TagOf<InternalEvents[number]>>> = [DuplicateInternal] extends [never] ? [Overlap] extends [never] ? unknown : EventProtocolError<"Public and internal event tags must be disjoint", Overlap> : EventProtocolError<"Internal event tags must be unique", DuplicateInternal>;
652
684
  type ValidateEventProtocolBuilder<Kind extends Machine.EventProtocolKind, Inputs extends ReadonlyArray<Machine.EventProtocolInput<Kind>>, Schemas extends ReadonlyArray<Machine.TaggedSchema> = Machine.EventProtocolInputSchemasOf<Kind, Inputs>, Duplicate extends PropertyKey = DuplicateEventTag<Schemas>> = [Duplicate] extends [never] ? unknown : EventProtocolError<"Event protocol tags must be unique", Duplicate>;
653
- declare const SnapshotBuilderStateTypeId: typeof internal.SnapshotBuilderStateTypeId;
654
- declare const SnapshotBuilderConstructionTypeId: unique symbol;
655
- type SnapshotBuilderComplete<Regions, Constructed extends boolean = false> = {
656
- readonly [SnapshotBuilderStateTypeId]: Regions;
657
- readonly [SnapshotBuilderConstructionTypeId]: Constructed;
658
- };
659
- type FromCallable<Arguments extends ReadonlyArray<unknown>, Result> = Arguments extends readonly [infer Input, ...infer Rest extends ReadonlyArray<unknown>] ? {} extends Input ? {
660
- (...args: Rest): Result;
661
- (...args: Arguments): Result;
662
- } : (...args: Arguments) => Result : (...args: Arguments) => Result;
663
- type FromMethod<in out Arguments extends ReadonlyArray<unknown>, out Result> = {
664
- /**
665
- * Constructs the selected state from its schema make input while the
666
- * machine plans the resulting configuration. The input may be omitted when
667
- * the schema accepts an empty constructor object.
668
- *
669
- * @since 0.4.0
670
- */
671
- readonly from: FromCallable<Arguments, Machine.StateConstruction<Result>>;
672
- };
673
- type DecodedMethod<Arguments extends ReadonlyArray<unknown>, Result> = {
674
- /**
675
- * Constructs the selected state from an already-decoded schema value. The
676
- * machine validates the value against the schema's type side while planning.
677
- *
678
- * @since 0.22.0
679
- */
680
- readonly decoded: (...args: Arguments) => Result;
681
- };
682
- type ConstructionResult<Result> = Result | Machine.StateConstruction<Result>;
683
- type UnwrapConstruction<Result> = Result extends Machine.StateConstruction<infer Value> ? Value : Result;
684
685
  type NodeValue<Node> = [Machine.NodeSchema<Node>] extends [never] ? undefined : Machine.NodeSchema<Node>["Type"];
685
686
  type NodeMakeInput<Node> = [Machine.NodeSchema<Node>] extends [never] ? never : Machine.NodeSchema<Node>["~type.make.in"];
686
- type WithNodeValue<Node, Rest extends ReadonlyArray<unknown>> = Machine.NodeSchema<Node> extends never ? Rest : readonly [value: NodeValue<Node>, ...Rest];
687
- type WithNodeInput<Node, Rest extends ReadonlyArray<unknown>> = Machine.NodeSchema<Node> extends never ? Rest : readonly [input: NodeMakeInput<Node>, ...Rest];
688
- type NodeBuilderMethod<Node, Arguments extends ReadonlyArray<unknown>, Result, FromArguments extends ReadonlyArray<unknown>, FromResult> = Machine.NodeSchema<Node> extends never ? {
689
- readonly from: FromCallable<FromArguments, FromResult>;
690
- } : DecodedMethod<Arguments, Result> & {
691
- readonly from: FromCallable<FromArguments, FromResult>;
692
- };
693
- type NodeMethod<Node, Arguments extends ReadonlyArray<unknown>, Result, FromArguments extends ReadonlyArray<unknown>> = Machine.NodeSchema<Node> extends never ? FromMethod<FromArguments, Result> : DecodedMethod<Arguments, Result> & FromMethod<FromArguments, Result>;
694
- type NodeMethodWithInitial<Node, Arguments extends ReadonlyArray<unknown>, Result, FromArguments extends ReadonlyArray<unknown>, Path extends string> = Machine.NodeSchema<Node> extends never ? {
695
- readonly from: FromCallable<FromArguments, Machine.StateConstruction<Result>>;
696
- readonly initial: InitialTargetFactory<Node, Path>;
697
- } : DecodedMethod<Arguments, Result> & {
698
- readonly from: FromCallable<FromArguments, Machine.StateConstruction<Result>>;
699
- readonly initial: InitialTargetFactory<Node, Path>;
700
- };
701
- interface InitialTargetMethod<Node, Path extends string> {
702
- /** Enters this state through its declared initial configuration. */
703
- readonly initial: InitialTargetFactory<Node, Path>;
704
- }
705
- interface InitialTargetFactory<Node, Path extends string> {
706
- readonly from: FromCallable<WithNodeInput<Node, readonly []>, Machine.StateConstruction<Machine.InitialTarget<Path>>>;
707
- readonly decoded: (...args: WithNodeValue<Node, readonly []>) => Machine.InitialTarget<Path>;
708
- }
709
- type NodeConstructionSelectorFromCallable<Node, Builder, Result> = Machine.NodeSchema<Node> extends never ? {
710
- <Selected extends ConstructionResult<Result>>(state: (builder: Builder) => Selected): Machine.StateConstruction<UnwrapConstruction<Selected>>;
711
- } : ConstructionSelectorFromCallable<NodeMakeInput<Node>, Builder, Result>;
712
- type NestedTargetMethod<Node, Builder, Result, Path extends string> = Machine.NodeSchema<Node> extends never ? {
713
- readonly from: NodeConstructionSelectorFromCallable<Node, Builder, Result>;
714
- readonly initial: InitialTargetFactory<Node, Path>;
715
- } : {
716
- readonly decoded: <Selected extends ConstructionResult<Result>>(value: NodeValue<Node>, state: (builder: Builder) => Selected) => Selected;
717
- readonly from: NodeConstructionSelectorFromCallable<Node, Builder, Result>;
718
- readonly initial: InitialTargetFactory<Node, Path>;
719
- };
720
- type ConstructionSelectorFromCallable<Input, Builder, Result> = {} extends Input ? {
721
- <Selected extends ConstructionResult<Result>>(state: (builder: Builder) => Selected): Machine.StateConstruction<UnwrapConstruction<Selected>>;
722
- <Selected extends ConstructionResult<Result>>(input: Input, state: (builder: Builder) => Selected): Machine.StateConstruction<UnwrapConstruction<Selected>>;
723
- } : <Selected extends ConstructionResult<Result>>(input: Input, state: (builder: Builder) => Selected) => Machine.StateConstruction<UnwrapConstruction<Selected>>;
724
- type FullSnapshotBuilderWithPrefix<in out States extends Machine.StateSchemas, in out Prefix extends string = ""> = {
725
- readonly [Key in ActiveStateKey<States> | ChoiceStateKey<States>]: Key extends ActiveStateKey<States> ? FullSnapshotMethod<States, Key, Prefix> : () => Machine.ChoiceTargetInstruction<Machine.JoinPath<Prefix, Key>>;
726
- };
727
- type FullSnapshotMethod<in out States extends Machine.StateSchemas, in out StateId extends ActiveStateKey<States>, in out Prefix extends string> = {
728
- readonly [
729
- /** Constructs this node using schema make input or an already decoded value. */
730
- Method in Machine.NodeSchema<States[StateId]> extends never ? "from" : "from" | "decoded"]: Method extends "from" ? FromCallable<FullSnapshotFromArguments<States, StateId, Prefix>, Machine.StateConstruction<FullSnapshotResult<States, StateId, Prefix>>> : (...args: FullSnapshotArguments<States, StateId, Prefix>) => FullSnapshotResult<States, StateId, Prefix>;
731
- };
732
- type FullSnapshotArguments<States extends Machine.StateSchemas, StateId extends ActiveStateKey<States>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends infer Node ? Node extends {
733
- readonly type: "parallel";
734
- readonly states: infer Children extends Machine.StateSchemas;
735
- } ? WithNodeValue<Node, [
736
- states: (builder: FullParallelBuilder<Children, Path>) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>>
737
- ]> : Node extends {
738
- readonly states: infer Children extends Machine.StateSchemas;
739
- } ? WithNodeValue<Node, [
740
- state: (builder: FullSnapshotBuilderWithPrefix<Children, Path>) => Machine.SnapshotWithPrefix<Children, Path> | Machine.ChoiceTargetInstruction<Machine.ChoiceIdentifierWithPrefix<Children, Path>>
741
- ]> : WithNodeValue<Node, []> : never;
742
- type FullSnapshotFromArguments<States extends Machine.StateSchemas, StateId extends ActiveStateKey<States>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends infer Node ? Node extends {
743
- readonly type: "parallel";
744
- readonly states: infer Children extends Machine.StateSchemas;
745
- } ? WithNodeInput<Node, [
746
- states: (builder: FullParallelBuilder<Children, Path>) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>, boolean>
747
- ]> : Node extends {
748
- readonly states: infer Children extends Machine.StateSchemas;
749
- } ? WithNodeInput<Node, [
750
- state: (builder: FullSnapshotBuilderWithPrefix<Children, Path>) => ConstructionResult<Machine.SnapshotWithPrefix<Children, Path> | Machine.ChoiceTargetInstruction<Machine.ChoiceIdentifierWithPrefix<Children, Path>>>
751
- ]> : WithNodeInput<Node, []> : never;
752
687
  type FullSnapshotResult<States extends Machine.StateSchemas, StateId extends ActiveStateKey<States>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = Machine.SnapshotByIdentifierWithPath<States, StateId, Path>;
753
- type InitialEntryStateKey<States extends Machine.StateSchemas> = {
754
- readonly [Key in ActiveStateKey<States>]: States[Key] extends {
755
- readonly states: Machine.StateSchemas;
756
- } ? Key : never;
757
- }[ActiveStateKey<States>];
758
- type FullInitialTargetBuilder<States extends Machine.StateSchemas> = {
759
- readonly [Key in InitialEntryStateKey<States>]: InitialTargetMethod<States[Key], Key>;
760
- };
761
- type FullParallelBuilder<States extends Machine.StateSchemas, Prefix extends string, Remaining extends ActiveStateKey<States> = ActiveStateKey<States>, Regions = {}, Constructed extends boolean = false> = SnapshotBuilderComplete<Regions, Constructed> & {
762
- readonly [Key in Remaining]: NodeBuilderMethod<States[Key], FullSnapshotArguments<States, Key, Prefix>, FullParallelBuilder<States, Prefix, Exclude<Remaining, Key>, Regions & {
763
- readonly [Region in Key]: FullSnapshotResult<States, Key, Prefix>;
764
- }, Constructed>, FullSnapshotFromArguments<States, Key, Prefix>, FullParallelBuilder<States, Prefix, Exclude<Remaining, Key>, Regions & {
765
- readonly [Region in Key]: FullSnapshotResult<States, Key, Prefix>;
766
- }, true>>;
767
- };
768
688
  type HistorySnapshotResult<States extends Machine.StateSchemas, StateId extends ActiveStateKey<States>, Prefix extends string, Owner extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = Path extends Owner ? FullSnapshotResult<States, StateId, Prefix> : States[StateId] extends infer Node ? Node extends {
769
689
  readonly type: "parallel";
770
690
  readonly states: infer Children extends Machine.StateSchemas;
@@ -778,89 +698,6 @@ type HistorySnapshotRegions<States extends Machine.StateSchemas, Prefix extends
778
698
  readonly [Key in ActiveStateKey<States>]: Owner extends Machine.JoinPath<Prefix, Key> | (Machine.JoinPath<Prefix, Key> extends "" ? string : `${Machine.JoinPath<Prefix, Key>}.${string}`) ? HistorySnapshotResult<States, Key, Prefix, Owner> : FullSnapshotResult<States, Key, Prefix>;
779
699
  };
780
700
  type ParentPath<Path extends string> = Machine.ImmediateParentStateIdentifier<Path>;
781
- type IsCompoundNode<Node> = Node extends {
782
- readonly type: "parallel";
783
- } ? false : Node extends {
784
- readonly states: Machine.StateSchemas;
785
- } ? true : false;
786
- type NearestCompoundScope<States extends Machine.StateSchemas, Source extends Machine.StateNodeIdentifier<States>> = Source extends Machine.StateIdentifier<States> ? IsCompoundNode<Machine.NodeByIdentifier<States, Source>> extends true ? Source : ParentPath<Source> extends infer Parent extends Machine.StateIdentifier<States> ? NearestCompoundScope<States, Parent> : never : ParentPath<Source> extends infer Parent extends Machine.StateIdentifier<States> ? NearestCompoundScope<States, Parent> : never;
787
- type ChildrenOf<States extends Machine.StateSchemas, Path extends Machine.StateIdentifier<States>> = Machine.NodeByIdentifier<States, Path> extends {
788
- readonly states: infer Children extends Machine.StateSchemas;
789
- } ? Children : never;
790
- type StateIdentifierFromPath<States extends Machine.StateSchemas, Path extends string> = Extract<Path, Machine.StateIdentifier<States>>;
791
- type LocalTargetResult<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, StateId extends ActiveStateKey<States>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends {
792
- readonly states: infer Children extends Machine.StateSchemas;
793
- } ? States[StateId] extends {
794
- readonly type: "parallel";
795
- } ? Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>> : LocalTargetResultWithPrefix<AllStates, Children, Path> : Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>;
796
- type LocalTargetResultWithPrefix<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, Prefix extends string> = {
797
- readonly [Key in ActiveStateKey<States>]: LocalTargetResult<AllStates, States, Key, Prefix>;
798
- }[ActiveStateKey<States>] | Machine.ChoiceTarget<AllStates, Extract<Machine.JoinPath<Prefix, ChoiceStateKey<States>>, Machine.ChoiceIdentifier<AllStates>>>;
799
- type LocalTargetBuilderWithPrefix<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, Prefix extends string, Source extends Machine.StateNodeIdentifier<AllStates>> = {
800
- readonly [Key in ActiveStateKey<States>]: LocalTargetMethod<AllStates, States, Key, Prefix, Source>;
801
- } & {
802
- readonly [Key in ChoiceStateKey<States>]: () => Machine.ChoiceTarget<AllStates, Extract<Machine.JoinPath<Prefix, Key>, Machine.ChoiceIdentifier<AllStates>>>;
803
- };
804
- type LocalTargetMethod<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, StateId extends ActiveStateKey<States>, Prefix extends string, Source extends Machine.StateNodeIdentifier<AllStates>, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends infer Node ? Node extends {
805
- readonly type: "parallel";
806
- readonly states: infer Children extends Machine.StateSchemas;
807
- } ? Source extends Path | (Path extends "" ? string : `${Path}.${string}`) ? NestedTargetMethod<Node, LocalTargetBuilderWithPrefix<AllStates, Children, Path, Source>, LocalTargetResultWithPrefix<AllStates, Children, Path>, Path> : NodeMethodWithInitial<Node, WithNodeValue<Node, [
808
- states: (builder: FullParallelBuilder<Children, Path>) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>>
809
- ]>, Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>, WithNodeInput<Node, [
810
- states: (builder: FullParallelBuilder<Children, Path>) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>, boolean>
811
- ]>, Path> : Node extends {
812
- readonly states: infer Children extends Machine.StateSchemas;
813
- } ? NestedTargetMethod<Node, LocalTargetBuilderWithPrefix<AllStates, Children, Path, Source>, LocalTargetResultWithPrefix<AllStates, Children, Path>, Path> : NodeMethod<Node, WithNodeValue<Node, []>, Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>, WithNodeInput<Node, []>> : never;
814
- type LocalTargetBuilderForScope<States extends Machine.StateSchemas, Scope extends Machine.StateIdentifier<States>, Source extends Machine.StateNodeIdentifier<States>> = ChildrenOf<States, Scope> extends infer Children extends Machine.StateSchemas ? LocalTargetBuilderWithPrefix<States, Children, Scope, Source> & (Scope extends Machine.ValuedStateIdentifier<States> ? {
815
- /**
816
- * Updates the value of the state containing the local group and moves to
817
- * one of the states inside it. Values in other active branches are kept.
818
- *
819
- * @since 0.4.0
820
- */
821
- readonly with: {
822
- readonly decoded: <Result extends ConstructionResult<LocalTargetResultWithPrefix<States, Children, Scope>>>(value: Machine.StateByIdentifier<States, Scope>, state: (builder: LocalTargetBuilderWithPrefix<States, Children, Scope, Source>) => Result) => Result;
823
- readonly from: ConstructionSelectorFromCallable<Machine.SchemaByIdentifier<States, Scope>["~type.make.in"], LocalTargetBuilderWithPrefix<States, Children, Scope, Source>, LocalTargetResultWithPrefix<States, Children, Scope>>;
824
- };
825
- } : {}) : {};
826
- type BranchTargetResult<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, StateId extends ActiveStateKey<States>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends {
827
- readonly states: infer Children extends Machine.StateSchemas;
828
- } ? States[StateId] extends {
829
- readonly type: "parallel";
830
- } ? Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>> : BranchTargetResultWithPrefix<AllStates, Children, Path> : Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>;
831
- type BranchTargetResultWithPrefix<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, Prefix extends string> = {
832
- readonly [Key in ActiveStateKey<States>]: BranchTargetResult<AllStates, States, Key, Prefix>;
833
- }[ActiveStateKey<States>] | Machine.ChoiceTarget<AllStates, Extract<Machine.JoinPath<Prefix, ChoiceStateKey<States>>, Machine.ChoiceIdentifier<AllStates>>>;
834
- type BranchTargetBuilderWithPrefix<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, Prefix extends string, Source extends Machine.StateNodeIdentifier<AllStates>> = {
835
- readonly [Key in ActiveStateKey<States>]: BranchTargetMethod<AllStates, States, Key, Prefix, Source>;
836
- } & {
837
- readonly [Key in ChoiceStateKey<States>]: () => Machine.ChoiceTarget<AllStates, Extract<Machine.JoinPath<Prefix, Key>, Machine.ChoiceIdentifier<AllStates>>>;
838
- };
839
- type BranchTargetMethod<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, StateId extends ActiveStateKey<States>, Prefix extends string, Source extends Machine.StateNodeIdentifier<AllStates>, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends infer Node ? Node extends {
840
- readonly type: "parallel";
841
- readonly states: infer Children extends Machine.StateSchemas;
842
- } ? Source extends Path | (Path extends "" ? string : `${Path}.${string}`) ? NestedTargetMethod<Node, BranchTargetBuilderWithPrefix<AllStates, Children, Path, Source>, BranchTargetResultWithPrefix<AllStates, Children, Path>, Path> & BranchTargetBuilderWithPrefix<AllStates, Children, Path, Source> : NodeMethodWithInitial<Node, WithNodeValue<Node, [
843
- states: (builder: FullParallelBuilder<Children, Path>) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>>
844
- ]>, Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>, WithNodeInput<Node, [
845
- states: (builder: FullParallelBuilder<Children, Path>) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>, boolean>
846
- ]>, Path> : Node extends {
847
- readonly states: infer Children extends Machine.StateSchemas;
848
- } ? NestedTargetMethod<Node, BranchTargetBuilderWithPrefix<AllStates, Children, Path, Source>, BranchTargetResultWithPrefix<AllStates, Children, Path>, Path> & BranchTargetBuilderWithPrefix<AllStates, Children, Path, Source> : NodeMethod<Node, WithNodeValue<Node, []>, Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>, WithNodeInput<Node, []>> : never;
849
- type BranchTargetBuilderForRoot<States extends Machine.StateSchemas, Root extends ActiveStateKey<States>, Source extends Machine.StateNodeIdentifier<States>> = {
850
- readonly [Key in Root]: BranchTargetMethod<States, States, Key, "", Source>;
851
- };
852
- type HistoryContainingKey<States extends Machine.StateSchemas> = {
853
- readonly [Key in Extract<keyof States, string>]: States[Key] extends Machine.HistoryStateNodeConfig ? Key : States[Key] extends {
854
- readonly states: infer Children extends Machine.StateSchemas;
855
- } ? [
856
- Machine.HistoryIdentifier<Children>
857
- ] extends [never] ? never : Key : never;
858
- }[Extract<keyof States, string>];
859
- type HistoryTargetBuilderWithPrefix<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, Prefix extends string> = {
860
- readonly [Key in HistoryContainingKey<States>]: States[Key] extends Machine.HistoryStateNodeConfig ? () => Machine.HistoryTarget<AllStates, Extract<Machine.JoinPath<Prefix, Key>, Machine.HistoryIdentifier<AllStates>>> : States[Key] extends {
861
- readonly states: infer Children extends Machine.StateSchemas;
862
- } ? HistoryTargetBuilderWithPrefix<AllStates, Children, Machine.JoinPath<Prefix, Key>> : never;
863
- };
864
701
  type HasDirectShallowHistory<States extends Machine.StateSchemas> = {
865
702
  readonly [Key in HistoryStateKey<States>]: States[Key] extends {
866
703
  readonly history: "deep";
@@ -891,7 +728,7 @@ type SpawnIdError<Options extends SpawnOptions> = "id" extends keyof Options ? O
891
728
  readonly id?: infer Id;
892
729
  } ? [Id] extends [undefined] ? never : ChildAlreadyExistsError : ChildAlreadyExistsError : never;
893
730
  type SpawnError<Options extends SpawnOptions> = SpawnIdError<Options>;
894
- type SpawnResult<State, Event, Error, Requirements, Output, SpawnError, InitialError = never> = Effect.Effect<MachineRef<State, Event, Error, Output>, SpawnError | InitialError, MachineRuntimeRequirement | SpawnRequirements<Requirements>>;
731
+ type SpawnResult<State, Event, Error, Requirements, Output, SpawnError, InitialError = never> = Effect.Effect<MachineRef<State, Event, Error, Output>, SpawnError | InitialError, MachineRuntime | SpawnRequirements<Requirements>>;
895
732
  /**
896
733
  * Represents the active or terminal lifecycle state of a running machine.
897
734
  *
@@ -1163,9 +1000,14 @@ export interface Prepared<out State, in Event, out Error, out Output, out Emitte
1163
1000
  * `send` reports whether an event was accepted for delivery. A running
1164
1001
  * machine reference is local, so an idle machine processes an accepted event
1165
1002
  * in the sender's turn: work that completes without suspending is reflected
1166
- * by `snapshot` when `send` returns. Work that suspends continues in the
1167
- * background, and an event sent while the machine is processing is queued
1168
- * behind the current work. `changes` subscribers receive every committed
1003
+ * by `snapshot` when `send` returns. Work invoked by an entered state also
1004
+ * starts in the sender's turn and runs until it first suspends, so browser
1005
+ * APIs that require user activation, such as `window.open`, can run in the
1006
+ * first step of an invoked Effect. Work that suspends continues in the
1007
+ * background, and its outcome is handled in a later turn, even when the work
1008
+ * completes without suspending, so the entered state is always observed
1009
+ * before the outcome leaves it. An event sent while the machine is processing
1010
+ * is queued behind the current work. `changes` subscribers receive every committed
1169
1011
  * snapshot in order once the sender yields, with consecutive sends delivered
1170
1012
  * together. This guarantee belongs to `MachineRef`; a `MachineTarget` only
1171
1013
  * promises delivery. Errors that occur while processing an accepted event are
@@ -1198,7 +1040,8 @@ export interface MachineRef<out State, in Event, out Error = never, out Output =
1198
1040
  /**
1199
1041
  * Accepts an event for processing by this local machine. An idle machine
1200
1042
  * processes it in the sender's turn until the work first suspends, so
1201
- * `snapshot` reflects it when `send` returns.
1043
+ * `snapshot` reflects it when `send` returns. Work invoked by an entered
1044
+ * state starts in the same turn; its outcome is handled in a later turn.
1202
1045
  */
1203
1046
  readonly send: (event: Event) => Effect.Effect<void, StoppedError>;
1204
1047
  /**
@@ -1310,10 +1153,11 @@ type InvokeLifecycleId = string & {
1310
1153
  *
1311
1154
  * **Details**
1312
1155
  *
1313
- * The descriptor carries the child's address and complete machine type. Pass
1314
- * a descriptor for the same id and machine to inline `invoke`, `sendTo`, and
1315
- * child lookup APIs so state, event, error, and output types are inferred
1316
- * without separate annotations.
1156
+ * The descriptor carries the child's address and complete machine type.
1157
+ * Register it in `make({ children })` to invoke it by `src`, and pass a
1158
+ * descriptor for the same id and machine to `sendTo` and child lookup APIs, so
1159
+ * state, event, error, and output types are inferred without separate
1160
+ * annotations.
1317
1161
  *
1318
1162
  * @category models
1319
1163
  * @since 0.4.0
@@ -1324,8 +1168,8 @@ export interface ChildMachine<Id extends string, M extends Machine.Any> {
1324
1168
  readonly id: Id;
1325
1169
  /** Complete machine definition carried by this descriptor. */
1326
1170
  readonly machine: M;
1327
- /** @internal */
1328
- readonly [ChildMachineLogicTypeId]: (input?: unknown) => Logic<any, any, any, any, any, any>;
1171
+ /** @internal Brand of descriptors built by `child` and `childFamily`. */
1172
+ readonly [ChildMachineLogicTypeId]: typeof ChildMachineLogicTypeId;
1329
1173
  }
1330
1174
  /**
1331
1175
  * Namespace containing type-level members associated with `ChildMachine`.
@@ -1402,7 +1246,7 @@ export declare namespace ChildMachine {
1402
1246
  * @category utility types
1403
1247
  * @since 0.20.0
1404
1248
  */
1405
- type StartRequirements<Child extends Any> = Child extends ChildMachine<string, infer M> ? Exclude<ExcludeCompatibleRuntime<Exclude<ExecutionServices<Machine.InitialServices<M> | Machine.Services<M>>, MachineRuntimeRequirement>, Machine.Event<M>, Machine.EmittedEvent<M>>, Scope.Scope> : never;
1249
+ type StartRequirements<Child extends Any> = Child extends ChildMachine<string, infer M> ? Exclude<ExcludeCompatibleRuntime<Exclude<ExecutionServices<Machine.InitialServices<M> | Machine.Services<M>>, MachineRuntime>, Machine.Event<M>, Machine.EmittedEvent<M>>, Scope.Scope> : never;
1406
1250
  /**
1407
1251
  * Running machine reference selected by a child descriptor.
1408
1252
  *
@@ -1500,15 +1344,6 @@ export declare namespace ChildAddress {
1500
1344
  export interface SpawnOptions {
1501
1345
  readonly id?: string;
1502
1346
  }
1503
- /**
1504
- * Options for spawning child processes with a parent-local id.
1505
- *
1506
- * @category models
1507
- * @since 0.4.0
1508
- */
1509
- export interface SpawnIdOptions extends SpawnOptions {
1510
- readonly id: string;
1511
- }
1512
1347
  /**
1513
1348
  * Namespace containing type-level members associated with `Machine`.
1514
1349
  *
@@ -1521,7 +1356,7 @@ export declare namespace Machine {
1521
1356
  *
1522
1357
  * @internal
1523
1358
  */
1524
- interface TypeCarrier<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Input extends Schema.Top, UnhandledStates extends StateIdentifier<States>, E, R, InitialE, InitialR, FinalStates extends StateIdentifier<States>, Output, Emits extends ReadonlyArray<TaggedSchema>, OutputStates extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema>, ParentEvents extends ReadonlyArray<TaggedSchema>> {
1359
+ export interface TypeCarrier<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Input extends Schema.Top, UnhandledStates extends StateIdentifier<States>, E, R, InitialE, InitialR, FinalStates extends StateIdentifier<States>, Output, Emits extends ReadonlyArray<TaggedSchema>, OutputStates extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema>, ParentEvents extends ReadonlyArray<TaggedSchema>> {
1525
1360
  readonly states: States;
1526
1361
  readonly events: Events;
1527
1362
  readonly input: Input;
@@ -1538,17 +1373,17 @@ export declare namespace Machine {
1538
1373
  readonly parentEvents: ParentEvents;
1539
1374
  }
1540
1375
  /** @internal Carries parent availability without widening the event tuple. */
1541
- type ParentEventSchemas<Mode extends ParentMode, Events extends ReadonlyArray<TaggedSchema>> = Events & {
1376
+ export type ParentEventSchemas<Mode extends ParentMode, Events extends ReadonlyArray<TaggedSchema>> = Events & {
1542
1377
  readonly [ParentModeTypeId]: Mode;
1543
1378
  };
1544
1379
  /** Extracts the parent availability encoded in a machine event tuple. */
1545
- type ParentModeOf<Events extends ReadonlyArray<TaggedSchema>> = Events extends {
1380
+ export type ParentModeOf<Events extends ReadonlyArray<TaggedSchema>> = Events extends {
1546
1381
  readonly [ParentModeTypeId]: infer Mode extends ParentMode;
1547
1382
  } ? Mode : Events extends readonly [] ? "none" : "optional";
1548
1383
  /** Extracts the event schemas declared by an owning-machine protocol. */
1549
- type ParentEventsOf<Declaration extends Parent.Any | undefined> = Declaration extends Parent<infer Mode, infer Events> ? ParentEventSchemas<Mode, Events> : readonly [];
1384
+ export type ParentEventsOf<Declaration extends Parent.Any | undefined> = Declaration extends Parent<infer Mode, infer Events> ? ParentEventSchemas<Mode, Events> : readonly [];
1550
1385
  /** Extracts the owning-machine declaration carried by a machine. */
1551
- type ParentDeclarationOf<Events extends ReadonlyArray<TaggedSchema>> = ParentModeOf<Events> extends infer Mode ? Mode extends ParentMode ? Parent<Mode, Events> : undefined : never;
1386
+ export type ParentDeclarationOf<Events extends ReadonlyArray<TaggedSchema>> = ParentModeOf<Events> extends infer Mode ? Mode extends ParentMode ? Parent<Mode, Events> : undefined : never;
1552
1387
  /**
1553
1388
  * Constraint applied to APIs that create an independent root runtime.
1554
1389
  *
@@ -1562,7 +1397,7 @@ export declare namespace Machine {
1562
1397
  * @category utility types
1563
1398
  * @since 0.27.0
1564
1399
  */
1565
- type RootCompatible<Events extends ReadonlyArray<TaggedSchema>> = ParentModeOf<Events> extends "required" ? RootCompatibilityError<"Machine declares a required parent and cannot run as a root; invoke or spawn it from an owning machine"> : unknown;
1400
+ export type RootCompatible<Events extends ReadonlyArray<TaggedSchema>> = ParentModeOf<Events> extends "required" ? RootCompatibilityError<"Machine declares a required parent and cannot run as a root; invoke or spawn it from an owning machine"> : unknown;
1566
1401
  /**
1567
1402
  * Any schema-first machine.
1568
1403
  *
@@ -1575,7 +1410,7 @@ export declare namespace Machine {
1575
1410
  * @category models
1576
1411
  * @since 0.4.0
1577
1412
  */
1578
- interface Any extends Pipeable {
1413
+ export interface Any extends Pipeable {
1579
1414
  readonly [TypeId]: TypeId;
1580
1415
  /** @internal */
1581
1416
  readonly [MachineTypeId]: TypeCarrier<any, any, any, any, any, any, any, any, any, any, any, any, any, any>;
@@ -1602,21 +1437,21 @@ export declare namespace Machine {
1602
1437
  * @category utility types
1603
1438
  * @since 0.4.0
1604
1439
  */
1605
- type States<M extends Any> = M[typeof MachineTypeId]["states"];
1440
+ export type States<M extends Any> = M[typeof MachineTypeId]["states"];
1606
1441
  /**
1607
1442
  * Extracts the complete event schema tuple carried by a machine definition.
1608
1443
  *
1609
1444
  * @category utility types
1610
1445
  * @since 0.4.0
1611
1446
  */
1612
- type Events<M extends Any> = M[typeof MachineTypeId]["events"];
1447
+ export type Events<M extends Any> = M[typeof MachineTypeId]["events"];
1613
1448
  /**
1614
1449
  * Extracts the startup input schema carried by a machine definition.
1615
1450
  *
1616
1451
  * @category utility types
1617
1452
  * @since 0.18.0
1618
1453
  */
1619
- type InputSchema<M extends Any> = M[typeof MachineTypeId]["input"];
1454
+ export type InputSchema<M extends Any> = M[typeof MachineTypeId]["input"];
1620
1455
  /**
1621
1456
  * Extracts the decoded startup input accepted by a machine definition.
1622
1457
  *
@@ -1626,102 +1461,102 @@ export declare namespace Machine {
1626
1461
  * @category utility types
1627
1462
  * @since 0.18.0
1628
1463
  */
1629
- type Input<M extends Any> = InputSchema<M> extends infer Input extends Schema.Top ? Input extends typeof Schema.Void ? never : Input["Type"] : never;
1464
+ export type Input<M extends Any> = InputSchema<M> extends infer Input extends Schema.Top ? Input extends typeof Schema.Void ? never : Input["Type"] : never;
1630
1465
  /**
1631
1466
  * Extracts state paths that do not yet have handlers.
1632
1467
  *
1633
1468
  * @category utility types
1634
1469
  * @since 0.4.0
1635
1470
  */
1636
- type UnhandledStates<M extends Any> = M[typeof MachineTypeId]["unhandledStates"];
1471
+ export type UnhandledStates<M extends Any> = M[typeof MachineTypeId]["unhandledStates"];
1637
1472
  /**
1638
1473
  * Extracts the runtime error channel carried by a machine definition.
1639
1474
  *
1640
1475
  * @category utility types
1641
1476
  * @since 0.4.0
1642
1477
  */
1643
- type Error<M extends Any> = M[typeof MachineTypeId]["error"];
1478
+ export type Error<M extends Any> = M[typeof MachineTypeId]["error"];
1644
1479
  /**
1645
1480
  * Extracts runtime service requirements carried by a machine definition.
1646
1481
  *
1647
1482
  * @category utility types
1648
1483
  * @since 0.4.0
1649
1484
  */
1650
- type Services<M extends Any> = M[typeof MachineTypeId]["services"];
1485
+ export type Services<M extends Any> = M[typeof MachineTypeId]["services"];
1651
1486
  /**
1652
1487
  * Extracts the startup error channel carried by a machine definition.
1653
1488
  *
1654
1489
  * @category utility types
1655
1490
  * @since 0.4.0
1656
1491
  */
1657
- type InitialError<M extends Any> = M[typeof MachineTypeId]["initialError"];
1492
+ export type InitialError<M extends Any> = M[typeof MachineTypeId]["initialError"];
1658
1493
  /**
1659
1494
  * Extracts startup service requirements carried by a machine definition.
1660
1495
  *
1661
1496
  * @category utility types
1662
1497
  * @since 0.4.0
1663
1498
  */
1664
- type InitialServices<M extends Any> = M[typeof MachineTypeId]["initialServices"];
1499
+ export type InitialServices<M extends Any> = M[typeof MachineTypeId]["initialServices"];
1665
1500
  /**
1666
1501
  * Extracts final state paths carried by a machine definition.
1667
1502
  *
1668
1503
  * @category utility types
1669
1504
  * @since 0.4.0
1670
1505
  */
1671
- type FinalStates<M extends Any> = M[typeof MachineTypeId]["finalStates"];
1506
+ export type FinalStates<M extends Any> = M[typeof MachineTypeId]["finalStates"];
1672
1507
  /**
1673
1508
  * Extracts the terminal output channel carried by a machine definition.
1674
1509
  *
1675
1510
  * @category utility types
1676
1511
  * @since 0.4.0
1677
1512
  */
1678
- type Output<M extends Any> = M[typeof MachineTypeId]["output"];
1513
+ export type Output<M extends Any> = M[typeof MachineTypeId]["output"];
1679
1514
  /**
1680
1515
  * Extracts the emitted event schema tuple carried by a machine definition.
1681
1516
  *
1682
1517
  * @category utility types
1683
1518
  * @since 0.4.0
1684
1519
  */
1685
- type EmittedEvents<M extends Any> = M[typeof MachineTypeId]["emittedEvents"];
1520
+ export type EmittedEvents<M extends Any> = M[typeof MachineTypeId]["emittedEvents"];
1686
1521
  /**
1687
1522
  * Extracts state paths with implemented output handlers.
1688
1523
  *
1689
1524
  * @category utility types
1690
1525
  * @since 0.4.0
1691
1526
  */
1692
- type OutputStates<M extends Any> = M[typeof MachineTypeId]["outputStates"];
1527
+ export type OutputStates<M extends Any> = M[typeof MachineTypeId]["outputStates"];
1693
1528
  /**
1694
1529
  * Extracts the public input event schema tuple carried by a machine definition.
1695
1530
  *
1696
1531
  * @category utility types
1697
1532
  * @since 0.4.0
1698
1533
  */
1699
- type InputEvents<M extends Any> = M[typeof MachineTypeId]["inputEvents"];
1534
+ export type InputEvents<M extends Any> = M[typeof MachineTypeId]["inputEvents"];
1700
1535
  /** Extracts the public input protocol required from an owning machine. */
1701
- type ParentEvents<M extends Any> = M[typeof MachineTypeId]["parentEvents"];
1536
+ export type ParentEvents<M extends Any> = M[typeof MachineTypeId]["parentEvents"];
1702
1537
  /** Extracts whether a machine requires or optionally accepts an owner. */
1703
- type ParentAvailability<M extends Any> = ParentModeOf<M[typeof MachineTypeId]["parentEvents"]>;
1538
+ export type ParentAvailability<M extends Any> = ParentModeOf<M[typeof MachineTypeId]["parentEvents"]>;
1704
1539
  /** Extracts an internal event schema tuple from the complete and public protocols. */
1705
- type InternalEventSchemas<Events extends ReadonlyArray<TaggedSchema>, InputEvents extends ReadonlyArray<TaggedSchema>> = Events extends readonly [
1540
+ export type InternalEventSchemas<Events extends ReadonlyArray<TaggedSchema>, InputEvents extends ReadonlyArray<TaggedSchema>> = Events extends readonly [
1706
1541
  ...InputEvents,
1707
1542
  ...infer Internal extends ReadonlyArray<TaggedSchema>
1708
1543
  ] ? readonly [...Internal] : readonly [];
1709
1544
  /** Extracts the internal event schema tuple carried by a machine definition. */
1710
- type InternalEvents<M extends Any> = InternalEventSchemas<Events<M>, InputEvents<M>>;
1545
+ export type InternalEvents<M extends Any> = InternalEventSchemas<Events<M>, InputEvents<M>>;
1711
1546
  /**
1712
1547
  * Extracts the complete event protocol handled inside a machine.
1713
1548
  *
1714
1549
  * @category utility types
1715
1550
  * @since 0.4.0
1716
1551
  */
1717
- type Event<M extends Any> = EventOf<Events<M>>;
1552
+ export type Event<M extends Any> = EventOf<Events<M>>;
1718
1553
  /**
1719
1554
  * Extracts the event protocol accepted by public machine input boundaries.
1720
1555
  *
1721
1556
  * @category utility types
1722
1557
  * @since 0.4.0
1723
1558
  */
1724
- type InputEvent<M extends Any> = EventOf<InputEvents<M>>;
1559
+ export type InputEvent<M extends Any> = EventOf<InputEvents<M>>;
1725
1560
  /**
1726
1561
  * Opaque event construction returned by {@link events} and
1727
1562
  * {@link internalEvents}.
@@ -1729,32 +1564,44 @@ export declare namespace Machine {
1729
1564
  * The machine resolves the instruction through its event schema when it is
1730
1565
  * delivered. Only the discriminator is available before decoding succeeds.
1731
1566
  */
1732
- interface EventConstruction<out Event extends {
1567
+ export interface EventConstruction<out Event extends {
1733
1568
  readonly _tag: PropertyKey;
1734
1569
  }> {
1735
1570
  readonly [EventConstructionTypeId]: Event;
1736
1571
  readonly _tag: Event["_tag"];
1737
1572
  }
1738
1573
  /** Opaque construction returned by {@link emittedEvents}. */
1739
- interface EmittedEventConstruction<out Event extends {
1574
+ export interface EmittedEventConstruction<out Event extends {
1740
1575
  readonly _tag: PropertyKey;
1741
1576
  }> {
1742
1577
  readonly [EmittedEventConstructionTypeId]: Event;
1743
1578
  readonly _tag: Event["_tag"];
1744
1579
  }
1745
1580
  /** A decoded event or a deferred machine-bound construction of that event. */
1746
- type EventInput<Event> = Event | (Event extends {
1581
+ export type EventInput<Event> = Event | (Event extends {
1747
1582
  readonly _tag: PropertyKey;
1748
1583
  } ? EventConstruction<Event> : never);
1749
1584
  /** A decoded emitted event or a deferred emitted-event construction. */
1750
- type EmittedEventInput<Event> = Event | (Event extends {
1585
+ export type EmittedEventInput<Event> = Event | (Event extends {
1751
1586
  readonly _tag: PropertyKey;
1752
1587
  } ? EmittedEventConstruction<Event> : never);
1753
1588
  /** Event inputs accepted for a schema tuple at machine delivery boundaries. */
1754
- type EventInputOf<Events extends ReadonlyArray<TaggedSchema>> = EventInput<EventOf<Events>>;
1589
+ export type EventInputOf<Events extends ReadonlyArray<TaggedSchema>> = EventInput<EventOf<Events>>;
1755
1590
  /** Identifies whether an event protocol is accepted publicly or only inside a machine. */
1756
- type EventProtocolKind = "public" | "internal" | "emitted";
1757
- type EventConstructorInput<EventSchema extends TaggedSchema> = Omit<EventSchema["~type.make.in"], "_tag">;
1591
+ export type EventProtocolKind = "public" | "internal" | "emitted";
1592
+ /**
1593
+ * Fields accepted by the constructor of one event in an event protocol.
1594
+ *
1595
+ * **Details**
1596
+ *
1597
+ * The input is the event schema's constructor input without `_tag`, which
1598
+ * the constructor supplies. When every field is optional, so is the
1599
+ * constructor's argument.
1600
+ *
1601
+ * @category utility types
1602
+ * @since 0.23.0
1603
+ */
1604
+ export type EventConstructorInput<EventSchema extends TaggedSchema> = Omit<EventSchema["~type.make.in"], "_tag">;
1758
1605
  type EventConstructor<EventSchema extends TaggedSchema, Tag extends EventSchema["Type"]["_tag"], Kind extends EventProtocolKind> = {} extends EventConstructorInput<EventSchema> ? (input?: EventConstructorInput<EventSchema>) => Kind extends "emitted" ? EmittedEventConstruction<EventByTag<readonly [EventSchema], Tag>> : EventConstruction<EventByTag<readonly [EventSchema], Tag>> : (input: EventConstructorInput<EventSchema>) => Kind extends "emitted" ? EmittedEventConstruction<EventByTag<readonly [EventSchema], Tag>> : EventConstruction<EventByTag<readonly [EventSchema], Tag>>;
1759
1606
  type FiniteEventTag<Tag extends PropertyKey> = string extends Tag ? never : number extends Tag ? never : symbol extends Tag ? never : Tag;
1760
1607
  type EventConstructorsForSchema<EventSchema extends TaggedSchema, Kind extends EventProtocolKind> = EventSchema extends {
@@ -1767,7 +1614,7 @@ export declare namespace Machine {
1767
1614
  readonly [Tag in FiniteEventTag<EventSchema["Type"]["_tag"]>]: EventConstructor<EventSchema, Tag, Kind>;
1768
1615
  };
1769
1616
  /** Protocol-bound constructors keyed by each configured event tag. */
1770
- type EventConstructors<Events extends ReadonlyArray<TaggedSchema>, Kind extends EventProtocolKind = "public"> = {
1617
+ export type EventConstructors<Events extends ReadonlyArray<TaggedSchema>, Kind extends EventProtocolKind = "public"> = {
1771
1618
  readonly [Tag in keyof Types.UnionToIntersection<EventConstructorsForSchema<Events[number], Kind>>]: Types.UnionToIntersection<EventConstructorsForSchema<Events[number], Kind>>[Tag];
1772
1619
  };
1773
1620
  /**
@@ -1778,13 +1625,13 @@ export declare namespace Machine {
1778
1625
  *
1779
1626
  * @since 0.10.0
1780
1627
  */
1781
- type EventProtocol<Kind extends EventProtocolKind, Schemas extends ReadonlyArray<TaggedSchema>> = EventConstructors<Schemas, Kind> & {
1628
+ export type EventProtocol<Kind extends EventProtocolKind, Schemas extends ReadonlyArray<TaggedSchema>> = EventConstructors<Schemas, Kind> & {
1782
1629
  readonly [EventProtocolTypeId]: {
1783
1630
  readonly kind: Kind;
1784
1631
  readonly schemas: Schemas;
1785
1632
  };
1786
1633
  };
1787
- namespace EventProtocol {
1634
+ export namespace EventProtocol {
1788
1635
  /** An erased event protocol descriptor retaining its kind and schema carrier. */
1789
1636
  interface Any<Kind extends EventProtocolKind = EventProtocolKind> {
1790
1637
  readonly [EventProtocolTypeId]: {
@@ -1793,23 +1640,23 @@ export declare namespace Machine {
1793
1640
  };
1794
1641
  }
1795
1642
  }
1796
- /** A schema or an existing protocol accepted by an event builder. */
1797
- type EventProtocolInput<Kind extends EventProtocolKind> = TaggedSchema | EventProtocol.Any<Kind>;
1643
+ /** A schema or an existing protocol accepted by `eventsFromSchemas` and its internal and emitted counterparts. */
1644
+ export type EventProtocolInput<Kind extends EventProtocolKind> = TaggedSchema | EventProtocol.Any<Kind>;
1798
1645
  type EventProtocolInputSchemas<Kind extends EventProtocolKind, Input extends EventProtocolInput<Kind>> = Input extends EventProtocol<Kind, infer Schemas> ? Schemas : Input extends TaggedSchema ? readonly [Input] : readonly [];
1799
1646
  /** Flattens schema and protocol inputs into one owned schema tuple. */
1800
- type EventProtocolInputSchemasOf<Kind extends EventProtocolKind, Inputs extends ReadonlyArray<EventProtocolInput<Kind>>> = Inputs extends readonly [
1647
+ export type EventProtocolInputSchemasOf<Kind extends EventProtocolKind, Inputs extends ReadonlyArray<EventProtocolInput<Kind>>> = Inputs extends readonly [
1801
1648
  infer Head extends EventProtocolInput<Kind>,
1802
1649
  ...infer Tail extends ReadonlyArray<EventProtocolInput<Kind>>
1803
1650
  ] ? readonly [...EventProtocolInputSchemas<Kind, Head>, ...EventProtocolInputSchemasOf<Kind, Tail>] : readonly [];
1804
1651
  /** @internal Extracts the schema tuple carried opaquely by an event protocol. */
1805
- type EventProtocolSchemas<Protocol extends EventProtocol.Any> = Protocol[typeof EventProtocolTypeId]["schemas"];
1652
+ export type EventProtocolSchemas<Protocol extends EventProtocol.Any> = Protocol[typeof EventProtocolTypeId]["schemas"];
1806
1653
  /**
1807
1654
  * Extracts the event protocol emitted by a machine.
1808
1655
  *
1809
1656
  * @category utility types
1810
1657
  * @since 0.4.0
1811
1658
  */
1812
- type EmittedEvent<M extends Any> = EmittedEventOf<EmittedEvents<M>>;
1659
+ export type EmittedEvent<M extends Any> = EmittedEventOf<EmittedEvents<M>>;
1813
1660
  /**
1814
1661
  * A schema whose decoded value contains a `_tag` discriminator.
1815
1662
  *
@@ -1820,7 +1667,7 @@ export declare namespace Machine {
1820
1667
  * @category models
1821
1668
  * @since 0.4.0
1822
1669
  */
1823
- type TaggedSchema = Schema.Top & {
1670
+ export type TaggedSchema = Schema.Top & {
1824
1671
  readonly Type: {
1825
1672
  readonly _tag: PropertyKey;
1826
1673
  };
@@ -1836,7 +1683,7 @@ export declare namespace Machine {
1836
1683
  * @category models
1837
1684
  * @since 0.4.0
1838
1685
  */
1839
- interface StateNodeAnnotations extends Schema.Annotations.Annotations {
1686
+ export interface StateNodeAnnotations extends Schema.Annotations.Annotations {
1840
1687
  /** Human-readable label used by visualization and documentation tooling. */
1841
1688
  readonly title?: string | undefined;
1842
1689
  /** Short explanation of the state node's domain meaning. */
@@ -1845,7 +1692,7 @@ export declare namespace Machine {
1845
1692
  readonly documentation?: string | undefined;
1846
1693
  }
1847
1694
  /** Descriptive annotations accepted by schema-less active and pseudo-states. */
1848
- type SchemaLessStateAnnotations = Pick<StateNodeAnnotations, "title" | "description" | "documentation">;
1695
+ export type SchemaLessStateAnnotations = Pick<StateNodeAnnotations, "title" | "description" | "documentation">;
1849
1696
  /**
1850
1697
  * Configuration accepted for an atomic object state node.
1851
1698
  *
@@ -1855,7 +1702,7 @@ export declare namespace Machine {
1855
1702
  * @category models
1856
1703
  * @since 0.4.0
1857
1704
  */
1858
- type AtomicStateNodeConfig = {
1705
+ export type AtomicStateNodeConfig = {
1859
1706
  /** Tagged schema that owns the state's decoded value. */
1860
1707
  readonly schema: TaggedSchema;
1861
1708
  /** Declares an ordinary active state. Omitted values default to `"active"`. */
@@ -1891,7 +1738,7 @@ export declare namespace Machine {
1891
1738
  * @category models
1892
1739
  * @since 0.4.0
1893
1740
  */
1894
- type CompoundStateNodeConfig = {
1741
+ export type CompoundStateNodeConfig = {
1895
1742
  /** Tagged schema that owns the compound state's decoded value. */
1896
1743
  readonly schema: TaggedSchema;
1897
1744
  /** Compound states are ordinary active states. */
@@ -1915,7 +1762,7 @@ export declare namespace Machine {
1915
1762
  * @category models
1916
1763
  * @since 0.4.0
1917
1764
  */
1918
- type ParallelStateNodeConfig = {
1765
+ export type ParallelStateNodeConfig = {
1919
1766
  /** Tagged schema that owns the parallel state's decoded value. */
1920
1767
  readonly schema: TaggedSchema;
1921
1768
  /** Selects parallel-region semantics for the node. */
@@ -1946,7 +1793,7 @@ export declare namespace Machine {
1946
1793
  * @category models
1947
1794
  * @since 0.4.0
1948
1795
  */
1949
- interface HistoryStateNodeConfig {
1796
+ export interface HistoryStateNodeConfig {
1950
1797
  /** Selects history pseudo-state semantics. */
1951
1798
  readonly type: "history";
1952
1799
  /**
@@ -1963,13 +1810,13 @@ export declare namespace Machine {
1963
1810
  * Transient decision pseudo-state resolved immediately when targeted.
1964
1811
  *
1965
1812
  * Choice nodes have no value and never belong to an active configuration.
1966
- * Their required `choice` implementation uses ordinary TypeScript or an
1967
- * Effect to select a typed target.
1813
+ * Their required `choice` transition selects a typed destination
1814
+ * synchronously.
1968
1815
  *
1969
1816
  * @category models
1970
1817
  * @since 0.4.0
1971
1818
  */
1972
- interface ChoiceStateNodeConfig {
1819
+ export interface ChoiceStateNodeConfig {
1973
1820
  /** Selects transient choice pseudo-state semantics. */
1974
1821
  readonly type: "choice";
1975
1822
  /** Descriptive metadata used by visualization and documentation tooling. */
@@ -1981,7 +1828,7 @@ export declare namespace Machine {
1981
1828
  * @category models
1982
1829
  * @since 0.4.0
1983
1830
  */
1984
- type StateNodeConfig = AtomicStateNodeConfig | CompoundStateNodeConfig | ParallelStateNodeConfig | HistoryStateNodeConfig | ChoiceStateNodeConfig;
1831
+ export type StateNodeConfig = AtomicStateNodeConfig | CompoundStateNodeConfig | ParallelStateNodeConfig | HistoryStateNodeConfig | ChoiceStateNodeConfig;
1985
1832
  /**
1986
1833
  * Object state tree keyed by state path.
1987
1834
  *
@@ -1991,30 +1838,15 @@ export declare namespace Machine {
1991
1838
  * @category models
1992
1839
  * @since 0.4.0
1993
1840
  */
1994
- type StateTree = Readonly<Record<string, TaggedSchema | StateNodeConfig>>;
1841
+ export type StateTree = Readonly<Record<string, TaggedSchema | StateNodeConfig>>;
1995
1842
  /**
1996
- * State schema definitions accepted by `make`.
1843
+ * State tree used as the topology parameter of machine types. A machine's
1844
+ * tree holds its root node under the `""` key.
1997
1845
  *
1998
1846
  * @category models
1999
1847
  * @since 0.4.0
2000
1848
  */
2001
- type StateSchemas = StateTree;
2002
- /**
2003
- * Builder for initial state snapshots generated by `states`.
2004
- *
2005
- * **When to use**
2006
- *
2007
- * Use when you need the type of the `initial` property returned by
2008
- * `states` or want to expose an initial snapshot builder from a helper.
2009
- *
2010
- * **Details**
2011
- *
2012
- * Initial builders enforce the declared initial child for compound states and
2013
- * require every direct region for parallel states.
2014
- *
2015
- * @category utility types
2016
- * @since 0.4.0
2017
- */
1849
+ export type StateSchemas = StateTree;
2018
1850
  /**
2019
1851
  * Typed snapshot access shared by state descriptors.
2020
1852
  *
@@ -2025,7 +1857,7 @@ export declare namespace Machine {
2025
1857
  * @category models
2026
1858
  * @since 0.4.0
2027
1859
  */
2028
- interface StateAccessors<States extends StateSchemas> {
1860
+ export interface StateAccessors<States extends StateSchemas> {
2029
1861
  /**
2030
1862
  * Checks and preserves one active state path from this definition.
2031
1863
  *
@@ -2089,9 +1921,9 @@ export declare namespace Machine {
2089
1921
  * @category utility types
2090
1922
  * @since 0.4.0
2091
1923
  */
2092
- type ValidateStateSchemas<States extends StateSchemas> = ValidateStateTree<States>;
1924
+ export type ValidateStateSchemas<States extends StateSchemas> = ValidateStateTree<States>;
2093
1925
  /** Properties shared by every compiled state-node variant. */
2094
- interface StateNodeBase<Path extends string = string> {
1926
+ export interface StateNodeBase<Path extends string = string> {
2095
1927
  readonly path: Path;
2096
1928
  readonly key: string;
2097
1929
  /** Resolved schema annotations, or descriptive schema-less-state annotations. */
@@ -2099,7 +1931,7 @@ export declare namespace Machine {
2099
1931
  readonly order: number;
2100
1932
  }
2101
1933
  /** Runtime metadata for a compiled atomic state. */
2102
- interface AtomicStateNode<OwnPath extends string = string, ActivePath extends string = OwnPath> extends StateNodeBase<OwnPath> {
1934
+ export interface AtomicStateNode<OwnPath extends string = string, ActivePath extends string = OwnPath> extends StateNodeBase<OwnPath> {
2103
1935
  readonly type: "atomic";
2104
1936
  readonly schema: TaggedSchema | undefined;
2105
1937
  readonly output: undefined;
@@ -2109,7 +1941,7 @@ export declare namespace Machine {
2109
1941
  readonly initial: undefined;
2110
1942
  }
2111
1943
  /** Runtime metadata for a compiled compound state. */
2112
- interface CompoundStateNode<OwnPath extends string = string, ActivePath extends string = OwnPath, ChoicePath extends string = ActivePath> extends StateNodeBase<OwnPath> {
1944
+ export interface CompoundStateNode<OwnPath extends string = string, ActivePath extends string = OwnPath, ChoicePath extends string = ActivePath> extends StateNodeBase<OwnPath> {
2113
1945
  readonly type: "compound";
2114
1946
  readonly schema: TaggedSchema | undefined;
2115
1947
  readonly output: undefined;
@@ -2120,7 +1952,7 @@ export declare namespace Machine {
2120
1952
  readonly initial: ActivePath | ChoicePath;
2121
1953
  }
2122
1954
  /** Runtime metadata for a compiled parallel state. */
2123
- interface ParallelStateNode<OwnPath extends string = string, ActivePath extends string = OwnPath> extends StateNodeBase<OwnPath> {
1955
+ export interface ParallelStateNode<OwnPath extends string = string, ActivePath extends string = OwnPath> extends StateNodeBase<OwnPath> {
2124
1956
  readonly type: "parallel";
2125
1957
  readonly schema: TaggedSchema | undefined;
2126
1958
  readonly output: Schema.Top | undefined;
@@ -2131,7 +1963,7 @@ export declare namespace Machine {
2131
1963
  readonly initial: undefined;
2132
1964
  }
2133
1965
  /** Runtime metadata for a compiled final state. */
2134
- interface FinalStateNode<OwnPath extends string = string, ActivePath extends string = OwnPath> extends StateNodeBase<OwnPath> {
1966
+ export interface FinalStateNode<OwnPath extends string = string, ActivePath extends string = OwnPath> extends StateNodeBase<OwnPath> {
2135
1967
  readonly type: "final";
2136
1968
  readonly schema: TaggedSchema | undefined;
2137
1969
  readonly output: Schema.Top | undefined;
@@ -2141,7 +1973,7 @@ export declare namespace Machine {
2141
1973
  readonly initial: undefined;
2142
1974
  }
2143
1975
  /** Runtime metadata for a compiled history pseudo-state. */
2144
- interface HistoryStateNode<OwnPath extends string = string, ActivePath extends string = string> extends StateNodeBase<OwnPath> {
1976
+ export interface HistoryStateNode<OwnPath extends string = string, ActivePath extends string = string> extends StateNodeBase<OwnPath> {
2145
1977
  readonly type: "history";
2146
1978
  readonly schema: undefined;
2147
1979
  readonly output: undefined;
@@ -2151,7 +1983,7 @@ export declare namespace Machine {
2151
1983
  readonly initial: undefined;
2152
1984
  }
2153
1985
  /** Runtime metadata for a compiled choice pseudo-state. */
2154
- interface ChoiceStateNode<OwnPath extends string = string, ActivePath extends string = string> extends StateNodeBase<OwnPath> {
1986
+ export interface ChoiceStateNode<OwnPath extends string = string, ActivePath extends string = string> extends StateNodeBase<OwnPath> {
2155
1987
  readonly type: "choice";
2156
1988
  readonly schema: undefined;
2157
1989
  readonly output: undefined;
@@ -2169,15 +2001,15 @@ export declare namespace Machine {
2169
2001
  * @category models
2170
2002
  * @since 0.4.0
2171
2003
  */
2172
- type ActiveStateNode<ActivePath extends string = string, ChoicePath extends string = ActivePath> = AtomicStateNode<ActivePath, ActivePath> | CompoundStateNode<ActivePath, ActivePath, ChoicePath> | ParallelStateNode<ActivePath, ActivePath> | FinalStateNode<ActivePath, ActivePath>;
2173
- type StateNode<ActivePath extends string = string, HistoryPath extends string = ActivePath, ChoicePath extends string = ActivePath> = ActiveStateNode<ActivePath, ChoicePath> | HistoryStateNode<HistoryPath, ActivePath> | ChoiceStateNode<ChoicePath, ActivePath>;
2004
+ export type ActiveStateNode<ActivePath extends string = string, ChoicePath extends string = ActivePath> = AtomicStateNode<ActivePath, ActivePath> | CompoundStateNode<ActivePath, ActivePath, ChoicePath> | ParallelStateNode<ActivePath, ActivePath> | FinalStateNode<ActivePath, ActivePath>;
2005
+ export type StateNode<ActivePath extends string = string, HistoryPath extends string = ActivePath, ChoicePath extends string = ActivePath> = ActiveStateNode<ActivePath, ChoicePath> | HistoryStateNode<HistoryPath, ActivePath> | ChoiceStateNode<ChoicePath, ActivePath>;
2174
2006
  /**
2175
2007
  * Runtime lookup table for state nodes.
2176
2008
  *
2177
2009
  * @category models
2178
2010
  * @since 0.4.0
2179
2011
  */
2180
- interface StateNodes<ActivePath extends string = string, HistoryPath extends string = ActivePath, ChoicePath extends string = ActivePath> {
2012
+ export interface StateNodes<ActivePath extends string = string, HistoryPath extends string = ActivePath, ChoicePath extends string = ActivePath> {
2181
2013
  readonly byPath: ReadonlyMap<ActivePath | HistoryPath | ChoicePath, StateNode<ActivePath, HistoryPath, ChoicePath>>;
2182
2014
  readonly roots: ReadonlyArray<ActivePath>;
2183
2015
  }
@@ -2187,7 +2019,7 @@ export declare namespace Machine {
2187
2019
  * @category models
2188
2020
  * @since 0.4.0
2189
2021
  */
2190
- type TransitionTrigger<EventTag extends PropertyKey = PropertyKey> = {
2022
+ export type TransitionTrigger<EventTag extends PropertyKey = PropertyKey> = {
2191
2023
  readonly type: "event";
2192
2024
  readonly event: EventTag;
2193
2025
  } | {
@@ -2201,30 +2033,40 @@ export declare namespace Machine {
2201
2033
  readonly id: string;
2202
2034
  readonly outcome: "element" | "done" | "failure" | "snapshot";
2203
2035
  };
2204
- /** Static topology selected by a transition branch. */
2205
- interface TransitionTargetSelection<Path extends string | undefined = string | undefined, Kind extends Topology.TargetSelectionKind = Topology.TargetSelectionKind, Scope extends Topology.TargetSelectionScope | undefined = Topology.TargetSelectionScope | undefined> {
2036
+ /**
2037
+ * Static topology selected by a transition branch.
2038
+ *
2039
+ * **Details**
2040
+ *
2041
+ * `kind` is `"state"` or `"choice"` for the path named by `target`,
2042
+ * `"history"` for `history`, `"state"` with the root path `""` for
2043
+ * `initialize`, and `"update"` for an `update` without a destination. A
2044
+ * `{ stay: true }` entry, or a transition with only `reenter: true`, has kind
2045
+ * `"none"` and no path. The machine's initial entry has kind `"initial"`.
2046
+ */
2047
+ export interface TransitionTargetSelection<Path extends string | undefined = string | undefined, Kind extends Topology.TargetSelectionKind = Topology.TargetSelectionKind, Scope extends Topology.TargetSelectionScope | undefined = Topology.TargetSelectionScope | undefined> {
2206
2048
  readonly path: Path;
2207
2049
  readonly kind: Kind;
2208
2050
  readonly scope: Scope;
2209
2051
  }
2210
2052
  /** One statically captured branch of a transition definition. */
2211
- type TransitionBranch<Path extends string = string> = {
2053
+ export type TransitionBranch<Path extends string = string> = {
2212
2054
  readonly type: "direct";
2213
2055
  readonly target: Path | undefined;
2214
2056
  readonly selection: TransitionTargetSelection<Path | undefined>;
2215
2057
  readonly updates: ReadonlyArray<string>;
2216
2058
  } | {
2217
2059
  readonly type: "branch";
2060
+ /** The entry as written: `target:Paid`, `target:Paid+update:root`, `update:root`, `history:X`, `initialize`, or `stay`. */
2218
2061
  readonly key: string;
2219
- readonly title: string;
2220
2062
  readonly target: Path | undefined;
2221
2063
  readonly selection: TransitionTargetSelection<Path | undefined>;
2222
2064
  readonly updates: ReadonlyArray<string>;
2223
2065
  };
2224
2066
  /** The statically selected root entry for machine startup. */
2225
- interface InitialDefinition<Path extends string = string> {
2067
+ export interface InitialDefinition<Path extends string = string> {
2226
2068
  readonly target: Path;
2227
- readonly selection: TransitionTargetSelection<Path, "state" | "initial", "initial">;
2069
+ readonly selection: TransitionTargetSelection<Path, "initial", "initial">;
2228
2070
  }
2229
2071
  /**
2230
2072
  * Inspectable registration for a transition handler.
@@ -2232,14 +2074,16 @@ export declare namespace Machine {
2232
2074
  * **Details**
2233
2075
  *
2234
2076
  * Every branch exposes its static selection without executing its resolver.
2235
- * A compound local or branch target covers its descendants. An `update`
2236
- * selection keeps `target` undefined and records its value owner in
2237
- * `selection.path`; `none` identifies an explicitly targetless branch.
2077
+ * Selecting a compound or parallel state also covers the descendants the
2078
+ * transition enters through it. An `update` selection keeps `target`
2079
+ * undefined and records its value owner in `selection.path`. A
2080
+ * `{ stay: true }` entry keeps `target` undefined and has
2081
+ * `selection.kind` `"none"`.
2238
2082
  *
2239
2083
  * @category models
2240
2084
  * @since 0.4.0
2241
2085
  */
2242
- interface TransitionDefinition<SourcePath extends string = string, EventTag extends PropertyKey = PropertyKey, TargetPath extends string = SourcePath> {
2086
+ export interface TransitionDefinition<SourcePath extends string = string, EventTag extends PropertyKey = PropertyKey, TargetPath extends string = SourcePath> {
2243
2087
  readonly source: SourcePath;
2244
2088
  readonly trigger: TransitionTrigger<EventTag>;
2245
2089
  readonly reenter: boolean;
@@ -2256,7 +2100,7 @@ export declare namespace Machine {
2256
2100
  * @category models
2257
2101
  * @since 0.4.0
2258
2102
  */
2259
- type ActivityDefinition<SourcePath extends string = string> = Activities.ActivityDefinition<SourcePath>;
2103
+ export type ActivityDefinition<SourcePath extends string = string> = Activities.ActivityDefinition<SourcePath>;
2260
2104
  /**
2261
2105
  * Transition retained after hierarchy precedence and conflict resolution for
2262
2106
  * one planned microstep.
@@ -2264,13 +2108,13 @@ export declare namespace Machine {
2264
2108
  * @category models
2265
2109
  * @since 0.4.0
2266
2110
  */
2267
- interface RetainedTransition<SourcePath extends string = string, EventTag extends PropertyKey = PropertyKey, TargetPath extends string = SourcePath> {
2111
+ export interface RetainedTransition<SourcePath extends string = string, EventTag extends PropertyKey = PropertyKey, TargetPath extends string = SourcePath> {
2268
2112
  readonly source: SourcePath;
2269
2113
  readonly trigger: TransitionTrigger<EventTag>;
2270
2114
  readonly reenter: boolean;
2271
2115
  /** Zero-based index of the selected static branch. */
2272
2116
  readonly branchIndex: number;
2273
- /** Stable key of a named branch, or `undefined` for a direct transition. */
2117
+ /** The selected `branches` entry as written, such as `target:Paid`, or `undefined` for a direct transition. */
2274
2118
  readonly branchKey: string | undefined;
2275
2119
  /** Path returned by the handler, including a choice or history pseudo-state. */
2276
2120
  readonly target: TargetPath | undefined;
@@ -2283,26 +2127,27 @@ export declare namespace Machine {
2283
2127
  readonly updates: ReadonlyArray<string>;
2284
2128
  }
2285
2129
  /**
2286
- * Constructor arguments for a machine initial state function.
2130
+ * Startup arguments: the decoded input when the machine declares an input
2131
+ * schema, and none otherwise.
2287
2132
  *
2288
2133
  * @category utility types
2289
2134
  * @since 0.4.0
2290
2135
  */
2291
- type InputArgs<Input extends Schema.Top> = Input extends typeof Schema.Void ? [] : [input: Input["Type"]];
2136
+ export type InputArgs<Input extends Schema.Top> = Input extends typeof Schema.Void ? [] : [input: Input["Type"]];
2292
2137
  /**
2293
2138
  * Extracts the discriminator value represented by a tagged schema.
2294
2139
  *
2295
2140
  * @category utility types
2296
2141
  * @since 0.4.0
2297
2142
  */
2298
- type TagOf<S extends TaggedSchema> = S["Type"]["_tag"];
2143
+ export type TagOf<S extends TaggedSchema> = S["Type"]["_tag"];
2299
2144
  /**
2300
2145
  * Extracts the schema from a state tree node definition.
2301
2146
  *
2302
2147
  * @category utility types
2303
2148
  * @since 0.4.0
2304
2149
  */
2305
- type NodeSchema<Node> = Node extends TaggedSchema ? Node : Node extends {
2150
+ export type NodeSchema<Node> = Node extends TaggedSchema ? Node : Node extends {
2306
2151
  readonly schema: infer Schema extends TaggedSchema;
2307
2152
  } ? Schema : never;
2308
2153
  /**
@@ -2311,18 +2156,18 @@ export declare namespace Machine {
2311
2156
  * @category utility types
2312
2157
  * @since 0.4.0
2313
2158
  */
2314
- type JoinPath<Parent extends string, Child extends string> = Parent extends "" ? Child : `${Parent}.${Child}`;
2159
+ export type JoinPath<Parent extends string, Child extends string> = Parent extends "" ? Child : `${Parent}.${Child}`;
2315
2160
  /**
2316
2161
  * Extracts the state path values represented by a state definition.
2317
2162
  *
2318
2163
  * @category utility types
2319
2164
  * @since 0.4.0
2320
2165
  */
2321
- type StateIdentifier<States extends StateSchemas> = StateIdentifierWithPrefix<States>;
2166
+ export type StateIdentifier<States extends StateSchemas> = StateIdentifierWithPrefix<States>;
2322
2167
  /** Extracts active state paths whose definitions declare a state value schema. */
2323
- type ValuedStateIdentifier<States extends StateSchemas> = StateIdentifier<States> extends infer StateId ? StateId extends StateIdentifier<States> ? NodeSchema<NodeByIdentifier<States, StateId>> extends never ? never : StateId : never : never;
2168
+ export type ValuedStateIdentifier<States extends StateSchemas> = StateIdentifier<States> extends infer StateId ? StateId extends StateIdentifier<States> ? NodeSchema<NodeByIdentifier<States, StateId>> extends never ? never : StateId : never : never;
2324
2169
  /** Extracts active state paths whose definitions intentionally omit a state value schema. */
2325
- type StructuralStateIdentifier<States extends StateSchemas> = Exclude<StateIdentifier<States>, ValuedStateIdentifier<States>>;
2170
+ export type StructuralStateIdentifier<States extends StateSchemas> = Exclude<StateIdentifier<States>, ValuedStateIdentifier<States>>;
2326
2171
  /**
2327
2172
  * Extracts the state path values represented by a state definition under a
2328
2173
  * parent path prefix.
@@ -2330,7 +2175,7 @@ export declare namespace Machine {
2330
2175
  * @category utility types
2331
2176
  * @since 0.4.0
2332
2177
  */
2333
- type StateIdentifierWithPrefix<States extends StateSchemas, Prefix extends string = ""> = {
2178
+ export type StateIdentifierWithPrefix<States extends StateSchemas, Prefix extends string = ""> = {
2334
2179
  readonly [Key in Extract<keyof States, string>]: States[Key] extends HistoryStateNodeConfig | ChoiceStateNodeConfig ? never : States[Key] extends {
2335
2180
  readonly states: infer Children;
2336
2181
  } ? Children extends StateSchemas ? JoinPath<Prefix, Key> | StateIdentifierWithPrefix<Children, JoinPath<Prefix, Key>> : JoinPath<Prefix, Key> : JoinPath<Prefix, Key>;
@@ -2341,38 +2186,38 @@ export declare namespace Machine {
2341
2186
  * @category utility types
2342
2187
  * @since 0.4.0
2343
2188
  */
2344
- type HistoryIdentifier<States extends StateSchemas> = HistoryIdentifierWithPrefix<States>;
2189
+ export type HistoryIdentifier<States extends StateSchemas> = HistoryIdentifierWithPrefix<States>;
2345
2190
  /** Extracts the transition-only choice pseudo-state paths. */
2346
- type ChoiceIdentifier<States extends StateSchemas> = ChoiceIdentifierWithPrefix<States>;
2191
+ export type ChoiceIdentifier<States extends StateSchemas> = ChoiceIdentifierWithPrefix<States>;
2347
2192
  /**
2348
2193
  * Extracts every compiled state-node path, including history pseudo-states.
2349
2194
  *
2350
2195
  * @category utility types
2351
2196
  * @since 0.4.0
2352
2197
  */
2353
- type StateNodeIdentifier<States extends StateSchemas> = StateIdentifier<States> | HistoryIdentifier<States> | ChoiceIdentifier<States>;
2198
+ export type StateNodeIdentifier<States extends StateSchemas> = StateIdentifier<States> | HistoryIdentifier<States> | ChoiceIdentifier<States>;
2354
2199
  /** @internal */
2355
- type HistoryIdentifierWithPrefix<States extends StateSchemas, Prefix extends string = ""> = {
2200
+ export type HistoryIdentifierWithPrefix<States extends StateSchemas, Prefix extends string = ""> = {
2356
2201
  readonly [Key in Extract<keyof States, string>]: States[Key] extends HistoryStateNodeConfig ? JoinPath<Prefix, Key> : States[Key] extends {
2357
2202
  readonly states: infer Children extends StateSchemas;
2358
2203
  } ? HistoryIdentifierWithPrefix<Children, JoinPath<Prefix, Key>> : never;
2359
2204
  }[Extract<keyof States, string>];
2360
2205
  /** @internal */
2361
- type ChoiceIdentifierWithPrefix<States extends StateSchemas, Prefix extends string = ""> = {
2206
+ export type ChoiceIdentifierWithPrefix<States extends StateSchemas, Prefix extends string = ""> = {
2362
2207
  readonly [Key in Extract<keyof States, string>]: States[Key] extends ChoiceStateNodeConfig ? JoinPath<Prefix, Key> : States[Key] extends {
2363
2208
  readonly states: infer Children extends StateSchemas;
2364
2209
  } ? ChoiceIdentifierWithPrefix<Children, JoinPath<Prefix, Key>> : never;
2365
2210
  }[Extract<keyof States, string>];
2366
2211
  /** Active keys directly declared in a state tree. */
2367
- type ActiveStateKey<States extends StateSchemas> = {
2212
+ export type ActiveStateKey<States extends StateSchemas> = {
2368
2213
  readonly [Key in Extract<keyof States, string>]: States[Key] extends HistoryStateNodeConfig | ChoiceStateNodeConfig ? never : Key;
2369
2214
  }[Extract<keyof States, string>];
2370
2215
  /** History pseudo-state keys directly declared in a state tree. */
2371
- type HistoryStateKey<States extends StateSchemas> = {
2216
+ export type HistoryStateKey<States extends StateSchemas> = {
2372
2217
  readonly [Key in Extract<keyof States, string>]: States[Key] extends HistoryStateNodeConfig ? Key : never;
2373
2218
  }[Extract<keyof States, string>];
2374
2219
  /** Choice pseudo-state keys directly declared in a state tree. */
2375
- type ChoiceStateKey<States extends StateSchemas> = {
2220
+ export type ChoiceStateKey<States extends StateSchemas> = {
2376
2221
  readonly [Key in Extract<keyof States, string>]: States[Key] extends ChoiceStateNodeConfig ? Key : never;
2377
2222
  }[Extract<keyof States, string>];
2378
2223
  /**
@@ -2382,27 +2227,27 @@ export declare namespace Machine {
2382
2227
  * @category utility types
2383
2228
  * @since 0.4.0
2384
2229
  */
2385
- type RequiredHistoryInitializers<States extends StateSchemas> = [HistoryIdentifier<States>] extends [never] ? never : Extract<RequiredHistoryInitializersWithPrefix<States, States, "">, StateIdentifier<States>>;
2230
+ export type RequiredHistoryInitializers<States extends StateSchemas> = [HistoryIdentifier<States>] extends [never] ? never : Extract<RequiredHistoryInitializersWithPrefix<States, States, "">, StateIdentifier<States>>;
2386
2231
  /** Active parent states that own one or more history pseudo-states. */
2387
- type HistoryParentIdentifier<States extends StateSchemas> = HistoryIdentifier<States> extends infer HistoryId ? HistoryId extends string ? Extract<ImmediateParentStateIdentifier<HistoryId>, StateIdentifier<States>> : never : never;
2232
+ export type HistoryParentIdentifier<States extends StateSchemas> = HistoryIdentifier<States> extends infer HistoryId ? HistoryId extends string ? Extract<ImmediateParentStateIdentifier<HistoryId>, StateIdentifier<States>> : never : never;
2388
2233
  /** Active parent states that own one or more choice pseudo-states. */
2389
- type ChoiceParentIdentifier<States extends StateSchemas> = ChoiceIdentifier<States> extends infer ChoiceId ? ChoiceId extends string ? Extract<ImmediateParentStateIdentifier<ChoiceId>, StateIdentifier<States>> : never : never;
2234
+ export type ChoiceParentIdentifier<States extends StateSchemas> = ChoiceIdentifier<States> extends infer ChoiceId ? ChoiceId extends string ? Extract<ImmediateParentStateIdentifier<ChoiceId>, StateIdentifier<States>> : never : never;
2390
2235
  /** History defaults and implicit initializers that remain unimplemented. */
2391
- type MissingHistoryImplementations<States extends StateSchemas, UnhandledStates extends StateIdentifier<States>> = Extract<UnhandledStates, HistoryParentIdentifier<States> | RequiredHistoryInitializers<States>>;
2236
+ export type MissingHistoryImplementations<States extends StateSchemas, UnhandledStates extends StateIdentifier<States>> = Extract<UnhandledStates, HistoryParentIdentifier<States> | RequiredHistoryInitializers<States>>;
2392
2237
  /** Choice-owning active parents that remain unimplemented. */
2393
- type MissingChoiceImplementations<States extends StateSchemas, UnhandledStates extends StateIdentifier<States>> = Extract<UnhandledStates, ChoiceParentIdentifier<States>>;
2238
+ export type MissingChoiceImplementations<States extends StateSchemas, UnhandledStates extends StateIdentifier<States>> = Extract<UnhandledStates, ChoiceParentIdentifier<States>>;
2394
2239
  /** @internal Readiness proof for required choice resolvers. */
2395
- type EnsureChoiceImplementations<States extends StateSchemas, UnhandledStates extends StateIdentifier<States>> = IsAny<States> extends true ? unknown : [ChoiceIdentifier<States>] extends [never] ? unknown : [MissingChoiceImplementations<States, UnhandledStates>] extends [never] ? unknown : {
2240
+ export type EnsureChoiceImplementations<States extends StateSchemas, UnhandledStates extends StateIdentifier<States>> = IsAny<States> extends true ? unknown : [ChoiceIdentifier<States>] extends [never] ? unknown : [MissingChoiceImplementations<States, UnhandledStates>] extends [never] ? unknown : {
2396
2241
  readonly "~effect/Machine/MissingChoiceImplementation": MissingChoiceImplementations<States, UnhandledStates>;
2397
2242
  };
2398
2243
  /** @internal Readiness proof required by planning and managed execution. */
2399
- type EnsureHistoryImplementations<States extends StateSchemas, UnhandledStates extends StateIdentifier<States>> = IsAny<States> extends true ? unknown : ([HistoryIdentifier<States>] extends [never] ? unknown : [MissingHistoryImplementations<States, UnhandledStates>] extends [never] ? unknown : {
2244
+ export type EnsureHistoryImplementations<States extends StateSchemas, UnhandledStates extends StateIdentifier<States>> = IsAny<States> extends true ? unknown : ([HistoryIdentifier<States>] extends [never] ? unknown : [MissingHistoryImplementations<States, UnhandledStates>] extends [never] ? unknown : {
2400
2245
  readonly "~effect/Machine/MissingHistoryImplementation": MissingHistoryImplementations<States, UnhandledStates>;
2401
2246
  }) & EnsureChoiceImplementations<States, UnhandledStates>;
2402
2247
  /** Owners that require a handler-owned initial edge or region data. */
2403
- type RequiredInitializers<States extends StateSchemas> = string extends keyof States ? never : "" extends keyof States ? InitializerClosureForNode<States, States[""], ""> : never;
2248
+ export type RequiredInitializers<States extends StateSchemas> = string extends keyof States ? never : "" extends keyof States ? InitializerClosureForNode<States, States[""], ""> : never;
2404
2249
  /** Proof that initialization can construct every required default value. */
2405
- type EnsureInitialImplementations<States extends StateSchemas, UnhandledStates extends StateIdentifier<States>> = [UnhandledStates] extends [never] ? unknown : [Extract<RequiredInitializers<States>, UnhandledStates>] extends [never] ? unknown : {
2250
+ export type EnsureInitialImplementations<States extends StateSchemas, UnhandledStates extends StateIdentifier<States>> = [UnhandledStates] extends [never] ? unknown : [Extract<RequiredInitializers<States>, UnhandledStates>] extends [never] ? unknown : {
2406
2251
  readonly "~effect/Machine/MissingInitialImplementation": Extract<RequiredInitializers<States>, UnhandledStates>;
2407
2252
  };
2408
2253
  /**
@@ -2411,7 +2256,7 @@ export declare namespace Machine {
2411
2256
  * @category utility types
2412
2257
  * @since 0.4.0
2413
2258
  */
2414
- type NodeByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = string extends keyof States ? NodeByNamedIdentifier<States, StateId> : "" extends keyof States ? StateId extends "" ? States[""] : States[""] extends {
2259
+ export type NodeByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = string extends keyof States ? NodeByNamedIdentifier<States, StateId> : "" extends keyof States ? StateId extends "" ? States[""] : States[""] extends {
2415
2260
  readonly states: infer Children extends StateSchemas;
2416
2261
  } ? NodeByIdentifier<Children, Extract<StateId, StateIdentifier<Children>>> : never : NodeByNamedIdentifier<States, StateId>;
2417
2262
  type NodeByNamedIdentifier<States extends StateSchemas, StateId extends string> = StateId extends `${infer Head}.${infer Rest}` ? Head extends keyof States ? States[Head] extends {
@@ -2423,21 +2268,21 @@ export declare namespace Machine {
2423
2268
  * @category utility types
2424
2269
  * @since 0.4.0
2425
2270
  */
2426
- type SchemaByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeSchema<NodeByIdentifier<States, StateId>>;
2271
+ export type SchemaByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeSchema<NodeByIdentifier<States, StateId>>;
2427
2272
  /**
2428
2273
  * Extracts the union of state values represented by a state definition.
2429
2274
  *
2430
2275
  * @category utility types
2431
2276
  * @since 0.4.0
2432
2277
  */
2433
- type StateOf<States extends StateSchemas> = StateIdentifier<States> extends infer StateId ? StateId extends StateIdentifier<States> ? SchemaByIdentifier<States, StateId>["Type"] : never : never;
2278
+ export type StateOf<States extends StateSchemas> = StateIdentifier<States> extends infer StateId ? StateId extends StateIdentifier<States> ? SchemaByIdentifier<States, StateId>["Type"] : never : never;
2434
2279
  /**
2435
2280
  * Extracts the union of event values represented by an event schema list.
2436
2281
  *
2437
2282
  * @category utility types
2438
2283
  * @since 0.4.0
2439
2284
  */
2440
- type EventOf<Events extends ReadonlyArray<TaggedSchema>> = Events[number]["Type"];
2285
+ export type EventOf<Events extends ReadonlyArray<TaggedSchema>> = Events[number]["Type"];
2441
2286
  /**
2442
2287
  * Extracts the union of emitted event values represented by an emitted event
2443
2288
  * schema list.
@@ -2445,28 +2290,28 @@ export declare namespace Machine {
2445
2290
  * @category utility types
2446
2291
  * @since 0.4.0
2447
2292
  */
2448
- type EmittedEventOf<Emits extends ReadonlyArray<TaggedSchema>> = Emits[number]["Type"];
2293
+ export type EmittedEventOf<Emits extends ReadonlyArray<TaggedSchema>> = Emits[number]["Type"];
2449
2294
  /**
2450
2295
  * Event values received by lifecycle callbacks.
2451
2296
  *
2452
2297
  * @category utility types
2453
2298
  * @since 0.4.0
2454
2299
  */
2455
- type LifecycleEvent<Events extends ReadonlyArray<TaggedSchema>> = EventOf<Events> | InitialEvent;
2300
+ export type LifecycleEvent<Events extends ReadonlyArray<TaggedSchema>> = EventOf<Events> | InitialEvent;
2456
2301
  /**
2457
2302
  * Extracts a state value from a state definition by identifier.
2458
2303
  *
2459
2304
  * @category utility types
2460
2305
  * @since 0.4.0
2461
2306
  */
2462
- type StateByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = StateId extends ValuedStateIdentifier<States> ? SchemaByIdentifier<States, StateId>["Type"] : undefined;
2307
+ export type StateByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = StateId extends ValuedStateIdentifier<States> ? SchemaByIdentifier<States, StateId>["Type"] : undefined;
2463
2308
  /**
2464
2309
  * Extracts every parent state path from a state identifier.
2465
2310
  *
2466
2311
  * @category utility types
2467
2312
  * @since 0.4.0
2468
2313
  */
2469
- type ParentStateIdentifier<StateId extends string> = StateId extends "" ? never : "" | NamedParentStateIdentifier<StateId>;
2314
+ export type ParentStateIdentifier<StateId extends string> = StateId extends "" ? never : "" | NamedParentStateIdentifier<StateId>;
2470
2315
  type NamedParentStateIdentifier<StateId extends string> = StateId extends `${infer Parent}.${infer Child}` ? Parent | (Child extends `${string}.${string}` ? `${Parent}.${NamedParentStateIdentifier<Child>}` : never) : never;
2471
2316
  /**
2472
2317
  * Extracts the nearest parent state path from a state identifier.
@@ -2474,14 +2319,14 @@ export declare namespace Machine {
2474
2319
  * @category utility types
2475
2320
  * @since 0.4.0
2476
2321
  */
2477
- type ImmediateParentStateIdentifier<StateId extends string> = StateId extends `${infer Head}.${infer Tail}` ? Tail extends `${string}.${string}` ? `${Head}.${ImmediateParentStateIdentifier<Tail>}` : Head : StateId extends "" ? never : "";
2322
+ export type ImmediateParentStateIdentifier<StateId extends string> = StateId extends `${infer Head}.${infer Tail}` ? Tail extends `${string}.${string}` ? `${Head}.${ImmediateParentStateIdentifier<Tail>}` : Head : StateId extends "" ? never : "";
2478
2323
  /**
2479
2324
  * Maps every parent state path of a state identifier to its decoded value.
2480
2325
  *
2481
2326
  * @category utility types
2482
2327
  * @since 0.4.0
2483
2328
  */
2484
- type ParentStateValues<States extends StateSchemas, StateId extends StateIdentifier<States>> = StateId extends StateIdentifier<States> ? {
2329
+ export type ParentStateValues<States extends StateSchemas, StateId extends StateIdentifier<States>> = StateId extends StateIdentifier<States> ? {
2485
2330
  readonly [Parent in Extract<ParentStateIdentifier<StateId>, ValuedStateIdentifier<States>>]: StateByIdentifier<States, Parent>;
2486
2331
  } : never;
2487
2332
  /**
@@ -2490,14 +2335,14 @@ export declare namespace Machine {
2490
2335
  * @category utility types
2491
2336
  * @since 0.4.0
2492
2337
  */
2493
- type ParentStateValue<States extends StateSchemas, StateId extends StateIdentifier<States>> = StateId extends StateIdentifier<States> ? Extract<ImmediateParentStateIdentifier<StateId>, StateIdentifier<States>> extends infer Parent ? [Parent] extends [never] ? undefined : Parent extends ValuedStateIdentifier<States> ? StateByIdentifier<States, Parent> : undefined : undefined : never;
2338
+ export type ParentStateValue<States extends StateSchemas, StateId extends StateIdentifier<States>> = StateId extends StateIdentifier<States> ? Extract<ImmediateParentStateIdentifier<StateId>, StateIdentifier<States>> extends infer Parent ? [Parent] extends [never] ? undefined : Parent extends ValuedStateIdentifier<States> ? StateByIdentifier<States, Parent> : undefined : undefined : never;
2494
2339
  /**
2495
2340
  * Represents a decoded state value together with all of its parent values.
2496
2341
  *
2497
2342
  * @category models
2498
2343
  * @since 0.4.0
2499
2344
  */
2500
- type StateWithParents<States extends StateSchemas, StateId extends StateIdentifier<States>> = StateId extends StateIdentifier<States> ? {
2345
+ export type StateWithParents<States extends StateSchemas, StateId extends StateIdentifier<States>> = StateId extends StateIdentifier<States> ? {
2501
2346
  readonly value: StateByIdentifier<States, StateId>;
2502
2347
  readonly parents: ParentStateValues<States, StateId>;
2503
2348
  } : never;
@@ -2511,7 +2356,7 @@ export declare namespace Machine {
2511
2356
  * @category utility types
2512
2357
  * @since 0.4.0
2513
2358
  */
2514
- type OutputByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeOutput<NodeByIdentifier<States, StateId>>;
2359
+ export type OutputByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeOutput<NodeByIdentifier<States, StateId>>;
2515
2360
  type DirectFinalCompletionOutput<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends {
2516
2361
  readonly type: "final";
2517
2362
  } ? OutputByIdentifier<States, StateId> : never;
@@ -2525,7 +2370,7 @@ export declare namespace Machine {
2525
2370
  * @category utility types
2526
2371
  * @since 0.4.0
2527
2372
  */
2528
- type CompletionOutputByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends infer Node ? Node extends {
2373
+ export type CompletionOutputByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends infer Node ? Node extends {
2529
2374
  readonly type: "parallel";
2530
2375
  } ? OutputByIdentifier<States, StateId> : Node extends {
2531
2376
  readonly states: infer Children extends StateSchemas;
@@ -2548,7 +2393,7 @@ export declare namespace Machine {
2548
2393
  * @category utility types
2549
2394
  * @since 0.4.0
2550
2395
  */
2551
- type TerminalOutput<States extends StateSchemas> = {
2396
+ export type TerminalOutput<States extends StateSchemas> = {
2552
2397
  readonly [Key in Extract<keyof States, string>]: Extract<Key, StateIdentifier<States>> extends infer StateId extends StateIdentifier<States> ? NodeByIdentifier<States, StateId> extends infer Node ? Node extends {
2553
2398
  readonly type: "parallel" | "final";
2554
2399
  } ? OutputByIdentifier<States, StateId> : Node extends {
@@ -2561,7 +2406,7 @@ export declare namespace Machine {
2561
2406
  * @category utility types
2562
2407
  * @since 0.4.0
2563
2408
  */
2564
- type DeclaredOutputState<States extends StateSchemas> = {
2409
+ export type DeclaredOutputState<States extends StateSchemas> = {
2565
2410
  readonly [StateId in StateIdentifier<States>]: NodeByIdentifier<States, StateId> extends {
2566
2411
  readonly output: Schema.Top;
2567
2412
  } ? StateId : never;
@@ -2573,7 +2418,7 @@ export declare namespace Machine {
2573
2418
  * @category utility types
2574
2419
  * @since 0.4.0
2575
2420
  */
2576
- type EnsureOutputImplementations<States extends StateSchemas, OutputStates extends StateIdentifier<States>> = [
2421
+ export type EnsureOutputImplementations<States extends StateSchemas, OutputStates extends StateIdentifier<States>> = [
2577
2422
  Exclude<DeclaredOutputState<States>, OutputStates>
2578
2423
  ] extends [never] ? unknown : {
2579
2424
  readonly "~effect/Machine/MissingOutputImplementation": Exclude<DeclaredOutputState<States>, OutputStates>;
@@ -2590,7 +2435,7 @@ export declare namespace Machine {
2590
2435
  * @category utility types
2591
2436
  * @since 0.4.0
2592
2437
  */
2593
- type SnapshotDecodingServices<States extends StateSchemas> = StateIdentifier<States> extends infer StateId ? StateId extends StateIdentifier<States> ? DecodingServices<SchemaByIdentifier<States, StateId>> | DecodingServices<OutputSchema<NodeByIdentifier<States, StateId>>> : never : never;
2438
+ export type SnapshotDecodingServices<States extends StateSchemas> = StateIdentifier<States> extends infer StateId ? StateId extends StateIdentifier<States> ? DecodingServices<SchemaByIdentifier<States, StateId>> | DecodingServices<OutputSchema<NodeByIdentifier<States, StateId>>> : never : never;
2594
2439
  /**
2595
2440
  * Services required to encode every state value and completion output in a
2596
2441
  * machine snapshot.
@@ -2598,14 +2443,14 @@ export declare namespace Machine {
2598
2443
  * @category utility types
2599
2444
  * @since 0.4.0
2600
2445
  */
2601
- type SnapshotEncodingServices<States extends StateSchemas> = StateIdentifier<States> extends infer StateId ? StateId extends StateIdentifier<States> ? EncodingServices<SchemaByIdentifier<States, StateId>> | EncodingServices<OutputSchema<NodeByIdentifier<States, StateId>>> : never : never;
2446
+ export type SnapshotEncodingServices<States extends StateSchemas> = StateIdentifier<States> extends infer StateId ? StateId extends StateIdentifier<States> ? EncodingServices<SchemaByIdentifier<States, StateId>> | EncodingServices<OutputSchema<NodeByIdentifier<States, StateId>>> : never : never;
2602
2447
  /**
2603
2448
  * Encoded value for one active state path in a normalized machine snapshot.
2604
2449
  *
2605
2450
  * @category models
2606
2451
  * @since 0.4.0
2607
2452
  */
2608
- interface EncodedSnapshotState {
2453
+ export interface EncodedSnapshotState {
2609
2454
  readonly path: string;
2610
2455
  readonly value?: Schema.Json;
2611
2456
  }
@@ -2618,12 +2463,12 @@ export declare namespace Machine {
2618
2463
  * @category models
2619
2464
  * @since 0.4.0
2620
2465
  */
2621
- interface EncodedSnapshotCompletion {
2466
+ export interface EncodedSnapshotCompletion {
2622
2467
  readonly path: string;
2623
2468
  readonly output?: Schema.Json;
2624
2469
  }
2625
2470
  /** Encoded values and paths retained by one history pseudo-state. */
2626
- interface EncodedSnapshotHistoryEntry {
2471
+ export interface EncodedSnapshotHistoryEntry {
2627
2472
  readonly mode: "shallow" | "deep";
2628
2473
  readonly active: ReadonlyArray<string>;
2629
2474
  readonly values: Readonly<Record<string, Schema.Json>>;
@@ -2641,7 +2486,7 @@ export declare namespace Machine {
2641
2486
  * @category models
2642
2487
  * @since 0.4.0
2643
2488
  */
2644
- interface EncodedSnapshot {
2489
+ export interface EncodedSnapshot {
2645
2490
  readonly version: 2;
2646
2491
  readonly _tag: "MachineSnapshot";
2647
2492
  readonly active: ReadonlyArray<EncodedSnapshotState>;
@@ -2654,12 +2499,12 @@ export declare namespace Machine {
2654
2499
  * @category models
2655
2500
  * @since 0.4.0
2656
2501
  */
2657
- interface SnapshotCompletion {
2502
+ export interface SnapshotCompletion {
2658
2503
  readonly path: string;
2659
2504
  readonly output: unknown;
2660
2505
  }
2661
2506
  /** Decoded values and paths retained by one history pseudo-state. */
2662
- interface SnapshotHistoryEntry {
2507
+ export interface SnapshotHistoryEntry {
2663
2508
  readonly mode: "shallow" | "deep";
2664
2509
  readonly active: ReadonlyArray<string>;
2665
2510
  readonly values: Readonly<Record<string, unknown>>;
@@ -2680,7 +2525,7 @@ export declare namespace Machine {
2680
2525
  * @category models
2681
2526
  * @since 0.4.0
2682
2527
  */
2683
- interface SnapshotMetadata {
2528
+ export interface SnapshotMetadata {
2684
2529
  readonly completed?: ReadonlyArray<SnapshotCompletion>;
2685
2530
  readonly history?: Readonly<Record<string, SnapshotHistoryEntry>>;
2686
2531
  }
@@ -2691,7 +2536,7 @@ export declare namespace Machine {
2691
2536
  * @category models
2692
2537
  * @since 0.4.0
2693
2538
  */
2694
- interface AtomicSnapshot<Path extends string, Value> extends SnapshotMetadata {
2539
+ export interface AtomicSnapshot<Path extends string, Value> extends SnapshotMetadata {
2695
2540
  readonly path: Path;
2696
2541
  readonly value: Value;
2697
2542
  }
@@ -2702,7 +2547,7 @@ export declare namespace Machine {
2702
2547
  * @category models
2703
2548
  * @since 0.4.0
2704
2549
  */
2705
- interface CompoundSnapshot<Path extends string, Value, Child> extends SnapshotMetadata {
2550
+ export interface CompoundSnapshot<Path extends string, Value, Child> extends SnapshotMetadata {
2706
2551
  readonly path: Path;
2707
2552
  readonly value: Value;
2708
2553
  readonly state: Child;
@@ -2714,7 +2559,7 @@ export declare namespace Machine {
2714
2559
  * @category models
2715
2560
  * @since 0.4.0
2716
2561
  */
2717
- interface ParallelSnapshot<Path extends string, Value, Regions> extends SnapshotMetadata {
2562
+ export interface ParallelSnapshot<Path extends string, Value, Regions> extends SnapshotMetadata {
2718
2563
  readonly path: Path;
2719
2564
  readonly value: Value;
2720
2565
  readonly states: Regions;
@@ -2726,7 +2571,7 @@ export declare namespace Machine {
2726
2571
  * @category utility types
2727
2572
  * @since 0.4.0
2728
2573
  */
2729
- type SnapshotByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends infer Node ? Node extends {
2574
+ export type SnapshotByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends infer Node ? Node extends {
2730
2575
  readonly type: "parallel";
2731
2576
  readonly states: infer Children;
2732
2577
  } ? Children extends StateSchemas ? ParallelSnapshot<StateId, StateByIdentifier<States, StateId>, SnapshotRegionsWithPrefix<Children, StateId>> : AtomicSnapshot<StateId, StateByIdentifier<States, StateId>> : Node extends {
@@ -2738,7 +2583,7 @@ export declare namespace Machine {
2738
2583
  * @category utility types
2739
2584
  * @since 0.4.0
2740
2585
  */
2741
- type SnapshotWithPrefix<States extends StateSchemas, Prefix extends string> = {
2586
+ export type SnapshotWithPrefix<States extends StateSchemas, Prefix extends string> = {
2742
2587
  readonly [Key in ActiveStateKey<States>]: SnapshotByIdentifierWithPath<States, Key, JoinPath<Prefix, Key>>;
2743
2588
  }[ActiveStateKey<States>];
2744
2589
  /**
@@ -2748,7 +2593,7 @@ export declare namespace Machine {
2748
2593
  * @category utility types
2749
2594
  * @since 0.4.0
2750
2595
  */
2751
- type SnapshotRegionsWithPrefix<States extends StateSchemas, Prefix extends string> = {
2596
+ export type SnapshotRegionsWithPrefix<States extends StateSchemas, Prefix extends string> = {
2752
2597
  readonly [Key in ActiveStateKey<States>]: SnapshotByIdentifierWithPath<States, Key, JoinPath<Prefix, Key>>;
2753
2598
  };
2754
2599
  /**
@@ -2757,7 +2602,7 @@ export declare namespace Machine {
2757
2602
  * @category utility types
2758
2603
  * @since 0.4.0
2759
2604
  */
2760
- type SnapshotByIdentifierWithPath<States extends StateSchemas, StateId extends ActiveStateKey<States>, Path extends string> = States[StateId] extends {
2605
+ export type SnapshotByIdentifierWithPath<States extends StateSchemas, StateId extends ActiveStateKey<States>, Path extends string> = States[StateId] extends {
2761
2606
  readonly type: "parallel";
2762
2607
  readonly states: infer Children;
2763
2608
  } ? Children extends StateSchemas ? ParallelSnapshot<Path, NodeValue<States[StateId]>, SnapshotRegionsWithPrefix<Children, Path>> : AtomicSnapshot<Path, NodeValue<States[StateId]>> : States[StateId] extends {
@@ -2773,7 +2618,7 @@ export declare namespace Machine {
2773
2618
  * @category utility types
2774
2619
  * @since 0.4.0
2775
2620
  */
2776
- type CompleteSnapshotContaining<States extends StateSchemas, Owner extends StateIdentifier<States>> = HistorySnapshotWithPrefix<States, Owner, "">;
2621
+ export type CompleteSnapshotContaining<States extends StateSchemas, Owner extends StateIdentifier<States>> = HistorySnapshotWithPrefix<States, Owner, "">;
2777
2622
  /**
2778
2623
  * Extracts the union of statechart snapshots represented by a state
2779
2624
  * definition.
@@ -2781,7 +2626,7 @@ export declare namespace Machine {
2781
2626
  * @category models
2782
2627
  * @since 0.4.0
2783
2628
  */
2784
- type Snapshot<States extends StateSchemas> = {
2629
+ export type Snapshot<States extends StateSchemas> = {
2785
2630
  readonly [StateId in ActiveStateKey<States>]: SnapshotByIdentifier<States, StateId & StateIdentifier<States>>;
2786
2631
  }[ActiveStateKey<States>];
2787
2632
  /**
@@ -2790,21 +2635,21 @@ export declare namespace Machine {
2790
2635
  * @category utility types
2791
2636
  * @since 0.4.0
2792
2637
  */
2793
- type RootStateIdentifier<StateId extends string> = StateId extends string ? "" : never;
2638
+ export type RootStateIdentifier<StateId extends string> = StateId extends string ? "" : never;
2794
2639
  /**
2795
2640
  * Extracts the public snapshot shape that contains a final state path.
2796
2641
  *
2797
2642
  * @category utility types
2798
2643
  * @since 0.4.0
2799
2644
  */
2800
- type SnapshotContainingFinal<States extends StateSchemas, FinalStates extends StateIdentifier<States>> = FinalStates extends StateIdentifier<States> ? RootStateIdentifier<FinalStates> extends infer Root extends StateIdentifier<States> ? SnapshotByIdentifier<States, Root> : never : never;
2645
+ export type SnapshotContainingFinal<States extends StateSchemas, FinalStates extends StateIdentifier<States>> = FinalStates extends StateIdentifier<States> ? RootStateIdentifier<FinalStates> extends infer Root extends StateIdentifier<States> ? SnapshotByIdentifier<States, Root> : never : never;
2801
2646
  /**
2802
2647
  * Extracts state identifiers whose state-tree definition marks them final.
2803
2648
  *
2804
2649
  * @category utility types
2805
2650
  * @since 0.4.0
2806
2651
  */
2807
- type FinalStateFromDefinition<States extends StateSchemas> = {
2652
+ export type FinalStateFromDefinition<States extends StateSchemas> = {
2808
2653
  readonly [StateId in StateIdentifier<States>]: NodeByIdentifier<States, StateId> extends {
2809
2654
  readonly type: "final";
2810
2655
  } ? StateId : never;
@@ -2815,7 +2660,7 @@ export declare namespace Machine {
2815
2660
  * @category utility types
2816
2661
  * @since 0.4.0
2817
2662
  */
2818
- type EventByTag<Events extends ReadonlyArray<TaggedSchema>, Tag extends TagOf<Events[number]>> = Extract<EventOf<Events>, {
2663
+ export type EventByTag<Events extends ReadonlyArray<TaggedSchema>, Tag extends TagOf<Events[number]>> = Extract<EventOf<Events>, {
2819
2664
  readonly _tag: Tag;
2820
2665
  }> | (EventOf<Events> extends infer Event ? Event extends {
2821
2666
  readonly _tag: infer EventTag extends PropertyKey;
@@ -2823,7 +2668,7 @@ export declare namespace Machine {
2823
2668
  readonly _tag: Tag;
2824
2669
  } : never : never : never);
2825
2670
  /**
2826
- * Opaque state construction returned by a builder's `.from` method.
2671
+ * Opaque state construction returned by a history default's `target`.
2827
2672
  *
2828
2673
  * The machine resolves the instruction through the selected state schema
2829
2674
  * while planning. Its decoded value is intentionally unavailable until
@@ -2832,8 +2677,8 @@ export declare namespace Machine {
2832
2677
  * @category models
2833
2678
  * @since 0.4.0
2834
2679
  */
2835
- interface StateConstruction<out Result> {
2836
- readonly [Topology.StateConstructionTypeId]: Result;
2680
+ export interface StateConstruction<out Result> {
2681
+ readonly [StateConstructionTypeId]: Result;
2837
2682
  }
2838
2683
  /**
2839
2684
  * Machine-bound target instruction accepted from transition handlers.
@@ -2841,9 +2686,9 @@ export declare namespace Machine {
2841
2686
  * @category models
2842
2687
  * @since 0.4.0
2843
2688
  */
2844
- interface Target<States extends StateSchemas, StateId extends StateIdentifier<States>> {
2689
+ export interface Target<States extends StateSchemas, StateId extends StateIdentifier<States>> {
2845
2690
  readonly [Topology.TargetTypeId]: typeof Topology.TargetTypeId;
2846
- readonly [Topology.TargetSnapshotTypeId]?: SnapshotByIdentifier<States, StateId>;
2691
+ readonly [TargetSnapshotTypeId]?: SnapshotByIdentifier<States, StateId>;
2847
2692
  readonly path: StateId;
2848
2693
  readonly value: StateByIdentifier<States, StateId>;
2849
2694
  readonly values?: Partial<{
@@ -2857,8 +2702,8 @@ export declare namespace Machine {
2857
2702
  * @category models
2858
2703
  * @since 0.21.0
2859
2704
  */
2860
- interface StateUpdate<States extends StateSchemas, StateId extends ValuedStateIdentifier<States>> {
2861
- readonly [Topology.StateUpdateTypeId]: {
2705
+ export interface StateUpdate<States extends StateSchemas, StateId extends ValuedStateIdentifier<States>> {
2706
+ readonly [StateUpdateTypeId]: {
2862
2707
  readonly states: Types.Covariant<States>;
2863
2708
  readonly owner: Types.Covariant<StateId>;
2864
2709
  };
@@ -2870,18 +2715,13 @@ export declare namespace Machine {
2870
2715
  * @category models
2871
2716
  * @since 0.22.0
2872
2717
  */
2873
- interface CombinedTarget<Result, States extends StateSchemas, Owner extends ValuedStateIdentifier<States>> {
2874
- readonly [Topology.CombinedTargetTypeId]: {
2718
+ export interface CombinedTarget<Result, States extends StateSchemas, Owner extends ValuedStateIdentifier<States>> {
2719
+ readonly [CombinedTargetTypeId]: {
2875
2720
  readonly result: Types.Covariant<Result>;
2876
2721
  readonly states: Types.Covariant<States>;
2877
2722
  readonly owner: Types.Covariant<Owner>;
2878
2723
  };
2879
2724
  }
2880
- /** @internal */
2881
- type StateUpdateBuilder<States extends StateSchemas, StateId extends ValuedStateIdentifier<States>> = {
2882
- readonly decoded: (value: StateByIdentifier<States, StateId>) => StateUpdate<States, StateId>;
2883
- readonly from: FromCallable<readonly [input: SchemaByIdentifier<States, StateId>["~type.make.in"]], StateUpdate<States, StateId>>;
2884
- };
2885
2725
  /**
2886
2726
  * Opaque result returned by an explicitly targetless transition.
2887
2727
  *
@@ -2891,12 +2731,12 @@ export declare namespace Machine {
2891
2731
  * @category models
2892
2732
  * @since 0.10.0
2893
2733
  */
2894
- interface NoTarget {
2895
- readonly [Topology.NoTargetTypeId]: typeof Topology.NoTargetTypeId;
2734
+ export interface NoTarget {
2735
+ readonly [NoTargetTypeId]: typeof NoTargetTypeId;
2896
2736
  }
2897
2737
  /**
2898
- * Opaque result returned when a declinable transition does not accept the
2899
- * current event or lifecycle outcome.
2738
+ * Opaque result of `select.decline()`, when a transition does not accept the
2739
+ * current event.
2900
2740
  *
2901
2741
  * Declining selects no transition and discards operations enqueued by that
2902
2742
  * resolver. Hierarchical event and eventless dispatch continues with the
@@ -2905,11 +2745,15 @@ export declare namespace Machine {
2905
2745
  * @category models
2906
2746
  * @since 0.17.0
2907
2747
  */
2908
- interface Declined {
2909
- readonly [Topology.DeclinedTypeId]: typeof Topology.DeclinedTypeId;
2748
+ export interface Declined {
2749
+ readonly [DeclinedTypeId]: typeof DeclinedTypeId;
2910
2750
  }
2911
- /** Static acceptance contract of one transition definition. */
2912
- type TransitionAcceptance = "required" | "declinable";
2751
+ /**
2752
+ * Static acceptance contract of one transition definition: `"declinable"`
2753
+ * when it has a `guard` or lists `{ decline: true }` in `branches`, so it may
2754
+ * leave the event to the next candidate, and `"required"` otherwise.
2755
+ */
2756
+ export type TransitionAcceptance = "required" | "declinable";
2913
2757
  /**
2914
2758
  * Transition instruction that restores a history pseudo-state's parent.
2915
2759
  *
@@ -2920,8 +2764,8 @@ export declare namespace Machine {
2920
2764
  * @category models
2921
2765
  * @since 0.4.0
2922
2766
  */
2923
- interface HistoryTarget<States extends StateSchemas, HistoryId extends HistoryIdentifier<States>> {
2924
- readonly [Topology.HistoryTargetTypeId]: typeof Topology.HistoryTargetTypeId;
2767
+ export interface HistoryTarget<States extends StateSchemas, HistoryId extends HistoryIdentifier<States>> {
2768
+ readonly [HistoryTargetTypeId]: typeof HistoryTargetTypeId;
2925
2769
  readonly path: HistoryId;
2926
2770
  readonly parent: Extract<ParentPath<HistoryId>, StateIdentifier<States>>;
2927
2771
  }
@@ -2932,159 +2776,41 @@ export declare namespace Machine {
2932
2776
  * @category models
2933
2777
  * @since 0.13.0
2934
2778
  */
2935
- interface InitialTarget<StateId extends string> {
2779
+ export interface InitialTarget<StateId extends string> {
2936
2780
  readonly [Topology.TargetTypeId]: typeof Topology.TargetTypeId;
2937
- readonly [Topology.TargetSnapshotTypeId]?: never;
2938
- readonly [Topology.InitialTargetTypeId]: typeof Topology.InitialTargetTypeId;
2781
+ readonly [TargetSnapshotTypeId]?: never;
2782
+ readonly [InitialTargetTypeId]: typeof InitialTargetTypeId;
2939
2783
  readonly _tag: "InitialTarget";
2940
2784
  readonly path: StateId;
2941
2785
  readonly value: never;
2942
2786
  readonly values?: never;
2943
2787
  }
2944
- /** Branded transient target instruction used while constructing initial states. */
2945
- interface ChoiceTargetInstruction<ChoiceId extends string = string> {
2946
- readonly [Topology.ChoiceTargetTypeId]: typeof Topology.ChoiceTargetTypeId;
2788
+ /** Branded instruction that enters a choice pseudo-state, before its parent is checked against a machine. */
2789
+ export interface ChoiceTargetInstruction<ChoiceId extends string = string> {
2790
+ readonly [ChoiceTargetTypeId]: typeof ChoiceTargetTypeId;
2947
2791
  readonly path: ChoiceId;
2948
2792
  readonly parent: ParentPath<ChoiceId>;
2949
2793
  readonly values?: Readonly<Record<string, unknown>>;
2950
2794
  }
2951
2795
  /** Transition instruction that enters a transient choice pseudo-state. */
2952
- interface ChoiceTarget<States extends StateSchemas, ChoiceId extends ChoiceIdentifier<States>> extends ChoiceTargetInstruction<ChoiceId> {
2796
+ export interface ChoiceTarget<States extends StateSchemas, ChoiceId extends ChoiceIdentifier<States>> extends ChoiceTargetInstruction<ChoiceId> {
2953
2797
  readonly parent: Extract<ParentPath<ChoiceId>, StateIdentifier<States>>;
2954
2798
  }
2955
- /** Builder containing only history pseudo-state paths. */
2956
- type HistoryTargetBuilder<States extends StateSchemas> = HistoryTargetBuilderWithPrefix<States, States, "">;
2957
- /**
2958
- * Builder for complete transition snapshots.
2959
- *
2960
- * **When to use**
2961
- *
2962
- * Use when a transition enters an inactive root or otherwise needs to provide
2963
- * every active child below the selected root.
2964
- *
2965
- * @category utility types
2966
- * @since 0.4.0
2967
- */
2968
- type FullTargetBuilder<States extends StateSchemas> = [InitialEntryStateKey<States>] extends [never] ? FullSnapshotBuilderWithPrefix<States> : FullSnapshotBuilderWithPrefix<States> & FullInitialTargetBuilder<States>;
2969
2799
  /**
2970
- * Builder for a complete fallback configuration containing a history owner.
2800
+ * Function that constructs a complete fallback configuration containing a
2801
+ * history owner, supplied as `target` to a history default.
2971
2802
  *
2972
2803
  * @category utility types
2973
2804
  * @since 0.4.0
2974
2805
  */
2975
- type HistoryDefaultTargetBuilder<States extends StateSchemas, Owner extends StateIdentifier<States>> = (construction: HistoryConstruction<States[""], Owner>) => StateConstruction<CompleteSnapshotContaining<States, Owner>>;
2976
- /**
2977
- * Builder for source-local transition targets.
2978
- *
2979
- * **When to use**
2980
- *
2981
- * Use when a transition stays inside the nearest active compound ancestor of
2982
- * the source state and should preserve active ancestor and sibling values.
2983
- *
2984
- * @category utility types
2985
- * @since 0.4.0
2986
- */
2987
- type LocalTargetBuilder<States extends StateSchemas, Source extends StateNodeIdentifier<States>> = NearestCompoundScope<States, Source> extends infer Scope ? [Scope] extends [never] ? {} : Scope extends StateIdentifier<States> ? LocalTargetBuilderForScope<States, Scope, Source> : {} : {};
2988
- /**
2989
- * Builder for partial transition targets within the active source root.
2990
- *
2991
- * **When to use**
2992
- *
2993
- * Use when a transition should replace one descendant of the active source
2994
- * root while preserving unmentioned active ancestors or parallel regions.
2995
- *
2996
- * @category utility types
2997
- * @since 0.4.0
2998
- */
2999
- type BranchTargetBuilder<States extends StateSchemas, Source extends StateNodeIdentifier<States>> = BranchTargetBuilderForRoot<States, Extract<"" extends keyof States ? "" : RootStateIdentifier<Source>, ActiveStateKey<States>>, Source>;
3000
- /**
3001
- * Machine-bound target builders available in transition contexts.
3002
- *
3003
- * **Details**
3004
- *
3005
- * `none()` handles without selecting a destination, `local` targets the
3006
- * nearest compound scope for the source state, `branch` targets descendants
3007
- * of the source root, and `full` builds complete snapshots for any root.
3008
- *
3009
- * These builders control how the next active configuration is assembled; they
3010
- * do not directly control state re-entry. Exit and entry paths are derived
3011
- * from the previous and next active paths. Shared active ancestors remain
3012
- * entered even when a `full` target supplies their values again. Use an event
3013
- * transition with `reenter: true` when the source should explicitly exit and
3014
- * enter again.
3015
- *
3016
- * @category models
3017
- * @since 0.4.0
3018
- */
3019
- interface TargetBuilder<in out States extends StateSchemas, in out Source extends StateNodeIdentifier<States>> {
3020
- /**
3021
- * Selects an explicitly targetless transition.
3022
- *
3023
- * The event or lifecycle outcome is handled and queued operations are
3024
- * retained, while the current state configuration remains the transition
3025
- * result.
3026
- *
3027
- * @since 0.10.0
3028
- */
3029
- readonly none: () => NoTarget;
3030
- /**
3031
- * Moves to another state in the same local group. The value of the state
3032
- * containing that group, and values in other active branches, are kept.
3033
- *
3034
- * @since 0.4.0
3035
- */
3036
- readonly local: LocalTargetBuilder<States, Source>;
3037
- /**
3038
- * Moves to a state elsewhere under the current top-level state. Parent
3039
- * values change only when their builder methods are explicitly called;
3040
- * other active branches are kept.
3041
- *
3042
- * @since 0.4.0
3043
- */
3044
- readonly branch: BranchTargetBuilder<States, Source>;
3045
- /**
3046
- * Moves to any top-level state by building its complete active state
3047
- * configuration.
3048
- *
3049
- * **Details**
3050
- *
3051
- * When the target contains nested states, an active child must be selected.
3052
- * When it contains parallel states, an active state must be provided for
3053
- * every region.
3054
- *
3055
- * @since 0.4.0
3056
- */
3057
- readonly full: FullTargetBuilder<States>;
3058
- /** Restores a declared shallow or deep history pseudo-state. */
3059
- readonly history: HistoryTargetBuilder<States>;
3060
- }
3061
- /**
3062
- * Opaque exact destination selected while a machine definition is captured.
3063
- * The selection contains topology only; state values are constructed later
3064
- * by the selected branch's resolver.
3065
- *
3066
- * @category models
3067
- * @since 0.14.0
3068
- */
3069
- interface TargetSelection<out Result, out Path extends string | undefined = string | undefined, out Kind extends Topology.TargetSelectionKind = Topology.TargetSelectionKind, out Scope extends Topology.TargetSelectionScope | undefined = Topology.TargetSelectionScope | undefined> {
3070
- readonly [Topology.TargetSelectionTypeId]: typeof Topology.TargetSelectionTypeId;
3071
- readonly kind: Kind;
3072
- readonly scope: Scope;
3073
- readonly path: Path;
3074
- readonly "~effect/Machine/TargetSelectionResult"?: Types.Covariant<Result>;
3075
- }
3076
- type SelectionValue<Builder, Path extends string, Kind extends Topology.TargetSelectionKind = "state", Scope extends Topology.TargetSelectionScope | undefined = Topology.TargetSelectionScope | undefined> = TargetSelection<Builder, Path, Kind, Scope>;
3077
- type SelectionMethod<Builder, Path extends string, Kind extends Topology.TargetSelectionKind = "state", Scope extends Topology.TargetSelectionScope | undefined = Topology.TargetSelectionScope | undefined> = () => SelectionValue<Builder, Path, Kind, Scope>;
3078
- type RootBuilder<Builder> = Builder extends {
3079
- readonly "": infer Root;
3080
- } ? Root : never;
2806
+ export type HistoryDefaultTargetBuilder<States extends StateSchemas, Owner extends StateIdentifier<States>> = (construction: HistoryConstruction<States[""], Owner>) => StateConstruction<CompleteSnapshotContaining<States, Owner>>;
3081
2807
  /**
3082
2808
  * Context passed to a state/event handler.
3083
2809
  *
3084
2810
  * @category models
3085
2811
  * @since 0.4.0
3086
2812
  */
3087
- type HandlerContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, EventTag extends TagOf<Events[number]>, E, R, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
2813
+ export type HandlerContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, EventTag extends TagOf<Events[number]>, E, R, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
3088
2814
  /** Value owned by the state whose handler is running. */
3089
2815
  readonly state: StateByIdentifier<States, StateId>;
3090
2816
  /** Value owned by the nearest schema-backed ancestor, when one exists. */
@@ -3104,7 +2830,7 @@ export declare namespace Machine {
3104
2830
  * @category models
3105
2831
  * @since 0.4.0
3106
2832
  */
3107
- type StateActionContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
2833
+ export type StateActionContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
3108
2834
  /** Value owned by the state entering or exiting. */
3109
2835
  readonly state: StateByIdentifier<States, StateId>;
3110
2836
  /** Value owned by the nearest schema-backed ancestor, when one exists. */
@@ -3120,7 +2846,7 @@ export declare namespace Machine {
3120
2846
  * @category models
3121
2847
  * @since 0.4.0
3122
2848
  */
3123
- type InvokeContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
2849
+ export type InvokeContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
3124
2850
  /** Process-owned child operations for dynamic child machine lifecycles. */
3125
2851
  readonly children: ChildOwner<EventOf<InputEvents>>;
3126
2852
  /** Value owned by the state that owns this invocation. */
@@ -3140,7 +2866,7 @@ export declare namespace Machine {
3140
2866
  * @category models
3141
2867
  * @since 0.4.0
3142
2868
  */
3143
- type InvokeSnapshotContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, State, Error, Output, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
2869
+ export type InvokeSnapshotContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, State, Error, Output, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
3144
2870
  /** Parent-local invocation identifier. */
3145
2871
  readonly id: string;
3146
2872
  /** Current value of the state that owns the invocation. */
@@ -3162,7 +2888,7 @@ export declare namespace Machine {
3162
2888
  * @category models
3163
2889
  * @since 0.4.0
3164
2890
  */
3165
- type InvokeDoneContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, Output, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
2891
+ export type InvokeDoneContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, Output, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
3166
2892
  /** Parent-local invocation identifier. */
3167
2893
  readonly id: string;
3168
2894
  /** Current value of the state that owns the invocation. */
@@ -3179,7 +2905,7 @@ export declare namespace Machine {
3179
2905
  readonly output: Output;
3180
2906
  };
3181
2907
  /** Context passed to a Stream invocation's element transition. */
3182
- type InvokeElementContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, Element, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
2908
+ export type InvokeElementContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, Element, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
3183
2909
  /** Parent-local invocation identifier. */
3184
2910
  readonly id: string;
3185
2911
  /** Current value of the state that owns the Stream invocation. */
@@ -3196,7 +2922,7 @@ export declare namespace Machine {
3196
2922
  readonly element: Element;
3197
2923
  };
3198
2924
  /** Context passed to an invocation typed-failure transition. */
3199
- type InvokeFailureContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, Error, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
2925
+ export type InvokeFailureContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, Error, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
3200
2926
  /** Parent-local invocation identifier. */
3201
2927
  readonly id: string;
3202
2928
  /** Current value of the state that owns the invocation. */
@@ -3218,7 +2944,7 @@ export declare namespace Machine {
3218
2944
  * @category models
3219
2945
  * @since 0.4.0
3220
2946
  */
3221
- type AlwaysContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
2947
+ export type AlwaysContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
3222
2948
  /** Current value of the state evaluating the eventless transition. */
3223
2949
  readonly state: StateByIdentifier<States, StateId>;
3224
2950
  /** Value owned by the nearest schema-backed ancestor, when one exists. */
@@ -3238,7 +2964,7 @@ export declare namespace Machine {
3238
2964
  * @category models
3239
2965
  * @since 0.4.0
3240
2966
  */
3241
- type DoneContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
2967
+ export type DoneContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
3242
2968
  /** Current value of the state whose child configuration completed. */
3243
2969
  readonly state: StateByIdentifier<States, StateId>;
3244
2970
  /** Value owned by the nearest schema-backed ancestor, when one exists. */
@@ -3255,7 +2981,7 @@ export declare namespace Machine {
3255
2981
  readonly root: StateByIdentifier<States, Extract<"", StateIdentifier<States>>>;
3256
2982
  };
3257
2983
  /** Context passed to a transient choice resolver. There is no `state` value. */
3258
- type ChoiceContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, ChoiceId extends ChoiceIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
2984
+ export type ChoiceContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, ChoiceId extends ChoiceIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = MachineReferences<InputEvents, ParentEvents> & {
3259
2985
  /** Value owned by the choice node's immediate schema-backed parent. */
3260
2986
  readonly containingState: StateByIdentifier<States, Extract<ImmediateParentStateIdentifier<ChoiceId>, StateIdentifier<States>>>;
3261
2987
  /** Schema-backed ancestor values keyed by their complete state paths. */
@@ -3273,7 +2999,7 @@ export declare namespace Machine {
3273
2999
  * @category models
3274
3000
  * @since 0.4.0
3275
3001
  */
3276
- interface FinalOutputContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> {
3002
+ export interface FinalOutputContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> {
3277
3003
  /** Decoded value owned by the final state. */
3278
3004
  readonly state: StateByIdentifier<States, StateId>;
3279
3005
  /** Value owned by the nearest schema-backed ancestor, when one exists. */
@@ -3289,7 +3015,7 @@ export declare namespace Machine {
3289
3015
  * @category utility types
3290
3016
  * @since 0.4.0
3291
3017
  */
3292
- type ParallelOutputRegions<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends {
3018
+ export type ParallelOutputRegions<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends {
3293
3019
  readonly type: "parallel";
3294
3020
  readonly states: infer Children extends StateSchemas;
3295
3021
  } ? {
@@ -3301,7 +3027,7 @@ export declare namespace Machine {
3301
3027
  * @category models
3302
3028
  * @since 0.4.0
3303
3029
  */
3304
- interface ParallelOutputContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> {
3030
+ export interface ParallelOutputContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> {
3305
3031
  /** Decoded value owned by the completed parallel state. */
3306
3032
  readonly state: StateByIdentifier<States, StateId>;
3307
3033
  /** Value owned by the nearest schema-backed ancestor, when one exists. */
@@ -3319,68 +3045,37 @@ export declare namespace Machine {
3319
3045
  * @category utility types
3320
3046
  * @since 0.4.0
3321
3047
  */
3322
- type StateActionResult<E, R> = undefined;
3048
+ export type StateActionResult<E, R> = undefined;
3323
3049
  /**
3324
- * Return value accepted from a machine initial state function.
3050
+ * Initial target that a machine resolves at startup.
3325
3051
  *
3326
3052
  * @category utility types
3327
3053
  * @since 0.4.0
3328
3054
  */
3329
- type InitialResult<States extends StateSchemas, E, R> = InitialTarget<StateIdentifier<States>>;
3055
+ export type InitialResult<States extends StateSchemas, E, R> = InitialTarget<StateIdentifier<States>>;
3330
3056
  /**
3331
- * Return value accepted from transition handlers.
3057
+ * Result that a transition declaration resolves to.
3332
3058
  *
3333
3059
  * **Details**
3334
3060
  *
3335
- * Handlers return snapshots for complete state replacement, target builder
3336
- * results for path-safe partial transitions, state-value updates, or
3337
- * an explicit targetless result. In a machine definition, select `{ none: true }`;
3338
- * its optional resolver returns `undefined`. Raw decoded state values are
3339
- * not accepted as transition targets.
3340
- *
3341
- * @category utility types
3342
- * @since 0.4.0
3343
- */
3344
- type HandlerResult<States extends StateSchemas, E, R> = Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>> | StateUpdate<States, ValuedStateIdentifier<States>> | CombinedTarget<Target<States, StateIdentifier<States>> | Snapshot<States> | ChoiceTarget<States, ChoiceIdentifier<States>>, States, ValuedStateIdentifier<States>> | StateConstruction<Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>> | StateUpdate<States, ValuedStateIdentifier<States>>> | NoTarget;
3345
- /** A choice resolver must always select a typed target synchronously. */
3346
- type ChoiceResult<States extends StateSchemas, E, R> = Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>> | StateConstruction<Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>>>;
3347
- /**
3348
- * Extracts the union of handler return values from a handler map.
3349
- *
3350
- * @category utility types
3351
- * @since 0.4.0
3352
- */
3353
- type HandlerEffect<Handlers> = Handlers[keyof Handlers];
3354
- /**
3355
- * Extracts the error type from a handler return value.
3356
- *
3357
- * @category utility types
3358
- * @since 0.4.0
3359
- */
3360
- type HandlerError<Handlers> = Effect.Error<HandlerEffect<Handlers>>;
3361
- /**
3362
- * Extracts the service requirements from a handler return value.
3363
- *
3364
- * @category utility types
3365
- * @since 0.4.0
3366
- */
3367
- type HandlerServices<Handlers> = Effect.Services<HandlerEffect<Handlers>>;
3368
- /**
3369
- * Extracts the return value from an initial state function.
3061
+ * A transition resolves to a complete snapshot, a target, history, or
3062
+ * choice destination, a state-value update, a target combined with an
3063
+ * owner update, or the targetless result of `{ stay: true }`. Raw decoded
3064
+ * state values are not accepted as transition targets.
3370
3065
  *
3371
3066
  * @category utility types
3372
3067
  * @since 0.4.0
3373
3068
  */
3374
- type InitialReturn<Initial> = Initial extends (...args: any) => infer Ret ? Ret : never;
3069
+ export type HandlerResult<States extends StateSchemas, E, R> = Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>> | StateUpdate<States, ValuedStateIdentifier<States>> | CombinedTarget<Target<States, StateIdentifier<States>> | Snapshot<States> | ChoiceTarget<States, ChoiceIdentifier<States>>, States, ValuedStateIdentifier<States>> | StateConstruction<Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>> | StateUpdate<States, ValuedStateIdentifier<States>>> | NoTarget;
3375
3070
  /**
3376
3071
  * Extracts the return value from an entry or exit action.
3377
3072
  *
3378
3073
  * @category utility types
3379
3074
  * @since 0.4.0
3380
3075
  */
3381
- type StateActionReturn<Config, Key extends "entry" | "exit"> = Key extends keyof Config ? NonNullable<Config[Key]> extends (...args: any) => infer Ret ? Ret : never : never;
3076
+ export type StateActionReturn<Config, Key extends "entry" | "exit"> = Key extends keyof Config ? NonNullable<Config[Key]> extends (...args: any) => infer Ret ? Ret : never : never;
3382
3077
  /** Extracts the return values from a state's history defaults. */
3383
- type HistoryDefaultReturn<Config> = Config extends {
3078
+ export type HistoryDefaultReturn<Config> = Config extends {
3384
3079
  readonly history?: infer History;
3385
3080
  } ? {
3386
3081
  readonly [Key in keyof NonNullable<History>]: NonNullable<History>[Key] extends {
@@ -3388,7 +3083,7 @@ export declare namespace Machine {
3388
3083
  } ? Ret : never;
3389
3084
  }[keyof NonNullable<History>] : never;
3390
3085
  /** Extracts the return value from a choice resolver. */
3391
- type ChoiceReturn<Config> = Config extends {
3086
+ export type ChoiceReturn<Config> = Config extends {
3392
3087
  readonly choice: infer Choice;
3393
3088
  } ? EventTransitionReturn<Choice> : never;
3394
3089
  /**
@@ -3397,7 +3092,7 @@ export declare namespace Machine {
3397
3092
  * @category utility types
3398
3093
  * @since 0.4.0
3399
3094
  */
3400
- type EventTransitionReturn<Transition> = Transition extends {
3095
+ export type EventTransitionReturn<Transition> = Transition extends {
3401
3096
  readonly resolve?: infer Resolve;
3402
3097
  } ? NonNullable<Resolve> extends (...args: any) => infer Ret ? Ret : never : never;
3403
3098
  /**
@@ -3406,7 +3101,7 @@ export declare namespace Machine {
3406
3101
  * @category utility types
3407
3102
  * @since 0.4.0
3408
3103
  */
3409
- type EventHandlerReturn<Config> = Config extends {
3104
+ export type EventHandlerReturn<Config> = Config extends {
3410
3105
  readonly on?: infer On;
3411
3106
  } ? {
3412
3107
  readonly [EventTag in keyof On]: EventTransitionReturn<NonNullable<On[EventTag]>>;
@@ -3417,7 +3112,7 @@ export declare namespace Machine {
3417
3112
  * @category utility types
3418
3113
  * @since 0.4.0
3419
3114
  */
3420
- type InvokeReturn<Config> = "invoke" extends keyof Config ? Config extends {
3115
+ export type InvokeReturn<Config> = "invoke" extends keyof Config ? Config extends {
3421
3116
  readonly invoke?: infer Invoke;
3422
3117
  } ? NonNullable<Invoke> extends (...args: any) => infer Resolved ? NonNullable<Resolved> extends ReadonlyArray<infer One> ? One : NonNullable<Resolved> : NonNullable<Invoke> extends ReadonlyArray<infer One> ? One : NonNullable<Invoke> : never : never;
3423
3118
  /**
@@ -3426,10 +3121,10 @@ export declare namespace Machine {
3426
3121
  * @category utility types
3427
3122
  * @since 0.4.0
3428
3123
  */
3429
- type InvokeResolvedSource<Source> = Source extends LazyProgramValue ? Source : Source extends (...args: any) => infer Resolved ? Resolved : Source;
3124
+ export type InvokeResolvedSource<Source> = Source extends LazyProgramValue ? Source : Source extends (...args: any) => infer Resolved ? Resolved : Source;
3430
3125
  type InvokeFactoryResult<Source> = Source extends (...args: any) => infer Resolved ? Resolved : never;
3431
- type ChildMachineLogic<Child> = Child extends ChildMachine<string, infer M> ? Logic<Snapshot<States<M>>, EventInput<InputEvent<M>>, Error<M> | ActionError<Services<M>> | InfiniteTransitionError | MachineSchemaDecodeError | StoppedError, ExcludeCompatibleRuntime<Exclude<ExecutionServices<InitialServices<M> | Services<M>>, internalRuntime.MachineRuntime>, Event<M>, EmittedEvent<M>>, Output<M>, InitialError<M> | Error<M> | ActionError<InitialServices<M> | Services<M>> | InfiniteTransitionError | MachineSchemaDecodeError | StartupError | StoppedError> : never;
3432
- type InvokeLogic<Invoke> = Invoke extends {
3126
+ type ChildMachineLogic<Child> = Child extends ChildMachine<string, infer M> ? Logic<Snapshot<States<M>>, EventInput<InputEvent<M>>, Error<M> | ActionError<Services<M>> | InfiniteTransitionError | MachineSchemaDecodeError | StoppedError, ExcludeCompatibleRuntime<Exclude<ExecutionServices<InitialServices<M> | Services<M>>, MachineRuntime>, Event<M>, EmittedEvent<M>>, Output<M>, InitialError<M> | Error<M> | ActionError<InitialServices<M> | Services<M>> | InfiniteTransitionError | MachineSchemaDecodeError | StartupError | StoppedError> : never;
3127
+ export type InvokeLogic<Invoke> = Invoke extends {
3433
3128
  readonly effect: infer Source;
3434
3129
  } ? InvokeFactoryResult<Source> extends infer Fx extends Effect.Effect<any, any, any> ? Logic<void, never, Effect.Error<Fx>, Effect.Services<Fx>, Effect.Success<Fx>> : never : Invoke extends {
3435
3130
  readonly stream: infer Source;
@@ -3446,7 +3141,7 @@ export declare namespace Machine {
3446
3141
  * @category utility types
3447
3142
  * @since 0.4.0
3448
3143
  */
3449
- type InvokeInitialError<Invoke> = Invoke extends {
3144
+ export type InvokeInitialError<Invoke> = Invoke extends {
3450
3145
  readonly [InvokeTypeId]: {
3451
3146
  readonly initialError: Types.Covariant<infer InitialError>;
3452
3147
  };
@@ -3457,7 +3152,7 @@ export declare namespace Machine {
3457
3152
  * @category utility types
3458
3153
  * @since 0.4.0
3459
3154
  */
3460
- type InvokeRuntimeError<Invoke> = Invoke extends {
3155
+ export type InvokeRuntimeError<Invoke> = Invoke extends {
3461
3156
  readonly [InvokeTypeId]: {
3462
3157
  readonly error: Types.Covariant<infer Error>;
3463
3158
  };
@@ -3468,7 +3163,7 @@ export declare namespace Machine {
3468
3163
  * @category utility types
3469
3164
  * @since 0.4.0
3470
3165
  */
3471
- type InvokeOutput<Invoke> = Invoke extends {
3166
+ export type InvokeOutput<Invoke> = Invoke extends {
3472
3167
  readonly [InvokeTypeId]: {
3473
3168
  readonly output: Types.Covariant<infer Output>;
3474
3169
  };
@@ -3479,26 +3174,13 @@ export declare namespace Machine {
3479
3174
  * @category utility types
3480
3175
  * @since 0.4.0
3481
3176
  */
3482
- type InvokeServices<Invoke> = Invoke extends {
3177
+ export type InvokeServices<Invoke> = Invoke extends {
3483
3178
  readonly [InvokeTypeId]: {
3484
3179
  readonly requirements: Types.Covariant<infer Requirements>;
3485
3180
  };
3486
3181
  } ? Requirements : LogicServicesOf<InvokeLogic<Invoke>>;
3487
- /**
3488
- * Extracts events emitted directly by an invoked child.
3489
- *
3490
- * @category utility types
3491
- * @since 0.4.0
3492
- */
3493
- type InvokeEmits<Invoke> = Invoke extends {
3494
- readonly [InvokeTypeId]: {
3495
- readonly emits: Types.Covariant<infer Emitted>;
3496
- };
3497
- } ? Emitted : Invoke extends {
3498
- readonly child: ChildMachine<string, infer M>;
3499
- } ? EmittedEvent<M> : never;
3500
3182
  /** Public parent inputs required by an invoked child machine. */
3501
- type InvokeParentEvents<Invoke> = Invoke extends {
3183
+ export type InvokeParentEvents<Invoke> = Invoke extends {
3502
3184
  readonly [InvokeTypeId]: {
3503
3185
  readonly parentEvents: Types.Covariant<infer ParentEvent>;
3504
3186
  };
@@ -3506,7 +3188,7 @@ export declare namespace Machine {
3506
3188
  readonly child: ChildMachine<string, infer M>;
3507
3189
  } ? EventOf<ParentEvents<M>> : never;
3508
3190
  /** Extracts transition results returned by invocation lifecycle handlers. */
3509
- type InvokeOutcomeReturn<Invoke> = Invoke extends unknown ? (Invoke extends {
3191
+ export type InvokeOutcomeReturn<Invoke> = Invoke extends unknown ? (Invoke extends {
3510
3192
  readonly [InvokeTypeId]: {
3511
3193
  readonly outcomes: Types.Covariant<infer Outcomes>;
3512
3194
  };
@@ -3541,21 +3223,21 @@ export declare namespace Machine {
3541
3223
  * @category utility types
3542
3224
  * @since 0.4.0
3543
3225
  */
3544
- type InvokeError<Config> = [InvokeReturn<Config>] extends [never] ? never : InvokeCollisionError<InvokeReturn<Config>> | InvokeInitialError<InvokeReturn<Config>> | InvokeOutcomeError<InvokeReturn<Config>>;
3226
+ export type InvokeError<Config> = [InvokeReturn<Config>] extends [never] ? never : InvokeCollisionError<InvokeReturn<Config>> | InvokeInitialError<InvokeReturn<Config>> | InvokeOutcomeError<InvokeReturn<Config>>;
3545
3227
  /**
3546
3228
  * Extracts the parent service requirement contribution from invoked children.
3547
3229
  *
3548
3230
  * @category utility types
3549
3231
  * @since 0.4.0
3550
3232
  */
3551
- type InvokeRequirements<Config> = [InvokeReturn<Config>] extends [never] ? never : MachineRuntimeRequirement | InvokeServices<InvokeReturn<Config>> | InvokeOutcomeServices<InvokeReturn<Config>>;
3233
+ export type InvokeRequirements<Config> = [InvokeReturn<Config>] extends [never] ? never : MachineRuntime | InvokeServices<InvokeReturn<Config>> | InvokeOutcomeServices<InvokeReturn<Config>>;
3552
3234
  /**
3553
3235
  * Extracts the return value from an eventless transition.
3554
3236
  *
3555
3237
  * @category utility types
3556
3238
  * @since 0.4.0
3557
3239
  */
3558
- type AlwaysReturn<Config> = Config extends {
3240
+ export type AlwaysReturn<Config> = Config extends {
3559
3241
  readonly always?: infer Always;
3560
3242
  } ? EventTransitionReturn<NonNullable<Always>> : never;
3561
3243
  /**
@@ -3564,117 +3246,40 @@ export declare namespace Machine {
3564
3246
  * @category utility types
3565
3247
  * @since 0.4.0
3566
3248
  */
3567
- type DoneReturn<Config> = Config extends {
3249
+ export type DoneReturn<Config> = Config extends {
3568
3250
  readonly onDone?: infer OnDone;
3569
3251
  } ? EventTransitionReturn<NonNullable<OnDone>> : never;
3570
- /**
3571
- * Extracts the return value from a final state output function.
3572
- *
3573
- * @category utility types
3574
- * @since 0.4.0
3575
- */
3576
- type FinalOutputReturn<Config> = Config extends {
3577
- readonly output?: infer Output;
3578
- } ? NonNullable<Output> extends (...args: any) => infer Ret ? Ret : never : never;
3579
3252
  /**
3580
3253
  * Extracts all service requirements contributed by a state handler config.
3581
3254
  *
3582
3255
  * @category utility types
3583
3256
  * @since 0.4.0
3584
3257
  */
3585
- type ConfigServices<Config> = Config extends unknown ? [keyof Config] extends [never] ? never : Effect.Services<EventHandlerReturn<Config>> | Effect.Services<AlwaysReturn<Config>> | Effect.Services<DoneReturn<Config>> | Effect.Services<StateActionReturn<Config, "entry">> | Effect.Services<StateActionReturn<Config, "exit">> | Effect.Services<HistoryDefaultReturn<Config>> | Effect.Services<ChoiceReturn<Config>> | InvokeRequirements<Config> : never;
3258
+ export type ConfigServices<Config> = Config extends unknown ? [keyof Config] extends [never] ? never : Effect.Services<EventHandlerReturn<Config>> | Effect.Services<AlwaysReturn<Config>> | Effect.Services<DoneReturn<Config>> | Effect.Services<StateActionReturn<Config, "entry">> | Effect.Services<StateActionReturn<Config, "exit">> | Effect.Services<HistoryDefaultReturn<Config>> | Effect.Services<ChoiceReturn<Config>> | InvokeRequirements<Config> : never;
3586
3259
  /** The only transition value accepted by machine handler APIs. */
3587
3260
  type TransitionConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateNodeIdentifier<States>, Context, Reenter extends boolean = false, Acceptance extends TransitionAcceptance = "required"> = Transition<States, StateId, Context, Events, Emits, {}, Reenter, Acceptance>;
3588
- type SelectionBuilder<Selection> = Selection extends TargetSelection<infer Builder, any, any, any> ? Builder : never;
3589
- type SelectionKind<Selection> = Selection extends TargetSelection<any, any, infer Kind, any> ? Kind : never;
3590
- type SelectionPath<Selection> = Selection extends TargetSelection<any, infer Path, any, any> ? Path : never;
3591
- type TargetBuilderResult<Builder> = (Builder extends (...args: any) => infer Result ? Result : never) | (Builder extends {
3592
- readonly decoded: (...args: any) => infer Result;
3593
- } ? Result : never) | (Builder extends {
3594
- readonly from: (...args: any) => infer Result;
3595
- } ? Result : never);
3596
- type SelectedTargetResult<Selection> = SelectionBuilder<Selection> extends infer Builder ? TargetBuilderResult<Builder> : never;
3597
- /**
3598
- * Destination construction returned when a transition declares one retained
3599
- * valued owner with a `{ target, update }` declaration.
3600
- *
3601
- * @category models
3602
- * @since 0.22.0
3603
- */
3604
- interface UpdatingStateConstruction<Result, States extends StateSchemas, Owner extends ValuedStateIdentifier<States>> {
3605
- /** Combines the selected topology with the required owner replacement. */
3606
- readonly update: (update: StateUpdate<States, Owner>) => CombinedTarget<UnwrapConstruction<Result>, States, Owner>;
3607
- }
3608
- type UpdatingCallable<Callable, States extends StateSchemas, Owner extends ValuedStateIdentifier<States>> = Callable extends {
3609
- (...args: infer Arguments1): infer Result1;
3610
- (...args: infer Arguments2): infer Result2;
3611
- } ? {
3612
- (...args: Arguments1): UpdatingStateConstruction<Result1, States, Owner>;
3613
- (...args: Arguments2): UpdatingStateConstruction<Result2, States, Owner>;
3614
- } : Callable extends (...args: infer Arguments) => infer Result ? (...args: Arguments) => UpdatingStateConstruction<Result, States, Owner> : never;
3615
- type UpdatingTargetBuilder<Builder, States extends StateSchemas, Owner extends ValuedStateIdentifier<States>> = {
3616
- readonly [Key in keyof Builder]: Key extends "from" | "decoded" ? UpdatingCallable<Builder[Key], States, Owner> : Builder[Key];
3617
- };
3618
- type SelectionSupportsDefaultConstruction<Selection> = SelectionKind<Selection> extends "none" ? true : SelectionBuilder<Selection> extends {
3619
- readonly from: (...args: infer Args) => any;
3620
- } ? [] extends Args ? true : false : false;
3621
- type TransitionResolveContext<Context, Selection> = Omit<Context, "target"> & (SelectionKind<Selection> extends "none" ? {} : {
3622
- readonly target: SelectionBuilder<Selection>;
3623
- });
3624
- /** Context capability available only to explicitly declinable resolvers. */
3625
- interface DeclineCapability {
3626
- /** Declines this candidate and continues hierarchical transition selection. */
3627
- readonly decline: () => Declined;
3628
- }
3629
- /** One named destination declared by a branching transition. */
3630
- interface TransitionBranchInput<Selection extends TargetSelection<any, any, any> = TargetSelection<any, any, any>> {
3631
- /** Exact topology destination available to the branching resolver. */
3632
- readonly target: Selection;
3633
- /** Optional human-readable branch label used by visualization tooling. */
3634
- readonly title?: string;
3635
- }
3636
- /** Opaque evidence that a branching resolver selected one declared branch. */
3637
- interface SelectedBranch<out Key extends string, out Result> {
3638
- readonly [Topology.SelectedBranchTypeId]: {
3261
+ /** Opaque evidence that `resolve` selected one declared branch. */
3262
+ export interface SelectedBranch<out Key extends string, out Result> {
3263
+ readonly [SelectedBranchTypeId]: {
3639
3264
  readonly key: Types.Covariant<Key>;
3640
3265
  readonly result: Types.Covariant<Result>;
3641
3266
  };
3642
3267
  }
3643
- type CompletedBranchResult<R> = R extends {
3644
- readonly update: unknown;
3645
- } ? R extends UpdatingStateConstruction<infer Target, infer S, infer Owner> ? CombinedTarget<UnwrapConstruction<Target>, S, Owner> : R : R;
3646
- type SelectedConstruction<K extends string, R> = R extends {
3647
- readonly update: unknown;
3648
- } ? R extends UpdatingStateConstruction<infer Target, infer S, infer Owner> ? {
3649
- readonly update: SelectedBranchBuilder<StateUpdateBuilder<S, Owner>, K> extends infer B ? {
3650
- readonly [M in keyof B]: StateUpdateBuilder<S, Owner>[Extract<M, keyof StateUpdateBuilder<S, Owner>>] extends (...args: infer A) => unknown ? (...args: A) => SelectedBranch<K, CombinedTarget<UnwrapConstruction<Target>, S, Owner>> : never;
3651
- } : never;
3652
- } : SelectedBranch<K, R> : SelectedBranch<K, R>;
3653
- type SelectedBranchCallable<Callable, Key extends string> = Callable extends {
3654
- (...args: infer Arguments1): infer Result1;
3655
- (...args: infer Arguments2): infer Result2;
3656
- } ? {
3657
- (...args: Arguments1): SelectedConstruction<Key, Result1>;
3658
- (...args: Arguments2): SelectedConstruction<Key, Result2>;
3659
- } : Callable extends (...args: infer Arguments) => infer Result ? (...args: Arguments) => SelectedConstruction<Key, Result> : {};
3660
- type SelectedBranchBuilderProperties<Builder, Key extends string> = {
3661
- readonly [Property in keyof Builder]: Builder[Property] extends (...args: any) => any ? SelectedBranchCallable<Builder[Property], Key> : Builder[Property];
3662
- };
3663
- /** Target-specific builder that brands every construction with its branch key. */
3664
- type SelectedBranchBuilder<Builder, Key extends string> = SelectedBranchCallable<Builder, Key> & SelectedBranchBuilderProperties<Builder, Key>;
3665
- type BranchSelectors<Branches extends Readonly<Record<string, TransitionBranchInput>>> = {
3666
- readonly [Key in Extract<keyof Branches, string>]: SelectedBranchBuilder<SelectionBuilder<Branches[Key]["target"]>, Key>;
3667
- };
3668
- type BranchSelectionResult<Branches extends Readonly<Record<string, TransitionBranchInput>>> = {
3669
- readonly [Key in Extract<keyof Branches, string>]: SelectedBranch<Key, CompletedBranchResult<SelectedTargetResult<Branches[Key]["target"]>>>;
3670
- }[Extract<keyof Branches, string>];
3671
- type TransitionBranchesResolveContext<Context, Branches extends Readonly<Record<string, TransitionBranchInput>>> = Omit<Context, "target"> & {
3672
- readonly select: BranchSelectors<Branches>;
3673
- };
3674
- type InvokeTransition<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateNodeIdentifier<States>, Context> = TransitionConfig<States, Events, Emits, StateId, Context, true, TransitionAcceptance>;
3675
- type InvokeSource<Value, Context> = Value | ((context: Context) => Value);
3676
- /** Inline state-owned work that runs for the lifetime of its active state. */
3677
- interface InvokeOwned<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> {
3268
+ export type InvokeSource<Value, Context> = Value | ((context: Context) => Value);
3269
+ /**
3270
+ * State-owned work that runs for the lifetime of its active state.
3271
+ *
3272
+ * **Details**
3273
+ *
3274
+ * Every `invoke` entry carries this type-level marker, which records the
3275
+ * state that owns the entry together with the machine's state schemas and
3276
+ * event protocols. The marker property is optional and is never set at
3277
+ * runtime.
3278
+ *
3279
+ * @category models
3280
+ * @since 0.23.0
3281
+ */
3282
+ export interface InvokeOwned<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> {
3678
3283
  readonly "~effect/Machine/InvokeOwner"?: Types.Covariant<readonly [States, Events, Emits, StateId, InputEvents, ParentEvents]>;
3679
3284
  }
3680
3285
  type StoredInvokeConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> = InvokeOwned<States, Events, Emits, StateId, InputEvents, ParentEvents> & ({
@@ -3746,14 +3351,14 @@ export declare namespace Machine {
3746
3351
  type LogicRunEffectOf<Value> = Value extends {
3747
3352
  readonly run: infer Run;
3748
3353
  } ? Run extends (...args: ReadonlyArray<any>) => infer Result ? Result : never : never;
3749
- type LogicStateOf<Value> = Effect.Success<LogicInitialEffectOf<Value>>;
3750
- type LogicEventOf<Value> = Value extends {
3354
+ export type LogicStateOf<Value> = Effect.Success<LogicInitialEffectOf<Value>>;
3355
+ export type LogicEventOf<Value> = Value extends {
3751
3356
  readonly initial: infer Initial;
3752
3357
  } ? Initial extends (scope: infer LogicScope, ...args: ReadonlyArray<any>) => any ? LogicScope extends Logic.Scope<infer Event> ? Event : never : never : never;
3753
- type LogicErrorOf<Value> = Effect.Error<LogicRunEffectOf<Value>>;
3754
- type LogicServicesOf<Value> = Effect.Services<LogicInitialEffectOf<Value> | LogicRunEffectOf<Value>>;
3755
- type LogicOutputOf<Value> = Effect.Success<LogicRunEffectOf<Value>>;
3756
- type LogicInitialErrorOf<Value> = Effect.Error<LogicInitialEffectOf<Value>>;
3358
+ export type LogicErrorOf<Value> = Effect.Error<LogicRunEffectOf<Value>>;
3359
+ export type LogicServicesOf<Value> = Effect.Services<LogicInitialEffectOf<Value> | LogicRunEffectOf<Value>>;
3360
+ export type LogicOutputOf<Value> = Effect.Success<LogicRunEffectOf<Value>>;
3361
+ export type LogicInitialErrorOf<Value> = Effect.Error<LogicInitialEffectOf<Value>>;
3757
3362
  /** Output construction available to final and output-producing parallel states. */
3758
3363
  type OutputHandlerConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, Context> = NodeByIdentifier<States, StateId> extends {
3759
3364
  readonly output: Schema.Top;
@@ -3786,10 +3391,10 @@ export declare namespace Machine {
3786
3391
  readonly states?: never;
3787
3392
  });
3788
3393
  /** Context used only when a history node has no previously captured record. */
3789
- interface HistoryDefaultContext<in out States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, in out ParentId extends StateIdentifier<States>> {
3394
+ export interface HistoryDefaultContext<in out States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, in out ParentId extends StateIdentifier<States>> {
3790
3395
  /** Lifecycle event that attempted to restore this history node. */
3791
3396
  readonly event: LifecycleEvent<Events>;
3792
- /** Complete target builder rooted at the history owner. */
3397
+ /** Constructs the complete root configuration that contains the history owner. */
3793
3398
  readonly target: HistoryDefaultTargetBuilder<States, ParentId>;
3794
3399
  /** State path whose child configuration is restored by this history node. */
3795
3400
  readonly owner: ParentId;
@@ -3801,13 +3406,20 @@ export declare namespace Machine {
3801
3406
  * history owner. This makes the default independent of the transition source
3802
3407
  * and provides every inactive ancestor and required parallel region.
3803
3408
  */
3804
- type HistoryDefaultHandler<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, ParentId extends StateIdentifier<States>> = (context: HistoryDefaultContext<States, Events, Emits, ParentId>, enqueue: Enqueue<EventOf<Events>, EmittedEventOf<Emits>>) => CompleteSnapshotContaining<States, ParentId> | StateConstruction<CompleteSnapshotContaining<States, ParentId>>;
3409
+ export type HistoryDefaultHandler<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, ParentId extends StateIdentifier<States>> = (context: HistoryDefaultContext<States, Events, Emits, ParentId>, enqueue: Enqueue<EventOf<Events>, EmittedEventOf<Emits>>) => CompleteSnapshotContaining<States, ParentId> | StateConstruction<CompleteSnapshotContaining<States, ParentId>>;
3805
3410
  /**
3806
3411
  * Fallback implementation for one direct history pseudo-state.
3807
3412
  *
3413
+ * **Details**
3414
+ *
3415
+ * `default` runs only when the history state is entered before its owner has
3416
+ * recorded a configuration, and returns the complete configuration to enter.
3417
+ *
3808
3418
  * @inline
3419
+ * @category models
3420
+ * @since 0.23.0
3809
3421
  */
3810
- interface HistoryDefaultEntry<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, ParentId extends StateIdentifier<States>> {
3422
+ export interface HistoryDefaultEntry<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, ParentId extends StateIdentifier<States>> {
3811
3423
  /** Builds the complete fallback configuration used before history is first captured. */
3812
3424
  readonly default: HistoryDefaultHandler<States, Events, Emits, ParentId>;
3813
3425
  }
@@ -3816,14 +3428,24 @@ export declare namespace Machine {
3816
3428
  *
3817
3429
  * @inlineType HistoryDefaultEntry
3818
3430
  */
3819
- type HistoryDefaultConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, ParentId extends StateIdentifier<States>, Children extends StateSchemas> = {
3431
+ export type HistoryDefaultConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, ParentId extends StateIdentifier<States>, Children extends StateSchemas> = {
3820
3432
  readonly [Key in HistoryStateKey<Children>]?: HistoryDefaultEntry<States, Events, Emits, ParentId>;
3821
3433
  };
3822
- /** Required implementation for a choice pseudo-state. */
3823
- interface ChoiceStateConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, ChoiceId extends ChoiceIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> {
3824
- /** Required transition that resolves this transient choice to a concrete destination. */
3825
- readonly choice: TransitionConfig<States, Events, Emits, ChoiceId, ChoiceContext<States, Events, Emits, ChoiceId, InputEvents, ParentEvents>>;
3826
- readonly entry?: never;
3434
+ /**
3435
+ * Required implementation for a choice pseudo-state.
3436
+ *
3437
+ * **Details**
3438
+ *
3439
+ * A choice state declares only `choice`, the transition that resolves it to
3440
+ * a concrete destination. Every other handler key is rejected.
3441
+ *
3442
+ * @category models
3443
+ * @since 0.23.0
3444
+ */
3445
+ export interface ChoiceStateConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, ChoiceId extends ChoiceIdentifier<States>, InputEvents extends ReadonlyArray<TaggedSchema> = Events, ParentEvents extends ReadonlyArray<TaggedSchema> = readonly []> {
3446
+ /** Required transition that resolves this transient choice to a concrete destination. */
3447
+ readonly choice: TransitionConfig<States, Events, Emits, ChoiceId, ChoiceContext<States, Events, Emits, ChoiceId, InputEvents, ParentEvents>>;
3448
+ readonly entry?: never;
3827
3449
  readonly exit?: never;
3828
3450
  readonly invoke?: never;
3829
3451
  readonly always?: never;
@@ -3837,22 +3459,6 @@ export declare namespace Machine {
3837
3459
  type HandlerConfigPart<Config> = {
3838
3460
  readonly [Key in keyof Config as Key extends "states" | "initial" | "root" ? never : Key]: Config[Key];
3839
3461
  };
3840
- type HandlerNodeChildrenConfig<Config> = "states" extends keyof Config ? Config extends {
3841
- readonly states?: infer Children;
3842
- } ? NonNullable<Children> : never : never;
3843
- type HandlerNodeByPath<States extends StateSchemas, Path extends string> = "" extends keyof States ? Path extends "" ? States[""] : States[""] extends {
3844
- readonly states: infer Children extends StateSchemas;
3845
- } ? HandlerNodeByPath<Children, Path> : never : Path extends `${infer Head}.${infer Rest}` ? Head extends keyof States ? States[Head] extends {
3846
- readonly states: infer Children extends StateSchemas;
3847
- } ? HandlerNodeByPath<Children, Rest> : never : never : Path extends keyof States ? States[Path] : never;
3848
- type HandlerConfigAtPath<Config, Path extends string> = [Config] extends [never] ? never : "" extends keyof Config ? Path extends "" ? Config[""] : HandlerConfigAtPath<HandlerNodeChildrenConfig<Config[""]>, Path> : Path extends `${infer Head}.${infer Rest}` ? Head extends keyof Config ? HandlerConfigAtPath<HandlerNodeChildrenConfig<Config[Head]>, Rest> : never : Path extends keyof Config ? Config[Path] : never;
3849
- type HandlerValidationAtPath<Path extends string, Validation> = Path extends `${infer Head}.${infer Rest}` ? {
3850
- readonly [Key in Head]?: {
3851
- readonly states: HandlerValidationAtPath<Rest, Validation>;
3852
- };
3853
- } : {
3854
- readonly [Key in Path]?: Validation;
3855
- };
3856
3462
  type HandlerNodeConfigKey = "always" | "choice" | "entry" | "exit" | "history" | "initial" | "root" | "invoke" | "on" | "onDone" | "output" | "states";
3857
3463
  type HandlerValidationError<Message extends string, Path extends string, Detail = unknown> = {
3858
3464
  readonly "~effect/Machine/HandlerError": readonly [message: Message, path: Path, detail: Detail];
@@ -3891,19 +3497,6 @@ export declare namespace Machine {
3891
3497
  readonly [Key in UnknownKeys]: HandlerValidationError<"Handler config contains an event key that does not exist", StateId, Key>;
3892
3498
  };
3893
3499
  } : unknown;
3894
- type TransitionResultInitialTargetPath<Result> = IsAny<Result> extends true ? never : Result extends Effect.Effect<infer Success, any, any> ? TransitionResultInitialTargetPath<Success> : Result extends SelectedBranch<any, infer Selected> ? TransitionResultInitialTargetPath<Selected> : Result extends StateConstruction<infer Constructed> ? TransitionResultInitialTargetPath<Constructed> : Result extends {
3895
- readonly [Topology.InitialTargetTypeId]: typeof Topology.InitialTargetTypeId;
3896
- readonly _tag: "InitialTarget";
3897
- } ? Result extends {
3898
- readonly path: infer Path extends string;
3899
- } ? Path : never : never;
3900
- type HandlerConfigInitialTargetPath<Config> = TransitionResultInitialTargetPath<EventHandlerReturn<Config> | AlwaysReturn<Config> | DoneReturn<Config> | ChoiceReturn<Config> | InvokeOutcomeReturn<InvokeReturn<Config>>>;
3901
- type RequiredInitializersForTargetPath<AllStates extends StateSchemas, Path> = string extends Path ? never : Path extends StateIdentifier<AllStates> ? InitializerClosureForNode<AllStates, NodeByIdentifier<AllStates, Path>, Path> : never;
3902
- type HandlerTreeInitialTargetPath<Config> = string extends keyof Config ? never : Config extends object ? {
3903
- readonly [Key in keyof Config]: HandlerConfigInitialTargetPath<HandlerConfigPart<Config[Key]>> | (Config[Key] extends {
3904
- readonly states: infer Children;
3905
- } ? HandlerTreeInitialTargetPath<Children> : never);
3906
- }[keyof Config] : never;
3907
3500
  type HandlerChildrenValidation<Node, Prefix extends string, Config> = "states" extends keyof Config ? Config extends {
3908
3501
  readonly states?: infer ChildrenConfig;
3909
3502
  } ? HandlerChildren<Node> extends infer Children extends StateSchemas ? [Children] extends [never] ? {
@@ -3935,20 +3528,6 @@ export declare namespace Machine {
3935
3528
  readonly invoke: HandlerValidationError<"Invoked child expects parent events not accepted by this machine", StateId, Exclude<InvokeParentEvents<InvokeReturn<Config>>, EventOf<Events>>>;
3936
3529
  };
3937
3530
  type HandlerRuntimeValidation<Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends string, Config, Incompatible = keyof Config extends never ? never : IncompatibleRuntime<ConfigServices<HandlerConfigPart<Config>>, EventOf<Events>, EmittedEventOf<Emits>>> = [Incompatible] extends [never] ? unknown : HandlerValidationError<"Handler config requires an incompatible machine runtime", StateId, Incompatible>;
3938
- type RootInitialTargetValidation<States extends StateSchemas, Config> = RequiredInitializersForTargetPath<States, HandlerTreeInitialTargetPath<{
3939
- readonly "": Config;
3940
- }>> extends infer Required ? Types.UnionToIntersection<Required extends string ? HandlerConfigAtPath<{
3941
- readonly "": Config;
3942
- }, Required> extends infer NodeConfig ? [
3943
- NodeConfig
3944
- ] extends [never] ? RootInitializeError<Required> : "initial" extends keyof NodeConfig ? never : RootInitializeError<Required> : never : unknown> : unknown;
3945
- type RootInitializeError<Path extends string> = Path extends "" ? {
3946
- readonly initialize: HandlerValidationError<"State requires initialize because a transition enters its declared initial configuration", Path>;
3947
- } : {
3948
- readonly states: HandlerValidationAtPath<Path, {
3949
- readonly initialize: HandlerValidationError<"State requires initialize because a transition enters its declared initial configuration", Path>;
3950
- }>;
3951
- };
3952
3531
  type HandlerTreeValidation<States extends StateSchemas, Node, Events extends ReadonlyArray<TaggedSchema>, InputEvents extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, Path extends StateNodeIdentifier<States>, Config, OutputStates extends StateIdentifier<States>> = HandlerNodeValidation<States, Node, Events, InputEvents, Emits, Path, Config, OutputStates> & (Config extends {
3953
3532
  readonly states: infer Handlers;
3954
3533
  } ? Node extends {
@@ -3993,29 +3572,25 @@ export declare namespace Machine {
3993
3572
  readonly states: infer Handlers;
3994
3573
  } ? HandlerTreeEvidence<AllStates, Handlers, Children, JoinPath<Prefix, K>> : never : never);
3995
3574
  }[Extract<keyof Config & keyof Nodes, string>];
3996
- type HandleTreeResult<AllStates extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, Input extends Schema.Top, UnhandledStates extends StateIdentifier<AllStates>, E, R, InitialE, InitialR, FinalStates extends StateIdentifier<AllStates>, Output, OutputStates extends StateIdentifier<AllStates>, InputEvents extends ReadonlyArray<TaggedSchema>, ParentEvents extends ReadonlyArray<TaggedSchema>, Config> = Machine<AllStates, Events, Input, Exclude<UnhandledStates, HandlerTreeEvidence<AllStates, Config>["stateId"]>, E | HandlerTreeEvidence<AllStates, Config>["error"], ExcludeCompatibleRuntime<R | HandlerTreeEvidence<AllStates, Config>["services"], EventOf<Events>, EmittedEventOf<Emits>>, InitialE, InitialR, FinalStates, Output, Emits, OutputStates | Extract<HandlerTreeEvidence<AllStates, Config>["outputState"], StateIdentifier<AllStates>>, InputEvents, ParentEvents>;
3997
- type ObjectCompoundPath<S extends StateSchemas> = {
3998
- readonly [P in StateIdentifier<S>]: NodeByIdentifier<S, P> extends {
3999
- /** Child handlers nested according to the declared root topology. */
4000
- readonly states: StateSchemas;
4001
- } ? P : never;
4002
- }[StateIdentifier<S>];
3575
+ type HandleEvidence<S extends StateSchemas, C, R> = HandlerTreeEvidence<S, {
3576
+ readonly "": NormalizeObjectConfig<C, R>;
3577
+ }>;
4003
3578
  type LazyProgramValue = Effect.Effect<unknown, unknown, unknown> | Stream.Stream<unknown, unknown, unknown>;
4004
3579
  /** Registered lazy programs and their optional explicit input adapters. */
4005
- type Program<Value> = Value | ((...args: never[]) => Value);
4006
- type EffectSources = Readonly<Record<string, Program<Effect.Effect<unknown, unknown, unknown>>>>;
4007
- type StreamSources = Readonly<Record<string, Program<Stream.Stream<unknown, unknown, unknown>>>>;
4008
- type TimerSources = Readonly<Record<string, Program<Duration.Input>>>;
4009
- type LogicSources = Readonly<Record<string, unknown>>;
4010
- type ValidateLogicSources<Sources> = {
3580
+ export type Program<Value> = Value | ((...args: never[]) => Value);
3581
+ export type EffectSources = Readonly<Record<string, Program<Effect.Effect<unknown, unknown, unknown>>>>;
3582
+ export type StreamSources = Readonly<Record<string, Program<Stream.Stream<unknown, unknown, unknown>>>>;
3583
+ export type TimerSources = Readonly<Record<string, Program<Duration.Input>>>;
3584
+ export type LogicSources = Readonly<Record<string, unknown>>;
3585
+ export type ValidateLogicSources<Sources> = {
4011
3586
  readonly [K in keyof Sources]: InvokeResolvedSource<Sources[K]> extends {
4012
- /** Enters a compound or parallel subtree through its declared initialization. */
3587
+ /** Produces the first state of the registered logic. */
4013
3588
  readonly initial: (...args: never[]) => Effect.Effect<unknown, unknown, unknown>;
4014
3589
  readonly run: (...args: never[]) => Effect.Effect<unknown, unknown, unknown>;
4015
3590
  } ? unknown : never;
4016
3591
  };
4017
- type ChildSources = Readonly<Record<string, ChildMachine.Any>>;
4018
- type ValidatePrograms<Sources> = {
3592
+ export type ChildSources = Readonly<Record<string, ChildMachine.Any>>;
3593
+ export type ValidatePrograms<Sources> = {
4019
3594
  readonly [K in keyof Sources]: Sources[K] extends LazyProgramValue ? unknown : Sources[K] extends (...args: never[]) => unknown ? Parameters<Sources[K]>["length"] extends 1 ? unknown : never : unknown;
4020
3595
  };
4021
3596
  type PathName<P extends string> = P extends "" ? "root" : P;
@@ -4023,85 +3598,8 @@ export declare namespace Machine {
4023
3598
  type ReferenceAt<S extends StateSchemas, P extends StateNodeIdentifier<S> | HistoryIdentifier<S>> = PathName<P>;
4024
3599
  type ReferenceUnion<S extends StateSchemas, Paths extends StateNodeIdentifier<S> | HistoryIdentifier<S>> = PathName<Paths>;
4025
3600
  type DestinationPath<S extends StateSchemas> = Exclude<StateNodeIdentifier<S>, "">;
4026
- type RootSchemas<Root extends StateNodeConfig> = {
4027
- readonly "": Root;
4028
- };
4029
- /** A topology declaration; its state values are constructed by a resolver. */
4030
- type BranchDeclaration<Root extends StateNodeConfig, S extends StateSchemas = RootSchemas<Root>> = {
4031
- /** Optional presentation label for this named branch. */
4032
- readonly title?: string;
4033
- } & ({
4034
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4035
- readonly target: ReferenceUnion<S, DestinationPath<S>>;
4036
- /**
4037
- * Replaces the complete value of a retained ancestor of the source and target without replacing its active
4038
- * children. A choice target resolves after the update, and every branch it can reach must stay below the owner.
4039
- */
4040
- readonly update?: ReferenceUnion<S, ValuedStateIdentifier<S>>;
4041
- /** Enters a compound or parallel subtree through its declared initialization. */
4042
- readonly initial?: never;
4043
- /** Restores the declared history reference, using its fallback on first entry. */
4044
- readonly history?: never;
4045
- /** Accepts the event without selecting a new destination. */
4046
- readonly none?: never;
4047
- /** Reconstructs root and its initial children from fresh machine input. */
4048
- readonly initialize?: never;
4049
- } | {
4050
- /** Reconstructs root and its initial children from fresh machine input supplied by the resolver. */
4051
- readonly initialize: true;
4052
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4053
- readonly target?: never;
4054
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4055
- readonly update?: never;
4056
- /** Enters a compound or parallel subtree through its declared initialization. */
4057
- readonly initial?: never;
4058
- /** Restores the declared history reference, using its fallback on first entry. */
4059
- readonly history?: never;
4060
- /** Accepts the event without selecting a new destination. */
4061
- readonly none?: never;
4062
- } | {
4063
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4064
- readonly update: ReferenceUnion<S, ValuedStateIdentifier<S>>;
4065
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4066
- readonly target?: never;
4067
- /** Enters a compound or parallel subtree through its declared initialization. */
4068
- readonly initial?: never;
4069
- /** Restores the declared history reference, using its fallback on first entry. */
4070
- readonly history?: never;
4071
- /** Accepts the event without selecting a new destination. */
4072
- readonly none?: never;
4073
- /** Reconstructs root and its initial children from fresh machine input. */
4074
- readonly initialize?: never;
4075
- } | {
4076
- /** Restores the declared history reference, using its fallback on first entry. */
4077
- readonly history: ReferenceUnion<S, HistoryIdentifier<S>>;
4078
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4079
- readonly target?: never;
4080
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4081
- readonly update?: never;
4082
- /** Enters a compound or parallel subtree through its declared initialization. */
4083
- readonly initial?: never;
4084
- /** Accepts the event without selecting a new destination. */
4085
- readonly none?: never;
4086
- /** Reconstructs root and its initial children from fresh machine input. */
4087
- readonly initialize?: never;
4088
- } | {
4089
- /** Accepts the event without selecting a new destination. */
4090
- readonly none: true;
4091
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4092
- readonly target?: never;
4093
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4094
- readonly update?: never;
4095
- /** Enters a compound or parallel subtree through its declared initialization. */
4096
- readonly initial?: never;
4097
- /** Restores the declared history reference, using its fallback on first entry. */
4098
- readonly history?: never;
4099
- /** Reconstructs root and its initial children from fresh machine input. */
4100
- readonly initialize?: never;
4101
- });
4102
- type BranchDefinitions<Root extends StateNodeConfig> = Readonly<Record<string, Readonly<Record<string, BranchDeclaration<Root>>>>>;
4103
3601
  /** Source programs and named topology declarations captured by a machine definition. */
4104
- interface Registrations {
3602
+ export interface Registrations {
4105
3603
  /** Lazy Effects or functions with one required input, invoked by registered name. */
4106
3604
  readonly effects?: EffectSources;
4107
3605
  /** Lazy Streams or functions with one required input, invoked by registered name. */
@@ -4112,14 +3610,11 @@ export declare namespace Machine {
4112
3610
  readonly logic?: LogicSources;
4113
3611
  /** Child machine descriptors registered for state-owned invocation. */
4114
3612
  readonly children?: ChildSources;
4115
- /** Named groups of inspectable destinations used by transition resolvers. */
4116
- readonly branches?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
4117
3613
  }
4118
3614
  type RegisteredInput<R> = R extends {
4119
3615
  readonly "~input": infer I extends Schema.Top;
4120
3616
  } ? I : typeof Schema.Void;
4121
3617
  type Registered<R, Kind extends PropertyKey> = Kind extends keyof R ? NonNullable<R[Kind]> : {};
4122
- type RefPath<R> = PathOf<R>;
4123
3618
  type ConstructionData<Node> = [NodeSchema<Node>] extends [never] ? {
4124
3619
  readonly data?: never;
4125
3620
  readonly decoded?: never;
@@ -4143,7 +3638,7 @@ export declare namespace Machine {
4143
3638
  };
4144
3639
  }[ActiveStateKey<Children> | ChoiceStateKey<Children>];
4145
3640
  /** Values for one state and, optionally, its explicitly selected descendants. */
4146
- type ConstructionObject<Node, Source extends string = never> = {
3641
+ export type ConstructionObject<Node, Source extends string = never> = {
4147
3642
  readonly input?: never;
4148
3643
  } & ConstructionData<Node> & (Node extends {
4149
3644
  readonly states: infer Children extends StateSchemas;
@@ -4165,34 +3660,52 @@ export declare namespace Machine {
4165
3660
  } : {
4166
3661
  /** Fresh machine input used by root construction and root initial callbacks. */ readonly input: RegisteredInput<R>["Type"];
4167
3662
  });
4168
- type ObjectSelection<S extends StateSchemas, Src extends StateNodeIdentifier<S>, P extends StateNodeIdentifier<S>, R> = P extends "" ? ConstructionCall<RootInput<R>, InitialTarget<P>> : P extends ChoiceIdentifier<S> ? () => ChoiceTarget<S, P> : P extends StateIdentifier<S> ? ConstructionCall<ConstructionObject<NodeByIdentifier<S, P>, Src extends `${P}.${infer Rest}` ? Rest : Src extends P ? "" : never> & {
3663
+ type UpdateValue<Node> = OrdinaryData<NodeMakeInput<Node>> | {
3664
+ readonly decoded: true;
3665
+ readonly data: NodeValue<Node>;
3666
+ };
3667
+ type TargetConstruction<S extends StateSchemas, Src extends StateNodeIdentifier<S>, P extends DestinationPath<S>> = P extends StateIdentifier<S> ? ConstructionObject<NodeByIdentifier<S, P>, Src extends `${P}.${infer Rest}` ? Rest : Src extends P ? "" : never> : {};
3668
+ type TargetArguments<A> = {} extends A ? [construction?: A & {
4169
3669
  readonly update?: never;
4170
- }, Target<S, P>> : never;
4171
- type SelectionOf<S extends StateSchemas, Src extends StateNodeIdentifier<S>, D, R = {}> = D extends {
4172
- readonly initialize: true;
4173
- } ? TargetSelection<ObjectSelection<S, Src, Extract<"", StateNodeIdentifier<S>>, R>, "", "state", "branch"> : D extends {
4174
- readonly target: infer Ref;
4175
- } ? RefPath<Ref> extends infer P extends StateNodeIdentifier<S> ? D extends {
4176
- readonly update: infer Update;
4177
- } ? RefPath<Update> extends infer Owner extends Extract<ParentStateIdentifier<Src>, ParentStateIdentifier<P> & ValuedStateIdentifier<S>> ? P extends StateIdentifier<S> ? TargetSelection<ConstructionCall<ConstructionObject<NodeByIdentifier<S, P>, Src extends `${P}.${infer Rest}` ? Rest : Src extends P ? "" : never> & {
4178
- readonly update: ConstructionData<NodeByIdentifier<S, Owner>>;
4179
- }, CombinedTarget<Target<S, P>, S, Owner>>, P, "state", "branch"> : P extends ChoiceIdentifier<S> ? TargetSelection<(construction: {
4180
- readonly update: ConstructionData<NodeByIdentifier<S, Owner>>;
4181
- }) => CombinedTarget<ChoiceTarget<S, P>, S, Owner>, P, "choice", "branch"> : never : never : TargetSelection<ObjectSelection<S, Src, P, R>, P, P extends ChoiceIdentifier<S> ? "choice" : "state", "branch"> : never : D extends {
4182
- readonly history: infer Ref;
4183
- } ? RefPath<Ref> extends infer P extends HistoryIdentifier<S> ? TargetSelection<() => HistoryTarget<S, P>, P, "history", "full"> : never : D extends {
4184
- readonly update: infer Ref;
4185
- } ? RefPath<Ref> extends infer P extends Extract<Src | ParentStateIdentifier<Src>, ValuedStateIdentifier<S>> ? TargetSelection<ConstructionCall<ConstructionData<NodeByIdentifier<S, P>>, StateUpdate<S, P>>, P, "update", "branch"> : never : D extends {
4186
- readonly none: true;
4187
- } ? TargetSelection<() => NoTarget, never, "none", "local"> : never;
4188
- type BuilderArgs<B, K extends PropertyKey> = K extends keyof B ? B[K] extends (...args: infer A) => unknown ? A : never : never;
4189
- type ObjectConstruction<C, B> = {
4190
- readonly [M in Extract<keyof B, "from" | "decoded">]: BuilderArgs<B, M> extends readonly [unknown?] ? {
4191
- readonly [K in M]: (context: C) => BuilderArgs<B, M>[0];
4192
- } & {
4193
- readonly [K in Exclude<"from" | "decoded", M>]?: never;
4194
- } : never;
4195
- }[Extract<keyof B, "from" | "decoded">];
3670
+ }] : [construction: A & {
3671
+ readonly update?: never;
3672
+ }];
3673
+ type TargetResult<S extends StateSchemas, P extends string> = P extends ChoiceIdentifier<S> ? ChoiceTarget<S, P> : P extends StateIdentifier<S> ? Target<S, P> : never;
3674
+ type OnePath<P extends string> = Types.IsUnion<P> extends true ? {
3675
+ readonly [K in `select.target takes one path, got: ${JoinUnion<P>}. Call it once per path`]: never;
3676
+ } : unknown;
3677
+ type OneOwner<O extends string> = Types.IsUnion<O> extends true ? `update takes one owner, got: ${JoinUnion<O>}` : unknown;
3678
+ /**
3679
+ * Selects one entry of a transition's `branches` list. The compiler checks that `resolve` selects exactly the
3680
+ * declared entries, so each call here must match one of them.
3681
+ *
3682
+ * @category models
3683
+ * @since 0.47.0
3684
+ */
3685
+ export interface BranchSelect<S extends StateSchemas, Src extends StateNodeIdentifier<S>, R> {
3686
+ /** Selects `{ target }`, or `{ target, update }` when the construction has an `update` record. */
3687
+ readonly target: {
3688
+ <P extends DestinationPath<S>, O extends ReferenceUnion<S, TargetOwner<S, Src, P>>>(path: P & OnePath<P>, construction: TargetConstruction<S, Src, P> & {
3689
+ /** The new value of the retained owner named by this branch. */
3690
+ readonly update: {
3691
+ readonly [Owner in O]: UpdateValue<NodeByIdentifier<S, Extract<PathOf<Owner>, StateIdentifier<S>>>>;
3692
+ } & OneOwner<O>;
3693
+ }): SelectedBranch<`target:${P}+update:${O}`, CombinedTarget<TargetResult<S, P>, S, Extract<PathOf<O>, ValuedStateIdentifier<S>>>>;
3694
+ <P extends DestinationPath<S>>(path: P & OnePath<P>, ...construction: TargetArguments<TargetConstruction<S, Src, P>>): SelectedBranch<`target:${P}`, TargetResult<S, P>>;
3695
+ };
3696
+ /** Selects `{ update }`, replacing the value of one retained source or ancestor. */
3697
+ readonly update: <O extends ReferenceUnion<S, UpdatableOwner<S, Src>>>(updates: {
3698
+ readonly [Owner in O]: UpdateValue<NodeByIdentifier<S, Extract<PathOf<Owner>, StateIdentifier<S>>>>;
3699
+ } & OneOwner<O>) => SelectedBranch<`update:${O}`, StateUpdate<S, Extract<PathOf<O>, ValuedStateIdentifier<S>>>>;
3700
+ /** Selects `{ history }`. */
3701
+ readonly history: <P extends ReferenceUnion<S, HistoryIdentifier<S>>>(path: P) => SelectedBranch<`history:${P}`, HistoryTarget<S, Extract<PathOf<P>, HistoryIdentifier<S>>>>;
3702
+ /** Selects `{ initialize: true }`. */
3703
+ readonly initialize: ConstructionCall<RootInput<R>, SelectedBranch<"initialize", InitialTarget<"">>>;
3704
+ /** Selects `{ stay: true }`. */
3705
+ readonly stay: () => SelectedBranch<"stay", NoTarget>;
3706
+ /** Selects `{ decline: true }`, passing the event on to the next candidate. */
3707
+ readonly decline: () => SelectedBranch<"decline", Declined>;
3708
+ }
4196
3709
  type ObjectPolicy<C, Reenter extends boolean, Acceptance extends TransitionAcceptance> = {
4197
3710
  /** Set to true to exit and reenter the handler source. */
4198
3711
  readonly reenter?: Reenter extends true ? boolean : never;
@@ -4222,139 +3735,133 @@ export declare namespace Machine {
4222
3735
  * Machines without an input schema use `true`.
4223
3736
  */
4224
3737
  readonly initialize: RegisteredInput<R> extends typeof Schema.Void ? true : DataValue<C, RegisteredInput<R>["Type"]>;
3738
+ /** Selects a declared descendant, constructing the values it requires. */
4225
3739
  readonly target?: never;
3740
+ /** Replaces the value of one retained state without replacing its active children. */
4226
3741
  readonly update?: never;
3742
+ /** Restores the declared history reference, using its fallback on first entry. */
3743
+ readonly history?: never;
3744
+ /** Accepts the event and stays in the current states. */
3745
+ readonly stay?: never;
3746
+ /** The destinations this transition can select, each one checked against `resolve`. */
4227
3747
  readonly branches?: never;
3748
+ /** Selects one declared branch and may enqueue synchronous commands. */
4228
3749
  readonly resolve?: never;
4229
- readonly history?: never;
4230
- readonly none?: never;
4231
3750
  };
3751
+ type OwnerUpdates<S extends StateSchemas, Owners extends ValuedStateIdentifier<S>, C> = {
3752
+ readonly [O in Owners as PathName<O>]?: ShortConstruction<C, NodeByIdentifier<S, O>>;
3753
+ };
3754
+ type TargetOwner<S extends StateSchemas, Src extends StateNodeIdentifier<S>, P extends string> = Src extends ChoiceIdentifier<S> ? never : Extract<ParentStateIdentifier<Src>, ParentStateIdentifier<P> & ValuedStateIdentifier<S>>;
3755
+ type UpdatableOwner<S extends StateSchemas, Src extends StateNodeIdentifier<S>> = Src extends ChoiceIdentifier<S> ? never : Extract<Src | ParentStateIdentifier<Src>, ValuedStateIdentifier<S>>;
4232
3756
  type InlineDestination<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C> = {
4233
3757
  readonly [P in DestinationPath<S>]: {
4234
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
3758
+ /** Selects a declared descendant, constructing the values it requires. */
4235
3759
  readonly target: ReferenceAt<S, P>;
4236
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4237
- readonly update?: never;
4238
- /** Enters a compound or parallel subtree through its declared initialization. */
4239
- readonly initial?: never;
3760
+ /**
3761
+ * Replaces the value of one retained ancestor of the source and target without replacing its active children.
3762
+ * A choice target resolves after the update, and every branch it can reach must stay below the owner.
3763
+ */
3764
+ readonly update?: OwnerUpdates<S, TargetOwner<S, Src, P>, C>;
3765
+ /** Reconstructs root and its initial children from fresh machine input. */
3766
+ readonly initialize?: never;
4240
3767
  /** Restores the declared history reference, using its fallback on first entry. */
4241
3768
  readonly history?: never;
4242
- /** Accepts the event without selecting a new destination. */
4243
- readonly none?: never;
4244
- /** Named groups of inspectable destinations used by transition resolvers. */
3769
+ /** Accepts the event and stays in the current states. */
3770
+ readonly stay?: never;
3771
+ /** The destinations this transition can select, each one checked against `resolve`. */
4245
3772
  readonly branches?: never;
4246
3773
  /** Selects one declared branch and may enqueue synchronous commands. */
4247
3774
  readonly resolve?: never;
4248
- /** Set to true when the resolver can explicitly return decline(). */
4249
- readonly declinable?: never;
4250
3775
  } & InlineDestinationConstruction<S, Src, P, C>;
4251
3776
  }[DestinationPath<S>];
4252
- type InlinePairConstruction<S extends StateSchemas, Src extends StateNodeIdentifier<S>, P extends string, Owner extends ValuedStateIdentifier<S>, C> = P extends StateIdentifier<S> ? {
4253
- readonly from: (context: C) => {
4254
- readonly target: [NodeSchema<NodeByIdentifier<S, P>>] extends [never] ? undefined : NodeMakeInput<NodeByIdentifier<S, P>>;
4255
- readonly update: SchemaByIdentifier<S, Owner>["~type.make.in"];
4256
- };
4257
- readonly decoded?: never;
4258
- } | ([NodeSchema<NodeByIdentifier<S, P>>] extends [never] ? never : {
4259
- readonly decoded: (context: C) => {
4260
- readonly target: NodeValue<NodeByIdentifier<S, P>>;
4261
- readonly update: StateByIdentifier<S, Owner>;
4262
- };
4263
- readonly from?: never;
4264
- }) : P extends ChoiceIdentifier<S> ? ObjectConstruction<C, StateUpdateBuilder<S, Owner>> : never;
4265
- type InlineCombined<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C> = Src extends ChoiceIdentifier<S> ? never : [
4266
- Extract<ParentStateIdentifier<Src>, ValuedStateIdentifier<S>>
4267
- ] extends [never] ? never : {
3777
+ type InlineUnknownTarget<S extends StateSchemas> = {
3778
+ /** Selects a declared descendant, constructing the values it requires. */
3779
+ readonly target: ReferenceUnion<S, DestinationPath<S>> | (string & {});
3780
+ readonly update?: never;
3781
+ readonly initialize?: never;
3782
+ readonly history?: never;
3783
+ readonly stay?: never;
3784
+ readonly branches?: never;
3785
+ readonly resolve?: never;
3786
+ };
3787
+ type InlineUpdate<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C> = [UpdatableOwner<S, Src>] extends [
3788
+ never
3789
+ ] ? never : {
3790
+ /** Replaces the value of one retained source or ancestor without replacing its active children. */
3791
+ readonly update: OwnerUpdates<S, UpdatableOwner<S, Src>, C>;
3792
+ /** Selects a declared descendant, constructing the values it requires. */
3793
+ readonly target?: never;
3794
+ /** Reconstructs root and its initial children from fresh machine input. */
3795
+ readonly initialize?: never;
3796
+ /** Restores the declared history reference, using its fallback on first entry. */
3797
+ readonly history?: never;
3798
+ /** Accepts the event and stays in the current states. */
3799
+ readonly stay?: never;
3800
+ /** The destinations this transition can select, each one checked against `resolve`. */
3801
+ readonly branches?: never;
3802
+ /** Selects one declared branch and may enqueue synchronous commands. */
3803
+ readonly resolve?: never;
3804
+ };
3805
+ /**
3806
+ * One destination a `resolve` function can select. Here `update` names the owner as a string, because the value is
3807
+ * passed to the `select` call.
3808
+ *
3809
+ * @category models
3810
+ * @since 0.47.0
3811
+ */
3812
+ export type BranchEntry<S extends StateSchemas, Src extends StateNodeIdentifier<S>, Acceptance extends TransitionAcceptance> = {
4268
3813
  readonly [P in DestinationPath<S>]: {
4269
- readonly [Owner in Extract<ParentStateIdentifier<Src>, ParentStateIdentifier<P> & ValuedStateIdentifier<S>>]: {
4270
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4271
- readonly target: ReferenceAt<S, P>;
4272
- /**
4273
- * Replaces the complete value of a retained ancestor of the source and target without replacing its active
4274
- * children. A choice target resolves after the update, and every branch it can reach must stay below the
4275
- * owner; `data` then constructs only the owner value.
4276
- */
4277
- readonly update: ReferenceAt<S, Owner>;
4278
- /** Enters a compound or parallel subtree through its declared initialization. */
4279
- readonly initial?: never;
4280
- /** Restores the declared history reference, using its fallback on first entry. */
4281
- readonly history?: never;
4282
- /** Accepts the event without selecting a new destination. */
4283
- readonly none?: never;
4284
- /** Named groups of inspectable destinations used by transition resolvers. */
4285
- readonly branches?: never;
4286
- /** Selects one declared branch and may enqueue synchronous commands. */
4287
- readonly resolve?: never;
4288
- /** Set to true when the resolver can explicitly return decline(). */
4289
- readonly declinable?: never;
4290
- } & InlinePairConstruction<S, Src, P, Owner, C>;
4291
- }[Extract<ParentStateIdentifier<Src>, ParentStateIdentifier<P> & ValuedStateIdentifier<S>>];
4292
- }[DestinationPath<S>];
4293
- type InlineUpdate<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C> = Src extends ChoiceIdentifier<S> ? never : {
4294
- readonly [P in Extract<Src | ParentStateIdentifier<Src>, ValuedStateIdentifier<S>>]: {
4295
- /** Set to true to exit and reenter the handler source. */
4296
- readonly reenter?: P extends Src ? never : boolean;
4297
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4298
- readonly update: ReferenceAt<S, P>;
4299
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4300
- readonly target?: never;
4301
- /** Enters a compound or parallel subtree through its declared initialization. */
4302
- readonly initial?: never;
4303
- /** Restores the declared history reference, using its fallback on first entry. */
4304
- readonly history?: never;
4305
- /** Accepts the event without selecting a new destination. */
4306
- readonly none?: never;
4307
- /** Named groups of inspectable destinations used by transition resolvers. */
4308
- readonly branches?: never;
4309
- /** Selects one declared branch and may enqueue synchronous commands. */
4310
- readonly resolve?: never;
4311
- /** Set to true when the resolver can explicitly return decline(). */
4312
- readonly declinable?: never;
4313
- } & ObjectConstruction<C, StateUpdateBuilder<S, P>>;
4314
- }[Extract<Src | ParentStateIdentifier<Src>, ValuedStateIdentifier<S>>];
4315
- type BranchSelections<S extends StateSchemas, Src extends StateNodeIdentifier<S>, Group, R> = {
4316
- readonly [K in Extract<keyof Group, string>]: {
4317
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4318
- readonly target: SelectionOf<S, Src, Group[K], R>;
3814
+ /** Selects a declared descendant through `select.target`. */
3815
+ readonly target: ReferenceAt<S, P>;
3816
+ /** The retained ancestor that this branch's `select.target` call updates. */
3817
+ readonly update?: ReferenceUnion<S, TargetOwner<S, Src, P>>;
4319
3818
  };
3819
+ }[DestinationPath<S>] | ([UpdatableOwner<S, Src>] extends [never] ? never : {
3820
+ /** The retained state updated through `select.update`. */
3821
+ readonly update: ReferenceUnion<S, UpdatableOwner<S, Src>>;
3822
+ readonly target?: never;
3823
+ }) | {
3824
+ /** Restores this history reference through `select.history`. */
3825
+ readonly history: ReferenceUnion<S, HistoryIdentifier<S>>;
3826
+ } | {
3827
+ /** Reconstructs root from fresh machine input through `select.initialize`. */
3828
+ readonly initialize: true;
3829
+ } | (Src extends ChoiceIdentifier<S> ? never : {
3830
+ /** Accepts the event and stays in the current states through `select.stay`. */
3831
+ readonly stay: true;
3832
+ }) | (Acceptance extends "declinable" ? {
3833
+ /** Passes the event on to the next candidate through `select.decline`. */
3834
+ readonly decline: true;
3835
+ } : never);
3836
+ type ObjectBranches<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C, Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, R, Reenter extends boolean, Acceptance extends TransitionAcceptance> = {
3837
+ /** The destinations this transition can select, each one checked against `resolve`. */
3838
+ readonly branches?: ReadonlyArray<BranchEntry<S, Src, Acceptance>>;
3839
+ /** Selects one declared branch and may enqueue synchronous commands. */
3840
+ readonly resolve?: (context: C & {
3841
+ /** Selects one of the declared `branches`. */
3842
+ readonly select: BranchSelect<S, Src, R>;
3843
+ }, enqueue: Enqueue<EventOf<Ev>, EmittedEventOf<Em>>) => unknown;
3844
+ /** Set to true to exit and reenter the handler source. */
3845
+ readonly reenter?: Reenter extends true ? boolean : never;
3846
+ /** Branch on the condition inside `resolve`, returning `select.decline()`. */
3847
+ readonly guard?: never;
3848
+ /** Enqueue commands inside `resolve`. */
3849
+ readonly commands?: never;
3850
+ /** Constructs values through the `select` calls inside `resolve`. */
3851
+ readonly data?: never;
3852
+ /** Constructs values through the `select` calls inside `resolve`. */
3853
+ readonly decoded?: never;
3854
+ /** Selects a declared descendant, constructing the values it requires. */
3855
+ readonly target?: never;
3856
+ /** Replaces the value of one retained state without replacing its active children. */
3857
+ readonly update?: never;
3858
+ /** Reconstructs root and its initial children from fresh machine input. */
3859
+ readonly initialize?: never;
3860
+ /** Restores the declared history reference, using its fallback on first entry. */
3861
+ readonly history?: never;
3862
+ /** Accepts the event and stays in the current states. */
3863
+ readonly stay?: never;
4320
3864
  };
4321
- type ObjectBranchResolver<Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, C, B extends Readonly<Record<string, TransitionBranchInput>>, Declinable extends boolean> = (context: C & {
4322
- readonly select: BranchSelectors<B>;
4323
- } & DeclineCapability, enqueue: Enqueue<EventOf<Ev>, EmittedEventOf<Em>>) => BranchSelectionResult<B> | (Declinable extends true ? Declined : never);
4324
- type InvalidBranchSelection<S extends StateSchemas, Src extends StateNodeIdentifier<S>, Group, R> = {
4325
- readonly [K in keyof Group]: Src extends ChoiceIdentifier<S> ? Group[K] extends {
4326
- /** Accepts the event without selecting a new destination. */
4327
- readonly none: true;
4328
- } | {
4329
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4330
- readonly update: unknown;
4331
- } ? K : [SelectionBuilder<SelectionOf<S, Src, Group[K], R>>] extends [never] ? K : never : [SelectionBuilder<SelectionOf<S, Src, Group[K], R>>] extends [never] ? K : never;
4332
- }[keyof Group];
4333
- type ObjectBranches<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C, Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, R, Acceptance extends TransitionAcceptance> = {
4334
- readonly [K in Extract<keyof Registered<R, "branches">, string>]: ([InvalidBranchSelection<S, Src, Registered<R, "branches">[K], R>] extends [never] ? unknown : never) & {
4335
- /** Named groups of inspectable destinations used by transition resolvers. */
4336
- readonly branches: K;
4337
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4338
- readonly target?: never;
4339
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4340
- readonly update?: never;
4341
- /** Enters a compound or parallel subtree through its declared initialization. */
4342
- readonly initial?: never;
4343
- /** Restores the declared history reference, using its fallback on first entry. */
4344
- readonly history?: never;
4345
- /** Accepts the event without selecting a new destination. */
4346
- readonly none?: never;
4347
- /** Constructs schema make input from the typed source context. */
4348
- readonly from?: never;
4349
- /** Supplies an already decoded schema value from the typed source context. */
4350
- readonly decoded?: never;
4351
- } & {
4352
- /** Set to true when the resolver can explicitly return decline(). */
4353
- readonly declinable?: "declinable" extends Acceptance ? boolean : false;
4354
- /** Selects one declared branch and may enqueue synchronous commands. */
4355
- readonly resolve: ObjectBranchResolver<Ev, Em, C, BranchSelections<S, Src, Registered<R, "branches">[K], R>, true>;
4356
- };
4357
- }[Extract<keyof Registered<R, "branches">, string>];
4358
3865
  type DataValue<C, A> = A | ((context: C) => A);
4359
3866
  type DeclarationData<T> = T extends {
4360
3867
  readonly from: (context: infer C) => infer A;
@@ -4376,49 +3883,57 @@ export declare namespace Machine {
4376
3883
  * @category models
4377
3884
  * @since 0.34.0
4378
3885
  */
4379
- type Transition<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C, Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, R, Reenter extends boolean = false, Acceptance extends TransitionAcceptance = "required"> = ObjectPolicy<C, Reenter, Acceptance> & DeclarationData<(InlineDestination<S, Src, C> | InlineUpdate<S, Src, C> | InlineCombined<S, Src, C> | InlineRoot<C, R> | {
3886
+ export type Transition<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C, Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, R, Reenter extends boolean = false, Acceptance extends TransitionAcceptance = "required"> = (ObjectPolicy<C, Reenter, Acceptance> & {
3887
+ /** Enqueues synchronous commands when this transition is selected. */
3888
+ readonly commands?: (context: C, enqueue: Enqueue<EventOf<Ev>, EmittedEventOf<Em>>) => void;
3889
+ } & DeclarationData<InlineDestination<S, Src, C> | InlineUnknownTarget<S> | InlineUpdate<S, Src, C> | InlineRoot<C, R> | {
4380
3890
  /** Restores the declared history reference, using its fallback on first entry. */
4381
3891
  readonly history: ReferenceUnion<S, HistoryIdentifier<S>>;
4382
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
3892
+ /** Selects a declared descendant, constructing the values it requires. */
4383
3893
  readonly target?: never;
4384
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
3894
+ /** Replaces the value of one retained state without replacing its active children. */
4385
3895
  readonly update?: never;
4386
- /** Enters a compound or parallel subtree through its declared initialization. */
4387
- readonly initial?: never;
4388
- /** Accepts the event without selecting a new destination. */
4389
- readonly none?: never;
4390
- /** Named groups of inspectable destinations used by transition resolvers. */
3896
+ /** Reconstructs root and its initial children from fresh machine input. */
3897
+ readonly initialize?: never;
3898
+ /** Accepts the event and stays in the current states. */
3899
+ readonly stay?: never;
3900
+ /** The destinations this transition can select, each one checked against `resolve`. */
4391
3901
  readonly branches?: never;
4392
3902
  /** Selects one declared branch and may enqueue synchronous commands. */
4393
3903
  readonly resolve?: never;
4394
- /** Constructs schema make input from the typed source context. */
4395
- readonly from?: never;
4396
- /** Supplies an already decoded schema value from the typed source context. */
4397
- readonly decoded?: never;
4398
- /** Set to true when the resolver can explicitly return decline(). */
4399
- readonly declinable?: never;
4400
3904
  } | (Src extends ChoiceIdentifier<S> ? never : {
4401
- /** Accepts the event without selecting a new destination. */
4402
- readonly none: true;
4403
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
3905
+ /** Accepts the event and stays in the current states. */
3906
+ readonly stay: true;
3907
+ /** Selects a declared descendant, constructing the values it requires. */
4404
3908
  readonly target?: never;
4405
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
3909
+ /** Replaces the value of one retained state without replacing its active children. */
4406
3910
  readonly update?: never;
4407
- /** Enters a compound or parallel subtree through its declared initialization. */
4408
- readonly initial?: never;
3911
+ /** Reconstructs root and its initial children from fresh machine input. */
3912
+ readonly initialize?: never;
4409
3913
  /** Restores the declared history reference, using its fallback on first entry. */
4410
3914
  readonly history?: never;
4411
- /** Named groups of inspectable destinations used by transition resolvers. */
3915
+ /** The destinations this transition can select, each one checked against `resolve`. */
3916
+ readonly branches?: never;
3917
+ /** Selects one declared branch and may enqueue synchronous commands. */
3918
+ readonly resolve?: never;
3919
+ }) | (Src extends ChoiceIdentifier<S> ? never : Reenter extends true ? {
3920
+ /** Exits and reenters the source. */
3921
+ readonly reenter: true;
3922
+ /** Selects a declared descendant, constructing the values it requires. */
3923
+ readonly target?: never;
3924
+ /** Replaces the value of one retained state without replacing its active children. */
3925
+ readonly update?: never;
3926
+ /** Reconstructs root and its initial children from fresh machine input. */
3927
+ readonly initialize?: never;
3928
+ /** Restores the declared history reference, using its fallback on first entry. */
3929
+ readonly history?: never;
3930
+ /** Accepts the event and stays in the current states. */
3931
+ readonly stay?: never;
3932
+ /** The destinations this transition can select, each one checked against `resolve`. */
4412
3933
  readonly branches?: never;
4413
- /** Constructs schema make input from the typed source context. */
4414
- readonly from?: never;
4415
- /** Supplies an already decoded schema value from the typed source context. */
4416
- readonly decoded?: never;
4417
- /** Set to true when the resolver can explicitly return decline(). */
4418
- readonly declinable?: "declinable" extends Acceptance ? boolean : false;
4419
3934
  /** Selects one declared branch and may enqueue synchronous commands. */
4420
- readonly resolve?: (context: C & DeclineCapability, enqueue: Enqueue<EventOf<Ev>, EmittedEventOf<Em>>) => undefined | Declined;
4421
- }) | ObjectBranches<S, Src, C, Ev, Em, R, Acceptance>)>;
3935
+ readonly resolve?: never;
3936
+ } : never)>) | ObjectBranches<S, Src, C, Ev, Em, R, Reenter, Acceptance>;
4422
3937
  type SourceValue<R, K extends PropertyKey> = {
4423
3938
  readonly [Kind in "effects" | "streams" | "timers" | "logic" | "children"]: K extends keyof Registered<R, Kind> ? Registered<R, Kind>[K] : never;
4424
3939
  }["effects" | "streams" | "timers" | "logic" | "children"];
@@ -4464,16 +3979,16 @@ export declare namespace Machine {
4464
3979
  } : never : SourceInput<SourceValue<R, K>, C>;
4465
3980
  type ObjectOutcome<S extends StateSchemas, Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, Src extends StateIdentifier<S>, In extends ReadonlyArray<TaggedSchema>, Pa extends ReadonlyArray<TaggedSchema>, R, V, Channel extends "onDone" | "onFailure" | "onElement" | "onSnapshot"> = [V] extends [never] ? {} : Channel extends "onDone" ? {
4466
3981
  /** Handles successful invocation or state completion with its exact output type. */
4467
- readonly onDone: Transition<S, Src, InvokeDoneContext<S, Ev, Em, Src, V, In, Pa>, Ev, Em, R, true, TransitionAcceptance>;
3982
+ readonly onDone: Transition<S, Src, InvokeDoneContext<S, Ev, Em, Src, V, In, Pa>, Ev, Em, R, true, "required">;
4468
3983
  } : Channel extends "onFailure" ? {
4469
3984
  /** Handles the typed failure of the invoked source; required exactly when that channel is reachable. */
4470
- readonly onFailure: Transition<S, Src, InvokeFailureContext<S, Ev, Em, Src, V, In, Pa>, Ev, Em, R, true, TransitionAcceptance>;
3985
+ readonly onFailure: Transition<S, Src, InvokeFailureContext<S, Ev, Em, Src, V, In, Pa>, Ev, Em, R, true, "required">;
4471
3986
  } : Channel extends "onElement" ? {
4472
3987
  /** Handles each Stream element; required when the element type is reachable. */
4473
- readonly onElement: Transition<S, Src, InvokeElementContext<S, Ev, Em, Src, V, In, Pa>, Ev, Em, R, true, TransitionAcceptance>;
3988
+ readonly onElement: Transition<S, Src, InvokeElementContext<S, Ev, Em, Src, V, In, Pa>, Ev, Em, R, true, "required">;
4474
3989
  } : {
4475
3990
  /** Optionally handles active snapshots of invoked logic or a child machine. */
4476
- readonly onSnapshot: Transition<S, Src, InvokeSnapshotContext<S, Ev, Em, Src, V, never, never, In, Pa>, Ev, Em, R, true, TransitionAcceptance>;
3991
+ readonly onSnapshot: Transition<S, Src, InvokeSnapshotContext<S, Ev, Em, Src, V, never, never, In, Pa>, Ev, Em, R, true, "required">;
4477
3992
  };
4478
3993
  type RegisteredInvokeError<R, K extends PropertyKey> = SourceKind<R, K> extends "children" ? SourceValue<R, K> extends ChildMachine<string, infer M> ? Error<M> | ActionError<Services<M>> : never : InvokeRuntimeError<ResolvedInvoke<R, K>>;
4479
3994
  /**
@@ -4482,7 +3997,7 @@ export declare namespace Machine {
4482
3997
  * @category models
4483
3998
  * @since 0.34.0
4484
3999
  */
4485
- type Invocation<S extends StateSchemas, Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, Src extends StateIdentifier<S>, In extends ReadonlyArray<TaggedSchema>, Pa extends ReadonlyArray<TaggedSchema>, R> = {
4000
+ export type Invocation<S extends StateSchemas, Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, Src extends StateIdentifier<S>, In extends ReadonlyArray<TaggedSchema>, Pa extends ReadonlyArray<TaggedSchema>, R> = {
4486
4001
  readonly [K in Extract<SourceKeys<R>, string>]: Types.Simplify<{
4487
4002
  /** Name of the source registered in make. */
4488
4003
  readonly src: K;
@@ -4613,13 +4128,14 @@ export declare namespace Machine {
4613
4128
  readonly exit?: never; /** Constructs the decoded output declared by the state schema. */
4614
4129
  readonly output?: never;
4615
4130
  };
4131
+ type StateFieldError<Kind extends string, Src extends string, Field extends string, Fix extends string> = `${Kind} state "${PathName<Src>}" cannot declare ${Field}. ${Fix}`;
4616
4132
  /**
4617
4133
  * Handlers for a node of the declared root tree.
4618
4134
  *
4619
4135
  * @category models
4620
4136
  * @since 0.34.0
4621
4137
  */
4622
- type StateHandler<S extends StateSchemas, Node, Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, Src extends StateNodeIdentifier<S>, In extends ReadonlyArray<TaggedSchema>, Pa extends ReadonlyArray<TaggedSchema>, R> = ObjectLifecycle<S, Node, Ev, Em, Src, In, Pa> & InitialHandler<S, Node, Src, StateActionContext<S, Ev, Em, Extract<Src, StateIdentifier<S>>, In, Pa> & {
4138
+ export type StateHandler<S extends StateSchemas, Node, Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, Src extends StateNodeIdentifier<S>, In extends ReadonlyArray<TaggedSchema>, Pa extends ReadonlyArray<TaggedSchema>, R> = ObjectLifecycle<S, Node, Ev, Em, Src, In, Pa> & InitialHandler<S, Node, Src, StateActionContext<S, Ev, Em, Extract<Src, StateIdentifier<S>>, In, Pa> & {
4623
4139
  /** Root-owned data constructed before initial descendant values. */
4624
4140
  readonly root: StateByIdentifier<S, Extract<"", StateIdentifier<S>>>;
4625
4141
  } & (Src extends "" ? {
@@ -4628,13 +4144,13 @@ export declare namespace Machine {
4628
4144
  /** Required total transition for a transient choice state. */
4629
4145
  readonly choice: Transition<S, Src, ChoiceContext<S, Ev, Em, Src, In, Pa>, Ev, Em, R>;
4630
4146
  /** Event handlers keyed by the public or internal event tag. */
4631
- readonly on?: never;
4147
+ readonly on?: StateFieldError<"Choice", Src, "on", "Declare one transition in choice">;
4632
4148
  /** Eventless transition evaluated during stabilization. */
4633
- readonly always?: never;
4149
+ readonly always?: StateFieldError<"Choice", Src, "always", "Declare one transition in choice">;
4634
4150
  /** Handles successful invocation or state completion with its exact output type. */
4635
- readonly onDone?: never;
4151
+ readonly onDone?: StateFieldError<"Choice", Src, "onDone", "Declare one transition in choice">;
4636
4152
  /** One registered invocation or an array with distinct lifecycle identities. */
4637
- readonly invoke?: never;
4153
+ readonly invoke?: StateFieldError<"Choice", Src, "invoke", "Declare one transition in choice">;
4638
4154
  /** Child handlers nested according to the declared root topology. */
4639
4155
  readonly states?: never;
4640
4156
  /** Restores the declared history reference, using its fallback on first entry. */
@@ -4643,15 +4159,15 @@ export declare namespace Machine {
4643
4159
  readonly type: "final";
4644
4160
  } ? {
4645
4161
  /** Event handlers keyed by the public or internal event tag. */
4646
- readonly on?: never;
4162
+ readonly on?: StateFieldError<"Final", Src, "on", "A final state has no outgoing work">;
4647
4163
  /** Eventless transition evaluated during stabilization. */
4648
- readonly always?: never;
4164
+ readonly always?: StateFieldError<"Final", Src, "always", "A final state has no outgoing work">;
4649
4165
  /** Handles successful invocation or state completion with its exact output type. */
4650
- readonly onDone?: never;
4166
+ readonly onDone?: StateFieldError<"Final", Src, "onDone", "A final state has no outgoing work">;
4651
4167
  /** Required total transition for a transient choice state. */
4652
4168
  readonly choice?: never;
4653
4169
  /** One registered invocation or an array with distinct lifecycle identities. */
4654
- readonly invoke?: never;
4170
+ readonly invoke?: StateFieldError<"Final", Src, "invoke", "A final state has no outgoing work">;
4655
4171
  /** Child handlers nested according to the declared root topology. */
4656
4172
  readonly states?: never;
4657
4173
  /** Restores the declared history reference, using its fallback on first entry. */
@@ -4659,12 +4175,12 @@ export declare namespace Machine {
4659
4175
  } : {
4660
4176
  /** Event handlers keyed by the public or internal event tag. */
4661
4177
  readonly on?: {
4662
- readonly [Tag in TagOf<Ev[number]>]?: Transition<S, Src, HandlerContext<S, Ev, Em, Src, Tag, never, never, In, Pa>, Ev, Em, R, true, TransitionAcceptance>;
4178
+ readonly [Tag in TagOf<Ev[number]>]?: Transition<S, Src, HandlerContext<S, Ev, Em, Src, Tag, never, never, In, Pa>, Ev, Em, R, true, "declinable">;
4663
4179
  };
4664
4180
  /** Eventless transition evaluated during stabilization. */
4665
- readonly always?: Transition<S, Src, AlwaysContext<S, Ev, Em, Src, In, Pa>, Ev, Em, R, false, TransitionAcceptance>;
4181
+ readonly always?: Transition<S, Src, AlwaysContext<S, Ev, Em, Src, In, Pa>, Ev, Em, R, false, "declinable">;
4666
4182
  /** Handles successful invocation or state completion with its exact output type. */
4667
- readonly onDone?: Transition<S, Src, DoneContext<S, Ev, Em, Src, In, Pa>, Ev, Em, R, false, TransitionAcceptance>;
4183
+ readonly onDone?: Transition<S, Src, DoneContext<S, Ev, Em, Src, In, Pa>, Ev, Em, R, false, "required">;
4668
4184
  /** Required total transition for a transient choice state. */
4669
4185
  readonly choice?: never;
4670
4186
  /** One registered invocation or an array with distinct lifecycle identities. */
@@ -4684,26 +4200,128 @@ export declare namespace Machine {
4684
4200
  readonly states?: never; /** Restores the declared history reference, using its fallback on first entry. */
4685
4201
  readonly history?: never;
4686
4202
  }) : never);
4687
- type ValidateObjectTransition<T> = ("initialize" extends keyof T ? {
4688
- readonly [K in Exclude<keyof T, "initialize" | "guard" | "reenter">]: never;
4689
- } : unknown) & {
4690
- readonly [K in Exclude<keyof T, "target" | "update" | "initialize" | "history" | "none" | "branches" | "data" | "decoded" | "resolve" | "guard" | "reenter" | "declinable">]: never;
4691
- } & (T extends {
4692
- /** Set to true when the resolver can explicitly return decline(). */
4693
- readonly declinable: infer D;
4694
- } ? boolean extends D ? {
4695
- /** Set to true when the resolver can explicitly return decline(). */
4696
- readonly declinable: never;
4697
- } : unknown : unknown) & (T extends {
4698
- /** Set to true when the resolver can explicitly return decline(). */
4699
- readonly declinable: true;
4700
- } ? unknown : T extends {
4701
- /** Selects one declared branch and may enqueue synchronous commands. */
4203
+ type LastOfUnion<U> = Types.UnionToIntersection<U extends unknown ? () => U : never> extends () => infer Last ? Last : never;
4204
+ type JoinUnion<U extends string> = [U] extends [never] ? "" : LastOfUnion<U> extends infer Last extends string ? [Exclude<U, Last>] extends [never] ? Last : `${JoinUnion<Exclude<U, Last>>}, ${Last}` : never;
4205
+ type BranchEntryKey<Entry> = Entry extends {
4206
+ readonly target: infer P extends string;
4207
+ readonly update: infer O extends string;
4208
+ } ? `target:${P}+update:${O}` : Entry extends {
4209
+ readonly target: infer P extends string;
4210
+ } ? `target:${P}` : Entry extends {
4211
+ readonly update: infer O extends string;
4212
+ } ? `update:${O}` : Entry extends {
4213
+ readonly history: infer P extends string;
4214
+ } ? `history:${P}` : Entry extends {
4215
+ readonly initialize: true;
4216
+ } ? "initialize" : Entry extends {
4217
+ readonly stay: true;
4218
+ } ? "stay" : Entry extends {
4219
+ readonly decline: true;
4220
+ } ? "decline" : never;
4221
+ type BranchLabel<Key extends string> = Key extends `target:${infer P}+update:${infer O}` ? `{ target: "${P}", update: "${O}" }` : Key extends `target:${infer P}` ? `{ target: "${P}" }` : Key extends `update:${infer O}` ? `{ update: "${O}" }` : Key extends `history:${infer P}` ? `{ history: "${P}" }` : Key extends "initialize" | "stay" | "decline" ? `{ ${Key}: true }` : never;
4222
+ type BranchEntryKeyAt<B extends ReadonlyArray<unknown>, K> = K extends keyof B ? BranchEntryKey<B[K]> : never;
4223
+ type DuplicateBranchKey<B extends ReadonlyArray<unknown>, Indices extends keyof B = Extract<keyof B, `${number}`>> = {
4224
+ readonly [K in Indices]: BranchEntryKeyAt<B, K> extends BranchEntryKeyAt<B, Exclude<Indices, K>> ? BranchEntryKeyAt<B, K> : never;
4225
+ }[Indices];
4226
+ type SelectedBranchKey<Result> = Result extends SelectedBranch<infer Key, any> ? Key : never;
4227
+ type ValidateBranchSelection<B extends ReadonlyArray<unknown>, Result> = number extends B["length"] ? {
4228
+ readonly branches: "branches must list its entries inline";
4229
+ } : B["length"] extends 0 ? {
4230
+ readonly branches: "branches needs at least one entry";
4231
+ } : [DuplicateBranchKey<B>] extends [never] ? 0 extends 1 & Result ? {
4232
+ readonly resolve: "resolve must return a select call, got any";
4233
+ } : unknown extends Result ? {
4234
+ readonly resolve: "resolve must return a select call, got unknown";
4235
+ } : [Exclude<Result, SelectedBranch<any, any>>] extends [never] ? [
4236
+ Exclude<SelectedBranchKey<Result>, BranchEntryKey<B[number]>>
4237
+ ] extends [never] ? [
4238
+ Exclude<BranchEntryKey<B[number]>, SelectedBranchKey<Result>>
4239
+ ] extends [never] ? unknown : {
4240
+ readonly branches: `Declared branch ${BranchLabel<Exclude<BranchEntryKey<B[number]>, SelectedBranchKey<Result>>> extends infer Label extends string ? JoinUnion<Label> : never} is never selected by resolve`;
4241
+ } : {
4242
+ readonly resolve: `resolve selects undeclared ${BranchLabel<Exclude<SelectedBranchKey<Result>, BranchEntryKey<B[number]>>> extends infer Label extends string ? JoinUnion<Label> : never}. Add it to branches`;
4243
+ } : {
4244
+ readonly resolve: "resolve must return a select call on every path";
4245
+ } : {
4246
+ readonly branches: `Declared branch ${BranchLabel<DuplicateBranchKey<B>> extends infer Label extends string ? JoinUnion<Label> : never} appears more than once`;
4247
+ };
4248
+ type ValidateBranches<T> = T extends {
4249
+ readonly branches: infer B extends ReadonlyArray<unknown>;
4250
+ } ? T extends {
4702
4251
  readonly resolve: (...args: any[]) => infer Result;
4703
- } ? [Extract<Result, Declined>] extends [never] ? unknown : {
4704
- /** Selects one declared branch and may enqueue synchronous commands. */
4705
- readonly resolve: never;
4706
- } : unknown);
4252
+ } ? ValidateBranchSelection<B, Result> : {
4253
+ readonly branches: "branches needs a resolve that selects one of them";
4254
+ } : T extends {
4255
+ readonly resolve: unknown;
4256
+ } ? {
4257
+ readonly resolve: "resolve needs a branches list. Add: branches: [...]";
4258
+ } : unknown;
4259
+ type UpdatableNames<S extends StateSchemas, Src extends string, T> = T extends {
4260
+ readonly target: infer Target extends string;
4261
+ } ? PathName<TargetOwner<S, Extract<Src, StateNodeIdentifier<S>>, PathOf<Target>>> : PathName<UpdatableOwner<S, Extract<Src, StateNodeIdentifier<S>>>>;
4262
+ type ValidateOwnerNames<U, Allowed extends string> = [Exclude<keyof U, Allowed>] extends [never] ? unknown : {
4263
+ readonly update: `Cannot update "${JoinUnion<Extract<Exclude<keyof U, Allowed>, string>>}". ${[Allowed] extends [
4264
+ never
4265
+ ] ? "No retained state can be updated here" : `Updatable here: ${JoinUnion<Allowed>}`}`;
4266
+ };
4267
+ type ValidateUpdateOwners<T, S extends StateSchemas, Src extends string> = T extends {
4268
+ readonly update: infer U;
4269
+ } ? Types.IsUnion<keyof U> extends true ? {
4270
+ readonly update: `update takes one owner, got: ${JoinUnion<Extract<keyof U, string>>}`;
4271
+ } : [keyof U] extends [never] ? {
4272
+ readonly update: "update takes one owner, got none";
4273
+ } : ValidateOwnerNames<U, UpdatableNames<S, Src, T>> & (T extends {
4274
+ readonly reenter: true;
4275
+ } ? keyof U extends PathName<Src> ? {
4276
+ readonly reenter: `Cannot reenter "${PathName<Src>}" while updating it. Update it or reenter it`;
4277
+ } : unknown : unknown) : unknown;
4278
+ type ValidateCommands<T> = T extends {
4279
+ readonly commands: (...args: any[]) => infer Result;
4280
+ } ? [
4281
+ Result
4282
+ ] extends [void | undefined] ? unknown : {
4283
+ readonly commands: "commands must not return a value. Enqueue work with its second argument";
4284
+ } : unknown;
4285
+ type DestinationNames<S extends StateSchemas> = ReferenceUnion<S, Exclude<DestinationPath<S>, HistoryIdentifier<S>>>;
4286
+ type UnknownTargetMessage<P extends string, S extends StateSchemas> = P extends "root" ? `Cannot target "root". Reconstruct it with initialize, or update it with update: { root: ... }` : P extends ReferenceUnion<S, HistoryIdentifier<S>> ? `"${P}" is a history state. Restore it with: { history: "${P}" }` : `Unknown target "${P}". Declared: ${JoinUnion<DestinationNames<S>>}`;
4287
+ type ValidateTarget<T, S extends StateSchemas, Src extends string> = T extends {
4288
+ readonly target: infer P extends string;
4289
+ } ? string extends P ? unknown : P extends DestinationNames<S> ? ValidateTargetAncestors<S, Src, P> & ValidateTargetData<T, S, P> : UnknownTargetMessage<P, S> : unknown;
4290
+ type ValidateTargetData<T, S extends StateSchemas, P extends string> = "data" extends keyof T ? unknown : PathOf<P> extends infer Id extends StateIdentifier<S> ? [
4291
+ NodeSchema<NodeByIdentifier<S, Id>>
4292
+ ] extends [never] ? unknown : {} extends NodeMakeInput<NodeByIdentifier<S, Id>> ? unknown : `Target "${P}" requires data` : unknown;
4293
+ type HasParallelAncestor<S extends StateSchemas, Id extends string> = true extends {
4294
+ [A in Extract<ParentStateIdentifier<Id>, StateIdentifier<S>>]: NodeByIdentifier<S, A> extends {
4295
+ readonly type: "parallel";
4296
+ } ? true : false;
4297
+ }[Extract<ParentStateIdentifier<Id>, StateIdentifier<S>>] ? true : false;
4298
+ type InactiveValuedAncestor<S extends StateSchemas, Src extends string, P extends string> = {
4299
+ [A in Exclude<Extract<ParentStateIdentifier<PathOf<P>>, ValuedStateIdentifier<S>>, Src | ParentStateIdentifier<Src> | JoinPath<Src, string>>]: HasParallelAncestor<S, A> extends true ? never : A;
4300
+ }[Exclude<Extract<ParentStateIdentifier<PathOf<P>>, ValuedStateIdentifier<S>>, Src | ParentStateIdentifier<Src> | JoinPath<Src, string>>];
4301
+ type ValidateTargetAncestors<S extends StateSchemas, Src extends string, P extends string> = [
4302
+ InactiveValuedAncestor<S, Src, P>
4303
+ ] extends [never] ? unknown : `Target "${P}" enters "${JoinUnion<PathName<InactiveValuedAncestor<S, Src, P>>>}", which needs a value. Target that state and construct "${P}" with states`;
4304
+ type ValidateBranchEntries<T, S extends StateSchemas, Src extends string> = T extends {
4305
+ readonly branches: infer B extends ReadonlyArray<unknown>;
4306
+ } ? {
4307
+ readonly branches: {
4308
+ readonly [K in keyof B]: (B[K] extends {
4309
+ readonly target: infer P extends string;
4310
+ } ? P extends DestinationNames<S> ? ValidateTargetAncestors<S, Src, P> : UnknownTargetMessage<P, S> : unknown) & (B[K] extends {
4311
+ readonly update: infer O extends string;
4312
+ } ? O extends UpdatableNames<S, Src, B[K]> ? unknown : `Cannot update "${O}". ${[UpdatableNames<S, Src, B[K]>] extends [never] ? "No retained state can be updated here" : `Updatable here: ${JoinUnion<UpdatableNames<S, Src, B[K]>>}`}` : unknown);
4313
+ };
4314
+ } : unknown;
4315
+ type ValidateDestination<T> = Extract<keyof T, "target" | "update" | "initialize" | "history" | "stay" | "branches" | "resolve"> extends never ? T extends {
4316
+ readonly reenter: true;
4317
+ } ? unknown : {
4318
+ readonly target: "A transition needs one of: target, update, initialize, history, stay, reenter: true, branches";
4319
+ } : unknown;
4320
+ type ValidateObjectTransition<T, S extends StateSchemas, Src extends string> = ("initialize" extends keyof T ? {
4321
+ readonly [K in Exclude<keyof T, "initialize" | "guard" | "reenter" | "commands">]: never;
4322
+ } : unknown) & {
4323
+ readonly [K in Exclude<keyof T, "target" | "update" | "initialize" | "history" | "stay" | "branches" | "data" | "decoded" | "resolve" | "guard" | "reenter" | "commands">]: never;
4324
+ } & ValidateDestination<T> & ValidateTarget<T, S, Src> & ValidateBranches<T> & ValidateBranchEntries<T, S, Src> & ValidateUpdateOwners<T, S, Src> & ValidateCommands<T>;
4707
4325
  type AllowedInvokeChannels<R, K extends PropertyKey> = ([InvokeOutput<ResolvedInvoke<R, K>>] extends [never] ? never : "onDone") | ([RegisteredInvokeError<R, K>] extends [never] ? never : "onFailure") | (SourceKind<R, K> extends "streams" ? [Stream.Success<Extract<InvokeResolvedSource<SourceValue<R, K>>, Stream.Stream<any, any, any>>>] extends [never] ? never : "onElement" : never) | (SourceKind<R, K> extends "logic" | "children" ? "onSnapshot" : never);
4708
4326
  type UnreachableInvokeChannelMessage<Channel extends string, Src extends string> = Channel extends "onDone" ? `Invocation '${Src}' never completes, so onDone is unreachable` : Channel extends "onFailure" ? `Invocation '${Src}' cannot fail, so onFailure is unreachable` : Channel extends "onElement" ? `Invocation '${Src}' emits no Stream elements, so onElement is unreachable` : `Invocation '${Src}' has no snapshots; onSnapshot applies only to logic and child invocations`;
4709
4327
  type InvokeFieldError<K, Src extends string> = K extends "onDone" | "onFailure" | "onElement" | "onSnapshot" ? InvocationDefinitionError<UnreachableInvokeChannelMessage<K, Src>, Src, K> : K extends string ? InvocationDefinitionError<`Invocation '${Src}' does not accept the field '${K}'`, Src, K> : never;
@@ -4716,18 +4334,19 @@ export declare namespace Machine {
4716
4334
  type DuplicateInvokeId<I extends ReadonlyArray<unknown>, K, R> = LiteralInvokeIdAt<I, K, R> extends infer Id ? [
4717
4335
  Id
4718
4336
  ] extends [never] ? never : Id extends LiteralInvokeIdAt<I, Exclude<Extract<keyof I, `${number}`>, K>, R> ? Id : never : never;
4719
- type ValidateInvokeEntry<I, R, Duplicate extends string, Root> = I extends {
4337
+ type ValidateInvokeEntry<I, R, Duplicate extends string, Root, S extends StateSchemas, Path extends string> = I extends {
4720
4338
  /** Name of the source registered in make. */
4721
4339
  readonly src: infer Src extends PropertyKey;
4722
- } ? {
4723
- readonly [K in keyof I]: [Duplicate] extends [never] ? ValidateInvokeField<I, K, R, Extract<Src, string>, Root> : K extends ("id" extends keyof I ? "id" : "src") ? InvocationDefinitionError<`Invocation id '${Duplicate}' is declared more than once in this state`, Extract<Src, string>, K> : ValidateInvokeField<I, K, R, Extract<Src, string>, Root>;
4724
- } : never;
4725
- type ValidateInvokeField<I, K extends keyof I, R, Src extends string, Root> = K extends AllowedInvokeChannels<R, Src> ? ValidateObjectTransition<I[K]> & ValidateChoiceUpdate<I[K], R, Root> : K extends "src" | "id" | "address" | "input" ? unknown : InvokeFieldError<K, Src>;
4726
- type ValidateObjectInvoke<I, R, Root> = I extends ReadonlyArray<unknown> ? number extends I["length"] ? {
4727
- readonly [K in keyof I]: ValidateInvokeEntry<I[K], R, never, Root>;
4340
+ } ? Src extends SourceKeys<R> ? {
4341
+ readonly [K in keyof I]: [Duplicate] extends [never] ? ValidateInvokeField<I, K, R, Extract<Src, string>, Root, S, Path> : K extends ("id" extends keyof I ? "id" : "src") ? InvocationDefinitionError<`Invocation id '${Duplicate}' is declared more than once in this state`, Extract<Src, string>, K> : ValidateInvokeField<I, K, R, Extract<Src, string>, Root, S, Path>;
4342
+ } : UnknownSourceMessage<R> : never;
4343
+ type ValidateInvokeField<I, K extends keyof I, R, Src extends string, Root, S extends StateSchemas, Path extends string> = K extends AllowedInvokeChannels<R, Src> ? ValidateObjectTransition<I[K], S, Path> & ValidateChoiceUpdate<I[K], Root> : K extends "src" | "id" | "address" | "input" ? unknown : InvokeFieldError<K, Src>;
4344
+ type UnknownSourceMessage<R> = [Extract<SourceKeys<R>, string>] extends [never] ? "Unknown source. Register it in make with effects, streams, timers, logic, or children" : `Unknown source. Registered: ${JoinUnion<Extract<SourceKeys<R>, string>>}`;
4345
+ type ValidateObjectInvoke<I, R, Root, S extends StateSchemas, Path extends string> = I extends ReadonlyArray<unknown> ? number extends I["length"] ? {
4346
+ readonly [K in keyof I]: ValidateInvokeEntry<I[K], R, never, Root, S, Path>;
4728
4347
  } : {
4729
- readonly [K in keyof I]: ValidateInvokeEntry<I[K], R, DuplicateInvokeId<I, K, R>, Root>;
4730
- } : ValidateInvokeEntry<I, R, never, Root>;
4348
+ readonly [K in keyof I]: ValidateInvokeEntry<I[K], R, DuplicateInvokeId<I, K, R>, Root, S, Path>;
4349
+ } : ValidateInvokeEntry<I, R, never, Root, S, Path>;
4731
4350
  type HandlerConfigAt<Config, Path extends string> = Config extends {
4732
4351
  readonly states: infer Children;
4733
4352
  } ? Path extends `${infer Head}.${infer Rest}` ? Head extends keyof Children ? HandlerConfigAt<Children[Head], Rest> : never : Path extends keyof Children ? Children[Path] : never : never;
@@ -4735,51 +4354,48 @@ export declare namespace Machine {
4735
4354
  /** Implements this choice pseudo-state with one required synchronous transition. */
4736
4355
  readonly choice: infer Choice;
4737
4356
  } ? Choice : never;
4738
- type ChoiceBranchDeclaration<Choice, R> = Choice extends {
4739
- /** Named groups of inspectable destinations used by transition resolvers. */
4740
- readonly branches: infer G extends keyof Registered<R, "branches">;
4741
- } ? {
4742
- readonly [K in Extract<keyof Registered<R, "branches">[G], string>]: {
4743
- readonly label: `branch '${K}'`;
4744
- readonly declaration: Registered<R, "branches">[G][K];
4745
- };
4746
- }[Extract<keyof Registered<R, "branches">[G], string>] : {
4357
+ type ChoiceBranchDeclaration<Choice> = Choice extends {
4358
+ /** The destinations this transition can select, each one checked against `resolve`. */
4359
+ readonly branches: infer B extends ReadonlyArray<unknown>;
4360
+ } ? B[number] extends infer Entry ? Entry extends unknown ? {
4361
+ readonly label: `branch ${BranchLabel<BranchEntryKey<Entry>>}`;
4362
+ readonly declaration: Entry;
4363
+ } : never : never : {
4747
4364
  readonly label: "transition";
4748
4365
  readonly declaration: Choice;
4749
4366
  };
4750
4367
  type IsBelowOwner<Path extends string, Owner extends string> = Owner extends "" ? Path extends "" ? false : true : Path extends `${Owner}.${string}` ? true : false;
4751
4368
  type ChoiceBranchEscape<Path extends string, Owner extends string, Choice extends string, Label extends string> = IsBelowOwner<Path, Owner> extends true ? never : TransitionDefinitionError<`Choice '${Choice}' ${Label} targets '${PathName<Path>}' outside the updated owner '${PathName<Owner>}'`, Choice, PathName<Path>>;
4752
- type ChoiceUpdateEscape<Root, R, Choice extends string, Owner extends string, Visited extends string = never> = Choice extends Visited ? never : ChoiceBranchDeclaration<ChoiceConfigAt<Root, Choice>, R> extends infer Branch ? Branch extends {
4369
+ type ChoiceUpdateEscape<Root, Choice extends string, Owner extends string, Visited extends string = never> = Choice extends Visited ? never : ChoiceBranchDeclaration<ChoiceConfigAt<Root, Choice>> extends infer Branch ? Branch extends {
4753
4370
  readonly label: infer Label extends string;
4754
4371
  readonly declaration: infer D;
4755
4372
  } ? D extends {
4756
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4373
+ /** Selects a declared descendant, constructing the values it requires. */
4757
4374
  readonly target: infer Ref extends string;
4758
4375
  } ? [
4759
4376
  ChoiceConfigAt<Root, PathOf<Ref>>
4760
- ] extends [never] ? ChoiceBranchEscape<PathOf<Ref>, Owner, Choice, Label> : ChoiceUpdateEscape<Root, R, PathOf<Ref>, Owner, Visited | Choice> : D extends {
4377
+ ] extends [never] ? ChoiceBranchEscape<PathOf<Ref>, Owner, Choice, Label> : ChoiceUpdateEscape<Root, PathOf<Ref>, Owner, Visited | Choice> : D extends {
4761
4378
  /** Restores the declared history reference, using its fallback on first entry. */
4762
4379
  readonly history: infer Ref extends string;
4763
4380
  } ? ChoiceBranchEscape<PathOf<Ref>, Owner, Choice, Label> : D extends {
4764
4381
  /** Reconstructs root and its initial children from fresh machine input. */
4765
4382
  readonly initialize: unknown;
4766
4383
  } ? ChoiceBranchEscape<"", Owner, Choice, Label> : never : never : never;
4767
- type ChoiceUpdateEscapeOf<D, R, Root> = D extends {
4768
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4384
+ type OwnerNameOf<Update> = Update extends string ? Update : Extract<keyof Update, string>;
4385
+ type ChoiceUpdateEscapeOf<D, Root> = D extends {
4386
+ /** Selects a declared descendant, constructing the values it requires. */
4769
4387
  readonly target: infer Ref extends string;
4770
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4771
- readonly update: infer Owner extends string;
4772
- } ? [ChoiceConfigAt<Root, PathOf<Ref>>] extends [never] ? never : ChoiceUpdateEscape<Root, R, PathOf<Ref>, PathOf<Owner>> : never;
4773
- type ValidateChoiceUpdate<T, R, Root> = T extends {
4774
- /** Named groups of inspectable destinations used by transition resolvers. */
4775
- readonly branches: infer G extends keyof Registered<R, "branches">;
4776
- } ? {
4777
- readonly [K in keyof Registered<R, "branches">[G]]: ChoiceUpdateEscapeOf<Registered<R, "branches">[G][K], R, Root>;
4778
- }[keyof Registered<R, "branches">[G]] extends infer Escape ? [Escape] extends [never] ? unknown : {
4779
- /** Named groups of inspectable destinations used by transition resolvers. */
4388
+ /** Replaces the value of one retained state without replacing its active children. */
4389
+ readonly update: infer Update;
4390
+ } ? [ChoiceConfigAt<Root, PathOf<Ref>>] extends [never] ? never : ChoiceUpdateEscape<Root, PathOf<Ref>, PathOf<OwnerNameOf<Update>>> : never;
4391
+ type ValidateChoiceUpdate<T, Root> = T extends {
4392
+ /** The destinations this transition can select, each one checked against `resolve`. */
4393
+ readonly branches: infer B extends ReadonlyArray<unknown>;
4394
+ } ? ChoiceUpdateEscapeOf<B[number], Root> extends infer Escape ? [Escape] extends [never] ? unknown : {
4395
+ /** The destinations this transition can select, each one checked against `resolve`. */
4780
4396
  readonly branches: Escape;
4781
- } : never : ChoiceUpdateEscapeOf<T, R, Root> extends infer Escape ? [Escape] extends [never] ? unknown : {
4782
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4397
+ } : never : ChoiceUpdateEscapeOf<T, Root> extends infer Escape ? [Escape] extends [never] ? unknown : {
4398
+ /** Replaces the value of one retained state without replacing its active children. */
4783
4399
  readonly update: Escape;
4784
4400
  } : never;
4785
4401
  type ObjectDeclarations<C> = Extract<keyof C, "on" | "always" | "onDone" | "choice" | "invoke"> | (C extends {
@@ -4787,12 +4403,14 @@ export declare namespace Machine {
4787
4403
  } ? {
4788
4404
  readonly [K in keyof Children]: ObjectDeclarations<Children[K]>;
4789
4405
  }[keyof Children] : never);
4790
- type ValidateObjectConfig<C, R, Root = C> = [ObjectDeclarations<C>] extends [never] ? unknown : {
4406
+ type ValidateObjectConfig<C, R, S extends StateSchemas, Path extends string = "", Root = C> = [
4407
+ ObjectDeclarations<C>
4408
+ ] extends [never] ? unknown : {
4791
4409
  readonly [K in keyof C]: K extends "states" ? {
4792
- readonly [P in keyof C[K]]: ValidateObjectConfig<C[K][P], R, Root>;
4410
+ readonly [P in keyof C[K]]: ValidateObjectConfig<C[K][P], R, S, JoinPath<Path, Extract<P, string>>, Root>;
4793
4411
  } : K extends "on" ? {
4794
- readonly [P in keyof C[K]]: ValidateObjectTransition<C[K][P]> & ValidateChoiceUpdate<C[K][P], R, Root>;
4795
- } : K extends "always" | "onDone" ? ValidateObjectTransition<C[K]> & ValidateChoiceUpdate<C[K], R, Root> : K extends "choice" ? ValidateObjectTransition<C[K]> : K extends "invoke" ? ValidateObjectInvoke<C[K], R, Root> : unknown;
4412
+ readonly [P in keyof C[K]]: ValidateObjectTransition<C[K][P], S, Path> & ValidateChoiceUpdate<C[K][P], Root>;
4413
+ } : K extends "always" | "onDone" ? ValidateObjectTransition<C[K], S, Path> & ValidateChoiceUpdate<C[K], Root> : K extends "choice" ? ValidateObjectTransition<C[K], S, Path> : K extends "invoke" ? ValidateObjectInvoke<C[K], R, Root, S, Path> : unknown;
4796
4414
  };
4797
4415
  type NormalizeObjectInvoke<I, R> = I extends ReadonlyArray<unknown> ? {
4798
4416
  readonly [K in keyof I]: NormalizeObjectInvoke<I[K], R>;
@@ -4805,10 +4423,17 @@ export declare namespace Machine {
4805
4423
  readonly [P in keyof C[K]]: NormalizeObjectConfig<C[K][P], R>;
4806
4424
  } : K extends "invoke" ? NormalizeObjectInvoke<C[K], R> : C[K];
4807
4425
  };
4808
- type HandlerShape<C, H> = {
4426
+ type InvokeShape<I, H, R> = I extends ReadonlyArray<{
4427
+ readonly src: infer Src;
4428
+ }> ? [
4429
+ Exclude<Src, SourceKeys<R>>
4430
+ ] extends [never] ? H : UnknownSourceMessage<R> : I extends {
4431
+ readonly src: infer Src;
4432
+ } ? [Src] extends [SourceKeys<R>] ? H : UnknownSourceMessage<R> : H;
4433
+ type HandlerShape<C, H, R> = {
4809
4434
  readonly [K in keyof C]: K extends keyof H ? K extends "states" ? {
4810
- readonly [P in keyof C[K]]: P extends keyof NonNullable<H[K]> ? HandlerShape<C[K][P], NonNullable<NonNullable<H[K]>[P]>> : never;
4811
- } : H[K] : never;
4435
+ readonly [P in keyof C[K]]: P extends keyof NonNullable<H[K]> ? HandlerShape<C[K][P], NonNullable<NonNullable<H[K]>[P]>, R> : never;
4436
+ } : K extends "invoke" ? InvokeShape<C[K], H[K], R> : H[K] : never;
4812
4437
  } & Omit<H, keyof C>;
4813
4438
  /**
4814
4439
  * Adds object handlers while checking topology, protocols, invocation outcomes, and readiness.
@@ -4816,14 +4441,12 @@ export declare namespace Machine {
4816
4441
  * @category combinators
4817
4442
  * @since 0.34.0
4818
4443
  */
4819
- interface Handler<S extends StateSchemas, Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, I extends Schema.Top, IE, IR, Final extends StateIdentifier<S>, Out, In extends ReadonlyArray<TaggedSchema>, Pa extends ReadonlyArray<TaggedSchema>, R> {
4820
- <const C>(config: C & (C extends (...args: never[]) => unknown ? never : unknown) & HandlerShape<C, StateHandler<S, S[""], Ev, Em, Extract<"", StateNodeIdentifier<S>>, In, Pa, R & {
4444
+ export interface Handler<S extends StateSchemas, Ev extends ReadonlyArray<TaggedSchema>, Em extends ReadonlyArray<TaggedSchema>, I extends Schema.Top, IE, IR, Final extends StateIdentifier<S>, Out, In extends ReadonlyArray<TaggedSchema>, Pa extends ReadonlyArray<TaggedSchema>, R> {
4445
+ <const C>(config: C & (C extends (...args: never[]) => unknown ? never : unknown) & ValidateObjectConfig<NoInfer<C>, R, S> & HandlerShape<C, StateHandler<S, S[""], Ev, Em, Extract<"", StateNodeIdentifier<S>>, In, Pa, R & {
4821
4446
  readonly "~input": I;
4822
- }> & RootConstruction<S[""], I["Type"]>> & RootConstruction<S[""], I["Type"]> & ValidateObjectConfig<NoInfer<C>, R> & RootHandlerValidation<S, Ev, In, Em, NormalizeObjectConfig<NoInfer<C>, R>, Extract<HandlerTreeEvidence<S, {
4447
+ }> & RootConstruction<S[""], I["Type"]>, R> & RootConstruction<S[""], I["Type"]> & RootHandlerValidation<S, Ev, In, Em, NormalizeObjectConfig<NoInfer<C>, R>, Extract<HandlerTreeEvidence<S, {
4823
4448
  readonly "": NormalizeObjectConfig<NoInfer<C>, R>;
4824
- }>["outputState"], StateIdentifier<S>>>): HandleTreeResult<S, Ev, Em, I, StateIdentifier<S>, never, never, IE, IR, Final, Out, never, In, Pa, {
4825
- readonly "": NormalizeObjectConfig<C, R>;
4826
- }>;
4449
+ }>["outputState"], StateIdentifier<S>>>): Machine<S, Ev, I, Exclude<StateIdentifier<S>, HandleEvidence<S, C, R>["stateId"]>, HandleEvidence<S, C, R>["error"], ExcludeCompatibleRuntime<HandleEvidence<S, C, R>["services"], EventOf<Ev>, EmittedEventOf<Em>>, IE, IR, Final, Out, Em, Extract<HandleEvidence<S, C, R>["outputState"], StateIdentifier<S>>, In, Pa>;
4827
4450
  }
4828
4451
  /**
4829
4452
  * Any state config.
@@ -4831,21 +4454,21 @@ export declare namespace Machine {
4831
4454
  * @category utility types
4832
4455
  * @since 0.4.0
4833
4456
  */
4834
- type AnyStateConfig = StateConfig<any, any, any, any, any, any, any> | ChoiceStateConfig<any, any, any, any>;
4457
+ export type AnyStateConfig = StateConfig<any, any, any, any, any, any, any> | ChoiceStateConfig<any, any, any, any>;
4835
4458
  /**
4836
4459
  * Runtime event-handler map stored for a single state tag.
4837
4460
  *
4838
4461
  * @category models
4839
4462
  * @since 0.4.0
4840
4463
  */
4841
- type EventHandlerMap<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, EventTag extends TagOf<Events[number]>, E, R> = Readonly<Record<PropertyKey, TransitionConfig<States, Events, Emits, StateId, HandlerContext<States, Events, Emits, StateId, EventTag, E, R>, true, TransitionAcceptance>>>;
4464
+ export type EventHandlerMap<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, EventTag extends TagOf<Events[number]>, E, R> = Readonly<Record<PropertyKey, TransitionConfig<States, Events, Emits, StateId, HandlerContext<States, Events, Emits, StateId, EventTag, E, R>, true, TransitionAcceptance>>>;
4842
4465
  /**
4843
4466
  * Runtime state config stored for a single state tag.
4844
4467
  *
4845
4468
  * @category models
4846
4469
  * @since 0.4.0
4847
4470
  */
4848
- interface StateConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, EventTag extends TagOf<Events[number]>, E, R> {
4471
+ export interface StateConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, EventTag extends TagOf<Events[number]>, E, R> {
4849
4472
  /** Runs synchronously on entry and may enqueue commands. */
4850
4473
  readonly entry?: (context: StateActionContext<States, Events, Emits, StateId>, enqueue: Enqueue<EventOf<Events>, EmittedEventOf<Emits>>) => StateActionResult<E, R>;
4851
4474
  /** Runs synchronously on exit and may enqueue commands. */
@@ -4861,13 +4484,7 @@ export declare namespace Machine {
4861
4484
  /** Event handlers keyed by the public or internal event tag. */
4862
4485
  readonly on?: EventHandlerMap<States, Events, Emits, StateId, EventTag, E, R>;
4863
4486
  }
4864
- /**
4865
- * Runtime handler table stored on a machine.
4866
- *
4867
- * @category models
4868
- * @since 0.4.0
4869
- */
4870
- type StateConfigs<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, EventTag extends TagOf<Events[number]>, E, R> = Readonly<Record<PropertyKey, StateConfig<States, Events, Emits, StateId, EventTag, E, R> | ChoiceStateConfig<States, Events, Emits, ChoiceIdentifier<States>>>>;
4487
+ export {};
4871
4488
  }
4872
4489
  type StateSource = State<any> | Machine.Any;
4873
4490
  type StateSchemasOf<Source extends StateSource> = Source extends State<infer Node> ? {
@@ -4909,8 +4526,8 @@ export declare namespace Snapshot {
4909
4526
  /**
4910
4527
  * Extracts the decoded value owned by a schema-backed state path.
4911
4528
  *
4912
- * The source may be the object returned by {@link states} or a machine
4913
- * definition. Control-only state paths are intentionally excluded.
4529
+ * The source may be a descriptor returned by {@link state} or a machine.
4530
+ * Control-only state paths are intentionally excluded.
4914
4531
  *
4915
4532
  * @category utility types
4916
4533
  * @since 0.18.0
@@ -4919,9 +4536,8 @@ export type Value<Source extends StateSource, Path extends Machine.ValuedStateId
4919
4536
  /**
4920
4537
  * Extracts the logical snapshot rooted at a state path.
4921
4538
  *
4922
- * The source may be the object returned by {@link states} or a machine
4923
- * definition. This is the type-level counterpart of
4924
- * `State.getSnapshot`.
4539
+ * The source may be a descriptor returned by {@link state} or a machine.
4540
+ * This is the type-level counterpart of a descriptor's `getSnapshot`.
4925
4541
  *
4926
4542
  * @category utility types
4927
4543
  * @since 0.18.0
@@ -4948,16 +4564,13 @@ export declare const isFinal: <const States extends Machine.StateSchemas, const
4948
4564
  * can be declared inline or reused by mounting a descriptor in multiple places.
4949
4565
  * Initial edges and value constructors belong in the handler tree.
4950
4566
  *
4951
- * **Example** (Repeated compound state)
4567
+ * **Example** (Reusing one subtree in two parallel regions)
4952
4568
  *
4953
- * ```ts
4569
+ * ```ts import.meta.vitest
4954
4570
  * import { Machine } from "@typeonce/effect-machine"
4955
- * import { Schema } from "effect"
4571
+ * import { Effect, Schema } from "effect"
4956
4572
  *
4957
- * const TradingState = Schema.TaggedUnion({
4958
- * InSession: {},
4959
- * Applying: {}
4960
- * })
4573
+ * const TradingState = Schema.TaggedUnion({ InSession: {}, Applying: {} })
4961
4574
  * const TradingSlot = Machine.state({
4962
4575
  * states: {
4963
4576
  * Idle: {},
@@ -4965,13 +4578,21 @@ export declare const isFinal: <const States extends Machine.StateSchemas, const
4965
4578
  * Applying: TradingState.cases.Applying
4966
4579
  * }
4967
4580
  * })
4581
+ * const States = Machine.state({ type: "parallel", states: { slot1: TradingSlot, slot2: TradingSlot } })
4968
4582
  *
4969
- * const States = Machine.state({
4583
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
4970
4584
  * states: {
4971
- * slot1: TradingSlot,
4972
- * slot2: TradingSlot
4585
+ * slot1: { initial: { target: "slot1.Idle" } },
4586
+ * slot2: { initial: { target: "slot2.Idle" } }
4973
4587
  * }
4974
4588
  * })
4589
+ *
4590
+ * const paths = Effect.map(Machine.planInitial(machine), ({ state }) => [
4591
+ * state.states.slot1.state.path,
4592
+ * state.states.slot2.state.path
4593
+ * ])
4594
+ *
4595
+ * await Effect.runPromise(paths) // => ["slot1.Idle", "slot2.Idle"]
4975
4596
  * ```
4976
4597
  *
4977
4598
  * @category constructors
@@ -4988,7 +4609,7 @@ type ReservedRootName<Root> = Root extends {
4988
4609
  } ? "root" extends keyof Children ? {
4989
4610
  readonly "~effect/Machine/ReservedRootStateName": never;
4990
4611
  } : unknown : unknown;
4991
- type MakeConfig<Root extends Machine.StateNodeConfig, InputEvents extends ReadonlyArray<Machine.TaggedSchema>, Emits extends ReadonlyArray<Machine.TaggedSchema>, Input extends Schema.Top, InitialE, InitialR, InternalEvents extends ReadonlyArray<Machine.TaggedSchema>, ParentDeclaration extends Parent.Any | undefined, Effects extends Machine.EffectSources, Streams extends Machine.StreamSources, Timers extends Machine.TimerSources, Logics extends Machine.LogicSources, Children extends Machine.ChildSources, Branches extends Machine.BranchDefinitions<Root>> = {
4612
+ type MakeConfig<Root extends Machine.StateNodeConfig, InputEvents extends ReadonlyArray<Machine.TaggedSchema>, Emits extends ReadonlyArray<Machine.TaggedSchema>, Input extends Schema.Top, InitialE, InitialR, InternalEvents extends ReadonlyArray<Machine.TaggedSchema>, ParentDeclaration extends Parent.Any | undefined, Effects extends Machine.EffectSources, Streams extends Machine.StreamSources, Timers extends Machine.TimerSources, Logics extends Machine.LogicSources, Children extends Machine.ChildSources> = {
4992
4613
  /** Lazy Effects or functions with one required input, invoked by registered name. */
4993
4614
  readonly effects?: Effects & Machine.ValidatePrograms<Effects>;
4994
4615
  /** Lazy Streams or functions with one required input, invoked by registered name. */
@@ -4999,10 +4620,6 @@ type MakeConfig<Root extends Machine.StateNodeConfig, InputEvents extends Readon
4999
4620
  readonly logic?: Logics & Machine.ValidatePrograms<Logics> & Machine.ValidateLogicSources<NoInfer<Logics>>;
5000
4621
  /** Child machine descriptors registered for state-owned invocation. */
5001
4622
  readonly children?: Children;
5002
- /** Named groups of inspectable destinations used by transition resolvers. */
5003
- readonly branches?: Branches & {
5004
- readonly [K in keyof Branches]: ValidateTransitionBranchRecord<NoInfer<Branches[K]>>;
5005
- };
5006
4623
  /** Stable definition identifier used by inspection and visualization. */
5007
4624
  readonly id?: string;
5008
4625
  /** State topology and value schemas, captured by a `Machine.state` descriptor. */
@@ -5021,7 +4638,7 @@ type MakeConfig<Root extends Machine.StateNodeConfig, InputEvents extends Readon
5021
4638
  /** Schema used to decode input before initial-state construction. */
5022
4639
  readonly input?: Input;
5023
4640
  };
5024
- type MakeResult<Root extends Machine.StateNodeConfig, InputEvents extends ReadonlyArray<Machine.TaggedSchema>, Emits extends ReadonlyArray<Machine.TaggedSchema>, Input extends Schema.Top, InitialE, InitialR, InternalEvents extends ReadonlyArray<Machine.TaggedSchema>, ParentDeclaration extends Parent.Any | undefined, Effects extends Machine.EffectSources, Streams extends Machine.StreamSources, Timers extends Machine.TimerSources, Logics extends Machine.LogicSources, Children extends Machine.ChildSources, Branches extends Readonly<Record<string, Readonly<Record<string, unknown>>>>> = Definition<{
4641
+ type MakeResult<Root extends Machine.StateNodeConfig, InputEvents extends ReadonlyArray<Machine.TaggedSchema>, Emits extends ReadonlyArray<Machine.TaggedSchema>, Input extends Schema.Top, InitialE, InitialR, InternalEvents extends ReadonlyArray<Machine.TaggedSchema>, ParentDeclaration extends Parent.Any | undefined, Effects extends Machine.EffectSources, Streams extends Machine.StreamSources, Timers extends Machine.TimerSources, Logics extends Machine.LogicSources, Children extends Machine.ChildSources> = Definition<{
5025
4642
  readonly "": Root;
5026
4643
  }, readonly [...InputEvents, ...InternalEvents], Input, InitialE, InitialR, Machine.FinalStateFromDefinition<{
5027
4644
  readonly "": Root;
@@ -5038,29 +4655,27 @@ type MakeResult<Root extends Machine.StateNodeConfig, InputEvents extends Readon
5038
4655
  readonly logic: Logics;
5039
4656
  /** Child machine descriptors registered for state-owned invocation. */
5040
4657
  readonly children: Children;
5041
- /** Named groups of inspectable destinations used by transition resolvers. */
5042
- readonly branches: Branches;
5043
4658
  }>;
5044
4659
  /** @inline */
5045
- interface Make {
4660
+ type Make = {
5046
4661
  /** @param config Complete schema-first machine definition. */
5047
- <const Root extends Machine.StateNodeConfig, const InputEvents extends ReadonlyArray<Machine.TaggedSchema>, const Emits extends ReadonlyArray<Machine.TaggedSchema> = readonly [], const Input extends Schema.Top = typeof Schema.Void, InitialE = never, InitialR = never, const InternalEvents extends ReadonlyArray<Machine.TaggedSchema> = readonly [], const ParentDeclaration extends Parent.Any | undefined = undefined, const Effects extends Machine.EffectSources = {}, const Streams extends Machine.StreamSources = {}, const Timers extends Machine.TimerSources = {}, const Logics extends Machine.LogicSources = {}, const Children extends Machine.ChildSources = {}, const Branches extends Machine.BranchDefinitions<NoInfer<Root>> = {}>(config: MakeConfig<Root, InputEvents, Emits, Input, InitialE, InitialR, InternalEvents, ParentDeclaration, Effects, Streams, Timers, Logics, Children, Branches> & UniqueSourceNames<NoInfer<Effects>, NoInfer<Streams>, NoInfer<Timers>, NoInfer<Logics>, NoInfer<Children>>): MakeResult<Root, InputEvents, Emits, Input, InitialE, InitialR, InternalEvents, ParentDeclaration, Effects, Streams, Timers, Logics, Children, Branches>;
5048
- }
4662
+ <const Root extends Machine.StateNodeConfig, const InputEvents extends ReadonlyArray<Machine.TaggedSchema>, const Emits extends ReadonlyArray<Machine.TaggedSchema> = readonly [], const Input extends Schema.Top = typeof Schema.Void, InitialE = never, InitialR = never, const InternalEvents extends ReadonlyArray<Machine.TaggedSchema> = readonly [], const ParentDeclaration extends Parent.Any | undefined = undefined, const Effects extends Machine.EffectSources = {}, const Streams extends Machine.StreamSources = {}, const Timers extends Machine.TimerSources = {}, const Logics extends Machine.LogicSources = {}, const Children extends Machine.ChildSources = {}>(config: MakeConfig<Root, InputEvents, Emits, Input, InitialE, InitialR, InternalEvents, ParentDeclaration, Effects, Streams, Timers, Logics, Children> & UniqueSourceNames<NoInfer<Effects>, NoInfer<Streams>, NoInfer<Timers>, NoInfer<Logics>, NoInfer<Children>>): MakeResult<Root, InputEvents, Emits, Input, InitialE, InitialR, InternalEvents, ParentDeclaration, Effects, Streams, Timers, Logics, Children>;
4663
+ };
5049
4664
  /**
5050
4665
  * Creates a schema-first machine definition.
5051
4666
  *
5052
4667
  * **Details**
5053
4668
  *
5054
- * State and event schemas provide runtime boundary validation while their
5055
- * decoded types drive handler, state, event, target, error, and service
5056
- * inference. State-tree validation is applied whether `states` comes from
5057
- * `states` or is passed inline. Call `handle` on the returned definition
5058
- * to implement state behavior with ordinary TypeScript control flow.
4669
+ * `root` is the `Machine.state` descriptor of the complete state tree. State
4670
+ * and event schemas provide runtime boundary validation while their decoded
4671
+ * types drive handler, state, event, target, error, and service inference.
4672
+ * Call `handle` on the returned {@link Definition} to declare the initial
4673
+ * target and the behavior of each state.
5059
4674
  *
5060
- * `initial` is a target-first callback. Its outer selector runs once while the
5061
- * definition is captured; an attached `.resolve(...)` callback remains lazy
5062
- * until initial planning. Return a bare selected state when its schema supports
5063
- * default construction.
4675
+ * Register Effects, Streams, timers, logic, and child machines under
4676
+ * `effects`, `streams`, `timers`, `logic`, and `children`. A state invokes a
4677
+ * registered source by name with `invoke: { src }`, and only invoked sources
4678
+ * add to the machine's requirements.
5064
4679
  *
5065
4680
  * `Machine.events` defines the public input protocol. `Machine.internalEvents`
5066
4681
  * adds raised events and other machine-local deliveries.
@@ -5071,42 +4686,82 @@ interface Make {
5071
4686
  * schemas opaquely for runtime validation. Public and internal tags must be
5072
4687
  * disjoint.
5073
4688
  *
5074
- * **Example** (Typed counter machine)
4689
+ * **Gotchas**
5075
4690
  *
5076
- * ```ts
4691
+ * Source names must be unique across all five registries. A top-level state
4692
+ * cannot be named `root`, because `root` names the root state.
4693
+ *
4694
+ * **Example** (Invoking a registered Effect)
4695
+ *
4696
+ * ```ts import.meta.vitest
5077
4697
  * import { Machine } from "@typeonce/effect-machine"
5078
- * import { Schema } from "effect"
5079
- * class Count extends Schema.TaggedClass<Count>("Count")("Count", {
5080
- * value: Schema.Number
5081
- * }) {
5082
- * }
5083
- * class Increment extends Schema.TaggedClass<Increment>("Increment")("Increment", {
5084
- * by: Schema.Number
5085
- * }) {
5086
- * }
4698
+ * import { Effect, Option, Schema } from "effect"
4699
+ *
4700
+ * const Lookup = Schema.TaggedUnion({ Loading: { id: Schema.String }, Ready: { name: Schema.String } })
4701
+ * const States = Machine.state({ states: { Idle: {}, Loading: Lookup.cases.Loading, Ready: Lookup.cases.Ready } })
4702
+ * const Events = Machine.events({ Load: { id: Schema.String } })
4703
+ *
4704
+ * const machine = Machine.make({
4705
+ * root: States,
4706
+ * events: Events,
4707
+ * effects: { findName: (id: string) => Effect.succeed(`User ${id}`) }
4708
+ * }).handle({
4709
+ * initial: { target: "Idle" },
4710
+ * states: {
4711
+ * Idle: { on: { Load: { target: "Loading", data: ({ event }) => ({ id: event.id }) } } },
4712
+ * Loading: {
4713
+ * invoke: {
4714
+ * src: "findName",
4715
+ * input: ({ state }) => state.id,
4716
+ * onDone: { target: "Ready", data: ({ output }) => ({ name: output }) }
4717
+ * }
4718
+ * }
4719
+ * }
4720
+ * })
4721
+ *
4722
+ * const name = Effect.scoped(Effect.gen(function*() {
4723
+ * const ref = yield* Machine.start(machine)
4724
+ * yield* ref.send(Events.Load({ id: "1" }))
4725
+ * const ready = yield* Machine.waitFor(ref, ({ state }) => state.state.path === "Ready").pipe(Effect.timeout("5 seconds"))
4726
+ * return States.get(ready.state, "Ready").pipe(Option.map((state) => state.name))
4727
+ * }))
4728
+ *
4729
+ * await Effect.runPromise(name) // => Option.some("User 1")
4730
+ * ```
4731
+ *
4732
+ * **Example** (Counting with schema classes)
4733
+ *
4734
+ * ```ts import.meta.vitest
4735
+ * import { Machine } from "@typeonce/effect-machine"
4736
+ * import { Effect, Option, Schema } from "effect"
4737
+ *
4738
+ * class Count extends Schema.TaggedClass<Count>("Count")("Count", { value: Schema.Number }) {}
4739
+ * class Increment extends Schema.TaggedClass<Increment>("Increment")("Increment", { by: Schema.Number }) {}
4740
+ *
5087
4741
  * const States = Machine.state({ states: { Count } })
5088
- * const Events = Machine.eventsFromSchemas(Increment)
5089
4742
  * const counter = Machine.make({
5090
4743
  * root: States,
5091
- * events: Events
4744
+ * events: Machine.eventsFromSchemas(Increment)
5092
4745
  * }).handle({
5093
- * initial: {
5094
- * target: "Count",
5095
- * decoded: true,
5096
- * data: new Count({ value: 0 })
5097
- * },
4746
+ * initial: { target: "Count", decoded: true, data: new Count({ value: 0 }) },
5098
4747
  * states: {
5099
4748
  * Count: {
5100
4749
  * on: {
5101
4750
  * Increment: {
5102
- * update: "Count",
5103
- * decoded: true,
5104
- * data: ({ event, state }) => new Count({ value: state.value + event.by })
4751
+ * update: { Count: { decoded: true, data: ({ event, state }) => new Count({ value: state.value + event.by }) } }
5105
4752
  * }
5106
4753
  * }
5107
4754
  * }
5108
4755
  * }
5109
4756
  * })
4757
+ *
4758
+ * const value = Effect.gen(function*() {
4759
+ * const initial = yield* Machine.planInitial(counter)
4760
+ * const planned = yield* Machine.plan(counter, initial.state, new Increment({ by: 2 }))
4761
+ * return States.get(planned.next, "Count").pipe(Option.map((count) => count.value))
4762
+ * })
4763
+ *
4764
+ * await Effect.runPromise(value) // => Option.some(2)
5110
4765
  * ```
5111
4766
  *
5112
4767
  * @see {@link state} for typed state-tree helpers.
@@ -5122,53 +4777,76 @@ export declare const make: Make;
5122
4777
  * @since 0.10.0
5123
4778
  */
5124
4779
  export type EventOf<Protocol extends Machine.EventProtocol.Any> = Machine.EventOf<Machine.EventProtocolSchemas<Protocol>>;
4780
+ type EventFieldsSchemas<Cases extends Readonly<Record<string, Schema.Struct.Fields>>> = keyof Cases extends never ? readonly [] : readonly [
4781
+ Extract<Schema.TaggedUnion<{
4782
+ readonly [Tag in keyof Cases & string]: Schema.TaggedStruct<Tag, Cases[Tag]>;
4783
+ }>, Machine.TaggedSchema>
4784
+ ];
4785
+ type ValidateEventFields<Cases> = {
4786
+ readonly [Tag in keyof Cases]: "_tag" extends keyof Cases[Tag] ? EventProtocolError<"Event fields cannot declare _tag", Extract<Tag, PropertyKey>> : unknown;
4787
+ };
4788
+ /**
4789
+ * Defines a public event protocol from tagged field records.
4790
+ *
4791
+ * Constructors defer schema validation until delivery. Use
4792
+ * {@link eventsFromSchemas} when importing existing tagged schemas or protocol
4793
+ * descriptors.
4794
+ *
4795
+ * **Example** (Defining events from fields)
4796
+ *
4797
+ * ```ts import.meta.vitest
4798
+ * import { Machine } from "@typeonce/effect-machine"
4799
+ * import { Schema } from "effect"
4800
+ *
4801
+ * const Events = Machine.events({ Increment: { by: Schema.Number }, Reset: {} })
4802
+ *
4803
+ * Events.Increment({ by: 1 })._tag // => "Increment"
4804
+ * Events.Reset()._tag // => "Reset"
4805
+ * ```
4806
+ *
4807
+ * @category constructors
4808
+ * @since 0.32.0
4809
+ */
4810
+ export declare const events: <const Cases extends Readonly<Record<string, Schema.Struct.Fields>>>(cases: Cases & ValidateEventFields<NoInfer<Cases>> & ValidateEventProtocolBuilder<"public", EventFieldsSchemas<Cases>>) => Machine.EventProtocol<"public", EventFieldsSchemas<Cases>>;
5125
4811
  /**
5126
- * Defines a public event protocol and returns deferred constructors for every
5127
- * statically finite configured event tag.
4812
+ * Defines a public event protocol from existing tagged schemas or protocol
4813
+ * descriptors, without rebuilding their contracts, and returns deferred
4814
+ * constructors for every statically finite configured event tag.
5128
4815
  *
5129
4816
  * Constructor inputs retain their schema-derived required fields, defaults,
5130
4817
  * and transformations. Construction is deferred until delivery so failures
5131
4818
  * enter the machine's `MachineSchemaDecodeError` channel rather than throwing
5132
4819
  * at the call site.
5133
4820
  *
5134
- * **Example**
4821
+ * **Example** (Reusing a tagged union as the event protocol)
5135
4822
  *
5136
- * ```ts
5137
- * export const Event = Machine.eventsFromSchemas(
4823
+ * ```ts import.meta.vitest
4824
+ * import { Machine } from "@typeonce/effect-machine"
4825
+ * import { Effect, Schema } from "effect"
4826
+ *
4827
+ * const Event = Machine.eventsFromSchemas(
5138
4828
  * Schema.TaggedUnion({
5139
4829
  * Increment: { by: Schema.Number },
5140
4830
  * Reset: {}
5141
4831
  * })
5142
4832
  * )
5143
- * const machine = Machine.make({ events: Event, ... })
5144
- * yield* ref.send(Event.Increment({ by: 1 }))
5145
- * ```
4833
+ * const machine = Machine.make({ root: Machine.state({ fields: { count: Schema.Number } }), events: Event }).handle({
4834
+ * root: { count: 0 },
4835
+ * on: {
4836
+ * Increment: { update: { root: ({ root, event }) => ({ count: root.count + event.by }) } },
4837
+ * Reset: { update: { root: { count: 0 } } }
4838
+ * }
4839
+ * })
5146
4840
  *
5147
- * @category constructors
5148
- * @since 0.10.0
5149
- */
5150
- type EventFieldsSchemas<Cases extends Readonly<Record<string, Schema.Struct.Fields>>> = keyof Cases extends never ? readonly [] : readonly [
5151
- Extract<Schema.TaggedUnion<{
5152
- readonly [Tag in keyof Cases & string]: Schema.TaggedStruct<Tag, Cases[Tag]>;
5153
- }>, Machine.TaggedSchema>
5154
- ];
5155
- type ValidateEventFields<Cases> = {
5156
- readonly [Tag in keyof Cases]: "_tag" extends keyof Cases[Tag] ? EventProtocolError<"Event fields cannot declare _tag", Extract<Tag, PropertyKey>> : unknown;
5157
- };
5158
- /** Defines a public event protocol from tagged field records.
4841
+ * const count = Effect.scoped(Effect.gen(function*() {
4842
+ * const ref = yield* Machine.start(machine)
4843
+ * yield* ref.send(Event.Increment({ by: 1 }))
4844
+ * return (yield* ref.state).value.count
4845
+ * }))
5159
4846
  *
5160
- * ```ts
5161
- * const Events = Machine.events({ Increment: { by: Schema.Number }, Reset: {} })
5162
- * const increment = Events.Increment({ by: 1 })
4847
+ * await Effect.runPromise(count) // => 1
5163
4848
  * ```
5164
4849
  *
5165
- * Constructors defer schema validation until delivery. Use eventsFromSchemas
5166
- * when importing existing tagged schemas or protocol descriptors.
5167
- * @category constructors
5168
- * @since 0.32.0
5169
- */
5170
- export declare const events: <const Cases extends Readonly<Record<string, Schema.Struct.Fields>>>(cases: Cases & ValidateEventFields<NoInfer<Cases>> & ValidateEventProtocolBuilder<"public", EventFieldsSchemas<Cases>>) => Machine.EventProtocol<"public", EventFieldsSchemas<Cases>>;
5171
- /** Imports existing schemas and protocols without rebuilding their contracts.
5172
4850
  * @category constructors
5173
4851
  * @since 0.32.0
5174
4852
  */
@@ -5202,28 +4880,48 @@ export declare const optionalParent: <const Events extends ReadonlyArray<Machine
5202
4880
  *
5203
4881
  * Use these constructors for raised events and other machine-local deliveries.
5204
4882
  * Construction failures are reported through the
5205
- * owning machine's `MachineSchemaDecodeError` channel.
4883
+ * owning machine's `MachineSchemaDecodeError` channel. Use
4884
+ * {@link internalEventsFromSchemas} when importing existing tagged schemas or
4885
+ * protocol descriptors.
5206
4886
  *
5207
- * **Example**
4887
+ * **Example** (Raising an internal event)
5208
4888
  *
5209
- * ```ts
5210
- * const Internal = Machine.internalEventsFromSchemas(
5211
- * Schema.TaggedUnion({
5212
- * Loaded: { value: Schema.String },
5213
- * Failed: { message: Schema.String }
5214
- * })
5215
- * )
5216
- * const machine = Machine.make({ internalEvents: Internal, ... })
4889
+ * ```ts import.meta.vitest
4890
+ * import { Machine } from "@typeonce/effect-machine"
4891
+ * import { Effect, Schema } from "effect"
5217
4892
  *
5218
- * // Inside a transition callback:
5219
- * enqueue.raise(Internal.Loaded({ value }))
4893
+ * const Events = Machine.events({ Load: { value: Schema.String } })
4894
+ * const Internal = Machine.internalEvents({ Loaded: { value: Schema.String }, Failed: { message: Schema.String } })
4895
+ * const machine = Machine.make({
4896
+ * root: Machine.state({ fields: { value: Schema.String } }),
4897
+ * events: Events,
4898
+ * internalEvents: Internal
4899
+ * }).handle({
4900
+ * root: { value: "" },
4901
+ * on: {
4902
+ * Load: { stay: true, commands: ({ event }, enqueue) => enqueue.raise(Internal.Loaded({ value: event.value })) },
4903
+ * Loaded: { update: { root: ({ event }) => ({ value: event.value }) } },
4904
+ * Failed: { stay: true }
4905
+ * }
4906
+ * })
4907
+ *
4908
+ * const value = Effect.gen(function*() {
4909
+ * const initial = yield* Machine.planInitial(machine)
4910
+ * const planned = yield* Machine.plan(machine, initial.state, Events.Load({ value: "ready" }))
4911
+ * return planned.next.value.value
4912
+ * })
4913
+ *
4914
+ * await Effect.runPromise(value) // => "ready"
5220
4915
  * ```
5221
4916
  *
5222
4917
  * @category constructors
5223
4918
  * @since 0.10.0
5224
4919
  */
5225
4920
  export declare const internalEvents: <const Cases extends Readonly<Record<string, Schema.Struct.Fields>>>(cases: Cases & ValidateEventFields<NoInfer<Cases>> & ValidateEventProtocolBuilder<"internal", EventFieldsSchemas<Cases>>) => Machine.EventProtocol<"internal", EventFieldsSchemas<Cases>>;
5226
- /** Imports existing schemas and protocols without rebuilding their contracts.
4921
+ /**
4922
+ * Defines an internal event protocol from existing tagged schemas or protocol
4923
+ * descriptors, without rebuilding their contracts.
4924
+ *
5227
4925
  * @category constructors
5228
4926
  * @since 0.32.0
5229
4927
  */
@@ -5234,24 +4932,47 @@ export declare const internalEventsFromSchemas: {
5234
4932
  * Defines the ephemeral notifications a machine may publish to external
5235
4933
  * observers. Emitted events are separate from machine input and are never sent
5236
4934
  * implicitly to a parent machine. Observe them through `MachineRef.emissions` or
5237
- * the AtomMachine emission stream adapters.
4935
+ * the AtomMachine emission stream adapters. Use {@link emittedEventsFromSchemas}
4936
+ * when importing existing tagged schemas or protocol descriptors.
5238
4937
  *
5239
- * **Example**
4938
+ * **Example** (Emitting an event to observers)
5240
4939
  *
5241
- * ```ts
5242
- * const Emitted = Machine.emittedEventsFromSchemas(
5243
- * Schema.TaggedUnion({
5244
- * Saved: { id: Schema.String }
5245
- * })
5246
- * )
5247
- * const machine = Machine.make({ emittedEvents: Emitted, ... })
4940
+ * ```ts import.meta.vitest
4941
+ * import { Machine } from "@typeonce/effect-machine"
4942
+ * import { Effect, Schema } from "effect"
4943
+ *
4944
+ * const Events = Machine.events({ Save: { id: Schema.String } })
4945
+ * const Emitted = Machine.emittedEvents({ Saved: { id: Schema.String } })
4946
+ * const machine = Machine.make({
4947
+ * root: Machine.state({ states: { Idle: {} } }),
4948
+ * events: Events,
4949
+ * emittedEvents: Emitted
4950
+ * }).handle({
4951
+ * initial: { target: "Idle" },
4952
+ * states: {
4953
+ * Idle: {
4954
+ * on: { Save: { stay: true, commands: ({ event }, enqueue) => enqueue.emit(Emitted.Saved({ id: event.id })) } }
4955
+ * }
4956
+ * }
4957
+ * })
4958
+ *
4959
+ * const emitted = Effect.gen(function*() {
4960
+ * const initial = yield* Machine.planInitial(machine)
4961
+ * const planned = yield* Machine.plan(machine, initial.state, Events.Save({ id: "a" }))
4962
+ * return planned.emittedEvents.length
4963
+ * })
4964
+ *
4965
+ * await Effect.runPromise(emitted) // => 1
5248
4966
  * ```
5249
4967
  *
5250
4968
  * @category constructors
5251
4969
  * @since 0.10.0
5252
4970
  */
5253
4971
  export declare const emittedEvents: <const Cases extends Readonly<Record<string, Schema.Struct.Fields>>>(cases: Cases & ValidateEventFields<NoInfer<Cases>> & ValidateEventProtocolBuilder<"emitted", EventFieldsSchemas<Cases>>) => Machine.EventProtocol<"emitted", EventFieldsSchemas<Cases>>;
5254
- /** Imports existing schemas and protocols without rebuilding their contracts.
4972
+ /**
4973
+ * Defines an emitted event protocol from existing tagged schemas or protocol
4974
+ * descriptors, without rebuilding their contracts.
4975
+ *
5255
4976
  * @category constructors
5256
4977
  * @since 0.32.0
5257
4978
  */
@@ -5284,29 +5005,24 @@ export declare const emittedEventsFromSchemas: {
5284
5005
  * Define an explicit JSON codec or keep process-local capabilities outside the
5285
5006
  * logical snapshot.
5286
5007
  *
5287
- * **Example**
5008
+ * **Example** (Encoding a snapshot for storage)
5288
5009
  *
5289
- * ```ts
5010
+ * ```ts import.meta.vitest
5290
5011
  * import { Machine } from "@typeonce/effect-machine"
5291
- * import { Effect, Schema } from "effect"
5292
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
5293
- * }
5294
- * const States = Machine.state({ states: { Idle } })
5295
- * const machine = Machine.make({
5296
- * root: States,
5297
- * events: Machine.eventsFromSchemas()
5298
- * }).handle({
5299
- * initial: {
5300
- * target: "Idle"
5301
- * },
5302
- * states: {
5303
- * Idle: {}
5304
- * }
5012
+ * import { Effect } from "effect"
5013
+ *
5014
+ * const States = Machine.state({ states: { Idle: {} } })
5015
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
5016
+ * initial: { target: "Idle" }
5305
5017
  * })
5018
+ *
5306
5019
  * const encoded = Effect.gen(function*() {
5307
5020
  * const initial = yield* Machine.planInitial(machine)
5308
- * return yield* Machine.encodeSnapshot(machine, initial.state)
5021
+ * const snapshot = yield* Machine.encodeSnapshot(machine, initial.state)
5022
+ * return typeof snapshot
5309
5023
  * })
5024
+ *
5025
+ * await Effect.runPromise(encoded) // => "object"
5310
5026
  * ```
5311
5027
  *
5312
5028
  * @see {@link decodeSnapshot} for restoring an encoded snapshot.
@@ -5333,30 +5049,25 @@ export declare const encodeSnapshot: <const States extends Machine.StateSchemas,
5333
5049
  * Decoding restores logical statechart data only. It does not restart invoked
5334
5050
  * processes, recreate spawned children, or restore a previous `MachineRef`.
5335
5051
  *
5336
- * **Example**
5052
+ * **Example** (Restoring an encoded snapshot)
5337
5053
  *
5338
- * ```ts
5054
+ * ```ts import.meta.vitest
5339
5055
  * import { Machine } from "@typeonce/effect-machine"
5340
- * import { Effect, Schema } from "effect"
5341
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
5342
- * }
5343
- * const States = Machine.state({ states: { Idle } })
5344
- * const machine = Machine.make({
5345
- * root: States,
5346
- * events: Machine.eventsFromSchemas()
5347
- * }).handle({
5348
- * initial: {
5349
- * target: "Idle"
5350
- * },
5351
- * states: {
5352
- * Idle: {}
5353
- * }
5056
+ * import { Effect } from "effect"
5057
+ *
5058
+ * const States = Machine.state({ states: { Idle: {} } })
5059
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
5060
+ * initial: { target: "Idle" }
5354
5061
  * })
5355
- * const roundTrip = Effect.gen(function*() {
5062
+ *
5063
+ * const path = Effect.gen(function*() {
5356
5064
  * const initial = yield* Machine.planInitial(machine)
5357
5065
  * const encoded = yield* Machine.encodeSnapshot(machine, initial.state)
5358
- * return yield* Machine.decodeSnapshot(machine, encoded)
5066
+ * const decoded = yield* Machine.decodeSnapshot(machine, encoded)
5067
+ * return decoded.state.path
5359
5068
  * })
5069
+ *
5070
+ * await Effect.runPromise(path) // => "Idle"
5360
5071
  * ```
5361
5072
  *
5362
5073
  * @see {@link encodeSnapshot} for creating the normalized representation.
@@ -5364,20 +5075,6 @@ export declare const encodeSnapshot: <const States extends Machine.StateSchemas,
5364
5075
  * @since 0.4.0
5365
5076
  */
5366
5077
  export declare const decodeSnapshot: <const States extends Machine.StateSchemas, const Events extends ReadonlyArray<Machine.TaggedSchema>, const Emits extends ReadonlyArray<Machine.TaggedSchema> = readonly [], const Input extends Schema.Top = typeof Schema.Void, UnhandledStates extends Machine.StateIdentifier<States> = Machine.StateIdentifier<States>, E = never, R = never, InitialE = never, InitialR = never, FinalStates extends Machine.StateIdentifier<States> = never, Output = never, OutputStates extends Machine.StateIdentifier<States> = never, InputEvents extends ReadonlyArray<Machine.TaggedSchema> = Events, ParentEvents extends ReadonlyArray<Machine.TaggedSchema> = readonly []>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents>, encoded: unknown) => Effect.Effect<Machine.Snapshot<States>, MachineSchemaDecodeError, Machine.SnapshotDecodingServices<States>>;
5367
- type TransitionBranchRecordError<Message extends string, Key extends PropertyKey = never> = {
5368
- readonly "~effect/Machine/TransitionBranchRecordError": Message;
5369
- readonly key: Key;
5370
- };
5371
- type InvalidStaticTransitionBranchKey<Branches> = Extract<keyof Branches, "" | number | symbol | `${number}` | "NaN" | "Infinity" | "-Infinity">;
5372
- type ValidateTransitionBranchRecord<Branches> = [keyof Branches] extends [never] ? TransitionBranchRecordError<"Branch records must contain at least one branch"> : [InvalidStaticTransitionBranchKey<Branches>] extends [never] ? {
5373
- readonly [K in keyof Branches]: {
5374
- readonly [Extra in Exclude<keyof Branches[K], "target" | "update" | "initialize" | "initial" | "history" | "none" | "title">]: never;
5375
- } & (Branches[K] extends {
5376
- readonly title: "";
5377
- } ? {
5378
- readonly title: never;
5379
- } : unknown);
5380
- } : TransitionBranchRecordError<"Branch keys must be non-empty, non-numeric strings", InvalidStaticTransitionBranchKey<Branches>>;
5381
5078
  /**
5382
5079
  * Plans the initial state for a machine without executing machine commands.
5383
5080
  *
@@ -5396,26 +5093,20 @@ type ValidateTransitionBranchRecord<Branches> = [keyof Branches] extends [never]
5396
5093
  * protocol. Manual planners may inspect commands but need running machine targets
5397
5094
  * to execute child-addressed operations.
5398
5095
  *
5399
- * **Example**
5096
+ * **Example** (Planning startup without running the machine)
5400
5097
  *
5401
- * ```ts
5098
+ * ```ts import.meta.vitest
5402
5099
  * import { Machine } from "@typeonce/effect-machine"
5403
- * import { Effect, Schema } from "effect"
5404
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
5405
- * }
5406
- * const States = Machine.state({ states: { Idle } })
5407
- * const machine = Machine.make({
5408
- * root: States,
5409
- * events: Machine.eventsFromSchemas()
5410
- * }).handle({
5411
- * initial: {
5412
- * target: "Idle"
5413
- * },
5414
- * states: {
5415
- * Idle: {}
5416
- * }
5100
+ * import { Effect } from "effect"
5101
+ *
5102
+ * const States = Machine.state({ states: { Idle: {} } })
5103
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
5104
+ * initial: { target: "Idle" }
5417
5105
  * })
5418
- * const initialState = Effect.map(Machine.planInitial(machine), (plan) => plan.state)
5106
+ *
5107
+ * const path = Effect.map(Machine.planInitial(machine), (plan) => plan.state.state.path)
5108
+ *
5109
+ * await Effect.runPromise(path) // => "Idle"
5419
5110
  * ```
5420
5111
  *
5421
5112
  * @see {@link plan} for planning a received event.
@@ -5467,9 +5158,9 @@ export declare const stateNodes: <M extends Machine.Any>(machine: M) => Readonly
5467
5158
  /**
5468
5159
  * Returns the statically selected root entry used during machine startup.
5469
5160
  *
5470
- * This function does not execute the initial resolver or require machine
5471
- * input. `kind: "initial"` means that the selected root enters its declared
5472
- * initial configuration.
5161
+ * This function does not construct initial state values or require machine
5162
+ * input. `kind: "initial"` means that the root enters its declared initial
5163
+ * configuration.
5473
5164
  *
5474
5165
  * @category getters
5475
5166
  * @since 0.14.0
@@ -5480,7 +5171,8 @@ export declare const initialDefinition: <M extends Machine.Any>(machine: M) => M
5480
5171
  *
5481
5172
  * **Details**
5482
5173
  *
5483
- * The returned tuple retains the schemas supplied to {@link events}, including
5174
+ * The returned tuple retains the schemas supplied to {@link events} or
5175
+ * {@link eventsFromSchemas}, including
5484
5176
  * grouped tagged unions. Internal and emitted event schemas are excluded. This
5485
5177
  * getter is intended for tooling that needs to describe or construct valid
5486
5178
  * external inputs without reaching into the opaque event protocol.
@@ -5490,16 +5182,16 @@ export declare const initialDefinition: <M extends Machine.Any>(machine: M) => M
5490
5182
  */
5491
5183
  export declare const inputEventSchemas: <M extends Machine.Any>(machine: M) => Machine.InputEvents<M>;
5492
5184
  /**
5493
- * Returns every registered transition handler in state definition order.
5185
+ * Returns every declared transition in state definition order.
5494
5186
  *
5495
5187
  * **Details**
5496
5188
  *
5497
- * Event handlers retain their handler-key order within each source state and
5498
- * are followed by eventless and completion handlers. This function does not
5189
+ * Event transitions retain their key order within each source state and are
5190
+ * followed by eventless and completion transitions. This function does not
5499
5191
  * execute resolvers. Every branch exposes its static selection. State updates
5500
5192
  * retain the updated owner in `selection.path` while leaving `target`
5501
5193
  * undefined because they do not change topology. `acceptance` reports whether
5502
- * the resolver may decline the transition.
5194
+ * the transition may decline the event.
5503
5195
  *
5504
5196
  * @category getters
5505
5197
  * @since 0.4.0
@@ -5510,7 +5202,7 @@ export declare const transitionDefinitions: <M extends Machine.Any>(machine: M)
5510
5202
  *
5511
5203
  * **Details**
5512
5204
  *
5513
- * Static inline invocation definitions expose stable ownership and lifecycle
5205
+ * Static invocation definitions expose stable ownership and lifecycle
5514
5206
  * metadata without serializing runtime values. Function-valued sources are
5515
5207
  * represented as dynamic and are never evaluated during inspection.
5516
5208
  *
@@ -5535,7 +5227,7 @@ export declare const configuration: <M extends Machine.Any>(machine: M, state: M
5535
5227
  * Returns event tags with at least one structurally eligible handler in the
5536
5228
  * current state snapshot.
5537
5229
  *
5538
- * A `declinable` handler may still reject a concrete event at planning time,
5230
+ * A handler with `guard` or `{ decline: true }` may still reject a concrete event at planning time,
5539
5231
  * so this is a static candidate query rather than a guarantee that every value
5540
5232
  * with the returned tag will be handled.
5541
5233
  *
@@ -5549,9 +5241,10 @@ export declare const enabled: <const States extends Machine.StateSchemas, const
5549
5241
  *
5550
5242
  * **Details**
5551
5243
  *
5552
- * Required handlers are accepted from their structural eligibility.
5553
- * Declinable handlers run their resolver only far enough to decide whether
5554
- * they accept the event. Any commands, emissions, or raised events collected
5244
+ * Required transitions are accepted from their structural eligibility.
5245
+ * Declinable transitions, which have a `guard` or a `{ decline: true }` entry,
5246
+ * run their guard or resolver only far enough to decide whether they accept
5247
+ * the event. Any commands, emissions, or raised events collected
5555
5248
  * during that check are discarded.
5556
5249
  *
5557
5250
  * Event input is decoded through the machine's public and internal event protocols.
@@ -5569,9 +5262,9 @@ export declare const enabled: <const States extends Machine.StateSchemas, const
5569
5262
  * Synchronous transition resolvers cannot execute it. Querying an internal event
5570
5263
  * does not make that event available to `MachineRef.send`.
5571
5264
  *
5572
- * **Example**
5265
+ * **Example** (Checking an event against the current state)
5573
5266
  *
5574
- * ```ts
5267
+ * ```ts import.meta.vitest
5575
5268
  * import { Machine } from "@typeonce/effect-machine"
5576
5269
  * import { Effect, Schema } from "effect"
5577
5270
  *
@@ -5583,13 +5276,15 @@ export declare const enabled: <const States extends Machine.StateSchemas, const
5583
5276
  * internalEvents
5584
5277
  * }).handle({
5585
5278
  * initial: { target: "Idle" },
5586
- * states: { Idle: { on: { Loaded: { none: true } } } }
5279
+ * states: { Idle: { on: { Loaded: { stay: true } } } }
5587
5280
  * })
5588
5281
  *
5589
- * export const canLoad = Effect.gen(function*() {
5282
+ * const canLoad = Effect.gen(function*() {
5590
5283
  * const initial = yield* Machine.planInitial(machine)
5591
5284
  * return yield* Machine.can(machine, initial.state, internalEvents.Loaded())
5592
5285
  * })
5286
+ *
5287
+ * await Effect.runPromise(canLoad) // => true
5593
5288
  * ```
5594
5289
  *
5595
5290
  * @category getters
@@ -5616,38 +5311,30 @@ export declare const can: {
5616
5311
  * `emittedEvents`. Events with no enabled transition are ignored and produce
5617
5312
  * an unchanged plan.
5618
5313
  *
5619
- * **Example**
5314
+ * **Example** (Planning one event without running the machine)
5620
5315
  *
5621
- * ```ts
5316
+ * ```ts import.meta.vitest
5622
5317
  * import { Machine } from "@typeonce/effect-machine"
5623
- * import { Effect, Schema } from "effect"
5624
- * class Off extends Schema.TaggedClass<Off>("Off")("Off", {}) {
5625
- * }
5626
- * class On extends Schema.TaggedClass<On>("On")("On", {}) {
5627
- * }
5628
- * class Toggle extends Schema.TaggedClass<Toggle>("Toggle")("Toggle", {}) {
5629
- * }
5630
- * const States = Machine.state({ states: { Off, On } })
5318
+ * import { Effect } from "effect"
5319
+ *
5320
+ * const Events = Machine.events({ Toggle: {} })
5631
5321
  * const machine = Machine.make({
5632
- * root: States,
5633
- * events: Machine.eventsFromSchemas(Toggle)
5322
+ * root: Machine.state({ states: { Off: {}, On: {} } }),
5323
+ * events: Events
5634
5324
  * }).handle({
5635
- * initial: {
5636
- * target: "Off"
5637
- * },
5325
+ * initial: { target: "Off" },
5638
5326
  * states: {
5639
- * Off: {
5640
- * on: {
5641
- * Toggle: { target: "On" }
5642
- * }
5643
- * },
5644
- * On: {}
5327
+ * Off: { on: { Toggle: { target: "On" } } }
5645
5328
  * }
5646
5329
  * })
5647
- * const nextState = Effect.gen(function*() {
5330
+ *
5331
+ * const path = Effect.gen(function*() {
5648
5332
  * const initial = yield* Machine.planInitial(machine)
5649
- * return (yield* Machine.plan(machine, initial.state, new Toggle({}))).next
5333
+ * const planned = yield* Machine.plan(machine, initial.state, Events.Toggle())
5334
+ * return planned.next.state.path
5650
5335
  * })
5336
+ *
5337
+ * await Effect.runPromise(path) // => "On"
5651
5338
  * ```
5652
5339
  *
5653
5340
  * @see {@link planInitial} for planning machine startup.
@@ -5703,13 +5390,16 @@ export declare const plan: <const States extends Machine.StateSchemas, const Eve
5703
5390
  * which machine will eventually own it. Prefer typed output, typed child
5704
5391
  * addresses, or invocation lifecycle transitions when possible.
5705
5392
  *
5706
- * Use an inline `invoke` with an `effect` source for one-shot work.
5707
- * @see {@link transition} for event-driven state.
5393
+ * For one-shot work, register an Effect in `make({ effects })` and invoke it
5394
+ * with `invoke: { src }` instead. Register logic in `make({ logic })` to run it
5395
+ * for the lifetime of one state.
5396
+ *
5397
+ * @see {@link make} for registering sources that states invoke by name.
5708
5398
  * @category constructors
5709
5399
  * @since 0.4.0
5710
5400
  */
5711
5401
  export declare const logic: <State, Event = never, Output = void, Error = never, Requirements = never, InitialError = never, InitialRequirements = never>(options: {
5712
- /** Enters a compound or parallel subtree through its declared initialization. */
5402
+ /** The first state, or an Effect that produces it from the process scope before `run` starts. */
5713
5403
  readonly initial: State | ((scope: Logic.Scope<Event>) => Effect.Effect<State, InitialError, InitialRequirements>);
5714
5404
  readonly run: (context: Logic.Context<State, Event>) => Effect.Effect<Output, Error, Requirements>;
5715
5405
  }) => Logic<State, Event, Error, Requirements | InitialRequirements, Output, InitialError>;
@@ -5774,8 +5464,8 @@ export declare const spawn: {
5774
5464
  * @since 0.4.0
5775
5465
  */
5776
5466
  export declare const sendTo: {
5777
- <Child extends ChildMachine.Any>(child: Child, event: ChildMachine.Event<Child>): Effect.Effect<void, StoppedError, MachineRuntimeRequirement>;
5778
- <Address extends ChildAddress<never>>(id: Address, event: ChildAddress.Event<Address>): Effect.Effect<void, StoppedError, MachineRuntimeRequirement>;
5467
+ <Child extends ChildMachine.Any>(child: Child, event: ChildMachine.Event<Child>): Effect.Effect<void, StoppedError, MachineRuntime>;
5468
+ <Address extends ChildAddress<never>>(id: Address, event: ChildAddress.Event<Address>): Effect.Effect<void, StoppedError, MachineRuntime>;
5779
5469
  };
5780
5470
  /**
5781
5471
  * Stops a named child process of the running machine.
@@ -5784,8 +5474,8 @@ export declare const sendTo: {
5784
5474
  * @since 0.4.0
5785
5475
  */
5786
5476
  export declare const stopChild: {
5787
- <Event>(child: ChildAddress<Event>): Effect.Effect<void, never, MachineRuntimeRequirement>;
5788
- <Child extends ChildMachine.Any>(child: Child): Effect.Effect<void, never, MachineRuntimeRequirement>;
5477
+ <Event>(child: ChildAddress<Event>): Effect.Effect<void, never, MachineRuntime>;
5478
+ <Child extends ChildMachine.Any>(child: Child): Effect.Effect<void, never, MachineRuntime>;
5789
5479
  };
5790
5480
  /**
5791
5481
  * Returns a stream of terminal lifecycle outcomes for a running machine.
@@ -5811,9 +5501,31 @@ export declare const watch: <State, Event, Error = never, Output = never>(ref: M
5811
5501
  * Type predicates narrow the returned snapshot. Intermediate microsteps and
5812
5502
  * historical snapshots are not observed.
5813
5503
  *
5814
- * @example
5815
- * ```ts
5816
- * const snapshot = yield* Machine.waitFor(ref, isReady).pipe(Effect.timeout("5 seconds"))
5504
+ * **Example** (Waiting for a state with a timeout)
5505
+ *
5506
+ * ```ts import.meta.vitest
5507
+ * import { Machine } from "@typeonce/effect-machine"
5508
+ * import { Effect } from "effect"
5509
+ *
5510
+ * const Events = Machine.events({ Finish: {} })
5511
+ * const machine = Machine.make({
5512
+ * root: Machine.state({ states: { Working: {}, Ready: {} } }),
5513
+ * events: Events
5514
+ * }).handle({
5515
+ * initial: { target: "Working" },
5516
+ * states: {
5517
+ * Working: { on: { Finish: { target: "Ready" } } }
5518
+ * }
5519
+ * })
5520
+ *
5521
+ * const path = Effect.scoped(Effect.gen(function*() {
5522
+ * const ref = yield* Machine.start(machine)
5523
+ * yield* ref.send(Events.Finish())
5524
+ * const ready = yield* Machine.waitFor(ref, ({ state }) => state.state.path === "Ready").pipe(Effect.timeout("5 seconds"))
5525
+ * return ready.state.state.path
5526
+ * }))
5527
+ *
5528
+ * await Effect.runPromise(path) // => "Ready"
5817
5529
  * ```
5818
5530
  * @category combinators
5819
5531
  * @since 0.37.0
@@ -5835,15 +5547,41 @@ export declare const waitFor: {
5835
5547
  * `prepared.start` is one-shot and scoped: the `Scope` that first evaluates it
5836
5548
  * owns the machine, and closing that `Scope` is equivalent to `ref.stop`.
5837
5549
  *
5838
- * ```ts
5839
- * const prepared = yield* Machine.prepare(machine)
5550
+ * **Example** (Observing emissions before startup)
5840
5551
  *
5841
- * yield* prepared.emissions.pipe(
5842
- * Stream.runForEach(handleEmission),
5843
- * Effect.forkScoped({ startImmediately: true })
5844
- * )
5552
+ * ```ts import.meta.vitest
5553
+ * import { Machine } from "@typeonce/effect-machine"
5554
+ * import { Effect, Stream } from "effect"
5555
+ *
5556
+ * const Emitted = Machine.emittedEvents({ Started: {} })
5557
+ * const machine = Machine.make({
5558
+ * root: Machine.state({ states: { Idle: {} } }),
5559
+ * events: Machine.events({}),
5560
+ * emittedEvents: Emitted
5561
+ * }).handle({
5562
+ * initial: { target: "Idle" },
5563
+ * states: {
5564
+ * Idle: {
5565
+ * entry: (_, enqueue) => {
5566
+ * enqueue.emit(Emitted.Started())
5567
+ * }
5568
+ * }
5569
+ * }
5570
+ * })
5571
+ *
5572
+ * const emitted = Effect.scoped(Effect.gen(function*() {
5573
+ * const prepared = yield* Machine.prepare(machine)
5574
+ * const seen: Array<string> = []
5575
+ * yield* prepared.emissions.pipe(
5576
+ * Stream.runForEach((event) => Effect.sync(() => seen.push(event._tag))),
5577
+ * Effect.forkScoped({ startImmediately: true })
5578
+ * )
5579
+ * yield* prepared.start
5580
+ * yield* Effect.yieldNow
5581
+ * return seen
5582
+ * }))
5845
5583
  *
5846
- * const ref = yield* prepared.start
5584
+ * await Effect.runPromise(emitted) // => ["Started"]
5847
5585
  * ```
5848
5586
  *
5849
5587
  * @category constructors
@@ -5879,29 +5617,23 @@ export declare const prepare: <const States extends Machine.StateSchemas, const
5879
5617
  * rather than being returned by `send`. Sending after the machine reaches any
5880
5618
  * terminal state fails immediately with `StoppedError`.
5881
5619
  *
5882
- * **Example**
5620
+ * **Example** (Starting a machine in a scope)
5883
5621
  *
5884
- * ```ts
5622
+ * ```ts import.meta.vitest
5885
5623
  * import { Machine } from "@typeonce/effect-machine"
5886
- * import { Effect, Schema } from "effect"
5887
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
5888
- * }
5889
- * const States = Machine.state({ states: { Idle } })
5890
- * const machine = Machine.make({
5891
- * root: States,
5892
- * events: Machine.eventsFromSchemas()
5893
- * }).handle({
5894
- * initial: {
5895
- * target: "Idle"
5896
- * },
5897
- * states: {
5898
- * Idle: {}
5899
- * }
5624
+ * import { Effect } from "effect"
5625
+ *
5626
+ * const States = Machine.state({ states: { Idle: {} } })
5627
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
5628
+ * initial: { target: "Idle" }
5900
5629
  * })
5901
- * const state = Effect.scoped(Effect.gen(function*() {
5630
+ *
5631
+ * const path = Effect.scoped(Effect.gen(function*() {
5902
5632
  * const ref = yield* Machine.start(machine)
5903
- * return yield* ref.state
5633
+ * return (yield* ref.state).state.path
5904
5634
  * }))
5635
+ *
5636
+ * await Effect.runPromise(path) // => "Idle"
5905
5637
  * ```
5906
5638
  *
5907
5639
  * @see {@link plan} for inspecting the same transition plan without executing it.
@@ -5920,7 +5652,7 @@ export declare const start: <const States extends Machine.StateSchemas, const Ev
5920
5652
  * the `Scope` is equivalent to `ref.stop`.
5921
5653
  *
5922
5654
  * `resume` validates and normalizes the supplied snapshot before publishing it
5923
- * as the first state. It does not call the machine's initial function, replay
5655
+ * as the first state. It does not construct the declared initial state, replay
5924
5656
  * entry or transition actions, re-deliver raised or emitted events, or
5925
5657
  * re-evaluate historical completion and eventless transitions. Active-state
5926
5658
  * invokes start once in ancestor and document order with {@link InitialEvent};
@@ -5938,31 +5670,26 @@ export declare const start: <const States extends Machine.StateSchemas, const Ev
5938
5670
  * evaluated merely because the runtime was resumed; only ordinary subsequent
5939
5671
  * transition planning can enter and stabilize states.
5940
5672
  *
5941
- * **Example**
5673
+ * **Example** (Resuming from a decoded snapshot)
5942
5674
  *
5943
- * ```ts
5675
+ * ```ts import.meta.vitest
5944
5676
  * import { Machine } from "@typeonce/effect-machine"
5945
- * import { Effect, Schema } from "effect"
5946
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
5947
- * }
5948
- * const States = Machine.state({ states: { Idle } })
5949
- * const machine = Machine.make({
5950
- * root: States,
5951
- * events: Machine.eventsFromSchemas()
5952
- * }).handle({
5953
- * initial: {
5954
- * target: "Idle"
5955
- * },
5956
- * states: {
5957
- * Idle: {}
5958
- * }
5677
+ * import { Effect } from "effect"
5678
+ *
5679
+ * const States = Machine.state({ states: { Idle: {} } })
5680
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
5681
+ * initial: { target: "Idle" }
5959
5682
  * })
5960
- * const resumed = Effect.scoped(Effect.gen(function*() {
5683
+ *
5684
+ * const path = Effect.scoped(Effect.gen(function*() {
5961
5685
  * const initial = yield* Machine.planInitial(machine)
5962
5686
  * const encoded = yield* Machine.encodeSnapshot(machine, initial.state)
5963
5687
  * const snapshot = yield* Machine.decodeSnapshot(machine, encoded)
5964
- * return yield* Machine.resume(machine, snapshot)
5688
+ * const ref = yield* Machine.resume(machine, snapshot)
5689
+ * return (yield* ref.state).state.path
5965
5690
  * }))
5691
+ *
5692
+ * await Effect.runPromise(path) // => "Idle"
5966
5693
  * ```
5967
5694
  *
5968
5695
  * @see {@link decodeSnapshot} for the schema and transport boundary.