@typeonce/effect-machine 0.3.0 → 0.5.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 (170) hide show
  1. package/README.md +410 -17
  2. package/dist/Machine.d.ts +1191 -510
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +371 -565
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/activities.d.ts +57 -0
  7. package/dist/internal/machine/activities.d.ts.map +1 -0
  8. package/dist/internal/machine/activities.js +49 -0
  9. package/dist/internal/machine/activities.js.map +1 -0
  10. package/dist/internal/machine/atom.d.ts +69 -0
  11. package/dist/internal/machine/atom.d.ts.map +1 -0
  12. package/dist/{AtomMachine.js → internal/machine/atom.js} +20 -95
  13. package/dist/internal/machine/atom.js.map +1 -0
  14. package/dist/internal/machine/cluster.d.ts +63 -0
  15. package/dist/internal/machine/cluster.d.ts.map +1 -0
  16. package/dist/{ClusterMachine.js → internal/machine/cluster.js} +15 -119
  17. package/dist/internal/machine/cluster.js.map +1 -0
  18. package/dist/internal/machine/command.d.ts +16 -0
  19. package/dist/internal/machine/command.d.ts.map +1 -0
  20. package/dist/internal/machine/command.js +45 -0
  21. package/dist/internal/machine/command.js.map +1 -0
  22. package/dist/internal/machine/commandRuntime.d.ts +13 -0
  23. package/dist/internal/machine/commandRuntime.d.ts.map +1 -0
  24. package/dist/internal/machine/commandRuntime.js +16 -0
  25. package/dist/internal/machine/commandRuntime.js.map +1 -0
  26. package/dist/internal/{machineModel.d.ts → machine/configuration.d.ts} +12 -61
  27. package/dist/internal/machine/configuration.d.ts.map +1 -0
  28. package/dist/internal/{machineModel.js → machine/configuration.js} +250 -545
  29. package/dist/internal/machine/configuration.js.map +1 -0
  30. package/dist/internal/{machineErrors.d.ts → machine/errors.d.ts} +8 -8
  31. package/dist/internal/machine/errors.d.ts.map +1 -0
  32. package/dist/internal/{machineErrors.js → machine/errors.js} +8 -8
  33. package/dist/internal/machine/errors.js.map +1 -0
  34. package/dist/internal/machine/executionPlan.d.ts +49 -0
  35. package/dist/internal/machine/executionPlan.d.ts.map +1 -0
  36. package/dist/internal/machine/executionPlan.js +676 -0
  37. package/dist/internal/machine/executionPlan.js.map +1 -0
  38. package/dist/internal/machine/invocation.d.ts +23 -0
  39. package/dist/internal/machine/invocation.d.ts.map +1 -0
  40. package/dist/internal/machine/invocation.js +77 -0
  41. package/dist/internal/machine/invocation.js.map +1 -0
  42. package/dist/internal/machine/machine.d.ts +183 -0
  43. package/dist/internal/machine/machine.d.ts.map +1 -0
  44. package/dist/internal/machine/machine.js +552 -0
  45. package/dist/internal/machine/machine.js.map +1 -0
  46. package/dist/internal/machine/planner.d.ts +182 -0
  47. package/dist/internal/machine/planner.d.ts.map +1 -0
  48. package/dist/internal/machine/planner.js +1082 -0
  49. package/dist/internal/machine/planner.js.map +1 -0
  50. package/dist/internal/{machineProcess.d.ts → machine/process.d.ts} +11 -5
  51. package/dist/internal/machine/process.d.ts.map +1 -0
  52. package/dist/internal/machine/process.js +498 -0
  53. package/dist/internal/machine/process.js.map +1 -0
  54. package/dist/internal/machine/protocol.d.ts +34 -0
  55. package/dist/internal/machine/protocol.d.ts.map +1 -0
  56. package/dist/internal/machine/protocol.js +182 -0
  57. package/dist/internal/machine/protocol.js.map +1 -0
  58. package/dist/internal/machine/readiness.d.ts +4 -0
  59. package/dist/internal/machine/readiness.d.ts.map +1 -0
  60. package/dist/internal/machine/readiness.js +2 -0
  61. package/dist/internal/machine/readiness.js.map +1 -0
  62. package/dist/internal/machine/runtime.d.ts +255 -0
  63. package/dist/internal/machine/runtime.d.ts.map +1 -0
  64. package/dist/internal/machine/runtime.js +1489 -0
  65. package/dist/internal/machine/runtime.js.map +1 -0
  66. package/dist/internal/machine/serialization.d.ts +14 -0
  67. package/dist/internal/machine/serialization.d.ts.map +1 -0
  68. package/dist/internal/machine/serialization.js +338 -0
  69. package/dist/internal/machine/serialization.js.map +1 -0
  70. package/dist/internal/machine/stateDefinition.d.ts +15 -0
  71. package/dist/internal/machine/stateDefinition.d.ts.map +1 -0
  72. package/dist/internal/machine/stateDefinition.js +210 -0
  73. package/dist/internal/machine/stateDefinition.js.map +1 -0
  74. package/dist/internal/machine/symbols.d.ts +3 -0
  75. package/dist/internal/machine/symbols.d.ts.map +1 -0
  76. package/dist/internal/machine/symbols.js +3 -0
  77. package/dist/internal/machine/symbols.js.map +1 -0
  78. package/dist/internal/machine/topology.d.ts +98 -0
  79. package/dist/internal/machine/topology.d.ts.map +1 -0
  80. package/dist/internal/machine/topology.js +347 -0
  81. package/dist/internal/machine/topology.js.map +1 -0
  82. package/dist/internal/testing/machine/arbitrary.d.ts +36 -0
  83. package/dist/internal/testing/machine/arbitrary.d.ts.map +1 -0
  84. package/dist/internal/testing/machine/arbitrary.js +68 -0
  85. package/dist/internal/testing/machine/arbitrary.js.map +1 -0
  86. package/dist/internal/testing/machine/exploration.d.ts +30 -0
  87. package/dist/internal/testing/machine/exploration.d.ts.map +1 -0
  88. package/dist/internal/testing/machine/exploration.js +237 -0
  89. package/dist/internal/testing/machine/exploration.js.map +1 -0
  90. package/dist/internal/testing/machine/finiteModel.d.ts +322 -0
  91. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -0
  92. package/dist/internal/testing/machine/finiteModel.js +976 -0
  93. package/dist/internal/testing/machine/finiteModel.js.map +1 -0
  94. package/dist/internal/testing/machine/invariant.d.ts +31 -0
  95. package/dist/internal/testing/machine/invariant.d.ts.map +1 -0
  96. package/dist/internal/testing/machine/invariant.js +214 -0
  97. package/dist/internal/testing/machine/invariant.js.map +1 -0
  98. package/dist/internal/testing/machine/probe.d.ts +26 -0
  99. package/dist/internal/testing/machine/probe.d.ts.map +1 -0
  100. package/dist/internal/testing/machine/probe.js +45 -0
  101. package/dist/internal/testing/machine/probe.js.map +1 -0
  102. package/dist/internal/testing/machine/referenceModel.d.ts +203 -0
  103. package/dist/internal/testing/machine/referenceModel.d.ts.map +1 -0
  104. package/dist/internal/testing/machine/referenceModel.js +1012 -0
  105. package/dist/internal/testing/machine/referenceModel.js.map +1 -0
  106. package/dist/internal/testing/machine/runtime.d.ts +631 -0
  107. package/dist/internal/testing/machine/runtime.d.ts.map +1 -0
  108. package/dist/internal/testing/machine/runtime.js +726 -0
  109. package/dist/internal/testing/machine/runtime.js.map +1 -0
  110. package/dist/internal/testing/machine/runtimeInvariant.d.ts +32 -0
  111. package/dist/internal/testing/machine/runtimeInvariant.d.ts.map +1 -0
  112. package/dist/internal/testing/machine/runtimeInvariant.js +334 -0
  113. package/dist/internal/testing/machine/runtimeInvariant.js.map +1 -0
  114. package/dist/internal/testing/machine/trace.d.ts +17 -0
  115. package/dist/internal/testing/machine/trace.d.ts.map +1 -0
  116. package/dist/internal/testing/machine/trace.js +94 -0
  117. package/dist/internal/testing/machine/trace.js.map +1 -0
  118. package/dist/internal/testing/machine/verification.d.ts +36 -0
  119. package/dist/internal/testing/machine/verification.d.ts.map +1 -0
  120. package/dist/internal/testing/machine/verification.js +1375 -0
  121. package/dist/internal/testing/machine/verification.js.map +1 -0
  122. package/dist/testing/MachineTest.d.ts +1588 -0
  123. package/dist/testing/MachineTest.d.ts.map +1 -0
  124. package/dist/testing/MachineTest.js +406 -0
  125. package/dist/testing/MachineTest.js.map +1 -0
  126. package/dist/testing/index.d.ts +7 -0
  127. package/dist/testing/index.d.ts.map +1 -0
  128. package/dist/testing/index.js +7 -0
  129. package/dist/testing/index.js.map +1 -0
  130. package/dist/{ClusterMachine.d.ts → unstable/cluster/ClusterMachine.d.ts} +56 -45
  131. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -0
  132. package/dist/unstable/cluster/ClusterMachine.js +144 -0
  133. package/dist/unstable/cluster/ClusterMachine.js.map +1 -0
  134. package/dist/{cluster.js → unstable/cluster/index.d.ts} +1 -1
  135. package/dist/unstable/cluster/index.d.ts.map +1 -0
  136. package/dist/{cluster.d.ts → unstable/cluster/index.js} +1 -1
  137. package/dist/unstable/cluster/index.js.map +1 -0
  138. package/dist/{AtomMachine.d.ts → unstable/reactivity/AtomMachine.d.ts} +116 -50
  139. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -0
  140. package/dist/unstable/reactivity/AtomMachine.js +164 -0
  141. package/dist/unstable/reactivity/AtomMachine.js.map +1 -0
  142. package/dist/{reactivity.js → unstable/reactivity/index.d.ts} +1 -1
  143. package/dist/unstable/reactivity/index.d.ts.map +1 -0
  144. package/dist/{reactivity.d.ts → unstable/reactivity/index.js} +1 -1
  145. package/dist/unstable/reactivity/index.js.map +1 -0
  146. package/docs/agent-guide.md +316 -31
  147. package/package.json +28 -10
  148. package/dist/AtomMachine.d.ts.map +0 -1
  149. package/dist/AtomMachine.js.map +0 -1
  150. package/dist/ClusterMachine.d.ts.map +0 -1
  151. package/dist/ClusterMachine.js.map +0 -1
  152. package/dist/cluster.d.ts.map +0 -1
  153. package/dist/cluster.js.map +0 -1
  154. package/dist/internal/machineErrors.d.ts.map +0 -1
  155. package/dist/internal/machineErrors.js.map +0 -1
  156. package/dist/internal/machineModel.d.ts.map +0 -1
  157. package/dist/internal/machineModel.js.map +0 -1
  158. package/dist/internal/machinePlanner.d.ts +0 -74
  159. package/dist/internal/machinePlanner.d.ts.map +0 -1
  160. package/dist/internal/machinePlanner.js +0 -797
  161. package/dist/internal/machinePlanner.js.map +0 -1
  162. package/dist/internal/machineProcess.d.ts.map +0 -1
  163. package/dist/internal/machineProcess.js +0 -181
  164. package/dist/internal/machineProcess.js.map +0 -1
  165. package/dist/internal/machineRuntime.d.ts +0 -125
  166. package/dist/internal/machineRuntime.d.ts.map +0 -1
  167. package/dist/internal/machineRuntime.js +0 -365
  168. package/dist/internal/machineRuntime.js.map +0 -1
  169. package/dist/reactivity.d.ts.map +0 -1
  170. package/dist/reactivity.js.map +0 -1
package/dist/Machine.js CHANGED
@@ -1,23 +1,16 @@
1
1
  /**
2
2
  * Schema-first machine definitions.
3
3
  *
4
- * @since 4.0.0
4
+ * @since 0.4.0
5
5
  */
6
- import * as Effect from "effect/Effect";
7
- import * as Inspectable from "effect/Inspectable";
8
- import * as Option from "effect/Option";
9
- import { Prototype as PipeablePrototype } from "effect/Pipeable";
10
6
  import { hasProperty } from "effect/Predicate";
11
- import { ProcessLocalError as ProcessLocalErrorValue } from "./internal/machineErrors.js";
12
- import * as Model from "./internal/machineModel.js";
13
- import * as internalPlanner from "./internal/machinePlanner.js";
14
- import * as internalProcess from "./internal/machineProcess.js";
15
- import * as internalRuntime from "./internal/machineRuntime.js";
7
+ import * as internal from "./internal/machine/machine.js";
8
+ import { InitialEventTypeId } from "./internal/machine/machine.js";
16
9
  /**
17
10
  * Runtime type identifier attached to `Machine` values.
18
11
  *
19
12
  * @category type IDs
20
- * @since 4.0.0
13
+ * @since 0.4.0
21
14
  */
22
15
  export const TypeId = "~effect/Machine";
23
16
  /**
@@ -25,21 +18,21 @@ export const TypeId = "~effect/Machine";
25
18
  * actions.
26
19
  *
27
20
  * @category type IDs
28
- * @since 4.0.0
21
+ * @since 0.4.0
29
22
  */
30
- export const InitialEventTypeId = internalPlanner.InitialEventTypeId;
23
+ export { InitialEventTypeId };
31
24
  /**
32
25
  * Synthetic event value used while the machine settles its initial state.
33
26
  *
34
27
  * @category constructors
35
- * @since 4.0.0
28
+ * @since 0.4.0
36
29
  */
37
- export const InitialEvent = internalPlanner.InitialEvent;
30
+ export const InitialEvent = { _tag: InitialEventTypeId };
38
31
  /**
39
32
  * Returns `true` if a value is the synthetic machine initial event.
40
33
  *
41
34
  * @category guards
42
- * @since 4.0.0
35
+ * @since 0.4.0
43
36
  */
44
37
  export const isInitialEvent = (u) => hasProperty(u, "_tag") && u._tag === InitialEventTypeId;
45
38
  export {
@@ -48,7 +41,7 @@ export {
48
41
  * exists for the current machine.
49
42
  *
50
43
  * @category errors
51
- * @since 4.0.0
44
+ * @since 0.4.0
52
45
  */
53
46
  ChildAlreadyExistsError,
54
47
  /**
@@ -56,7 +49,7 @@ ChildAlreadyExistsError,
56
49
  * number of macrostep iterations.
57
50
  *
58
51
  * @category errors
59
- * @since 4.0.0
52
+ * @since 0.4.0
60
53
  */
61
54
  InfiniteTransitionError,
62
55
  /**
@@ -64,7 +57,7 @@ InfiniteTransitionError,
64
57
  * structural configuration declared for a machine boundary.
65
58
  *
66
59
  * @category errors
67
- * @since 4.0.0
60
+ * @since 0.4.0
68
61
  */
69
62
  MachineSchemaDecodeError,
70
63
  /**
@@ -72,7 +65,7 @@ MachineSchemaDecodeError,
72
65
  * its declared state or output schemas.
73
66
  *
74
67
  * @category errors
75
- * @since 4.0.0
68
+ * @since 0.4.0
76
69
  */
77
70
  MachineSchemaEncodeError,
78
71
  /**
@@ -80,7 +73,7 @@ MachineSchemaEncodeError,
80
73
  * requires a managed machine process.
81
74
  *
82
75
  * @category errors
83
- * @since 4.0.0
76
+ * @since 0.4.0
84
77
  */
85
78
  ProcessLocalError,
86
79
  /**
@@ -88,7 +81,7 @@ ProcessLocalError,
88
81
  * logic after the initial state has been computed.
89
82
  *
90
83
  * @category errors
91
- * @since 4.0.0
84
+ * @since 0.4.0
92
85
  */
93
86
  StartupError,
94
87
  /**
@@ -96,359 +89,31 @@ StartupError,
96
89
  * producing an output.
97
90
  *
98
91
  * @category errors
99
- * @since 4.0.0
92
+ * @since 0.4.0
100
93
  */
101
- StoppedError } from "./internal/machineErrors.js";
94
+ StoppedError } from "./internal/machine/machine.js";
102
95
  const RuntimeRequirementTypeId = "~effect/Machine/RuntimeRequirement";
103
96
  const ActionRequirementTypeId = "~effect/Machine/ActionRequirement";
104
- const RuntimeCompatibilityErrorTypeId = "~effect/Machine/RuntimeCompatibilityError";
105
- const InvokeTypeId = Symbol.for("effect/Machine/Invoke");
106
- const SnapshotBuilderStateTypeId = Symbol("effect/Machine/SnapshotBuilderState");
97
+ const InvokeTypeId = internal.InvokeTypeId;
98
+ const SnapshotBuilderStateTypeId = internal.SnapshotBuilderStateTypeId;
107
99
  const SnapshotBuilderConstructionTypeId = Symbol("effect/Machine/SnapshotBuilderConstruction");
108
100
  const ChildAddressTypeId = "~effect/Machine/ChildAddress";
109
101
  const ChildAddressCompatibilityErrorTypeId = "~effect/Machine/ChildAddressCompatibilityError";
110
102
  const ChildMachineTypeId = "~effect/Machine/ChildMachine";
111
- const Proto = {
112
- ...Inspectable.BaseProto,
113
- ...PipeablePrototype,
114
- [TypeId]: TypeId,
115
- toJSON() {
116
- return {
117
- _id: "Machine"
118
- };
119
- }
120
- };
121
- const cloneWithHandlers = (self, handlers) => {
122
- const machine = Object.create(Proto);
123
- machine.states = self.states;
124
- machine.events = self.events;
125
- machine.internalEvents = self.internalEvents;
126
- machine.emits = self.emits;
127
- machine.input = self.input;
128
- machine.id = self.id;
129
- machine.initial = self.initial;
130
- machine.stateNodes = self.stateNodes;
131
- machine.makeTargetBuilder = self.makeTargetBuilder;
132
- machine.handlers = handlers;
133
- machine.handle = makeHandle(machine);
134
- Model.copyProtocol(self, machine);
135
- return machine;
136
- };
137
- const flattenHandlers = (handlers, states, prefix, config) => {
138
- for (const key of Object.keys(config)) {
139
- const path = prefix === "" ? key : `${prefix}.${key}`;
140
- if (!hasProperty(states, key)) {
141
- throw new Error(`Machine received handler for unknown state "${path}"`);
142
- }
143
- const nodeConfig = config[key];
144
- if (typeof nodeConfig !== "object" || nodeConfig === null) {
145
- throw new Error(`Machine expected state "${path}" handler to be an object`);
146
- }
147
- const { states: childConfig, ...stateConfig } = nodeConfig;
148
- handlers[path] = stateConfig;
149
- if (childConfig !== undefined) {
150
- const node = Model.getStateNodeDefinition(path, states[key]);
151
- if (node.states === undefined) {
152
- throw new Error(`Machine expected state "${path}" to declare child states`);
153
- }
154
- if (typeof childConfig !== "object" || childConfig === null) {
155
- throw new Error(`Machine expected state "${path}" child handlers to be an object`);
156
- }
157
- flattenHandlers(handlers, node.states, path, childConfig);
158
- }
159
- }
160
- };
161
- const makeHandle = (self) => ((config) => {
162
- const handlers = Object.assign(Object.create(null), self.handlers);
163
- flattenHandlers(handlers, self.states, "", config);
164
- return cloneWithHandlers(self, handlers);
165
- });
166
103
  /**
167
104
  * Returns `true` if a value is a `Machine`.
168
105
  *
169
106
  * @category guards
170
- * @since 4.0.0
107
+ * @since 0.4.0
171
108
  */
172
- export const isMachine = (u) => hasProperty(u, TypeId);
109
+ export const isMachine = internal.isMachine;
173
110
  /**
174
111
  * Returns `true` if a state snapshot is final for a machine.
175
112
  *
176
113
  * @category guards
177
- * @since 4.0.0
114
+ * @since 0.4.0
178
115
  */
179
- export const isFinal = (machine, state) => internalPlanner.isFinal(machine, state);
180
- const withFrom = (method, kind) => {
181
- Object.defineProperty(method, "from", {
182
- value: (...args) => {
183
- const omitted = args.length === 0 || (kind === "nested" && args.length === 1 && typeof args[0] === "function");
184
- const input = omitted ? {} : args[0];
185
- const rest = omitted ? args : args.slice(1);
186
- return Model.markStateConstruction(method(Model.makeStateInput(input), ...rest));
187
- },
188
- enumerable: false
189
- });
190
- return method;
191
- };
192
- const makeSnapshotBuilder = (states, options) => {
193
- const builder = {};
194
- for (const key of Object.keys(states)) {
195
- if (states[key].type === "history") {
196
- continue;
197
- }
198
- const path = options.prefix === "" ? key : `${options.prefix}.${key}`;
199
- const node = Model.getStateNodeDefinition(path, states[key]);
200
- builder[key] = withFrom((value, selector) => makeSnapshotForNode(states[key], key, value, selector, options), node.states === undefined ? "leaf" : "nested");
201
- }
202
- return builder;
203
- };
204
- const makeParallelSnapshotBuilder = (states, options, regions) => {
205
- const builder = {};
206
- Object.defineProperty(builder, SnapshotBuilderStateTypeId, {
207
- value: regions,
208
- enumerable: false
209
- });
210
- Object.defineProperty(builder, SnapshotBuilderConstructionTypeId, {
211
- value: Model.isStateConstruction(builder),
212
- enumerable: false
213
- });
214
- for (const key of Object.keys(states)) {
215
- if (states[key].type === "history") {
216
- continue;
217
- }
218
- if (hasProperty(regions, key)) {
219
- continue;
220
- }
221
- const path = options.prefix === "" ? key : `${options.prefix}.${key}`;
222
- const node = Model.getStateNodeDefinition(path, states[key]);
223
- builder[key] = withFrom((value, selector) => {
224
- const nextRegions = {};
225
- for (const regionKey of Object.keys(regions)) {
226
- nextRegions[regionKey] = regions[regionKey];
227
- }
228
- nextRegions[key] = makeSnapshotForNode(states[key], key, value, selector, options);
229
- const next = makeParallelSnapshotBuilder(states, options, nextRegions);
230
- return Model.isStateConstruction(builder) ? Model.markStateConstruction(next) : next;
231
- }, node.states === undefined ? "leaf" : "nested");
232
- }
233
- return builder;
234
- };
235
- const getParallelSnapshotBuilderRegions = (path, states, builder) => {
236
- if (typeof builder !== "object" || builder === null || !hasProperty(builder, SnapshotBuilderStateTypeId)) {
237
- throw new Error(`Machine expected parallel state "${path}" builder callback to return a builder`);
238
- }
239
- const regions = builder[SnapshotBuilderStateTypeId];
240
- for (const key of Object.keys(states)) {
241
- if (states[key].type === "history") {
242
- continue;
243
- }
244
- if (!hasProperty(regions, key)) {
245
- throw new Error(`Machine expected parallel state "${path}" builder callback to provide region "${key}"`);
246
- }
247
- }
248
- return regions;
249
- };
250
- const makeSnapshotForNode = (definition, key, value, selector, options) => {
251
- const path = options.prefix === "" ? key : `${options.prefix}.${key}`;
252
- const node = Model.getStateNodeDefinition(path, definition);
253
- const snapshot = {
254
- path,
255
- value
256
- };
257
- if (node.states === undefined) {
258
- return snapshot;
259
- }
260
- if (selector === undefined) {
261
- throw new Error(`Machine expected state "${path}" builder to provide active child states`);
262
- }
263
- if (node.type === "parallel") {
264
- const builder = makeParallelSnapshotBuilder(node.states, { ...options, prefix: path }, {});
265
- const selected = selector(builder);
266
- snapshot.states = getParallelSnapshotBuilderRegions(path, node.states, selected);
267
- return Model.isStateConstruction(selected) ? Model.markStateConstruction(snapshot) : snapshot;
268
- }
269
- const childStates = options.mode === "initial" && node.initial !== undefined
270
- ? { [node.initial]: node.states[node.initial] }
271
- : node.states;
272
- const selected = selector(makeSnapshotBuilder(childStates, { ...options, prefix: path }));
273
- snapshot.state = selected;
274
- return Model.isStateConstruction(selected) ? Model.markStateConstruction(snapshot) : snapshot;
275
- };
276
- const getTargetBuilderNode = (stateNodes, path) => {
277
- const node = stateNodes.byPath.get(path);
278
- if (node === undefined) {
279
- throw new Error(`Machine expected state path "${path}" to exist`);
280
- }
281
- return node;
282
- };
283
- const getLocalTargetScope = (stateNodes, source) => {
284
- let current = source;
285
- while (current !== undefined) {
286
- const node = stateNodes.byPath.get(current);
287
- if (node === undefined) {
288
- return undefined;
289
- }
290
- if (node.type === "compound") {
291
- return node.path;
292
- }
293
- current = node.parent;
294
- }
295
- return undefined;
296
- };
297
- const hasTargetValues = (values) => values !== undefined && Object.keys(values).length > 0;
298
- const makeTargetWithValues = (path, value, values) => hasTargetValues(values)
299
- ? Model.makeTarget(path, value, { values: values })
300
- : Model.makeTarget(path, value);
301
- const getTargetBuilderDefinition = (states, targetPath) => {
302
- let children = states;
303
- let path = "";
304
- let definition;
305
- for (const key of targetPath.split(".")) {
306
- if (!hasProperty(children, key)) {
307
- throw new Error(`Machine expected state path "${targetPath}" to exist`);
308
- }
309
- definition = children[key];
310
- path = path === "" ? key : `${path}.${key}`;
311
- const node = Model.getStateNodeDefinition(path, definition);
312
- children = node.states ?? {};
313
- }
314
- return definition;
315
- };
316
- const makeParallelTarget = (states, node, value, selector, values) => {
317
- if (selector === undefined) {
318
- throw new Error(`Machine expected parallel target "${node.path}" builder to provide every active region`);
319
- }
320
- const snapshot = makeSnapshotForNode(getTargetBuilderDefinition(states, node.path), node.key, value, selector, { mode: "full", prefix: node.parent ?? "" });
321
- return Model.makeTarget(node.path, value, {
322
- snapshot: snapshot,
323
- values: values
324
- });
325
- };
326
- const extendTargetValues = (values, path, value) => {
327
- const next = {};
328
- if (values !== undefined) {
329
- for (const key of Object.keys(values)) {
330
- next[key] = values[key];
331
- }
332
- }
333
- next[path] = value;
334
- return next;
335
- };
336
- const makeLocalTargetChildBuilder = (states, stateNodes, parentPath, values, source) => {
337
- const parent = getTargetBuilderNode(stateNodes, parentPath);
338
- const builder = {};
339
- for (const childPath of parent.children) {
340
- const child = getTargetBuilderNode(stateNodes, childPath);
341
- builder[child.key] = withFrom((value, selector) => {
342
- if (child.type === "atomic" || child.type === "final") {
343
- return makeTargetWithValues(child.path, value, values);
344
- }
345
- if (child.type === "parallel") {
346
- if (source !== child.path && !source.startsWith(`${child.path}.`)) {
347
- return makeParallelTarget(states, child, value, selector, values);
348
- }
349
- if (selector === undefined) {
350
- throw new Error(`Machine expected target "${child.path}" builder to provide an active child state`);
351
- }
352
- return selector(makeLocalTargetChildBuilder(states, stateNodes, child.path, extendTargetValues(values, child.path, value), source));
353
- }
354
- if (selector === undefined) {
355
- throw new Error(`Machine expected target "${child.path}" builder to provide an active child state`);
356
- }
357
- return selector(makeLocalTargetChildBuilder(states, stateNodes, child.path, extendTargetValues(values, child.path, value), source));
358
- }, child.type === "atomic" || child.type === "final" ? "leaf" : "nested");
359
- }
360
- return builder;
361
- };
362
- const makeLocalTargetBuilder = (states, stateNodes, source) => {
363
- const scope = getLocalTargetScope(stateNodes, source);
364
- if (scope === undefined) {
365
- return {};
366
- }
367
- const builder = makeLocalTargetChildBuilder(states, stateNodes, scope, undefined, source);
368
- builder.with = withFrom((value, selector) => {
369
- if (selector === undefined) {
370
- throw new Error(`Machine expected target "${scope}" builder to provide an active child state`);
371
- }
372
- return selector(makeLocalTargetChildBuilder(states, stateNodes, scope, { [scope]: value }, source));
373
- }, "nested");
374
- return builder;
375
- };
376
- const addBranchTargetChildren = (builder, states, stateNodes, parentPath, values, source) => {
377
- const parent = getTargetBuilderNode(stateNodes, parentPath);
378
- for (const childPath of parent.children) {
379
- const child = getTargetBuilderNode(stateNodes, childPath);
380
- builder[child.key] = makeBranchTargetNodeBuilder(states, stateNodes, child.path, values, source);
381
- }
382
- };
383
- const makeBranchTargetNodeBuilder = (states, stateNodes, path, values, source) => {
384
- const node = getTargetBuilderNode(stateNodes, path);
385
- if (node.type === "atomic" || node.type === "final") {
386
- return withFrom((value) => makeTargetWithValues(node.path, value, values), "leaf");
387
- }
388
- const builder = withFrom((value, selector) => {
389
- if (node.type === "parallel") {
390
- if (source !== node.path && !source.startsWith(`${node.path}.`)) {
391
- return makeParallelTarget(states, node, value, selector, values);
392
- }
393
- if (selector === undefined) {
394
- throw new Error(`Machine expected target "${node.path}" builder to provide an active child state`);
395
- }
396
- const nextBuilder = {};
397
- addBranchTargetChildren(nextBuilder, states, stateNodes, node.path, extendTargetValues(values, node.path, value), source);
398
- return selector(nextBuilder);
399
- }
400
- if (selector === undefined) {
401
- throw new Error(`Machine expected target "${node.path}" builder to provide an active child state`);
402
- }
403
- const nextBuilder = {};
404
- addBranchTargetChildren(nextBuilder, states, stateNodes, node.path, extendTargetValues(values, node.path, value), source);
405
- return selector(nextBuilder);
406
- }, "nested");
407
- if (node.type !== "parallel" || source === node.path || source.startsWith(`${node.path}.`)) {
408
- addBranchTargetChildren(builder, states, stateNodes, node.path, values, source);
409
- }
410
- return builder;
411
- };
412
- const makeBranchTargetBuilder = (states, stateNodes, source) => {
413
- const rootPath = source.split(".")[0];
414
- const root = getTargetBuilderNode(stateNodes, rootPath);
415
- return {
416
- [root.key]: makeBranchTargetNodeBuilder(states, stateNodes, root.path, undefined, source)
417
- };
418
- };
419
- const makeHistoryTargetBuilder = (states, prefix) => {
420
- const builder = {};
421
- for (const key of Object.keys(states)) {
422
- const path = prefix === "" ? key : `${prefix}.${key}`;
423
- const definition = states[key];
424
- if (definition.type === "history") {
425
- const parent = getParentPathRuntime(path);
426
- builder[key] = () => Model.makeHistoryTarget(path, parent);
427
- continue;
428
- }
429
- if (typeof definition === "object" && definition !== null && hasProperty(definition, "states")) {
430
- builder[key] = makeHistoryTargetBuilder(definition.states, path);
431
- }
432
- }
433
- return builder;
434
- };
435
- const getParentPathRuntime = (path) => {
436
- const separator = path.lastIndexOf(".");
437
- if (separator < 0) {
438
- throw new Error(`Machine expected history state "${path}" to have an active parent`);
439
- }
440
- return path.slice(0, separator);
441
- };
442
- const makeTargetBuilder = (states, stateNodes) => {
443
- const full = makeSnapshotBuilder(states, { mode: "full", prefix: "" });
444
- const history = makeHistoryTargetBuilder(states, "");
445
- return (source) => ({
446
- local: makeLocalTargetBuilder(states, stateNodes, source),
447
- branch: makeBranchTargetBuilder(states, stateNodes, source),
448
- full,
449
- history
450
- });
451
- };
116
+ export const isFinal = internal.isFinal;
452
117
  /**
453
118
  * Defines a state tree while preserving literal state paths.
454
119
  *
@@ -481,19 +146,9 @@ const makeTargetBuilder = (states, stateNodes) => {
481
146
  * ```
482
147
  *
483
148
  * @category constructors
484
- * @since 4.0.0
149
+ * @since 0.4.0
485
150
  */
486
- export const defineStates = ((states) => ({
487
- states: states,
488
- initial: makeSnapshotBuilder(states, { mode: "initial", prefix: "" }),
489
- get: ((snapshot, path) => Model.getSnapshotByPath(snapshot, path).pipe(Option.map((snapshot) => snapshot.value))),
490
- getWithParents: ((snapshot, path) => {
491
- const parents = {};
492
- return Model.getSnapshotByPath(snapshot, path, parents).pipe(Option.map((snapshot) => ({ value: snapshot.value, parents })));
493
- }),
494
- getSnapshot: Model.getSnapshotByPath,
495
- matches: (snapshot, path) => Option.isSome(Model.getSnapshotByPath(snapshot, path))
496
- }));
151
+ export const defineStates = internal.defineStates;
497
152
  /**
498
153
  * Creates a schema-first machine definition.
499
154
  *
@@ -542,24 +197,49 @@ export const defineStates = ((states) => ({
542
197
  *
543
198
  * @see {@link defineStates} for typed initial snapshot builders.
544
199
  * @category constructors
545
- * @since 4.0.0
200
+ * @since 0.4.0
546
201
  */
547
- export const make = ((config) => {
548
- const self = Object.create(Proto);
549
- self.states = config.states;
550
- self.events = config.events;
551
- self.internalEvents = config.internalEvents ?? [];
552
- self.emits = config.emits ?? [];
553
- self.input = config.input;
554
- self.id = config.id;
555
- self.initial = config.initial;
556
- self.stateNodes = Model.compileStateNodes(config.states);
557
- self.makeTargetBuilder = makeTargetBuilder(config.states, self.stateNodes);
558
- self.handlers = Object.create(null);
559
- self.handle = makeHandle(self);
560
- Model.setProtocol(self);
561
- return self;
562
- });
202
+ export const make = internal.make;
203
+ /**
204
+ * Constructs an event from a schema owned by a machine's protocol.
205
+ *
206
+ * **Details**
207
+ *
208
+ * The schema constructor runs exactly once. The resulting decoded event is
209
+ * trusted by this machine and definitions derived from it with `handle`, so
210
+ * repeated delivery does not decode the same already-constructed value again.
211
+ * Events supplied through ordinary `send` and `plan` calls remain untrusted
212
+ * and continue through full runtime schema validation.
213
+ * Treat the returned event as immutable after construction.
214
+ *
215
+ * The schema must be one of the machine's configured public or internal event
216
+ * schemas, or a case schema belonging to a configured `Schema.TaggedUnion`.
217
+ *
218
+ * **Example**
219
+ *
220
+ * ```ts
221
+ * import { Schema } from "effect"
222
+ * import { Machine } from "@typeonce/effect-machine"
223
+ *
224
+ * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {}
225
+ * class Increment extends Schema.TaggedClass<Increment>("Increment")("Increment", {
226
+ * by: Schema.Number
227
+ * }) {}
228
+ *
229
+ * const States = Machine.defineStates({ Idle })
230
+ * const counter = Machine.make({
231
+ * states: States.states,
232
+ * events: [Increment],
233
+ * initial: () => States.initial.Idle.from()
234
+ * }).handle({ Idle: { on: { Increment: () => States.initial.Idle.from() } } })
235
+ *
236
+ * const increment = Machine.event(counter, Increment, { by: 1 })
237
+ * ```
238
+ *
239
+ * @category constructors
240
+ * @since 0.4.0
241
+ */
242
+ export const event = internal.event;
563
243
  /**
564
244
  * Encodes a decoded machine snapshot into a normalized data representation.
565
245
  *
@@ -583,11 +263,31 @@ export const make = ((config) => {
583
263
  * guarantee JSON-compatible values; schemas used with JSON-backed storage must
584
264
  * have JSON-compatible encoded representations.
585
265
  *
266
+ * **Example**
267
+ *
268
+ * ```ts
269
+ * import { Effect, Schema } from "effect"
270
+ * import { Machine } from "@typeonce/effect-machine"
271
+ *
272
+ * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {}
273
+ * const States = Machine.defineStates({ Idle })
274
+ * const machine = Machine.make({
275
+ * states: States.states,
276
+ * events: [],
277
+ * initial: () => States.initial.Idle.from()
278
+ * }).handle({ Idle: {} })
279
+ *
280
+ * const encoded = Effect.gen(function*() {
281
+ * const initial = yield* Machine.planInitial(machine)
282
+ * return yield* Machine.encodeSnapshot(machine, initial.state)
283
+ * })
284
+ * ```
285
+ *
586
286
  * @see {@link decodeSnapshot} for restoring an encoded snapshot.
587
287
  * @category encoding
588
- * @since 4.0.0
288
+ * @since 0.4.0
589
289
  */
590
- export const encodeSnapshot = Model.encodeSnapshot;
290
+ export const encodeSnapshot = internal.encodeSnapshot;
591
291
  /**
592
292
  * Decodes a normalized data representation into a validated machine snapshot.
593
293
  *
@@ -607,11 +307,32 @@ export const encodeSnapshot = Model.encodeSnapshot;
607
307
  * Decoding restores logical statechart data only. It does not restart invoked
608
308
  * processes, recreate spawned children, or restore a previous `MachineRef`.
609
309
  *
310
+ * **Example**
311
+ *
312
+ * ```ts
313
+ * import { Effect, Schema } from "effect"
314
+ * import { Machine } from "@typeonce/effect-machine"
315
+ *
316
+ * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {}
317
+ * const States = Machine.defineStates({ Idle })
318
+ * const machine = Machine.make({
319
+ * states: States.states,
320
+ * events: [],
321
+ * initial: () => States.initial.Idle.from()
322
+ * }).handle({ Idle: {} })
323
+ *
324
+ * const roundTrip = Effect.gen(function*() {
325
+ * const initial = yield* Machine.planInitial(machine)
326
+ * const encoded = yield* Machine.encodeSnapshot(machine, initial.state)
327
+ * return yield* Machine.decodeSnapshot(machine, encoded)
328
+ * })
329
+ * ```
330
+ *
610
331
  * @see {@link encodeSnapshot} for creating the normalized representation.
611
332
  * @category decoding
612
- * @since 4.0.0
333
+ * @since 0.4.0
613
334
  */
614
- export const decodeSnapshot = Model.decodeSnapshot;
335
+ export const decodeSnapshot = internal.decodeSnapshot;
615
336
  /**
616
337
  * Creates an invoked child process configuration for an active state.
617
338
  *
@@ -653,9 +374,9 @@ export const decodeSnapshot = Model.decodeSnapshot;
653
374
  * @see {@link effect} for one-shot child effects.
654
375
  * @see {@link spawn} for children whose lifetime is controlled by actions.
655
376
  * @category constructors
656
- * @since 4.0.0
377
+ * @since 0.4.0
657
378
  */
658
- export const invoke = (config) => ({ ...config, [InvokeTypeId]: undefined });
379
+ export const invoke = internal.invoke;
659
380
  /**
660
381
  * Invokes one Effect and maps its typed outcome into machine-local events.
661
382
  *
@@ -669,20 +390,29 @@ export const invoke = (config) => ({ ...config, [InvokeTypeId]: undefined });
669
390
  * Declare mapped outcomes in `internalEvents` unless they are also legitimate
670
391
  * public commands.
671
392
  *
393
+ * **Example**
394
+ *
395
+ * ```ts
396
+ * import { Effect, Schema } from "effect"
397
+ * import { Machine } from "@typeonce/effect-machine"
398
+ *
399
+ * class Loaded extends Schema.TaggedClass<Loaded>("Loaded")("Loaded", {
400
+ * value: Schema.String
401
+ * }) {}
402
+ *
403
+ * const load = Machine.invokeEffect({
404
+ * id: "load",
405
+ * effect: Effect.succeed("ready"),
406
+ * onSuccess: (value) => new Loaded({ value })
407
+ * })
408
+ * ```
409
+ *
672
410
  * @see {@link invoke} for arbitrary child process logic.
673
411
  * @see {@link after} for a state-scoped delayed event.
674
412
  * @category constructors
675
- * @since 4.0.0
413
+ * @since 0.4.0
676
414
  */
677
- export const invokeEffect = (config) => ((config) => invoke({
678
- id: config.id,
679
- src: () => effect(config.onFailure === undefined
680
- ? Effect.map(config.effect, config.onSuccess)
681
- : Effect.matchEffect(config.effect, {
682
- onFailure: (error) => Effect.succeed(config.onFailure(error)),
683
- onSuccess: (value) => Effect.succeed(config.onSuccess(value))
684
- }))
685
- }))(config);
415
+ export const invokeEffect = internal.invokeEffect;
686
416
  /**
687
417
  * Creates a cancellable state-scoped delayed event.
688
418
  *
@@ -690,13 +420,21 @@ export const invokeEffect = (config) => ((config) => invoke({
690
420
  * that state exits. The delayed value should normally be declared in
691
421
  * `internalEvents`.
692
422
  *
423
+ * **Example**
424
+ *
425
+ * ```ts
426
+ * import { Schema } from "effect"
427
+ * import { Machine } from "@typeonce/effect-machine"
428
+ *
429
+ * class TimedOut extends Schema.TaggedClass<TimedOut>("TimedOut")("TimedOut", {}) {}
430
+ *
431
+ * const timeout = Machine.after("5 seconds", new TimedOut({}))
432
+ * ```
433
+ *
693
434
  * @category constructors
694
- * @since 4.0.0
435
+ * @since 0.4.0
695
436
  */
696
- export const after = (duration, event, options) => invoke({
697
- id: options?.id ?? `Machine.after:${String(event._tag)}`,
698
- src: () => effect(Effect.as(Effect.sleep(duration), event))
699
- });
437
+ export const after = internal.after;
700
438
  /**
701
439
  * Constructs another tagged case from compatible source fields.
702
440
  *
@@ -708,12 +446,9 @@ export const after = (duration, event, options) => invoke({
708
446
  * remains authoritative at runtime.
709
447
  *
710
448
  * @category constructors
711
- * @since 4.0.0
449
+ * @since 0.4.0
712
450
  */
713
- export const retag = (target, source, ...args) => {
714
- const { _tag: _, ...fields } = source;
715
- return target.make({ ...fields, ...(args[0] ?? {}) });
716
- };
451
+ export const retag = internal.retag;
717
452
  /**
718
453
  * Creates an invoked child process from a complete statechart machine.
719
454
  *
@@ -737,155 +472,159 @@ export const retag = (target, source, ...args) => {
737
472
  * @see {@link invoke} for invoking lower-level process logic.
738
473
  * @see {@link sendTo} for sending events to the invoked machine.
739
474
  * @category constructors
740
- * @since 4.0.0
475
+ * @since 0.4.0
741
476
  */
742
- export const invokeMachine = ((config) => {
743
- const machine = config.child.machine;
744
- return {
745
- id: config.child.id,
746
- address: config.child.id,
747
- descriptor: config.child,
748
- src: () => machine.input === undefined
749
- ? internalProcess.toProcessLogic(machine)
750
- : internalProcess.toProcessLogic(machine, config.input),
751
- snapshot: config.snapshot,
752
- onDone: config.onDone,
753
- [InvokeTypeId]: undefined
754
- };
755
- });
477
+ export const invokeMachine = internal.invokeMachine;
756
478
  /**
757
- * Plans the initial state for a machine without running deferred actions.
479
+ * Plans the initial state for a machine without executing actor commands.
758
480
  *
759
481
  * **Details**
760
482
  *
761
- * The returned plan contains the settled initial snapshot, staged actions,
762
- * emitted events, and optional final output. Planning may evaluate transition
763
- * logic and follow completion, eventless, and raised-event steps, but it does
764
- * not execute effects passed to `action`.
483
+ * The returned plan contains the settled initial snapshot, actor commands,
484
+ * emitted events, optional final output, and every startup microstep. Planning
485
+ * may evaluate transition logic and follow completion, eventless, and
486
+ * raised-event steps. Transition callbacks are evaluated synchronously.
487
+ * `startingState` and `initialEntryPaths` describe the normalized
488
+ * configuration before entry callbacks and settlement begin.
765
489
  *
766
490
  * **Gotchas**
767
491
  *
768
- * Callers that execute a plan manually must run actions sequentially before
769
- * publishing its state or delivering its emitted events. `start` performs this
770
- * protocol automatically.
492
+ * `start` executes the closed command list as part of the managed actor commit
493
+ * protocol. Manual planners may inspect commands but need a running actor scope
494
+ * to execute child-addressed operations.
495
+ *
496
+ * **Example**
497
+ *
498
+ * ```ts
499
+ * import { Effect, Schema } from "effect"
500
+ * import { Machine } from "@typeonce/effect-machine"
501
+ *
502
+ * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {}
503
+ * const States = Machine.defineStates({ Idle })
504
+ * const machine = Machine.make({
505
+ * states: States.states,
506
+ * events: [],
507
+ * initial: () => States.initial.Idle.from()
508
+ * }).handle({ Idle: {} })
509
+ *
510
+ * const initialState = Effect.map(Machine.planInitial(machine), (plan) => plan.state)
511
+ * ```
771
512
  *
772
513
  * @see {@link plan} for planning a received event.
773
514
  * @see {@link start} for the managed runtime protocol.
774
515
  * @category constructors
775
- * @since 4.0.0
516
+ * @since 0.4.0
776
517
  */
777
- export const planInitial = internalPlanner.planInitial;
518
+ export const planInitial = internal.planInitial;
778
519
  /**
779
- * Returns the event tags handled by the current state snapshot.
520
+ * Returns every compiled state node in definition order.
521
+ *
522
+ * **Details**
523
+ *
524
+ * The result includes atomic, compound, parallel, final, history, and choice
525
+ * nodes together with their resolved descriptive annotations. Use each node's
526
+ * `parent` property to reconstruct the complete hierarchy. Pseudo-states are
527
+ * intentionally omitted from `children` because they can never appear in an
528
+ * active configuration.
780
529
  *
781
530
  * @category getters
782
- * @since 4.0.0
531
+ * @since 0.4.0
783
532
  */
784
- export const enabled = (machine, state) => internalPlanner.enabled(machine, state);
533
+ export const stateNodes = internal.stateNodes;
785
534
  /**
786
- * Plans the next state snapshot without running deferred actions.
535
+ * Returns every registered transition handler in state definition order.
787
536
  *
788
537
  * **Details**
789
538
  *
790
- * Planning selects child transitions before conflicting ancestors, permits
791
- * non-conflicting transitions in parallel regions, processes completion and
792
- * eventless transitions, and drains raised events in FIFO order. Exit paths
793
- * are deepest-first and entry paths are parent-first.
794
- *
795
- * **Gotchas**
539
+ * Event handlers retain their handler-key order within each source state and
540
+ * are followed by eventless and completion handlers. This function does not
541
+ * execute handlers. Object-form event, eventless, and completion handlers with
542
+ * a `targets` declaration expose those possible paths; handlers without one
543
+ * remain dynamic.
796
544
  *
797
- * `plan` returns data; it does not implement the runtime commit protocol. Run
798
- * actions sequentially, publish `next` only after they succeed, and then
799
- * deliver `emittedEvents`. A failed action must retain the previously
800
- * published state and suppress emissions. Events with no enabled transition
801
- * are ignored and produce an unchanged plan.
802
- *
803
- * @see {@link planInitial} for planning machine startup.
804
- * @see {@link start} for managed execution and lifecycle observation.
805
- * @category combinators
806
- * @since 4.0.0
545
+ * @category getters
546
+ * @since 0.4.0
807
547
  */
808
- export const plan = internalPlanner.plan;
548
+ export const transitionDefinitions = internal.transitionDefinitions;
809
549
  /**
810
- * Defers an effectful action until the current machine step is planned.
550
+ * Returns serializable descriptions of every state-owned activity.
811
551
  *
812
552
  * **Details**
813
553
  *
814
- * The action's error and service requirements are retained in the machine
815
- * type without becoming requirements of `plan` or `planInitial`. The managed
816
- * runtime executes staged actions sequentially before publishing the planned
817
- * state. Pass a second argument when the planning Effect should return that
818
- * value after staging.
554
+ * Static `invoke`, `invokeEffect`, `after`, and `invokeMachine` descriptors
555
+ * expose stable ownership and lifecycle metadata without serializing runtime
556
+ * values. Function-valued invoke factories are represented as dynamic and are
557
+ * never evaluated during inspection.
819
558
  *
820
- * **Example** (Typed staged action)
559
+ * @category getters
560
+ * @since 0.4.0
561
+ */
562
+ export const activityDefinitions = internal.activityDefinitions;
563
+ /**
564
+ * Returns every state node active in a decoded snapshot, in definition order.
821
565
  *
822
- * ```ts
823
- * import { Context, Effect } from "effect"
824
- * import { Machine } from "@typeonce/effect-machine"
566
+ * **Details**
825
567
  *
826
- * class Audit extends Context.Service<Audit, {
827
- * readonly write: Effect.Effect<void, "AuditError">
828
- * }>()("example/Audit") {}
568
+ * Active compound ancestors and parallel regions are included together with
569
+ * their active descendants. History and choice pseudo-states are never active
570
+ * and are not returned.
829
571
  *
830
- * const writeAudit = Machine.action(
831
- * Effect.flatMap(Audit, (audit) => audit.write)
832
- * )
833
- * ```
572
+ * @category getters
573
+ * @since 0.4.0
574
+ */
575
+ export const configuration = internal.configuration;
576
+ /**
577
+ * Returns the event tags handled by the current state snapshot.
834
578
  *
835
- * @see {@link plan} for inspecting staged actions without executing them.
836
- * @category combinators
837
- * @since 4.0.0
579
+ * @category getters
580
+ * @since 0.4.0
838
581
  */
839
- export const action = ((effect, ...next) => {
840
- const staged = internalPlanner.action(effect);
841
- return next.length === 0 ? staged : Effect.as(staged, next[0]);
842
- });
843
- const processLocal = (operation) => Effect.die(new ProcessLocalErrorValue({ operation }));
844
- const standaloneProcessRuntime = internalRuntime.MachineRuntime.of({
845
- self: {
846
- id: "Machine.runActions",
847
- sessionId: "Machine.runActions",
848
- stop: processLocal("stop self"),
849
- send: () => processLocal("send to self")
850
- },
851
- parent: undefined,
852
- spawn: () => processLocal("spawn"),
853
- sendParent: () => processLocal("send to parent"),
854
- sendTo: () => processLocal("send to child"),
855
- stopChild: () => processLocal("stop child"),
856
- failCause: () => processLocal("fail process")
857
- });
582
+ export const enabled = internal.enabled;
858
583
  /**
859
- * Runs staged machine actions sequentially with the supplied runtime.
584
+ * Plans the next state snapshot synchronously.
860
585
  *
861
- * **When to use**
586
+ * **Details**
862
587
  *
863
- * Use when you implement a commit protocol around `plan` or `planInitial` and
864
- * need to execute their staged actions before publishing the planned snapshot.
588
+ * Planning selects child transitions before conflicting ancestors, permits
589
+ * non-conflicting transitions in parallel regions, processes completion and
590
+ * eventless transitions, and drains raised events in FIFO order. Exit paths
591
+ * are deepest-first and entry paths are parent-first.
865
592
  *
866
593
  * **Gotchas**
867
594
  *
868
- * This function only runs actions. The caller remains responsible for
869
- * publishing the planned state and delivering planned emitted events after all
870
- * actions succeed. Process-local operations such as `spawn`, `sendTo`, and
871
- * `stopChild` fail with `ProcessLocalError` because no managed machine process
872
- * owns the actions.
595
+ * `plan` returns data; it does not implement the actor commit protocol.
596
+ * `start` executes child commands, publishes `next`, and then delivers
597
+ * `emittedEvents`. Events with no enabled transition are ignored and produce
598
+ * an unchanged plan.
873
599
  *
874
- * @see {@link plan} for creating a transition plan.
875
- * @see {@link planInitial} for creating an initial plan.
876
- * @category running
877
- * @since 4.0.0
878
- */
879
- export const runActions = (actions, runtime) => internalRuntime.provideMachineRuntime(internalPlanner.runActions(actions, runtime), standaloneProcessRuntime).pipe(Effect.catchDefect((defect) => defect instanceof ProcessLocalErrorValue
880
- ? Effect.fail(defect)
881
- : Effect.die(defect)));
882
- /**
883
- * Returns the typed runtime capability for the current machine.
600
+ * **Example**
601
+ *
602
+ * ```ts
603
+ * import { Effect, Schema } from "effect"
604
+ * import { Machine } from "@typeonce/effect-machine"
605
+ *
606
+ * class Off extends Schema.TaggedClass<Off>("Off")("Off", {}) {}
607
+ * class On extends Schema.TaggedClass<On>("On")("On", {}) {}
608
+ * class Toggle extends Schema.TaggedClass<Toggle>("Toggle")("Toggle", {}) {}
609
+ * const States = Machine.defineStates({ Off, On })
610
+ * const machine = Machine.make({
611
+ * states: States.states,
612
+ * events: [Toggle],
613
+ * initial: () => States.initial.Off.from()
614
+ * }).handle({ Off: { on: { Toggle: () => States.initial.On.from() } }, On: {} })
615
+ *
616
+ * const nextState = Effect.gen(function*() {
617
+ * const initial = yield* Machine.planInitial(machine)
618
+ * return (yield* Machine.plan(machine, initial.state, new Toggle({}))).next
619
+ * })
620
+ * ```
884
621
  *
622
+ * @see {@link planInitial} for planning machine startup.
623
+ * @see {@link start} for managed execution and lifecycle observation.
885
624
  * @category combinators
886
- * @since 4.0.0
625
+ * @since 0.4.0
887
626
  */
888
- export const runtime = () => internalPlanner.runtime();
627
+ export const plan = internal.plan;
889
628
  /**
890
629
  * Creates a one-shot child process from an Effect.
891
630
  *
@@ -926,12 +665,9 @@ export const runtime = () => internalPlanner.runtime();
926
665
  * @see {@link transition} for event-driven state.
927
666
  * @see {@link logic} for direct control over intermediate snapshots.
928
667
  * @category constructors
929
- * @since 4.0.0
668
+ * @since 0.4.0
930
669
  */
931
- export const effect = (effect) => ({
932
- initial: () => Effect.void,
933
- run: () => effect
934
- });
670
+ export const effect = internal.effect;
935
671
  /**
936
672
  * Creates advanced stateful process logic from explicit initialization and
937
673
  * execution methods.
@@ -958,14 +694,9 @@ export const effect = (effect) => ({
958
694
  * @see {@link effect} for one-shot work.
959
695
  * @see {@link transition} for event-driven state.
960
696
  * @category constructors
961
- * @since 4.0.0
697
+ * @since 0.4.0
962
698
  */
963
- export const logic = (options) => ({
964
- initial: (scope) => typeof options.initial === "function"
965
- ? options.initial(scope)
966
- : Effect.succeed(options.initial),
967
- run: options.run
968
- });
699
+ export const logic = internal.logic;
969
700
  /**
970
701
  * Creates child process logic from an initial state and a transition function.
971
702
  *
@@ -979,15 +710,24 @@ export const logic = (options) => ({
979
710
  * Each received event runs the transition Effect against the latest state. The
980
711
  * resulting state is published before the next queued event is processed.
981
712
  *
713
+ * **Example**
714
+ *
715
+ * ```ts
716
+ * import { Effect } from "effect"
717
+ * import { Machine } from "@typeonce/effect-machine"
718
+ *
719
+ * const counter = Machine.transition(
720
+ * 0,
721
+ * (count, event: { readonly by: number }) => Effect.succeed(count + event.by)
722
+ * )
723
+ * ```
724
+ *
982
725
  * @see {@link effect} for one-shot work.
983
726
  * @see {@link logic} for direct process lifecycle control.
984
727
  * @category constructors
985
- * @since 4.0.0
728
+ * @since 0.4.0
986
729
  */
987
- export const transition = (initial, transition) => logic({
988
- initial,
989
- run: ({ receive, updateState }) => receive.pipe(Effect.flatMap((event) => updateState((state) => transition(state, event))), Effect.forever)
990
- });
730
+ export const transition = internal.transition;
991
731
  /**
992
732
  * Creates a typed descriptor for a complete child machine.
993
733
  *
@@ -995,13 +735,9 @@ export const transition = (initial, transition) => logic({
995
735
  * constructed descriptors for the same pair address the same invoked child.
996
736
  *
997
737
  * @category constructors
998
- * @since 4.0.0
738
+ * @since 0.4.0
999
739
  */
1000
- export const child = (id, machine) => ({
1001
- [ChildMachineTypeId]: ChildMachineTypeId,
1002
- id,
1003
- machine
1004
- });
740
+ export const child = internal.child;
1005
741
  /**
1006
742
  * Creates a typed parent-local address for lower-level child process logic.
1007
743
  *
@@ -1009,51 +745,50 @@ export const child = (id, machine) => ({
1009
745
  * the address with `spawn`, `invoke`, or `sendTo`.
1010
746
  *
1011
747
  * @category constructors
1012
- * @since 4.0.0
748
+ * @since 0.4.0
1013
749
  */
1014
- export const childAddress = (id) => id;
750
+ export const childAddress = internal.childAddress;
1015
751
  /**
1016
752
  * Spawns a child process owned by the currently running machine.
1017
753
  *
1018
754
  * **When to use**
1019
755
  *
1020
- * Use to create child processes from machine actions when the child
1021
- * should be addressed or stopped by the owning machine instead of tied to a
1022
- * single state's `invoke` lifecycle.
756
+ * Use from lower-level process logic to create children that should be
757
+ * addressed or stopped by the owning process instead of tied to a single
758
+ * state's `invoke` lifecycle.
1023
759
  *
1024
760
  * **Gotchas**
1025
761
  *
1026
- * This effect requires the machine runtime, so it only runs from machine
1027
- * actions. A named child id must be unique for the current parent machine until
1028
- * that child stops.
762
+ * This Effect requires a managed process runtime. A named child id must be
763
+ * unique for the current parent until that child stops.
1029
764
  *
1030
765
  * @see {@link invoke} for children that start and stop with a state.
1031
766
  * @see {@link sendTo} for sending events to named children.
1032
767
  * @category runtime
1033
- * @since 4.0.0
768
+ * @since 0.4.0
1034
769
  */
1035
- export const spawn = ((logic, options) => Effect.flatMap(internalRuntime.MachineRuntime, (runtime) => options === undefined ? runtime.spawn(logic) : runtime.spawn(logic, options)));
770
+ export const spawn = internal.spawn;
1036
771
  /**
1037
772
  * Sends an event to a named child process of the running machine.
1038
773
  *
1039
774
  * @category runtime
1040
- * @since 4.0.0
775
+ * @since 0.4.0
1041
776
  */
1042
- export const sendTo = ((child, event) => Effect.flatMap(internalRuntime.MachineRuntime, (runtime) => runtime.sendTo(child, event)));
777
+ export const sendTo = internal.sendTo;
1043
778
  /**
1044
779
  * Stops a named child process of the running machine.
1045
780
  *
1046
781
  * @category runtime
1047
- * @since 4.0.0
782
+ * @since 0.4.0
1048
783
  */
1049
- export const stopChild = ((child) => Effect.flatMap(internalRuntime.MachineRuntime, (runtime) => runtime.stopChild(child)));
784
+ export const stopChild = internal.stopChild;
1050
785
  /**
1051
786
  * Returns a stream of terminal lifecycle outcomes for a running machine.
1052
787
  *
1053
788
  * @category combinators
1054
- * @since 4.0.0
789
+ * @since 0.4.0
1055
790
  */
1056
- export const watch = (ref) => internalRuntime.watch(ref);
791
+ export const watch = internal.watch;
1057
792
  /**
1058
793
  * Starts a machine.
1059
794
  *
@@ -1064,11 +799,10 @@ export const watch = (ref) => internalRuntime.watch(ref);
1064
799
  *
1065
800
  * **Details**
1066
801
  *
1067
- * For each accepted event the runtime plans the complete macrostep, runs staged
1068
- * actions sequentially, stops invokes for exited states, publishes the new
1069
- * state, delivers emitted events, and then starts invokes for entered states.
1070
- * If an action fails, the previous published state is retained and emissions
1071
- * from that plan are suppressed.
802
+ * For each accepted event the runtime plans the complete synchronous
803
+ * macrostep, executes closed actor commands, stops invokes for exited states,
804
+ * publishes the new state, delivers emitted events, and then starts invokes
805
+ * for entered states.
1072
806
  *
1073
807
  * **Gotchas**
1074
808
  *
@@ -1077,10 +811,82 @@ export const watch = (ref) => internalRuntime.watch(ref);
1077
811
  * rather than being returned by `send`. Sending after the machine reaches any
1078
812
  * terminal state fails immediately with `StoppedError`.
1079
813
  *
814
+ * **Example**
815
+ *
816
+ * ```ts
817
+ * import { Effect, Schema } from "effect"
818
+ * import { Machine } from "@typeonce/effect-machine"
819
+ *
820
+ * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {}
821
+ * const States = Machine.defineStates({ Idle })
822
+ * const machine = Machine.make({
823
+ * states: States.states,
824
+ * events: [],
825
+ * initial: () => States.initial.Idle.from()
826
+ * }).handle({ Idle: {} })
827
+ *
828
+ * const state = Effect.gen(function*() {
829
+ * const ref = yield* Machine.start(machine)
830
+ * return yield* ref.state
831
+ * })
832
+ * ```
833
+ *
1080
834
  * @see {@link plan} for inspecting the same transition plan without executing it.
1081
835
  * @see {@link watch} for classified terminal outcomes.
1082
836
  * @category constructors
1083
- * @since 4.0.0
837
+ * @since 0.4.0
838
+ */
839
+ export const start = internal.start;
840
+ /**
841
+ * Starts a fresh managed runtime from a decoded logical snapshot.
842
+ *
843
+ * **Details**
844
+ *
845
+ * `resume` validates and normalizes the supplied snapshot before publishing it
846
+ * as the first state. It does not call the machine's initial function, replay
847
+ * entry or transition actions, re-deliver raised or emitted events, or
848
+ * re-evaluate historical completion and eventless transitions. Active-state
849
+ * invokes start once in ancestor and document order with {@link InitialEvent};
850
+ * delayed invokes restart their complete duration and invoked machines start
851
+ * from their own initial state.
852
+ *
853
+ * Only logical state, completion, and history metadata are resumed. Queues,
854
+ * scopes, subscriptions, fibers, spawned children, invoke progress, and prior
855
+ * runtime status are process-local and are not restored. A final snapshot
856
+ * immediately produces a completed ref with its current-machine output.
857
+ *
858
+ * Decode encoded data explicitly with {@link decodeSnapshot} before calling
859
+ * this function. Stable snapshots are hosted as supplied; newly enabled
860
+ * eventless or completion transitions in a changed machine definition are not
861
+ * evaluated merely because the runtime was resumed; only ordinary subsequent
862
+ * transition planning can enter and stabilize states.
863
+ *
864
+ * **Example**
865
+ *
866
+ * ```ts
867
+ * import { Effect, Schema } from "effect"
868
+ * import { Machine } from "@typeonce/effect-machine"
869
+ *
870
+ * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {}
871
+ * const States = Machine.defineStates({ Idle })
872
+ * const machine = Machine.make({
873
+ * states: States.states,
874
+ * events: [],
875
+ * initial: () => States.initial.Idle.from()
876
+ * }).handle({ Idle: {} })
877
+ *
878
+ * const resumed = Effect.gen(function*() {
879
+ * const initial = yield* Machine.planInitial(machine)
880
+ * const encoded = yield* Machine.encodeSnapshot(machine, initial.state)
881
+ * const snapshot = yield* Machine.decodeSnapshot(machine, encoded)
882
+ * return yield* Machine.resume(machine, snapshot)
883
+ * })
884
+ * ```
885
+ *
886
+ * @see {@link decodeSnapshot} for the schema and transport boundary.
887
+ * @see {@link start} for ordinary initial startup.
888
+ * @category constructors
889
+ * @since 0.4.0
1084
890
  */
1085
- export const start = internalProcess.start;
891
+ export const resume = internal.resume;
1086
892
  //# sourceMappingURL=Machine.js.map