import { Effect, Stream, Scope } from 'effect';
import { b as Cmd, P as Port, E as ErrorsOf, q as OkOfCmd, r as Owed, s as DeclaredErrorsOf, c as Sub, t as BuiltinSubType, B as BuiltinSub, M as Machine } from './core-sEWVgnpI.js';
import { d as DispatchOptions, C as CtxArg, a as StoreAndOnError, b as Supervision, T as TelemetrySink } from './runtime-types-f231H8Gq.js';
import { P as Postable } from './loop-CKqoteig.js';
import * as effect_Cause from 'effect/Cause';
import * as effect_Types from 'effect/Types';
declare const Stopped_base: new = {}>(args: effect_Types.VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => effect_Cause.YieldableError & {
readonly _tag: "Stopped";
} & Readonly;
/**
* A dispatch the run refused because it is stopping or has stopped. The Msg
* was never folded.
*
* `when` is `"stopping"` for a Msg that arrived while `stop()` (or a closing
* Scope) drained the run's in-flight work, and `"stopped"` once it had.
*/
declare class Stopped extends Stopped_base<{
readonly msgType: string;
readonly when: "stopping" | "stopped";
}> {
get message(): string;
}
declare const StoreFailed_base: new = {}>(args: effect_Types.VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => effect_Cause.YieldableError & {
readonly _tag: "StoreFailed";
} & Readonly;
/**
* The run's store failed. `operation` is `"load"` when the saved state could
* not be restored at boot — `cause` is then the `StoreRefusedError` that says
* why — and `"save"` when a transition's save threw, a fenced store's
* `StoreConflictError` included; `cause` is then the store's own throw.
*/
declare class StoreFailed extends StoreFailed_base<{
readonly operation: "load" | "save";
readonly cause: unknown;
}> {
get message(): string;
}
declare const SubFailed_base: new = {}>(args: effect_Types.VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => effect_Cause.YieldableError & {
readonly _tag: "SubFailed";
} & Readonly;
/**
* A Sub failed with an error it did not map to a Msg, and that stopped the run
* before it reached a terminal State. `cause` is what the Sub failed with, the
* value `onError` heard under `"sub"`. Only `done()` fails with it.
*/
declare class SubFailed extends SubFailed_base<{
readonly cause: unknown;
}> {
get message(): string;
}
/**
* The Effect engine's run handle (#308, ruling R4.1 of #325). Its members have
* the Promise engine's names (the shared-handle ruling of #250); only the
* return types differ. Each member that returns a Promise there returns an
* Effect here, with a typed error channel a host reads with `Effect.catchTags`.
* Members that neither wait nor fail — `getState`, `result` and the listener
* registrations — are the same functions on both engines.
*/
/**
* What the Effect engine's `run` yields while boot is in flight. `Err` is the
* union of the declared failures of the run's hand-written cells: a dispatch
* whose Cmd's cell fails with one fails with it. Reading State and waiting for
* quiescence need boot to have run, so they live on the {@link EffectRuntime}
* that `ready` succeeds with.
*/
interface EffectBootingRuntime {
/**
* Fold `msg` and run to quiescence, as the Promise engine's `dispatch` does.
* Fails with `Stopped` once the run is stopping or stopped, `StoreFailed`
* when the transition's save fails, and a hand-written cell's declared
* failure when the transition's Cmd fails with one.
*/
dispatch(msg: M, opts?: DispatchOptions): Effect.Effect;
/** `dispatch(msg, { settle: "once" })`: one transition, no follow-up drain. */
dispatchOnce(msg: M, opts?: DispatchOptions): Effect.Effect;
/**
* A zero-arg change notifier, fired for each applied transition after its
* save and before its first Cmd's handler starts.
*/
subscribe(listener: () => void): () => void;
/**
* A `(msg, state, cmds)` hook, fired after each applied transition's Cmds,
* with the Cmds that transition started.
*/
observe(observer: (msg: M, state: S, cmds?: readonly Cmd[]) => void): () => void;
/** Fires once with the initial State — at once if boot already ran. */
onBoot(handler: (state: S) => void): () => void;
/** Subscribe to the semantic event of `_tag` the run's `events` projects. */
on(type: K, handler: (event: Extract) => void): () => void;
/** Subscribe to a typed Port. */
subscribePort(port: Port, listener: (value: T) => void): () => void;
/** Emit a value on a Port from outside a Cmd handler. */
emitPort(port: Port, value: T): void;
/**
* Succeeds with the booted handle once boot completes. Fails with
* `StoreFailed` when the saved state could not be restored (`"load"`) or the
* initial save failed (`"save"`), and with a hand-written cell's declared
* failure when a boot Cmd fails with one.
*/
readonly ready: Effect.Effect, Err | StoreFailed>;
/**
* Stop the run: drain in-flight work, up to `disposeTimeoutMs`, stop its
* Subs, flush the final State. `stop()` interrupts every handler still in
* flight, so the limit is reached only by a handler that cannot be
* interrupted. Closing the run's Scope stops the run the same way, and
* `stop()` leaves that Scope open. So for a child under `spawn` the two
* differ: `stop()` does not take the child out of the host's table or tell
* the parent. Stop such a child with the `stop` helper.
*/
stop(): Effect.Effect;
}
/**
* The Effect engine's booted handle. `ready` on a real run succeeds with an
* {@link EffectRun}, which is one of these and carries what `tell` asks for.
*/
interface EffectRuntime extends EffectBootingRuntime {
/** The current State. Total. */
getState(): S;
readonly ready: Effect.Effect, Err | StoreFailed>;
/** Succeeds once every dispatched Msg and its follow-ups are processed. */
idle(): Effect.Effect;
/**
* The saved terminal State, or `undefined` while its save is pending or failed.
* Without a store, answers as soon as State is set. A run a failure closed
* reads `undefined` here; `done()` says why.
*/
result(): S | undefined;
/**
* Succeeds with the terminal State only once it is saved. When a failure
* closes the run short of a terminal State, it fails with that failure, for
* waiting and later callers: a failed terminal save with `StoreFailed`
* (`operation: "save"`), a Sub failure with `SubFailed`, and a reducer throw
* under the `stop` strategy with a defect, the thrown value itself. The defect
* is outside the error channel, so `Effect.catchTags` does not see it and
* `Effect.catchDefect` or the fiber's `Exit` does. The Msgs already in line
* fold first, so one of them reaching a terminal State makes that State the
* answer. A terminal State already saved keeps its answer whatever fails
* after it. A `stop()` with no failure leaves this waiting. Without a store,
* answers as soon as State is set.
*/
done(): Effect.Effect;
}
/**
* The handle `run` yields: an {@link EffectBootingRuntime} whose `ready` succeeds
* with an {@link EffectRun}. It does not compile as `tell`'s argument: wait for
* `ready`.
*/
interface EffectBootingRun extends EffectBootingRuntime {
readonly ready: Effect.Effect, Err | StoreFailed>;
}
/**
* What an {@link EffectBootingRun}'s `ready` succeeds with: a booted
* {@link EffectRuntime} that also carries the run's line, which is what `tell`
* asks for. A spread keeps the line. An object built by hand cannot have one,
* because tea does not export its key, so an {@link EffectRuntime} that is not one
* of these does not compile as `tell`'s argument. It fits anywhere an
* `EffectRuntime` is asked for.
*/
interface EffectRun extends EffectRuntime, Postable {
readonly ready: Effect.Effect, Err | StoreFailed>;
}
/**
* The Effect engine's `run` (#283): the same machine the Promise engine runs,
* with Effect handlers, Effect sub runners, the caller's Layers and
* interruption on stop.
*
* It runs the one core loop both engines share (`src/internal/engine/loop.ts`)
* with the same built-ins in the same order, so a machine folds the same way on
* either engine. What this file adds is the Effect edge:
*
* - an `interpret` cell returns `Effect`, read with
* `Effect.result`: a success settles `_ok`, a declared failure settles
* `_err`, a defect goes to the error sink;
* - a `subscribe` runner returns a `Stream`, drained on its own fiber;
* - every handler and runner fiber runs with the services the caller
* provided, so `R` reaches them from the caller's Layers;
* - stopping interrupts every handler fiber still in flight;
* - the handle's verbs are Effects with a typed error channel
* (`./handle`, `./failures`).
*/
/**
* One Effect `interpret` cell. For a `Cmd.define`d Cmd it succeeds with the
* Cmd's `Ok` and fails with one of its declared tags, and the engine mints
* `_ok` / `_err` from that (ADR 0021). For a hand-written Cmd it
* succeeds with a follow-up Msg, a list of them (dispatched in order), or
* nothing, and its failure fails the dispatch with that error, typed on the
* handle (see {@link CellErrors}). `R` is whatever services it reads.
*/
type EffectInterpretCell = unknown extends ErrorsOf ? (cmd: C, ctx?: unknown) => Effect.Effect : (cmd: C, ctx?: unknown) => Effect.Effect | Owed, DeclaredErrorsOf, R>;
/**
* The Effect engine's `interpret` map: one cell per Cmd variant, each reading
* services within `R`.
*/
type EffectInterpret = {
readonly [K in C["_tag"]]: EffectInterpretCell, R>;
};
/**
* One Effect sub runner: the Sub in, a `Stream` of Msgs out. The engine drains
* it on its own fiber and interrupts that fiber when the Sub stops.
*
* A Sub maps the errors it expects into Msgs itself, the way an Elm `Sub msg`
* carries no error type: `Stream.catchTag("Closed", () => Stream.make({ _tag:
* "disconnected" }))`. A stream that still fails reaches the error sink under
* `"sub"` and stops the run (#309), and `done()` fails with `SubFailed`.
*/
type EffectRunner = (sub: U) => Stream.Stream;
/**
* The Effect engine's `subscribe` map: a runner for every Sub type the machine
* declares beyond the built-ins, and optionally one for a built-in, which
* replaces the engine's own (#270 R2.1).
*/
type EffectSubscribe = {
readonly [K in Exclude]: EffectRunner, R>;
} & {
readonly [K in BuiltinSubType]?: EffectRunner, {
_tag: K;
}>, R>;
};
/** The services every cell of an `interpret` map reads. */
type InterpretServices = {
[K in keyof I]: ServicesOfCell;
}[keyof I];
type ServicesOfCell = F extends (cmd: never) => Effect.Effect ? R : never;
/**
* The failures a dispatch on the handle can end with from an `interpret` map:
* the error type of every hand-written Cmd's cell. A `Cmd.define`d Cmd's
* declared failure settles its `_err` Msg instead, so it adds nothing here.
*/
type CellErrors = {
[K in keyof I & C["_tag"]]: unknown extends ErrorsOf> ? ErrorOfCell : never;
}[keyof I & C["_tag"]];
type ErrorOfCell = F extends (cmd: never) => Effect.Effect ? Err : never;
/** The services every runner of a `subscribe` map reads. */
type SubscribeServices = {
[K in keyof B]-?: ServicesOfRunner>;
}[keyof B];
type ServicesOfRunner = F extends (sub: never) => Stream.Stream ? R : never;
type InterpretOption = [C] extends [Cmd] ? {
readonly interpret?: I;
} : {
readonly interpret: I;
};
type SubscribeOption = [
Exclude
] extends [never] ? {
readonly subscribe?: B;
} : {
readonly subscribe: B;
};
/**
* The options of the Effect engine's `run`. Beside `interpret` and
* `subscribe`, they are the Promise engine's, with the same meaning; see `run`
* in `@demlik/tea/promise` for each one's contract.
*/
type EffectRunOptions = CtxArg & InterpretOption & SubscribeOption & StoreAndOnError & {
/** Stamps `at` on minted Msgs and telemetry. Defaults to `Date.now`. */
readonly clock?: () => number;
/** Projects each applied transition to the public events `on` serves. */
readonly events?: (msg: M, state: S) => readonly E[];
/** The policy for a reducer throw. Defaults to `"stop"`. */
readonly supervision?: Supervision;
/** The terminal predicate `result()` and `done()` read. */
readonly terminal?: (state: S) => boolean;
/** A fire-and-forget sink for every applied transition. */
readonly telemetry?: TelemetrySink;
/**
* How long `stop()` waits for the queue, and then for async teardown,
* before giving up on each. Defaults to 5_000ms. `stop()` interrupts every
* handler here, so the first wait ends early unless a handler cannot be
* interrupted.
*
* A store call is not interrupted. tea starts none after `stop()` has
* returned, but one already under way when `stop()` gave up can finish
* after it. A fenced store refuses that late save, and so does
* `doEventSourcedStore` once a newer run has loaded its log. A custom
* plain store that waits before it writes takes it over what a newer run
* saved, unless it checks at its own write point. So a host that starts a
* new run on the same store after a `stop()` that gave up needs one of the
* first two.
*/
readonly disposeTimeoutMs?: number;
/** `"restored"`: this start is a wake; see `run` in `@demlik/tea/promise`. */
readonly boot?: "restored";
};
/**
* Run `machine` on the Effect engine. The returned Effect needs a `Scope` and
* the services its handlers and runners read, and yields the run handle. The
* handle's members have the Promise engine's names; the ones that return a
* Promise there return an Effect here, failing with `Stopped`, `StoreFailed`
* or a hand-written cell's declared failure, so a host sorts them with
* `Effect.catchTags`.
*
* Closing the scope stops the run and its Subs: every handler still in flight
* is interrupted (its finalizers run), its Msg is never dispatched, and a
* dispatch after stop fails with `Stopped`. The handle's `stop()` does the
* same.
*
* A Sub whose Stream fails with an error it did not map to a Msg stops this run
* alone. The run forks its own child of that scope and closes only the child,
* so the rest of the scope stays open, and `done()` fails with `SubFailed`. A
* handler or runner that reads `Scope.Scope` gets that child, so what it acquires
* is released with the run. With no `onError`, the default sink still rethrows
* the failure and ends the process. A reducer throw under the default `stop`
* strategy closes that same child, so the run stops and `done()` fails with
* what was thrown, as a defect (ADR 0033).
*
* A fenced store is fenced here exactly as on the Promise engine: the check is
* one of the built-ins both engines run. A run on a store that is fenced at
* runtime with no `onError` dies at start, before anything is loaded, even when
* the store is typed plain `Store` (ADR 0031).
*
* ```ts
* const program = Effect.gen(function* () {
* const handle = yield* run(machine, {
* interpret: {
* fetch: (cmd) =>
* Effect.gen(function* () {
* const api = yield* Api;
* return yield* api.get(cmd.id);
* }),
* },
* });
* const runtime = yield* handle.ready;
* yield* runtime.dispatch({ _tag: "go", id: "7" });
* return runtime.getState();
* });
* Effect.runPromise(program.pipe(Effect.scoped, Effect.provide(ApiLive)));
* ```
*/
declare function run = EffectInterpret, B extends EffectSubscribe = EffectSubscribe, E extends {
_tag: string;
} = never>(machine: Machine, opts: EffectRunOptions): Effect.Effect>, never, Scope.Scope | InterpretServices | SubscribeServices>;
export { type CellErrors as C, type EffectInterpret as E, type InterpretServices as I, type SubscribeOption as S, type EffectSubscribe as a, type SubscribeServices as b, type EffectRun as c, type InterpretOption as d, type EffectBootingRun as e, type EffectBootingRuntime as f, type EffectInterpretCell as g, type EffectRunOptions as h, type EffectRunner as i, type EffectRuntime as j, Stopped as k, StoreFailed as l, SubFailed as m, run as r };