effect-machine 0.12.0 → 0.14.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 (53) hide show
  1. package/README.md +133 -324
  2. package/dist/actor.d.ts +46 -28
  3. package/dist/actor.js +276 -315
  4. package/dist/cluster/entity-machine.d.ts +1 -1
  5. package/dist/cluster/entity-machine.js +20 -9
  6. package/dist/cluster/to-entity.d.ts +3 -3
  7. package/dist/errors.d.ts +24 -20
  8. package/dist/errors.js +10 -6
  9. package/dist/index.d.ts +5 -4
  10. package/dist/index.js +3 -2
  11. package/dist/internal/runtime.d.ts +82 -7
  12. package/dist/internal/runtime.js +162 -58
  13. package/dist/internal/transition.d.ts +12 -11
  14. package/dist/internal/transition.js +12 -14
  15. package/dist/machine.d.ts +148 -140
  16. package/dist/machine.js +141 -155
  17. package/dist/schema.d.ts +14 -0
  18. package/dist/schema.js +10 -1
  19. package/dist/slot.d.ts +112 -86
  20. package/dist/slot.js +92 -59
  21. package/dist/supervision.d.ts +97 -0
  22. package/dist/supervision.js +42 -0
  23. package/dist/testing.d.ts +21 -12
  24. package/dist/testing.js +23 -26
  25. package/package.json +7 -7
  26. package/v3/dist/actor.d.ts +53 -30
  27. package/v3/dist/actor.js +286 -311
  28. package/v3/dist/cluster/entity-machine.d.ts +1 -1
  29. package/v3/dist/cluster/entity-machine.js +5 -5
  30. package/v3/dist/cluster/to-entity.d.ts +1 -1
  31. package/v3/dist/errors.d.ts +14 -10
  32. package/v3/dist/errors.js +11 -7
  33. package/v3/dist/index.d.ts +6 -5
  34. package/v3/dist/index.js +3 -2
  35. package/v3/dist/inspection.d.ts +3 -22
  36. package/v3/dist/inspection.js +1 -15
  37. package/v3/dist/internal/brands.d.ts +4 -8
  38. package/v3/dist/internal/inspection.js +1 -1
  39. package/v3/dist/internal/runtime.d.ts +87 -10
  40. package/v3/dist/internal/runtime.js +177 -61
  41. package/v3/dist/internal/transition.d.ts +13 -12
  42. package/v3/dist/internal/transition.js +14 -16
  43. package/v3/dist/internal/utils.js +5 -1
  44. package/v3/dist/machine.d.ts +158 -143
  45. package/v3/dist/machine.js +148 -155
  46. package/v3/dist/schema.d.ts +25 -11
  47. package/v3/dist/schema.js +18 -5
  48. package/v3/dist/slot.d.ts +112 -86
  49. package/v3/dist/slot.js +92 -59
  50. package/v3/dist/supervision.d.ts +97 -0
  51. package/v3/dist/supervision.js +42 -0
  52. package/v3/dist/testing.d.ts +21 -12
  53. package/v3/dist/testing.js +23 -24
@@ -65,7 +65,7 @@ declare const EntityMachine: {
65
65
  readonly _tag: string;
66
66
  }, E extends {
67
67
  readonly _tag: string;
68
- }, R, EntityType extends string, Rpcs extends Rpc.Any>(entity: Entity.Entity<EntityType, Rpcs>, machine: Machine<S, E, R, any, any, any, any>, options?: EntityMachineOptions<S, E>) => Layer.Layer<never, never, R>;
68
+ }, R, EntityType extends string, Rpcs extends Rpc.Any>(entity: Entity.Entity<EntityType, Rpcs>, machine: Machine<S, E, R, any, any, any>, options?: EntityMachineOptions<S, E>) => Layer.Layer<never, never, R>;
69
69
  };
70
70
  //#endregion
71
71
  export { EntityMachine, EntityMachineOptions };
@@ -1,8 +1,8 @@
1
- import { BuiltMachine, replay } from "../machine.js";
2
- import { ActorSystem, makeSystem } from "../actor.js";
1
+ import { replay } from "../machine.js";
3
2
  import { createRuntime } from "../internal/runtime.js";
3
+ import { ActorSystem, makeSystem } from "../actor.js";
4
4
  import { PersistenceAdapter } from "./persistence.js";
5
- import { Effect, Option, Queue, Ref, Stream, SubscriptionRef } from "effect";
5
+ import { Clock, Effect, Option, Queue, Ref, Stream, SubscriptionRef } from "effect";
6
6
  import { Entity } from "effect/unstable/cluster";
7
7
  //#region src/cluster/entity-machine.ts
8
8
  /**
@@ -46,9 +46,19 @@ const EntityMachine = { layer: (entity, machine, options) => {
46
46
  enumerable: true
47
47
  } }) : machine;
48
48
  const versionRef = yield* Ref.make(persistCtx.initialVersion);
49
+ const computedInitial = initialState ?? machine.initial;
50
+ const stateRef = yield* SubscriptionRef.make(computedInitial);
51
+ const stoppedRef = yield* Ref.make(false);
52
+ const eventQueue = yield* Queue.unbounded();
49
53
  const runtime = yield* createRuntime(machineWithState, system, {
50
54
  actorId: entityId,
51
- hooks: options?.hooks
55
+ hooks: options?.hooks,
56
+ childIdPrefix: `${entityId}/`,
57
+ cellResources: {
58
+ stateRef,
59
+ stoppedRef,
60
+ eventQueue
61
+ }
52
62
  });
53
63
  if (persistCtx.adapter !== void 0) {
54
64
  const { adapter: pAdapter, key } = persistCtx;
@@ -56,19 +66,21 @@ const EntityMachine = { layer: (entity, machine, options) => {
56
66
  const schedule = persistence?.snapshotSchedule;
57
67
  if (strategy === "snapshot") yield* SubscriptionRef.changes(runtime.stateRef).pipe(schedule !== void 0 ? Stream.schedule(schedule) : (s) => s, Stream.runForEach((state) => Effect.gen(function* () {
58
68
  const version = yield* Ref.get(versionRef);
69
+ const now = yield* Clock.currentTimeMillis;
59
70
  yield* pAdapter.saveSnapshot(key, {
60
71
  state,
61
72
  version,
62
- timestamp: Date.now()
73
+ timestamp: now
63
74
  });
64
75
  }).pipe(Effect.catch(() => Effect.void))), Effect.forkScoped);
65
76
  yield* Effect.addFinalizer(() => Effect.gen(function* () {
66
77
  const state = yield* SubscriptionRef.get(runtime.stateRef);
67
78
  const version = yield* Ref.get(versionRef);
79
+ const now = yield* Clock.currentTimeMillis;
68
80
  yield* pAdapter.saveSnapshot(key, {
69
81
  state,
70
82
  version,
71
- timestamp: Date.now()
83
+ timestamp: now
72
84
  });
73
85
  }).pipe(Effect.catch(() => Effect.void)));
74
86
  }
@@ -138,8 +150,7 @@ const hydratePersistence = (persistence, entityDef, entityId, machine, initializ
138
150
  const snapshotVersion = Option.isSome(maybeSnapshot) ? maybeSnapshot.value.version : 0;
139
151
  const events = yield* adapter.loadEvents(key, snapshotVersion);
140
152
  if (events.length > 0) {
141
- const eventValues = events.map((e) => e.event);
142
- const hydratedState = yield* replay(new BuiltMachine(machine), eventValues, { from: baseState });
153
+ const hydratedState = yield* replay(machine, events.map((e) => e.event), { from: baseState });
143
154
  const lastEvent = events[events.length - 1];
144
155
  return {
145
156
  adapter,
@@ -183,7 +194,7 @@ const persistEvent = (adapter, key, versionRef, event) => Effect.gen(function* (
183
194
  const persisted = {
184
195
  event,
185
196
  version: newVersion,
186
- timestamp: Date.now()
197
+ timestamp: yield* Clock.currentTimeMillis
187
198
  };
188
199
  yield* adapter.appendEvents(key, [persisted], expectedVersion);
189
200
  yield* Ref.set(versionRef, newVersion);
@@ -2,7 +2,7 @@ import { Machine } from "../machine.js";
2
2
  import { Schema } from "effect";
3
3
  import { Entity } from "effect/unstable/cluster";
4
4
  import { Rpc } from "effect/unstable/rpc";
5
- import * as effect_unstable_rpc_RpcSchema0 from "effect/unstable/rpc/RpcSchema";
5
+ import * as _$effect_unstable_rpc_RpcSchema0 from "effect/unstable/rpc/RpcSchema";
6
6
 
7
7
  //#region src/cluster/to-entity.d.ts
8
8
  /**
@@ -61,10 +61,10 @@ declare const toEntity: <S extends {
61
61
  readonly _tag: string;
62
62
  }, E extends {
63
63
  readonly _tag: string;
64
- }, R>(machine: Machine<S, E, R, any, any, any, any>, options: ToEntityOptions) => Entity.Entity<string, Rpc.Rpc<"Send", Schema.Struct<{
64
+ }, R>(machine: Machine<S, E, R, any, any, any>, options: ToEntityOptions) => Entity.Entity<string, Rpc.Rpc<"Send", Schema.Struct<{
65
65
  event: Schema.Schema<E>;
66
66
  }>, Schema.Schema<S>, Schema.Never, never, never> | Rpc.Rpc<"Ask", Schema.Struct<{
67
67
  event: Schema.Schema<E>;
68
- }>, Schema.Unknown, Schema.Never, never, never> | Rpc.Rpc<"GetState", Schema.Void, Schema.Schema<S>, Schema.Never, never, never> | Rpc.Rpc<"WatchState", Schema.Void, effect_unstable_rpc_RpcSchema0.Stream<Schema.Schema<S>, Schema.Never>, Schema.Never, never, never>>;
68
+ }>, Schema.Unknown, Schema.Never, never, never> | Rpc.Rpc<"GetState", Schema.Void, Schema.Schema<S>, Schema.Never, never, never> | Rpc.Rpc<"WatchState", Schema.Void, _$effect_unstable_rpc_RpcSchema0.Stream<Schema.Schema<S>, Schema.Never>, Schema.Never, never, never>>;
69
69
  //#endregion
70
70
  export { EntityRpcs, ToEntityOptions, toEntity };
package/dist/errors.d.ts CHANGED
@@ -1,68 +1,72 @@
1
1
  import { Schema } from "effect";
2
- import * as effect_Cause0 from "effect/Cause";
2
+ import * as _$effect_Cause0 from "effect/Cause";
3
3
 
4
4
  //#region src/errors.d.ts
5
5
  declare const DuplicateActorError_base: Schema.ErrorClass<DuplicateActorError, Schema.TaggedStruct<"DuplicateActorError", {
6
6
  readonly actorId: Schema.String;
7
- }>, effect_Cause0.YieldableError>;
7
+ }>, _$effect_Cause0.YieldableError>;
8
8
  /** Attempted to spawn/restore actor with ID already in use */
9
9
  declare class DuplicateActorError extends DuplicateActorError_base {}
10
- declare const UnprovidedSlotsError_base: Schema.ErrorClass<UnprovidedSlotsError, Schema.TaggedStruct<"UnprovidedSlotsError", {
11
- readonly slots: Schema.$Array<Schema.String>;
12
- }>, effect_Cause0.YieldableError>;
13
- /** Machine has unprovided effect slots */
14
- declare class UnprovidedSlotsError extends UnprovidedSlotsError_base {}
15
10
  declare const MissingSchemaError_base: Schema.ErrorClass<MissingSchemaError, Schema.TaggedStruct<"MissingSchemaError", {
16
11
  readonly operation: Schema.String;
17
- }>, effect_Cause0.YieldableError>;
12
+ }>, _$effect_Cause0.YieldableError>;
18
13
  /** Operation requires schemas attached to machine */
19
14
  declare class MissingSchemaError extends MissingSchemaError_base {}
20
- declare const InvalidSchemaError_base: Schema.ErrorClass<InvalidSchemaError, Schema.TaggedStruct<"InvalidSchemaError", {}>, effect_Cause0.YieldableError>;
15
+ declare const InvalidSchemaError_base: Schema.ErrorClass<InvalidSchemaError, Schema.TaggedStruct<"InvalidSchemaError", {
16
+ readonly message: Schema.String;
17
+ }>, _$effect_Cause0.YieldableError>;
21
18
  /** State/Event schema has no variants */
22
19
  declare class InvalidSchemaError extends InvalidSchemaError_base {}
23
20
  declare const MissingMatchHandlerError_base: Schema.ErrorClass<MissingMatchHandlerError, Schema.TaggedStruct<"MissingMatchHandlerError", {
24
21
  readonly tag: Schema.String;
25
- }>, effect_Cause0.YieldableError>;
22
+ }>, _$effect_Cause0.YieldableError>;
26
23
  /** $match called with missing handler for tag */
27
24
  declare class MissingMatchHandlerError extends MissingMatchHandlerError_base {}
28
25
  declare const SlotProvisionError_base: Schema.ErrorClass<SlotProvisionError, Schema.TaggedStruct<"SlotProvisionError", {
29
26
  readonly slotName: Schema.String;
30
- readonly slotType: Schema.Literals<readonly ["guard", "effect"]>;
31
- }>, effect_Cause0.YieldableError>;
27
+ readonly slotType: Schema.Literal<"slot">;
28
+ }>, _$effect_Cause0.YieldableError>;
32
29
  /** Slot handler not found at runtime (internal error) */
33
30
  declare class SlotProvisionError extends SlotProvisionError_base {}
34
31
  declare const ProvisionValidationError_base: Schema.ErrorClass<ProvisionValidationError, Schema.TaggedStruct<"ProvisionValidationError", {
35
32
  readonly missing: Schema.$Array<Schema.String>;
36
33
  readonly extra: Schema.$Array<Schema.String>;
37
- }>, effect_Cause0.YieldableError>;
38
- /** Machine.build() validation failed - missing or extra handlers */
34
+ }>, _$effect_Cause0.YieldableError>;
35
+ /** Slot provision validation failed missing or extra handlers */
39
36
  declare class ProvisionValidationError extends ProvisionValidationError_base {}
40
37
  declare const AssertionError_base: Schema.ErrorClass<AssertionError, Schema.TaggedStruct<"AssertionError", {
41
38
  readonly message: Schema.String;
42
- }>, effect_Cause0.YieldableError>;
39
+ }>, _$effect_Cause0.YieldableError>;
43
40
  /** Assertion failed in testing utilities */
44
41
  declare class AssertionError extends AssertionError_base {}
45
42
  declare const ActorStoppedError_base: Schema.ErrorClass<ActorStoppedError, Schema.TaggedStruct<"ActorStoppedError", {
46
43
  readonly actorId: Schema.String;
47
- }>, effect_Cause0.YieldableError>;
44
+ }>, _$effect_Cause0.YieldableError>;
48
45
  /** Actor was stopped while a call/ask was pending */
49
46
  declare class ActorStoppedError extends ActorStoppedError_base {}
50
47
  declare const NoReplyError_base: Schema.ErrorClass<NoReplyError, Schema.TaggedStruct<"NoReplyError", {
51
48
  readonly actorId: Schema.String;
52
49
  readonly eventTag: Schema.String;
53
- }>, effect_Cause0.YieldableError>;
50
+ }>, _$effect_Cause0.YieldableError>;
54
51
  /** ask() was used but the transition handler did not call reply */
55
52
  declare class NoReplyError extends NoReplyError_base {}
56
53
  declare const PersistenceError_base: Schema.ErrorClass<PersistenceError, Schema.TaggedStruct<"PersistenceError", {
57
54
  readonly message: Schema.String;
58
- }>, effect_Cause0.YieldableError>;
55
+ }>, _$effect_Cause0.YieldableError>;
59
56
  /** Persistence adapter operation failed */
60
57
  declare class PersistenceError extends PersistenceError_base {}
58
+ declare const SlotCodecError_base: Schema.ErrorClass<SlotCodecError, Schema.TaggedStruct<"SlotCodecError", {
59
+ readonly slotName: Schema.String;
60
+ readonly phase: Schema.Literals<readonly ["input", "output"]>;
61
+ readonly message: Schema.String;
62
+ }>, _$effect_Cause0.YieldableError>;
63
+ /** Slot input/output schema validation failed */
64
+ declare class SlotCodecError extends SlotCodecError_base {}
61
65
  declare const VersionConflictError_base: Schema.ErrorClass<VersionConflictError, Schema.TaggedStruct<"VersionConflictError", {
62
66
  readonly expected: Schema.Number;
63
67
  readonly actual: Schema.Number;
64
- }>, effect_Cause0.YieldableError>;
68
+ }>, _$effect_Cause0.YieldableError>;
65
69
  /** Optimistic locking failure — stored version doesn't match expected */
66
70
  declare class VersionConflictError extends VersionConflictError_base {}
67
71
  //#endregion
68
- export { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, SlotProvisionError, UnprovidedSlotsError, VersionConflictError };
72
+ export { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, SlotCodecError, SlotProvisionError, VersionConflictError };
package/dist/errors.js CHANGED
@@ -12,20 +12,18 @@ import { Schema } from "effect";
12
12
  */
13
13
  /** Attempted to spawn/restore actor with ID already in use */
14
14
  var DuplicateActorError = class extends Schema.TaggedErrorClass()("DuplicateActorError", { actorId: Schema.String }) {};
15
- /** Machine has unprovided effect slots */
16
- var UnprovidedSlotsError = class extends Schema.TaggedErrorClass()("UnprovidedSlotsError", { slots: Schema.Array(Schema.String) }) {};
17
15
  /** Operation requires schemas attached to machine */
18
16
  var MissingSchemaError = class extends Schema.TaggedErrorClass()("MissingSchemaError", { operation: Schema.String }) {};
19
17
  /** State/Event schema has no variants */
20
- var InvalidSchemaError = class extends Schema.TaggedErrorClass()("InvalidSchemaError", {}) {};
18
+ var InvalidSchemaError = class extends Schema.TaggedErrorClass()("InvalidSchemaError", { message: Schema.String }) {};
21
19
  /** $match called with missing handler for tag */
22
20
  var MissingMatchHandlerError = class extends Schema.TaggedErrorClass()("MissingMatchHandlerError", { tag: Schema.String }) {};
23
21
  /** Slot handler not found at runtime (internal error) */
24
22
  var SlotProvisionError = class extends Schema.TaggedErrorClass()("SlotProvisionError", {
25
23
  slotName: Schema.String,
26
- slotType: Schema.Literals(["guard", "effect"])
24
+ slotType: Schema.Literal("slot")
27
25
  }) {};
28
- /** Machine.build() validation failed - missing or extra handlers */
26
+ /** Slot provision validation failed missing or extra handlers */
29
27
  var ProvisionValidationError = class extends Schema.TaggedErrorClass()("ProvisionValidationError", {
30
28
  missing: Schema.Array(Schema.String),
31
29
  extra: Schema.Array(Schema.String)
@@ -41,10 +39,16 @@ var NoReplyError = class extends Schema.TaggedErrorClass()("NoReplyError", {
41
39
  }) {};
42
40
  /** Persistence adapter operation failed */
43
41
  var PersistenceError = class extends Schema.TaggedErrorClass()("PersistenceError", { message: Schema.String }) {};
42
+ /** Slot input/output schema validation failed */
43
+ var SlotCodecError = class extends Schema.TaggedErrorClass()("SlotCodecError", {
44
+ slotName: Schema.String,
45
+ phase: Schema.Literals(["input", "output"]),
46
+ message: Schema.String
47
+ }) {};
44
48
  /** Optimistic locking failure — stored version doesn't match expected */
45
49
  var VersionConflictError = class extends Schema.TaggedErrorClass()("VersionConflictError", {
46
50
  expected: Schema.Number,
47
51
  actual: Schema.Number
48
52
  }) {};
49
53
  //#endregion
50
- export { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, SlotProvisionError, UnprovidedSlotsError, VersionConflictError };
54
+ export { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, SlotCodecError, SlotProvisionError, VersionConflictError };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { EffectHandlers, EffectSlot, EffectSlots, EffectsDef, EffectsSchema, GuardHandlers, GuardSlot, GuardSlots, GuardsDef, GuardsSchema, MachineContext, Slot } from "./slot.js";
2
1
  import { DeferReplyResult, ReplyResult } from "./internal/utils.js";
3
2
  import { Event, MachineEventSchema, MachineStateSchema, ReplyFields, State } from "./schema.js";
4
- import { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, ProvisionValidationError, SlotProvisionError, UnprovidedSlotsError } from "./errors.js";
3
+ import { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, SlotCodecError, SlotProvisionError, VersionConflictError } from "./errors.js";
4
+ import { HasSlotKeys, MachineContext, ProvideSlots, Slot, SlotCall, SlotCalls, SlotFnDef, SlotHandler, SlotInvocation, SlotRequest, SlotResult, SlotsDef, SlotsSchema } from "./slot.js";
5
+ import { ActorExit, CellPhase, DefectPhase, Supervision } from "./supervision.js";
5
6
  import { ProcessEventResult } from "./internal/transition.js";
6
- import { BackgroundEffect, BuiltMachine, HandlerContext, Machine, MachineRef, MakeConfig, ProvideHandlers, SpawnEffect, StateHandlerContext, TaskOptions, Transition, machine_d_exports } from "./machine.js";
7
+ import { BackgroundEffect, HandlerContext, Machine, MachineRef, MakeConfig, SpawnEffect, StateHandlerContext, TaskOptions, TimeoutConfig, Transition, machine_d_exports } from "./machine.js";
7
8
  import { ActorRef, ActorRefSync, ActorSystem, Default, SystemEvent, SystemEventListener, TransitionInfo } from "./actor.js";
8
9
  import { SimulationResult, TestHarness, TestHarnessOptions, assertNeverReaches, assertPath, assertReaches, createTestHarness, simulate } from "./testing.js";
9
10
  import { AnyInspectionEvent, EffectEvent, ErrorEvent, EventReceivedEvent, InspectionEvent, Inspector, InspectorHandler, SpawnEvent, StopEvent, TaskEvent, TracingInspectorOptions, TransitionEvent, collectingInspector, combineInspectors, consoleInspector, makeInspector, makeInspectorEffect, tracingInspector } from "./inspection.js";
10
- export { type ActorRef, type ActorRefSync, ActorStoppedError, type ActorSystem, Default as ActorSystemDefault, ActorSystem as ActorSystemService, type AnyInspectionEvent, AssertionError, type BackgroundEffect, type BuiltMachine, type DeferReplyResult, DuplicateActorError, type EffectEvent, type EffectSlots, type EffectsDef, type EffectsSchema, type ErrorEvent, Event, type EventReceivedEvent, type GuardHandlers, type GuardSlot, type GuardSlots, type GuardsDef, type GuardsSchema, type HandlerContext, type InspectionEvent, type Inspector, type InspectorHandler, Inspector as InspectorService, InvalidSchemaError, machine_d_exports as Machine, type MachineContext, type MachineEventSchema, type MachineRef, type MachineStateSchema, type Machine as MachineType, type MakeConfig, MissingMatchHandlerError, MissingSchemaError, NoReplyError, type ProcessEventResult, type ProvideHandlers, ProvisionValidationError, type ReplyFields, type ReplyResult, type SimulationResult, Slot, type EffectHandlers as SlotEffectHandlers, type EffectSlot as SlotEffectSlot, SlotProvisionError, type SpawnEffect, type SpawnEvent, State, type StateHandlerContext, type StopEvent, type SystemEvent, type SystemEventListener, type TaskEvent, type TaskOptions, type TestHarness, type TestHarnessOptions, type TracingInspectorOptions, type Transition, type TransitionEvent, type TransitionInfo, UnprovidedSlotsError, assertNeverReaches, assertPath, assertReaches, collectingInspector, combineInspectors, consoleInspector, createTestHarness, makeInspector, makeInspectorEffect, simulate, tracingInspector };
11
+ export { ActorExit, type ActorRef, type ActorRefSync, ActorStoppedError, type ActorSystem, Default as ActorSystemDefault, ActorSystem as ActorSystemService, type AnyInspectionEvent, AssertionError, type BackgroundEffect, type CellPhase, type DefectPhase, type DeferReplyResult, DuplicateActorError, type EffectEvent, type ErrorEvent, Event, type EventReceivedEvent, type HandlerContext, type HasSlotKeys, type InspectionEvent, type Inspector, type InspectorHandler, Inspector as InspectorService, InvalidSchemaError, machine_d_exports as Machine, type MachineContext, type MachineEventSchema, type MachineRef, type MachineStateSchema, type Machine as MachineType, type MakeConfig, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, type ProcessEventResult, type ProvideSlots, ProvisionValidationError, type ReplyFields, type ReplyResult, type SimulationResult, Slot, type SlotCall, type SlotCalls, SlotCodecError, type SlotFnDef, type SlotHandler, type SlotInvocation, SlotProvisionError, type SlotRequest, type SlotResult, type SlotsDef, type SlotsSchema, type SpawnEffect, type SpawnEvent, State, type StateHandlerContext, type StopEvent, Supervision, type SystemEvent, type SystemEventListener, type TaskEvent, type TaskOptions, type TestHarness, type TestHarnessOptions, type TimeoutConfig, type TracingInspectorOptions, type Transition, type TransitionEvent, type TransitionInfo, VersionConflictError, assertNeverReaches, assertPath, assertReaches, collectingInspector, combineInspectors, consoleInspector, createTestHarness, makeInspector, makeInspectorEffect, simulate, tracingInspector };
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
+ import { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, SlotCodecError, SlotProvisionError, VersionConflictError } from "./errors.js";
1
2
  import { Inspector, collectingInspector, combineInspectors, consoleInspector, makeInspector, makeInspectorEffect, tracingInspector } from "./inspection.js";
2
- import { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, ProvisionValidationError, SlotProvisionError, UnprovidedSlotsError } from "./errors.js";
3
3
  import { Slot } from "./slot.js";
4
4
  import { machine_exports } from "./machine.js";
5
+ import { ActorExit, Supervision } from "./supervision.js";
5
6
  import { ActorSystem, Default } from "./actor.js";
6
7
  import { Event, State } from "./schema.js";
7
8
  import { assertNeverReaches, assertPath, assertReaches, createTestHarness, simulate } from "./testing.js";
8
- export { ActorStoppedError, Default as ActorSystemDefault, ActorSystem as ActorSystemService, AssertionError, DuplicateActorError, Event, Inspector as InspectorService, InvalidSchemaError, machine_exports as Machine, MissingMatchHandlerError, MissingSchemaError, NoReplyError, ProvisionValidationError, Slot, SlotProvisionError, State, UnprovidedSlotsError, assertNeverReaches, assertPath, assertReaches, collectingInspector, combineInspectors, consoleInspector, createTestHarness, makeInspector, makeInspectorEffect, simulate, tracingInspector };
9
+ export { ActorExit, ActorStoppedError, Default as ActorSystemDefault, ActorSystem as ActorSystemService, AssertionError, DuplicateActorError, Event, Inspector as InspectorService, InvalidSchemaError, machine_exports as Machine, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, Slot, SlotCodecError, SlotProvisionError, State, Supervision, VersionConflictError, assertNeverReaches, assertPath, assertReaches, collectingInspector, combineInspectors, consoleInspector, createTestHarness, makeInspector, makeInspectorEffect, simulate, tracingInspector };
@@ -1,9 +1,10 @@
1
- import { EffectsDef, GuardsDef, MachineContext } from "../slot.js";
2
1
  import { NoReplyError } from "../errors.js";
3
- import { ProcessEventHooks } from "./transition.js";
2
+ import { MachineContext, SlotsDef } from "../slot.js";
3
+ import { ActorExit } from "../supervision.js";
4
+ import { ProcessEventHooks, ProcessEventResult } from "./transition.js";
4
5
  import { Machine, MachineRef } from "../machine.js";
5
6
  import { ActorSystem } from "../actor.js";
6
- import { Deferred, Effect, Queue, Scope, SubscriptionRef } from "effect";
7
+ import { Deferred, Effect, Queue, Ref, Scope, SubscriptionRef } from "effect";
7
8
 
8
9
  //#region src/internal/runtime.d.ts
9
10
  /** @internal */
@@ -14,11 +15,30 @@ type RuntimeQueuedEvent<E> = {
14
15
  readonly _tag: "sendWait";
15
16
  readonly event: E;
16
17
  readonly done: Deferred.Deferred<void, unknown>;
18
+ } | {
19
+ readonly _tag: "call";
20
+ readonly event: E;
21
+ readonly reply: Deferred.Deferred<ProcessEventResult<{
22
+ readonly _tag: string;
23
+ }>, unknown>;
17
24
  } | {
18
25
  readonly _tag: "ask";
19
26
  readonly event: E;
20
27
  readonly reply: Deferred.Deferred<unknown, NoReplyError>;
28
+ } | {
29
+ readonly _tag: "drain";
30
+ readonly done: Deferred.Deferred<void, never>;
21
31
  };
32
+ /**
33
+ * Resources owned by the actor cell (stable across generations).
34
+ * When provided, createRuntime uses these instead of allocating its own.
35
+ * @internal
36
+ */
37
+ interface RuntimeCellResources<S, E> {
38
+ readonly stateRef: SubscriptionRef.SubscriptionRef<S>;
39
+ readonly eventQueue: Queue.Queue<RuntimeQueuedEvent<E>>;
40
+ readonly stoppedRef: Ref.Ref<boolean>;
41
+ }
22
42
  /** @internal */
23
43
  interface RuntimeHandle<S, E> {
24
44
  /** Enqueue a fire-and-forget event */
@@ -35,26 +55,81 @@ interface RuntimeHandle<S, E> {
35
55
  readonly isStopped: Effect.Effect<boolean>;
36
56
  /** Stop the runtime (interrupt event loop, clean up) */
37
57
  readonly stop: Effect.Effect<void>;
58
+ /** @internal — raw event queue for direct enqueue (actor.ts uses this for pendingReplies tracking) */
59
+ readonly _queue: Queue.Queue<RuntimeQueuedEvent<E>>;
60
+ /** @internal — stopped ref for direct access */
61
+ readonly _stoppedRef: Ref.Ref<boolean>;
62
+ /**
63
+ * Exit deferred — set exactly once with the exit reason when the runtime stops.
64
+ * Final state → ActorExit.Final, explicit stop → ActorExit.Stopped, defect → ActorExit.Defect.
65
+ */
66
+ readonly exitDeferred: Deferred.Deferred<ActorExit<S>, never>;
67
+ /**
68
+ * Actor scope — owns background fibers for this generation.
69
+ * Closing this scope interrupts all background fibers.
70
+ */
71
+ readonly actorScope: Scope.Closeable;
72
+ }
73
+ /** @internal */
74
+ interface RuntimeLifecycleHooks<S, E> {
75
+ /** Before processEventCore — actor emits @machine.event inspection */
76
+ readonly onEvent?: (state: S, event: E) => Effect.Effect<void>;
77
+ /** After SubscriptionRef.set on transition — actor notifies listeners, annotates spans */
78
+ readonly onStateChange?: (result: ProcessEventResult<S>, event: E) => Effect.Effect<void>;
79
+ /** After reply settlement when transition occurred — actor publishes to transitionsPubSub */
80
+ readonly onProcessed?: (result: ProcessEventResult<S>, event: E) => Effect.Effect<void>;
81
+ /** When final state detected in event loop — actor emits @machine.stop */
82
+ readonly onFinal?: (state: S) => Effect.Effect<void>;
83
+ /** Before stop resource cleanup — actor emits @machine.stop, settles pending replies */
84
+ readonly onShutdown?: () => Effect.Effect<void>;
85
+ /** Before initial spawn effects — actor emits @machine.effect inspection */
86
+ readonly onInitialSpawnEffects?: (state: S) => Effect.Effect<void>;
38
87
  }
39
88
  /** @internal */
40
89
  interface RuntimeConfig<S, E> {
41
90
  readonly actorId: string;
42
91
  readonly hooks?: ProcessEventHooks<S, E>;
92
+ /**
93
+ * Cell-owned resources. When provided, the runtime uses the cell's stateRef,
94
+ * eventQueue, and stoppedRef instead of creating its own.
95
+ * Used by actor.ts for supervision (cell owns stable resources across generations).
96
+ */
97
+ readonly cellResources?: RuntimeCellResources<S, E>;
43
98
  /**
44
99
  * Custom queue factory. Default: `Queue.unbounded()`.
45
100
  * Use `Queue.sliding(n)` or `Queue.dropping(n)` for bounded queues.
101
+ * Ignored when cellResources is provided.
46
102
  */
47
103
  readonly queueFactory?: Effect.Effect<Queue.Queue<RuntimeQueuedEvent<E>>>;
104
+ /** Lifecycle callbacks for actor-specific concerns */
105
+ readonly lifecycle?: RuntimeLifecycleHooks<S, E>;
106
+ /** Wrap each processQueued invocation — actor uses for span annotations */
107
+ readonly wrapProcess?: (state: S, event: E, inner: Effect.Effect<ProcessQueuedResult<S>>) => Effect.Effect<ProcessQueuedResult<S>>;
108
+ /** Called after self.spawn succeeds — actor tracks children */
109
+ readonly onChildSpawned?: (childId: string, child: unknown) => Effect.Effect<void>;
110
+ /** Skip registering stop as scope finalizer — actor manages its own lifecycle */
111
+ readonly skipFinalizer?: boolean;
112
+ /** Prefix for child actor IDs in self.spawn. Entity-machine uses `${actorId}/`. Default: no prefix. */
113
+ readonly childIdPrefix?: string;
114
+ }
115
+ /** @internal */
116
+ interface ProcessQueuedResult<S> {
117
+ readonly shouldStop: boolean;
118
+ readonly stateChanged: boolean;
119
+ readonly result: ProcessEventResult<S>;
48
120
  }
49
121
  /**
50
122
  * Create a runtime for a machine. Returns a handle for sending events
51
123
  * and querying state. The runtime owns:
52
- * - Single event queue (all events serialized)
53
124
  * - Event loop fiber
54
125
  * - Postpone buffer
55
- * - Background effects
126
+ * - Background effects (under actorScope)
56
127
  * - State scope (spawn effects)
57
128
  * - Final state detection
129
+ * - Exit reason via exitDeferred
130
+ *
131
+ * Resources (stateRef, eventQueue, stoppedRef) are either cell-provided
132
+ * or allocated fresh by the runtime.
58
133
  *
59
134
  * @internal
60
135
  */
@@ -62,6 +137,6 @@ declare const createRuntime: <S extends {
62
137
  readonly _tag: string;
63
138
  }, E extends {
64
139
  readonly _tag: string;
65
- }, R, GD extends GuardsDef, EFD extends EffectsDef>(machine: Machine<S, E, R, any, any, GD, EFD>, system: ActorSystem, config: RuntimeConfig<S, E>) => Effect.Effect<RuntimeHandle<S, E>, never, Scope.Scope | Exclude<R, MachineContext<S, E, MachineRef<E>>> | Exclude<Exclude<R, MachineContext<S, E, MachineRef<E>>>, Scope.Scope>>;
140
+ }, R, SD extends SlotsDef>(machine: Machine<S, E, R, any, any, SD>, system: ActorSystem, config: RuntimeConfig<S, E>) => Effect.Effect<RuntimeHandle<S, E>, never, Scope.Scope | Exclude<R, MachineContext<S, E, MachineRef<E>>> | Exclude<Exclude<R, MachineContext<S, E, MachineRef<E>>>, Scope.Scope>>;
66
141
  //#endregion
67
- export { RuntimeConfig, RuntimeHandle, RuntimeQueuedEvent, createRuntime };
142
+ export { ProcessQueuedResult, RuntimeCellResources, RuntimeConfig, RuntimeHandle, RuntimeLifecycleHooks, RuntimeQueuedEvent, createRuntime };