@typeonce/effect-machine 0.32.0 → 0.34.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 (108) hide show
  1. package/README.md +216 -635
  2. package/dist/Machine.d.ts +814 -545
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +20 -8
  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 -1
  19. package/dist/internal/machine/configuration.d.ts.map +1 -1
  20. package/dist/internal/machine/configuration.js +38 -45
  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 +5 -4
  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/invocation.d.ts +1 -1
  34. package/dist/internal/machine/invocation.d.ts.map +1 -1
  35. package/dist/internal/machine/invocation.js +1 -1
  36. package/dist/internal/machine/invocation.js.map +1 -1
  37. package/dist/internal/machine/invocationDefinition.d.ts +1 -1
  38. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  39. package/dist/internal/machine/machine.d.ts +13 -2
  40. package/dist/internal/machine/machine.d.ts.map +1 -1
  41. package/dist/internal/machine/machine.js +149 -280
  42. package/dist/internal/machine/machine.js.map +1 -1
  43. package/dist/internal/machine/planner.d.ts.map +1 -1
  44. package/dist/internal/machine/planner.js +12 -11
  45. package/dist/internal/machine/planner.js.map +1 -1
  46. package/dist/internal/machine/process.d.ts +8 -7
  47. package/dist/internal/machine/process.d.ts.map +1 -1
  48. package/dist/internal/machine/process.js +16 -12
  49. package/dist/internal/machine/process.js.map +1 -1
  50. package/dist/internal/machine/runtime.d.ts +2 -230
  51. package/dist/internal/machine/runtime.d.ts.map +1 -1
  52. package/dist/internal/machine/runtime.js +8 -1857
  53. package/dist/internal/machine/runtime.js.map +1 -1
  54. package/dist/internal/machine/runtimeCompiled.d.ts +5 -0
  55. package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -0
  56. package/dist/internal/machine/runtimeCompiled.js +867 -0
  57. package/dist/internal/machine/runtimeCompiled.js.map +1 -0
  58. package/dist/internal/machine/runtimeGeneric.d.ts +3 -0
  59. package/dist/internal/machine/runtimeGeneric.d.ts.map +1 -0
  60. package/dist/internal/machine/runtimeGeneric.js +471 -0
  61. package/dist/internal/machine/runtimeGeneric.js.map +1 -0
  62. package/dist/internal/machine/runtimeProtocol.d.ts +312 -0
  63. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -0
  64. package/dist/internal/machine/runtimeProtocol.js +561 -0
  65. package/dist/internal/machine/runtimeProtocol.js.map +1 -0
  66. package/dist/internal/machine/targetReference.d.ts +15 -0
  67. package/dist/internal/machine/targetReference.d.ts.map +1 -0
  68. package/dist/internal/machine/targetReference.js +31 -0
  69. package/dist/internal/machine/targetReference.js.map +1 -0
  70. package/dist/internal/machine/topology.d.ts.map +1 -1
  71. package/dist/internal/machine/topology.js +2 -1
  72. package/dist/internal/machine/topology.js.map +1 -1
  73. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  74. package/dist/internal/testing/machine/finiteModel.js +38 -40
  75. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  76. package/dist/internal/testing/machine/probe.js +1 -1
  77. package/dist/internal/testing/machine/probe.js.map +1 -1
  78. package/dist/unstable/cluster/ClusterMachine.d.ts +5 -5
  79. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  80. package/dist/unstable/cluster/ClusterMachine.js +5 -17
  81. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  82. package/docs/agent-guide.md +66 -91
  83. package/docs/machine-review.md +19 -49
  84. package/docs/root-api.md +68 -23
  85. package/package.json +1 -1
  86. package/src/Machine.ts +1387 -2011
  87. package/src/internal/machine/childRegistry.ts +1 -1
  88. package/src/internal/machine/cluster.ts +7 -73
  89. package/src/internal/machine/clusterProtocol.ts +56 -0
  90. package/src/internal/machine/commandRuntime.ts +1 -1
  91. package/src/internal/machine/configuration.ts +53 -45
  92. package/src/internal/machine/declaration.ts +140 -0
  93. package/src/internal/machine/executionPlan.ts +6 -5
  94. package/src/internal/machine/implementation.ts +41 -0
  95. package/src/internal/machine/invocation.ts +3 -3
  96. package/src/internal/machine/invocationDefinition.ts +1 -1
  97. package/src/internal/machine/machine.ts +210 -389
  98. package/src/internal/machine/planner.ts +54 -35
  99. package/src/internal/machine/process.ts +40 -33
  100. package/src/internal/machine/runtime.ts +20 -3037
  101. package/src/internal/machine/runtimeCompiled.ts +1166 -0
  102. package/src/internal/machine/runtimeGeneric.ts +799 -0
  103. package/src/internal/machine/runtimeProtocol.ts +1213 -0
  104. package/src/internal/machine/targetReference.ts +40 -0
  105. package/src/internal/machine/topology.ts +2 -1
  106. package/src/internal/testing/machine/finiteModel.ts +42 -43
  107. package/src/internal/testing/machine/probe.ts +1 -1
  108. package/src/unstable/cluster/ClusterMachine.ts +9 -17
@@ -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
  })
@@ -1140,7 +1148,7 @@ export const normalizeTargetConfigurationSync = <const States extends Machine.St
1140
1148
  export const getStateConfigByPath = (
1141
1149
  machine: Machine.Any,
1142
1150
  path: string
1143
- ): Machine.AnyStateConfig | undefined => machine.handlers[path]
1151
+ ): CapturedStateConfig | undefined => toImpl(machine).handlers[path]
1144
1152
 
1145
1153
  export const getActiveChildPath = (
1146
1154
  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
+ }
@@ -24,6 +24,7 @@ import {
24
24
  withMachineReferences
25
25
  } from "./configuration.js"
26
26
  import { InfiniteTransitionError, StoppedError } from "./errors.js"
27
+ import { type CapturedStateConfig, toImpl } from "./implementation.js"
27
28
  import * as InvocationEvent from "./invocationEvent.js"
28
29
  import {
29
30
  broadenTransitionBoundary,
@@ -114,7 +115,7 @@ const indexedStateConfigKeys: ReadonlySet<PropertyKey> = new Set([
114
115
 
115
116
  // Fail closed so a newly introduced semantic field must explicitly opt into
116
117
  // indexed execution instead of being accepted before the kernel supports it.
117
- const supportsIndexedStateConfig = (config: Machine.AnyStateConfig | undefined): boolean => {
118
+ const supportsIndexedStateConfig = (config: CapturedStateConfig | undefined): boolean => {
118
119
  if (config === undefined) {
119
120
  return true
120
121
  }
@@ -149,7 +150,7 @@ const compileIndexedExecutionDescriptor = (
149
150
  finalPaths.push(node.path)
150
151
  }
151
152
 
152
- const config = machine.handlers[node.path] as Machine.AnyStateConfig | undefined
153
+ const config = toImpl(machine).handlers[node.path] as CapturedStateConfig | undefined
153
154
  if (!supportsIndexedStateConfig(config)) {
154
155
  return undefined
155
156
  }
@@ -212,7 +213,7 @@ const compileIndexedExecutionDescriptor = (
212
213
  // the hierarchical planner so their entry and exit boundaries stay explicit.
213
214
  flat: nodes.every((node) => node.parent === undefined && (node.type === "atomic" || node.type === "final")) || (
214
215
  nodes[0]?.path === "" && nodes[0].type === "compound" && nodes[0].schema === undefined &&
215
- (machine.handlers[""] === undefined || Reflect.ownKeys(machine.handlers[""]).length === 0) &&
216
+ (toImpl(machine).handlers[""] === undefined || Reflect.ownKeys(toImpl(machine).handlers[""]!).length === 0) &&
216
217
  nodes.slice(1).every((node) => node.parent === "" && (node.type === "atomic" || node.type === "final")) &&
217
218
  [...transitionsByPath.values()].every((events) =>
218
219
  [...events.values()].every((transition) =>
@@ -816,7 +817,7 @@ const planIndexedFlatState = (
816
817
  }
817
818
 
818
819
  const sourcePath = descriptor.nodes[sourceIndex]!.path
819
- const transition = normalizeTransition(machine.handlers[sourcePath]?.on?.[event._tag])
820
+ const transition = normalizeTransition(toImpl(machine).handlers[sourcePath]?.on?.[event._tag])
820
821
  if (transition !== undefined) {
821
822
  const transitionResult = collectIndexedTransition(
822
823
  machine,
@@ -1131,7 +1132,7 @@ const makeIndexedExecutionPlan = (
1131
1132
  planIndexedState(machine, indexed, state as OwnedIndexedState, event, retainMicrosteps, machineReferences),
1132
1133
  // Initializers may enqueue commands and emissions. Managed startup owns that
1133
1134
  // work through the generic initial planner; indexed event execution remains valid.
1134
- ...(Object.values(machine.handlers as Record<string, Machine.AnyStateConfig>).some((config) =>
1135
+ ...(Object.values(toImpl(machine).handlers as Record<string, CapturedStateConfig>).some((config) =>
1135
1136
  "initialize" in config
1136
1137
  ) ?
1137
1138
  {} :
@@ -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
@@ -13,7 +13,7 @@ import { InfiniteTransitionError, MachineSchemaDecodeError, StoppedError } from
13
13
  import * as InvocationDefinition from "./invocationDefinition.js"
14
14
  import * as InvocationEvent from "./invocationEvent.js"
15
15
  import * as Planner from "./planner.js"
16
- import * as Runtime from "./runtime.js"
16
+ import * as Runtime from "./runtimeProtocol.js"
17
17
  import { ChildMachineLogicTypeId } from "./symbols.js"
18
18
 
19
19
  /** @internal */
@@ -61,7 +61,7 @@ const streamLogic = (
61
61
  }
62
62
  })
63
63
 
64
- const resolveValue = (value: unknown, context: Machine.InvokeContext<any, any, any, any>): unknown =>
64
+ const resolveValue = (value: unknown, context: Omit<Machine.InvokeContext<any, any, any, any>, "root">): unknown =>
65
65
  typeof value === "function" ? value(context) : value
66
66
 
67
67
  const makeChildOwner = (scope: Runtime.ProcessScope<any>): ChildOwner<any> => ({
@@ -76,7 +76,7 @@ const makeChildOwner = (scope: Runtime.ProcessScope<any>): ChildOwner<any> => ({
76
76
 
77
77
  const resolveOne = (
78
78
  raw: InvocationDefinition.InvocationDefinition,
79
- context: Machine.InvokeContext<any, any, any, any>,
79
+ context: Omit<Machine.InvokeContext<any, any, any, any>, "root">,
80
80
  path: string
81
81
  ): AnyConfig => {
82
82
  if ("effect" in raw) {
@@ -6,7 +6,7 @@ import type { EventTransition } from "./transition.js"
6
6
 
7
7
  // Source callbacks cross the erased machine-definition boundary here. Their
8
8
  // state, event, error and service relationships are checked by the public builder.
9
- type Context = Machine.InvokeContext<any, any, any, any>
9
+ type Context = Omit<Machine.InvokeContext<any, any, any, any>, "root">
10
10
  interface Outcomes {
11
11
  readonly onDone?: EventTransition<any, any, any, any>
12
12
  readonly onFailure?: EventTransition<any, any, any, any>