SDK guide
Receiving events
How to open a server's event socket with EventSocket, listen for typed events, choose subscriptions, keep stream positions across restarts and handle resyncs, reconnects and token changes.
Specification: 03 Client transport, envelopes and errors, 11 Messages, attachments, read state and presence, 15 Calls: control, leases, routing and continuity, 19 Notifications and push
Each server pushes events to you over one WebSocket at {base}/v1/events. In the SDK that socket is an EventSocket. It runs the whole client side of document 03, §5 to §7: the hello, subscriptions, sequencing, gap repair, heartbeats, re-authentication and reconnecting. What it can't do for you is refetch your own cached state when a stream needs a resync, and it can't know where you keep that state. Those two parts are your job, and most of this page is about them.
The wire protocol behind this page is described in Event WebSocket.
Connecting
Get the socket from a ServerClient with events(), add your listeners, then call connect():
import { SloppyVoiceClient, botToken, isWithheldPayload } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
const sv = new SloppyVoiceClient({
client: 'log-bot/1.0',
home: 'sloppyvoice.com',
auth: botToken(process.env.SV_BOT_TOKEN!),
txt: nodeTxtResolver(),
})
const home = await sv.home()
const events = home.events()
events.on('message.created', (e) => {
if (isWithheldPayload(e.d)) return
console.log(e.ctx, e.seq, e.d.sender.addr, e.d.content?.text)
})
await events.connect()
console.log('ready as', events.session?.account)events()fills in the base URL, the server's credential, the client name and the server's advertisedlimits. There is at most one socket per client session per server (03 §5.12 item 1), so a second call returns the same socket and ignores its options. Change subscriptions on the socket instead.connect()resolves at the nextsession.ready. After that, reconnects happen by themselves. The promise rejects only if the socket stops for good (see Stopping) or you close it first.- Before the first connection, and after every third consecutive handshake failure, the socket reads
{base}/metaand applies itsversionsandminClient, because a browser can't read why a handshake failed (03 §5.1 item 5). - session is the
session.readypayload while the socket is ready, andnullotherwise. state is one ofidle,connecting,awaiting_ready,ready,backofforstopped(03 §5.3).
A server other than your home works the same way: await sv.serverFor('publiclobby@sloppyvoice.com') gives you its ServerClient, and its events() socket authenticates with the remote session the SDK created there.
Listening
on() is typed by the composed EventMap: the event type you pass picks the payload type. The listener gets the whole envelope (03 §6.1):
| Member | Meaning |
|---|---|
t |
The event type, for example message.created. |
d |
The payload, typed for t. |
ctx |
The stream the event belongs to: a context reference, me or community. Absent on control messages (session.*, error). |
seq |
The event's position in its stream. Present on durable events only. |
id, ts |
The envelope ID and server timestamp, the same in every delivery and replay of a durable event (03 §7.2 D5). |
on() returns an unsubscribe function. once() listens for one envelope, and off() removes a listener. For types EventMap doesn't know, such as another server's extension events, use onAny(), which gets every envelope with its type. Receivers must tolerate unknown types (03 §12.3), and the socket still advances its position past an unknown durable event (03 §7.3 rule 2).
What the socket guarantees to your listeners:
- Each durable event reaches you at most once, in
seqorder within its stream. Duplicates are dropped before your listener runs (03 §7.3 rule 2). - Ephemeral events, such as
typing.startedorcall.tick, have noseq, are never replayed, and can be dropped by the server under load (03 §7.2 E1 to E3). Don't build state from them that you need after a reconnect. The socket delivers them at once, even while their stream is repairing a gap or resyncing. - The
session.*control messages are delivered toon()too, after the socket has acted on them. You rarely need them; the lifecycle events below are usually easier.
Listeners run synchronously as each message arrives. The socket doesn't wait for a promise a listener returns, which is what you want: a client MUST keep reading the socket while it processes events, so that the server sees the real drain rate (03 §7.6). Put slow work in your own queue.
SDK-level events, such as state changes, resyncs and refusals, come from a separate emitter, lifecycle, typed by EventSocketLifecycleEvents:
import type { EventMap, EventSocket } from '@sloppyvoice/sdk'
export function logLifecycle(events: EventSocket<EventMap>): void {
events.lifecycle.on('state', ({ state, previous }) => console.log(previous, '→', state))
events.lifecycle.on('diagnostic', (d) => console.warn(d.kind, d.message, d.data))
}A diagnostic's kind is one of protocol_violation, close, gap, resync, replaced, reauth, token, store or meta. Diagnostics never contain tokens (03 §3.2 rule 7).
Subscriptions
A stream is a context (ch:…, dm:…, gdm:…), your account's me stream, or the server's community stream (03 §7.1). You follow each at one of two levels (03 §5.6):
full: every event of the stream.meis always followed atfull, whether you ask or not.heads: onlysession.headsupdates for unread indicators. Only context references can be atheads, socommunitycan't.
You can set the starting set when you create the socket, with subscribe (level full) and heads options. After that, change it with these methods:
| Method | What it does |
|---|---|
| follow(streams) | Level full. Resumes from the stored position where there is one, otherwise subscribes from the current head. Also upgrades a heads stream. |
| watchHeads(ctxs) | Level heads. Also downgrades a full stream. |
| unsubscribe(streams) | Removes streams. me is ignored. |
| subscribe(request) | The raw session.subscribe with resume, subscribe and heads lists, for when you manage positions yourself. |
On a ready socket the request goes out at once; otherwise it goes in the next session.hello. follow(), watchHeads() and subscribe() resolve with one SubscriptionResult per stream when the server answers. A refused stream is a result with status: 'refused', not a rejection:
import { SloppyVoiceClient, botToken, isChannelRef } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
const sv = new SloppyVoiceClient({
client: 'log-bot/1.0',
home: 'sloppyvoice.com',
auth: botToken(process.env.SV_BOT_TOKEN!),
txt: nodeTxtResolver(),
})
const home = await sv.home()
const events = home.events({ subscribe: ['community'] })
await events.connect()
const ctx = process.env.SV_CHANNEL
if (!isChannelRef(ctx)) throw new Error('SV_CHANNEL must be a ch: reference')
const [result] = await events.follow([ctx])
if (result?.status === 'refused') {
console.log('refused:', result.problem?.code, result.problem?.userAction)
}
// Access can end later: kick, ban, leaving, a permission change, a channel that now needs encryption.
events.on('session.subscription_ended', (e) => {
console.log('no longer following', e.d.stream, e.d.problem.code)
})The socket removes a refused or ended stream from its subscription set and from the next resume, as 03 §5.6 requires. It also emits the subscription_refused lifecycle event for refusals. If the user is looking at that stream, show the problem's userAction (03 §10). Contexts you aren't allowed to know about are refused with core.not_found, never core.forbidden.
If the server answers a whole request with a non-fatal error (core.invalid_request), the promise rejects with that problem; if the socket stops or you close it, it rejects with the stop or sdk.closed error. subscribe(), follow() and watchHeads() throw sdk.invalid_argument synchronously if the set would exceed the server's maxSubscriptions (03 §16.2), which clients should stay within (03 §5.4). Moving the context of a call set with setCall() to heads or unsubscribing it also throws. subscriptions() returns the desired set, stream to level.
Heads
For channels the user isn't looking at, heads is cheaper than full: right after session.ready or session.subscribed the server sends one session.heads covering the new heads subscriptions, then at most one update per socket every 2 s, listing only the streams whose lastItemSeq changed (03 §5.7). Compare lastItemSeq with your read position (11 §9.1) to show an unread indicator. Withheld events don't count toward lastItemSeq, so nobody sees an unread indicator for something they can't read.
import type { CtxRef, EventMap, EventSocket } from '@sloppyvoice/sdk'
/** Unread indicators for sidebar channels; `readSeq` holds the user's read positions (11 §9). */
export async function watchSidebar(
events: EventSocket<EventMap>,
sidebar: CtxRef[],
readSeq: Map<CtxRef, number>,
setUnread: (ctx: CtxRef, unread: boolean) => void,
): Promise<void> {
events.on('session.heads', () => {
for (const [ctx, head] of events.heads()) {
setUnread(ctx, (head.lastItemSeq ?? 0) > (readSeq.get(ctx) ?? 0))
}
})
await events.watchHeads(sidebar)
}
/** The user opens a channel: follow it in full. */
export async function opened(events: EventSocket<EventMap>, ctx: CtxRef): Promise<void> {
await events.follow([ctx])
}
/** The user leaves it: back to heads. */
export async function left(events: EventSocket<EventMap>, ctx: CtxRef): Promise<void> {
await events.watchHeads([ctx])
}heads() holds the latest value for each heads stream, and the socket has already updated it when your session.heads listener runs.
Positions and resume
For every stream at full, the socket keeps a position P: the seq of the last durable event it applied (03 §7.3). position(stream) returns it. The socket applies the rules of §7.3 for you:
- A fresh subscription starts at the result's
headSeq. - An event with
seq = P + 1is delivered and advancesP. One withseq ≤ Pis a duplicate and is dropped. - An event with
seq > P + 1is a gap. The socket records agapdiagnostic, drops the event and the ones after it, and resumes the stream fromP. After three gaps on the same stream within 5 minutes it resyncs the stream itself, which reaches you as aresyncrequest withselfInitiated: true. - On every reconnect the
session.hellolistsresumepositions for allfullstreams (streams without a position go insubscribe) and theheadslist, so the whole set comes back in one round trip (03 §5.11 item 4). If that hello would exceedmaxEventBytes, the rest follows insession.subscribemessages (03 §16.2 rule 4). The server then replays what you missed, or asks for a resync (03 §7.4).
The server keeps no record of what you have seen. Your resume positions are the only record, so they must survive as long as the state you derived from them. Where they live is a SeqStore. The default, MemorySeqStore, survives reconnects but not a restart: after a restart every stream is subscribed fresh and you refetch over HTTP.
A store holds the positions for one server and one account, because positions are kept per (server canonical domain, account, stream) (03 §7.3). Pass a factory as the client's seqStore option; it is called with each server's canonical domain when the client first creates that server's ServerClient. A SloppyVoiceClient is one account, so if your app runs several accounts, put the account in the store's key as well.
Storing positions durably
The rule that shapes a durable store is 03 §7.3 rule 4: you MUST store P atomically with the state you derived from events up to P. If you can't, store a value no greater than what you have durably applied. If you lost the cached state for a stream but still have P, you MUST NOT resume from it; subscribe fresh and refetch over HTTP. Otherwise a restart would resume after events your cache never saw, and they would be missing for good.
The socket calls set() right after the listeners of an event have returned. It also calls set(), without calling a listener, when a subscription result sets P, when a resync completes and for a withheld event. So a store can meet the rule by writing your state and the positions in one write, as long as your listeners change that state synchronously. This example keeps both in one JSON file and replaces it with an atomic rename. The cached state here is just the message IDs of each stream:
import { readFile, rename, writeFile } from 'node:fs/promises'
import { SloppyVoiceClient, botToken, isChannelRef, isWithheldPayload } from '@sloppyvoice/sdk'
import type { SeqStore, StreamName, StreamPositions } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
interface Saved {
positions: StreamPositions
/** The state derived from each stream's events: here, the message IDs seen. */
timelines: Partial<Record<StreamName, string[]>>
}
/** Positions and the state derived from them in one file, written together (03 §7.3 rule 4). */
class FileStore implements SeqStore {
readonly #file: string
#saved: Saved = { positions: {}, timelines: {} }
#loading: Promise<StreamPositions> | null = null
#writes: Promise<void> = Promise.resolve()
constructor(file: string) {
this.#file = file
}
/** A stream's cached message IDs. Change them only synchronously, inside a listener. */
timeline(stream: StreamName): string[] {
return (this.#saved.timelines[stream] ??= [])
}
load(): Promise<StreamPositions> {
this.#loading ??= this.#read()
return this.#loading
}
set(stream: StreamName, position: number): Promise<void> {
this.#saved.positions[stream] = position
this.timeline(stream)
return this.#save()
}
delete(stream: StreamName): Promise<void> {
delete this.#saved.positions[stream]
delete this.#saved.timelines[stream]
return this.#save()
}
clear(): Promise<void> {
this.#saved = { positions: {}, timelines: {} }
return this.#save()
}
async #read(): Promise<StreamPositions> {
let saved: Saved = { positions: {}, timelines: {} }
try {
saved = JSON.parse(await readFile(this.#file, 'utf8')) as Saved
} catch {
// No file yet: every stream is subscribed fresh.
}
// Keep a position only with its state, and state only with its position.
for (const [stream, p] of Object.entries(saved.positions) as [StreamName, number | undefined][]) {
const timeline = saved.timelines[stream]
if (p === undefined || !timeline) continue
this.#saved.positions[stream] = p
this.#saved.timelines[stream] = timeline
}
return { ...this.#saved.positions }
}
/** Snapshot now, then write to a temporary file and rename it over the old one, one write at a time. */
#save(): Promise<void> {
const text = JSON.stringify(this.#saved)
const tmp = `${this.#file}.tmp`
this.#writes = this.#writes
.catch(() => {})
.then(async () => {
await writeFile(tmp, text)
await rename(tmp, this.#file)
})
return this.#writes
}
}
const store = new FileStore('sloppyvoice.com.json')
await store.load()
const sv = new SloppyVoiceClient({
client: 'archive-bot/1.0',
home: 'sloppyvoice.com',
auth: botToken(process.env.SV_BOT_TOKEN!),
txt: nodeTxtResolver(),
seqStore: () => store, // one server here; with several, keep one store per domain
})
const home = await sv.home()
const ctx = process.env.SV_CHANNEL
if (!isChannelRef(ctx)) throw new Error('SV_CHANNEL must be a ch: reference')
const events = home.events({ subscribe: [ctx] })
events.on('message.created', (e) => {
if (isWithheldPayload(e.d) || !e.ctx) return
store.timeline(e.ctx).push(e.d.mid)
})
events.lifecycle.on('diagnostic', (d) => {
if (d.kind === 'store') console.error(d.message, d.data)
})
await events.connect()Notes on the example:
- The socket reads
load()once, before its first connection. Calling it yourself first, as above, lets you show cached state before the socket is ready; the second call returns the same result. - The socket calls
delete()when your cache for a stream is no longer valid: forget(), and a resync that must discard cached state. Dropping the timeline there keeps the file consistent if the app stops before the refetch finishes. - A failed write is reported as a
storediagnostic; the socket keeps running. - Rewriting the whole file per event is fine for a bot. A client with a real cache does the same thing in a database transaction (SQLite, IndexedDB): the derived rows and the position row in one commit.
If your listeners persist state asynchronously, make set() a no-op, save P yourself in the same transaction as the state it covers, and return the saved values from load(). Inside a listener, e.seq is the value to save with the state that event produced (position() already returns it). Positions that the socket advances without a listener (subscription results, withheld events, completed resyncs) then go unsaved, which is safe: you resume from a lower position and re-apply events, which is harmless (03 §7.2 D8).
If you lose the cached state for a stream some other way, call forget(stream). It deletes the stored position and, for a stream at full on a ready socket, subscribes it fresh at once; otherwise the next session.hello subscribes it fresh. Either way you never resume from a position whose state is gone (03 §7.3 rule 4). Then refetch over HTTP. me is the exception on a ready socket: the server ignores me in subscribe (03 §5.4), so forget('me') only deletes the stored position and the socket keeps applying live me events from its current position.
Resyncs
A server sends session.resync_required when it can't bring a stream up to date by replay: too many events missed, events no longer retained, read access that lapsed, a position ahead of the server, a dropped queue or a server reset (03 §7.5). The socket starts the procedure, then hands you the part only you can do as a resync lifecycle event carrying a ResyncRequest:
- The socket marks the stream as resyncing and queues its live events (isResyncing() is
true). - If
discardCacheis set (reasonaheadorserver_reset), discard the state you derived from this stream's events, because the server no longer has, or has renumbered, events you saw. The socket has already asked your store to delete the stored position and recorded aresyncdiagnostic. - Refetch what you cache for the stream over HTTP: for a context, its latest timeline page, membership and settings; for
community, the community, channel list and roles; forme, the account, devices and DM index. - Call
complete()with the lowestheadSeqamong the responses you fetched, or with nothing if none reported one. The socket then delivers the queued events the snapshot doesn't already hold and sets the position. Re-applying an event already in the snapshot is harmless, because durable payloads are idempotent (03 §7.2 D8).
For the durable-store example above, which caches one channel's message IDs, call this with store.timeline.bind(store) before connect():
import type { ChannelRef, EventMap, EventSocket, ServerClient, StreamName } from '@sloppyvoice/sdk'
/** Refetch the cached timeline of `ctx` when its stream needs a resync (03 §7.5). */
export function handleResyncs(
server: ServerClient,
events: EventSocket<EventMap>,
ctx: ChannelRef,
timeline: (stream: StreamName) => string[],
): void {
events.lifecycle.on('resync', async (r) => {
if (r.stream !== ctx) {
r.complete() // nothing cached for this stream
return
}
try {
const page = await server.messages.page(ctx, { limit: 50 }, { signal: r.signal })
const cached = timeline(ctx)
cached.length = 0
for (const item of page.items) if (item.type === 'message') cached.push(item.mid)
r.complete(page.headSeq)
} catch {
if (r.signal.aborted) return
// Couldn't refetch: drop the cache and the position, and subscribe fresh.
await events.forget(ctx)
}
})
}- The
headSeqof an HTTP response never setsPby itself (03 §2.8); you pass it only so the socket can skip queued events the snapshot already holds. r.signalaborts when the resync is superseded by a newer one, when the connection closes (the next socket resumes fromP, and the server asks for a new resync if one is still needed), or when the stream is unsubscribed, ended, refused or forgotten. Acomplete()after that is ignored.- If no listener handles
resync, the socket completes it at once. That is right for a client that caches nothing. Alifecycle.onAny()listener counts as a listener. Once you add one, callcomplete()for every request, including streams you don't cache, or that stream's events stay queued. - A resync is silent: show the latest page at once and load older messages as the user scrolls back. Never show a prompt (03 §7.5).
Secure contexts only
A resync never by itself discards MLS group state, history keys (K_hist), identity pins or AccountVault data; discardCache covers only state derived from the stream's events. For a secure context, continue MLS processing from your current epoch and catch up from the hosting server's handshake log; use a resync external commit only when 13's own conditions for one hold, never because of the resync alone. Also report an ahead or server_reset resync to the hosting server through /v1/diagnostics with kind transport and data {"event": "resync", "reason": …, "stream": …} (03 §7.5, 15 §14.4). The socket doesn't send this report; use CallsApi.sendDiagnostics. See MLS and sealed messages.
Withheld events
When a subscriber may see nothing of a durable event's payload, the server still delivers the envelope, with d set to {"withheld": true}, so that every subscriber receives every seq (03 §7.2 D4 and D4a). Messaging adds {"target": …, "withheld": true}, the replay form of an edit or reaction whose content has since been deleted (11 §8.3). A client advances P past a withheld event and does nothing else.
The socket does exactly that: it advances the position and doesn't call your listeners for a withheld payload. The payload types in EventMap still include the withheld forms, so narrow with isWithheldPayload() before reading the payload, as the examples above do. Withheld events also don't count toward lastItemSeq in session.heads.
Foreground and network changes
A client with a visible UI tells each server whether the user can see the app, because the server sends message notifications only to recipients without an attentive session there (03 §5.8, 19 §4.3). The foreground option sets the initial state, false by default, which is right for a bot. After that, call setForeground():
import type { EventSocket } from '@sloppyvoice/sdk'
/** Keep a browser client's foreground state and connection checks in step with the page. */
export function trackPage<M extends object>(events: EventSocket<M>): void {
const update = () => events.setForeground(document.visibilityState === 'visible')
document.addEventListener('visibilitychange', update)
window.addEventListener('online', () => events.networkChanged())
update()
}setForeground(false)is sent at once;trueat most once per 5 s (03 §5.8). A change made while the socket isn't ready is sent when it is.- Returning to the foreground while the socket is in
backoffreconnects at once, counting as retry 0, at most once per 5 s (03 §5.11 item 3). - networkChanged() is for when the operating system reports the network came back or changed. In
backoffit reconnects at once, at most once per 5 s (the limit is shared with returning to the foreground); when ready it checks the connection withping(). - ping(), for example after the device wakes, sends a
session.pingat most once per 5 s. Without a pong within 10 s the socket closes with 4008 and reconnects at once (03 §5.9 item 5). - While the client takes part in a call on this server, call setCall(ctx), and
setCall(null)when it leaves. The socket then keeps that context atfull, pings whenever nocall.tickhas arrived for 3 s (at most once per 3 s), treats a missing pong after 3 s as a dead connection, and caps its delay after aserver_shutdownclose at 2 s (03 §5.9 item 6, 03 §5.10).
The socket answers the server's session.ping and treats 75 s without any message as a dead connection on its own, closing with 4008 (03 §5.9).
Reconnecting and close codes
Reconnecting is silent (03 §5.11 item 5). Retry n waits a random delay up to min(30 s, 1 s × 2^n), never less than the close code or retryAfterMs requires, and n resets only after a socket has stayed ready for 60 s. Messages the user sends meanwhile go over HTTP and don't wait for the socket.
The socket reacts to each close code as the table in 03 §5.10 says:
| Close code | What the socket does |
|---|---|
| 1001, 1011 | Reconnects with backoff. |
| 1002, 1003, 1007, 1009, 4000 | Reconnects with backoff and records a diagnostic. |
1012 server_shutdown |
Reconnects after retryAfterMs, or after 1 to 10 s; at most 2 s during a call. |
| 1013 | Reconnects with backoff of at least retryAfterMs, or at least 5 s without it. |
4001 unauthenticated |
Asks the TokenProvider to recover, then reconnects at once the first time and with backoff after that. Keeps retrying with backoff while recovery fails transiently (network, server unreachable); stops with unauthenticated if it fails for good. |
4004 session_ended |
Never reuses the token. For a remote session it creates a new one silently first; otherwise it stops with session_ended. |
| 4008 | Reconnects at once, then with backoff. |
4010 replaced |
Reconnects silently once, only if isSingleInstance() says no other instance runs and it hasn't already reconnected silently after a 4010 in the last 60 s. Otherwise records a diagnostic and stops with replaced. |
4011 slow_consumer |
Moves streams for which isViewing(ctx) is false to heads (never a call's context), then reconnects with backoff of at least 1 s. |
4026 unsupported_version |
Stops with update_required. |
4029 rate_limited |
Reconnects with backoff of at least retryAfterMs, or after 60 s without it. |
| Other codes, including 1006 | Stops with server_closed if session.closing said reconnect: false; otherwise reconnects with backoff of at least retryAfterMs, if given. |
Two options feed this table. Pass isSingleInstance when your process can tell that it is the only instance for this client session: on the web it holds the Web Locks lock or SharedWorker leadership, on desktop and mobile a single-instance lock. A web client that can run in several tabs MUST share one socket across them (03 §5.12 item 4). Pass isViewing so a slow-consumer close can move the streams the user isn't looking at to heads; without it, every stream stays at full (03 §7.6).
Lifecycle events for the status line and logs:
reconnectingistrueonly after 5 s without a ready socket andfalseonce ready again. Show a small "Reconnecting…" line on it, never a dialog.disconnectedreports each close with its code, thesession.closingpayload if there was one, and who closed it.reconnect_scheduledgives the delay and retry number.slow_consumerlists the streams moved toheadsafter a 4011.
Stopping
When the socket can't continue without the user or an update, it goes to stopped, emits stopped with an EventSocketStopReason, and rejects any pending connect():
| Reason | Show the user |
|---|---|
update_required |
"Update required" (update_app, 03 §12.4). |
server_too_old |
The server only serves older protocol versions. |
unauthenticated |
Follow 03 §3.3; for the home server, sign in again. Also used when the token provider fails with userAction: sign_in or returns a token that breaks the credentials grammar of 03 §3.1. |
session_ended |
Follow the problem's userAction; the old token is never reused. |
replaced |
A quiet "open in another window" notice with a button that calls connect() (03 §5.12 item 3). |
server_closed |
Nothing automatic; the server closed with 1000, or with reconnect: false on a code the table doesn't list. Also used when the runtime has no WebSocket constructor (pass the WebSocket option). |
connect() starts a stopped socket again.
Reauthentication
A socket stays authenticated until the latest token accepted on it expires, plus 60 s of grace (03 §5.13). The socket extends that deadline in band, without reconnecting:
- It sends
session.reauthwhenever the token provider reports a new token, which happens after every refresh or remote-session renewal. - When the deadline is less than 120 s away it asks the provider for a token, which refreshes first if it is about to expire, and sends the new one. Until a new token arrives it asks again every 15 s, until the grace period ends.
- A token refreshed while waiting for
session.readyis sent once the socket is ready.
authDeadline is the current deadline in Unix milliseconds, or null for a token that doesn't expire and while no socket is connected. A refused session.reauth emits reauth_failed with the problem and the old deadline stands (03 §5.13 item 3). Unless the problem is session.wrong_session, the socket then asks the provider to recover the token, once per deadline. If the deadline then passes, the server closes with 4001 and the recovery in the table above runs.
You don't call anything for this. It works with the token providers the SDK creates for you, and with your own TokenProvider as long as its onChange() reports new tokens.
Closing
Call close() when the app no longer needs the server. The socket closes with 1000, goes idle, and pending waits reject with sdk.closed. Stored positions stay, so the next connect() resumes.
When the user signs out or the account is deleted, discard the positions too (03 §7.3 rule 5):
import type { EventMap, EventSocket } from '@sloppyvoice/sdk'
export async function signOut(events: EventSocket<EventMap>): Promise<void> {
await events.close({ discardPositions: true })
}That clears the socket's positions and calls your store's clear(). Delete the state you derived from them at the same time.