@typeonce/effect-machine 0.35.0 → 0.37.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 (72) hide show
  1. package/README.md +45 -7
  2. package/dist/Machine.d.ts +143 -136
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +25 -0
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/command.d.ts +0 -1
  7. package/dist/internal/machine/command.d.ts.map +1 -1
  8. package/dist/internal/machine/command.js +0 -14
  9. package/dist/internal/machine/command.js.map +1 -1
  10. package/dist/internal/machine/configuration.d.ts.map +1 -1
  11. package/dist/internal/machine/configuration.js +15 -2
  12. package/dist/internal/machine/configuration.js.map +1 -1
  13. package/dist/internal/machine/construction.d.ts +9 -0
  14. package/dist/internal/machine/construction.d.ts.map +1 -0
  15. package/dist/internal/machine/construction.js +132 -0
  16. package/dist/internal/machine/construction.js.map +1 -0
  17. package/dist/internal/machine/declaration.d.ts +1 -0
  18. package/dist/internal/machine/declaration.d.ts.map +1 -1
  19. package/dist/internal/machine/declaration.js +4 -8
  20. package/dist/internal/machine/declaration.js.map +1 -1
  21. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  22. package/dist/internal/machine/executionPlan.js +13 -9
  23. package/dist/internal/machine/executionPlan.js.map +1 -1
  24. package/dist/internal/machine/implementation.d.ts +2 -3
  25. package/dist/internal/machine/implementation.d.ts.map +1 -1
  26. package/dist/internal/machine/implementation.js.map +1 -1
  27. package/dist/internal/machine/invocation.d.ts +1 -0
  28. package/dist/internal/machine/invocation.d.ts.map +1 -1
  29. package/dist/internal/machine/invocation.js +26 -3
  30. package/dist/internal/machine/invocation.js.map +1 -1
  31. package/dist/internal/machine/invocationDefinition.d.ts +3 -1
  32. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  33. package/dist/internal/machine/invocationDefinition.js.map +1 -1
  34. package/dist/internal/machine/machine.d.ts +6 -0
  35. package/dist/internal/machine/machine.d.ts.map +1 -1
  36. package/dist/internal/machine/machine.js +70 -168
  37. package/dist/internal/machine/machine.js.map +1 -1
  38. package/dist/internal/machine/observation.d.ts +3 -0
  39. package/dist/internal/machine/observation.d.ts.map +1 -0
  40. package/dist/internal/machine/observation.js +28 -0
  41. package/dist/internal/machine/observation.js.map +1 -0
  42. package/dist/internal/machine/planner.d.ts.map +1 -1
  43. package/dist/internal/machine/planner.js +63 -17
  44. package/dist/internal/machine/planner.js.map +1 -1
  45. package/dist/internal/machine/topology.d.ts +6 -0
  46. package/dist/internal/machine/topology.d.ts.map +1 -1
  47. package/dist/internal/machine/topology.js.map +1 -1
  48. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  49. package/dist/internal/testing/machine/finiteModel.js +36 -76
  50. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  51. package/docs/agent-guide.md +57 -34
  52. package/docs/root-api.md +143 -190
  53. package/package.json +1 -1
  54. package/src/Machine.ts +223 -144
  55. package/src/internal/machine/command.ts +0 -16
  56. package/src/internal/machine/configuration.ts +13 -10
  57. package/src/internal/machine/construction.ts +147 -0
  58. package/src/internal/machine/declaration.ts +5 -7
  59. package/src/internal/machine/executionPlan.ts +13 -9
  60. package/src/internal/machine/implementation.ts +2 -3
  61. package/src/internal/machine/invocation.ts +34 -3
  62. package/src/internal/machine/invocationDefinition.ts +1 -0
  63. package/src/internal/machine/machine.ts +89 -223
  64. package/src/internal/machine/observation.ts +39 -0
  65. package/src/internal/machine/planner.ts +69 -18
  66. package/src/internal/machine/topology.ts +4 -0
  67. package/src/internal/testing/machine/finiteModel.ts +44 -122
  68. package/dist/internal/machine/targetBuilder.d.ts +0 -16
  69. package/dist/internal/machine/targetBuilder.d.ts.map +0 -1
  70. package/dist/internal/machine/targetBuilder.js +0 -333
  71. package/dist/internal/machine/targetBuilder.js.map +0 -1
  72. package/src/internal/machine/targetBuilder.ts +0 -525
@@ -28,11 +28,13 @@ import type {
28
28
  } from "../../Machine.js"
29
29
  import * as Activities from "./activities.js"
30
30
  import * as Configuration from "./configuration.js"
31
+ import * as Construction from "./construction.js"
31
32
  import * as Declaration from "./declaration.js"
32
33
  import type { ChildAlreadyExistsError, InfiniteTransitionError, StartupError } from "./errors.js"
33
34
  import type { CapturedStateConfig } from "./implementation.js"
34
35
  import * as InitialDeclaration from "./initialDeclaration.js"
35
36
  import * as InvocationDefinition from "./invocationDefinition.js"
37
+ import * as Observation from "./observation.js"
36
38
  import * as internalPlanner from "./planner.js"
37
39
  import * as internalProcess from "./process.js"
38
40
  import * as Protocol from "./protocol.js"
@@ -42,7 +44,6 @@ import * as internalRuntime from "./runtimeProtocol.js"
42
44
  import * as Serialization from "./serialization.js"
43
45
  import * as StateDefinition from "./stateDefinition.js"
44
46
  import { ChildMachineLogicTypeId } from "./symbols.js"
45
- import { getLocalTargetScope, makeTargetBuilder, withFrom } from "./targetBuilder.js"
46
47
  import * as TargetReference from "./targetReference.js"
47
48
  import * as Topology from "./topology.js"
48
49
 
@@ -107,7 +108,6 @@ const makeWithHandlers = (
107
108
  machine.initial = self.initial
108
109
  machine.initialDefinition = self.initialDefinition
109
110
  machine.stateNodes = self.stateNodes
110
- machine.makeTargetBuilder = self.makeTargetBuilder
111
111
  machine.handlers = handlers
112
112
  Protocol.copyProtocol(self, machine)
113
113
  return machine
@@ -139,20 +139,6 @@ const plainTargetSelection = (selection: Topology.TargetSelection): Topology.Tar
139
139
  ? Topology.noneTargetSelection
140
140
  : Topology.makeTargetSelection(selection.kind, selection.path, selection.scope, selection.updatePath)
141
141
 
142
- // The authored callback crosses an erased schema boundary here. Each builder
143
- // retains its construction mode, and planning validates both resulting values.
144
- const constructSelectionValue = (
145
- selection: Topology.TargetSelection,
146
- context: any,
147
- method: "from" | "decoded",
148
- value: unknown
149
- ): unknown => {
150
- if (selection.kind === "update") return context.owner[method](value)
151
- if (selection.updatePath === undefined) return context.target[method](value)
152
- const values = value as { readonly target: unknown; readonly update: unknown }
153
- return context.target[method](values.target).update(context.owner[method](values.update))
154
- }
155
-
156
142
  const transitionTargetSelection = (
157
143
  selection: Topology.TargetSelection
158
144
  ): Machine.TransitionTargetSelection =>
@@ -167,11 +153,6 @@ const selectionUpdates = (selection: Topology.TargetSelection): ReadonlyArray<st
167
153
  selection.kind === "update" && selection.path !== undefined ? [selection.path] : []
168
154
  : [selection.updatePath]
169
155
 
170
- const makeStateUpdateSelection = (
171
- path: string,
172
- scope: "local" | "branch"
173
- ): Topology.TargetSelection => Topology.makeTargetSelection("update", path, scope)
174
-
175
156
  const captureDefinitionBranch = (
176
157
  branch: unknown,
177
158
  selector: unknown,
@@ -206,91 +187,6 @@ const captureDefinitionBranch = (
206
187
  return { ...(branch as DefinitionBranch), selection }
207
188
  }
208
189
 
209
- const makeUpdatingConstruction = (
210
- target: unknown,
211
- ownerPath: string
212
- ): { readonly update: (update: unknown) => Topology.CombinedTarget } =>
213
- Object.freeze({
214
- update: (update: unknown) => {
215
- if (!Topology.isStateUpdate(update) || update.path !== ownerPath) {
216
- throw new Error(`Machine combined target must update its declared owner "${ownerPath}"`)
217
- }
218
- return Topology.makeCombinedTarget(target, update)
219
- }
220
- })
221
-
222
- const makeUpdatingTargetBuilder = (
223
- builder: unknown,
224
- ownerPath: string
225
- ): unknown => {
226
- if (typeof builder !== "object" || builder === null) {
227
- throw new Error("Machine combined target requires a state construction builder")
228
- }
229
- const updating: Record<PropertyKey, unknown> = {}
230
- for (const property of Reflect.ownKeys(builder)) {
231
- const descriptor = Object.getOwnPropertyDescriptor(builder, property)
232
- if (descriptor === undefined) continue
233
- if (
234
- (property === "from" || property === "decoded") && "value" in descriptor && typeof descriptor.value === "function"
235
- ) {
236
- const construct = descriptor.value
237
- descriptor.value = (...args: ReadonlyArray<unknown>) => makeUpdatingConstruction(construct(...args), ownerPath)
238
- }
239
- Object.defineProperty(updating, property, descriptor)
240
- }
241
- return Object.freeze(updating)
242
- }
243
-
244
- const getSelectionBuilder = (
245
- target: Record<string, any>,
246
- selection: Topology.TargetSelection,
247
- stateNodes: Machine.StateNodes,
248
- source: string
249
- ): unknown => {
250
- if (selection.kind === "none") return target.none
251
- if (selection.kind === "update") {
252
- return withFrom(
253
- (value: unknown) => Topology.makeStateUpdate(selection.path!, value),
254
- "leaf",
255
- true
256
- )
257
- }
258
- let builder: any
259
- let parts = selection.path!.split(".")
260
- if (selection.kind === "history") {
261
- builder = target.history
262
- if (selection.path !== "") parts.unshift("")
263
- } else if (selection.scope === "local") {
264
- builder = target.local
265
- const scope = getLocalTargetScope(stateNodes, source)
266
- if (scope !== undefined) {
267
- if (selection.path === scope) {
268
- builder = builder.with
269
- parts = []
270
- } else {
271
- parts = (scope === "" ? selection.path! : selection.path!.slice(scope.length + 1)).split(".")
272
- }
273
- }
274
- } else if (selection.scope === "branch") {
275
- builder = target.branch
276
- if (selection.path !== "") parts.unshift("")
277
- } else {
278
- builder = target.full
279
- }
280
- for (const part of parts) builder = builder[part]
281
- if (selection.kind === "initial") builder = builder.initial
282
- if (
283
- typeof builder !== "function" &&
284
- (typeof builder !== "object" || builder === null || typeof builder.from !== "function")
285
- ) {
286
- throw new Error(`Machine could not construct selected transition target "${selection.path}"`)
287
- }
288
- return selection.updatePath === undefined ? builder : makeUpdatingTargetBuilder(builder, selection.updatePath)
289
- }
290
-
291
- const constructSelectedTarget = (builder: any): unknown =>
292
- typeof builder?.from === "function" ? builder.from() : builder()
293
-
294
190
  const validateResolvedSelection = (
295
191
  result: unknown,
296
192
  selection: Topology.TargetSelection,
@@ -341,37 +237,13 @@ const runCapturedBranch = (
341
237
  stateNodes: Machine.StateNodes,
342
238
  source: string
343
239
  ): unknown => {
344
- const selectedTarget = getSelectionBuilder(context.target, branch.selection, stateNodes, source)
345
- if (branch.resolve === undefined) return constructSelectedTarget(selectedTarget)
346
- // This fresh context is owned by this evaluation and can be retained by user callbacks.
347
240
  const resolverContext: Record<string, any> = {
348
241
  ...context,
349
242
  root: source === "" ? context.state : context.ancestors[""],
350
243
  decline: Topology.makeDeclined
351
244
  }
352
- if (branch.selection.kind === "none") delete resolverContext.target
353
- else resolverContext.target = selectedTarget
354
- if (branch.selection.kind === "update") {
355
- const ownerPath = branch.selection.path!
356
- delete resolverContext.target
357
- resolverContext.current = context.ancestors[ownerPath] ?? context.state
358
- resolverContext.owner = getSelectionBuilder(
359
- context.target,
360
- makeStateUpdateSelection(ownerPath, branch.selection.scope === "local" ? "local" : "branch"),
361
- stateNodes,
362
- source
363
- )
364
- } else if (branch.selection.updatePath !== undefined) {
365
- const ownerPath = branch.selection.updatePath
366
- resolverContext.current = context.ancestors[ownerPath]
367
- resolverContext.owner = getSelectionBuilder(
368
- context.target,
369
- makeStateUpdateSelection(ownerPath, "branch"),
370
- stateNodes,
371
- source
372
- )
373
- }
374
- const resolved = branch.resolve(resolverContext, enqueue)
245
+ delete resolverContext.target
246
+ const resolved = branch.resolve!(resolverContext, enqueue)
375
247
  if (Topology.isDeclined(resolved)) {
376
248
  if (branch.declinable !== true) {
377
249
  throw new Error(`Machine transition for state "${source}" returned decline without declaring declinable: true`)
@@ -379,7 +251,7 @@ const runCapturedBranch = (
379
251
  return resolved
380
252
  }
381
253
  validateResolvedSelection(resolved, branch.selection, stateNodes)
382
- return resolved === undefined ? constructSelectedTarget(selectedTarget) : resolved
254
+ return resolved
383
255
  }
384
256
 
385
257
  const topologyTargetPath = (selection: Topology.TargetSelection): string | undefined =>
@@ -426,92 +298,59 @@ const captureNamedBranches = (
426
298
  }))
427
299
  }
428
300
 
429
- const wrapSelectedBranchBuilder = (
430
- builder: unknown,
431
- owner: object,
432
- branchIndex: number,
433
- branchKey: string,
434
- updateBuilder?: Record<string, (value: unknown) => unknown>
301
+ const constructBranch = (
302
+ selection: Topology.TargetSelection,
303
+ stateNodes: Machine.StateNodes,
304
+ declaration: Declaration.Declaration,
305
+ raw: unknown = {},
306
+ source?: string
435
307
  ): unknown => {
436
- if (typeof builder === "function") {
437
- const wrapped = (...args: ReadonlyArray<unknown>) => {
438
- const result = builder(...args)
439
- if (updateBuilder !== undefined) {
440
- return Object.freeze({
441
- update: Object.freeze(
442
- Object.fromEntries(
443
- Object.getOwnPropertyNames(updateBuilder).map((
444
- method
445
- ) => [method, (value: unknown) =>
446
- Topology.makeSelectedBranch(
447
- owner,
448
- branchIndex,
449
- branchKey,
450
- result.update(updateBuilder[method]!(value))
451
- )]
452
- )
453
- )
454
- )
455
- })
456
- }
457
- return Topology.makeSelectedBranch(owner, branchIndex, branchKey, result)
458
- }
459
- for (const property of Reflect.ownKeys(builder)) {
460
- if (
461
- property === "length" || property === "name" || property === "prototype" || property === "caller" ||
462
- property === "arguments"
463
- ) continue
464
- const descriptor = Object.getOwnPropertyDescriptor(builder, property)
465
- if (descriptor === undefined) continue
466
- if ("value" in descriptor && typeof descriptor.value === "function") {
467
- descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey, updateBuilder)
468
- }
469
- Object.defineProperty(wrapped, property, descriptor)
470
- }
471
- return wrapped
308
+ const config = Construction.record(raw)
309
+ if (selection.kind === "none" || selection.kind === "history" || selection.kind === "choice") {
310
+ if (Reflect.ownKeys(config).length > 0) throw new Error("Machine pseudo-state construction accepts no data")
311
+ if (selection.kind === "none") return undefined
312
+ const node = stateNodes.byPath.get(selection.path!)!
313
+ return selection.kind === "history" ?
314
+ Topology.makeHistoryTarget(node.path, node.parent!)
315
+ : Topology.makeChoiceTarget(node.path, node.parent!)
472
316
  }
473
- if (typeof builder === "object" && builder !== null) {
474
- const wrapped: Record<PropertyKey, unknown> = {}
475
- for (const property of Reflect.ownKeys(builder)) {
476
- const descriptor = Object.getOwnPropertyDescriptor(builder, property)
477
- if (descriptor === undefined) continue
478
- if ("value" in descriptor && typeof descriptor.value === "function") {
479
- descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey, updateBuilder)
480
- }
481
- Object.defineProperty(wrapped, property, descriptor)
317
+ if (selection.kind === "update") return Construction.update(stateNodes, selection.path!, config)
318
+ if (selection.path === "") {
319
+ if (Reflect.ownKeys(config).some((key) => key !== "input")) {
320
+ throw new Error("Machine root targets accept input only")
482
321
  }
483
- return wrapped
322
+ if (declaration.initialize === undefined) throw new Error("Machine root initialization is unavailable")
323
+ return declaration.initialize(config.input)
484
324
  }
485
- throw new Error(`Machine could not construct transition branch "${branchKey}"`)
325
+ if (selection.updatePath !== undefined) {
326
+ const { update, ...state } = config
327
+ return Topology.makeCombinedTarget(
328
+ Construction.target(stateNodes, selection.path!, state, source),
329
+ Construction.update(stateNodes, selection.updatePath, update)
330
+ )
331
+ }
332
+ return Construction.target(stateNodes, selection.path!, config, source)
486
333
  }
487
334
 
488
335
  const makeBranchSelectors = (
489
- context: Record<string, any>,
490
336
  branches: ReadonlyArray<CapturedNamedBranch>,
491
337
  owner: object,
492
338
  stateNodes: Machine.StateNodes,
339
+ declaration: Declaration.Declaration,
493
340
  source: string
494
- ): Readonly<Record<string, unknown>> => {
495
- const select: Record<string, unknown> = Object.create(null)
496
- for (let branchIndex = 0; branchIndex < branches.length; branchIndex++) {
497
- const branch = branches[branchIndex]!
498
- select[branch.key] = wrapSelectedBranchBuilder(
499
- getSelectionBuilder(context.target, branch.selection, stateNodes, source),
500
- owner,
501
- branchIndex,
502
- branch.key,
503
- branch.selection.updatePath === undefined
504
- ? undefined
505
- : getSelectionBuilder(
506
- context.target,
507
- makeStateUpdateSelection(branch.selection.updatePath, "branch"),
508
- stateNodes,
509
- source
510
- ) as Record<string, (value: unknown) => unknown>
341
+ ): Readonly<Record<string, unknown>> =>
342
+ Object.freeze(Object.fromEntries(
343
+ branches.map((branch, index) => [branch.key, (config?: unknown) =>
344
+ Topology.makeSelectedBranch(
345
+ owner,
346
+ index,
347
+ branch.key,
348
+ branch.selection.kind === "none"
349
+ ? Topology.makeNoTarget()
350
+ : constructBranch(branch.selection, stateNodes, declaration, config, source)
351
+ )]
511
352
  )
512
- }
513
- return Object.freeze(select)
514
- }
353
+ ))
515
354
 
516
355
  const validateSelectedBranchResult = (
517
356
  result: unknown,
@@ -547,7 +386,7 @@ const normalizeObjectTransition = (
547
386
  const allowed = [
548
387
  "target",
549
388
  "update",
550
- "initial",
389
+ "input",
551
390
  "history",
552
391
  "none",
553
392
  "branches",
@@ -586,7 +425,7 @@ const normalizeObjectTransition = (
586
425
  throw new Error("Machine branching transition requires a registered group and resolver")
587
426
  }
588
427
  if (
589
- ["target", "update", "initial", "history", "none", "data", "decoded"].some((key) => config[key] !== undefined)
428
+ ["target", "update", "input", "history", "none", "data", "decoded"].some((key) => config[key] !== undefined)
590
429
  ) throw new Error("Machine branching transition cannot redeclare its destination")
591
430
  const entries = Object.fromEntries(
592
431
  Object.entries(group).map(([key, spec]) => [key, {
@@ -613,21 +452,41 @@ const normalizeObjectTransition = (
613
452
  if (resolve !== undefined && selection.kind !== "none") {
614
453
  throw new Error("Machine advanced construction requires a declared branch group")
615
454
  }
616
- const method = hasData ? config.decoded === true ? "decoded" : "from" : undefined
455
+ const input = config.input
456
+ const constructInput = typeof input === "function" ? input : () => input
457
+ if (selection.path !== "" && Object.hasOwn(config, "input")) {
458
+ throw new Error("Machine input belongs only to root targets")
459
+ }
460
+ if (selection.path === "" && selection.kind !== "update" && (hasData || config.decoded !== undefined)) {
461
+ throw new Error("Machine root targets accept input instead of data")
462
+ }
617
463
  return {
618
464
  target: () => selection,
619
465
  reenter: config.reenter,
620
466
  declinable,
621
- ...(!guarded && method === undefined && resolve === undefined ? {} : {
622
- resolve: (context: Record<string, any>, enqueue: unknown) => {
623
- if (guarded && !guard(context)) return Topology.makeDeclined()
624
- if (method !== undefined && construct !== undefined) {
625
- return constructSelectionValue(selection, context, method, construct(context))
626
- }
627
- if (resolve !== undefined) return resolve(context, enqueue)
628
- return selection.kind === "none" ? undefined : constructSelectedTarget(context.target)
467
+ resolve: (context: Record<string, any>, enqueue: unknown) => {
468
+ if (guarded && !guard(context)) return Topology.makeDeclined()
469
+ if (resolve !== undefined) return resolve(context, enqueue)
470
+ if (selection.path === "" && selection.kind !== "update") {
471
+ return constructBranch(selection, stateNodes, declaration, { input: constructInput(context) })
629
472
  }
630
- })
473
+ const value = construct(context)
474
+ return constructBranch(
475
+ selection,
476
+ stateNodes,
477
+ declaration,
478
+ selection.updatePath === undefined
479
+ ? {
480
+ ...(hasData ? { data: value } : {}),
481
+ ...(config.decoded === undefined ? {} : { decoded: config.decoded })
482
+ }
483
+ : {
484
+ ...(value.target === undefined ? {} : { data: value.target, decoded: config.decoded }),
485
+ update: { data: value.update, decoded: config.decoded }
486
+ },
487
+ path
488
+ )
489
+ }
631
490
  }
632
491
  }
633
492
 
@@ -662,7 +521,7 @@ const captureTransition = (
662
521
  decline: Topology.makeDeclined
663
522
  }
664
523
  delete resolverContext.target
665
- resolverContext.select = makeBranchSelectors(context, branches, owner, stateNodes, path)
524
+ resolverContext.select = makeBranchSelectors(branches, owner, stateNodes, declaration, path)
666
525
  const selected = resolve(resolverContext, enqueue)
667
526
  if (Topology.isDeclined(selected)) {
668
527
  if (!declinable) {
@@ -863,14 +722,19 @@ const makeHandle = (self: Definition.Any, declaration: Declaration.Declaration):
863
722
  const constructRoot = compiled.stateNodes.byPath.get("").schema === undefined
864
723
  ? () => undefined
865
724
  : InitialDeclaration.construction(config.root)
866
- compiled.initial = (input: unknown) => Topology.makeInitialTarget("", constructRoot({ input }))
725
+ compiled.initial = (input: unknown) => ({
726
+ ...Topology.makeInitialTarget("", constructRoot({ input })),
727
+ input: { value: input }
728
+ })
867
729
  compiled.initialDefinition = Object.freeze({
868
730
  target: "",
869
731
  selection: Object.freeze({ path: "", kind: "initial", scope: "initial" })
870
732
  })
871
- compiled.makeTargetBuilder = makeTargetBuilder(compiled.states, compiled.stateNodes)
872
733
  const handlers: Record<PropertyKey, CapturedStateConfig> = Object.create(null)
873
- flattenHandlers(handlers, compiled.stateNodes, compiled.states, "", declaration, { "": captured.handlers })
734
+ flattenHandlers(handlers, compiled.stateNodes, compiled.states, "", {
735
+ ...declaration,
736
+ initialize: (input) => compiled.initial(Protocol.decodeInputSync(compiled, compiled.input, input))
737
+ }, { "": captured.handlers })
874
738
  return makeWithHandlers(compiled, handlers)
875
739
  }) as Definition.Any["handle"]
876
740
 
@@ -1548,6 +1412,8 @@ export const watch = <State, Event, Error = never, Output = never>(
1548
1412
  ref: MachineRef<State, Event, Error, Output>
1549
1413
  ): Stream.Stream<RuntimeOutcome<State, Error, Output>> => internalRuntime.watch(ref)
1550
1414
 
1415
+ export const waitFor = Observation.waitFor
1416
+
1551
1417
  export const prepare = internalProcess.prepare
1552
1418
 
1553
1419
  export const start: <
@@ -0,0 +1,39 @@
1
+ /** Observation of current and subsequent published runtime snapshots. */
2
+ import * as Cause from "effect/Cause"
3
+ import * as Effect from "effect/Effect"
4
+ import { dual } from "effect/Function"
5
+ import * as Option from "effect/Option"
6
+ import * as Stream from "effect/Stream"
7
+ import type * as Machine from "../../Machine.js"
8
+ import { StoppedError } from "./errors.js"
9
+
10
+ export const waitFor: typeof Machine.waitFor = dual(2, <State, Event, Error, Output, Emitted>(
11
+ ref: Machine.MachineRef<State, Event, Error, Output, Emitted>,
12
+ predicate: (snapshot: Machine.RuntimeSnapshot<State, Error, Output>) => boolean
13
+ ): Effect.Effect<Machine.RuntimeSnapshot<State, Error, Output>, Error | StoppedError | Cause.NoSuchElementError> =>
14
+ Effect.suspend(() => {
15
+ let result = Option.none<Machine.RuntimeSnapshot<State, Error, Output>>()
16
+ const absent = () => new Cause.NoSuchElementError(`Machine "${ref.id}" ended without a matching snapshot`)
17
+ return Stream.runForEachWhile(
18
+ ref.changes,
19
+ (snapshot) =>
20
+ Effect.suspend((): Effect.Effect<boolean, Error | StoppedError | Cause.NoSuchElementError> => {
21
+ if (predicate(snapshot)) {
22
+ result = Option.some(snapshot)
23
+ return Effect.succeed(false)
24
+ }
25
+ switch (snapshot.status) {
26
+ case "active":
27
+ return Effect.succeed(true)
28
+ case "error":
29
+ return Effect.failCause(snapshot.cause)
30
+ case "stopped":
31
+ return Effect.fail(new StoppedError())
32
+ case "done":
33
+ return Effect.fail(absent())
34
+ }
35
+ })
36
+ ).pipe(
37
+ Effect.flatMap(() => Option.isSome(result) ? Effect.succeed(result.value) : Effect.fail(absent()))
38
+ )
39
+ }))