@typeonce/effect-machine 0.41.0 → 0.42.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 (67) hide show
  1. package/README.md +33 -6
  2. package/dist/Machine.d.ts +159 -27
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +20 -6
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/atom.d.ts +2 -7
  7. package/dist/internal/machine/atom.d.ts.map +1 -1
  8. package/dist/internal/machine/atom.js +132 -87
  9. package/dist/internal/machine/atom.js.map +1 -1
  10. package/dist/internal/machine/childRegistry.d.ts +7 -0
  11. package/dist/internal/machine/childRegistry.d.ts.map +1 -1
  12. package/dist/internal/machine/childRegistry.js +7 -0
  13. package/dist/internal/machine/childRegistry.js.map +1 -1
  14. package/dist/internal/machine/invocation.d.ts.map +1 -1
  15. package/dist/internal/machine/invocation.js +13 -2
  16. package/dist/internal/machine/invocation.js.map +1 -1
  17. package/dist/internal/machine/invocationDefinition.d.ts +7 -0
  18. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  19. package/dist/internal/machine/invocationDefinition.js +16 -0
  20. package/dist/internal/machine/invocationDefinition.js.map +1 -1
  21. package/dist/internal/machine/machine.d.ts.map +1 -1
  22. package/dist/internal/machine/machine.js +69 -6
  23. package/dist/internal/machine/machine.js.map +1 -1
  24. package/dist/internal/machine/plannedSnapshot.d.ts +30 -0
  25. package/dist/internal/machine/plannedSnapshot.d.ts.map +1 -0
  26. package/dist/internal/machine/plannedSnapshot.js +103 -0
  27. package/dist/internal/machine/plannedSnapshot.js.map +1 -0
  28. package/dist/internal/machine/planner.d.ts +5 -0
  29. package/dist/internal/machine/planner.d.ts.map +1 -1
  30. package/dist/internal/machine/planner.js +1 -1
  31. package/dist/internal/machine/planner.js.map +1 -1
  32. package/dist/internal/machine/runtime.d.ts +5 -4
  33. package/dist/internal/machine/runtime.d.ts.map +1 -1
  34. package/dist/internal/machine/runtime.js +60 -15
  35. package/dist/internal/machine/runtime.js.map +1 -1
  36. package/dist/internal/machine/runtimeCompiled.js +2 -2
  37. package/dist/internal/machine/runtimeCompiled.js.map +1 -1
  38. package/dist/internal/machine/runtimeGeneric.js +1 -1
  39. package/dist/internal/machine/runtimeGeneric.js.map +1 -1
  40. package/dist/internal/machine/runtimeProtocol.d.ts +2 -1
  41. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -1
  42. package/dist/internal/machine/runtimeProtocol.js +2 -2
  43. package/dist/internal/machine/runtimeProtocol.js.map +1 -1
  44. package/dist/testing/MachineTest.d.ts +2 -2
  45. package/dist/testing/MachineTest.js +2 -2
  46. package/dist/unstable/reactivity/AtomMachine.d.ts +82 -19
  47. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  48. package/dist/unstable/reactivity/AtomMachine.js +0 -7
  49. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  50. package/docs/agent-guide.md +28 -5
  51. package/docs/effect-atom-react.md +207 -11
  52. package/docs/machine-review.md +18 -4
  53. package/package.json +4 -4
  54. package/src/Machine.ts +229 -32
  55. package/src/internal/machine/atom.ts +263 -113
  56. package/src/internal/machine/childRegistry.ts +9 -0
  57. package/src/internal/machine/invocation.ts +17 -2
  58. package/src/internal/machine/invocationDefinition.ts +19 -0
  59. package/src/internal/machine/machine.ts +65 -2
  60. package/src/internal/machine/plannedSnapshot.ts +113 -0
  61. package/src/internal/machine/planner.ts +1 -1
  62. package/src/internal/machine/runtime.ts +101 -28
  63. package/src/internal/machine/runtimeCompiled.ts +2 -2
  64. package/src/internal/machine/runtimeGeneric.ts +1 -1
  65. package/src/internal/machine/runtimeProtocol.ts +4 -2
  66. package/src/testing/MachineTest.ts +2 -2
  67. package/src/unstable/reactivity/AtomMachine.ts +90 -20
@@ -53,23 +53,90 @@ export const useAuthMachine = Auth.useMachine
53
53
  function AuthRoute({ input, attemptId }: Props) {
54
54
  return (
55
55
  <Auth.Provider key={attemptId} input={input}>
56
- <Suspense fallback={<Loading />}>
57
- <AuthCard />
58
- </Suspense>
56
+ <AuthCard />
59
57
  </Auth.Provider>
60
58
  )
61
59
  }
62
60
  ```
63
61
 
64
62
  Input is startup-only. Send events to update the existing workflow; change the
65
- Provider's React key to create a new one. Keep the Provider above Suspense so
66
- suspension does not discard the owner. Supply an Atom RegistryProvider at the
67
- application boundary. The same factory used by two Providers creates isolated
63
+ Provider's React key to create a new one. `MachineState` does not suspend, so
64
+ the first paint needs no Suspense boundary. Custom readers that use
65
+ `useAtomSuspense` still suspend during startup; keep the Provider above their
66
+ Suspense boundary so suspension does not discard the owner. Supply an Atom
67
+ RegistryProvider at the application boundary. The same factory used by two Providers creates isolated
68
68
  machines, even when their inputs are equal.
69
69
 
70
70
  `useMachineAtom(() => makeMachine(input))` remains available for custom owners.
71
71
  It mounts the reference after commit without reading `result` or `snapshot`.
72
72
 
73
+ ## Per-owner capabilities
74
+
75
+ A router, a callback owned by a component, or another per-instance capability
76
+ is a service, never a schema field or startup input. Declare the service, let a
77
+ state invoke the work that needs it, and provide the implementation from the
78
+ React owner:
79
+
80
+ ```tsx
81
+ import { Machine } from "@typeonce/effect-machine"
82
+ import { AtomMachine } from "@typeonce/effect-machine/reactivity"
83
+ import { useMachineAtom } from "@typeonce/effect-machine-react"
84
+ import { Context, Effect, Layer } from "effect"
85
+ import { Atom } from "effect/reactivity"
86
+ import { AppLayer } from "../lib/app-layer"
87
+
88
+ export class Navigation extends Context.Service<Navigation, {
89
+ readonly push: (href: string) => Effect.Effect<void>
90
+ }>()("Navigation") {}
91
+
92
+ export const OnboardingMachine = Machine.make({
93
+ root: Machine.state({
94
+ states: { Editing: {}, Leaving: {}, Done: { type: "final" } }
95
+ }),
96
+ events: Machine.events({ Submit: {} }),
97
+ effects: {
98
+ navigateNext: Effect.flatMap(Navigation, (navigation) =>
99
+ navigation.push("/onboarding/next"))
100
+ }
101
+ }).handle({
102
+ initial: { target: "Editing" },
103
+ states: {
104
+ Editing: { on: { Submit: { target: "Leaving" } } },
105
+ Leaving: { invoke: { src: "navigateNext", onDone: { target: "Done" } } },
106
+ Done: {}
107
+ }
108
+ })
109
+
110
+ function OnboardingRoute() {
111
+ const router = useRouter()
112
+ const machine = useMachineAtom(() =>
113
+ AtomMachine
114
+ .bind(Atom.runtime(Layer.merge(
115
+ AppLayer,
116
+ Layer.succeed(Navigation, {
117
+ push: (href) => Effect.sync(() => router.push(href))
118
+ })
119
+ )))
120
+ .make(OnboardingMachine)
121
+ )
122
+
123
+ return <OnboardingForm machine={machine} />
124
+ }
125
+ ```
126
+
127
+ The requirement stays on the machine type. Binding the machine to a runtime
128
+ without `Navigation`, such as the application-wide `MachineAtoms`, is a compile
129
+ error. Snapshots contain only schema data, so `Machine.encodeSnapshot` keeps
130
+ working, and tests substitute the capability with `Layer.mock(Navigation, ...)`.
131
+
132
+ Create the runtime inside the `useMachineAtom` factory so each owner builds it
133
+ once. `Atom.runtime` builds layers through the registry's memo map: the shared
134
+ `AppLayer` is built once per registry and reused, and each owner builds only its
135
+ own capability layer. Use `Layer.provideMerge(ownerLayer, AppLayer)` when the
136
+ owner layer itself needs application services. `createMachineContext` takes a
137
+ module-level factory, so distribute an owner-bound machine through props or a
138
+ React Context of your own.
139
+
73
140
  ## Render state-owned data
74
141
 
75
142
  Render a typed path in the smallest component that needs it:
@@ -88,8 +155,11 @@ function EditingFields() {
88
155
  ```
89
156
 
90
157
  `MachineState` subscribes only its renderer. The path determines the callback's
91
- snapshot type. Startup suspends, failures reach the nearest error boundary,
92
- and an inactive path renders `inactive` (null by default).
158
+ snapshot type. It does not suspend: until the machine has a snapshot it renders
159
+ `pending`, and an inactive path renders `inactive` (both null by default).
160
+ Startup and runtime failures reach the nearest error boundary. Once a snapshot
161
+ has rendered, the renderer keeps it while the machine is still starting, for
162
+ example while a bound runtime layer builds after hydration.
93
163
 
94
164
  For custom hooks, `useAtomSuspense(AtomMachine.selectSnapshot(machine, path)).value`
95
165
  returns an Option of the selected snapshot.
@@ -159,6 +229,14 @@ function SubmitButton() {
159
229
  `useAtomSet` mounts the writable atom and does not subscribe the component to
160
230
  its value.
161
231
 
232
+ Writes made while the machine is still starting, for example while a bound
233
+ `Atom.runtime` layer is building after hydration, are held and delivered in
234
+ write order once the machine is ready. The write result stays waiting until
235
+ the event is delivered and fails with the startup error if startup fails.
236
+ Writes after the machine stopped or completed fail with `StoppedError`. The
237
+ same applies to `stop` and to child `send` and `stop`; a child command fails
238
+ with `ChildNotActiveError` when the state that owns the child is not active.
239
+
162
240
  ## Query concrete event acceptance
163
241
 
164
242
  `AtomMachine.can` turns one concrete event input into a reusable machine
@@ -206,6 +284,47 @@ const submitAllowed = AtomMachine.can(submitEvent)
206
284
  Changes to `draftAtom` recompute acceptance. The event atom contains the event
207
285
  input itself rather than an `AsyncResult`.
208
286
 
287
+ `can` is `true` whenever the active configuration selects a transition. A
288
+ `{ none: true }` branch is a selected transition: it accepts the event without
289
+ changing state. A resolver that falls back to a `none` branch therefore keeps
290
+ the button enabled:
291
+
292
+ ```ts
293
+ // Before: an incomplete form still accepts Submitted, so `can` is true.
294
+ // In make: branches: { submit: { review: { target: "Reviewing" }, incomplete: { none: true } } }
295
+ Submitted: {
296
+ branches: "submit",
297
+ resolve: ({ state, select }) =>
298
+ state.email.length > 0 ? select.review() : select.incomplete()
299
+ }
300
+ ```
301
+
302
+ When the event must be refused, decline it. Use `guard` for an ordinary
303
+ transition, or `declinable: true` with `decline()` in a resolver:
304
+
305
+ ```ts
306
+ // After: an incomplete form declines Submitted, so `can` is false.
307
+ Submitted: { target: "Reviewing", guard: ({ state }) => state.email.length > 0 }
308
+
309
+ // A resolver that needs commands or construction declines explicitly.
310
+ // In make: branches: { submit: { review: { target: "Reviewing" } } }
311
+ Submitted: {
312
+ branches: "submit",
313
+ declinable: true,
314
+ resolve: ({ state, select, decline }) =>
315
+ state.email.length > 0 ? select.review() : decline()
316
+ }
317
+ ```
318
+
319
+ Keep `none` for events that are deliberately accepted and ignored. The
320
+ `effect-machine/no-conditional-none-branch` lint rule reports the conditional
321
+ fallback.
322
+
323
+ Query acceptance during render through `AtomMachine.can(event)(machine)`. Do
324
+ not call `Effect.runSync(Machine.can(...))` in a component: the atom shares the
325
+ running machine's snapshot, suspends during startup, and recomputes when the
326
+ snapshot changes.
327
+
209
328
  ## Whole-result and custom selections
210
329
 
211
330
  Reading the full result is correct when a component renders the complete
@@ -328,6 +447,45 @@ export const plantAtoms = AtomMachine.familyChild(CentralMachineAtom, {
328
447
  })
329
448
  ```
330
449
 
450
+ ## Generic helpers
451
+
452
+ Use `AtomMachine.MachineAtom.Any` and `AtomMachine.ChildMachineAtom.Any` to
453
+ accept any bridge, including bridges for machines without events. Recover the
454
+ exact types with the namespace extractors:
455
+
456
+ ```ts
457
+ function StateView<A extends AtomMachine.MachineAtom.Any>(props: {
458
+ readonly machine: A
459
+ readonly render: (state: AtomMachine.MachineAtom.State<A>) => React.ReactNode
460
+ }) {
461
+ const state = useAtomSuspense(props.machine.result).value
462
+ return props.render(state)
463
+ }
464
+
465
+ type AuthEvent = AtomMachine.MachineAtom.Event<typeof AuthMachineAtom>
466
+ type EditorState = AtomMachine.ChildMachineAtom.State<
467
+ AtomMachine.ChildOf<typeof AuthMachineAtom, typeof Editor>
468
+ >
469
+ ```
470
+
471
+ ## Keep workflow effects out of emissions
472
+
473
+ Emissions are ephemeral notifications for observers. They are not replayed, so
474
+ a subscriber that mounts late never sees an earlier emission. Do not drive work
475
+ the workflow depends on, such as navigation, from emissions. Invoke that work
476
+ from the state that requires it through a capability service, as in
477
+ [Per-owner capabilities](#per-owner-capabilities); the machine then decides when
478
+ it runs, what cancels it, and how failure changes the workflow.
479
+
480
+ An emission that only feeds UI feedback has two stream-atom details:
481
+
482
+ - `Atom.make(AtomMachine.emissions(machine))` publishes each emission as a
483
+ waiting `Success`, then publishes the last emission again, no longer waiting,
484
+ when the machine completes. Handlers must tolerate that repeated value.
485
+ - `useAtomSubscribe(atom, f)` subscribes after commit without reading the atom.
486
+ Pass `{ immediate: true }` so a lazy emissions atom starts; without it the
487
+ callback never runs. The callback then also receives the initial result.
488
+
331
489
  ## Registry and rendering semantics
332
490
 
333
491
  A `MachineAtom` identifies one machine per `AtomRegistry`. Passing the same
@@ -337,6 +495,44 @@ after its final subscription and configured idle retention expire.
337
495
  `registry.dispose()` stops it immediately.
338
496
 
339
497
  `useMachineAtom` does not start a machine during server rendering because
340
- React effects do not run on the server. Reading a machine atom during server
341
- render follows `@effect/atom-react` server-read behavior, so choose an explicit
342
- client boundary when server startup would be undesirable.
498
+ React effects do not run on the server. Server reads never start a machine
499
+ either. Every bridge atom carries an Effect Atom server value, which
500
+ `@effect/atom-react` hooks read during server rendering and hydration, and
501
+ `Atom.getServerValue` reads directly:
502
+
503
+ | Atom | Server value |
504
+ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
505
+ | `ref`, `send`, `stop` | `Initial` |
506
+ | `snapshot` | `Success({ status: "active", state })`, waiting |
507
+ | `result` | `Success(state)`, waiting |
508
+ | `select`, `selectSnapshot`, `matches`, `can` | the projection of `state`, waiting |
509
+ | `child(Child).result` and child projections | `Success(Option.some(childState))` when the planned state invokes `Child`, otherwise `Success(Option.none())` |
510
+ | `family` and `familyChild` projections | the server value of the projected bridge atom |
511
+
512
+ `state` is the machine's planned startup state: the state `Machine.planInitial`
513
+ settles into with the bridge's input, without running startup commands,
514
+ invocations, or services. A resumed bridge uses its resumed snapshot. Children
515
+ spawned at runtime or through child families are `Option.none()`. When the
516
+ startup state cannot be planned synchronously, for example because the input
517
+ is invalid, every server value is `Initial`. Each bridge plans at most once,
518
+ on its first server read.
519
+
520
+ ## Server rendering and hydration
521
+
522
+ Render state slots with `MachineState` and no Suspense boundary:
523
+
524
+ ```tsx
525
+ <Onboarding.Provider input={input}>
526
+ <MachineState machine={Onboarding.useMachine()} path="Editing">
527
+ {(editing) => <input value={editing.value.email} onChange={onChange} />}
528
+ </MachineState>
529
+ </Onboarding.Provider>
530
+ ```
531
+
532
+ The server renders the planned `Editing` snapshot. Hydration renders the same
533
+ markup, then the Provider mounts the machine and the same component tree
534
+ receives live snapshots. The input keeps its DOM node, typed text, and focus.
535
+
536
+ Do not wrap hydrated forms in a Suspense boundary that a startup read can
537
+ trigger. A suspended boundary replaces its server-rendered content with the
538
+ fallback and later mounts new DOM nodes, discarding typed text and focus.
@@ -11,10 +11,10 @@ patterns.
11
11
  Run the recommended rules from
12
12
  [`@typeonce/oxlint-plugin-effect-machine`](../../oxlint-plugin/README.md) before
13
13
  the manual review. They catch provable duplicate invocation identities,
14
- asynchronous work, browser access, nondeterminism, and redundant resolvers in
15
- direct same-module machine definitions. Continue with this review for
16
- cross-module ownership and architectural questions that syntax alone cannot
17
- answer.
14
+ asynchronous work, browser access, nondeterminism, redundant resolvers, and
15
+ conditional `none` fallbacks in direct same-module machine definitions.
16
+ Continue with this review for cross-module ownership and architectural
17
+ questions that syntax alone cannot answer.
18
18
 
19
19
  ## Review the responsibility boundaries
20
20
 
@@ -43,6 +43,12 @@ constructors derived from those declarations. Avoid an extra branch group for
43
43
  an ordinary transition. Use `reenter: true` when the source must restart.
44
44
  An empty targetless resolver simplifies to `{ none: true }`.
45
45
 
46
+ A `{ none: true }` branch accepts its event, so `Machine.can` and
47
+ `AtomMachine.can` return `true` when a resolver selects it. Review check: for
48
+ every event that enables or disables a control, refuse it with `guard` or with
49
+ `declinable: true` and `decline()`. Keep `none` only for events that are
50
+ deliberately accepted and ignored.
51
+
46
52
  ## Choose React ownership or keyed family lookup
47
53
 
48
54
  Use `useMachineAtom` when one React subtree owns the workflow, including a
@@ -187,6 +193,14 @@ Review check: search components, hooks, and atom modules for service calls,
187
193
  `Effect.run*`, promises, browser APIs, analytics, timers, and chains of `send`
188
194
  calls. Move workflow coordination into states, transitions, and invoked work.
189
195
 
196
+ Per-instance capabilities, such as a router or a component callback, are
197
+ services provided by the React owner, not schema fields or startup input. A
198
+ function in state data or input cannot be encoded by `Machine.encodeSnapshot`.
199
+ Review check: search schemas for `Schema.declare` guards that accept functions
200
+ and move each one to a service, as in
201
+ [Per-owner capabilities](./effect-atom-react.md#per-owner-capabilities). Do not
202
+ drive navigation or other workflow effects from emissions.
203
+
190
204
  ## Report findings
191
205
 
192
206
  For each issue, cite the file and line, name the violated boundary, and show the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typeonce/effect-machine",
3
- "version": "0.41.0",
3
+ "version": "0.42.0",
4
4
  "description": "Schema-first state machines and statecharts for Effect",
5
5
  "author": "Sandro Maglione",
6
6
  "repository": {
@@ -46,12 +46,12 @@
46
46
  "provenance": true
47
47
  },
48
48
  "peerDependencies": {
49
- "effect": "^4.0.5"
49
+ "effect": "^4.0.0"
50
50
  },
51
51
  "devDependencies": {
52
- "@effect/vitest": "4.0.5",
52
+ "@effect/vitest": "4.0.0",
53
53
  "@types/node": "25.7.0",
54
- "effect": "4.0.5",
54
+ "effect": "4.0.0",
55
55
  "tinybench": "2.9.0",
56
56
  "tstyche": "7.2.1",
57
57
  "typescript": "6.0.3",