import { Actyx } from '@actyx/sdk'; import { ActyxOpts } from '@actyx/sdk'; import { AppManifest } from '@actyx/sdk'; import { CancelSubscription } from '@actyx/sdk'; import * as immutable from 'immutable'; import { Metadata } from '@actyx/sdk'; import { Milliseconds } from '@actyx/sdk'; import { NodeId } from '@actyx/sdk'; import { NodeInfo } from '@actyx/sdk'; import { PendingEmission } from '@actyx/sdk'; import { TaggedEvent } from '@actyx/sdk'; import { TaggedTypedEvent } from '@actyx/sdk'; import { Tags } from '@actyx/sdk'; import { TestEvent } from '@actyx/sdk'; import { TimeInjector } from '@actyx/sdk'; import { Where } from '@actyx/sdk'; /** * Queue emission of an event whose type is covered by `EWrite`. * @public */ export declare type AddEmission = (...args: [Tags, E] | [TaggedTypedEvent]) => void; /** Caching indicator for pond.observeAll(). * @beta */ export declare type Caching = NoCaching | InProcessCaching; /** Caching related functions * @beta */ export declare const Caching: { none: { type: "none"; }; isEnabled: (c: Caching | undefined) => c is InProcessCaching; inProcess: (key: string) => Caching; }; /** * Immutable swarm counters information. * @public */ export declare type Counters = Readonly; /** * Mutable swarm counters information. * @public */ export declare type CountersMut = { /** * The pond has it, the swarm doesn't */ own: number; /** * The swarm has it, the pond does not */ swarm: number; /** * Both the pond and the swarm have it */ both: number; }; /** * A `Fish` describes an ongoing aggregration (fold) of events of type `E` into state of type `S`. * A Fish always sees events in the correct order, even though event delivery on Actyx is only eventually consistent: * To this effect, arrival of an hitherto unknown event "from the past" will cause a replay of the aggregation * from an earlier state, instead of passing that event to the Fish out of order. * @public */ export declare type Fish = { /** * Selection of events to aggregate in this Fish. * You may specify plain strings inline: `where: Tags('my', 'tag', 'selection')` (which requires all three tags) * Or refer to typed static tags: `where: myFirstTag.and(mySecondTag).or(myThirdTag)` * In both cases you would select events which contain all three given tags. */ where: Where; initialState: S; /** * Function to create the next state from previous state and next event. It works similar to `Array.reduce`. * Do note however that — while it may modify the passed-in state — this function must be _pure_: * - It should not cause any side-effects (except logging) * - It should not reference dynamic outside state like random numbers or the current time. The result must depend purely on the input parameters. */ onEvent: Reduce; fishId: FishId; isReset?: IsReset; deserializeState?: (jsonState: unknown) => S; }; /** * Fish generic generator methods. * @public */ export declare const Fish: { latestEvent: (where: Where) => Fish; eventsDescending: (where: Where, capacity?: number) => Fish; eventsAscending: (where: Where, capacity?: number) => Fish; }; /** Context for an error thrown by a Fish’s functions. * @public */ export declare type FishErrorContext = { occuredIn: 'onEvent'; state: unknown; event: unknown; metadata: Metadata; } | { occuredIn: 'isReset'; event: unknown; metadata: Metadata; } | { occuredIn: 'deserializeState'; jsonState: unknown; }; /** Error reporter for when Fish functions throw exceptions. * @public */ export declare type FishErrorReporter = (err: unknown, fishId: FishId, detail: FishErrorContext) => void; /** * Unique identifier for a fish. * @public */ export declare type FishId = { entityType: string; name: string; version: number; }; /** * FishId associated functions. * @public */ export declare const FishId: { /** * Create a FishId from three components. * * @param entityType - A general description for the class of thing the Fish represents, e.g. 'robot' * @param name - Concrete name of the represented thing, e.g. 'superAssembler2000' * @param version - Version of the underlying code. Must be increased whenever the Fish’s underlying logic or event selection changes. * @returns A FishId. */ of: (entityType: string, name: string, version: number) => { entityType: string; name: string; version: number; }; canonical: (v: FishId) => string; }; /** * How many Fish are active, and of which entityTypes? * @public */ export declare type FishProcessInfo = { numBeingProcessed: number; fish: { [semantics: string]: true | undefined; }; }; /** Configure how to wait for swarm. * @public */ export declare type FullWaitForSwarmConfig = { /** * Splash screen enabled */ enabled: boolean; /** * Delay until we consider that we got the swarm state */ waitForSwarmMs: number; /** * Minimum number of sources until we consider that we got the swarm state */ minSources: number; /** * Delay that we allow to sync with the swarm state (leave undefined to wait indefinitely) */ waitForSyncMs?: number; /** * True if we allow the user to skip the splash screen */ allowSkip: boolean; }; /** Parameter object for the `Pond.getNodeConnectivity` call. * @public */ export declare type GetNodeConnectivityParams = { callback: (newState: unknown) => void; specialSources?: NodeId[]; }; /** Indicate in-process (nonpersistent) Caching. * @beta */ export declare type InProcessCaching = { type: 'in-process'; key: string; }; /** * A function indicating events which completely determine the state. * Any event for which isReset returns true will be applied to the initial state, all earlier events discarded. * @public */ export declare type IsReset = (event: E, metadata: Metadata) => boolean; /** Indicator for disabled caching of pond.observeAll(). * @beta */ export declare type NoCaching = { readonly type: 'none'; }; /** * All the info we got for a single node * * This might grow in the future to include things like timestamps * @public */ export declare type NodeInfoEntry = { own?: number; swarm?: number; }; /** Optional parameters to pond.observeAll * @beta */ export declare type ObserveAllOpts = Partial<{ /** * How to cache the known set of Fish. * Defaults to no caching, i.e. the set will be rebuilt from events on every invocation. */ caching: Caching; /** Fish expires from the set of 'all' when its first event reaches a certain age */ expireAfterSeed: Milliseconds; /** * @deprecated Renamed to `expireAfterSeed` */ expireAfterFirst: Milliseconds; }>; /** Pending command application. * @public */ export declare type PendingCommand = { subscribe: (whenEmitted: () => void) => void; toPromise: () => Promise; }; /** * Main interface for interaction with the Actyx event system. * New instances are created via `Pond.default()` or `Pond.of(options)`. * Acquire a Pond for testing (which uses a simulated clean Event Store) via `Pond.test()`. * @public */ export declare type Pond = { /** * Emit a single event directly. * * @typeParam E - Type of the event payload. If your tags are statically declared, * their type will be checked against the payload’s type. * * @param tags - Tags to attach to the event. E.g. `Tags('myTag', 'myOtherTag')` * @param event - The event itself. * @returns A `PendingEmission` object that can be used to register * callbacks with the emission’s completion. * * @deprecated Use `publish` instead, and always await the Promise. */ emit(tags: Tags, event: E): PendingEmission; /** * Publish any number of events. * * @param events - Events to publish. Use `Tag('foo').apply(event)` to create an array of `TaggedEvent`. * * @returns A Promise that resolves to the emitted event’s metadata. */ publish(event: TaggedEvent): Promise; publish(events: TaggedEvent[]): Promise; /** * Observe the current state of a Fish. * * Caching is done based on the `fishId` inside the `fish`, i.e. if a fish with the included * `fishId` is already known, that other Fish’s ongoing aggregation will be used instead of * starting a new one. * * @param fish - Complete Fish information. * @param callback - Function that will be called whenever a new state becomes available. * @param stoppedByError - Function that will be called when one of the Fish’s functions throws an error. * A Fish will always stop emitting further states after errors, even if no `stoppedByError` argument is passed. * @returns A function that can be called in order to cancel the subscription. */ observe(fish: Fish, callback: (newState: S) => void, stoppedByError?: (err: unknown) => void): CancelSubscription; /** * Read the current state of a Fish. * * Caching is done based on the `fishId` inside the `fish`, i.e. if a fish with the included * `fishId` is already known, that other Fish’s ongoing aggregation will be used instead of * starting a new one. * * @param fish - Complete Fish information. * * @returns A Promise that resolves to the Fish’s latest known state. If the Fish was stopped due to an error, the Promise will reject with that error. */ currentState(fish: Fish): Promise; /** * Create Fish from events and observe them all. * Note that if a Fish created from some event f0 will also observe events earlier than f0, if they are selected by `where` * * @typeParam F - Type of the events used to initialize Fish. * @typeParam S - Type of the observed Fish’s state. * * @param seedEventsSelector - A `Where` object identifying the seed events to start Fish from * @param makeFish - Factory function to create a Fish with state `S` from an event of type `F`. * If Fish with same FishId are created by makeFish, these Fish must be identical! * `undefined` may be returned to indicate the given seed event should not be converted to a Fish at all. * @param opts - Optional arguments regarding caching and expiry * @param callback - Function that will be called with the array of states whenever the set of Fish * changes or any of the contained Fish’s state changes. * * @returns A function that can be called in order to cancel the subscription. * * @beta */ observeAll(seedEventsSelector: Where, makeFish: (seedEvent: ESeed) => Fish | undefined, opts: ObserveAllOpts, callback: (states: S[]) => void): CancelSubscription; /** * Find the event selected by `firstEvent`, and start a Fish from it. * It is legal for `firstEvent` to actually select multiple events; * however, `makeFish` must yield the same Fish no matter one is passed in. * * @typeParam F - Type of the initial event. * @typeParam S - Type of the observed Fish’s state. * * @param seedEventSelector - A `Where` object identifying the seed event * @param makeFish - Factory function to create the Fish with state `S` from the event of type `F`. * The Fish is able to observe events earlier than the first event. * @param callback - Function that will be called with the Fish’s state `S`. * As long as the first event does not exist, this callback will also not be called. * * @returns A function that can be called in order to cancel the subscription. * * @beta */ observeOne(seedEventSelector: Where, makeFish: (seedEvent: ESeed) => Fish, callback: (newState: S) => void, stoppedByError?: (err: unknown) => void): CancelSubscription; /** * Run a `StateEffect` against currently known local state of Fish. Emit events based on it by * calling the `enqueue` function passed into the invocation of your effect. Every subsequent * invocation of `run` for the same Fish is guaranteed to see all events previously enqueued by * effects on that Fish already applied to the state. (Local serialisation guarantee.) * * In regards to other nodes or Fishes, there are no serialisation guarantees. * * @typeParam S - State of the Fish, input value to the effect. * @typeParam EWrite - Event type(s) the effect may emit. * * @param fish - Complete Fish information. * @param effect - Function to enqueue new events based on state. * @returns A `PendingEmission` object that can be used to register callbacks with the effect’s completion. */ run(fish: Fish, fn: StateEffect): PendingCommand; /** * Install a StateEffect that will be applied automatically whenever the `Fish`’s State has changed. * Every application will see the previous one’s resulting Events applied to the State already, if applicable; * but any number of intermediate States may have been skipped between two applications. * * In regards to other nodes or Fishes, there are no serialisation guarantees. * * The effect can be uninstalled by calling the returned `CancelSubscription`. * * @typeParam S - State of the Fish, input value to the effect. * @typeParam EWrite - Event type(s) the effect may emit. * * @param fish - Complete Fish information. * @param effect - Function that decides whether to enqueue new events based on the current state. * @param autoCancel - Condition on which the automatic effect will be cancelled -- state on which `autoCancel` returns `true` * will be the first state the effect is *not* applied to anymore. Keep in mind that not all intermediate * states will be seen by this function. * @returns A `CancelSubscription` object that can be used to cancel the automatic effect. */ keepRunning(fish: Fish, fn: StateEffect, autoCancel?: (state: S) => boolean): CancelSubscription; /** * Dispose of this Pond, stopping all underlying async operations. */ dispose(): void; /** * Information about the current pond */ info(): PondInfo; /** * Obtain information on the Actyx node. In order to save some cycles, and because the information * doesn’t change all that quickly, please provide a time parameter that matches your app’s * freshness requirements — for human consumption a couple hundred milliseconds is good enough. * * The underlying API endpoint has been added in Actyx 2.5.0, earlier versions report dummy data. */ nodeInfo(maxAgeMillis: number): Promise; /** * Register a callback invoked whenever the Pond’s state changes. * The `PondState` is a general description of activity within the Pond internals. */ getPondState(callback: (newState: PondState) => void): CancelSubscription; /** * Wait for the node to get in sync with the swarm. * It is strongly recommended that any interaction with the Pond is delayed until the onSyncComplete callback has been notified. * To obtain progress information about the sync, the onProgress callback can be supplied. */ waitForSwarmSync(params: WaitForSwarmSyncParams): void; /** * Get an object that offers a number of functions related purely to events (no Fish). */ events(): Actyx; }; /** Static methods for constructing Pond instances. * @public */ export declare const Pond: { /** Start Pond with default parameters. * @public */ default: (manifest: AppManifest) => Promise; /** Start Pond with custom parameters. * @public */ of: (manifest: AppManifest, connectionOpts: ActyxOpts, opts: PondOptions) => Promise; /** Start Pond from provided Actyx SDK instance. * @public */ from: (actyx: Actyx, opts: PondOptions) => Pond; /** * Get a Pond instance that runs a simulated store locally * whose contents can be manually modified. * @public */ test: (opts?: TestPondOptions | undefined) => TestPond; }; /** Information concerning the running Pond. * @public */ export declare type PondInfo = { nodeId: NodeId; }; /** Advanced configuration options for the Pond. * @public */ export declare type PondOptions = { /** * Callback that is invoked whenever Fish execution encounters an error. * If none is supplied, errors will be logged to the console. */ fishErrorReporter?: FishErrorReporter; }; /** * What sort of activity is currently going on in the Pond? * @public */ export declare type PondState = { hydration: FishProcessInfo; commands: FishProcessInfo; eventsFromOtherSources: FishProcessInfo; }; /** * `PondState` associated functions. * @public */ export declare const PondState: { isHydrating: (state: PondState) => boolean; isProcessingCommands: (state: PondState) => boolean; isProcessingEventsFromOtherSources: (state: PondState) => boolean; isBusy: (state: PondState) => boolean; }; /** Sync progress in terms of event numbers. * @public */ export declare type Progress = { min: number; current: number; max: number; }; /** * Combine the existing ("old") state and next event into a new state. * The returned value may be something completely new, or a mutated version of the input state. * @public */ export declare type Reduce = (state: S, event: E, metadata: Metadata) => S; /** * Current state of swarm synchronization procedure. * @public */ export declare type SplashState = SplashStateDiscovery | SplashStateSync; /** * Discovering swarm state. * @public */ export declare type SplashStateDiscovery = { mode: 'discovery'; current: SwarmSummary; skip?: () => void; }; /** * Synchronizing up to the discovered swarm state. * @public */ export declare type SplashStateSync = { mode: 'sync'; reference: SwarmSummary; progress: SyncProgress; current: SwarmSummary; skip?: () => void; }; /** * Enqueue event emissions based on currently known local state. * @public */ export declare type StateEffect = (state: S, enqueue: AddEmission, pond: Pond) => void | Promise; /** * All the info we got for our device in relation to the swarm * @public */ export declare type SwarmInfo = { nodes: immutable.Map; }; /** * Summary of swarm info * @public */ export declare type SwarmSummary = { info: SwarmInfo; sources: Counters; events: Counters; }; /** SwarmSummary associated functions. * @public */ export declare const SwarmSummary: { empty: SwarmSummary; fromSwarmInfo: (info: SwarmInfo) => SwarmSummary; }; /** Sync progress per source, and overall. * @public */ export declare type SyncProgress = { sources: Progress; events: Progress; }; /** A Pond with extensions for testing. * @public */ export declare type TestPond = Pond & { directlyPushEvents: (events: TestEvent[]) => void; }; /** Extended options for TestPond. * @public */ export declare type TestPondOptions = PondOptions & { timeInjector?: TimeInjector; }; /** * Assert that from the type information, a piece of code can never be reached. * If it’s still reached at runtime, this throws an Error. * @public */ export declare const unreachable: (x?: never) => never; /** * Assert that from the type information, a certain statement can never be reached, * while installing a default value to return in case the type information was wrong * and the statement was in fact reached. * @public */ export declare function unreachableOrElse(_: never, t: T): T; /** Partially configure waiting for the swarm. * @public */ export declare type WaitForSwarmConfig = Partial; /** `WaitForSwarmConfig` associated functions. * @public */ export declare const WaitForSwarmConfig: { defaults: FullWaitForSwarmConfig; }; /** Parameter object for the `Pond.waitForSwarmSync` call. * @public */ export declare type WaitForSwarmSyncParams = WaitForSwarmConfig & { onSyncComplete: () => void; onProgress?: (newState: SplashState) => void; }; export * from "@actyx/sdk"; export { }