Test helpers (@sloppyvoice/sdk/testing): MockServer, an in-memory Sloppy Voice server for insecure-mode flows, and MockNetwork, which connects several of them. See mock-server.ts for what is and isn't implemented.

import { … } from '@sloppyvoice/sdk/testing'

Classes

MockNetwork class

A set of mock servers that can reach each other. Give a client its fetch, WebSocket and txt.

class MockNetwork

constructor

new MockNetwork()

log

readonly log: ({ method: string; url: string; authorization: string | null })[]

Every URL fetched through this network, in order.

servers

get servers(): MockServer[]

The servers of this network.

fetch

readonly fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>

fetch for the whole network. Requests to a server's base URL go to that server; https://<domain>/.well-known/sloppyv is answered for every domain of a server with delegation: 'wellknown' and 404 for the others (02 §4); every other host fails like an unknown host.

MDN Reference

txt

readonly txt: TxtResolver

A TXT resolver answering _sloppyv.<domain> for servers with delegation: 'txt' (02 §3.2); NXDOMAIN otherwise.

WebSocket

get WebSocket(): WebSocketConstructor

A WebSocket constructor for the whole network: wss://<base host><base path>/v1/events reaches that server (03 §5.1).

add

add(server: MockServer): void

Add a server (done by MockServer.create).

server: MockServer

remove

remove(server: MockServer): void

Remove a server: its URLs stop answering.

server: MockServer

serverFor

serverFor(domain: string): MockServer | null

The server that accepts domain (02 §7.3 domains), or null.

domain: string

account

account(addr: string): { addr: string; name: string; kind: "bot" | "user"; inc: string } | null

A local account of any server of the network, by canonical address.

addr: string

close

close(): void

Close every server's sockets.

Source: testing/mock-network.ts:26

MockServer class

An in-memory Sloppy Voice server (see the module documentation for what it implements). Create it with MockServer.create; point a client at it with fetch, WebSocket and txt (or the same members of its network when several servers talk to each other).

const server = await MockServer.create({ domain: 'alpha.test' })
const bot = server.createBot({ local: 'helper' })
const sv = new SloppyVoiceClient({
  client: 'test/1.0', home: 'alpha.test', auth: botToken(bot.token),
  fetch: server.fetch, WebSocket: server.WebSocket, txt: server.txt, allowSpecialUseDomains: true,
})
class MockServer implements MockSocketPeer

domain

readonly domain: string

The canonical domain (02 §7.3).

domains

readonly domains: string[]

Every domain the server accepts, canonical first.

baseUrl

readonly baseUrl: string

The normalized base URL (02 §3.3).

delegation

readonly delegation: "txt" | "wellknown"

How the domain delegates (02 §3, §4).

network

readonly network: MockNetwork

The network this server is part of.

requests

readonly requests: MockRequestRecord[]

Every HTTP request received, oldest first.

pings

readonly pings: ({ connId: string; id: string })[]

Every session.ping the server sent: the connection and the envelope id (03 §5.9).

pongs

readonly pongs: ({ connId: string; re: string | null; matched: boolean })[]

Every session.pong received: its re, and whether it answered a ping this server sent on that connection (03 §5.9 item 2).

fetch

get fetch(): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>

A fetch that reaches every server of this server's network (02, 03 §2).

WebSocket

get WebSocket(): WebSocketConstructor

A WebSocket constructor that reaches every server of the network (03 §5.1).

txt

get txt(): TxtResolver

The network's TXT resolver, serving _sloppyv records (02 §3).

txtRecord

get txtRecord(): string

The _sloppyv TXT record text (02 §3.2).

baseHost

get baseHost(): string

The base URL's host.

basePath

get basePath(): string

The base URL's path, '' for the root.

socketCount

get socketCount(): number

The number of open event sockets.

create

static create(options: MockServerOptions): Promise<MockServer>

Create a server; generates its Ed25519 server keys first (02 §11).

serverKey

serverKey(kid: string): Uint8Array<ArrayBufferLike> | null

The server's public signing key for kid, for federation in the network (02 §11.6).

kid: string

createUser

createUser(opts: { local: string; name?: string; admin?: boolean }): MockCredentials

Create a local user account with a static home-session access token (sva_…, 05 §7.5) and its device. The first account created (user or bot) is an admin unless admin says otherwise.

opts: { local: string; name?: string; admin?: boolean }

createBot

createBot(opts: { local: string; name?: string; admin?: boolean }): MockCredentials

Create a bot account with a bot token (svb_…, 05 §15.4), used with Authorization: Bot.

opts: { local: string; name?: string; admin?: boolean }

createChannel

createChannel(name: string, opts?: { kind?: "text" | "voice"; topic?: string; by?: string }): Channel

Create a channel as by (default: the first admin). Emits channel.created (09 §14.2).

name: string
opts: { kind?: "text" | "voice"; topic?: string; by?: string }

Default: {}

post

post(as: string, ctx: string, text: string): EntryAck

Post a text message as a local account, as if its client had sent it (11 §4).

as: string
ctx: string
text: string

failNext

failNext(failure: InjectedFailure): void

Make the next matching requests fail with a problem (03 §10).

setRateLimit

setRateLimit(limit: { limit: number; windowMs: number } | null): void

Enforce a per-session (or, unauthenticated, per-server) request limit: over it, 429 core.rate_limited with Retry-After, RateLimit and RateLimit-Policy (03 §15). null turns it off.

limit: { limit: number; windowMs: number } | null

revokeToken

revokeToken(token: string): void

Revoke a token: later requests and hellos with it get 401 core.unauthenticated (03 §3.3).

token: string

expireToken

expireToken(token: string): void

Expire a remote session's token now, so the next use gets 401 core.token_expired (06 §6.7).

token: string

expireEvents

expireEvents(stream: string, throughSeq: number): void

Forget the retained events of a stream up to throughSeq, so a resume from before it gets expired (03 §7.4).

stream: string
throughSeq: number

headSeq

headSeq(stream: string): number

The head seq of a stream (community, a context reference, or me:<address>), 0 if it has no events (03 §7.1).

stream: string

disconnectAll

disconnectAll(code: number, closing?: SessionClosing): void

Close every event socket with code, after a session.closing when closing is given (03 §5.10). For example 1012 with { reason: 'server_shutdown', reconnect: true, retryAfterMs: 0 }.

code: number
closing?: SessionClosing

endSession

endSession(token: string, opts?: { code?: string; reason?: string; retry?: boolean }): void

End the client session of token (06 §6.7): mark it ended, and on every socket of that session send the federation.session_ended event (remote sessions, 06 §6.8), an error with the problem, session.closing with reason session_ended, then close with 4004 (03 §5.10).

token: string
opts: { code?: string; reason?: string; retry?: boolean }

Default: {}

pingAll

pingAll(): void

Send session.ping on every ready socket now (03 §5.9).

close

close(): void

Close every socket (1001) and stop timers.

wellKnown

wellKnown(): Response

The /.well-known/sloppyv document (02 §4.1).

metadata

metadata(): ServerMetadata

The validated-shape ServerMetadata (02 §7.3).

handle

handle(request: Request): Promise<Response>

Handle one HTTP request addressed to this server's base URL.

request: Request

Source: testing/mock-server.ts:505

MockServerSocket class

The server end of an in-memory WebSocket (03 §5).

class MockServerSocket

url

readonly url: string

The URL the client opened.

protocol

readonly protocol: string

The subprotocol the server selected (03 §5.1 item 3): sloppyv.v1 if offered, else ''.

isOpen

get isOpen(): boolean

Whether the connection is still open.

send

send(text: string): void

Send a text message to the client (03 §5.2 item 1).

text: string

close

close(code: number, reason?: string): void

Close the connection from the server with code (03 §5.10).

code: number
reason: string

Default: ''

Source: testing/mock-socket.ts:23

MockWebSocket class

The client end: implements the subset of the WHATWG WebSocket the SDK uses (WebSocketLike). Created by a mock network's WebSocket constructor; an unknown URL fails like a refused connection (error, then close 1006).

class MockWebSocket implements WebSocketLike

CONNECTING

static readonly CONNECTING: 0

WebSocket.CONNECTING.

OPEN

static readonly OPEN: 1

WebSocket.OPEN.

CLOSING

static readonly CLOSING: 2

WebSocket.CLOSING.

CLOSED

static readonly CLOSED: 3

WebSocket.CLOSED.

url

readonly url: string

protocol

protocol: string

The subprotocol the server selected; '' if none (03 §5.1 item 3).

extensions

readonly extensions: ""

The negotiated extensions, as in Sec-WebSocket-Extensions (03 §5.1 item 6).

readyState

readyState: number

0 connecting, 1 open, 2 closing, 3 closed.

binaryType

binaryType: string

The SDK sets 'arraybuffer' so binary messages are never decoded as text.

onopen

onopen: (event: unknown) => void | null

onmessage

onmessage: (event: WebSocketMessageEventLike) => void | null

onclose

onclose: (event: WebSocketCloseEventLike) => void | null

onerror

onerror: (event: unknown) => void | null

send

send(data: string): void

Send one text message to the server (03 §5.2 item 1).

data: string

close

close(code?: number, reason?: string): void

Close from the client side (03 §5.10).

code: number

Default: 1000

reason: string

Default: ''

Source: testing/mock-socket.ts:74

Interfaces

InjectedFailure interface

A failure to inject with MockServer.failNext.

interface InjectedFailure

method?

method?: string

Only requests with this method. Default: any.

path?

path?: string | RegExp

Only requests whose path (relative to the base URL, e.g. /v1/channels) equals this string or matches this pattern.

code

code: string

The error code; status, retryable and userAction default to its registry entry.

status?

status?: number

detail?

detail?: string

retryAfterMs?

retryAfterMs?: number

data?

data?: Record<string, unknown>

times?

times?: number

How many matching requests fail. Default 1.

Source: testing/mock-server.ts:202

MockAccount interface

A local account of a mock server (05 §11).

interface MockAccount

address

address: string

Canonical address (01).

name

name: string

Display name.

kind

kind: "bot" | "user"

user or bot.

inc

inc: string

The incarnation (05 §11.1).

admin

admin: boolean

Whether the account holds every permission (stand-in for 10's roles).

Source: testing/mock-server.ts:178

MockCredentials interface

The credential of a local account, as MockServer.createUser and MockServer.createBot return it.

interface MockCredentials extends MockAccount

address

address: string

Canonical address (01).

name

name: string

Display name.

kind

kind: "bot" | "user"

user or bot.

inc

inc: string

The incarnation (05 §11.1).

admin

admin: boolean

Whether the account holds every permission (stand-in for 10's roles).

token

token: string

The token: an access token sva_… (05 §7.5) for a user, a bot token svb_… (05 §15.4) for a bot.

scheme

scheme: "Bearer" | "Bot"

Bearer for a user, Bot for a bot (03 §3.1).

did

did: string

The session's device ID (05 §12.4).

Source: testing/mock-server.ts:192

MockRequestRecord interface

A request the mock server received, for assertions in tests.

interface MockRequestRecord

method

method: string

path

path: string

The path relative to the base URL.

authorization

authorization: string | null

The Authorization header as received, or null.

status

status: number

The HTTP status answered.

Source: testing/mock-server.ts:218

MockServerOptions interface

Options of MockServer.create.

interface MockServerOptions

domain

domain: string

The server's canonical domain, a lowercase A-label such as alpha.test (02 §7.3).

baseUrl?

baseUrl?: string

The base URL (02 §3.3). Default https://chat.<domain>/server.

aliases?

aliases?: string[]

Further domains the server accepts (02 §7.3 domains).

name?

name?: string

Server and community name. Default: the domain.

delegation?

delegation?: "txt" | "wellknown"

How the domain delegates to the base URL (02 §3, §4): a _sloppyv TXT record served by the network's TXT resolver, or only /.well-known/sloppyv. Default txt.

joinPolicy?

joinPolicy?: JoinPolicy

The community's join policy (09 §3.3). Default open.

limits?

limits?: ServerLimits

Advertised limits (02 §7.3, 03 §16); merged over the defaults.

maxReplayEvents?

maxReplayEvents?: number

Events of each stream kept for replay (03 §7.4). Default 5,000. Lower values (below the 1,000 floor of 03 §16, non-conforming) make resync tests cheap.

pingIntervalMs?

pingIntervalMs?: number | null

session.ping interval (03 §5.9). Default 30,000 ms; null sends no pings.

headsIntervalMs?

headsIntervalMs?: number

Minimum spacing of session.heads per socket (03 §5.7). Default 2,000 ms.

remoteSessionLifetimeMs?

remoteSessionLifetimeMs?: number

Lifetime of remote sessions (06 §6.2). Default 3,600,000 ms.

clock?

clock?: Clock

The server's clock. Default Date.now.

timers?

timers?: Timers

Timers for pings and heads. Default: the global setTimeout.

network?

network?: MockNetwork

The network to join. Default: a network of its own.

Source: testing/mock-server.ts:140

MockSocketPeer interface

The server side of one in-memory connection.

interface MockSocketPeer

onOpen

onOpen(end: MockServerSocket): void

Called once the client end is open.

onMessage

onMessage(end: MockServerSocket, data: string): void

A text message from the client.

data: string

onClose

onClose(end: MockServerSocket, code: number, reason: string): void

The connection closed (by either side); code as seen by the server.

code: number
reason: string

Source: testing/mock-socket.ts:13

Types

MockSocketRouter type

Resolves a WebSocket URL to the server that accepts it, or null (connection refused).

type MockSocketRouter = (url: string) => MockSocketPeer | null

Source: testing/mock-socket.ts:63