Skip to main content

API reference

@vaultys/peer-sdk​

createPeer(options)​

function createPeer(options: PeerOptions): Promise<Peer>;

Creates a peer, loads its contacts and outbox from the store, starts listening on the transport, and resumes delivery of queued messages.

PeerOptions​

OptionTypeDefaultDescription
identityVaultysIdrequiredWho the peer is. Switched to VaultysID v1. Never stored by the SDK.
transportTransportrequiredHow to reach other peers, e.g. peerjsTransport()
storeStorememoryStore()Where contacts and the outbox live
acceptIncoming(did) => boolean | Promise<boolean>contacts onlyWhether a peer that dialed you (and proved did) may connect
retry{ initialMs?, maxMs? }{ 2000, 300000 }Backoff for redelivering queued messages
handshakeTimeoutMsnumber15000Maximum time for the handshake
keepaliveMsnumber15000Keepalive interval; a session closes after 3 silent intervals. 0 disables it.

Peer​

MemberDescription
did: stringThis peer's DID
contacts: ContactsThe address book (see Contacts)
send<T>(did, body): Promise<{ id }>Queue a message durably; resolves once it's stored. See Messaging.
protocol<T>(name): Protocol<T>A typed, ephemeral channel. Names starting with vaultys/ are reserved.
connect(did): Promise<void>Open (or reuse) an authenticated session
isOnline(did): booleanWhether a session with did is open
online(): string[]DIDs with an open session
disconnect(did): voidClose the session with did
close(): Promise<void>Close all sessions and stop listening. Queued messages stay in the store.
on(event, listener): UnsubscribeListen to an event; returns a function that removes the listener
once(event, listener): UnsubscribeListen once
off(event, listener): voidRemove a listener

Events​

EventPayloadWhen
message{ id, from, body, sentAt }A message arrived. from is the proven DID. Each id is emitted once.
delivered{ id, to }The recipient acknowledged a message you sent
connection{ did, online }A session opened (online: true) or closed
errorPeerErrorA background failure: an incoming peer you rejected, a failed handshake, a delivery error other than "unreachable"

Protocol<T>​

Returned by peer.protocol<T>(name).

MemberDescription
name: stringThe protocol name
send(did, value: T): Promise<void>Send now, connecting if needed. Not stored or retried; throws if the peer can't be reached.
on(handler: (from, value: T) => void): UnsubscribeReceive values from any peer

Contacts​

MemberDescription
add(did, { name?, data? }): Promise<Contact>Add or update a contact. Throws INVALID_DID for anything but a did:vaultys.
update(did, { name?, data? }): Promise<Contact>Update an existing contact
remove(did): Promise<void>Remove a contact
get(did): Contact | undefinedLook one up
has(did): booleanWhether did is a contact
list(): Contact[]All contacts
interface Contact {
did: string;
name?: string;
data?: Record<string, unknown>; // your own fields; must be msgpack-serializable
addedAt: number;
}

Errors​

All SDK errors are PeerError instances with a code:

class PeerError extends Error {
readonly code: PeerErrorCode;
}
function isPeerError(error: unknown, code?: PeerErrorCode): error is PeerError;
CodeMeaning
INVALID_DIDNot a did:vaultys identifier
UNREACHABLEThe transport couldn't reach the peer or the relay
REJECTEDThe other side's policy refused you (or yours refused them)
IDENTITY_MISMATCHSomeone other than the dialed DID answered
HANDSHAKE_FAILEDMutual authentication failed
DECRYPT_FAILEDA frame failed authentication; the session was closed
TIMEOUTAn operation took too long
CLOSEDThe peer, session or transport is closed
try {
await peer.connect(did);
} catch (error) {
if (isPeerError(error, "UNREACHABLE")) showOffline(did);
else throw error;
}

Stores​

function memoryStore(): Store;
function indexedDBStore(dbName?: string): Store; // default "vaultys-peer"

interface Store {
get(key: string): Promise<Uint8Array | undefined>;
set(key: string, value: Uint8Array): Promise<void>;
delete(key: string): Promise<void>;
keys(prefix: string): Promise<string[]>;
}

See Storage.

Transports​

function memoryNetwork(): {
transport(): Transport;
disconnect(did: string): void; // make `did` undialable, to simulate it going offline
};

interface Transport {
listen(did: string, onLink: (link: Link) => void): Promise<void>;
dial(did: string): Promise<Link>;
close(): Promise<void>;
}

interface Link {
send(frame: Uint8Array): void;
onFrame(handler: (frame: Uint8Array) => void): void;
onClose(handler: () => void): void;
close(): void;
readonly closed: boolean;
}

class BufferedLink implements Link {
constructor(sendFrame: (frame: Uint8Array) => void, closeLink: () => void);
receiveFrame(frame: Uint8Array): void; // call when a frame arrives
receiveClose(): void; // call when the connection is gone
}

See Writing a transport.

Utilities​

ExportDescription
isVaultysDid(value): booleanWhether a string is a did:vaultys identifier
handshake(link, identity, options)The mutual authentication on its own, for custom tooling. Resolves with { remote, key, reader }.
SessionThe encrypted session class, for custom tooling

@vaultys/peer-sdk/peerjs​

function peerjsTransport(options?: PeerJSTransportOptions): Transport;

Accepts all PeerJS options, plus addressOf(did), timeoutMs (default 15000) and log(message). See Relays.

@vaultys/peer-sdk/yjs​

class YjsProvider {
constructor(peer: Peer, options: YjsProviderOptions);
readonly doc: Y.Doc;
readonly awareness: Awareness | null;
readonly peers: string[]; // current members
addPeer(did: string): void;
removePeer(did: string): void;
destroy(): void;
}

function ownedBy(ownerDid: string, myDid: string): (from: string) => boolean;
OptionTypeDefaultDescription
docY.DocrequiredThe document to sync
roomstringrequiredRoom name; peers sync only within the same room
peersstring[][]DIDs to sync with
awarenessAwareness | booleantruePresence: your instance, true to create one, or false
acceptUpdate(from) => booleanaccept allIgnore document updates from some members
admit(did) => booleannone admittedAccept members who aren't in peers when they first send
reconnectMsnumber5000How often to retry members who are offline; 0 disables it

See Collaboration.

@vaultys/peer-sdk/node​

ExportDescription
fileStore(directory): StoreA store with one file per key
installWebRTC(wrtc)Expose a Node WebRTC implementation as the globals PeerJS needs

See Node.js.