/** * A Bundle is one value holding everything a child machine is: its Model and * Message Schemas, `init`, `update`, Subscriptions, Managed Resources, view, * and programmatic entry points. It holds no state; placing it with a Link * compiles each part to the Foldkit lift that already exists for it. */ import { Pipeable, type Effect, type Option, type Schema } from 'effect' import type * as ManagedResource from 'foldkit/managedResource' import type * as Submodel from 'foldkit/submodel' import type * as Subscription from 'foldkit/subscription' import type * as Update from 'foldkit/update' import type { AnyMessage, Link } from './link.js' import { each, type EachConfig, type PlacedCollection } from './collection.js' import { checkArgs, place, type ArgsSource, type Invalid, type NoView, type PlaceConfig, type Placed, type TagOf, } from './placed.js' import type { CollectionLink } from './link.js' import { helpersFor } from './helpers.js' import type { BundleParts } from './declare.js' /** * The parent seed a factory observes: the parent without the placement's own * field, or the whole parent where the field is unknown (`string`). */ export type SeedFor = string extends Field ? Parent : Omit const BundleTypeId: unique symbol = Symbol.for('foldkit-bundle/Bundle') /** A child Managed Resource entry: its requirements are an `Option`, so the entry can release. */ export type ResourceEntry = ManagedResource.Entry< Model, Message, Option.Option, any, any > export type ResourceEntries = Readonly< Record> > /** A programmatic entry point, like `Dialog.open`: the child Model plus any input. */ export type Helper = ( model: Model, ...input: ReadonlyArray ) => Update.ReturnWithOutMessage /** * The helpers a spec may hold. Their services are left open (`any`) because * `make` reads them from each helper's Commands (`HelperRequirements`) rather * than requiring them to be named up front. */ export type HelperRecord = Readonly< Record> > type CommandRequirements = Commands extends ReadonlyArray ? Command extends { readonly effect: Effect.Effect } ? R : never : never /** The services the Commands of every helper in `H` need. */ export type HelperRequirements = { [K in keyof H]: H[K] extends (...input: ReadonlyArray) => infer Return ? Return extends { readonly commands?: infer Commands } ? CommandRequirements : never : never }[keyof H] /** * A bundle's view: none for one made without a view (`NoView`). Erased * (`any`) inputs keep any view, so every bundle is an `AnyBundle`. */ type ViewFor = 0 extends 1 & ViewInputs ? Submodel.View : [ViewInputs] extends [NoView] ? never : Submodel.View export interface BundleSpec< Name extends string, Args, Model, Message extends AnyMessage, OutMessage, R, S, ViewInputs, Resources extends ResourceEntries, Helpers extends Readonly>>, > { readonly name: Name readonly Model: Schema.Codec readonly Message: Schema.Codec /** * The args Schema. When given, `Args` is inferred from it, a placement's args * are checked against it, and Module lists them. */ readonly args?: Schema.Codec /** Set by `with`: the bound args, encoded as text, for Module. */ readonly preset?: string | undefined /** Runs when the bundle is placed; its Commands start with the placement. */ readonly init: (args: Args) => Update.Return readonly update: ( model: Model, message: Message, args: Args, ) => Update.ReturnWithOutMessage readonly subscriptions?: (args: Args) => Subscription.Subscriptions readonly resources?: (args: Args) => Resources readonly view?: ViewFor /** * Programmatic entry points, which a placement exposes as * `placed.helpers.name(...input)`. Give a function of the args when a helper * needs them, as `update` does: the placement calls it with the args it holds. */ readonly helpers?: Helpers | ((args: Args) => Helpers) } export interface Bundle< Name extends string, Args, Model, Message extends AnyMessage, OutMessage, R, S, ViewInputs, Resources extends ResourceEntries, Helpers extends Readonly>>, > extends BundleSpec, Pipeable.Pipeable { readonly [BundleTypeId]: typeof BundleTypeId /** * A preset: the same bundle with its args bound, so placements need no `args`. * The args are checked against the args Schema when there is one. */ readonly with: ( args: Args, ) => Bundle /** Places the bundle where `link` points. */ readonly at: ( link: Link, ...config: PlaceConfigParam< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, SeedFor, ViewInputs > ) => Placed< Name, Parent, LinkMessage | OutStepMessage, Model, Message, R | R2, S, ViewInputs, Resources, Helpers, Field, TagOf > /** Places the bundle once per key of the collection `link` points at. */ readonly each: [keyof Resources] extends [never] ? < Parent, LinkMessage, Key extends string, Field extends string, OutStepMessage = never, R2 = never, >( link: CollectionLink, ...config: EachConfigParam< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, Key, SeedFor > ) => PlacedCollection< Name, Parent, LinkMessage | OutStepMessage, Model, Message, R | R2, S, ViewInputs, Helpers, Field, Key, TagOf > : Invalid<'Bundle.each does not support Managed Resources yet: the runtime provides a resource by one tag, so items would share it'> } /** * What placing needs: `args` when `init` takes them, and `onOut` when the * bundle has an OutMessage, so an OutMessage is never dropped by omission. * `args` is a static value or a factory from the parent seed (the parent * without this placement's own field); the seed type defaults to the whole * parent where the field is unknown. */ export type PlacementConfig< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, ParentSeed = Parent, ViewInputs = unknown, > = { /** Prefix for the placement's Subscription and resource keys. Defaults to `Name@path`. */ readonly key?: string /** A gate beside the Link's own: the child's Subscriptions and resources run only while both hold. */ readonly when?: (parent: Parent) => boolean /** Observes each of the child's Messages in parent terms, after the child handled it. */ readonly onMessage?: Required< PlaceConfig >['onMessage'] /** * The inputs the child's view is drawn with, from the parent's Model and the * inputs given, at every draw. Refused for a view that takes no inputs, which * would be handed none. */ readonly viewInputs?: [ViewInputs] extends [void] ? Invalid<'This view takes no inputs, so viewInputs would never be called'> : (parent: Parent, given: ViewInputs) => ViewInputs /** * `false` draws the child's view on every render. By default a view drawn * without inputs is kept while the child's Model is the same object (#431), * since it is given nothing else: opt out for one that reads outside it. */ readonly memo?: false } & ([Args] extends [void] ? { readonly args?: never } : { readonly args: ArgsSource }) & ([OutMessage] extends [never] ? { readonly onOut?: never } : { readonly onOut: Required< PlaceConfig< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, ParentSeed > >['onOut'] }) /** The config argument is optional only when it would be empty. */ export type PlaceConfigParam< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, ParentSeed = Parent, ViewInputs = unknown, > = [Args] extends [void] ? [OutMessage] extends [never] ? [ config?: PlacementConfig< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, ParentSeed, ViewInputs >, ] : [ config: PlacementConfig< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, ParentSeed, ViewInputs >, ] : [ config: PlacementConfig< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, ParentSeed, ViewInputs >, ] type EachOptions< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, Key extends string = string, ParentSeed = Parent, > = { readonly key?: string /** A gate per item beside the Link's own: an item's Subscriptions run only while both hold. */ readonly when?: (parent: Parent, key: Key) => boolean /** Observes each item's Messages in parent terms, after the item handled it. */ readonly onMessage?: Required< EachConfig >['onMessage'] /** `false` draws each item's view on every render; by default one is kept while its Model is. */ readonly memo?: false } & ([Args] extends [void] ? { readonly args?: never } : { readonly args: ArgsSource }) & ([OutMessage] extends [never] ? { readonly onOut?: never } : { readonly onOut: Required< EachConfig< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, Key, ParentSeed > >['onOut'] }) export type EachConfigParam< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, Key extends string = string, ParentSeed = Parent, > = [Args] extends [void] ? [OutMessage] extends [never] ? [ config?: EachOptions< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, Key, ParentSeed >, ] : [ config: EachOptions< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, Key, ParentSeed >, ] : [ config: EachOptions< Args, Parent, LinkMessage, Message, OutMessage, OutStepMessage, R2, Key, ParentSeed >, ] /** Any bundle, for APIs that accept one without caring about its types. */ export type AnyBundle = Bundle export const isBundle = (value: unknown): value is AnyBundle => typeof value === 'object' && value !== null && BundleTypeId in value const build = < const Name extends string, Model, Message extends AnyMessage, Args = void, OutMessage = never, R = never, S = never, ViewInputs = NoView, Resources extends ResourceEntries = {}, Helpers extends Readonly>> = {}, >( spec: BundleSpec, ): Bundle => { const bundle: Bundle< Name, Args, Model, Message, OutMessage, R, S, ViewInputs, Resources, Helpers > = { ...spec, [BundleTypeId]: BundleTypeId, pipe() { return Pipeable.pipeArguments(this, arguments) }, with: args => { // A preset of a preset has no args Schema left, so it keeps the first preset's args. const preset = checkArgs(spec, args, spec.name) ?? spec.preset return build({ name: spec.name, preset, Model: spec.Model, Message: spec.Message, init: () => spec.init(args), update: (model, message) => spec.update(model, message, args), ...(spec.subscriptions === undefined ? {} : { subscriptions: () => spec.subscriptions!(args) }), ...(spec.resources === undefined ? {} : { resources: () => spec.resources!(args) }), ...(spec.view === undefined ? {} : { view: spec.view }), // A preset has its args, so helpers that read them become a record. ...(spec.helpers === undefined ? {} : { helpers: helpersFor(spec.helpers, args) }), }) }, // A refused `viewInputs` is a type error at the call, never a value here. at: (link, ...[config]) => place(bundle, link, config as never), // The conditional type only hides `each` from bundles with resources; the function is the same. each: (( link: CollectionLink, config?: EachConfig, ) => each(bundle, link, config)) as unknown as Bundle< Name, Args, Model, Message, OutMessage, R, S, ViewInputs, Resources, Helpers >['each'], } return bundle } /** * What `make` reads. The `Model` and `Message` Schemas alone declare those * types (every other part is checked against them, so an empty `{}` in `init` * cannot widen the Model), and the services each part's Commands need are * inferred per part, so `init`, `update` and the helpers may each need * different ones. */ export interface MakeSpec< Name extends string, Args, Model, Message extends AnyMessage, OutMessage, RInit, RUpdate, S, ViewInputs, Resources extends ResourceEntries, Helpers extends HelperRecord, > { readonly name: Name readonly Model: Schema.Codec readonly Message: Schema.Codec /** * The args Schema. When given, `Args` is inferred from it, a placement's args * are checked against it, and Module lists them. */ readonly args?: Schema.Codec /** Set by `with`: the bound args, encoded as text, for Module. */ readonly preset?: string | undefined /** Runs when the bundle is placed; its Commands start with the placement. */ readonly init: (args: Args) => Update.Return, NoInfer, RInit> readonly update: ( model: NoInfer, message: NoInfer, args: Args, ) => Update.ReturnWithOutMessage, NoInfer, OutMessage, RUpdate> readonly subscriptions?: ( args: Args, ) => Subscription.Subscriptions, NoInfer, S> readonly resources?: (args: Args) => Resources readonly view?: Submodel.View, NoInfer, ViewInputs> /** A record, or a function of the args returning one, as `BundleSpec`'s. */ readonly helpers?: Helpers | ((args: Args) => Helpers) } // `Model` is `const` because a paramless `init` is typed before the Schema // fixes `Model`, and `NoInfer` alone let its literals widen to `string` there. // The Schema supplies no literal expression, so nothing else changes. /** * Collects a child machine's parts into a bundle. Name it first, * `make('Search', { Model, Message, init, update })`, or inside the spec. * The bundle's services are what `init`, `update` and the helpers need together. */ export function make< const Name extends string, const Model, Message extends AnyMessage, Args = void, OutMessage = never, RInit = never, RUpdate = never, S = never, ViewInputs = NoView, Resources extends ResourceEntries = {}, Helpers extends HelperRecord = {}, >( name: Name, spec: Omit< MakeSpec< Name, Args, Model, Message, OutMessage, RInit, RUpdate, S, ViewInputs, Resources, Helpers >, 'name' > & { readonly name?: never }, ): Bundle< Name, Args, Model, Message, OutMessage, RInit | RUpdate | HelperRequirements, S, ViewInputs, Resources, Helpers > export function make< const Name extends string, const Model, Message extends AnyMessage, Args = void, OutMessage = never, RInit = never, RUpdate = never, S = never, ViewInputs = NoView, Resources extends ResourceEntries = {}, Helpers extends HelperRecord = {}, >( spec: MakeSpec< Name, Args, Model, Message, OutMessage, RInit, RUpdate, S, ViewInputs, Resources, Helpers >, ): Bundle< Name, Args, Model, Message, OutMessage, RInit | RUpdate | HelperRequirements, S, ViewInputs, Resources, Helpers > export function make( nameOrSpec: string | BundleSpec, spec?: Omit, 'name'>, ): AnyBundle { return build(typeof nameOrSpec === 'string' ? { ...spec!, name: nameOrSpec } : nameOrSpec) } export interface PartsConfig< Name extends string, Args, Model, Message extends AnyMessage, OutMessage, R, S, ViewInputs, Helpers extends HelperRecord, > { readonly name: Name readonly Model: Schema.Codec readonly Message: Schema.Codec readonly init: (args: Args) => NoInfer readonly parts: { readonly update: ( model: NoInfer, message: NoInfer, ) => Update.ReturnWithOutMessage, NoInfer, OutMessage, R> readonly view?: Submodel.View, NoInfer, ViewInputs> } readonly subscriptions?: ( args: Args, ) => Subscription.Subscriptions, NoInfer, S> /** As a spec's `helpers`: a record, or a function of the args returning one. */ readonly helpers?: Helpers | ((args: Args) => Helpers) } type ErasedPartsConfig = PartsConfig /** * A bundle from a component that ships its parts separately, like the * `@foldkit/ui` components: `init` returns only the Model, and `parts` is the * `{ update, view }` pair their `create()` returns. The Schemas declare the * Model and Message, as in `make`. */ export function fromParts< const Name extends string, const Model, Message extends AnyMessage, Args = void, OutMessage = never, R = never, S = never, ViewInputs = NoView, Helpers extends HelperRecord = {}, >( name: Name, config: Omit< PartsConfig, 'name' > & { readonly name?: never }, ): Bundle< Name, Args, Model, Message, OutMessage, R | HelperRequirements, S, ViewInputs, {}, Helpers > export function fromParts< const Name extends string, const Model, Message extends AnyMessage, Args = void, OutMessage = never, R = never, S = never, ViewInputs = NoView, Helpers extends HelperRecord = {}, >( config: PartsConfig, ): Bundle< Name, Args, Model, Message, OutMessage, R | HelperRequirements, S, ViewInputs, {}, Helpers > export function fromParts( nameOrConfig: string | ErasedPartsConfig, maybeConfig?: Omit, ): AnyBundle { const config: ErasedPartsConfig = typeof nameOrConfig === 'string' ? { ...maybeConfig!, name: nameOrConfig } : nameOrConfig return build({ name: config.name, Model: config.Model, Message: config.Message, init: args => ({ model: config.init(args) }), update: (model, message) => config.parts.update(model, message), ...(config.parts.view === undefined ? {} : { view: config.parts.view }), ...(config.subscriptions === undefined ? {} : { subscriptions: config.subscriptions }), ...(config.helpers === undefined ? {} : { helpers: config.helpers }), }) } /** * A bundle's helpers as a record, whichever form it was given: for a parent * that folds the child itself (`Update.foldChild`) rather than placing it. A * placement's own `placed.helpers` already reads them with its args. */ export const helpersOf = ( bundle: B, ...[args]: BundleParts['Args'] extends void ? [] : [args: BundleParts['Args']] ): BundleParts['Helpers'] => helpersFor(bundle.helpers, args) /** * An `onOut` that deliberately drops the OutMessage. `onOut` stays required, so * dropping one is a visible choice rather than an omission. */ // The returned Step is generic rather than `ignore` itself, so the placement still // infers its parent from the Link. export const ignore = (..._: ReadonlyArray) => (parent: Parent): Update.Return => ({ model: parent }) export { assemble } from './assembly.js' export type { Assembly, WiredRecord } from './assembly.js' export { declare, declareEach } from './declare.js' export { lazy } from './lazy.js' export { compose, configure, withChild, withEach, withMessages, withServices, withWiring, } from './compose.js' export type { AnyComposition, Child as ComposedChild, Composition } from './compose.js' export type { Body, Lazy, LazySpec, Loadable } from './lazy.js' export type { Declared, DeclaredEach, WrapperTag } from './declare.js' export { parent } from './parent.js' export type { Parent } from './parent.js' export type { BundleParts } from './declare.js' export type { InitialRest, OwnMessage, RuntimeInput, RuntimeInitFn, RuntimeResult, } from './assembly.js' export { mapInit, mapUpdate, mapView, rename, withHelpers, withSubscriptions, withView, } from './combinators.js'