On this pageFunctions
Update
/**
* Defines an update while inferring the union of services required by the
* Commands returned across all Message branches. If a branch emits an
* OutMessage, the returned function has a ReturnWithOutMessage
* contract so a parent must handle it. Otherwise it has a Return
* contract. Required, optional, and rest context parameters are preserved in
* the returned function.
*
* Use this when Command implementations come from Layers, so application
* completion can infer every required handler service without a hand-written
* requirements union:
*
* ```ts
* export const update = Update.define((model: Model, message: Message) =>
* Message.match(message, {
* ClickedSave: () => ({ model, commands: [Save()] }),
* CompletedSave: () => ({ model }),
* }),
* )
* ```
*/
<Update extends AnyUpdate>(update: Update & ValidateUpdate<Update>): DefinedUpdate<Parameters<Update>, Parameters<Update>[0], Parameters<Update>[1], OutMessageOf<ReturnOf<Update>>, CommandRequirements<ReturnOf<Update>>, RegistrationEvidenceOf<ReturnOf<Update>>>/**
* Defines an update Step while inferring its Message and service
* requirements from the Commands it returns. If a branch emits an OutMessage,
* the returned function has a StepWithOutMessage contract. Optional
* and rest context parameters after the Model are preserved.
*
* Use this for standalone Step producers, including OutMessage folds, whose
* Commands come from handler Layers:
*
* ```ts
* const foldSavedDraft = OutMessage.match({
* SavedDraft: () => Update.defineStep((model: Model) => ({
* model,
* commands: [RefreshDraft()],
* })),
* })
* ```
*/
<Step extends AnyStep>(step: Step & ValidateStep<Step>): DefinedStep<Parameters<Step>, Parameters<Step>[0], CommandMessage<ReturnOf<Step>>, OutMessageOf<ReturnOf<Step>>, CommandRequirements<ReturnOf<Step>>, RegistrationEvidenceOf<ReturnOf<Step>>>/**
* Turns a Refreshable into an update step that revalidates one
* cache: read the entry, ask `revalidate` whether it should transition,
* and only when it says yes write the transitioned state and emit the
* load Command. When `revalidate` returns `None` (a missing entry, or a
* state with nothing to revalidate) the step returns `{ model }`: same
* Model, no Command. A handler can list every affected cache, and only the
* caches that currently hold data reload.
*
* ```ts
* const refreshAllNotes = refresh({
* read: model => Option.some(model.allNotes),
* revalidate: AsyncData.revalidate,
* write: (model, nextAllNotes) => modifyFields(model, { allNotes: () => nextAllNotes }),
* load: LoadAllNotes(),
* })
* ```
*/
<Model, Message, A, E, R = never>(refreshable: Refreshable<Model, Message, A, E, R>): Step<Model, Message, R>/**
* The four capabilities that fold one child Block's update into the
* parent, for a child whose update cannot emit an OutMessage.
*
* - `update`: the child update function to run.
* - `read`: the getter half of the lens onto the child: reads the child
* Model from the parent Model. Returns an `Option` because a child
* may not be mounted (for example a page behind a route or a keyed
* collection miss); a single always-present field wraps in
* `Option.some`.
* - `write`: the setter half of the lens: writes the updated child
* Model back into the parent Model.
* - `toParentMessage`: lifts a child Message into the parent's Message,
* the same contract `h.block` takes for the view half. Always the
* child's `Got*` wrapper: `message => GotSearchMessage({ message })`.
*/
type ChildFold = Readonly<{
read: (model: ParentModel) => Option.Option<ChildModel>
toParentMessage: (message: ChildMessage) => ParentMessage
update: (childModel: ChildModel, input: Input) => Return<ChildModel, ChildMessage, R>
write: (model: ParentModel, nextChildModel: ChildModel) => ParentModel
}>/**
* Configuration for foldChildAt when the child emits no
* OutMessage. The key selects the child Model for `readAt` and `writeAt`.
* `toParentMessage` receives the same key when wrapping child Messages.
*/
type ChildFoldAt = Readonly<{
readAt: (model: ParentModel, key: Key) => Option.Option<ChildModel>
toParentMessage: (key: Key, message: ChildMessage) => ParentMessage
update: (childModel: ChildModel, input: Input) => Return<ChildModel, ChildMessage, R>
writeAt: (model: ParentModel, key: Key, nextChildModel: ChildModel) => ParentModel
}>/**
* ChildFoldAtWithOutMessage for a parent that derives its own
* OutMessage while handling the child's OutMessage.
*/
type ChildFoldAtWithDerivedParentOutMessage = Readonly<{
foldOutMessage: (key: Key, context: FoldContext<ChildMessage, ParentMessage>) => (outMessage: ChildOutMessage) => StepWithOutMessage<NoInfer<ParentModel>, OutMessageStepMessage, ParentOutMessage, OutMessageStepRequirements>
readAt: (model: ParentModel, key: Key) => Option.Option<ChildModel>
toParentMessage: (key: Key, message: ChildMessage) => ParentMessage
toParentOutMessage: never
update: (childModel: ChildModel, input: Input) => ReturnWithOutMessage<ChildModel, ChildMessage, ChildOutMessage, ChildRequirements>
writeAt: (model: ParentModel, key: Key, nextChildModel: ChildModel) => ParentModel
}>/**
* ChildFoldAt for a child that emits OutMessages handled locally.
* `foldOutMessage` takes the key and a FoldContext for lifting child
* Commands. It returns a matcher whose handlers produce parent Steps.
*/
type ChildFoldAtWithOutMessage = Readonly<{
foldOutMessage: (key: Key, context: FoldContext<ChildMessage, ParentMessage>) => (outMessage: ChildOutMessage) => Step<NoInfer<ParentModel>, OutMessageStepMessage, OutMessageStepRequirements>
readAt: (model: ParentModel, key: Key) => Option.Option<ChildModel>
toParentMessage: (key: Key, message: ChildMessage) => ParentMessage
update: (childModel: ChildModel, input: Input) => ReturnWithOutMessage<ChildModel, ChildMessage, ChildOutMessage, ChildRequirements>
writeAt: (model: ParentModel, key: Key, nextChildModel: ChildModel) => ParentModel
}>/**
* ChildFoldAtWithOutMessage for a parent that forwards at least one
* child OutMessage to its own parent. `toParentOutMessage` takes the key and
* returns a matcher that produces parent OutMessages. Return `undefined` for
* named child variants that should not reach the current Block's parent.
* If `foldOutMessage` derives a parent OutMessage, it takes precedence over
* forwarding.
*/
type ChildFoldAtWithParentOutMessage = Readonly<{
foldOutMessage: (key: Key, context: FoldContext<ChildMessage, ParentMessage>) => (outMessage: ChildOutMessage) => StepWithOutMessage<NoInfer<ParentModel>, OutMessageStepMessage, DerivedParentOutMessage, OutMessageStepRequirements>
readAt: (model: ParentModel, key: Key) => Option.Option<ChildModel>
toParentMessage: (key: Key, message: ChildMessage) => ParentMessage
toParentOutMessage: (key: Key) => (outMessage: ChildOutMessage) => ParentOutMessage | undefined
update: (childModel: ChildModel, input: Input) => ReturnWithOutMessage<ChildModel, ChildMessage, ChildOutMessage, ChildRequirements>
writeAt: (model: ParentModel, key: Key, nextChildModel: ChildModel) => ParentModel
}>/**
* ChildFoldWithOutMessage for a parent that derives its own
* OutMessage while folding the child's. The returned
* StepWithOutMessage receives the parent Model with the child already
* written back. Use this shape when no child OutMessage is forwarded one to
* one, so the fold needs no `toParentOutMessage` adapter.
*/
type ChildFoldWithDerivedParentOutMessage = Readonly<{
foldOutMessage: (outMessage: ChildOutMessage, context: FoldContext<ChildMessage, ParentMessage>) => StepWithOutMessage<NoInfer<ParentModel>, OutMessageStepMessage, ParentOutMessage, OutMessageStepRequirements>
read: (model: ParentModel) => Option.Option<ChildModel>
toParentMessage: (message: ChildMessage) => ParentMessage
toParentOutMessage: never
update: (childModel: ChildModel, input: Input) => ReturnWithOutMessage<ChildModel, ChildMessage, ChildOutMessage, ChildRequirements>
write: (model: ParentModel, nextChildModel: ChildModel) => ParentModel
}>/**
* ChildFold for a child whose update returns
* ReturnWithOutMessage, adding the fifth capability:
*
* - `foldOutMessage`: folds the child's OutMessage into the parent as a
* Step. The Step receives the parent Model with the child
* already written back, and its Commands follow the child's in the
* returned batch. Match on the OutMessage tag through its union matcher,
* and build a multi-step fold with combineSteps. Takes an optional
* second parameter, a
* FoldContext of lifters bound to `toParentMessage`, for a
* Command the Step returns whose result is the child's Message. Parent Model
* inference comes from `read` and `write`; the child wrapper and OutMessage
* Step infer their Message and service requirements independently, and the
* resulting Fold requires their unions.
*/
type ChildFoldWithOutMessage = Readonly<{
foldOutMessage: (outMessage: ChildOutMessage, context: FoldContext<ChildMessage, ParentMessage>) => Step<NoInfer<ParentModel>, OutMessageStepMessage, OutMessageStepRequirements>
read: (model: ParentModel) => Option.Option<ChildModel>
toParentMessage: (message: ChildMessage) => ParentMessage
update: (childModel: ChildModel, input: Input) => ReturnWithOutMessage<ChildModel, ChildMessage, ChildOutMessage, ChildRequirements>
write: (model: ParentModel, nextChildModel: ChildModel) => ParentModel
}>/**
* ChildFoldWithOutMessage for a parent that is itself a
* Block, so the fold can return the parent's own OutMessage. Adds:
*
* - `toParentOutMessage`: lifts the child's OutMessage into the
* parent's own OutMessage. Return `undefined` for a named child variant
* that stops at this parent. When the child returns no OutMessage, the fold
* omits `outMessage`.
* - `foldOutMessage` stays available for a parent that also updates
* its own state from the child's OutMessage, and is optional here.
* It may emit a derived parent OutMessage. That OutMessage replaces the
* one-to-one lift for the dispatch. When the Step emits nothing, the lift
* runs as usual.
*
* Use this shape only when at least one child OutMessage should continue to
* the current Block's parent. If every child OutMessage stops here, use
* ChildFoldWithDerivedParentOutMessage when the fold derives its own
* OutMessage, or ChildFoldWithOutMessage when it does not. When
* provided, `foldOutMessage` still handles each variant locally, including
* variants that continue upward.
*/
type ChildFoldWithParentOutMessage = Readonly<{
foldOutMessage: (outMessage: ChildOutMessage, context: FoldContext<ChildMessage, ParentMessage>) => StepWithOutMessage<NoInfer<ParentModel>, OutMessageStepMessage, DerivedParentOutMessage, OutMessageStepRequirements>
read: (model: ParentModel) => Option.Option<ChildModel>
toParentMessage: (message: ChildMessage) => ParentMessage
toParentOutMessage: (outMessage: ChildOutMessage) => ParentOutMessage | undefined
update: (childModel: ChildModel, input: Input) => ReturnWithOutMessage<ChildModel, ChildMessage, ChildOutMessage, ChildRequirements>
write: (model: ParentModel, nextChildModel: ChildModel) => ParentModel
}>/**
* ChildFold for an entry point that takes nothing but the child
* Model, such as `Dialog.close` or a Block's `informRouteChanged` that
* derives everything it needs from its own state. There is no `input`, so
* foldChildStep returns the Step itself rather than a dual
* Fold.
*/
type ChildStepFold = Readonly<{
read: (model: ParentModel) => Option.Option<ChildModel>
toParentMessage: (message: ChildMessage) => ParentMessage
update: (childModel: ChildModel) => Return<ChildModel, ChildMessage, R>
write: (model: ParentModel, nextChildModel: ChildModel) => ParentModel
}>/**
* ChildStepFoldWithOutMessage for a parent that derives its own
* OutMessage while folding the child's. This is the no-argument counterpart
* to ChildFoldWithDerivedParentOutMessage.
*/
type ChildStepFoldWithDerivedParentOutMessage = Readonly<{
foldOutMessage: (outMessage: ChildOutMessage, context: FoldContext<ChildMessage, ParentMessage>) => StepWithOutMessage<NoInfer<ParentModel>, OutMessageStepMessage, ParentOutMessage, OutMessageStepRequirements>
read: (model: ParentModel) => Option.Option<ChildModel>
toParentMessage: (message: ChildMessage) => ParentMessage
toParentOutMessage: never
update: (childModel: ChildModel) => ReturnWithOutMessage<ChildModel, ChildMessage, ChildOutMessage, ChildRequirements>
write: (model: ParentModel, nextChildModel: ChildModel) => ParentModel
}>/**
* ChildStepFold for an entry point whose return carries the child's
* OutMessage channel, adding `foldOutMessage`. It behaves exactly as it does
* in ChildFoldWithOutMessage, down to the optional second parameter,
* a FoldContext of lifters bound to `toParentMessage`, and combines
* the child update and OutMessage Step Message and service requirements.
*/
type ChildStepFoldWithOutMessage = Readonly<{
foldOutMessage: (outMessage: ChildOutMessage, context: FoldContext<ChildMessage, ParentMessage>) => Step<NoInfer<ParentModel>, OutMessageStepMessage, OutMessageStepRequirements>
read: (model: ParentModel) => Option.Option<ChildModel>
toParentMessage: (message: ChildMessage) => ParentMessage
update: (childModel: ChildModel) => ReturnWithOutMessage<ChildModel, ChildMessage, ChildOutMessage, ChildRequirements>
write: (model: ParentModel, nextChildModel: ChildModel) => ParentModel
}>/**
* ChildStepFoldWithOutMessage for a parent that is itself a
* Block. `toParentOutMessage` turns the child's OutMessage into the
* parent's OutMessage. Return `undefined` for a named child variant that
* stops at this parent. `foldOutMessage` remains available when the parent
* also updates its own state from the child's OutMessage. A derived
* OutMessage from that Step replaces the one-to-one lift for the dispatch.
* When the Step emits nothing, the lift runs as usual.
*
* Use this shape only when at least one child OutMessage should continue to
* the current Block's parent. If every child OutMessage stops here, use
* ChildStepFoldWithDerivedParentOutMessage when the fold derives its
* own OutMessage, or ChildStepFoldWithOutMessage when it does not.
* When provided, `foldOutMessage` still handles each variant locally,
* including variants that continue upward.
*/
type ChildStepFoldWithParentOutMessage = Readonly<{
foldOutMessage: (outMessage: ChildOutMessage, context: FoldContext<ChildMessage, ParentMessage>) => StepWithOutMessage<NoInfer<ParentModel>, OutMessageStepMessage, DerivedParentOutMessage, OutMessageStepRequirements>
read: (model: ParentModel) => Option.Option<ChildModel>
toParentMessage: (message: ChildMessage) => ParentMessage
toParentOutMessage: (outMessage: ChildOutMessage) => ParentOutMessage | undefined
update: (childModel: ChildModel) => ReturnWithOutMessage<ChildModel, ChildMessage, ChildOutMessage, ChildRequirements>
write: (model: ParentModel, nextChildModel: ChildModel) => ParentModel
}>/**
* The Commands collection an update return may include. The collection keeps
* the order in which the update returned them, but the runtime forks the
* Commands independently. `R` is the services the Commands need and defaults
* to `never` for updates without service requirements.
*
* Name an alias when a module reuses the same Message and service types:
*
* ```ts
* export type Commands = Update.Commands<Message, AppServices>
* ```
*/
type Commands = ReadonlyArray<Command<Message, never, R>>/**
* The normalized function contract returned by defineStep. It
* preserves the Step's full parameter list while deriving its Message,
* Command requirements, OutMessage channel, and child registration evidence
* from the return type.
*/
type DefinedStep = (args: Arguments) => WithRegistrationEvidence<[OutMessage] extends [never]
? Return<Model, Message, R>
: ReturnWithOutMessage<Model, Message, OutMessage, R>, Evidence>/**
* The normalized function contract returned by define. It preserves
* the update's full parameter list while deriving its Command requirements,
* OutMessage channel, and child registration evidence from the return type.
*/
type DefinedUpdate = (args: Arguments) => WithRegistrationEvidence<[OutMessage] extends [never]
? Return<Model, Message, R>
: ReturnWithOutMessage<Model, Message, OutMessage, R>, Evidence>/**
* The dual function foldChild returns. Data-first runs the
* fold now (`fold(model, input)` returns a Return); data-last
* builds a composable Step (`fold(input)`, for
* combineSteps).
*/
type Fold = (model: ParentModel, input: Input) => Return<ParentModel, ParentMessage, R>/**
* Fold for one child addressed by key. Data-first runs the fold
* now (`fold(model, key, input)`). Data-last builds a composable
* Step (`fold(key, input)`, for combineSteps).
*/
type FoldAt = (model: ParentModel, key: Key, input: Input) => Return<ParentModel, ParentMessage, R>/** FoldAt whose result can carry the parent OutMessage. */
type FoldAtWithOutMessage = (model: ParentModel, key: Key, input: Input) => ReturnWithOutMessage<ParentModel, ParentMessage, ParentOutMessage, R>/**
* The lifters a `foldOutMessage` receives as its second parameter,
* already bound to the fold config's `toParentMessage`.
*
* The fold already lifts the Commands returned by the child's `update`.
* Use these lifters for a Command returned by the parent's OutMessage Step
* when that Command still produces the child's Message. For example, the
* parent may handle a child's `Requested*` fact by returning a child Command
* built with routing context only the parent holds.
*
* The lifters apply the same lift the fold gives the child's own
* Commands, so the Step writes no `Command.mapMessage` call and keeps
* no second copy of the wrapper, and the mapping stays recorded on the
* Command for `Story.Command.resolve` and `Scene.Command.resolve`.
*
* The annotated standalone const takes both parameters, so pass the
* OutMessage value to its union matcher:
*
* ```ts
* const foldLoginOutMessage = (
* outMessage: Login.OutMessage,
* { liftCommand }: Update.FoldContext<Login.Message, Message>,
* ) =>
* Login.OutMessage.match<Update.Step<Model, Message>>(outMessage, {
* RequestedMagicLink:
* ({ email }) =>
* model => ({
* model,
* commands: [
* liftCommand(
* Login.SendMagicLink({ email, redirectRoute: model.route }),
* ),
* ],
* }),
* })
* ```
*/
type FoldContext = Readonly<{
liftCommand: (command: Command<ChildMessage, E, R>) => Command<ParentMessage, E, R>
liftCommands: (commands: ReadonlyArray<Command<ChildMessage, E, R>>) => ReadonlyArray<Command<ParentMessage, E, R>>
}> & [ParentModel] extends [never]
? unknown
: Readonly<{
modelBeforeUpdate: ParentModel
}>/**
* Fold for a ChildFoldWithParentOutMessage: the
* data-first form returns a ReturnWithOutMessage and the
* data-last form builds a StepWithOutMessage, so the fold slots
* directly into a parent that is itself a Block.
*/
type FoldWithOutMessage = (model: ParentModel, input: Input) => ReturnWithOutMessage<ParentModel, ParentMessage, ParentOutMessage, R>/**
* The four capabilities that make one cache field revalidatable.
*
* - `read`: gets the field's AsyncData out of the Model. Returns an
* `Option` because keyed caches miss (`HashMap.get`); single fields
* wrap in `Option.some`.
* - `revalidate`: decides whether and how the entry transitions.
* Usually exactly `AsyncData.revalidate` (refresh after a mutation:
* only `Success` and `Stale` move to `Refreshing`). Pass
* `AsyncData.revalidateOrLoad` instead for load-on-entry semantics.
* - `write`: puts the transitioned entry back into the Model.
* - `load`: the Command that refetches the data.
*/
type Refreshable = Readonly<{
load: Command<Message, never, R>
read: (model: Model) => Option.Option<AsyncData<A, E>>
revalidate: (current: AsyncData<A, E>) => Option.Option<AsyncData<A, E>>
write: (model: Model, next: AsyncData<A, E>) => Model
}>/**
* Type-level proof that an update result uses a child Binding registered in its
* owning Composition. It adds no Effect service requirement at runtime.
*/
type RegistrationEvidence = Readonly<{
[RegistrationEvidenceTypeId]: () => Evidence
}>/**
* Extracts child Binding registration evidence retained by an update result or
* its Commands. A raw Binding operation reports its direct child registration;
* policy-produced registrations remain an opaque obligation until a completed
* Composition resolves them against its registered graph.
*/
type RegistrationEvidenceOf = Value extends DeferredUpdateEvidence<any, any, any, infer Evidence>
? ConcreteRegistrationPart<Evidence>
: ConcreteRegistrationPart<DirectResultEvidenceChannelOf<Value>> | Value extends unknown
? "commands" extends keyof Value
? Value extends Readonly<{
commands: infer CommandValues
}>
? ConcreteRegistrationPart<DirectResultEvidenceChannelOf<NonNullable<CommandValues>>>
: never
: never
: never/**
* The Effect services required by the Commands an update can return. This
* reads the update's return contract, including requirements carried through
* child folds, without including services used only by Subscriptions, Mounts,
* or ManagedResources. A raw Binding operation reports direct child Command
* requirements. Policy-produced requirements become visible after a completed
* Composition resolves the operation against its registered graph.
*/
type RequirementsOf = CommandRequirements<ReturnOf<Update>>/**
* The record an update returns when it cannot emit an OutMessage: the next
* Model and any Commands to run.
*
* Inline the type when a matcher is its only use:
*
* ```ts
* export const update = (model: Model, message: Message) =>
* Message.match<Update.Return<Model, Message>>(message, {
* ClickedSave: () => ({ model, commands: [Save()] }),
* SucceededSave: ({ note }) => ({
* model: modifyFields(model, { note: () => note }),
* }),
* })
* ```
*
* Give it a local `UpdateReturn` alias when another matcher or helper in the
* module needs the same type. When Commands use handler Layers, wrap the
* update with define to infer their requirements across branches.
* An explicit `Return<Model, Message>` annotation fixes `R` to `never`.
*
* A graph-connected Step instead retains an opaque ResultRecipe
* until checked composition applies it.
*/
type Return = Readonly<{
commands: Commands<Message, R> & NoRegistrationEvidence
model: Model
outMessage: never
}> & NoRegistrationEvidence/**
* The return shape of an update that can also surface an OutMessage to its
* parent. Omit `commands` when the update statically creates none. Return a
* computed Commands collection directly, even when it may be empty. Omit
* `outMessage` when the update emitted nothing. A Block that cannot emit
* an OutMessage returns Return instead. A graph-connected Step retains
* an opaque ResultRecipe until checked composition applies it.
*/
type ReturnWithOutMessage = Readonly<{
commands: Commands<Message, R> & NoRegistrationEvidence
model: Model
outMessage: OutMessage
}> & NoRegistrationEvidence/**
* An update result that retains child Binding registration evidence alongside
* its Model, Commands, and optional OutMessage.
*/
type ReturnWithRegistrationEvidence = Readonly<{
commands: Commands<Message, R> & RegistrationEvidence<Evidence>
model: Model
outMessage: OutMessage
}> & RegistrationEvidence<Evidence>/**
* One self-contained edit to the Model paired with the Commands to run:
* the unit combineSteps composes. A step that needs arguments is a
* function returning a Step
* (`(noteId: NoteId) => Update.Step<Model, Message>`).
*/
type Step = (model: Model) => Return<Model, Message, R>/**
* Step for an update that also surfaces an OutMessage to its
* parent: maps a Model to a ReturnWithOutMessage over the same
* Model.
*/
type StepWithOutMessage = (model: Model) => ReturnWithOutMessage<Model, Message, OutMessage, R>/**
* Preserves child Binding registration evidence on an update result and its
* Commands.
*/
type WithRegistrationEvidence = Value extends unknown
? [Evidence] extends [never]
? Value
: ReturnWithRegistrationEvidence<RegistrationModelOf<Value>, RegistrationCommandMessageOf<Value>, RegistrationOutMessageOf<Value>, RegistrationCommandRequirementsOf<Value>, Evidence>
: never/**
* Carries the exact registered Binding graph available to a Composition callback.
* Connected Steps require this capability on their Model input.
* Apply them inside the Composition's `makeUpdate` or `makeInit` callback.
* To define a reusable Step before composition, return the connected Step from
* `Definition.makeStep`, or return `Update.combineSteps(steps)` for several Steps.
*/
interface GraphCapability {
[GraphCapabilityTypeId]: readonly [() => Model, (requirement: ConcreteGraphRequirement<Requirement>) => void]
}/**
* An opaque result produced by a graph-connected Step.
*
* It preserves the exact Model, Message, OutMessage, Command requirements, and
* Binding registration types. Return or compose it intact: `.model`,
* `.commands`, and `.outMessage` are unavailable until checked execution.
* A matching Composition `makeInit` or `makeUpdate` interprets it with the
* registered graph active. A completed Block's exposed operation produces a
* Message, invokes that completed update, and interprets any recipe returned by
* the selected branch.
*
* This type provides no public executor. Ordinary Return and
* ReturnWithOutMessage values remain readable Model-and-Commands results.
*/
interface ResultRecipe {
[DeferredUpdateEvidenceTypeId]: readonly [() => Model, () => Message, () => R, () => Evidence]
[ResultRecipeTypesTypeId]: readonly [(model: Model) => Model, () => Message, () => OutMessage, () => R, () => Evidence]
}/**
* Composes a list of update Steps into one. Each Step runs against the Model
* the previous Step produced. Their Commands form one batch for the Runtime,
* which runs them independently. Array order does not sequence their effects
* or completion.
*
* Dual: pass the Model and Steps (`combineSteps(model, steps)`), or pass only
* the Steps to build a composable Step that runs later
* (`combineSteps(steps)`, for a `pipe` or a nested Step list). Ordinary Steps
* produce a readable Return. Connected Steps preserve an opaque
* ResultRecipe for execution by a matching registered Composition.
*
* Steps only ever accumulate Commands; a Step cannot cancel or replace
* another Step's Commands, and no Command runs during the fold. The
* Runtime runs the batch after update returns. `combineSteps([])` returns
* `{ model }`.
*
* ```ts
* SucceededUpdateNote: ({ note }) =>
* combineSteps(model, [
* replaceNoteInCaches(note),
* refreshNote(note.id),
* refreshAllNotes,
* refreshNotebookNotes(note.maybeNotebookId),
* ...Array.filter([refreshNotebookNotes(previousNotebookId)], () => hasMoved),
* showToast('Success', `Updated ${note.title}`),
* ])
* ```
*/
const combineSteps: (steps: Steps & StepsForModel<Steps, ResultRecipeModel<ResultRecipeOfStep<Steps[number]>>> & RequireOperationStep<Steps> & StepsWithoutOutMessage<NoInfer<Steps>>) => NoInfer<(model: GraphInput<ResultRecipeModel<ResultRecipeOfStep<Steps[number]>>, GraphRequirementOf<Steps[number]>>) => CombinedStepRecipe<ResultRecipeModel<ResultRecipeOfStep<Steps[number]>>, Steps>>/**
* Folds a child Block's update into the parent: the update half of
* embedding a child, complementing `h.block` on the view half. Give
* it the facts that vary per child (a ChildFold, or a
* ChildFoldWithOutMessage when the child's update returns
* OutMessages) and it returns a dual Fold:
*
* ```ts
* const foldSearch = Update.foldChild({
* update: Search.update,
* read: (model: Model) => Option.some(model.search),
* write: (model, nextSearch) => modifyFields(model, { search: () => nextSearch }),
* toParentMessage: message => GotSearchMessage({ message }),
* })
*
* // in the parent update
* GotSearchMessage: ({ message }) => foldSearch(model, message),
* ```
*
* The fold runs `update` against the child Model `read` returns, writes
* the child back, and lifts the child's Commands through
* `toParentMessage`. When `read` returns `None` the fold returns
* `{ model }`: a Message for an unmounted child is a no-op. When the
* child's update returns an OutMessage, `foldOutMessage` runs against
* the Model with the child already written back, and its Commands
* follow the child's in the returned batch.
*
* `foldOutMessage` takes an optional second parameter, a
* FoldContext carrying `liftCommand` and `liftCommands` bound to
* this config's `toParentMessage`. Reach for it when the Step returns a
* Command that produces the child's Message, such as an animating
* component's overridable leave Command.
*
* A parent that is itself a Block receives a
* FoldWithOutMessage when `foldOutMessage` emits a derived parent
* OutMessage. Add `toParentOutMessage` only when at least one child OutMessage
* should continue to the current Block's parent. When provided,
* `foldOutMessage` still handles forwarded variants locally. A derived
* OutMessage replaces the one-to-one lift for the dispatch. When the Step
* emits nothing, the lift runs as usual.
*
* An entry point that takes nothing but the child Model, such as
* `Dialog.close`, has no input to pass: fold it with
* foldChildStep, which returns the Step directly.
*
* `update` closes over per-dispatch context, and the data-last form
* composes with combineSteps, here to put a navigation Command ahead
* of the child's:
*
* ```ts
* const enterJoinedRoom = (roomId: string, player: Player): UpdateStep =>
* Update.combineSteps([
* model => ({ model, commands: [NavigateToRoom({ roomId })] }),
* Update.foldChild({
* update: (room: Room.Model, joinedPlayer: Player) =>
* Room.informJoined(room, joinedPlayer, { roomId }),
* read: readRoom,
* write: writeRoom,
* toParentMessage: toGotRoomMessage,
* })(player),
* ])
* ```
*/
const foldChild: (childFold: ChildFoldWithParentOutMessage<ParentModel, ParentMessage, ChildModel, Input, ChildMessage, ChildOutMessage, ParentOutMessage, ChildRequirements, OutMessageStepRequirements, OutMessageStepMessage, DerivedParentOutMessage>) => FoldWithOutMessage<ParentModel, ParentMessage | OutMessageStepMessage, Input, ParentOutMessage | DerivedParentOutMessage, ChildRequirements | OutMessageStepRequirements>/**
* Folds one Block selected by key into the parent update. `readAt` and
* `writeAt` use the key to find and replace the child Model.
* `toParentMessage` receives the key when wrapping child Messages. The returned
* FoldAt runs data-first as `fold(model, key, input)` and data-last
* as `fold(key, input)` for combineSteps.
*
* When `readAt` returns `None` for the key, the fold returns `{ model }`.
*
* `foldOutMessage` takes the key and a FoldContext of lifters bound
* to `toParentMessage`, then returns a matcher that produces a parent Step.
* Callbacks that do not need the lifters can omit the context parameter.
* To forward a child OutMessage, `toParentOutMessage` takes the key and
* returns a matcher that produces a parent OutMessage. Both factories are
* skipped when the child emits no OutMessage. If the local Step derives a
* parent OutMessage, that result takes precedence over forwarding.
*
* For example, the parent stores Applicant Blocks in an array and uses each
* entry's stable id as its key:
*
* ```ts
* const foldApplicant = Update.foldChildAt({
* update: Applicant.update,
* readAt: (model: Model, entryId: string) =>
* Option.map(
* Array.findFirst(
* model.applicants,
* applicant => applicant.id === entryId,
* ),
* applicant => applicant.entry,
* ),
* writeAt: (model, entryId, nextEntry) =>
* modifyFields(model, {
* applicants: Array.map(applicant =>
* applicant.id === entryId
* ? modifyFields(applicant, { entry: () => nextEntry })
* : applicant,
* ),
* }),
* toParentMessage: (entryId, message) =>
* Message.GotApplicantMessage({ entryId, message }),
* })
*
* GotApplicantMessage: ({ entryId, message }) =>
* foldApplicant(model, entryId, message)
* ```
*
* When only one child is active at a time, store that one Model and an
* `Option` of its key instead of a collection.
*/
const foldChildAt: (childFold: ChildFoldAtWithParentOutMessage<ParentModel, ParentMessage, ChildModel, Key, Input, ChildMessage, ChildOutMessage, ParentOutMessage, ChildRequirements, OutMessageStepRequirements, OutMessageStepMessage, DerivedParentOutMessage>) => FoldAtWithOutMessage<ParentModel, ParentMessage | OutMessageStepMessage, Key, Input, ParentOutMessage | DerivedParentOutMessage, ChildRequirements | OutMessageStepRequirements>/**
* Builds a parent Model from a completed child initialization result and lifts
* its Commands through `toParentMessage`. Call it data-first with the child
* result and parent adapters.
*
* For connected Blocks, prefer the Binding's `init` and exposed operations.
* Construct the parent Model from init results, then apply any startup Steps
* to that Model. A boot Step takes an existing Model; it does not construct
* a child initialization result for this helper.
*
* `toParentModel` constructs the complete parent Model before `foldOutMessage`
* runs. The fold receives the same FoldContext as foldChild,
* and its Commands follow the mapped child Commands. The returned Message
* and service requirements include both the child's mapped Commands and the
* OutMessage Step's Commands.
*
* ```ts
* const init = () =>
* Update.foldChildInit(Search.init(), {
* toParentModel: search => Model.make({ search }),
* toParentMessage: message => Message.GotSearchMessage({ message }),
* })
* ```
*
* A child result that can emit an OutMessage requires `foldOutMessage` or
* `toParentOutMessage`. A local fold returning Step produces a plain
* Return; a fold returning StepWithOutMessage produces a
* ReturnWithOutMessage. Add `toParentOutMessage` to forward child
* OutMessages, optionally alongside local handling. A derived OutMessage
* replaces the forwarded one. When the child emits nothing, neither adapter
* runs and the result omits `outMessage`.
*/
const foldChildInit: (childInit: ChildInit & Readonly<{
commands: Commands<Message, R>
model: Model
outMessage: OutMessage
}>, childFold: ChildFold & Readonly<{
foldOutMessage: (outMessage: ChildOutMessage, context: FoldContext<ChildMessage, ParentMessage>) => (model: ParentModel) => ReturnWithOutMessageValue<ParentModel, OutMessageStepMessage, DerivedParentOutMessage, OutMessageStepRequirements>
toParentMessage: (message: ChildMessage) => ParentMessage
toParentModel: (childModel: ChildModel) => ParentModel
toParentOutMessage: (outMessage: ChildOutMessage) => ParentOutMessage | undefined
}>) => [RegistrationEvidenceOf<ChildInit> | InitFoldRegistrationEvidence<ChildFold>] extends [never]
? ReturnWithOutMessage<ParentModel, ParentMessage | OutMessageStepMessage, ParentOutMessage | DerivedParentOutMessage, ChildRequirements | OutMessageStepRequirements>
: ReturnWithRegistrationEvidence<ParentModel, Command<ParentMessage | OutMessageStepMessage, never, ChildRequirements | OutMessageStepRequirements> extends Command<Message, any, any>
? Message
: never, Exclude<ParentOutMessage, undefined> | Exclude<DerivedParentOutMessage, undefined>, Command<ParentMessage | OutMessageStepMessage, never, ChildRequirements | OutMessageStepRequirements> extends Readonly<{
args: Record<string, unknown>
effect: Effect.Effect<Schema.Schema.Type<T>, E, R>
key: string
name: string
}>
? R
: never, RegistrationEvidenceOf<ChildInit> | InitFoldRegistrationEvidence<ChildFold>>/**
* Builds a complete parent Model from named child initialization results before
* handling any of their OutMessages. Call this function data-first.
*
* `toParentModel` receives the record of child Models and runs exactly once.
* The `folds` record has the same keys as `childInits`. Each fold receives the
* Model produced by the preceding fold, so a change to another child is kept.
* Folds follow the record's own-key order: array-index keys first in numeric
* order, then other string keys in insertion order, then Symbols in insertion
* order.
* Prefer descriptive string keys to make that order visible at the call site.
*
* For example, a Workspace Block contains Search and Editor Blocks:
*
* ```ts
* const init = (): Update.Return<Model, Message> =>
* Update.foldChildInits(
* { search: Search.init(), editor: Editor.init() },
* {
* toParentModel: ({ search, editor }) => Model.make({ search, editor }),
* folds: {
* search: {
* toParentMessage: message => Message.GotSearchMessage({ message }),
* },
* editor: {
* toParentMessage: message => Message.GotEditorMessage({ message }),
* },
* },
* },
* )
* ```
*
* Add `foldOutMessage` to handle a child's OutMessage against the completed
* parent Model. The Editor fold also sees changes made by the Search fold.
* For each child, mapped child Commands precede Commands from its OutMessage
* fold. All Commands for that child precede the next child's Commands. Array
* order does not guarantee execution or completion order. Each fold receives
* its own FoldContext; Message and service requirement unions include
* every child and OutMessage Step. When using the context, annotate both
* handler parameters, for example `(outMessage: Search.OutMessage,
* context: Update.FoldContext<Search.Message, Message>)`. An unannotated
* context has an `unknown` parent Message. The annotated context is checked
* against the same entry's `toParentMessage`.
*
* Each entry supports the same local handling and forwarding as
* foldChildInit. A child that can emit an OutMessage requires
* `foldOutMessage` or `toParentOutMessage`. A derived parent OutMessage takes
* precedence over forwarding within that entry.
*
* TypeScript can leave an inline generic `match` adapter unresolved. Name the
* adapter or pass its output type explicitly to keep the exact Message,
* OutMessage, and service types. If an entry remains unresolved, the return
* keeps the parent Model type and widens those other types to `unknown` rather
* than incorrectly reporting `never`.
*
* If any entry can emit a parent OutMessage, supply `resolveOutMessage` to
* construct the single final OutMessage. It receives optional parent
* OutMessages under their child keys, followed by the final parent Model.
* For example, combine a restored query and a restored draft into one
* `RestoredWorkspace` OutMessage that preserves both results. Choosing one
* child's OutMessage discards the other and needs an application-specific
* reason. The resolver runs after all folds, only when at least one entry
* emitted an OutMessage. If the final Model alone contains everything needed,
* local folds followed by withOutMessage can report the parent result.
* Return `undefined` to emit nothing. Local-only folds return Return;
* outward-capable folds return ReturnWithOutMessage. Absent child
* OutMessages skip their handlers, and absent final OutMessages omit the
* `outMessage` property.
*/
const foldChildInits: (childInits: ChildInits, configuration: Readonly<{
folds: Folds & {
readonly [Key in keyof ChildInits]: InitFold<ChildInits[Key], ReturnType<ToParentModel>>
} & Record<Exclude<keyof Folds, keyof ChildInits>, never> & NoInfer<{
readonly [Key in keyof ChildInits]: InitFoldValidation<ChildInits[Key], ReturnType<ToParentModel>, Folds[Key]>
}>
toParentModel: ToParentModel
}> & {
resolveOutMessage: (outMessages: InitOutMessages<Folds>, model: ReturnType<ToParentModel>) => ParentOutMessage | undefined
} & NoInfer<InitResolution<Folds>>) => WithRegistrationEvidence<unknown extends Folds[keyof Folds]
? ReturnWithOutMessage<ReturnType<ToParentModel>, unknown, unknown, unknown>
: [InitParentOutMessage<Folds[keyof Folds]>] extends [never]
? Return<ReturnType<ToParentModel>, InitMessages<Folds>, InitRequirements<ChildInits, Folds>>
: ReturnWithOutMessage<ReturnType<ToParentModel>, InitMessages<Folds>, ParentOutMessage, InitRequirements<ChildInits, Folds>>, InitRegistrationEvidence<ChildInits, Folds>>/**
* Folds a child entry point that takes nothing but the child Model, and
* returns the Step directly. Everything else matches
* foldChild: the child is read, updated, and written back, its
* Commands are lifted through `toParentMessage`, a `None` from `read` makes
* the Step a no-op, and `foldOutMessage` runs against the Model with the
* child already written back.
*
* Reach for it wherever a Block exposes a no-argument entry point, so the
* call site composes with combineSteps as a plain Step and never invents
* an input the child does not take:
*
* ```ts
* const foldMobileMenuDialogClose = Update.foldChildStep({
* update: Dialog.close,
* read: readMobileMenuDialog,
* write: writeMobileMenuDialog,
* toParentMessage: toGotMobileMenuDialogMessage,
* foldOutMessage: foldMobileMenuDialogOutMessage,
* })
*
* // in the parent update
* Update.combineSteps(model, [writeRouteFields, foldMobileMenuDialogClose])
* ```
*
* `foldOutMessage` takes the same optional second parameter as
* foldChild: a FoldContext carrying `liftCommand` and
* `liftCommands` bound to this config's `toParentMessage`, for a Command the
* Step returns whose result is the child's Message.
*
* A parent that is itself a Block receives a
* StepWithOutMessage when `foldOutMessage` emits a derived parent
* OutMessage. Add `toParentOutMessage` only when at least one child OutMessage
* should continue to the current Block's parent. When provided,
* `foldOutMessage` still handles forwarded variants locally. A derived
* OutMessage replaces the one-to-one lift for the dispatch. When the Step
* emits nothing, the lift runs as usual.
*/
const foldChildStep: (childFold: ChildStepFoldWithParentOutMessage<ParentModel, ParentMessage, ChildModel, ChildMessage, ChildOutMessage, ParentOutMessage, ChildRequirements, OutMessageStepRequirements, OutMessageStepMessage, DerivedParentOutMessage>) => StepWithOutMessage<ParentModel, ParentMessage | OutMessageStepMessage, ParentOutMessage | DerivedParentOutMessage, ChildRequirements | OutMessageStepRequirements>/**
* Adds a known or optional OutMessage to a plain update return while
* preserving its Model and Commands. Use this helper when attaching to an
* existing return or when the value has the type `OutMessage | undefined`.
* For a reusable Model-preserving Step that only emits a known OutMessage,
* use the owning Definition's `makeOutMessageStep` helper.
* `undefined` means that the operation emitted no OutMessage, so the returned
* record omits the property.
*
* The input must be a Return, so this helper cannot replace an
* OutMessage that an update already emitted.
*
* ```ts
* const editorSave = Update.combineSteps(model, [writeDraft, clearErrors])
*
* return pipe(editorSave, Update.withOutMessage(outMessage))
* ```
*
* When the OutMessage is already known while constructing a new result,
* include it directly: `{ model, commands, outMessage }`. If the OutMessage
* may be `undefined`, pass the new result first:
* `Update.withOutMessage({ model, commands }, outMessage)`.
*/
const withOutMessage: (outMessage: OutMessage | undefined) => (updateReturn: Input) => WithOutMessageOutput<Input, OutMessage>