@typeonce/effect-machine 0.33.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +272 -628
  2. package/dist/Machine.d.ts +1076 -896
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +141 -90
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/childRegistry.d.ts +1 -1
  7. package/dist/internal/machine/childRegistry.d.ts.map +1 -1
  8. package/dist/internal/machine/cluster.d.ts +2 -50
  9. package/dist/internal/machine/cluster.d.ts.map +1 -1
  10. package/dist/internal/machine/cluster.js +4 -27
  11. package/dist/internal/machine/cluster.js.map +1 -1
  12. package/dist/internal/machine/clusterProtocol.d.ts +35 -0
  13. package/dist/internal/machine/clusterProtocol.d.ts.map +1 -0
  14. package/dist/internal/machine/clusterProtocol.js +28 -0
  15. package/dist/internal/machine/clusterProtocol.js.map +1 -0
  16. package/dist/internal/machine/commandRuntime.d.ts +1 -1
  17. package/dist/internal/machine/commandRuntime.d.ts.map +1 -1
  18. package/dist/internal/machine/configuration.d.ts +2 -2
  19. package/dist/internal/machine/configuration.d.ts.map +1 -1
  20. package/dist/internal/machine/configuration.js +38 -64
  21. package/dist/internal/machine/configuration.js.map +1 -1
  22. package/dist/internal/machine/declaration.d.ts +17 -0
  23. package/dist/internal/machine/declaration.d.ts.map +1 -0
  24. package/dist/internal/machine/declaration.js +120 -0
  25. package/dist/internal/machine/declaration.js.map +1 -0
  26. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  27. package/dist/internal/machine/executionPlan.js +15 -22
  28. package/dist/internal/machine/executionPlan.js.map +1 -1
  29. package/dist/internal/machine/implementation.d.ts +34 -0
  30. package/dist/internal/machine/implementation.d.ts.map +1 -0
  31. package/dist/internal/machine/implementation.js +3 -0
  32. package/dist/internal/machine/implementation.js.map +1 -0
  33. package/dist/internal/machine/initialDeclaration.d.ts +14 -0
  34. package/dist/internal/machine/initialDeclaration.d.ts.map +1 -0
  35. package/dist/internal/machine/initialDeclaration.js +137 -0
  36. package/dist/internal/machine/initialDeclaration.js.map +1 -0
  37. package/dist/internal/machine/invocation.d.ts +1 -1
  38. package/dist/internal/machine/invocation.d.ts.map +1 -1
  39. package/dist/internal/machine/invocation.js +1 -1
  40. package/dist/internal/machine/invocation.js.map +1 -1
  41. package/dist/internal/machine/invocationDefinition.d.ts +1 -1
  42. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  43. package/dist/internal/machine/machine.d.ts +13 -4
  44. package/dist/internal/machine/machine.d.ts.map +1 -1
  45. package/dist/internal/machine/machine.js +169 -388
  46. package/dist/internal/machine/machine.js.map +1 -1
  47. package/dist/internal/machine/planner.d.ts +8 -0
  48. package/dist/internal/machine/planner.d.ts.map +1 -1
  49. package/dist/internal/machine/planner.js +37 -78
  50. package/dist/internal/machine/planner.js.map +1 -1
  51. package/dist/internal/machine/process.d.ts +8 -7
  52. package/dist/internal/machine/process.d.ts.map +1 -1
  53. package/dist/internal/machine/process.js +16 -12
  54. package/dist/internal/machine/process.js.map +1 -1
  55. package/dist/internal/machine/protocol.d.ts +1 -1
  56. package/dist/internal/machine/protocol.d.ts.map +1 -1
  57. package/dist/internal/machine/protocol.js.map +1 -1
  58. package/dist/internal/machine/runtime.d.ts +2 -230
  59. package/dist/internal/machine/runtime.d.ts.map +1 -1
  60. package/dist/internal/machine/runtime.js +8 -1857
  61. package/dist/internal/machine/runtime.js.map +1 -1
  62. package/dist/internal/machine/runtimeCompiled.d.ts +5 -0
  63. package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -0
  64. package/dist/internal/machine/runtimeCompiled.js +867 -0
  65. package/dist/internal/machine/runtimeCompiled.js.map +1 -0
  66. package/dist/internal/machine/runtimeGeneric.d.ts +3 -0
  67. package/dist/internal/machine/runtimeGeneric.d.ts.map +1 -0
  68. package/dist/internal/machine/runtimeGeneric.js +471 -0
  69. package/dist/internal/machine/runtimeGeneric.js.map +1 -0
  70. package/dist/internal/machine/runtimeProtocol.d.ts +312 -0
  71. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -0
  72. package/dist/internal/machine/runtimeProtocol.js +561 -0
  73. package/dist/internal/machine/runtimeProtocol.js.map +1 -0
  74. package/dist/internal/machine/stateDefinition.d.ts +1 -1
  75. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  76. package/dist/internal/machine/stateDefinition.js +1 -13
  77. package/dist/internal/machine/stateDefinition.js.map +1 -1
  78. package/dist/internal/machine/targetReference.d.ts +15 -0
  79. package/dist/internal/machine/targetReference.d.ts.map +1 -0
  80. package/dist/internal/machine/targetReference.js +41 -0
  81. package/dist/internal/machine/targetReference.js.map +1 -0
  82. package/dist/internal/machine/topology.d.ts.map +1 -1
  83. package/dist/internal/machine/topology.js +5 -3
  84. package/dist/internal/machine/topology.js.map +1 -1
  85. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  86. package/dist/internal/testing/machine/finiteModel.js +53 -46
  87. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  88. package/dist/internal/testing/machine/probe.js +1 -1
  89. package/dist/internal/testing/machine/probe.js.map +1 -1
  90. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  91. package/dist/internal/testing/machine/verification.js +7 -1
  92. package/dist/internal/testing/machine/verification.js.map +1 -1
  93. package/dist/testing/MachineTest.d.ts +105 -73
  94. package/dist/testing/MachineTest.d.ts.map +1 -1
  95. package/dist/testing/MachineTest.js +105 -73
  96. package/dist/testing/MachineTest.js.map +1 -1
  97. package/dist/unstable/cluster/ClusterMachine.d.ts +18 -13
  98. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  99. package/dist/unstable/cluster/ClusterMachine.js +18 -25
  100. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  101. package/dist/unstable/reactivity/AtomMachine.d.ts +41 -24
  102. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  103. package/dist/unstable/reactivity/AtomMachine.js +41 -24
  104. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  105. package/docs/agent-guide.md +66 -91
  106. package/docs/machine-review.md +19 -49
  107. package/docs/root-api.md +62 -62
  108. package/package.json +1 -1
  109. package/src/Machine.ts +1836 -2907
  110. package/src/internal/machine/childRegistry.ts +1 -1
  111. package/src/internal/machine/cluster.ts +7 -73
  112. package/src/internal/machine/clusterProtocol.ts +56 -0
  113. package/src/internal/machine/commandRuntime.ts +1 -1
  114. package/src/internal/machine/configuration.ts +53 -65
  115. package/src/internal/machine/declaration.ts +140 -0
  116. package/src/internal/machine/executionPlan.ts +16 -22
  117. package/src/internal/machine/implementation.ts +41 -0
  118. package/src/internal/machine/initialDeclaration.ts +157 -0
  119. package/src/internal/machine/invocation.ts +3 -3
  120. package/src/internal/machine/invocationDefinition.ts +1 -1
  121. package/src/internal/machine/machine.ts +225 -576
  122. package/src/internal/machine/planner.ts +84 -118
  123. package/src/internal/machine/process.ts +40 -33
  124. package/src/internal/machine/protocol.ts +3 -3
  125. package/src/internal/machine/runtime.ts +20 -3037
  126. package/src/internal/machine/runtimeCompiled.ts +1166 -0
  127. package/src/internal/machine/runtimeGeneric.ts +799 -0
  128. package/src/internal/machine/runtimeProtocol.ts +1213 -0
  129. package/src/internal/machine/stateDefinition.ts +1 -15
  130. package/src/internal/machine/targetReference.ts +55 -0
  131. package/src/internal/machine/topology.ts +5 -3
  132. package/src/internal/testing/machine/finiteModel.ts +58 -53
  133. package/src/internal/testing/machine/probe.ts +1 -1
  134. package/src/internal/testing/machine/verification.ts +7 -1
  135. package/src/testing/MachineTest.ts +105 -73
  136. package/src/unstable/cluster/ClusterMachine.ts +22 -25
  137. package/src/unstable/reactivity/AtomMachine.ts +41 -24
@@ -3,7 +3,7 @@ import * as Deferred from "effect/Deferred"
3
3
  import * as Effect from "effect/Effect"
4
4
  import * as Option from "effect/Option"
5
5
  import type * as Scope from "effect/Scope"
6
- import type { MachineRef } from "./runtime.js"
6
+ import type { MachineRef } from "./runtimeProtocol.js"
7
7
 
8
8
  export type ChildDescriptor = {
9
9
  readonly id: string
@@ -4,92 +4,26 @@
4
4
  * @since 0.4.0
5
5
  */
6
6
  import * as Cause from "effect/Cause"
7
- import * as Context from "effect/Context"
8
7
  import * as Effect from "effect/Effect"
9
8
  import * as Layer from "effect/Layer"
10
9
  import * as Option from "effect/Option"
11
10
  import * as Schema from "effect/Schema"
12
- import { ClusterError, ClusterSchema, Entity, EntityAddress, MessageStorage, Snowflake } from "effect/unstable/cluster"
11
+ import { ClusterSchema, Entity, MessageStorage } from "effect/unstable/cluster"
12
+ import type { EntityAddress, Snowflake } from "effect/unstable/cluster"
13
13
  import { Rpc } from "effect/unstable/rpc"
14
14
  import type * as Machine from "../../Machine.js"
15
- import type { Checkpoint, ClusterMachine, LoadResult } from "../../unstable/cluster/ClusterMachine.js"
15
+ import type { Checkpoint } from "../../unstable/cluster/ClusterMachine.js"
16
+ import type { ClusterMachine } from "../../unstable/cluster/ClusterMachine.js"
17
+ import { Accepted, CommitResult, Rejected, type RejectionReason, SendResult, Storage } from "./clusterProtocol.js"
18
+ import { toImpl } from "./implementation.js"
16
19
  import * as internalMachine from "./machine.js"
17
20
  import * as Protocol from "./protocol.js"
18
21
  import type { EnsureExecutable } from "./readiness.js"
19
22
  import type { ExcludeCompatibleRuntime } from "./requirements.js"
20
23
 
21
24
  type EntityAddress = EntityAddress.EntityAddress
22
- type PersistenceError = ClusterError.PersistenceError
23
25
  type Snowflake = Snowflake.Snowflake
24
26
 
25
- export type CommitResult = CommitResult.Committed | CommitResult.Duplicate
26
-
27
- export const CommitResult = {
28
- Committed: (): CommitResult.Committed => ({ _tag: "Committed" }),
29
- Duplicate: (): CommitResult.Duplicate => ({ _tag: "Duplicate" })
30
- }
31
-
32
- export declare namespace CommitResult {
33
- /**
34
- * Indicates that the request id and checkpoint were committed atomically.
35
- *
36
- * @category models
37
- * @since 0.4.0
38
- */
39
- export interface Committed {
40
- readonly _tag: "Committed"
41
- }
42
-
43
- /**
44
- * Indicates that the request id was already committed.
45
- *
46
- * @category models
47
- * @since 0.4.0
48
- */
49
- export interface Duplicate {
50
- readonly _tag: "Duplicate"
51
- }
52
- }
53
-
54
- export class Storage extends Context.Service<Storage, {
55
- readonly load: (
56
- address: EntityAddress,
57
- requestId: Snowflake
58
- ) => Effect.Effect<LoadResult, PersistenceError>
59
- readonly commit: (
60
- address: EntityAddress,
61
- checkpoint: Checkpoint
62
- ) => Effect.Effect<CommitResult, PersistenceError>
63
- }>()("effect/cluster/ClusterMachine/Storage") {}
64
-
65
- export class Accepted extends Schema.TaggedClass<Accepted>("effect/cluster/ClusterMachine/Accepted")(
66
- "Accepted",
67
- {}
68
- ) {}
69
-
70
- export const RejectionReason = Schema.Literals([
71
- "MachineIdMismatch",
72
- "VersionMismatch",
73
- "InvalidCheckpoint",
74
- "UnsupportedProcessLocal",
75
- "TransitionFailure",
76
- "SnapshotEncodeFailure",
77
- "PersistenceFailure",
78
- "EmissionFailure"
79
- ])
80
-
81
- export type RejectionReason = typeof RejectionReason.Type
82
-
83
- export class Rejected extends Schema.TaggedClass<Rejected>("effect/cluster/ClusterMachine/Rejected")(
84
- "Rejected",
85
- {
86
- reason: RejectionReason,
87
- message: Schema.String
88
- }
89
- ) {}
90
-
91
- export const SendResult = Schema.Union([Accepted, Rejected])
92
-
93
27
  type SendRpc<Events extends ReadonlyArray<Machine.Machine.TaggedSchema>> = Rpc.Rpc<
94
28
  "send",
95
29
  Schema.Union<Events>,
@@ -101,7 +35,7 @@ type MachineEvents<M extends Machine.Machine.Any> = Machine.Machine.InputEvents<
101
35
  type MachineEmits<M extends Machine.Machine.Any> = Machine.Machine.EmittedEvents<M>
102
36
 
103
37
  const hasInvokes = (machine: Machine.Machine.Any): boolean =>
104
- Reflect.ownKeys(machine.handlers).some((key) => machine.handlers[key as string]?.invoke !== undefined)
38
+ Reflect.ownKeys(toImpl(machine).handlers).some((key) => toImpl(machine).handlers[key as string]?.invoke !== undefined)
105
39
 
106
40
  const reject = (reason: RejectionReason, message: string): Rejected => new Rejected({ reason, message })
107
41
 
@@ -0,0 +1,56 @@
1
+ /** Canonical checkpoint service and wire schemas for the Cluster adapter. */
2
+ import * as Context from "effect/Context"
3
+ import type * as Effect from "effect/Effect"
4
+ import * as Schema from "effect/Schema"
5
+ import type { ClusterError, EntityAddress, Snowflake } from "effect/unstable/cluster"
6
+ import type * as Public from "../../unstable/cluster/ClusterMachine.js"
7
+ import type { Checkpoint, LoadResult } from "../../unstable/cluster/ClusterMachine.js"
8
+ type EntityAddress = EntityAddress.EntityAddress
9
+ type PersistenceError = ClusterError.PersistenceError
10
+ type Snowflake = Snowflake.Snowflake
11
+
12
+ export type CommitResult = Public.CommitResult
13
+
14
+ export const CommitResult = {
15
+ Committed: (): Public.CommitResult.Committed => ({ _tag: "Committed" }),
16
+ Duplicate: (): Public.CommitResult.Duplicate => ({ _tag: "Duplicate" })
17
+ }
18
+
19
+ export class Storage extends Context.Service<Storage, {
20
+ readonly load: (
21
+ address: EntityAddress,
22
+ requestId: Snowflake
23
+ ) => Effect.Effect<LoadResult, PersistenceError>
24
+ readonly commit: (
25
+ address: EntityAddress,
26
+ checkpoint: Checkpoint
27
+ ) => Effect.Effect<CommitResult, PersistenceError>
28
+ }>()("effect/cluster/ClusterMachine/Storage") {}
29
+
30
+ export class Accepted extends Schema.TaggedClass<Accepted>("effect/cluster/ClusterMachine/Accepted")(
31
+ "Accepted",
32
+ {}
33
+ ) {}
34
+
35
+ export const RejectionReason = Schema.Literals([
36
+ "MachineIdMismatch",
37
+ "VersionMismatch",
38
+ "InvalidCheckpoint",
39
+ "UnsupportedProcessLocal",
40
+ "TransitionFailure",
41
+ "SnapshotEncodeFailure",
42
+ "PersistenceFailure",
43
+ "EmissionFailure"
44
+ ])
45
+
46
+ export type RejectionReason = typeof RejectionReason.Type
47
+
48
+ export class Rejected extends Schema.TaggedClass<Rejected>("effect/cluster/ClusterMachine/Rejected")(
49
+ "Rejected",
50
+ {
51
+ reason: RejectionReason,
52
+ message: Schema.String
53
+ }
54
+ ) {}
55
+
56
+ export const SendResult = Schema.Union([Accepted, Rejected])
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect"
8
8
  import type { Machine, Runtime } from "../../Machine.js"
9
9
  import type { RuntimeCommand } from "./command.js"
10
10
  import { decodeEmit, decodeEvent } from "./protocol.js"
11
- import type { ProcessScope } from "./runtime.js"
11
+ import type { ProcessScope } from "./runtimeProtocol.js"
12
12
 
13
13
  export const makeLiveRuntime = <Events, Emits>(
14
14
  machine: Machine.Any,
@@ -10,6 +10,7 @@ import * as Option from "effect/Option"
10
10
  import { hasProperty } from "effect/Predicate"
11
11
  import type { Machine, MachineTarget } from "../../Machine.js"
12
12
  import { MachineSchemaDecodeError } from "./errors.js"
13
+ import { type CapturedStateConfig, toImpl } from "./implementation.js"
13
14
  import {
14
15
  decodeBoundary,
15
16
  decodeOutputValue,
@@ -485,6 +486,51 @@ export const snapshotFromConfigurationAtPath = <const States extends Machine.Sta
485
486
  return snapshot
486
487
  }
487
488
 
489
+ /** Shared structural checks preserve the same traversal and failure order for
490
+ * synchronous planning and effectful codecs. Decoding stays in each caller. */
491
+ const compoundSnapshotChild = (
492
+ machine: Machine.Any,
493
+ node: Machine.StateNode,
494
+ current: Machine.AtomicSnapshot<string, unknown>
495
+ ): Machine.AtomicSnapshot<string, unknown> => {
496
+ if (!hasProperty(current, "state") || !isSnapshot(current.state)) {
497
+ throw new Error(`Machine expected compound snapshot "${node.path}" to include an active child state`)
498
+ }
499
+ const child = getNode(machine, String(current.state.path))
500
+ if (child.parent !== node.path) {
501
+ throw new Error(`Machine expected snapshot "${child.path}" to be a child of "${node.path}"`)
502
+ }
503
+ return current.state
504
+ }
505
+
506
+ const parallelSnapshotRegions = (
507
+ node: Machine.StateNode,
508
+ current: Machine.AtomicSnapshot<string, unknown>
509
+ ): Readonly<Record<string, unknown>> => {
510
+ if (!hasProperty(current, "states") || typeof current.states !== "object" || current.states === null) {
511
+ throw new Error(`Machine expected parallel snapshot "${node.path}" to include active child regions`)
512
+ }
513
+ return current.states as Readonly<Record<string, unknown>>
514
+ }
515
+
516
+ const parallelSnapshotChild = (
517
+ machine: Machine.Any,
518
+ node: Machine.StateNode,
519
+ childPath: string,
520
+ states: Readonly<Record<string, unknown>>
521
+ ): Machine.AtomicSnapshot<string, unknown> => {
522
+ const child = getNode(machine, childPath)
523
+ const childSnapshot = states[child.key]
524
+ if (!hasOwn(states, child.key) || !isSnapshot(childSnapshot)) {
525
+ throw new Error(`Machine expected parallel snapshot "${node.path}" to include region "${child.key}"`)
526
+ }
527
+ const snapshotChild = getNode(machine, String(childSnapshot.path))
528
+ if (snapshotChild.path !== child.path) {
529
+ throw new Error(`Machine expected snapshot "${snapshotChild.path}" to be region "${child.path}"`)
530
+ }
531
+ return childSnapshot
532
+ }
533
+
488
534
  export const configurationFromSnapshot = (
489
535
  machine: Machine.Any,
490
536
  snapshot: Machine.AtomicSnapshot<string, unknown>
@@ -504,31 +550,12 @@ export const configurationFromSnapshot = (
504
550
  values.set(node.path, decodeStateValueSync(machine, node, current.value))
505
551
  }
506
552
  if (node.type === "compound") {
507
- if (!hasProperty(current, "state") || !isSnapshot(current.state)) {
508
- throw new Error(`Machine expected compound snapshot "${node.path}" to include an active child state`)
509
- }
510
- const child = getNode(machine, String(current.state.path))
511
- if (child.parent !== node.path) {
512
- throw new Error(`Machine expected snapshot "${child.path}" to be a child of "${node.path}"`)
513
- }
514
- visit(current.state)
553
+ visit(compoundSnapshotChild(machine, node, current))
515
554
  }
516
555
  if (node.type === "parallel") {
517
- if (!hasProperty(current, "states") || typeof current.states !== "object" || current.states === null) {
518
- throw new Error(`Machine expected parallel snapshot "${node.path}" to include active child regions`)
519
- }
520
- const states = current.states as Readonly<Record<string, unknown>>
556
+ const states = parallelSnapshotRegions(node, current)
521
557
  for (const childPath of node.children) {
522
- const child = getNode(machine, childPath)
523
- const childSnapshot = states[child.key]
524
- if (!hasOwn(states, child.key) || !isSnapshot(childSnapshot)) {
525
- throw new Error(`Machine expected parallel snapshot "${node.path}" to include region "${child.key}"`)
526
- }
527
- const snapshotChild = getNode(machine, String(childSnapshot.path))
528
- if (snapshotChild.path !== child.path) {
529
- throw new Error(`Machine expected snapshot "${snapshotChild.path}" to be region "${child.path}"`)
530
- }
531
- visit(childSnapshot)
558
+ visit(parallelSnapshotChild(machine, node, childPath, states))
532
559
  }
533
560
  }
534
561
  }
@@ -591,31 +618,12 @@ export const configurationFromSnapshotEffect = Effect.fnUntraced(function*(
591
618
  values.set(node.path, yield* decodeStateValue(machine, node, current.value))
592
619
  }
593
620
  if (node.type === "compound") {
594
- if (!hasProperty(current, "state") || !isSnapshot(current.state)) {
595
- throw new Error(`Machine expected compound snapshot "${node.path}" to include an active child state`)
596
- }
597
- const child = getNode(machine, String(current.state.path))
598
- if (child.parent !== node.path) {
599
- throw new Error(`Machine expected snapshot "${child.path}" to be a child of "${node.path}"`)
600
- }
601
- yield* visit(current.state)
621
+ yield* visit(compoundSnapshotChild(machine, node, current))
602
622
  }
603
623
  if (node.type === "parallel") {
604
- if (!hasProperty(current, "states") || typeof current.states !== "object" || current.states === null) {
605
- throw new Error(`Machine expected parallel snapshot "${node.path}" to include active child regions`)
606
- }
607
- const states = current.states as Readonly<Record<string, unknown>>
624
+ const states = parallelSnapshotRegions(node, current)
608
625
  for (const childPath of node.children) {
609
- const child = getNode(machine, childPath)
610
- const childSnapshot = states[child.key]
611
- if (!hasOwn(states, child.key) || !isSnapshot(childSnapshot)) {
612
- throw new Error(`Machine expected parallel snapshot "${node.path}" to include region "${child.key}"`)
613
- }
614
- const snapshotChild = getNode(machine, String(childSnapshot.path))
615
- if (snapshotChild.path !== child.path) {
616
- throw new Error(`Machine expected snapshot "${snapshotChild.path}" to be region "${child.path}"`)
617
- }
618
- yield* visit(childSnapshot)
626
+ yield* visit(parallelSnapshotChild(machine, node, childPath, states))
619
627
  }
620
628
  }
621
629
  })
@@ -664,26 +672,6 @@ export const normalizeConfigurationEffect = <const States extends Machine.StateS
664
672
  })
665
673
  )
666
674
 
667
- export const validateInitialConfiguration = (machine: Machine.Any, configuration: ActiveConfiguration): void => {
668
- for (const path of configuration.active) {
669
- const node = getNode(machine, path)
670
- if (node.type === "compound") {
671
- const child = node.children.find((child) => configuration.active.has(child))
672
- const initialNode = node.initial === undefined ? undefined : getNode(machine, node.initial)
673
- if (initialNode?.type === "choice" ? child === undefined : child !== node.initial) {
674
- throw new Error(`Machine initial state "${node.path}" must enter initial child "${node.initial}"`)
675
- }
676
- }
677
- if (node.type === "parallel") {
678
- for (const child of node.children) {
679
- if (!configuration.active.has(child)) {
680
- throw new Error(`Machine initial state "${node.path}" must enter child region "${child}"`)
681
- }
682
- }
683
- }
684
- }
685
- }
686
-
687
675
  /** Capture every history register whose owning parent exits in this microstep.
688
676
  * The control record is deliberately independent from effects/actions: it is
689
677
  * part of the logical snapshot and is therefore preserved by pure planning. */
@@ -1140,7 +1128,7 @@ export const normalizeTargetConfigurationSync = <const States extends Machine.St
1140
1128
  export const getStateConfigByPath = (
1141
1129
  machine: Machine.Any,
1142
1130
  path: string
1143
- ): Machine.AnyStateConfig | undefined => machine.handlers[path]
1131
+ ): CapturedStateConfig | undefined => toImpl(machine).handlers[path]
1144
1132
 
1145
1133
  export const getActiveChildPath = (
1146
1134
  machine: Machine.Any,
@@ -0,0 +1,140 @@
1
+ /** Captures reusable sources and topology declarations before handler compilation. */
2
+ import * as Effect from "effect/Effect"
3
+ import { hasProperty } from "effect/Predicate"
4
+ import * as Stream from "effect/Stream"
5
+ import type { Machine, State } from "../../Machine.js"
6
+ import * as Reference from "./targetReference.js"
7
+ import * as Topology from "./topology.js"
8
+
9
+ type SourceKind = "effects" | "streams" | "timers" | "logic" | "children"
10
+ interface Source {
11
+ readonly kind: SourceKind
12
+ readonly value: unknown
13
+ }
14
+ export interface Declaration {
15
+ readonly root: State<Machine.StateNodeConfig>
16
+ readonly sources: ReadonlyMap<string, Source>
17
+ readonly branches: ReadonlyMap<string, Readonly<Record<string, Readonly<Record<string, unknown>>>>>
18
+ }
19
+ const record = (value: unknown, message: string): Record<string, unknown> => {
20
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(message)
21
+ return value as Record<string, unknown>
22
+ }
23
+ export const capture = (
24
+ root: State<Machine.StateNodeConfig>,
25
+ config: Readonly<Record<string, unknown>>
26
+ ): Declaration => {
27
+ const sources = new Map<string, Source>()
28
+ for (const kind of ["effects", "streams", "timers", "logic", "children"] as const) {
29
+ if (config[kind] === undefined) continue
30
+ for (const [name, value] of Object.entries(record(config[kind], `Machine ${kind} must be a source map`))) {
31
+ if (sources.has(name)) throw new Error(`Machine source name "${name}" is registered more than once`)
32
+ sources.set(name, Object.freeze({ kind, value }))
33
+ }
34
+ }
35
+ const branches = new Map<string, Readonly<Record<string, Readonly<Record<string, unknown>>>>>()
36
+ if (config.branches !== undefined) {
37
+ for (const [name, group] of Object.entries(record(config.branches, "Machine branches must be a map"))) {
38
+ const branchRecord = record(group, `Machine branches "${name}" must be a branch record`)
39
+ for (const key of Reflect.ownKeys(branchRecord)) {
40
+ if (typeof key !== "string") throw new Error("Machine branches cannot use symbol keys")
41
+ if (key.length === 0 || String(Number(key)) === key) {
42
+ throw new Error("Machine branches require non-index string branch keys")
43
+ }
44
+ }
45
+ const entries = Object.entries(branchRecord)
46
+ if (entries.length === 0) throw new Error(`Machine branches "${name}" requires a branch`)
47
+ branches.set(
48
+ name,
49
+ Object.freeze(Object.fromEntries(entries.map(([key, value]) => {
50
+ const spec = { ...record(value, `Machine branch "${name}.${key}" must be a declaration`) }
51
+ for (const field of Reflect.ownKeys(spec)) {
52
+ if (
53
+ typeof field !== "string" || !["target", "update", "initial", "history", "none", "title"].includes(field)
54
+ ) {
55
+ throw new Error(`Machine branch "${name}.${key}" contains an unknown declaration field`)
56
+ }
57
+ }
58
+ if (spec.title !== undefined && (typeof spec.title !== "string" || spec.title.length === 0)) {
59
+ throw new Error("Machine branch title must be a non-empty string")
60
+ }
61
+ selection({ root, sources, branches }, spec)
62
+ return [key, Object.freeze(spec)]
63
+ })))
64
+ )
65
+ }
66
+ }
67
+ return { root, sources, branches }
68
+ }
69
+ const reference = (value: unknown, root: Declaration["root"]): Reference.Reference[typeof Reference.TypeId] => {
70
+ if (!hasProperty(value, Reference.TypeId)) throw new Error("Machine target must be a declared state reference")
71
+ const ref = (value as Reference.Reference)[Reference.TypeId]
72
+ if (ref.root !== root) throw new Error("Machine target reference belongs to a different root descriptor")
73
+ return ref
74
+ }
75
+ export const selection = (
76
+ declaration: Declaration,
77
+ config: Readonly<Record<string, unknown>>
78
+ ): Topology.TargetSelection => {
79
+ const keys = ["target", "initial", "history", "none"].filter((key) => config[key] !== undefined)
80
+ if (keys.length === 0 && config.update !== undefined) {
81
+ const owner = reference(config.update, declaration.root)
82
+ if (owner.kind !== "state") throw new Error("Machine update requires an active state reference")
83
+ return Topology.makeTargetSelection("update", owner.path, "branch")
84
+ }
85
+ if (keys.length !== 1) throw new Error("Machine transition must declare exactly one destination operation")
86
+ const key = keys[0]!
87
+ if (key === "none") {
88
+ if (config.none !== true || config.update !== undefined) {
89
+ throw new Error("Machine targetless transition requires none: true")
90
+ }
91
+ return Topology.noneTargetSelection
92
+ }
93
+ const ref = reference(config[key], declaration.root)
94
+ if (ref.path === "") throw new Error("Machine root data changes use update; transitions select a descendant")
95
+ if ((key === "history") !== (ref.kind === "history")) {
96
+ throw new Error("Machine history references require a history transition")
97
+ }
98
+ if (key === "initial" && ref.kind !== "state") {
99
+ throw new Error("Machine initial entry requires an active state reference")
100
+ }
101
+ const update = config.update === undefined ? undefined : reference(config.update, declaration.root).path
102
+ if (update !== undefined && key !== "target") throw new Error("Machine owner updates require an ordinary destination")
103
+ return Topology.makeTargetSelection(
104
+ key === "initial" ? "initial" : ref.kind,
105
+ ref.path,
106
+ key === "history" ? "full" : "branch",
107
+ update
108
+ )
109
+ }
110
+ export const invocation = (
111
+ declaration: Declaration,
112
+ value: unknown,
113
+ path: string,
114
+ adaptContext: (context: unknown) => unknown
115
+ ): Record<string, unknown> => {
116
+ const config = record(value, `Machine invocation for "${path}" must be an object`)
117
+ const source = typeof config.src === "string" ? declaration.sources.get(config.src) : undefined
118
+ if (source === undefined) throw new Error(`Machine invocation for "${path}" names an unknown source`)
119
+ const { src, input: rawInput, ...rest } = config
120
+ const input = typeof rawInput === "function" ? (context: unknown) => rawInput(adaptContext(context)) : rawInput
121
+ if (source.kind === "children") return { ...rest, child: source.value, ...(input === undefined ? {} : { input }) }
122
+ // Service classes are functions at runtime and also lazy Effect values.
123
+ // Recognize Effect/Stream protocols before treating a function as an input adapter.
124
+ const parameterized = typeof source.value === "function" &&
125
+ !(source.kind === "effects" && Effect.isEffect(source.value)) &&
126
+ !(source.kind === "streams" && Stream.isStream(source.value))
127
+ if (parameterized !== (typeof input === "function")) {
128
+ throw new Error(`Machine invocation "${src}" requires input exactly when its source takes an argument`)
129
+ }
130
+ const resolve = parameterized
131
+ ? (context: unknown) =>
132
+ (source.value as (input: unknown) => unknown)((input as (context: unknown) => unknown)(context))
133
+ : () => source.value
134
+ const field = { effects: "effect", streams: "stream", timers: "after", logic: "logic" }[source.kind]
135
+ return {
136
+ ...rest,
137
+ id: rest.id ?? src,
138
+ [field]: !parameterized && (source.kind === "timers" || source.kind === "logic") ? source.value : resolve
139
+ }
140
+ }
@@ -20,10 +20,11 @@ import {
20
20
  normalizeTargetConfigurationSync,
21
21
  type PlanningMachineReferences,
22
22
  snapshotFromConfiguration,
23
- validateInitialConfiguration,
24
23
  withMachineReferences
25
24
  } from "./configuration.js"
26
25
  import { InfiniteTransitionError, StoppedError } from "./errors.js"
26
+ import { type CapturedStateConfig, toImpl } from "./implementation.js"
27
+ import { isDataInitializer } from "./initialDeclaration.js"
27
28
  import * as InvocationEvent from "./invocationEvent.js"
28
29
  import {
29
30
  broadenTransitionBoundary,
@@ -38,6 +39,7 @@ import {
38
39
  normalizeTransition,
39
40
  planConfiguration,
40
41
  removeConflictingTransitions,
42
+ resolveInitialConfiguration,
41
43
  resolveInitialTarget,
42
44
  type SelectedTransition,
43
45
  sortEntryPaths,
@@ -114,7 +116,7 @@ const indexedStateConfigKeys: ReadonlySet<PropertyKey> = new Set([
114
116
 
115
117
  // Fail closed so a newly introduced semantic field must explicitly opt into
116
118
  // indexed execution instead of being accepted before the kernel supports it.
117
- const supportsIndexedStateConfig = (config: Machine.AnyStateConfig | undefined): boolean => {
119
+ const supportsIndexedStateConfig = (config: CapturedStateConfig | undefined): boolean => {
118
120
  if (config === undefined) {
119
121
  return true
120
122
  }
@@ -149,7 +151,7 @@ const compileIndexedExecutionDescriptor = (
149
151
  finalPaths.push(node.path)
150
152
  }
151
153
 
152
- const config = machine.handlers[node.path] as Machine.AnyStateConfig | undefined
154
+ const config = toImpl(machine).handlers[node.path] as CapturedStateConfig | undefined
153
155
  if (!supportsIndexedStateConfig(config)) {
154
156
  return undefined
155
157
  }
@@ -212,7 +214,8 @@ const compileIndexedExecutionDescriptor = (
212
214
  // the hierarchical planner so their entry and exit boundaries stay explicit.
213
215
  flat: nodes.every((node) => node.parent === undefined && (node.type === "atomic" || node.type === "final")) || (
214
216
  nodes[0]?.path === "" && nodes[0].type === "compound" && nodes[0].schema === undefined &&
215
- (machine.handlers[""] === undefined || Reflect.ownKeys(machine.handlers[""]).length === 0) &&
217
+ (toImpl(machine).handlers[""] === undefined ||
218
+ Reflect.ownKeys(toImpl(machine).handlers[""]!).every((key) => key === "initialize")) &&
216
219
  nodes.slice(1).every((node) => node.parent === "" && (node.type === "atomic" || node.type === "final")) &&
217
220
  [...transitionsByPath.values()].every((events) =>
218
221
  [...events.values()].every((transition) =>
@@ -816,7 +819,7 @@ const planIndexedFlatState = (
816
819
  }
817
820
 
818
821
  const sourcePath = descriptor.nodes[sourceIndex]!.path
819
- const transition = normalizeTransition(machine.handlers[sourcePath]?.on?.[event._tag])
822
+ const transition = normalizeTransition(toImpl(machine).handlers[sourcePath]?.on?.[event._tag])
820
823
  if (transition !== undefined) {
821
824
  const transitionResult = collectIndexedTransition(
822
825
  machine,
@@ -1129,10 +1132,10 @@ const makeIndexedExecutionPlan = (
1129
1132
  snapshot: (state) => snapshotFromIndexedState(indexed, state as OwnedIndexedState),
1130
1133
  plan: (state, event, retainMicrosteps = false, machineReferences) =>
1131
1134
  planIndexedState(machine, indexed, state as OwnedIndexedState, event, retainMicrosteps, machineReferences),
1132
- // Initializers may enqueue commands and emissions. Managed startup owns that
1133
- // work through the generic initial planner; indexed event execution remains valid.
1134
- ...(Object.values(machine.handlers as Record<string, Machine.AnyStateConfig>).some((config) =>
1135
- "initialize" in config
1135
+ // Only captured data constructors can use indexed startup. Unknown initializer
1136
+ // protocols retain generic startup so commands and emissions cannot be dropped.
1137
+ ...(Object.values(toImpl(machine).handlers as Record<string, CapturedStateConfig>).some((config) =>
1138
+ config.initialize !== undefined && !isDataInitializer(config.initialize)
1136
1139
  ) ?
1137
1140
  {} :
1138
1141
  {
@@ -1143,8 +1146,8 @@ const makeIndexedExecutionPlan = (
1143
1146
  ? (decodeInputSync(machine, machine.input, undefined), args)
1144
1147
  : [decodeInputSync(machine, machine.input, args[0])]
1145
1148
  const initial = machine.initial(...inputArgs as any)
1146
- const resolved = isInitialTarget(initial)
1147
- ? resolveInitialTarget(
1149
+ const normalized = isInitialTarget(initial)
1150
+ ? resolveInitialConfiguration(
1148
1151
  machine,
1149
1152
  {
1150
1153
  active: new Set(),
@@ -1155,20 +1158,11 @@ const makeIndexedExecutionPlan = (
1155
1158
  },
1156
1159
  initial,
1157
1160
  InitialEvent
1158
- ).target
1159
- : initial
1160
- const normalized = isInitialTarget(initial)
1161
- ? normalizeTargetConfigurationSync(machine, {
1162
- active: new Set(),
1163
- values: new Map(),
1164
- outputs: new Map(),
1165
- history: new Map()
1166
- }, resolved)
1167
- : normalizeConfigurationSync(machine, resolved as Machine.Snapshot<any>)
1161
+ ).configuration
1162
+ : normalizeConfigurationSync(machine, initial as Machine.Snapshot<any>)
1168
1163
  const active = machineReferences === undefined
1169
1164
  ? normalized
1170
1165
  : withMachineReferences(normalized, machineReferences)
1171
- if (machine.initialDefinition.selection.kind === "initial") validateInitialConfiguration(machine, active)
1172
1166
  const completed = completeConfigurationSync(machine, active, InitialEvent).configuration
1173
1167
  const configuration = ownedIndexedStateFromActive(indexed, completed)
1174
1168
  const state = snapshotFromIndexedState(indexed, configuration)
@@ -0,0 +1,41 @@
1
+ import type { Enqueue, Machine } from "../../Machine.js"
2
+ import type { InvocationDefinition } from "./invocationDefinition.js"
3
+ import type { EventTransition } from "./transition.js"
4
+
5
+ // Callback contexts are erased after the public builder checks their dependent
6
+ // state/event types. Stored transitions are evaluated callbacks, not the public
7
+ // selector factories accepted by Definition.handle.
8
+ type Transition = EventTransition<any, any, any, any>
9
+ type Action = (context: any, enqueue: Enqueue<any, any>) => undefined
10
+
11
+ export interface CapturedStateConfig {
12
+ readonly entry?: Action
13
+ readonly exit?: Action
14
+ readonly on?: Readonly<Record<PropertyKey, Transition>>
15
+ readonly always?: Transition
16
+ readonly onDone?: Transition
17
+ readonly choice?: Exclude<Transition, (...args: never[]) => unknown>
18
+ readonly invoke?: InvocationDefinition | ReadonlyArray<InvocationDefinition>
19
+ readonly initialize?: (context: any) => unknown
20
+ readonly output?: (context: any) => unknown
21
+ readonly history?: Readonly<
22
+ Record<string, {
23
+ readonly default: (context: any, enqueue: Enqueue<any, any>) => Machine.HandlerResult<any, any, any>
24
+ }>
25
+ >
26
+ }
27
+
28
+ /**
29
+ * Captured machine implementation consumed by semantic layers.
30
+ *
31
+ * The public erased view retains its existing fields for compatibility. Internal
32
+ * code enters through this view so handler lookup cannot silently produce `any`.
33
+ * Construction captures these containers before handing the machine to a planner.
34
+ */
35
+ export interface MachineInternal extends Machine.Any {
36
+ readonly handlers: Readonly<Record<string, CapturedStateConfig | undefined>>
37
+ readonly makeTargetBuilder: (source: string) => Machine.TargetBuilder<any, any>
38
+ }
39
+
40
+ /** The single conversion from an erased public machine to its captured implementation. */
41
+ export const toImpl = (machine: Machine.Any): MachineInternal => machine as MachineInternal