Published foldkit API declarations for runtime.
./runtime
@wsagency/wseffect-foldkit · MIT · source · MIT license · WS-AGENCY-NOTICE · THIRD-PARTY-NOTICES
This entry point is published in @wsagency/wseffect-foldkit@0.1.0-rc.1. Import it from the package subpath shown below; the signatures and documentation are read from the installed package declarations.
import * as Wseffect from '@wsagency/wseffect-foldkit/runtime'
Exported declarations
ApplicationConfig
Configuration for `makeApplication` without Flags or URL routing.
export type ApplicationConfig<Model, Message, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined> = BaseApplicationConfig<Model, Message, Resources, ManagedResourceServices, P> & Readonly<{
init: () => UpdateReturn<Model, Message, Resources | ManagedResourceServices>;
}>;
ApplicationConfigWithFlags
Configuration for `makeApplication` with Flags but no URL routing.
export type ApplicationConfigWithFlags<Model, Message, Flags, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined> = BaseApplicationConfig<Model, Message, Resources, ManagedResourceServices, P> & FlagsSchemaConfig<Flags> & Readonly<{
init: (flags: Flags) => UpdateReturn<Model, Message, Resources | ManagedResourceServices>;
}>;
ApplicationInit
The `init` function type for a `makeApplication` app without URL routing.
export type ApplicationInit<Model, Message, Flags = void, Resources = never, ManagedResourceServices = never> = Flags extends void ? () => UpdateReturn<Model, Message, Resources | ManagedResourceServices> : (flags: Flags) => UpdateReturn<Model, Message, Resources | ManagedResourceServices>;
CrashConfig
Configuration for crash handling, with custom crash UI and/or crash
reporting. The crash view renders after the dispatch loop has stopped, so
its builder's Message is `never` and no handler is expressible. Reload or
navigate with a raw DOM attribute instead.
export type CrashConfig<Model, Message> = Readonly<{
view?: (context: CrashContext<Model, Message>, h: HtmlBuilder<never>) => Document;
report?: (context: CrashContext<Model, Message>) => void;
}>;
CrashContext
Context provided to crash.view and crash.report when the runtime encounters
an unrecoverable error. `message` is the Message being processed when the
crash occurred, present as an `Option` because a crash during the initial
render has no triggering Message.
export type CrashContext<Model, Message> = Readonly<{
error: Error;
model: Model;
message: Option.Option<Message>;
}>;
defaultSlowCallback
defaultSlowCallback: (context: SlowContext<unknown, unknown>) => void
DevToolsConfig
DevTools configuration.
Pass `false` to disable DevTools entirely.
- `show`: `'Development'` (default) enables in dev mode only, `'Always'` enables in all environments including production.
- `position`: Where the badge and panel appear. Defaults to `'BottomRight'`.
- `mode`: `'TimeTravel'` (default) enables full time-travel debugging by installing a paused historical view while the live application continues. `'Inspect'` allows browsing state snapshots without replacing the live view. Pass `{ development, production }` to use different modes per environment. Useful when DevTools is shown in production (`show: 'Always'`) and you want `'TimeTravel'` only in local development.
- `banner`: Optional text shown as a banner at the top of the panel.
- `excludeFromHistory`: Message `_tag` values whose dispatches should not be recorded in DevTools history. The Messages still drive `update` and the runtime as usual; they just don't appear in the history panel and don't pay the per-Message diff cost. Use for high-frequency Messages (animation frames, pointer moves, scroll events) that would flood history without adding insight.
- `maxEntries`: Maximum number of recorded Messages retained in history before the oldest is evicted. Defaults to 100. Clamped to the range 20-500: smaller values keep the panel snappy under high message rates, larger values give you more scroll-back. Each retained entry stores a full Model snapshot, so memory cost scales linearly with both `maxEntries` and your Model size.
- `keyframeInterval`: Number of recorded Messages between full Model snapshots. Defaults to 31. Time-travel to an index replays `update` forward from the nearest earlier keyframe, so this is a memory/time tradeoff: smaller values store more snapshots (more memory) but make each jump cheaper, down to `1` where every jump is a constant-time snapshot lookup with no replay. Reach for a denser interval when the app has a heavy `update` and time-travel jumps feel sluggish. Clamped to a minimum of 1. Forced to 1 automatically when `excludeFromHistory` is active, since excluded Messages are never replayed.
DevTools records Models, Message payloads, Command args, and Mount args. A connected DevTools MCP agent can read that data. Keep secrets out of browser state where possible and use Effect `Redacted` for sensitive values the browser must temporarily hold. `excludeFromHistory` does not hide changes that enter the Model, and omitting `Message` disables agent dispatch without disabling inspection.
export type DevToolsConfig = false | Readonly<{
show?: Visibility;
position?: DevToolsPosition;
mode?: DevToolsModeConfig;
banner?: string;
excludeFromHistory?: ReadonlyArray<string>;
maxEntries?: number;
keyframeInterval?: number;
/**
* The application's `Message` Schema. When provided and the running app
* is connected to the Foldkit DevTools MCP server, AI agents can dispatch
* Messages into the runtime. The Schema decodes inbound dispatch payloads
* at the bridge boundary and returns a clean error on mismatch.
*
* Without this field, `RequestDispatchMessage` is rejected with an
* informative error.
*/
Message?: Schema.Codec<any, any, unknown, unknown>;
}>;
DevToolsMode
Controls DevTools interaction mode.
- `'Inspect'`: Messages stream in and clicking a row shows its state snapshot without pausing the rendered view.
- `'TimeTravel'`: Clicking a row installs a paused historical view while the live application continues. Resume to patch the latest live view.
export type DevToolsMode = 'Inspect' | 'TimeTravel';
DevToolsModeConfig
Mode value for the DevTools panel. Either a single mode used in every
environment, or an object selecting different modes for development and
production. Use the object form to keep `'TimeTravel'` for local debugging
while shipping the safer `'Inspect'` mode to users. `'TimeTravel'` in
production pauses the user's rendered view when a history row is clicked.
export type DevToolsModeConfig = DevToolsMode | Readonly<{
development: DevToolsMode;
production: DevToolsMode;
}>;
DevToolsPosition
Position of the DevTools badge and panel on screen.
export type DevToolsPosition = 'BottomRight' | 'BottomLeft' | 'TopRight' | 'TopLeft';
ElementConfig
Configuration for `makeElement` without Flags.
export type ElementConfig<Model, Message, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined> = BaseElementConfig<Model, Message, Resources, ManagedResourceServices, P> & Readonly<{
init: () => UpdateReturn<Model, Message, Resources | ManagedResourceServices>;
}>;
ElementConfigWithFlags
Configuration for `makeElement` with Flags.
export type ElementConfigWithFlags<Model, Message, Flags, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined> = BaseElementConfig<Model, Message, Resources, ManagedResourceServices, P> & FlagsSchemaConfig<Flags> & Readonly<{
/**
* Resolves the Flags once at startup, before `init` runs. Services this
* Effect requires are provided from the `resources` Layer, which the
* runtime builds a single time and shares with every Command and
* Subscription. The error channel is `never`, so this Effect handles its
* own failures with `Effect.catch`, the same contract a Command's Effect
* has.
*/
flags: Effect.Effect<Flags, never, NoInfer<Resources>>;
init: (flags: Flags) => UpdateReturn<Model, Message, Resources | ManagedResourceServices>;
}>;
ElementCrashConfig
Configuration for crash handling in a `makeElement` app. The crash view
returns `Html`, not a `Document`, because a scoped app never owns the
document `<head>`.
export type ElementCrashConfig<Model, Message> = Readonly<{
view?: (context: CrashContext<Model, Message>, h: HtmlBuilder<never>) => Html;
report?: (context: CrashContext<Model, Message>) => void;
}>;
ElementInit
The `init` function type for a `makeElement` app. A scoped app never owns
the URL, so its `init` has the same shape as a non-routing
`ApplicationInit`: argless, or receiving Flags when `Flags` is set.
export type ElementInit<Model, Message, Flags = void, Resources = never, ManagedResourceServices = never> = ApplicationInit<Model, Message, Flags, Resources, ManagedResourceServices>;
embed
Starts a Foldkit runtime under a host-controlled lifecycle and returns an
`EmbedHandle`. This is the entry point for embedding a Foldkit app inside
another application: the host pushes values in through the handle's inbound
Ports, listens to outbound Ports, and calls `dispose` when it unmounts the
app. The host never touches the Model or dispatches Messages directly; the
Schema-typed Ports are the whole boundary.
Works with programs from both `makeApplication` and `makeElement`; for a
widget on a page the host owns, `makeElement` is the natural fit.
A program can be embedded once at a time (it owns one container). After
`dispose`, the same container can be embedded again with a fresh program.
```ts
const handle = Runtime.embed(element)
handle.ports.stepChanged.send(5)
const unsubscribe = handle.ports.countChanged.subscribe(count => {
console.log(count)
})
handle.dispose()
```
export declare function embed<P extends Ports | undefined = undefined, Resources = never, Kind extends 'Application' | 'Element' = 'Application' | 'Element'>(program: MakeRuntimeReturn<P, void, Resources, Kind>): EmbedHandle<P>;
embed
export declare function embed<P extends Ports | undefined, Flags, Resources, Kind extends 'Application' | 'Element'>(program: MakeRuntimeReturn<P, Flags, Resources, Kind>, options: RunOptions<Flags, Resources>): EmbedHandle<P>;
EmbedHandle
The handle returned by `embed`. The host talks to the embedded app only
through it: `ports.<name>.send` pushes values in, `ports.<name>.subscribe`
listens to values the app emits, and `dispose` shuts the runtime down.
`dispose` is idempotent. It interrupts the runtime and runs all cleanup:
Subscriptions, ManagedResources, Mounts, listeners, and in-flight Commands
stop, and the rendered DOM is removed with the container element restored
empty in its place, ready for a fresh `embed`.
export type EmbedHandle<P extends Ports | undefined = undefined> = Readonly<{
ports: PortHandles<P>;
dispose: () => void;
}>;
hydrate
Starts a Foldkit runtime by adopting a server-rendered DOM in place instead
of building it fresh. Use this as the client entry for a page served by
`renderToString`: the first render attaches to the stamped root, keeps the
existing nodes, and reconstructs the Model from the Flags the server
embedded. The handoff is strict: a missing server root, an empty or
duplicated root stamp, more than one stamped root, a requested root outside
the document body light DOM, a missing Flags payload, an undecodable
payload, or a page from another deployment terminates startup. Every one of
those contains the page first:
the document's body is marked `inert` and a nondismissable modal shield is
opened above existing top-layer content, so pointer and physical keyboard
input do not activate same-document native links, forms, or controls.
Containment leaves author-owned dialogs open without calling `close` or
dispatching `cancel`.
Nothing is moved, so no custom element reconnects and no frame reloads.
This is not a script, event, or embedded-document sandbox: existing
capture-phase handlers, browser-generated top-layer events, timers, and
stale scripts can still run. Controls in embedded documents can still
receive input if stale code focuses them. Stale code can also open newer
top-layer UI. Use `run` in a separate client-only entry when the page should
boot without server output.
hydrate: <P extends Ports | undefined, Flags, Resources>(program: MakeRuntimeReturn<P, Flags, Resources, 'Application'>, options?: HydrateOptions) => void
HydrateOptions
export type HydrateOptions = Readonly<{
/**
* The deployment this client belongs to, compared against the id the server
* stamped on the root before the Flags payload text is accessed or decoded,
* so a page from a different deployment stops startup rather than handing its
* Flags to this build. When omitted, Foldkit uses the identity compiled into
* this artifact by `@wsagency/wseffect-vite-plugin`. An explicit id overrides that
* value and must be non-empty: an absent id would equal the absent marker on
* a page served before build ids existed.
*
* This explicit option is for integrations that cannot compile the shared
* identity into the artifact. Give the server the same public,
* deployment-specific value.
*/
buildId?: string;
}>;
InboundPortHandle
Host-side handle for one inbound Port. `send` validates the value by
decoding it against the Port's Schema: on success the decoded value enters
the app through the Port's Subscription; on failure nothing reaches the
app, the failure is logged, and the returned `Exit` carries the
`SchemaError`. Sends after `dispose` are no-ops.
export type InboundPortHandle<Encoded> = Readonly<{
send: (value: Encoded) => Exit.Exit<void, Schema.SchemaError>;
}>;
InboundPortHandles
The inbound half of `PortHandles`: one `InboundPortHandle` per declared
inbound Port, keyed by Port name.
export type InboundPortHandles<InboundPorts> = InboundPorts extends Readonly<Record<string, Inbound<any, any>>> ? {
readonly [Name in keyof InboundPorts]: InboundPorts[Name] extends Inbound<any, infer Encoded> ? InboundPortHandle<Encoded> : never;
} : unknown;
makeApplication
export declare function makeApplication<Model, Message extends {
_tag: string;
}, Flags, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined>(config: ApplicationConfigWithFlags<Model, Message, Flags, Resources, ManagedResourceServices, P>): MakeRuntimeReturn<P, Flags, Resources, 'Application'>;
makeApplication
Creates a Foldkit application that owns the page and returns a runtime that
can be passed to `run`. The `view` returns a `Document`, so the runtime
manages `document.title` and the canonical / og:url tags. Add a `routing`
config for URL routing. Use one page-owning application per document. To
mount an app scoped to a node without touching the document `<head>`, use
`makeElement`.
export declare function makeApplication<Model, Message extends {
_tag: string;
}, Flags, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined>(config: RoutingApplicationConfigWithFlags<Model, Message, Flags, Resources, ManagedResourceServices, P>): MakeRuntimeReturn<P, Flags, Resources, 'Application'>;
makeApplication
export declare function makeApplication<Model, Message extends {
_tag: string;
}, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined>(config: ApplicationConfig<Model, Message, Resources, ManagedResourceServices, P>): MakeRuntimeReturn<P, void, Resources, 'Application'>;
makeApplication
export declare function makeApplication<Model, Message extends {
_tag: string;
}, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined>(config: RoutingApplicationConfig<Model, Message, Resources, ManagedResourceServices, P>): MakeRuntimeReturn<P, void, Resources, 'Application'>;
makeElement
Creates a Foldkit app scoped to its container and returns a runtime that
can be passed to `run`.
Unlike `makeApplication`, the `view` returns `Html` directly rather than a
`Document`, and the runtime never touches the document `<head>`. This lets a
Foldkit app be embedded at a node (a widget on a page it does not own)
without clobbering the host page's `title`, `canonical`, or `og:url`. Use
`makeApplication` when the app owns the page and should manage those tags, and
`makeElement` when it is one component among others on a page it does not
control. Embedded apps do not own the URL bar, so `makeElement` has no
`routing` config.
export declare function makeElement<Model, Message extends {
_tag: string;
}, Flags, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined>(config: ElementConfigWithFlags<Model, Message, Flags, Resources, ManagedResourceServices, P>): MakeRuntimeReturn<P, void, Resources, 'Element'>;
makeElement
export declare function makeElement<Model, Message extends {
_tag: string;
}, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined>(config: ElementConfig<Model, Message, Resources, ManagedResourceServices, P>): MakeRuntimeReturn<P, void, Resources, 'Element'>;
MakeRuntimeReturn
A configured Foldkit runtime returned by `makeApplication` or `makeElement`.
Pass it to `run` to start a page-owning app, or to `embed` to start it under
a host-controlled lifecycle handle. `ports` is the Ports record from the
config (or `undefined` when the config declared none); it types the
`EmbedHandle` that `embed` returns. `Flags` and `Resources` carry the
fresh-boot requirements from `makeApplication` to `run` and `embed`; they
have no runtime representation.
export type MakeRuntimeReturn<P extends Ports | undefined = undefined, Flags = void, Resources = never, Kind extends 'Application' | 'Element' = 'Application' | 'Element'> = Readonly<{
runtimeId: string;
start: (preservedModel?: unknown) => Effect.Effect<void>;
ports: P;
'~foldkit/RuntimeBoot'?: Readonly<{
Flags: (flags: Flags) => Flags;
Resources: (resources: Resources) => Resources;
Kind: Kind;
}>;
}>;
OutboundPortHandle
Host-side handle for one outbound Port. `subscribe` registers a listener
for the encoded values the app emits with `Port.emit` and returns an
unsubscribe function. Multiple listeners receive each value in
registration order.
export type OutboundPortHandle<Encoded> = Readonly<{
subscribe: (listener: (value: Encoded) => void) => () => void;
}>;
OutboundPortHandles
The outbound half of `PortHandles`: one `OutboundPortHandle` per declared
outbound Port, keyed by Port name.
export type OutboundPortHandles<OutboundPorts> = OutboundPorts extends Readonly<Record<string, Outbound<any, any>>> ? {
readonly [Name in keyof OutboundPorts]: OutboundPorts[Name] extends Outbound<any, infer Encoded> ? OutboundPortHandle<Encoded> : never;
} : unknown;
PortHandles
The `ports` field of an `EmbedHandle`: one `InboundPortHandle` or
`OutboundPortHandle` per declared Port, keyed by Port name.
export type PortHandles<P extends Ports | undefined> = P extends Ports ? InboundPortHandles<P['inbound']> & OutboundPortHandles<P['outbound']> : unknown;
RoutingApplicationConfig
Configuration for `makeApplication` with URL routing but no Flags.
export type RoutingApplicationConfig<Model, Message, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined> = BaseApplicationConfig<Model, Message, Resources, ManagedResourceServices, P> & Readonly<{
routing: RoutingConfig<Message>;
init: (url: Url) => UpdateReturn<Model, Message, Resources | ManagedResourceServices>;
}>;
RoutingApplicationConfigWithFlags
Configuration for `makeApplication` with Flags and URL routing.
export type RoutingApplicationConfigWithFlags<Model, Message, Flags, Resources = never, ManagedResourceServices = never, P extends Ports | undefined = undefined> = BaseApplicationConfig<Model, Message, Resources, ManagedResourceServices, P> & FlagsSchemaConfig<Flags> & Readonly<{
routing: RoutingConfig<Message>;
init: (flags: Flags, url: Url) => UpdateReturn<Model, Message, Resources | ManagedResourceServices>;
}>;
RoutingApplicationInit
The `init` function type for a `makeApplication` app with URL routing, receives the current URL and optional Flags.
export type RoutingApplicationInit<Model, Message, Flags = void, Resources = never, ManagedResourceServices = never> = Flags extends void ? (url: Url) => UpdateReturn<Model, Message, Resources | ManagedResourceServices> : (flags: Flags, url: Url) => UpdateReturn<Model, Message, Resources | ManagedResourceServices>;
RoutingConfig
Configuration for URL routing with handlers for URL requests and URL changes.
export type RoutingConfig<Message> = Readonly<{
onUrlRequest: (request: UrlRequest) => Message;
onUrlChange: (url: Url) => Message;
}>;
run
export declare function run<P extends Ports | undefined, Flags, Resources, Kind extends 'Application' | 'Element'>(program: MakeRuntimeReturn<P, Flags, Resources, Kind>, options: RunOptions<Flags, Resources>): void;
run
Starts a Foldkit runtime that owns the page for the page's whole lifetime,
with state-preserving live reload for development. The first render builds
the DOM fresh in the container, replacing whatever is there. On a
server-rendered page use `hydrate` instead, which adopts the existing DOM.
To start a runtime under a host-controlled lifecycle, use `embed`.
export declare function run<P extends Ports | undefined, Resources, Kind extends 'Application' | 'Element'>(program: MakeRuntimeReturn<P, void, Resources, Kind>): void;
RunOptions
Client-only startup input for an application that declares Flags. Pass it
to `run` or `embed`; `hydrate` instead decodes the exact Flags value
embedded by the server render.
export type RunOptions<Flags, Resources = never> = Readonly<{
flags: Effect.Effect<Flags, never, Resources>;
}>;
SlowConfig
Slow-phase warning configuration.
By default, all phases are enabled in development with Foldkit's default
thresholds. Pass `false` to disable warnings entirely. Pass an object to
refine those defaults.
- `show`: `'Development'` (default) enables warnings only under Vite's dev
server. `'Always'` enables them in every environment.
- `measuredPhases`: Phases to measure. Defaults to every slow warning phase.
- `thresholdOverrides`: Per-phase budget overrides. Omitted fields keep defaults; overrides for unmeasured phases are ignored.
- `onSlow`: Callback for every measured phase that exceeds its budget. Replaces Foldkit's default `console.warn`; Foldkit will not also warn for tags your callback ignores.
export type SlowConfig<Model, Message> = false | Readonly<{
show?: Visibility;
measuredPhases?: ReadonlyArray<SlowPhase>;
thresholdOverrides?: SlowThresholdOverrides;
onSlow?: (context: SlowContext<Model, Message>) => void;
}>;
SlowContext
Tagged union of every slow-phase context passed to `slow.onSlow`.
export type SlowContext<Model, Message> = SlowViewContext<Model, Message> | SlowUpdateContext<Model, Message> | SlowPatchContext<Model, Message> | SlowSubscriptionDependenciesContext<Model>;
SlowPatchContext
Context provided when DOM patching exceeds its configured time budget.
export type SlowPatchContext<Model, Message> = Readonly<{
_tag: 'Patch';
model: Model;
message: Option.Option<Message>;
durationMs: number;
thresholdMs: number;
}>;
SlowPhase
export type SlowPhase = typeof SlowPhase.Type;
SlowPhase
Phase names measured by the slow warning runtime option.
SlowPhase: Schema.Literals<readonly ["Update", "View", "Patch", "SubscriptionDependencies"]>
SlowSubscriptionDependenciesContext
Context provided when subscription dependency extraction exceeds its configured time budget.
export type SlowSubscriptionDependenciesContext<Model> = Readonly<{
_tag: 'SubscriptionDependencies';
subscriptionKey: string;
model: Model;
durationMs: number;
thresholdMs: number;
}>;
SlowThresholdOverrides
Budget overrides for slow warning phases. Omitted fields use Foldkit defaults.
export type SlowThresholdOverrides = Readonly<{
Update?: number;
View?: number;
Patch?: number;
SubscriptionDependencies?: number;
}>;
SlowUpdateContext
Context provided when update exceeds its configured time budget.
export type SlowUpdateContext<Model, Message> = Readonly<{
_tag: 'Update';
previousModel: Model;
nextModel: Model;
message: Message;
durationMs: number;
thresholdMs: number;
}>;
SlowViewContext
Context provided when view construction exceeds its configured time budget.
export type SlowViewContext<Model, Message> = Readonly<{
_tag: 'View';
model: Model;
message: Option.Option<Message>;
durationMs: number;
thresholdMs: number;
}>;
ViewTransitionConfig
Decides, per render, whether the DOM update should run inside a View
Transition. The predicate is total over the Message union, so animation is
opted into per Message: return `true` for the ones worth animating and
`false` for everything else.
export type ViewTransitionConfig<Model, Message> = (context: ViewTransitionContext<Model, Message>) => ViewTransitionDecision;
ViewTransitionContext
Context passed to the `viewTransition` predicate before each live render.
A View Transition animates between two states, so the predicate is given
both. `previousModel` is the Model behind the DOM on screen, the state the
browser is about to snapshot. `model` is the Model the pending render will
paint. Direction is the pair: comparing the two says where the application
is going and where it came from, with no route history kept in the Model.
`previousModel` is always a real painted state rather than an `Option`. The
predicate only runs once a Message has dirtied the Model, and the initial
render completes before any Message is processed.
`message` is the Message that dirtied the Model for this frame. The runtime
coalesces a burst of dispatches into one render frame, so the predicate
sees the last dirtying Message before the frame.
export type ViewTransitionContext<Model, Message> = Readonly<{
previousModel: Model;
model: Model;
message: Message;
}>;
ViewTransitionDecision
What the `viewTransition` predicate returns for a render. `false` renders
plainly. `true` wraps the render in `document.startViewTransition`.
`{ types }` additionally tags the transition so CSS can scope animations
via `:active-view-transition-type(...)`.
export type ViewTransitionDecision = boolean | Readonly<{
types: ReadonlyArray<string>;
}>;
Visibility
Controls when a feature is shown.
export type Visibility = 'Development' | 'Always';