/** * Copyright (c) 2025 Elara AI Pty Ltd * Dual-licensed under AGPL-3.0 and commercial license. See LICENSE for details. */ /** * Runtime implementation for the `Func.bind` platform function — calling * named package functions (`e3.function`) from East UI code, RPC-style. * * A tracked call is an un-awaited `FunctionApi.call` promise tagged with * the monotonic `launchSeq` it was issued under; whichever response still * holds the current seq writes the terminal state (latest-wins). A call is * the server's for its lifetime, and outlives the request that starts it: * `cancel`, and a call that supersedes another on its channel, bump the seq * and abort the in-flight call's signal, which asks the server to stop it. * So does its page going: the provider's teardown ({@link FuncRuntime.clear}) * and the page closing for good (`pagehide`, unless the page is kept for the * back button) stop every call in flight. e3's client names each call before * it sends it, so a call is asked to stop however soon its page goes. * * All handles bound to the same function name in the same workspace share * one registry entry, mirroring how `Data.bind` handles share the dataset * cache by path. Declared signatures are validated against the deployed * package's function list before any call is sent. * * A handle of a function that lists `drafts` takes them as its call's last * argument (east-workspace#1620): unsaved edits of the records the function * reads, sent with the call, which e3 lays over them and never saves. The * channel keeps, with a call's result, the records that call drafted and the * commit each stood at; a draft the record refuses ends the call as the Save * of it would have ended, and the error names the draft. * * State (registry, signature cache, tracking context) is encapsulated in * the {@link FuncRuntime} class. A process-global {@link defaultFuncRuntime} * powers the `FuncPlatform` export; tests construct their own runtime for * isolation. * * @packageDocumentation */ import { type EastType, type EastTypeValue, type ValueTypeOf } from "@elaraai/east"; import { type PlatformFunction } from "@elaraai/east/internal"; import { FuncDraftType, FuncDraftedType, FuncStatusType, FuncErrorType } from "@elaraai/e3-ui/internal"; import { type ExecuteResult, type FunctionSignature, type RequestOptions } from "@elaraai/e3-api-client"; import { TrackedChannelStore } from "./tracked-channel.js"; /** A draft, decoded: a call of a record's mutation that is not committed. */ export type FuncDraft = ValueTypeOf; /** A record a call drafted, decoded: its name and the commit it stood at. */ export type FuncDrafted = ValueTypeOf; /** Request shape for {@link FunctionApi.call} — beast2-encoded positional * args, and the call's drafts. Runner/limit overrides are deliberately not * exposed (the deployed function's runner is authoritative). */ export interface FunctionCallArgs { args: Uint8Array[]; /** The call's drafts: unsaved edits of records the function lists, which * the call lays over them and never saves. None, and the function reads * the workspace as saved. */ drafts: FuncDraft[]; } /** Options for {@link FunctionApi.call}. */ export interface FunctionCallOptions { /** Stops the call: the call stops waiting, and asks the server to stop it */ signal?: AbortSignal; } /** * Adapter for the workspace function endpoints. The default wraps * `@elaraai/e3-api-client`'s `workspaceFunctionList` / * `workspaceFunctionCall`. */ export interface FunctionApi { /** List the workspace's deployed functions with their signatures. */ list(workspace: string): Promise; /** * Call a function, returning its terminal ExecuteResult once it ends, * however long it runs. Aborting `options.signal` stops the call: its * promise rejects with the abort, and the server is asked to stop it. */ call(workspace: string, fn: string, req: FunctionCallArgs, options?: FunctionCallOptions): Promise; } /** Options for {@link createDefaultFunctionApi}. */ export interface DefaultFunctionApiOptions { /** * How long a call's start waits for it to end before it answers * `running`, in milliseconds: the server's window unless set. A call that * ends within it costs one request; one that runs on past it is polled. */ readonly startWaitMs?: number; } /** * Build the default {@link FunctionApi} that talks to a real e3 server via * `@elaraai/e3-api-client`. * * @param apiUrl - Base URL of the e3 API server * @param repo - Repository name * @param getOptions - Reads the current request options — the token, and the * `fetch` requests go through — so a rotated one is used at once * @param options - How long a call's start waits for it to end * @returns The adapter */ export declare function createDefaultFunctionApi(apiUrl: string, repo: string, getOptions: () => RequestOptions, options?: DefaultFunctionApiOptions): FunctionApi; type FuncError = ValueTypeOf; type FuncStatusTag = ValueTypeOf["type"]; /** A handle's signature, recovered from the instantiated handle type. */ interface FuncHandleSignature { /** The function's argument types: what its call takes before any drafts. */ readonly inputs: EastTypeValue[]; readonly output: EastTypeValue; /** Whether the handle is of a function that lists `drafts`: its call takes * them after the arguments, and it has `drafted`. */ readonly drafts: boolean; } /** * Introspect the instantiated handle struct type `H`: the input types come * from the `call` field's FunctionType, the output type from the `read` * field's `Option(Output)` return. The handle's shape IS the signature — * there are no duplicate signature arguments to drift out of sync. * * A handle has what its type names: one with `drafted` is of a function that * lists `drafts`, and its `call`'s last input is the drafts, not an argument * of the function. */ export declare function signatureOfFuncHandleType(handleType: EastTypeValue): FuncHandleSignature; /** The draft whose mutation ended a failed call, decoded: its place among the call's drafts, from 1, and what its record said of it. */ export type FuncFailedDraft = ValueTypeOf; /** * The draft whose mutation failed as a call laid it, ending the call before its function ran (east-workspace#1619, * rule 8), as the call's error carries it: its place among the call's drafts, and what its record said of it. * * @param error - A call's error, as {@link errorOfExecuteResult} makes it * @returns The draft; `undefined` for a call that ended another way, and for a failed one no draft's mutation ended */ export declare function failedDraft(error: FuncError): FuncFailedDraft | undefined; /** * What a record said of a draft it refused as a call laid it (east-workspace#1619, rule 8): the message its mutation's * program raised, as the call's error carries it — the reason a Save of the same edit is refused for. What shows why * a call ended says them in place of the call's own summary, which names the draft and no reason. * * @param error - A failed call's error, as {@link errorOfExecuteResult} makes it * @returns The record's words; `undefined` for a call no draft's mutation failed, and for one that said nothing */ export declare function draftRefusal(error: FuncError): string | undefined; /** One tracked channel per `(workspace, name)`. */ interface FuncEntry { status: FuncStatusTag; /** Monotonic; a settling call whose seq is no longer current is * discarded (latest-wins, and `cancel` orphans by bumping it). */ launchSeq: number; /** Decoded Output of the last `succeeded` call. */ result?: unknown; /** The records that call drafted, each with the commit it stood at as the * server laid its drafts: kept with `result`, which it answers for. */ drafted?: FuncDrafted[]; /** Detail of the last `failed` call. */ error?: FuncError; /** Stops the call in flight, while one is: a call that supersedes it, and * `cancel`, abort it, which asks the server to stop it. */ inflight?: AbortController; } /** Tracked-channel key. */ export declare function funcChannelKey(workspace: string, name: string): string; /** What tells a runtime its page is going: a page's window, or a stand-in. */ export type FuncPage = Pick; /** Options for {@link FuncRuntime}. */ export interface FuncRuntimeOptions { /** * The page whose closing stops the calls in flight: its `pagehide`, unless * the page is kept for the back button (`persisted`). Default: the global * object where it has events, a browser's window; none elsewhere. */ readonly page?: FuncPage | null; } /** * Encapsulates all `Func.bind` runtime state. The module-level * {@link defaultFuncRuntime} instance backs the registered platform; tests * construct their own for isolation. */ export declare class FuncRuntime extends TrackedChannelStore { private api; private workspace; /** The page whose closing stops the calls in flight; none outside a browser. */ private readonly page; /** Stops watching the page, while an adapter is installed. */ private unwatchPage; /** * @param options - The page whose closing stops the calls in flight */ constructor(options?: FuncRuntimeOptions); private signatureLists; private readonly handleCache; protected createEntry(): FuncEntry; /** Install the API adapter + workspace — called by the React provider * (or a test, or the snapshot harness) before any handle is used. From * now until {@link clear}, the page closing for good stops the calls in * flight. */ initialize(api: FunctionApi, workspace: string): void; /** * Tear down the adapter and all call state. A call in flight is its * page's, and its page is going: each is asked to stop on the server. * * @param api - Clear only while this is the installed adapter, so a * provider tearing down after another installed its own leaves that one * in place */ clear(api?: FunctionApi): void; /** Stops the calls in flight once the page closes for good: a page kept * for the back button may come back, its calls with it. */ private watchPage; /** Cancels a channel's call in flight: the server is asked to stop it. */ private cancelCall; /** Cancels every call in flight, each asked to stop on the server. */ private stopInFlight; /** The deployed signature list for a workspace (fetched once). */ private signatures; /** Validate a declared signature against the deployed list. Returns a * FuncError when the name is unknown or the signature disagrees. */ private validate; private launch; /** * The low-level primitives backing handle methods, bound to THIS runtime. * Registered globally (extension registry) and included by the scoped * platform (e3 `ui()` tasks) so a decoded handle re-binds to whatever runtime * resolves the primitives on the decode side. The host effects (launch / * channel reads + reactive tracking) live here, keyed only on the plain-data * function name; the output type rides as a type-arg. */ buildPrimitives(): PlatformFunction[]; /** * Build the handle value for one `Func.bind` evaluation. The methods are * thin IR-bearing `East.function`s over {@link buildPrimitives}, capturing * only the function name (and the signature types via type-args) — so the * handle is ordinary serializable East data (issue #106). * * A handle has what its type names: one whose type has `drafted` is of a * function that lists `drafts`, and its `call` takes them last; any other * has today's call, which sends none. * * @param handleType - The instantiated handle struct type * @param name - The function's name in the deployed package * @param drafts - The records the function lists in its `drafts`, by name: * what the handle's `binding` carries * @param reads - The records the function reads, by name, which the * handle's `binding` carries too * @returns The handle: the cached methods, and a binding of its own */ buildHandle(handleType: EastTypeValue, name: string, drafts: readonly string[], reads: readonly string[]): Record; /** Build a `Func.bind` PlatformFunction bound to this runtime. Pass * `allowed=null` for an unscoped impl; pass a Set of function names * for manifest scoping. */ buildPlatform(allowed: ReadonlySet | null): PlatformFunction; } /** Process-global runtime backing the `FuncPlatform` export. */ export declare const defaultFuncRuntime: FuncRuntime; /** Install the function API adapter + workspace — called by the React * provider on mount (or by a test, or the snapshot harness). */ export declare function initializeFunctionApi(api: FunctionApi, workspace: string): void; /** * Tear down the function API adapter and all call state. * * @param api - Clear only while this is the installed adapter */ export declare function clearFunctionApi(api?: FunctionApi): void; /** Global, manifest-unscoped `Func.bind` impl + its backing primitives. * Registered on module load (powers the extension registry decode path). */ export declare const FuncPlatform: PlatformFunction[]; /** Build a manifest-scoped `Func.bind` implementation + its backing primitives. * * The `function_*` primitives MUST ship with the scoped platform: e3 `ui()` * tasks render through `createScoped*()` arrays (UITaskPreview), NOT the global * registry, so a serialized handle's methods would otherwise decode to * "Platform function 'function_call' is not available". */ export declare function createScopedFuncPlatform(functions: readonly string[]): PlatformFunction[]; /** One offline function implementation for {@link createInMemoryFunctionApi}. */ export interface InMemoryFunctionDef { /** Function name (what `Func.bind` is bound to). */ name: string; /** The argument types a caller passes. */ argTypes: (EastType | EastTypeValue)[]; /** Return type. */ outputType: EastType | EastTypeValue; /** The implementation — receives decoded args, returns the result * value (or a promise of it). */ fn: (...args: unknown[]) => unknown; } /** * Build an offline {@link FunctionApi} from local implementations — the * snapshot harness's stand-in for a deployed package. It reads no record, so * it has none to lay a draft over: a call that passes one ends `invalid`, * naming the draft, and a call that passes none runs. */ export declare function createInMemoryFunctionApi(functions: InMemoryFunctionDef[]): FunctionApi; export {}; //# sourceMappingURL=func-runtime.d.ts.map