@typeonce/effect-machine 0.45.1 → 0.47.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 (148) hide show
  1. package/AGENTS.md +1823 -0
  2. package/CLAUDE.md +1823 -0
  3. package/README.md +100 -77
  4. package/ai-docs/README.md +18 -0
  5. package/ai-docs/src/10_modeling/01_create-a-machine.ts +51 -0
  6. package/ai-docs/src/10_modeling/02_branch-on-an-event.ts +55 -0
  7. package/ai-docs/src/10_modeling/03_update-retained-state.ts +58 -0
  8. package/ai-docs/src/10_modeling/04_verify-after-changing.ts +29 -0
  9. package/{docs/agent-guide.md → ai-docs/src/10_modeling/index.md} +254 -155
  10. package/{docs/root-api.md → ai-docs/src/20_root-api/index.md} +29 -57
  11. package/{docs/effect-atom-react.md → ai-docs/src/30_react/index.md} +49 -49
  12. package/{docs/machine-review.md → ai-docs/src/40_review/index.md} +42 -40
  13. package/ai-docs/src/index.md +7 -0
  14. package/ai-docs/tsconfig.json +22 -0
  15. package/dist/Machine.d.ts +1205 -1478
  16. package/dist/Machine.d.ts.map +1 -1
  17. package/dist/Machine.js +366 -214
  18. package/dist/Machine.js.map +1 -1
  19. package/dist/internal/machine/atom.js.map +1 -1
  20. package/dist/internal/machine/cluster.js.map +1 -1
  21. package/dist/internal/machine/command.d.ts +8 -0
  22. package/dist/internal/machine/command.d.ts.map +1 -1
  23. package/dist/internal/machine/command.js +2 -2
  24. package/dist/internal/machine/command.js.map +1 -1
  25. package/dist/internal/machine/configuration.d.ts +21 -5
  26. package/dist/internal/machine/configuration.d.ts.map +1 -1
  27. package/dist/internal/machine/configuration.js +1 -0
  28. package/dist/internal/machine/configuration.js.map +1 -1
  29. package/dist/internal/machine/construction.js.map +1 -1
  30. package/dist/internal/machine/declaration.d.ts +2 -1
  31. package/dist/internal/machine/declaration.d.ts.map +1 -1
  32. package/dist/internal/machine/declaration.js +28 -46
  33. package/dist/internal/machine/declaration.js.map +1 -1
  34. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  35. package/dist/internal/machine/executionPlan.js +23 -16
  36. package/dist/internal/machine/executionPlan.js.map +1 -1
  37. package/dist/internal/machine/implementation.d.ts +2 -0
  38. package/dist/internal/machine/implementation.d.ts.map +1 -1
  39. package/dist/internal/machine/implementation.js.map +1 -1
  40. package/dist/internal/machine/initialDeclaration.d.ts +2 -0
  41. package/dist/internal/machine/initialDeclaration.d.ts.map +1 -1
  42. package/dist/internal/machine/initialDeclaration.js +15 -0
  43. package/dist/internal/machine/initialDeclaration.js.map +1 -1
  44. package/dist/internal/machine/invocation.d.ts.map +1 -1
  45. package/dist/internal/machine/invocation.js +32 -21
  46. package/dist/internal/machine/invocation.js.map +1 -1
  47. package/dist/internal/machine/invocationEvent.d.ts +34 -17
  48. package/dist/internal/machine/invocationEvent.d.ts.map +1 -1
  49. package/dist/internal/machine/invocationEvent.js +16 -4
  50. package/dist/internal/machine/invocationEvent.js.map +1 -1
  51. package/dist/internal/machine/machine.d.ts +5 -22
  52. package/dist/internal/machine/machine.d.ts.map +1 -1
  53. package/dist/internal/machine/machine.js +157 -119
  54. package/dist/internal/machine/machine.js.map +1 -1
  55. package/dist/internal/machine/planner.d.ts +15 -4
  56. package/dist/internal/machine/planner.d.ts.map +1 -1
  57. package/dist/internal/machine/planner.js +18 -21
  58. package/dist/internal/machine/planner.js.map +1 -1
  59. package/dist/internal/machine/process.d.ts +2 -0
  60. package/dist/internal/machine/process.d.ts.map +1 -1
  61. package/dist/internal/machine/process.js +2 -0
  62. package/dist/internal/machine/process.js.map +1 -1
  63. package/dist/internal/machine/protocol.js.map +1 -1
  64. package/dist/internal/machine/runtime.d.ts.map +1 -1
  65. package/dist/internal/machine/runtime.js.map +1 -1
  66. package/dist/internal/machine/runtimeCompiled.js.map +1 -1
  67. package/dist/internal/machine/runtimeGeneric.js +5 -3
  68. package/dist/internal/machine/runtimeGeneric.js.map +1 -1
  69. package/dist/internal/machine/runtimeProtocol.d.ts +26 -0
  70. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -1
  71. package/dist/internal/machine/runtimeProtocol.js +71 -0
  72. package/dist/internal/machine/runtimeProtocol.js.map +1 -1
  73. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  74. package/dist/internal/machine/stateDefinition.js +0 -14
  75. package/dist/internal/machine/stateDefinition.js.map +1 -1
  76. package/dist/internal/machine/symbols.d.ts +9 -0
  77. package/dist/internal/machine/symbols.d.ts.map +1 -1
  78. package/dist/internal/machine/symbols.js.map +1 -1
  79. package/dist/internal/machine/topology.d.ts +18 -9
  80. package/dist/internal/machine/topology.d.ts.map +1 -1
  81. package/dist/internal/machine/topology.js +16 -1
  82. package/dist/internal/machine/topology.js.map +1 -1
  83. package/dist/internal/testing/machine/arbitrary.d.ts.map +1 -1
  84. package/dist/internal/testing/machine/arbitrary.js +2 -0
  85. package/dist/internal/testing/machine/arbitrary.js.map +1 -1
  86. package/dist/internal/testing/machine/check.d.ts +17 -0
  87. package/dist/internal/testing/machine/check.d.ts.map +1 -0
  88. package/dist/internal/testing/machine/check.js +371 -0
  89. package/dist/internal/testing/machine/check.js.map +1 -0
  90. package/dist/internal/testing/machine/exploration.d.ts.map +1 -1
  91. package/dist/internal/testing/machine/exploration.js.map +1 -1
  92. package/dist/internal/testing/machine/finiteModel.d.ts +14 -13
  93. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  94. package/dist/internal/testing/machine/finiteModel.js +21 -23
  95. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  96. package/dist/internal/testing/machine/runtime.d.ts +19 -88
  97. package/dist/internal/testing/machine/runtime.d.ts.map +1 -1
  98. package/dist/internal/testing/machine/runtime.js +0 -19
  99. package/dist/internal/testing/machine/runtime.js.map +1 -1
  100. package/dist/internal/testing/machine/runtimeInvariant.js.map +1 -1
  101. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  102. package/dist/internal/testing/machine/verification.js.map +1 -1
  103. package/dist/testing/MachineTest.d.ts +349 -139
  104. package/dist/testing/MachineTest.d.ts.map +1 -1
  105. package/dist/testing/MachineTest.js +201 -136
  106. package/dist/testing/MachineTest.js.map +1 -1
  107. package/dist/unstable/cluster/ClusterMachine.d.ts +9 -14
  108. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  109. package/dist/unstable/cluster/ClusterMachine.js +9 -14
  110. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  111. package/dist/unstable/reactivity/AtomMachine.d.ts +169 -80
  112. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  113. package/dist/unstable/reactivity/AtomMachine.js +165 -76
  114. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  115. package/package.json +11 -9
  116. package/src/Machine.ts +1149 -2134
  117. package/src/internal/machine/atom.ts +3 -3
  118. package/src/internal/machine/cluster.ts +2 -2
  119. package/src/internal/machine/command.ts +10 -4
  120. package/src/internal/machine/configuration.ts +16 -17
  121. package/src/internal/machine/construction.ts +1 -1
  122. package/src/internal/machine/declaration.ts +25 -50
  123. package/src/internal/machine/executionPlan.ts +90 -56
  124. package/src/internal/machine/implementation.ts +3 -1
  125. package/src/internal/machine/initialDeclaration.ts +16 -0
  126. package/src/internal/machine/invocation.ts +73 -70
  127. package/src/internal/machine/invocationEvent.ts +46 -20
  128. package/src/internal/machine/machine.ts +217 -243
  129. package/src/internal/machine/planner.ts +72 -106
  130. package/src/internal/machine/process.ts +12 -0
  131. package/src/internal/machine/protocol.ts +6 -6
  132. package/src/internal/machine/runtime.ts +1 -5
  133. package/src/internal/machine/runtimeCompiled.ts +2 -2
  134. package/src/internal/machine/runtimeGeneric.ts +7 -7
  135. package/src/internal/machine/runtimeProtocol.ts +80 -4
  136. package/src/internal/machine/stateDefinition.ts +0 -39
  137. package/src/internal/machine/symbols.ts +11 -0
  138. package/src/internal/machine/topology.ts +40 -18
  139. package/src/internal/testing/machine/arbitrary.ts +2 -0
  140. package/src/internal/testing/machine/check.ts +460 -0
  141. package/src/internal/testing/machine/exploration.ts +4 -5
  142. package/src/internal/testing/machine/finiteModel.ts +40 -42
  143. package/src/internal/testing/machine/runtime.ts +31 -170
  144. package/src/internal/testing/machine/runtimeInvariant.ts +3 -3
  145. package/src/internal/testing/machine/verification.ts +14 -14
  146. package/src/testing/MachineTest.ts +366 -145
  147. package/src/unstable/cluster/ClusterMachine.ts +9 -14
  148. package/src/unstable/reactivity/AtomMachine.ts +167 -78
@@ -4,7 +4,6 @@ import * as Option from "effect/Option"
4
4
  import { Prototype as PipeablePrototype } from "effect/Pipeable"
5
5
  import { hasProperty } from "effect/Predicate"
6
6
  import * as Schema from "effect/Schema"
7
- import type * as Scope from "effect/Scope"
8
7
  import type * as Stream from "effect/Stream"
9
8
  import type {
10
9
  ChildAddress,
@@ -26,7 +25,7 @@ import * as Activities from "./activities.js"
26
25
  import * as Configuration from "./configuration.js"
27
26
  import * as Construction from "./construction.js"
28
27
  import * as Declaration from "./declaration.js"
29
- import type { ChildAlreadyExistsError, PlanningError, StartupError } from "./errors.js"
28
+ import type { PlanningError, StartupError } from "./errors.js"
30
29
  import type { CapturedStateConfig } from "./implementation.js"
31
30
  import * as InitialDeclaration from "./initialDeclaration.js"
32
31
  import * as InvocationDefinition from "./invocationDefinition.js"
@@ -37,7 +36,7 @@ import * as Protocol from "./protocol.js"
37
36
  import * as internalRuntime from "./runtimeProtocol.js"
38
37
  import * as Serialization from "./serialization.js"
39
38
  import * as StateDefinition from "./stateDefinition.js"
40
- import { ChildMachineLogicTypeId } from "./symbols.js"
39
+ import { type ChildMachineLogicSlot, ChildMachineLogicTypeId } from "./symbols.js"
41
40
  import * as Topology from "./topology.js"
42
41
 
43
42
  export {
@@ -49,28 +48,15 @@ export {
49
48
  StartupError,
50
49
  StoppedError
51
50
  } from "./errors.js"
52
- export { ChildMachineLogicTypeId, InitialEventTypeId, SnapshotBuilderStateTypeId } from "./symbols.js"
51
+ export { InitialEventTypeId } from "./symbols.js"
53
52
 
54
53
  /** Internal seam for the public target-reference factory and its opaque brand. */
55
54
 
56
55
  const TypeId = "~effect/Machine"
57
56
  const ParentTypeId = "~effect/Machine/Parent"
58
- export const InvokeTypeId: unique symbol = Symbol.for("effect/Machine/Invoke")
59
57
  const ChildMachineTypeId = "~effect/Machine/ChildMachine"
60
58
  type MachineRuntimeRequirement = internalRuntime.MachineRuntime
61
59
 
62
- type SpawnRequirements<Requirements> = Exclude<Requirements, Scope.Scope>
63
- type SpawnIdError<Options extends SpawnOptions> = "id" extends keyof Options ? Options extends {
64
- readonly id?: infer Id
65
- } ? [Id] extends [undefined] ? never : ChildAlreadyExistsError
66
- : ChildAlreadyExistsError
67
- : never
68
- type SpawnError<Options extends SpawnOptions> = SpawnIdError<Options>
69
- type SpawnResult<State, Event, Error, Requirements, Output, SpawnError, InitialError = never> = Effect.Effect<
70
- MachineRef<State, Event, Error, Output>,
71
- SpawnError | InitialError,
72
- MachineRuntimeRequirement | SpawnRequirements<Requirements>
73
- >
74
60
  const Proto = {
75
61
  ...Inspectable.BaseProto,
76
62
  ...PipeablePrototype,
@@ -106,29 +92,17 @@ const makeWithHandlers = (
106
92
  type DefinitionBranch = {
107
93
  readonly target: (selector: unknown) => unknown
108
94
  readonly resolve?: (context: any, enqueue: unknown) => unknown
109
- readonly declinable?: boolean
110
95
  }
111
96
 
112
97
  type CapturedBranch = DefinitionBranch & {
113
98
  readonly selection: Topology.TargetSelection
114
99
  }
115
100
 
116
- type BranchDeclaration = {
117
- readonly title?: string
118
- readonly target: unknown
119
- }
120
-
121
101
  type CapturedNamedBranch = {
122
102
  readonly key: string
123
- readonly title: string
124
103
  readonly selection: Topology.TargetSelection
125
104
  }
126
105
 
127
- const plainTargetSelection = (selection: Topology.TargetSelection): Topology.TargetSelection =>
128
- selection.kind === "none"
129
- ? Topology.noneTargetSelection
130
- : Topology.makeTargetSelection(selection.kind, selection.path, selection.scope, selection.updatePath)
131
-
132
106
  const transitionTargetSelection = (
133
107
  selection: Topology.TargetSelection
134
108
  ): Machine.TransitionTargetSelection =>
@@ -230,17 +204,11 @@ const runCapturedBranch = (
230
204
  ): unknown => {
231
205
  const resolverContext: Record<string, any> = {
232
206
  ...context,
233
- root: source === "" ? context.state : context.ancestors[""],
234
- decline: Topology.makeDeclined
207
+ root: source === "" ? context.state : context.ancestors[""]
235
208
  }
236
209
  delete resolverContext.target
237
210
  const resolved = branch.resolve!(resolverContext, enqueue)
238
- if (Topology.isDeclined(resolved)) {
239
- if (branch.declinable !== true) {
240
- throw new Error(`Machine transition for state "${source}" returned decline without declaring declinable: true`)
241
- }
242
- return resolved
243
- }
211
+ if (Topology.isDeclined(resolved)) return resolved
244
212
  validateResolvedSelection(resolved, branch.selection, stateNodes)
245
213
  return resolved
246
214
  }
@@ -248,47 +216,6 @@ const runCapturedBranch = (
248
216
  const topologyTargetPath = (selection: Topology.TargetSelection): string | undefined =>
249
217
  selection.kind === "update" ? undefined : selection.path
250
218
 
251
- const isArrayIndexKey = (key: string): boolean => {
252
- const index = Number(key)
253
- return Number.isInteger(index) && index >= 0 && index < 0xffff_ffff && String(index) === key
254
- }
255
-
256
- const captureNamedBranches = (
257
- declarations: unknown,
258
- path: string,
259
- trigger: PropertyKey
260
- ): ReadonlyArray<CapturedNamedBranch> => {
261
- if (typeof declarations !== "object" || declarations === null || Array.isArray(declarations)) {
262
- throw new Error(`Machine branching transition for state "${path}" on "${String(trigger)}" requires a branch record`)
263
- }
264
- if (Object.getOwnPropertySymbols(declarations).length > 0) {
265
- throw new Error(`Machine branching transition for state "${path}" on "${String(trigger)}" cannot use symbol keys`)
266
- }
267
- const keys = Object.keys(declarations)
268
- if (keys.length === 0) {
269
- throw new Error(`Machine branching transition for state "${path}" on "${String(trigger)}" requires a branch`)
270
- }
271
- return Object.freeze(keys.map((key) => {
272
- if (key.length === 0 || isArrayIndexKey(key)) {
273
- throw new Error(
274
- `Machine branching transition for state "${path}" on "${String(trigger)}" requires non-index string branch keys`
275
- )
276
- }
277
- const declaration = (declarations as Record<string, unknown>)[key]
278
- if (typeof declaration !== "object" || declaration === null || !hasProperty(declaration, "target")) {
279
- throw new Error(`Machine transition branch "${key}" requires a target selection`)
280
- }
281
- const { target, title } = declaration as BranchDeclaration
282
- if (!Topology.isTargetSelection(target)) {
283
- throw new Error(`Machine transition branch "${key}" must select exactly one target`)
284
- }
285
- if (title !== undefined && (typeof title !== "string" || title.length === 0)) {
286
- throw new Error(`Machine transition branch "${key}" title must be a non-empty string`)
287
- }
288
- return Object.freeze({ key, title: title ?? key, selection: plainTargetSelection(target) })
289
- }))
290
- }
291
-
292
219
  const constructBranch = (
293
220
  selection: Topology.TargetSelection,
294
221
  stateNodes: Machine.StateNodes,
@@ -332,25 +259,126 @@ const constructBranch = (
332
259
  return Construction.target(stateNodes, selection.path!, config, source)
333
260
  }
334
261
 
335
- const makeBranchSelectors = (
262
+ // The key is the entry as written. It identifies the branch in `select` calls, retained transitions, and coverage.
263
+ const branchEntryKey = (entry: Readonly<Record<string, unknown>>, source: string, trigger: PropertyKey): string => {
264
+ const fields = Reflect.ownKeys(entry)
265
+ const invalid = () =>
266
+ new Error(`Machine branch entry for state "${source}" on "${String(trigger)}" must be one destination`)
267
+ if (typeof entry.target === "string") {
268
+ if (fields.some((field) => field !== "target" && field !== "update")) throw invalid()
269
+ if (entry.update === undefined) return `target:${entry.target}`
270
+ if (typeof entry.update !== "string") throw invalid()
271
+ return `target:${entry.target}+update:${entry.update}`
272
+ }
273
+ if (fields.length !== 1) throw invalid()
274
+ if (typeof entry.update === "string") return `update:${entry.update}`
275
+ if (typeof entry.history === "string") return `history:${entry.history}`
276
+ for (const field of ["initialize", "stay", "decline"]) {
277
+ if (entry[field] === true) return field
278
+ }
279
+ throw invalid()
280
+ }
281
+
282
+ const captureNamedBranches = (
283
+ entries: unknown,
284
+ declaration: Declaration.Declaration,
285
+ source: string,
286
+ trigger: PropertyKey,
287
+ stateNodes: Machine.StateNodes
288
+ ): { readonly branches: ReadonlyArray<CapturedNamedBranch>; readonly declines: boolean } => {
289
+ const label = `Machine branches for state "${source}" on "${String(trigger)}"`
290
+ if (!Array.isArray(entries) || entries.length === 0) throw new Error(`${label} require at least one entry`)
291
+ const keys = new Set<string>()
292
+ const branches: Array<CapturedNamedBranch> = []
293
+ let declines = false
294
+ for (const entry of entries) {
295
+ if (typeof entry !== "object" || entry === null) throw new Error(`${label} must list objects`)
296
+ const key = branchEntryKey(entry, source, trigger)
297
+ if (keys.has(key)) throw new Error(`${label} declare "${key}" more than once`)
298
+ keys.add(key)
299
+ if (key === "decline") {
300
+ declines = true
301
+ continue
302
+ }
303
+ branches.push(Object.freeze({
304
+ key,
305
+ selection: captureDefinitionBranch(
306
+ { target: () => Declaration.selection(declaration, entry) },
307
+ undefined,
308
+ stateNodes,
309
+ source,
310
+ trigger
311
+ ).selection
312
+ }))
313
+ }
314
+ if (branches.length === 0) throw new Error(`${label} need a destination besides decline`)
315
+ return { branches: Object.freeze(branches), declines }
316
+ }
317
+
318
+ const updateValue = (value: unknown): Readonly<Record<string, unknown>> =>
319
+ typeof value === "object" && value !== null && hasProperty(value, "decoded") && value.decoded === true &&
320
+ hasProperty(value, "data")
321
+ ? { decoded: true, data: value.data }
322
+ : { data: value }
323
+
324
+ const makeBranchSelect = (
336
325
  branches: ReadonlyArray<CapturedNamedBranch>,
326
+ declines: boolean,
337
327
  owner: object,
338
328
  stateNodes: Machine.StateNodes,
339
329
  declaration: Declaration.Declaration,
340
330
  source: string
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
- )]
352
- )
353
- ))
331
+ ): Readonly<Record<string, unknown>> => {
332
+ const selected = (key: string, construct: (selection: Topology.TargetSelection) => unknown) => {
333
+ const index = branches.findIndex((branch) => branch.key === key)
334
+ if (index === -1) {
335
+ throw new Error(`Machine resolve for state "${source}" selected "${key}", which branches does not declare`)
336
+ }
337
+ return Topology.makeSelectedBranch(owner, index, key, construct(branches[index]!.selection))
338
+ }
339
+ return Object.freeze({
340
+ target: (path: string, raw?: unknown) => {
341
+ const { update, ...construction } = raw === undefined ? {} as Record<string, unknown> : Construction.record(raw)
342
+ if (update === undefined) {
343
+ return selected(
344
+ `target:${path}`,
345
+ (selection) => constructBranch(selection, stateNodes, declaration, construction, source)
346
+ )
347
+ }
348
+ const name = Declaration.updateOwner(update)
349
+ return selected(`target:${path}+update:${name}`, (selection) =>
350
+ constructBranch(
351
+ selection,
352
+ stateNodes,
353
+ declaration,
354
+ { ...construction, update: updateValue((update as Record<string, unknown>)[name]) },
355
+ source
356
+ ))
357
+ },
358
+ update: (updates: unknown) => {
359
+ const name = Declaration.updateOwner(updates)
360
+ return selected(`update:${name}`, (selection) =>
361
+ constructBranch(
362
+ selection,
363
+ stateNodes,
364
+ declaration,
365
+ updateValue((updates as Record<string, unknown>)[name]),
366
+ source
367
+ ))
368
+ },
369
+ history: (path: string) =>
370
+ selected(`history:${path}`, (selection) => constructBranch(selection, stateNodes, declaration, {}, source)),
371
+ initialize: (raw?: unknown) =>
372
+ selected("initialize", (selection) => constructBranch(selection, stateNodes, declaration, raw, source)),
373
+ stay: () => selected("stay", () => Topology.makeNoTarget()),
374
+ decline: () => {
375
+ if (!declines) {
376
+ throw new Error(`Machine resolve for state "${source}" selected "decline", which branches does not declare`)
377
+ }
378
+ return Topology.makeSelectedBranch(owner, -1, "decline", Topology.makeDeclined())
379
+ }
380
+ })
381
+ }
354
382
 
355
383
  const validateSelectedBranchResult = (
356
384
  result: unknown,
@@ -379,7 +407,8 @@ const normalizeObjectTransition = (
379
407
  raw: unknown,
380
408
  declaration: Declaration.Declaration,
381
409
  path: string,
382
- stateNodes: Machine.StateNodes
410
+ stateNodes: Machine.StateNodes,
411
+ acceptance: Machine.TransitionAcceptance
383
412
  ): Record<string, unknown> => {
384
413
  if (typeof raw !== "object" || raw === null) throw new Error(`Machine transition for "${path}" must be an object`)
385
414
  const config = { ...raw } as Record<string, unknown>
@@ -388,70 +417,57 @@ const normalizeObjectTransition = (
388
417
  "update",
389
418
  "initialize",
390
419
  "history",
391
- "none",
420
+ "stay",
392
421
  "branches",
393
422
  "data",
394
423
  "decoded",
395
424
  "resolve",
396
425
  "guard",
397
426
  "reenter",
398
- "declinable"
427
+ "commands"
399
428
  ]
400
429
  for (const key of Reflect.ownKeys(config)) {
401
430
  if (typeof key !== "string" || !allowed.includes(key)) {
402
431
  throw new Error("Machine transition contains an unknown field")
403
432
  }
404
433
  }
405
- for (const key of ["resolve", "guard"]) {
434
+ for (const key of ["resolve", "guard", "commands"]) {
406
435
  if (config[key] !== undefined && typeof config[key] !== "function") {
407
436
  throw new Error(`Machine transition ${key} must be a function`)
408
437
  }
409
438
  }
410
439
  const guard = typeof config.guard === "function" ? config.guard : undefined
411
440
  const resolve = typeof config.resolve === "function" ? config.resolve : undefined
441
+ const commands = typeof config.commands === "function" ? config.commands : undefined
412
442
  if (config.decoded !== undefined && typeof config.decoded !== "boolean") {
413
443
  throw new Error("Machine decoded must be a boolean construction flag")
414
444
  }
415
445
  const hasData = Object.prototype.hasOwnProperty.call(config, "data")
416
446
  if (config.decoded === true && !hasData) throw new Error("Machine decoded construction requires data")
417
- if (hasData && resolve !== undefined) throw new Error("Machine data and resolve are mutually exclusive")
418
- const data = config.data
419
- const construct = typeof data === "function" ? data : () => data
420
447
  const guarded = guard !== undefined
421
- const declinable = guarded || config.declinable === true
422
- if (typeof config.branches === "string") {
423
- const group = declaration.branches.get(config.branches)
424
- if (group === undefined || resolve === undefined) {
425
- throw new Error("Machine branching transition requires a registered group and resolver")
426
- }
448
+ if (
449
+ acceptance === "required" &&
450
+ (guarded || (Array.isArray(config.branches) && config.branches.some((entry) => entry?.decline === true)))
451
+ ) {
452
+ throw new Error(`Machine guard and decline apply only to on and always, on state "${path}"`)
453
+ }
454
+ if ((config.branches === undefined) !== (resolve === undefined)) {
455
+ throw new Error("Machine branches and resolve must be declared together")
456
+ }
457
+ if (config.branches !== undefined) {
427
458
  if (
428
- ["target", "update", "initialize", "history", "none", "data", "decoded"].some((key) => config[key] !== undefined)
429
- ) throw new Error("Machine branching transition cannot redeclare its destination")
430
- const entries = Object.fromEntries(
431
- Object.entries(group).map(([key, spec]) => [key, {
432
- title: spec.title,
433
- target: captureDefinitionBranch(
434
- { target: () => Declaration.selection(declaration, spec) },
435
- undefined,
436
- stateNodes,
437
- path,
438
- key
439
- ).selection
440
- }])
441
- )
459
+ ["target", "update", "initialize", "history", "stay", "data", "decoded", "guard", "commands"].some((key) =>
460
+ config[key] !== undefined
461
+ )
462
+ ) throw new Error("Machine branching transition cannot redeclare its destination, guard, or commands")
442
463
  return {
443
- branches: () => entries,
464
+ branches: config.branches,
444
465
  reenter: config.reenter,
445
- declinable,
446
- resolve: (context: Record<string, any>, enqueue: unknown) => {
447
- return guarded && !guard(context) ? Topology.makeDeclined() : resolve(context, enqueue)
448
- }
466
+ resolve
449
467
  }
450
468
  }
469
+ if (typeof config.update === "string") throw new Error("Machine transition update must be a record with one owner")
451
470
  const selection = Declaration.selection(declaration, config)
452
- if (resolve !== undefined && selection.kind !== "none") {
453
- throw new Error("Machine advanced construction requires a declared branch group")
454
- }
455
471
  const initialize = config.initialize
456
472
  const initializes = initialize !== undefined
457
473
  if (initializes && (hasData || config.decoded !== undefined)) {
@@ -460,37 +476,43 @@ const normalizeObjectTransition = (
460
476
  if (initializes && !declaration.input && initialize !== true) {
461
477
  throw new Error("Machine initialize requires true when the machine declares no input")
462
478
  }
479
+ if (selection.kind === "none" && (hasData || config.decoded !== undefined)) {
480
+ throw new Error("Machine targetless transition accepts no data")
481
+ }
463
482
  const constructInput = !declaration.input
464
483
  ? () => undefined
465
484
  : typeof initialize === "function"
466
485
  ? initialize
467
486
  : () => initialize
487
+ const owner = selection.updatePath ?? (selection.kind === "update" ? selection.path : undefined)
488
+ const updates = config.update as Record<string, unknown> | undefined
489
+ const rawUpdate = owner === undefined || updates === undefined ? undefined : updates[Declaration.updateOwner(updates)]
490
+ const constructUpdate = rawUpdate === undefined ? undefined : InitialDeclaration.ownerUpdate(rawUpdate)
491
+ const construct = typeof config.data === "function" ? config.data : () => config.data
468
492
  return {
469
493
  target: () => selection,
470
494
  reenter: config.reenter,
471
- declinable,
495
+ declinable: guarded,
472
496
  resolve: (context: Record<string, any>, enqueue: unknown) => {
473
497
  if (guarded && !guard(context)) return Topology.makeDeclined()
474
- if (resolve !== undefined) return resolve(context, enqueue)
498
+ commands?.(context, enqueue)
499
+ if (selection.kind === "none") return undefined
475
500
  if (initializes) {
476
501
  return constructBranch(selection, stateNodes, declaration, { input: constructInput(context) })
477
502
  }
478
- const value = construct(context)
503
+ const state = {
504
+ ...(hasData ? { data: construct(context) } : {}),
505
+ ...(config.decoded === undefined ? {} : { decoded: config.decoded })
506
+ }
479
507
  return constructBranch(
480
508
  selection,
481
509
  stateNodes,
482
510
  declaration,
483
- selection.updatePath === undefined
484
- ? {
485
- ...(hasData ? { data: value } : {}),
486
- ...(config.decoded === undefined ? {} : { decoded: config.decoded })
487
- }
488
- : selection.kind === "choice"
489
- ? { update: { data: value, decoded: config.decoded } }
490
- : {
491
- ...(value.target === undefined ? {} : { data: value.target, decoded: config.decoded }),
492
- update: { data: value.update, decoded: config.decoded }
493
- },
511
+ selection.kind === "update" ?
512
+ constructUpdate!(context) :
513
+ selection.updatePath === undefined
514
+ ? state
515
+ : { ...state, update: constructUpdate!(context) },
494
516
  path
495
517
  )
496
518
  }
@@ -502,49 +524,39 @@ const captureTransition = (
502
524
  stateNodes: Machine.StateNodes,
503
525
  path: string,
504
526
  declaration: Declaration.Declaration,
505
- trigger: PropertyKey
527
+ trigger: PropertyKey,
528
+ acceptance: Machine.TransitionAcceptance
506
529
  ): unknown => {
507
- const transition = normalizeObjectTransition(rawTransition, declaration, path, stateNodes)
530
+ const transition = normalizeObjectTransition(rawTransition, declaration, path, stateNodes, acceptance)
508
531
  if (typeof transition !== "object" || transition === null) {
509
532
  throw new Error(`Machine transition for state "${path}" on "${String(trigger)}" must be an object`)
510
533
  }
511
534
  const definition = transition as Record<PropertyKey, unknown>
512
535
  const reenter = definition.reenter === true
513
- const declinable = definition.declinable === true
514
536
  if (hasProperty(definition, "branches")) {
515
- const branching = definition as { readonly branches: unknown; readonly resolve?: unknown }
516
- if (typeof branching.branches !== "function" || typeof branching.resolve !== "function") {
517
- throw new Error(
518
- `Machine branching transition for state "${path}" on "${String(trigger)}" requires branches and resolve`
519
- )
520
- }
521
- const resolve = branching.resolve
522
- const branches = captureNamedBranches(branching.branches(), path, trigger)
537
+ const resolve = (definition as Record<PropertyKey, unknown>).resolve as (
538
+ context: Record<string, any>,
539
+ enqueue: unknown
540
+ ) => unknown
541
+ const { branches, declines } = captureNamedBranches(definition.branches, declaration, path, trigger, stateNodes)
523
542
  const owner = Object.freeze({})
543
+ const select = makeBranchSelect(branches, declines, owner, stateNodes, declaration, path)
524
544
  const evaluate = (context: Record<string, any>, enqueue: unknown) => {
525
545
  const resolverContext: Record<string, any> = {
526
546
  ...context,
527
547
  root: path === "" ? context.state : context.ancestors[""],
528
- decline: Topology.makeDeclined
548
+ select
529
549
  }
530
550
  delete resolverContext.target
531
- resolverContext.select = makeBranchSelectors(branches, owner, stateNodes, declaration, path)
532
551
  const selected = resolve(resolverContext, enqueue)
533
- if (Topology.isDeclined(selected)) {
534
- if (!declinable) {
535
- throw new Error(
536
- `Machine branching transition for state "${path}" on "${
537
- String(trigger)
538
- }" returned decline without declaring declinable: true`
539
- )
540
- }
541
- return { result: selected, branchIndex: -1, branchKey: undefined }
542
- }
543
552
  if (!Topology.isSelectedBranch(selected) || selected.owner !== owner) {
544
553
  throw new Error(
545
- `Machine branching transition for state "${path}" on "${String(trigger)}" must select one declared branch`
554
+ `Machine branching transition for state "${path}" on "${String(trigger)}" must return a select call`
546
555
  )
547
556
  }
557
+ if (selected.branchIndex === -1) {
558
+ return { result: selected.result, branchIndex: -1, branchKey: undefined }
559
+ }
548
560
  const branch = branches[selected.branchIndex]
549
561
  if (branch === undefined || selected.branchKey !== branch.key) {
550
562
  throw new Error(`Machine branching transition returned invalid branch evidence`)
@@ -558,7 +570,7 @@ const captureTransition = (
558
570
  }
559
571
  return {
560
572
  reenter,
561
- declinable,
573
+ declinable: declines,
562
574
  targets: [
563
575
  ...new Set(
564
576
  branches.flatMap((branch) =>
@@ -570,7 +582,6 @@ const captureTransition = (
570
582
  Object.freeze({
571
583
  type: "branch" as const,
572
584
  key: branch.key,
573
- title: branch.title,
574
585
  target: topologyTargetPath(branch.selection),
575
586
  selection: transitionTargetSelection(branch.selection),
576
587
  updates: selectionUpdates(branch.selection)
@@ -580,6 +591,7 @@ const captureTransition = (
580
591
  transition: (context: Record<string, any>, enqueue: unknown) => evaluate(context, enqueue).result
581
592
  }
582
593
  }
594
+ const declinable = definition.declinable === true
583
595
  const branch = captureDefinitionBranch(transition, undefined, stateNodes, path, trigger)
584
596
  const evaluate = (context: Record<string, any>, enqueue: unknown) => ({
585
597
  result: runCapturedBranch(branch, context, enqueue, stateNodes, path),
@@ -617,7 +629,8 @@ const captureEventHandlers = (
617
629
  stateNodes,
618
630
  path,
619
631
  declaration,
620
- event
632
+ event,
633
+ "declinable"
621
634
  )
622
635
  }
623
636
  return captured
@@ -639,7 +652,7 @@ const captureInvokeDefinition = (
639
652
  )
640
653
  for (const key of ["onElement", "onDone", "onFailure", "onSnapshot"] as const) {
641
654
  if (captured[key] !== undefined) {
642
- captured[key] = captureTransition(captured[key], stateNodes, path, declaration, key)
655
+ captured[key] = captureTransition(captured[key], stateNodes, path, declaration, key, "required")
643
656
  }
644
657
  }
645
658
  return InvocationDefinition.capture(captured, path)
@@ -681,13 +694,13 @@ const flattenHandlers = (
681
694
  stateConfig.on = capturedOn
682
695
  }
683
696
  if (stateConfig.always !== undefined) {
684
- stateConfig.always = captureTransition(stateConfig.always, stateNodes, path, declaration, "always")
697
+ stateConfig.always = captureTransition(stateConfig.always, stateNodes, path, declaration, "always", "declinable")
685
698
  }
686
699
  if (stateConfig.onDone !== undefined) {
687
- stateConfig.onDone = captureTransition(stateConfig.onDone, stateNodes, path, declaration, "done")
700
+ stateConfig.onDone = captureTransition(stateConfig.onDone, stateNodes, path, declaration, "done", "required")
688
701
  }
689
702
  if (stateConfig.choice !== undefined) {
690
- stateConfig.choice = captureTransition(stateConfig.choice, stateNodes, path, declaration, "choice")
703
+ stateConfig.choice = captureTransition(stateConfig.choice, stateNodes, path, declaration, "choice", "required")
691
704
  }
692
705
  if (stateConfig.invoke !== undefined) {
693
706
  stateConfig.invoke = captureInvokeDefinition(stateConfig.invoke, stateNodes, path, declaration)
@@ -703,7 +716,7 @@ const flattenHandlers = (
703
716
  throw new Error(`Machine choice state "${path}" requires a transition`)
704
717
  }
705
718
  }
706
- handlers[path] = stateConfig as CapturedStateConfig
719
+ handlers[path] = stateConfig
707
720
  if (childConfig !== undefined) {
708
721
  const node = Topology.getStateNodeDefinition(path, states[key]!)
709
722
  if (node.states === undefined) {
@@ -829,14 +842,12 @@ const makeStateHelpers = (): Machine.StateAccessors<{ readonly "": Machine.State
829
842
  Option.map((snapshot) => ({ value: snapshot.value, parents }))
830
843
  )
831
844
  }) as Machine.StateAccessors<{ readonly "": Machine.StateNodeConfig }>["getWithParents"],
832
- getSnapshot: Topology.getSnapshotByPath as unknown as Machine.StateAccessors<
845
+ getSnapshot: Topology.getSnapshotByPath as Machine.StateAccessors<
833
846
  { readonly "": Machine.StateNodeConfig }
834
847
  >["getSnapshot"],
835
848
  matches:
836
849
  ((snapshot: Machine.AtomicSnapshot<string, unknown>, path: string) =>
837
- Option.isSome(Topology.getSnapshotByPath(snapshot, path))) as Machine.StateAccessors<
838
- { readonly "": Machine.StateNodeConfig }
839
- >["matches"]
850
+ Option.isSome(Topology.getSnapshotByPath(snapshot, path)))
840
851
  }
841
852
  }
842
853
 
@@ -883,7 +894,7 @@ const flattenEventProtocolInputs = <Kind extends Machine.EventProtocolKind>(
883
894
  inputs.flatMap((input) =>
884
895
  Protocol.isEventProtocol(input, kind)
885
896
  ? Protocol.eventProtocolSchemas(input)
886
- : [input as Machine.TaggedSchema]
897
+ : [input]
887
898
  )
888
899
 
889
900
  export const events = <const Inputs extends ReadonlyArray<Machine.EventProtocolInput<"public">>>(
@@ -965,6 +976,8 @@ export const planInitial: (
965
976
  ...args: ReadonlyArray<any>
966
977
  ) => Effect.Effect<any, PlanningError | StartupError> = internalPlanner.planInitial
967
978
 
979
+ // Erased boundary: compiled nodes are stored with string paths; the generic
980
+ // machine type is the only source of their literal identifiers.
968
981
  export const stateNodes = <M extends Machine.Any>(
969
982
  machine: M
970
983
  ): ReadonlyArray<
@@ -993,7 +1006,7 @@ export const initialDefinition = <M extends Machine.Any>(
993
1006
 
994
1007
  export const inputEventSchemas = <M extends Machine.Any>(
995
1008
  machine: M
996
- ): Machine.InputEvents<M> => Protocol.inputEventSchemas(machine) as Machine.InputEvents<M>
1009
+ ): Machine.InputEvents<M> => Protocol.inputEventSchemas(machine)
997
1010
 
998
1011
  export const transitionDefinitions = <M extends Machine.Any>(
999
1012
  machine: M
@@ -1105,12 +1118,15 @@ const makeChild = <const Id extends string, M extends Machine.Any>(
1105
1118
  id: Id,
1106
1119
  machine: M,
1107
1120
  makeLogic: (input?: unknown) => Logic<any, any, any, any, any, any>
1108
- ): ChildMachine<Id, M> => ({
1109
- [ChildMachineTypeId]: ChildMachineTypeId,
1110
- id,
1111
- machine,
1112
- [ChildMachineLogicTypeId]: makeLogic
1113
- })
1121
+ ): ChildMachine<Id, M> =>
1122
+ ({
1123
+ [ChildMachineTypeId]: ChildMachineTypeId,
1124
+ id,
1125
+ machine,
1126
+ [ChildMachineLogicTypeId]: makeLogic
1127
+ } satisfies
1128
+ & Pick<ChildMachine<Id, M>, typeof ChildMachineTypeId | "id" | "machine">
1129
+ & ChildMachineLogicSlot) as unknown as ChildMachine<Id, M>
1114
1130
 
1115
1131
  export const childFamily = <M extends Machine.Any>(machine: M): ChildMachine.Family<M> => {
1116
1132
  const makeLogic = (input?: unknown): Logic<any, any, any, any, any, any> =>
@@ -1122,73 +1138,31 @@ export const childFamily = <M extends Machine.Any>(machine: M): ChildMachine.Fam
1122
1138
 
1123
1139
  export const childAddress = <Event = never>(id: string): ChildAddress<Event> => id as ChildAddress<Event>
1124
1140
 
1125
- export const spawn: {
1126
- <ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(
1127
- logic: Logic<
1128
- ChildState,
1129
- ChildEvent,
1130
- ChildError,
1131
- ChildRequirements,
1132
- ChildOutput,
1133
- ChildInitialError
1134
- >
1135
- ): SpawnResult<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, never, ChildInitialError>
1136
- <
1137
- ChildState,
1138
- ChildEvent,
1139
- ChildError,
1140
- ChildRequirements,
1141
- ChildOutput,
1142
- Options extends SpawnOptions,
1143
- ChildInitialError = never
1144
- >(
1145
- logic: Logic<
1146
- ChildState,
1147
- ChildEvent,
1148
- ChildError,
1149
- ChildRequirements,
1150
- ChildOutput,
1151
- ChildInitialError
1152
- >,
1153
- options: Options & ChildAddress.OptionsCompatibility<Options, ChildEvent>
1154
- ): SpawnResult<
1155
- ChildState,
1156
- ChildEvent,
1157
- ChildError,
1158
- ChildRequirements,
1159
- ChildOutput,
1160
- SpawnError<Options>,
1161
- ChildInitialError
1162
- >
1163
- } = ((logic: Logic<any, any, any, any, any, any>, options?: SpawnOptions) =>
1141
+ // The public `Machine` module declares the typed overloads and checks these
1142
+ // erased implementations against them structurally.
1143
+ export const spawn = (logic: Logic<any, any, any, any, any, any>, options?: SpawnOptions) =>
1164
1144
  Effect.flatMap(
1165
1145
  internalRuntime.MachineRuntime,
1166
- (runtime) => options === undefined ? runtime.spawn(logic) : (runtime.spawn as any)(logic, options)
1167
- )) as any
1168
-
1169
- export const sendTo: {
1170
- <Child extends ChildMachine.Any>(
1171
- child: Child,
1172
- event: ChildMachine.Event<Child>
1173
- ): Effect.Effect<void, StoppedError, MachineRuntimeRequirement>
1174
- <Address extends ChildAddress<never>>(
1175
- id: Address,
1176
- event: ChildAddress.Event<Address>
1177
- ): Effect.Effect<void, StoppedError, MachineRuntimeRequirement>
1178
- } = ((child: string | ChildMachine.Any, event: unknown) =>
1146
+ // `SpawnOptions` declares only `id`; an absent id spawns an anonymous child.
1147
+ (runtime) => options?.id === undefined ? runtime.spawn(logic) : runtime.spawn(logic, { id: options.id })
1148
+ )
1149
+
1150
+ export const sendTo = (
1151
+ child: string | ChildMachine.Any,
1152
+ event: unknown
1153
+ ): Effect.Effect<void, StoppedError, MachineRuntimeRequirement> =>
1179
1154
  Effect.flatMap(
1180
1155
  internalRuntime.MachineRuntime,
1181
1156
  (runtime) => runtime.sendTo(child, event)
1182
- )) as any
1157
+ )
1183
1158
 
1184
- export const stopChild: {
1185
- <Event>(child: ChildAddress<Event>): Effect.Effect<void, never, MachineRuntimeRequirement>
1186
- <Child extends ChildMachine.Any>(child: Child): Effect.Effect<void, never, MachineRuntimeRequirement>
1187
- } = ((child: string | ChildMachine.Any) =>
1159
+ export const stopChild = (
1160
+ child: string | ChildMachine.Any
1161
+ ): Effect.Effect<void, never, MachineRuntimeRequirement> =>
1188
1162
  Effect.flatMap(
1189
1163
  internalRuntime.MachineRuntime,
1190
1164
  (runtime) => runtime.stopChild(child)
1191
- )) as any
1165
+ )
1192
1166
 
1193
1167
  export const watch = <State, Event, Error = never, Output = never>(
1194
1168
  ref: MachineRef<State, Event, Error, Output>