Interface in Client and Lifecycle · JavaScript & TypeScript
Use a bot client for messages, community resources, HTTP requests and gateway events
Call methods directly. Network and other I/O operations start immediately and return ResultAsync. Await it to receive Ok or Err. If is is true, read error. Otherwise, read value, or call or to get the value and throw the error instead. Expected failures are Err values, and an Err returned from a handler is reported like a thrown error. Local registration and cache lookups return their value directly and throw Configuration when misused. Subscriptions and collectors registered after shutdown began, such as from a handler still running, return already-closed handles. Middleware registration on a closing client throws Client. Unexpected SDK or cleanup failures reject with Sdk. Use run for a connection lifetime controlled by its signal. Alternatively, connect for startup, wait for terminal failure, and shutdown for final cleanup. Use await using to shut the client down when the enclosing block ends
interface Client<M extends MessageCore = Message>
extends AsyncDisposableinterface Client<
M extends MessageCore = Message
>
extends AsyncDisposableA malformed options returns Configuration for signal before work starts.
A valid aborted signal returns Cancelled.
Cleanup failure stops retries and preserves safe details of an accompanying failure or cancellation.
Shared REST success JSON is limited to 16 MiB before parsing, not total memory.
Upload-plan and completion responses have a separate 1 MiB limit
Confirmed HTTP 429 responses with a valid retry delay pause all of this client's API routes when
X-RateLimit-Global is true, X-RateLimit-Scope is global, or the bounded JSON body has global: true.
A valid global assertion wins over conflicting local metadata. Malformed scope values are ignored.
A global header with a valid Retry-After starts the pause before body inspection, including when
the body is missing, malformed, oversized or too slow. Body inspection stays bounded to 8 KiB and 100 ms before awaited cleanup.
Without global metadata, only requests in the same rate-limit group wait. Without a usable delay, the rejection fails instead of guessing how long to wait.
Waits remain within each call's original deadline. Cancelling a queued call removes only that call, not the shared pause.
A call whose known pause outlasts its deadline fails at once with reason rate and the remaining wait as retry instead of waiting.
Separate clients do not coordinate these waits. Attachment downloads do not wait for API rate limits.
Writes retry only confirmed rate-limit rejection, never an uncertain outcome
Valid X-RateLimit-Bucket metadata tells the client which requests share a rate limit, without application configuration. For known Fluxer routes, requests remain grouped by their channel, community, user, webhook or invite resource. Unknown routes reporting the same bucket identifier share one rate-limit group within this client. Initial requests can still receive 429 before the server's grouping is learned. Each client tracks at most 2,048 route aliases and 2,048 rate-limit groups. Unused aliases expire after five minutes unless a pause is still active. An older response cannot replace a newer grouping or lift a rate-limit pause early. Regrouping preserves an existing pause until it expires. When tracking is full, the client discards groups without active pauses first. If active pauses fill capacity or a request cannot be grouped safely, the client waits rather than ignoring a known limit. Closing the client clears this temporary tracking data
Each gateway connection accepts complete uncompressed text messages up to 100 MiB (104,857,600 bytes), including fragments combined.
The transport enforces this fixed receive ceiling before UTF-8 decoding and JSON parsing. It preserves the previous transport default.
This is not a Fluxer server-to-client maximum, an outbound command limit, a subscription budget or a JavaScript heap bound.
Larger messages fail with Connection, phase gateway, reason protocol and status 1009. Invalid UTF-8 uses status 1007.
Neither failure retries automatically.
A failed standalone connect waits for cleanup and allows another explicit connect.
A failed managed run or established connection ends the client lifetime.
Use wait to observe later failures
Properties#
application#
Read documented fields for the authenticated bot's application, without owner details or management operations
readonly application: CurrentBotApplicationattachments#
Refresh signed attachment URLs explicitly or download from this instance's discovered media path with byte limits
readonly attachments: AttachmentsauditLogs #
Read filtered audit pages or bounded entry scans, without retaining an audit cache
readonly auditLogs: AuditLogscache#
Enumerate or release locally cached data
Caching is disabled unless enabled in Client
readonly cache: ClientCache<M>channels#
readonly channels: ChannelsdirectMessages #
Open and manage one-to-one or group conversations, or send a direct message
Use messages for other content operations once the channel IDs are known
readonly directMessages: DirectMessages<M>readonly directMessages: DirectMessages<
M
>discovery#
Search the public community directory and manage listings, without joining communities or finding instance endpoints
readonly discovery: Discoveryemojis#
Manage custom emoji and optionally look up their cached metadata
readonly emojis: Emojisgateway#
readonly gateway: GatewayCommandsgatewayLatencyMs #
The slowest current heartbeat round-trip time in milliseconds across this client's gateway shards
Null unless the client is Connected and every local shard has a current heartbeat acknowledgement. Connection loss, recovery and shutdown clear the affected shard's measurement until its new connection receives an acknowledgement. Zero is a valid measurement, not a marker for unavailable data
readonly gatewayLatencyMs: number | nullreadonly gatewayLatencyMs:
| number | nullguilds#
Read community data and memberships, or use the optional local community cache
readonly guilds: Guildsinstance#
Find this client's instance endpoints and get pure asset and link URL helpers for that instance
readonly instance: Instanceinvites#
Inspect, create, list and revoke invite codes, without using them to join or retaining codes
readonly invites: InviteslastReceipt #
The receipt of the most recently accepted event, as Event numbers events, or 0 before the first
It is read live, counts every event the client accepted whether or not a handler receives it, and is not reset by reconnects. Events refused during a draining shutdown get no receipt. Work that is not an event, such as a timer or a command's follow-up, can use it to find its place in the event order: Record it when the work starts, and treat any event whose receipt is larger as newer than the work, such as a later edit that makes the work's result stale. Under a supervisor each child process numbers its own events, so values from different processes cannot be compared
readonly lastReceipt: numberconst edited = new Map()
export function trackEdits(client) {
return client.on("messageUpdate", (message, _signal, context) => void edited.set(message.id, context.receipt))
}
export async function summarize(client, messageId, work) {
const startedAt = client.lastReceipt
const summary = await work()
// An edit accepted after the work started makes the summary stale
return (edited.get(messageId) ?? 0) > startedAt ? undefined : summary
}
import type { Client } from "@neontechspace/fluxerly"
const edited = new Map<string, number>()
export function trackEdits(client: Client) {
return client.on("messageUpdate", (message, _signal, context) => void edited.set(message.id, context.receipt))
}
export async function summarize(client: Client, messageId: string, work: () => Promise<string>) {
const startedAt = client.lastReceipt
const summary = await work()
// An edit accepted after the work started makes the summary stale
return (edited.get(messageId) ?? 0) > startedAt ? undefined : summary
}
logging#
Change the log level and per-category levels while the client runs
readonly logging: ClientLoggingmembers#
readonly members: Membersmessages#
Read, send, edit and delete messages, use the optional message cache, or collect future messages and reactions
readonly messages: Messages<M>permissions#
Calculate permission flags locally or from fresh resource reads, without caching decisions
readonly permissions: PermissionHelperspresence#
Set bot status or select member presence updates, restored after gateway reconnects but not stored across process restarts
readonly presence: Presencerest#
Send requests to Fluxer API routes without an SDK method, through this client's shared request scheduling
readonly rest: RestRequestsroles#
readonly roles: Rolesshards#
Frozen connection state and heartbeat measurements for this client's shards, in configured local ID order
An unsharded client contains only shard ID zero until it moves to automatic sharding, and an automatically sized client contains none until its first connect has chosen the plan. Both contain the new plan's shards after a move. Inspect this to identify a recovering shard even while other shards remain ready. It excludes shards owned by other processes and does not establish whole-bot state or cross-process ordering
readonly shards: readonly ShardState[]state#
Current connection state, controlled by the SDK rather than the consumer
readonly state: ConnectionStatestickers#
Manage custom stickers and optionally look up their cached metadata
readonly stickers: Stickersthreads#
Create threads and forum posts, change, list and search threads, and manage thread members
readonly threads: Threads<M>users#
Fetch public account data or look up an account in the optional local cache
readonly users: Userswebhooks#
Manage webhooks with the bot's permissions, returning metadata without tokens
readonly webhooks: WebhooksMethods#
[asyncDispose] #
Shut down this client and wait for cleanup, as await using does at the end of a block
Unexpected cleanup failures reject with Sdk, as shutdown does
[asyncDispose](): Promise<void>- Returns
Promise<void>
connect#
Connect the gateway and complete when every shard assigned to this client has authenticated and received READY
This does not wait for GUILD_CREATE, a full community roster or all resources to load. Use connect when startup must finish separately from the client's lifetime. After success, the connection and automatic recovery continue until shutdown or permanent failure, and wait observes that later outcome
connect(options?: OperationOptions): ResultAsync<
void,
ConfigurationError | CancelledError | ConnectError
>connect(
options?: OperationOptions
): ResultAsync<
void,
| ConfigurationError
| CancelledError | ConnectError
>The call controls startup only, using the client's connection settings.
Cancellation or an expected failure before initial readiness waits for shard cleanup and leaves the client Disconnected, so connect can be tried again.
An already-connected client not managed by run succeeds without opening another socket.
A competing call fails with Client without disturbing active work, and closing clients fail with Client.
After initial readiness, permanent failure of a required shard in a multi-shard plan closes the client.
The wait method retains that failure as Shard with shard and failure
Parameters
optionsoptional-
OperationOptions
- Returns
ResultAsync< void, ConfigurationError | CancelledError | ConnectError >ResultAsync< void, | ConfigurationError | CancelledError | ConnectError >
diagnostics#
Read a frozen local report of active work, queues and cache occupancy
No request, telemetry or persistent record is created. The report excludes tokens, routes, resource IDs and payloads. Counts cover only this client's assigned shards and local work. Event counts include open sources, message and reaction collectors and executing subscription handlers, not an enforced client-wide admission quota. Accounted cache and queue bytes are not heap memory, process memory or remote storage. After closure, configured limits remain visible and retained counts show cleanup progress. These values do not prove remote completeness or gateway readiness. This runs immediately and takes no signal
diagnostics(): ClientDiagnostics- Returns
ClientDiagnostics
observeState #
Receive the current connection state, then later state updates
While a subscriber is busy, only the newest pending state is kept. Slow subscribers can miss intermediate states without delaying recovery. Ending the subscription drops pending delivery without stopping the client. Use wait, not state changes, to observe the client's terminal failure
observeState(
listener: (state: ConnectionState) => unknown
): StateObserverobserveState(
listener: (
state: ConnectionState
) => unknown
): StateObserverParameters
listener-
(state: ConnectionState) => unknown
- Returns
StateObserver
The listener runs asynchronously, one call at a time per subscriber, awaiting a returned promise.
A listener that throws, rejects or returns an Err result goes to the client-level on as an observer failure, or is logged at Error, and does not close the client.
The returned observer's close ends delivery, but cannot cancel listener code already running.
A listener that is not a function throws Configuration
on#
Register a handler for future events of one type, before or after connecting the client
Use the returned Subscription to close it and observe wait. No history is replayed and HTTP operations do not create events locally. Bulk deletion events do not also call message handlers. Enabled cache updates happen before handlers and do not depend on a subscription succeeding, including its overflow
on<K extends keyof EventMap<Message>>(
event: K,
handler: (
event: EventMap<M>[K],
signal: AbortSignal,
context: EventContext<K, M>
) => unknown,
options?: EventHandlerOptions<EventMap<M>[K]>
): Subscriptionon<
K extends keyof EventMap<Message>
>(
event: K,
handler: (
event: EventMap<M>[K],
signal: AbortSignal,
context: EventContext<K, M>
) => unknown,
options?: EventHandlerOptions<
EventMap<M>[K]
>
): SubscriptionHandlers run one at a time by default, except message handlers and partitioned handlers, which run up to eight at a time as run does.
A slow message callback therefore does not stall later messages, but callbacks can finish out of order.
Pass concurrency 1 or a partition such as "channel" to keep related messages in order.
Without a partition, increasing concurrency keeps receive-order starts but allows out-of-order completion. A
partition keeps receive order within each key, while a later event for another key may start first.
Each subscription has its own ordering and queue, with no ordering across event types and no exactly-once delivery.
Default pending limits are 256 payloads or 4 MiB of full source JSON, not total process memory.
A bulk payload counts once, including all its bytes.
A full queue drops its oldest waiting events by default, logs a Warn record and counts the drop, and the
subscription keeps running. With a partition, it drops from the longest backlog or the arriving event instead, as
the overflow option describes. An event larger than max that has to wait is itself dropped.
Choose overflow stop to close only this subscription instead, observable through the returned handle
A failed handler is isolated and not retried.
A default API handler fails when it throws, rejects, or returns or resolves an Err result, and a native handler fails when its Effect fails.
Its original failure, with the event name, subscription ID and message IDs, goes to this subscription's on, else the client-level on, else an Error log record with the full message, stack and cause chain.
Observe the subscription's outcome as well as the client's run or wait outcome.
Registration misuse, such as an unknown event name, fails with a suggested correction
Each invocation also receives an Event with the receiving shard, its session epoch, its receipt, the received
frame size and, for an event that changes or removes a cached entity, the previous snapshot of the enabled cache.
Event middleware registered with use runs around every handler invocation, including those of subscriptions registered earlier
Parameters
event-
K handler-
( event: EventMap<M>[K], signal: AbortSignal, context: EventContext<K, M> ) => unknown( event: EventMap<M>[K], signal: AbortSignal, context: EventContext<K, M> ) => unknown optionsoptional-
EventHandlerOptions<EventMap<M>[K]>
- Returns
Subscription
The handler receives the event payload, a signal requesting cancellation on close or shutdown, and the Event.
Return or await asynchronous handler work. Other return values are ignored.
The SDK cannot stop promises that ignore the signal or manage work the handler did not return.
Registration returns the Subscription synchronously.
Invalid arguments throw Configuration, and unexpected failures throw Sdk.
Registration after shutdown began, such as from a handler still running during shutdown, is not misuse: It returns
an already-closed Subscription whose handler never runs and whose wait succeeds, and writes a Warn log
record with code events
import { describeError } from "@neontechspace/fluxerly"
export function debugHandlerExample(client, handle, inspectFailure) {
return client.on("messageCreate", (event) => handle(event), {
// The report holds the original error and the message IDs, never its content
onError: (report) => inspectFailure(`${report.describe()}\n${describeError(report.error)}`),
})
}
import { describeError, type Client, type Message } from "@neontechspace/fluxerly"
export function debugHandlerExample(
client: Client,
handle: (message: Message) => Promise<void>,
inspectFailure: (text: string) => void,
) {
return client.on("messageCreate", (event) => handle(event), {
// The report holds the original error and the message IDs, never its content
onError: (report) => inspectFailure(`${report.describe()}\n${describeError(report.error)}`),
})
}
run#
Start and maintain a gateway connection for the client's whole lifetime, including transient recovery, until shutdown, permanent failure or cancellation
Use run when one owner should control startup, lifetime observation and permanent cleanup together. Once run is accepted, its end always leaves the client Closed after cleanup. Success means normal shutdown, not merely reaching READY. A permanent required-shard failure after readiness closes a multi-shard client with Shard
run(options?: OperationOptions): ResultAsync<
void,
ConfigurationError | CancelledError | ConnectError
>run(
options?: OperationOptions
): ResultAsync<
void,
| ConfigurationError
| CancelledError | ConnectError
>The run method requires a Disconnected client with no competing connection work.
A rejected or pre-cancelled call does not take over or close the client.
Expected connection, busy and closed failures use Connect
Parameters
optionsoptional-
OperationOptions
- Returns
ResultAsync< void, ConfigurationError | CancelledError | ConnectError >ResultAsync< void, | ConfigurationError | CancelledError | ConnectError >
The returned ResultAsync stays pending while connected or recovering, and one AbortSignal controls the whole lifetime.
Cancellation returns Cancelled.
Unexpected SDK or cleanup failures reject with Sdk, including failures during cancellation cleanup
import { createClient } from "@neontechspace/fluxerly"
export async function runClient(token, signal) {
await using client = createClient({ token })
const result = await client.run({ signal })
if (result.isErr() && result.error._tag !== "CancelledError")
console.error(result.error.message)
}
import { createClient } from "@neontechspace/fluxerly"
export async function runClient(token: string | undefined, signal: AbortSignal): Promise<void> {
await using client = createClient({ token })
const result = await client.run({ signal })
if (result.isErr() && result.error._tag !== "CancelledError") console.error(result.error.message)
}
schedule#
Run a task later, once or repeatedly, as part of this client's lifetime instead of an event handler or command
Scheduling returns at once, so a handler or command that schedules a task finishes without waiting for it and does not hold its slot. Without options the task runs once as soon as possible, which suits background work started in run setup. The delay and interval follow the Clock of the client's other timers, and the interval counts from the end of each run, so runs never overlap
schedule(
task: (signal: AbortSignal) => unknown,
options?: ScheduleOptions
): ScheduledTaskschedule(
task: (signal: AbortSignal)
=> unknown,
options?: ScheduleOptions
): ScheduledTaskA failed run is reported with its original error to the client-level on, else an Error log record with code
lifecycle. A repeating task keeps its schedule after a failed run, so a passing problem such as a network
error does not end it, and a lasting one is reported at every run
Shutdown cancels the runs that have not started. A draining shutdown, such as a stop requested from run, starts no
new run and lets runs in progress finish within its drain, and then shutdown cancels what is left.
One lifecycle Info record counts the tasks that shutdown ended with a run waiting or in progress.
Tasks are kept in memory only, so a restart forgets them.
Scheduling after shutdown began, including during a drain, is refused with Client, and invalid options
are misuse with Configuration
Parameters
task-
(signal: AbortSignal) => unknown optionsoptional-
ScheduleOptions
- Returns
ScheduledTask
The task receives a signal that aborts when shutdown cancels its run. Return or await its asynchronous work: A throw,
a rejection, or a returned or resolved Err result fails the run. The SDK cannot stop a promise that ignores the signal.
Returns the task's handle synchronously. A task that is not a function and invalid options throw Configuration,
scheduling after shutdown began throws Client, and an option getter that throws causes Sdk.
A waiting task keeps Node.js running until it ends or closes, or the client shuts down
export function hourlyStatusExample(client, channelId) {
return client.schedule((signal) => client.messages.send(channelId, "Still running", { signal }), {
intervalMs: 3_600_000,
})
}
import type { Client } from "@neontechspace/fluxerly"
export function hourlyStatusExample(client: Client, channelId: string) {
return client.schedule((signal) => client.messages.send(channelId, "Still running", { signal }), {
intervalMs: 3_600_000,
})
}
shardIdForGuild #
Return the ID of this client's shard that receives a community's gateway events, or undefined when another process owns that shard
Fluxer calls a community a guild, so the argument is a guild ID. An automatically sized client returns undefined until its first connect has chosen the plan, and the answer can change when automatic sharding moves to a larger plan, including the first move of a client without sharding settings. The snowflakes helper computes the same routing for any plan. Throws Configuration when the ID is not a decimal string
shardIdForGuild(guildId: string): number | undefinedshardIdForGuild(
guildId: string
): number | undefinedParameters
guildId -
string
- Returns
number | undefined
shutdown#
Permanently close this client and wait for startup, recovery, sockets and request cleanup
Credentials, cached references, presence intent and expiry timers are released. Active handlers and message and reaction collector callbacks are cancelled. Pass drain to first stop accepting events and let running handlers and REST requests finish for up to that many milliseconds, as run does when asked to stop. See Shutdown. Events still waiting in a subscription's queue are discarded, with one events Info record for each subscription that had any, and a drain records the events it refused in one events Info record. Both kinds are counted in diagnostics().counters.eventsDropped.closed. Collector callback cleanup is awaited, so a collector callback that ignores cancellation can delay shutdown. Repeated and concurrent calls share the shutdown outcome. A pending connection call fails with Client rather than cancellation. Established sockets get up to 5,000 ms to close gracefully, then are terminated and their close events awaited. Pending handshakes are terminated immediately, and forced termination can discard unsent data. Cleanup cannot be abandoned, and this method never exits the application or undoes remote writes. Create a new client to connect again. A failed cleanup step, such as a socket close that throws or an event handler or collector callback whose cancellation cleanup fails, is also logged at Error in the lifecycle category and counted in diagnostics().counters.cleanupFailures
shutdown(options?: ShutdownOptions): ResultAsync<void, never>shutdown(
options?: ShutdownOptions
): ResultAsync<void, never>Parameters
optionsoptional-
ShutdownOptions
- Returns
ResultAsync<void, never>
Handlers and callbacks receive cancellation through their signal, and returned collector callback promises are awaited.
Application reporter promises are not awaited.
No signal is accepted.
Invalid options throw Configuration before shutdown starts.
Success is Ok(undefined) after cleanup.
Unexpected SDK or cleanup failures reject with Sdk, whose reasons keep every interruption and fault value
export function stopGracefully(client) {
// Let running handlers finish their replies for up to 10 seconds
return client.shutdown({ drainMs: 10_000 })
}
import type { Client } from "@neontechspace/fluxerly"
export function stopGracefully(client: Client) {
// Let running handlers finish their replies for up to 10 seconds
return client.shutdown({ drainMs: 10_000 })
}
subscribe#
Receive future events of one type in receive order through a bounded buffer
No history is replayed and bulk events are not split into individual events. Enabled cache changes happen before delivery and remain independent of this subscription and its overflow. Overflow fails this subscription rather than silently dropping events. Options govern the source buffer only
subscribe<
K extends keyof EventMap<Message>
>(event: K, options?: EventBufferOptions): EventSubscription<K, M>subscribe<
K extends keyof EventMap<Message>
>(
event: K,
options?: EventBufferOptions
): EventSubscription<K, M>Parameters
event-
K optionsoptional-
EventBufferOptions
- Returns
EventSubscription<K, M>
Returns a subscription synchronously.
Call next for each payload and close when finished, or use await using.
Invalid arguments throw Configuration, and unexpected failures throw Sdk.
Registration after shutdown began is not misuse: It returns an already-closed subscription whose next returns
Ok(null) and whose wait succeeds, and writes a Warn log record with code events
use#
Add event middleware that runs around every later on handler invocation, for every event and subscription, including subscriptions registered before it, command routers and run handlers
Middleware runs in registration order, the first registered outermost, and each invocation keeps the middleware registered when it started. It receives the invocation's event name, payload, Event and subscription ID, and a next step that runs the rest of the chain and the handler. Not calling next skips the handler for that invocation. Calling next again returns the same completion without running the handler twice, and calling it after the middleware finished reports a Configuration instead of running the handler. The handler slot stays occupied until the middleware and any next it started have finished. The next step completes whether or not the rest of the chain failed and never fails itself, so a handler failure is always reported. A failing middleware is reported like a failed handler, with the event name, subscription ID and message IDs, to the subscription's on, else the client-level on, else an Error log record. Middleware does not run for subscribe, wait, message collectors or reaction collectors. Registration misuse, such as a middleware that is not a function, fails like other registration misuse
use(middleware: EventMiddleware<M>): MiddlewareRegistrationuse(
middleware: EventMiddleware<M>
): MiddlewareRegistrationParameters
middleware-
EventMiddleware<M>
- Returns
MiddlewareRegistration
The middleware receives the invocation, a next function returning a promise and the handler's cancellation signal.
Registration returns synchronously. The returned registration's close stops applying the middleware to later invocations.
A middleware that is not a function throws Configuration, a closing or closed client throws Client, and unexpected failures throw Sdk
export function timingMiddlewareExample(client, record) {
return client.use(async (invocation, next) => {
const startedAt = performance.now()
await next()
record(invocation.event, performance.now() - startedAt)
})
}
import type { Client } from "@neontechspace/fluxerly"
export function timingMiddlewareExample(client: Client, record: (event: string, durationMs: number) => void) {
return client.use(async (invocation, next) => {
const startedAt = performance.now()
await next()
record(invocation.event, performance.now() - startedAt)
})
}
waitFor #
Wait for the first future event of one type that passes the supplied synchronous filter
Observation starts without connecting the client, reading history or cache, or making a remote request
waitFor<K extends keyof EventMap<Message>>(
event: K,
options?: EventWaitOptions<K, M>
): ResultAsync<EventMap<M>[K], EventWaitFailure | CancelledError>waitFor<
K extends keyof EventMap<Message>
>(
event: K,
options?: EventWaitOptions<K, M>
): ResultAsync<
EventMap<M>[K],
EventWaitFailure | CancelledError
>The default timeout is 30,000 ms from registration.
A timeout or invalid or throwing filter fails with Event without input or exception text.
Inspect a filter exception inside the filter before rethrowing if needed.
Buffer limits match subscribe.
Reconnection can miss events and does not reset the deadline.
Overflow, invalid configuration and client closure remain distinct failures
Completion or cancellation releases the queue, filter, timer and subscription without shutting down the client. This returns an event, not a registration handle. Use subscribe, a scoped on subscription or a collector to confirm registration before triggering an action
Parameters
event-
K optionsoptional-
EventWaitOptions<K, M>
- Returns
ResultAsync<EventMap<M>[K], EventWaitFailure | CancelledError>ResultAsync< EventMap<M>[K], EventWaitFailure | CancelledError >- Fails with
Observation starts when called.
Abort returns Cancelled after subscription cleanup.
Unexpected SDK or cleanup failures reject with Sdk
export function eventWaitExample(client, channelId, userId) {
return client.waitFor("typingStart", {
filter: event => event.channelId === channelId && event.userId === userId,
timeoutMs: 10_000,
})
}
import type { Client } from "@neontechspace/fluxerly"
export function eventWaitExample(client: Client, channelId: string, userId: string) {
return client.waitFor("typingStart", {
filter: event => event.channelId === channelId && event.userId === userId,
timeoutMs: 10_000,
})
}
waitForClose #
Wait for this client's final shutdown or permanent connection failure, without starting or owning a connection
Recovery keeps the wait pending. An expected connect failure before initial readiness also leaves this wait pending, because the client can connect again. Multiple or later waiters receive the same retained outcome. Normal shutdown succeeds with no value, and a permanent connection failure fails with Connection. After initial readiness, required-shard failure in a multi-shard plan is retained as Shard. Cancelling this wait affects only this waiter, not the client or other waiters
waitForClose(options?: OperationOptions): ResultAsync<
void,
ConfigurationError | CancelledError | ConnectionFailure
>waitForClose(
options?: OperationOptions
): ResultAsync<
void,
| ConfigurationError
| CancelledError
| ConnectionFailure
>Parameters
optionsoptional-
OperationOptions
- Returns
ResultAsync< void, ConfigurationError | CancelledError | ConnectionFailure >ResultAsync< void, | ConfigurationError | CancelledError | ConnectionFailure >
Unexpected background or cleanup failures reject with Sdk