@typeonce/effect-machine 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +345 -42
  2. package/dist/Machine.d.ts +1273 -347
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +161 -426
  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} +19 -94
  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} +32 -38
  27. package/dist/internal/machine/configuration.d.ts.map +1 -0
  28. package/dist/internal/machine/configuration.js +965 -0
  29. package/dist/internal/machine/configuration.js.map +1 -0
  30. package/dist/internal/{machineErrors.d.ts → machine/errors.d.ts} +3 -3
  31. package/dist/internal/machine/errors.d.ts.map +1 -0
  32. package/dist/internal/{machineErrors.js → machine/errors.js} +1 -1
  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 +667 -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} +10 -4
  51. package/dist/internal/machine/process.d.ts.map +1 -0
  52. package/dist/internal/machine/process.js +446 -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/{machineRuntime.d.ts → machine/runtime.d.ts} +104 -2
  63. package/dist/internal/machine/runtime.d.ts.map +1 -0
  64. package/dist/internal/machine/runtime.js +1381 -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/finiteModel.d.ts +322 -0
  87. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -0
  88. package/dist/internal/testing/machine/finiteModel.js +976 -0
  89. package/dist/internal/testing/machine/finiteModel.js.map +1 -0
  90. package/dist/internal/testing/machine/referenceModel.d.ts +203 -0
  91. package/dist/internal/testing/machine/referenceModel.d.ts.map +1 -0
  92. package/dist/internal/testing/machine/referenceModel.js +1012 -0
  93. package/dist/internal/testing/machine/referenceModel.js.map +1 -0
  94. package/dist/internal/testing/machine/runtime.d.ts +328 -0
  95. package/dist/internal/testing/machine/runtime.d.ts.map +1 -0
  96. package/dist/internal/testing/machine/runtime.js +437 -0
  97. package/dist/internal/testing/machine/runtime.js.map +1 -0
  98. package/dist/internal/testing/machine/verification.d.ts +33 -0
  99. package/dist/internal/testing/machine/verification.d.ts.map +1 -0
  100. package/dist/internal/testing/machine/verification.js +1446 -0
  101. package/dist/internal/testing/machine/verification.js.map +1 -0
  102. package/dist/testing/MachineTest.d.ts +606 -0
  103. package/dist/testing/MachineTest.d.ts.map +1 -0
  104. package/dist/testing/MachineTest.js +102 -0
  105. package/dist/testing/MachineTest.js.map +1 -0
  106. package/dist/testing/index.d.ts +7 -0
  107. package/dist/testing/index.d.ts.map +1 -0
  108. package/dist/testing/index.js +7 -0
  109. package/dist/testing/index.js.map +1 -0
  110. package/dist/{ClusterMachine.d.ts → unstable/cluster/ClusterMachine.d.ts} +22 -30
  111. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -0
  112. package/dist/unstable/cluster/ClusterMachine.js +126 -0
  113. package/dist/unstable/cluster/ClusterMachine.js.map +1 -0
  114. package/dist/{cluster.js → unstable/cluster/index.d.ts} +1 -1
  115. package/dist/unstable/cluster/index.d.ts.map +1 -0
  116. package/dist/{cluster.d.ts → unstable/cluster/index.js} +1 -1
  117. package/dist/unstable/cluster/index.js.map +1 -0
  118. package/dist/{AtomMachine.d.ts → unstable/reactivity/AtomMachine.d.ts} +40 -23
  119. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -0
  120. package/dist/unstable/reactivity/AtomMachine.js +113 -0
  121. package/dist/unstable/reactivity/AtomMachine.js.map +1 -0
  122. package/dist/{reactivity.js → unstable/reactivity/index.d.ts} +1 -1
  123. package/dist/unstable/reactivity/index.d.ts.map +1 -0
  124. package/dist/{reactivity.d.ts → unstable/reactivity/index.js} +1 -1
  125. package/dist/unstable/reactivity/index.js.map +1 -0
  126. package/docs/agent-guide.md +271 -38
  127. package/package.json +23 -13
  128. package/dist/AtomMachine.d.ts.map +0 -1
  129. package/dist/AtomMachine.js.map +0 -1
  130. package/dist/ClusterMachine.d.ts.map +0 -1
  131. package/dist/ClusterMachine.js.map +0 -1
  132. package/dist/cluster.d.ts.map +0 -1
  133. package/dist/cluster.js.map +0 -1
  134. package/dist/internal/machineErrors.d.ts.map +0 -1
  135. package/dist/internal/machineErrors.js.map +0 -1
  136. package/dist/internal/machineModel.d.ts.map +0 -1
  137. package/dist/internal/machineModel.js +0 -766
  138. package/dist/internal/machineModel.js.map +0 -1
  139. package/dist/internal/machinePlanner.d.ts +0 -74
  140. package/dist/internal/machinePlanner.d.ts.map +0 -1
  141. package/dist/internal/machinePlanner.js +0 -621
  142. package/dist/internal/machinePlanner.js.map +0 -1
  143. package/dist/internal/machineProcess.d.ts.map +0 -1
  144. package/dist/internal/machineProcess.js +0 -181
  145. package/dist/internal/machineProcess.js.map +0 -1
  146. package/dist/internal/machineRuntime.d.ts.map +0 -1
  147. package/dist/internal/machineRuntime.js +0 -365
  148. package/dist/internal/machineRuntime.js.map +0 -1
  149. package/dist/reactivity.d.ts.map +0 -1
  150. package/dist/reactivity.js.map +0 -1
@@ -1,621 +0,0 @@
1
- /**
2
- * Internal machine planning helpers.
3
- *
4
- * @since 4.0.0
5
- */
6
- import * as Cause from "effect/Cause";
7
- import * as Context from "effect/Context";
8
- import * as Effect from "effect/Effect";
9
- import * as Option from "effect/Option";
10
- import { InfiniteTransitionError, MachineSchemaDecodeError, StartupError } from "./machineErrors.js";
11
- import { compareDocumentOrder, completeConfigurationEffect, decodeEmit, decodeEvent, decodeInput, getActiveLeafPathFrom, getActiveLeafPaths, getActiveValue, getInitialEntryPaths, getLeafPath, getNode, getParentValue, getParentValues, getPathToRoot, getRootPath, isActiveFinalConfiguration, isDescendantOf, isSnapshot, isTarget, normalizeConfiguration, normalizeConfigurationEffect, normalizeTargetConfigurationEffect, pathDepth, snapshotFromConfiguration, validateInitialConfiguration } from "./machineModel.js";
12
- class DeferredActions extends Context.Service()("effect/Machine/DeferredActions") {
13
- }
14
- class DeferredRaisedEvents extends Context.Service()("effect/Machine/DeferredRaisedEvents") {
15
- }
16
- class RuntimeContext extends Context.Service()("effect/Machine/Runtime") {
17
- }
18
- const makeDeferredQueue = () => Effect.sync(() => {
19
- const values = [];
20
- return {
21
- read: Effect.sync(() => values),
22
- add: (value) => Effect.sync(() => {
23
- values.push(value);
24
- })
25
- };
26
- });
27
- const makeDeferredActions = Effect.map(makeDeferredQueue(), (queue) => DeferredActions.of({
28
- read: queue.read,
29
- add: (effect) => queue.add(effect)
30
- }));
31
- const makeDeferredRaisedEvents = Effect.gen(function* () {
32
- const raised = yield* makeDeferredQueue();
33
- const emitted = yield* makeDeferredQueue();
34
- return (DeferredRaisedEvents.of({
35
- read: raised.read,
36
- readEmitted: emitted.read,
37
- add: (event) => raised.add(event),
38
- addEmitted: (event) => emitted.add(event)
39
- }));
40
- });
41
- const provideDeferredServices = (effect, machine, deferredActions, deferredRaisedEvents) => effect.pipe(Effect.provideService(DeferredActions, deferredActions), Effect.provideService(DeferredRaisedEvents, deferredRaisedEvents), Effect.provideService(RuntimeContext, makePlanningRuntime(machine, deferredRaisedEvents)));
42
- const provideRuntimeContext = (effect, runtime) => Effect.provideService(effect, RuntimeContext, runtime);
43
- const makePlanningRuntime = (machine, deferredRaisedEvents) => RuntimeContext.of({
44
- raise: (event) => decodeEvent(machine, event).pipe(Effect.flatMap((event) => deferredRaisedEvents.add(event))),
45
- sendParent: (event) => decodeEmit(machine, event).pipe(Effect.flatMap((event) => deferredRaisedEvents.addEmitted(event)))
46
- });
47
- export const makeLiveRuntime = (machine, scope) => RuntimeContext.of({
48
- raise: (event) => decodeEvent(machine, event).pipe(Effect.flatMap((event) => scope.self.send(event))),
49
- sendParent: (event) => decodeEmit(machine, event).pipe(Effect.flatMap((event) => scope.sendParent(event)))
50
- });
51
- export const runActions = (actions, runtime) => Effect.all(Array.from(actions, (action) => provideRuntimeContext(action, runtime)), { discard: true });
52
- export const runEmittedEvents = (events, runtime) => Effect.all(Array.from(events, (event) => runtime.sendParent(event)), { discard: true });
53
- export const runtimeFor = () => runtime();
54
- const normalizeEventTransition = (transition) => {
55
- if (transition === undefined) {
56
- return undefined;
57
- }
58
- return typeof transition === "function"
59
- ? { reenter: false, transition }
60
- : { reenter: transition.reenter === true, transition: transition.transition };
61
- };
62
- const collectStateAction = Effect.fnUntraced(function* (machine, handler, context) {
63
- const deferredActions = yield* makeDeferredActions;
64
- const deferredRaisedEvents = yield* makeDeferredRaisedEvents;
65
- if (handler !== undefined) {
66
- const result = handler(context);
67
- if (Effect.isEffect(result)) {
68
- yield* provideDeferredServices(result, machine, deferredActions, deferredRaisedEvents);
69
- }
70
- }
71
- const actions = yield* deferredActions.read;
72
- const raisedEvents = yield* deferredRaisedEvents.read;
73
- const emittedEvents = yield* deferredRaisedEvents.readEmitted;
74
- return {
75
- actions: actions,
76
- raisedEvents: raisedEvents,
77
- emittedEvents
78
- };
79
- });
80
- const collectTransition = Effect.fnUntraced(function* (machine, transition, context) {
81
- const deferredActions = yield* makeDeferredActions;
82
- const deferredRaisedEvents = yield* makeDeferredRaisedEvents;
83
- const result = transition(context);
84
- const state = Effect.isEffect(result)
85
- ? yield* provideDeferredServices(result, machine, deferredActions, deferredRaisedEvents)
86
- : result;
87
- const actions = yield* deferredActions.read;
88
- const raisedEvents = yield* deferredRaisedEvents.read;
89
- const emittedEvents = yield* deferredRaisedEvents.readEmitted;
90
- return {
91
- state,
92
- actions: actions,
93
- raisedEvents: raisedEvents,
94
- emittedEvents
95
- };
96
- });
97
- const getCandidatePaths = (machine, configuration) => Array.from(configuration.active)
98
- .sort((left, right) => {
99
- const depth = pathDepth(machine, right) - pathDepth(machine, left);
100
- return depth === 0 ? compareDocumentOrder(machine, left, right) : depth;
101
- });
102
- const getLeafCandidatePaths = (machine, leaf) => [...getPathToRoot(machine, leaf)].reverse();
103
- const getLeastCommonAncestor = (machine, left, right) => {
104
- const leftPath = getPathToRoot(machine, left);
105
- const rightPath = getPathToRoot(machine, right);
106
- let ancestor = undefined;
107
- const length = Math.min(leftPath.length, rightPath.length);
108
- for (let index = 0; index < length; index++) {
109
- if (leftPath[index] !== rightPath[index]) {
110
- break;
111
- }
112
- ancestor = leftPath[index];
113
- }
114
- return ancestor;
115
- };
116
- const getExitPaths = (machine, configuration, boundary) => sortExitPaths(machine, Array.from(configuration.active)
117
- .filter((path) => boundary === undefined || isDescendantOf(path, boundary)));
118
- const getEntryPaths = (machine, configuration, boundary) => sortEntryPaths(machine, Array.from(configuration.active).filter((path) => boundary === undefined || isDescendantOf(path, boundary)));
119
- const hasSameActivePaths = (left, right) => left.active.size === right.active.size && Array.from(left.active).every((path) => right.active.has(path));
120
- export const sortExitPaths = (machine, paths) => Array.from(new Set(paths))
121
- .sort((left, right) => {
122
- const depth = getPathToRoot(machine, right).length - getPathToRoot(machine, left).length;
123
- return depth === 0 ? getNode(machine, right).order - getNode(machine, left).order : depth;
124
- });
125
- export const sortEntryPaths = (machine, paths) => Array.from(new Set(paths))
126
- .sort((left, right) => {
127
- const depth = getPathToRoot(machine, left).length - getPathToRoot(machine, right).length;
128
- return depth === 0 ? compareDocumentOrder(machine, left, right) : depth;
129
- });
130
- const makePlanningCapabilities = () => {
131
- const runtimeEffect = runtimeFor();
132
- return {
133
- runtime: runtimeEffect,
134
- raise: (event) => Effect.flatMap(runtimeEffect, (runtime) => runtime.raise(event)),
135
- emit: (event) => Effect.flatMap(runtimeEffect, (runtime) => runtime.sendParent(event))
136
- };
137
- };
138
- const makeStateActionContext = (machine, configuration, path, event) => ({
139
- state: getActiveValue(configuration, path),
140
- parent: getParentValue(machine, configuration, path),
141
- parents: getParentValues(machine, configuration, path),
142
- event,
143
- ...makePlanningCapabilities()
144
- });
145
- const makeTransitionContext = (machine, configuration, path, event) => ({
146
- state: getActiveValue(configuration, path),
147
- parent: getParentValue(machine, configuration, path),
148
- parents: getParentValues(machine, configuration, path),
149
- event,
150
- ...makePlanningCapabilities(),
151
- target: machine.makeTargetBuilder(path)
152
- });
153
- const makeDoneContext = (machine, configuration, path, event, output) => ({
154
- state: getActiveValue(configuration, path),
155
- parent: getParentValue(machine, configuration, path),
156
- parents: getParentValues(machine, configuration, path),
157
- event,
158
- output: output,
159
- ...makePlanningCapabilities(),
160
- target: machine.makeTargetBuilder(path)
161
- });
162
- const collectStateActions = Effect.fnUntraced(function* (machine, configuration, paths, event, key) {
163
- const actions = [];
164
- const raisedEvents = [];
165
- const emittedEvents = [];
166
- for (const path of paths) {
167
- const collected = yield* collectStateAction(machine, machine.handlers[path]?.[key], makeStateActionContext(machine, configuration, path, event));
168
- actions.push(...collected.actions);
169
- raisedEvents.push(...collected.raisedEvents);
170
- emittedEvents.push(...collected.emittedEvents);
171
- }
172
- return { actions, emittedEvents, raisedEvents };
173
- });
174
- const selectAlwaysTransitions = (machine, configuration, event) => {
175
- const selected = [];
176
- const selectedSources = new Set();
177
- for (const leaf of getActiveLeafPaths(machine, configuration)) {
178
- for (const path of getLeafCandidatePaths(machine, leaf)) {
179
- const always = machine.handlers[path]?.always;
180
- if (always !== undefined) {
181
- if (!selectedSources.has(path)) {
182
- selectedSources.add(path);
183
- selected.push({
184
- sourcePath: path,
185
- leafPath: leaf,
186
- transition: { reenter: false, transition: always },
187
- context: {
188
- state: getActiveValue(configuration, path),
189
- parent: getParentValue(machine, configuration, path),
190
- parents: getParentValues(machine, configuration, path),
191
- event,
192
- ...makePlanningCapabilities(),
193
- target: machine.makeTargetBuilder(path)
194
- }
195
- });
196
- }
197
- break;
198
- }
199
- }
200
- }
201
- return selected;
202
- };
203
- const selectDoneTransitions = (machine, configuration, event, completions) => {
204
- const selected = [];
205
- const selectedSources = new Set();
206
- for (const completion of completions) {
207
- const onDone = machine.handlers[completion.path]?.onDone;
208
- if (onDone !== undefined && !selectedSources.has(completion.path)) {
209
- selectedSources.add(completion.path);
210
- selected.push({
211
- sourcePath: completion.path,
212
- leafPath: getActiveLeafPathFrom(machine, configuration, completion.path),
213
- transition: { reenter: false, transition: onDone },
214
- context: makeDoneContext(machine, configuration, completion.path, event, completion.output)
215
- });
216
- }
217
- }
218
- return selected;
219
- };
220
- const selectEventTransitions = (machine, configuration, event) => {
221
- const selected = [];
222
- const selectedSources = new Set();
223
- for (const leaf of getActiveLeafPaths(machine, configuration)) {
224
- for (const path of getLeafCandidatePaths(machine, leaf)) {
225
- const transition = normalizeEventTransition(machine.handlers[path]?.on?.[event._tag]);
226
- if (transition !== undefined) {
227
- if (!selectedSources.has(path)) {
228
- selectedSources.add(path);
229
- selected.push({
230
- sourcePath: path,
231
- leafPath: leaf,
232
- transition: transition,
233
- context: makeTransitionContext(machine, configuration, path, event)
234
- });
235
- }
236
- break;
237
- }
238
- }
239
- }
240
- return selected;
241
- };
242
- const getTargetNodePath = (target) => {
243
- if (isTarget(target)) {
244
- return String(target.path);
245
- }
246
- if (isSnapshot(target)) {
247
- return String(target.path);
248
- }
249
- throw new Error("Machine expected transition target to be a snapshot or target builder result");
250
- };
251
- const hasPathIntersection = (left, right) => {
252
- for (const path of left) {
253
- if (right.includes(path)) {
254
- return true;
255
- }
256
- }
257
- return false;
258
- };
259
- const sortEvaluatedTransitions = (machine, transitions) => Array.from(transitions)
260
- .sort((left, right) => compareDocumentOrder(machine, left.selection.sourcePath, right.selection.sourcePath));
261
- const removePreemptedAncestorSelections = (selections) => selections.filter((selection) => !selections.some((other) => other.sourcePath !== selection.sourcePath && isDescendantOf(other.sourcePath, selection.sourcePath)));
262
- const removeConflictingTransitions = (machine, transitions) => {
263
- const filtered = [];
264
- for (const transition of sortEvaluatedTransitions(machine, transitions)) {
265
- let preempted = false;
266
- const transitionsToRemove = new Set();
267
- for (const selected of filtered) {
268
- if (hasPathIntersection(transition.exitPaths, selected.exitPaths)) {
269
- if (isDescendantOf(transition.selection.sourcePath, selected.selection.sourcePath)) {
270
- transitionsToRemove.add(selected);
271
- }
272
- else {
273
- preempted = true;
274
- break;
275
- }
276
- }
277
- }
278
- if (!preempted) {
279
- for (const removed of transitionsToRemove) {
280
- const index = filtered.indexOf(removed);
281
- if (index >= 0) {
282
- filtered.splice(index, 1);
283
- }
284
- }
285
- filtered.push(transition);
286
- }
287
- }
288
- return filtered;
289
- };
290
- const collectEvaluatedTransition = Effect.fnUntraced(function* (machine, state, selection) {
291
- const stateIdentifier = selection.leafPath;
292
- const transitionResult = yield* collectTransition(machine, selection.transition.transition, selection.context);
293
- const target = transitionResult.state === undefined
294
- ? undefined
295
- : transitionResult.state;
296
- const targetPath = target === undefined ? undefined : getTargetNodePath(target);
297
- const stateAfterTransition = target === undefined
298
- ? state
299
- : yield* normalizeTargetConfigurationEffect(machine, state, target);
300
- const changed = selection.transition.reenter || !hasSameActivePaths(state, stateAfterTransition);
301
- if (!changed) {
302
- return {
303
- selection,
304
- target,
305
- actions: transitionResult.actions,
306
- raisedEvents: transitionResult.raisedEvents,
307
- emittedEvents: transitionResult.emittedEvents,
308
- changed,
309
- exitPaths: [],
310
- entryPaths: []
311
- };
312
- }
313
- const boundary = selection.transition.reenter
314
- ? getNode(machine, selection.sourcePath).parent
315
- : getLeastCommonAncestor(machine, stateIdentifier, targetPath);
316
- return {
317
- selection,
318
- target,
319
- actions: transitionResult.actions,
320
- raisedEvents: transitionResult.raisedEvents,
321
- emittedEvents: transitionResult.emittedEvents,
322
- changed,
323
- exitPaths: getExitPaths(machine, state, boundary),
324
- entryPaths: getEntryPaths(machine, stateAfterTransition, boundary)
325
- };
326
- });
327
- const MaxMacrostepIterations = 1000;
328
- export const InitialEventTypeId = Symbol("effect/Machine/InitialEvent");
329
- export const InitialEvent = { _tag: InitialEventTypeId };
330
- const catchStartup = (effect) => Effect.catchCause(effect, (cause) => {
331
- if (Cause.hasDies(cause)) {
332
- return Effect.fail(new StartupError({ cause }));
333
- }
334
- return Effect.failCause(cause);
335
- });
336
- export const isFinalState = (machine, state) => isActiveFinalConfiguration(machine, normalizeConfiguration(machine, state));
337
- export const getFinalOutputEffect = (machine, state, event) => normalizeConfigurationEffect(machine, state).pipe(Effect.flatMap((configuration) => completeConfigurationEffect(machine, configuration, event)), Effect.flatMap((completed) => {
338
- const root = getRootPath(machine, completed.configuration);
339
- if (!isActiveFinalConfiguration(machine, completed.configuration)
340
- || !completed.configuration.outputs.has(root)) {
341
- return Effect.die(new Error("Machine attempted to read terminal output from a non-terminal configuration"));
342
- }
343
- return Effect.succeed(completed.configuration.outputs.get(root));
344
- }));
345
- export const isFinal = (machine, state) => isFinalState(machine, state);
346
- export const planInitial = Effect.fnUntraced(function* (machine, ...args) {
347
- return yield* catchStartup(Effect.gen(function* () {
348
- const deferredActions = yield* makeDeferredActions;
349
- const deferredRaisedEvents = yield* makeDeferredRaisedEvents;
350
- const inputArgs = machine.input === undefined
351
- ? args
352
- : args.length === 0
353
- ? (yield* decodeInput(machine, machine.input, undefined), args)
354
- : [yield* decodeInput(machine, machine.input, args[0])];
355
- const result = machine.initial(...inputArgs);
356
- const state = Effect.isEffect(result)
357
- ? yield* provideDeferredServices(result, machine, deferredActions, deferredRaisedEvents)
358
- : result;
359
- const configuration = yield* normalizeConfigurationEffect(machine, state);
360
- validateInitialConfiguration(machine, configuration);
361
- const actions = yield* deferredActions.read;
362
- const raisedEvents = yield* deferredRaisedEvents.read;
363
- const emittedEvents = yield* deferredRaisedEvents.readEmitted;
364
- const settled = yield* Effect.gen(function* () {
365
- const entry = yield* collectStateActions(machine, configuration, getInitialEntryPaths(machine, configuration), InitialEvent, "entry");
366
- return yield* settle(machine, configuration, InitialEvent, [...entry.actions], [...raisedEvents, ...entry.raisedEvents], [...emittedEvents, ...entry.emittedEvents], []);
367
- });
368
- const planned = {
369
- state: snapshotFromConfiguration(machine, settled.next),
370
- actions: [
371
- ...actions,
372
- ...settled.actions
373
- ],
374
- emittedEvents: settled.emittedEvents
375
- };
376
- return settled.done
377
- ? { ...planned, done: true, output: settled.output }
378
- : { ...planned, done: false, output: undefined };
379
- }));
380
- });
381
- export const enabled = (machine, state) => {
382
- if (isFinalState(machine, state)) {
383
- return [];
384
- }
385
- const configuration = normalizeConfiguration(machine, state);
386
- const tags = [];
387
- const seen = new Set();
388
- for (const path of getCandidatePaths(machine, configuration)) {
389
- for (const tag of Reflect.ownKeys(machine.handlers[path]?.on ?? {})) {
390
- if (!seen.has(tag)) {
391
- seen.add(tag);
392
- tags.push(tag);
393
- }
394
- }
395
- }
396
- return tags;
397
- };
398
- const microstep = Effect.fnUntraced(function* (machine, state, event, selections) {
399
- if (selections.length === 0) {
400
- return {
401
- next: state,
402
- event,
403
- actions: [],
404
- raisedEvents: [],
405
- emittedEvents: [],
406
- exitPaths: [],
407
- entryPaths: [],
408
- changed: false
409
- };
410
- }
411
- const activeSelections = removePreemptedAncestorSelections(selections);
412
- const evaluatedTransitions = [];
413
- for (const selection of activeSelections) {
414
- evaluatedTransitions.push(yield* collectEvaluatedTransition(machine, state, selection));
415
- }
416
- const transitions = removeConflictingTransitions(machine, evaluatedTransitions);
417
- const sortedTransitions = sortEvaluatedTransitions(machine, transitions);
418
- let stateAfterTransition = state;
419
- for (const transition of sortedTransitions) {
420
- if (transition.target !== undefined) {
421
- stateAfterTransition = yield* normalizeTargetConfigurationEffect(machine, stateAfterTransition, transition.target);
422
- }
423
- }
424
- const changed = transitions.some((transition) => transition.changed);
425
- const transitionActions = sortedTransitions
426
- .flatMap((transition) => transition.actions);
427
- const transitionRaisedEvents = sortedTransitions
428
- .flatMap((transition) => transition.raisedEvents);
429
- const transitionEmittedEvents = sortedTransitions
430
- .flatMap((transition) => transition.emittedEvents);
431
- if (!changed) {
432
- return {
433
- next: stateAfterTransition,
434
- event,
435
- actions: transitionActions,
436
- raisedEvents: transitionRaisedEvents,
437
- emittedEvents: transitionEmittedEvents,
438
- exitPaths: [],
439
- entryPaths: [],
440
- changed: false
441
- };
442
- }
443
- const exitPaths = sortExitPaths(machine, sortedTransitions.flatMap((transition) => transition.exitPaths));
444
- const entryPaths = sortEntryPaths(machine, sortedTransitions.flatMap((transition) => transition.entryPaths));
445
- const exit = yield* collectStateActions(machine, state, exitPaths, event, "exit");
446
- const entry = yield* collectStateActions(machine, stateAfterTransition, entryPaths, event, "entry");
447
- return {
448
- next: stateAfterTransition,
449
- event,
450
- actions: [...exit.actions, ...transitionActions, ...entry.actions],
451
- raisedEvents: [...exit.raisedEvents, ...transitionRaisedEvents, ...entry.raisedEvents],
452
- emittedEvents: [...exit.emittedEvents, ...transitionEmittedEvents, ...entry.emittedEvents],
453
- exitPaths,
454
- entryPaths,
455
- changed: true
456
- };
457
- });
458
- const settle = Effect.fnUntraced(function* (machine, state, event, actions, raisedEvents, emittedEvents, microsteps) {
459
- let currentState = state;
460
- let currentEvent = event;
461
- let shouldRunAlways = true;
462
- let iterations = 0;
463
- let raisedEventIndex = 0;
464
- let completedTerminal = false;
465
- let finalOutput = undefined;
466
- const pendingCompletions = [];
467
- while (true) {
468
- iterations += 1;
469
- if (iterations > MaxMacrostepIterations) {
470
- return yield* new InfiniteTransitionError({
471
- machineId: machine.id,
472
- state: String(getLeafPath(machine, currentState)),
473
- maxIterations: MaxMacrostepIterations
474
- });
475
- }
476
- const completed = yield* completeConfigurationEffect(machine, currentState, currentEvent);
477
- currentState = completed.configuration;
478
- pendingCompletions.push(...completed.completions.filter((completion) => machine.handlers[completion.path]?.onDone !== undefined));
479
- while (pendingCompletions.length > 0 && !currentState.active.has(pendingCompletions[0].path)) {
480
- pendingCompletions.shift();
481
- }
482
- const done = selectDoneTransitions(machine, currentState, currentEvent, pendingCompletions.length === 0 ? [] : [pendingCompletions.shift()]);
483
- if (done.length > 0) {
484
- const doneStep = yield* microstep(machine, currentState, currentEvent, done);
485
- actions.push(...doneStep.actions);
486
- raisedEvents.push(...doneStep.raisedEvents);
487
- emittedEvents.push(...doneStep.emittedEvents);
488
- microsteps.push(doneStep);
489
- currentState = doneStep.next;
490
- shouldRunAlways = doneStep.changed;
491
- continue;
492
- }
493
- if (isActiveFinalConfiguration(machine, currentState)) {
494
- const root = getRootPath(machine, currentState);
495
- if (!currentState.outputs.has(root)) {
496
- return yield* Effect.die(new Error("Machine reached a terminal configuration without a completed root output"));
497
- }
498
- completedTerminal = true;
499
- finalOutput = currentState.outputs.get(root);
500
- break;
501
- }
502
- const always = shouldRunAlways
503
- ? selectAlwaysTransitions(machine, currentState, currentEvent)
504
- : [];
505
- if (always.length > 0) {
506
- const alwaysStep = yield* microstep(machine, currentState, currentEvent, always);
507
- actions.push(...alwaysStep.actions);
508
- raisedEvents.push(...alwaysStep.raisedEvents);
509
- emittedEvents.push(...alwaysStep.emittedEvents);
510
- microsteps.push(alwaysStep);
511
- currentState = alwaysStep.next;
512
- shouldRunAlways = alwaysStep.changed;
513
- continue;
514
- }
515
- const raisedEventValue = raisedEvents[raisedEventIndex];
516
- if (raisedEventValue === undefined) {
517
- break;
518
- }
519
- raisedEventIndex += 1;
520
- // Planning runtime validates and normalizes every event before it enters this
521
- // internal queue, so decoding it again here only repeats schema work.
522
- const raisedEvent = raisedEventValue;
523
- currentEvent = raisedEvent;
524
- const raisedSelections = selectEventTransitions(machine, currentState, raisedEvent);
525
- if (raisedSelections.length === 0) {
526
- shouldRunAlways = true;
527
- continue;
528
- }
529
- const raisedStep = yield* microstep(machine, currentState, raisedEvent, raisedSelections);
530
- actions.push(...raisedStep.actions);
531
- raisedEvents.push(...raisedStep.raisedEvents);
532
- emittedEvents.push(...raisedStep.emittedEvents);
533
- microsteps.push(raisedStep);
534
- currentState = raisedStep.next;
535
- shouldRunAlways = true;
536
- }
537
- const result = {
538
- next: currentState,
539
- actions,
540
- emittedEvents,
541
- microsteps
542
- };
543
- return completedTerminal
544
- ? { ...result, done: true, output: finalOutput }
545
- : { ...result, done: false, output: undefined };
546
- });
547
- const macrostep = Effect.fnUntraced(function* (machine, state, event) {
548
- const configuration = yield* normalizeConfigurationEffect(machine, state);
549
- const snapshot = snapshotFromConfiguration(machine, configuration);
550
- const decodedEvent = yield* decodeEvent(machine, event);
551
- if (isActiveFinalConfiguration(machine, configuration)) {
552
- const completed = yield* completeConfigurationEffect(machine, configuration, decodedEvent);
553
- const root = getRootPath(machine, completed.configuration);
554
- if (!completed.configuration.outputs.has(root)) {
555
- return yield* Effect.die(new Error("Machine reached a terminal configuration without a completed root output"));
556
- }
557
- return {
558
- next: snapshotFromConfiguration(machine, completed.configuration),
559
- actions: [],
560
- emittedEvents: [],
561
- microsteps: [],
562
- done: true,
563
- output: completed.configuration.outputs.get(root)
564
- };
565
- }
566
- const selections = selectEventTransitions(machine, configuration, decodedEvent);
567
- if (selections.length === 0) {
568
- return {
569
- next: snapshot,
570
- actions: [],
571
- emittedEvents: [],
572
- microsteps: [],
573
- done: false,
574
- output: undefined
575
- };
576
- }
577
- const step = yield* microstep(machine, configuration, decodedEvent, selections);
578
- const actions = [...step.actions];
579
- const raisedEvents = [...step.raisedEvents];
580
- const emittedEvents = [...step.emittedEvents];
581
- const microsteps = [step];
582
- const settled = yield* settle(machine, step.next, decodedEvent, actions, raisedEvents, emittedEvents, microsteps);
583
- const planned = {
584
- next: snapshotFromConfiguration(machine, settled.next),
585
- actions: settled.actions,
586
- emittedEvents: settled.emittedEvents,
587
- microsteps: settled.microsteps.map((step) => ({
588
- next: snapshotFromConfiguration(machine, step.next),
589
- event: step.event,
590
- actions: step.actions,
591
- raisedEvents: step.raisedEvents,
592
- emittedEvents: step.emittedEvents,
593
- exitPaths: step.exitPaths,
594
- entryPaths: step.entryPaths,
595
- changed: step.changed
596
- }))
597
- };
598
- return settled.done
599
- ? { ...planned, done: true, output: settled.output }
600
- : { ...planned, done: false, output: undefined };
601
- });
602
- export const plan = macrostep;
603
- const actionUnsafe = Effect.fnUntraced(function* (effect) {
604
- const actions = yield* DeferredActions;
605
- yield* actions.add(effect);
606
- });
607
- /**
608
- * Defers an effectful action until the current machine step is planned.
609
- *
610
- * @category combinators
611
- * @since 4.0.0
612
- */
613
- export const action = (effect) => actionUnsafe(effect);
614
- /**
615
- * Returns the typed runtime capability for the current machine.
616
- *
617
- * @category combinators
618
- * @since 4.0.0
619
- */
620
- export const runtime = () => RuntimeContext;
621
- //# sourceMappingURL=machinePlanner.js.map