Skip to content

js-bao-wss-client


js-bao-wss-client / JsBaoClient

Class: JsBaoClient ​

JsBaoClient - Multi-tenant client for js-bao-wss

Provides a hierarchical API for:

  • HTTP operations: document management, permissions, user profile, session
  • Real-time operations: multiplexed Y.Doc updates over WebSocket
  • Awareness: collaborative presence state

Extends ​

  • Observable<any>

Documents ​

addDocumentModelMapping() ​

addDocumentModelMapping(modelName, documentId): void

Map a js-bao model name to a specific document ID.

Parameters ​

modelName ​

string

The model class name to map

documentId ​

string

The document that should store instances of this model

Returns ​

void


cancelPendingCreate() ​

cancelPendingCreate(documentId, opts?): Promise<void>

Cancel a pending offline document creation.

Parameters ​

documentId ​

string

The pending document to cancel

opts? ​

Optional cleanup behavior

evictLocal? ​

boolean

If true, also removes the document's local data from storage

Returns ​

Promise<void>


clearDefaultDocumentId() ​

clearDefaultDocumentId(): void

Clear the default document ID.

Returns ​

void


clearDocumentModelMapping() ​

clearDocumentModelMapping(modelName): void

Remove a model-to-document mapping.

Parameters ​

modelName ​

string

The model class name to unmap

Returns ​

void


clearSelfRemovalPending() ​

clearSelfRemovalPending(documentId): void

Clear the self-removal pending flag for a document.

Parameters ​

documentId ​

string

The document to clear the pending self-removal flag for

Returns ​

void


closeDocument() ​

closeDocument(documentId, options?): Promise<{ evicted: boolean; }>

Close an open document and stop syncing.

Parameters ​

documentId ​

string

The document to close

options? ​

Optional close behavior

evictLocal? ​

boolean

If true, removes the document's local data from storage on close

Returns ​

Promise<{ evicted: boolean; }>


commitOfflineCreate() ​

commitOfflineCreate(documentId, opts?): Promise<{ created: boolean; linked?: boolean; reason?: string; }>

Commit a locally created document to the server.

Parameters ​

documentId ​

string

The locally created document to commit

opts? ​

Optional commit behavior

onExists? ​

"link" | "fail"

What to do if the document already exists on the server: "link" adopts the existing document, "fail" throws an error

Returns ​

Promise<{ created: boolean; linked?: boolean; reason?: string; }>


createDocument() ​

createDocument(options): Promise<{ metadata: LocalMetadataEntry; }>

Create a new document. Writes local metadata only, with the server commit racing in the background — unless options.localOnly is set, in which case the document never syncs. The document is NOT opened: call documents.open(documentId) before reading or writing it, or the write throws "Document <id> is not open".

Parameters ​

options ​

CreateDocumentOptions

Document creation options

Returns ​

Promise<{ metadata: LocalMetadataEntry; }>


document() ​

document(documentId): DocumentContext

Get a scoped API for a specific document

Parameters ​

documentId ​

string

The document to scope operations to

Returns ​

DocumentContext


getDefaultDocumentId() ​

getDefaultDocumentId(): string | null

Get the current default document ID.

Returns ​

string | null


getDoc() ​

getDoc(documentId): Doc | undefined

Get the raw Yjs Doc instance for a document.

Parameters ​

documentId ​

string

The document to retrieve

Returns ​

Doc | undefined


getDocDebug() ​

getDocDebug(documentId): DocumentDebugSnapshot

Get debug information about a document's internal state.

Parameters ​

documentId ​

string

The document to inspect

Returns ​

DocumentDebugSnapshot


getDocHash() ​

getDocHash(documentId): Promise<string>

Compute a hash of the document's current state.

Parameters ​

documentId ​

string

The document to hash

Returns ​

Promise<string>


getDocumentModelMapping() ​

getDocumentModelMapping(modelName): string | null

Get the document ID mapped to a model name.

Parameters ​

modelName ​

string

The model class name to look up

Returns ​

string | null


getDocumentPermission() ​

getDocumentPermission(documentId): DocumentPermission | null

Get the current user's permission level for a document.

Parameters ​

documentId ​

string

The document to check permissions for

Returns ​

DocumentPermission | null


getDocumentSchema() ​

getDocumentSchema(documentId): DiscoveredSchema | null

Get the discovered schema for a document. Returns null if no schema has been discovered yet (document not synced, or explicit models were provided).

Parameters ​

documentId ​

string

The document to get the schema for

Returns ​

DiscoveredSchema | null


isDocOpen() ​

isDocOpen(documentId): boolean

Check if a document is currently open.

Parameters ​

documentId ​

string

The document to check

Returns ​

boolean


isDocumentReadOnly() ​

isDocumentReadOnly(documentId): boolean

Check if the current user has read-only access to a document.

Parameters ​

documentId ​

string

The document to check

Returns ​

boolean


isMetadataDeleted() ​

isMetadataDeleted(documentId): boolean

Check if a document's metadata has been marked as deleted.

Parameters ​

documentId ​

string

The document to check

Returns ​

boolean


isPendingCreate() ​

isPendingCreate(documentId): boolean

Check if a document is pending server creation.

Parameters ​

documentId ​

string

The document to check

Returns ​

boolean


isRootDocument() ​

isRootDocument(documentId): boolean

Check if a document is the user's root document.

Parameters ​

documentId ​

string

The document to check

Returns ​

boolean


listOpenDocuments() ​

listOpenDocuments(): string[]

List IDs of all currently open documents.

Returns ​

string[]


listPendingCreates() ​

listPendingCreates(): Promise<object[]>

List all documents pending server creation.

Returns ​

Promise<object[]>


markMetadataDeleted() ​

markMetadataDeleted(documentId): number | undefined

Mark a document's metadata as deleted locally.

Parameters ​

documentId ​

string

The document to mark as deleted

Returns ​

number | undefined


markSelfRemovalPending() ​

markSelfRemovalPending(documentId): void

Mark a document as pending self-removal to suppress duplicate server delete events.

Parameters ​

documentId ​

string

The document being removed by the current user

Returns ​

void


openDocument() ​

openDocument(documentId, options?): Promise<Doc>

Open a document for real-time collaboration and sync.

Parameters ​

documentId ​

string

The document to open

options? ​

Controls how the document is loaded and synced

availabilityWaitMs? ​

number

How long to wait for initial data before resolving with an empty doc (ms, default 30000)

deferNetworkSync? ​

boolean

If true, opens locally without starting server sync until startNetworkSync() is called

enableNetworkSync? ​

boolean

If false, opens the document without subscribing to server updates (default true)

requestSyncPerf? ​

boolean

If true, requests sync performance timings from the server

retainLocal? ​

boolean

If true, persists the document data locally for offline access (default true)

waitForLoad? ​

"local" | "network" | "localIfAvailableElseNetwork"

Controls when the returned promise resolves: "local" for local data only, "network" to wait for server sync, "localIfAvailableElseNetwork" to prefer local but fall back to network

Returns ​

Promise<Doc>


openDocumentByAlias() ​

openDocumentByAlias(alias, options?): Promise<{ doc: Doc; metadata: LocalMetadataEntry | null; }>

Resolve a document alias and open the document.

Parameters ​

alias ​

ResolveAliasParams

Alias parameters identifying the document (scope, aliasKey, optional userId)

options? ​

Controls how the resolved document is loaded and synced

availabilityWaitMs? ​

number

How long to wait for initial data before resolving with an empty doc (ms)

enableNetworkSync? ​

boolean

If false, opens the document without subscribing to server updates

retainLocal? ​

boolean

If true, persists the document data locally for offline access

waitForLoad? ​

"local" | "network" | "localIfAvailableElseNetwork"

Controls when the returned promise resolves: "local", "network", or "localIfAvailableElseNetwork"

Returns ​

Promise<{ doc: Doc; metadata: LocalMetadataEntry | null; }>


registerModel() ​

registerModel(model): Promise<void>

Add a model to this client after it is already running.

Every model a client uses is normally known when the client is built, and the list it was built with is fixed for that client's lifetime. An app that learns its schema at runtime — a plugin, a tenant-supplied type, an import that defines its own shape — calls this instead of tearing the client down and rebuilding it. The model joins this client's runtime, is initialized for every document this client already has open, and (on a large document) has its query tables built from what the document already holds, so a query() answers those rows straight away.

Scoped to this client: the model becomes visible here and nowhere else. Registering the same class again is not an error and does no further work. If a document's initialization fails, the model stays registered and the call can be retried; the retry finishes only the documents left incomplete.

ts
const client = await initializeClient({ apiUrl, appId, models: [Note] });
await client.registerModel(Tag);
const tags = await Tag.query({});

Parameters ​

model ​

any

The model class to register, built with createModelClass (or defineModelSchema plus attachAndRegisterModel)

Returns ​

Promise<void>

Throws ​

If the client is destroyed, the class has no name, another class is already registered under its name, or it belongs to another live client


retryCommit() ​

retryCommit(documentId): Promise<{ created: boolean; } | null>

Retry committing a pending offline-created document to the server.

Parameters ​

documentId ​

string

The pending document to retry committing

Returns ​

Promise<{ created: boolean; } | null>


runLocalTransaction() ​

runLocalTransaction(documentId, fn): void

Run a function as a local Yjs transaction (batches updates).

Parameters ​

documentId ​

string

The document to transact against

fn ​

() => void

Function to execute within the transaction; all Yjs mutations inside are batched into a single update

Returns ​

void


setDefaultDocumentId() ​

setDefaultDocumentId(documentId): void

Set the default document ID used by js-bao models when no explicit mapping exists.

Parameters ​

documentId ​

string

The document to use as the default for all unmapped models

Returns ​

void


updateLocalMetadata() ​

updateLocalMetadata<M>(documentId, updates): Promise<void>

Update a document's locally stored metadata (title, tags, thumbnailBlobId, docMetadata).

Type Parameters ​

M ​

M = unknown

Parameters ​

documentId ​

string

The document to update metadata for

updates ​

Fields to update in the local metadata cache

docMetadata? ​

M | null

New parsed metadata blob (or null to clear). Note: the server's wire field is named metadata; the local cache key is docMetadata to avoid colliding with the cache envelope's metadata key.

tags? ​

string[]

New document tags

thumbnailBlobId? ​

string | null

New thumbnail blob id (or null to clear)

title? ​

string

New document title

Returns ​

Promise<void>

Constructors ​

Constructor ​

new JsBaoClient(options): JsBaoClient

Parameters ​

options ​

JsBaoClientOptions

Returns ​

JsBaoClient

Overrides ​

Observable<any>.constructor

Properties ​

functions ​

functions: FunctionsAPI

Server functions, available as client.functions. Invokes code an app's team authored and pushed with primitive config push.

Methods ​

checkStateVector() ​

checkStateVector(documentId, timeoutMs?): Promise<{ includesWrites: boolean; inSync: boolean; }>

Ask the server to compare its state vector with the client's for a document. Returns { includesWrites, inSync } or safe defaults on failure/timeout.

Parameters ​

documentId ​

string

timeoutMs? ​

number = 5000

Returns ​

Promise<{ includesWrites: boolean; inSync: boolean; }>


createJsBaoInstance() ​

protected createJsBaoInstance(options): Promise<InitJsBaoResult>

Build this client's js-bao instance.

A seam, not an extension point: the constructor starts initialization without awaiting it, so the destroy/init race has no other place a test can hold the instance back from.

Parameters ​

options ​

InitJsBaoOptions

Returns ​

Promise<InitJsBaoResult>


once() ​

once(name, f): void

Parameters ​

name ​

any

f ​

Function

Returns ​

void

Inherited from ​

Observable.once


waitForSync() ​

waitForSync(documentId, timeoutMs?): Promise<void>

Parameters ​

documentId ​

string

timeoutMs? ​

number = 30000

Returns ​

Promise<void>

Deprecated ​

Use waitForInitialSync instead.

Authentication ​

checkOAuthAvailable() ​

checkOAuthAvailable(): Promise<boolean>

Check if OAuth authentication is available for this app.

Returns ​

Promise<boolean>


emailSignInRequest() ​

emailSignInRequest(email, options?): Promise<{ success: boolean; }>

Request one sign-in email. It carries a 6-digit code and — when a redirect target is available AND the app allow-lists it — a sign-in link, so the user can finish on the device they started on or on whichever device has their mail. Nothing selects a method up front.

Finish with otpVerify(email, code) for the code, or magicLinkVerify(token) for the link. Consuming either one retires both: one email, one session.

Parameters ​

email ​

string

The email address to sign in

options? ​

Optional configuration

redirectUri? ​

string

Where the link should land. Defaults to the client's oauthRedirectUri. With neither, the email carries the code alone rather than failing.

Returns ​

Promise<{ success: boolean; }>


getAppConfig() ​

getAppConfig(): Promise<{ appId: string; emailSignInEnabled: boolean; googleAvailable: boolean; hasPasskey: boolean; magicLinkEnabled: boolean; mode: "public" | "invite-only" | "domain"; name: string; waitlistEnabled: boolean; }>

Get the app's authentication configuration. Useful for checking what auth methods are available before showing login UI.

Returns ​

Promise<{ appId: string; emailSignInEnabled: boolean; googleAvailable: boolean; hasPasskey: boolean; magicLinkEnabled: boolean; mode: "public" | "invite-only" | "domain"; name: string; waitlistEnabled: boolean; }>


getAuthConfig() ​

getAuthConfig(): Promise<{ appId: string; appleSignInEnabled: boolean; emailSignInEnabled: boolean; googleClients: GoogleClientsConfig; googleOAuthEnabled: boolean; hasApple: boolean; hasPasskey: boolean; magicLinkEnabled: boolean; mode: string; name: string; otpEnabled: boolean; passkeyEnabled: boolean; passkeyRpConfig: Record<string, { name: string; }> | null; waitlistEnabled: boolean; }>

Get detailed authentication configuration including enabled providers and passkey settings.

Returns ​

Promise<{ appId: string; appleSignInEnabled: boolean; emailSignInEnabled: boolean; googleClients: GoogleClientsConfig; googleOAuthEnabled: boolean; hasApple: boolean; hasPasskey: boolean; magicLinkEnabled: boolean; mode: string; name: string; otpEnabled: boolean; passkeyEnabled: boolean; passkeyRpConfig: Record<string, { name: string; }> | null; waitlistEnabled: boolean; }>


getAuthPersistenceInfo() ​

getAuthPersistenceInfo(): object

Get info about how auth tokens are persisted (memory vs storage).

Returns ​

object

Object with persistence mode ("memory" or "persisted") and whether the stored token has been hydrated

hydrated ​

hydrated: boolean

mode ​

mode: "memory" | "persisted"


getAuthState() ​

getAuthState(): object

Get the current authentication state including mode (online/offline/none) and user ID.

Returns ​

object

Object with authenticated flag, current auth mode, and optional userId

authenticated ​

authenticated: boolean

mode ​

mode: "none" | "online" | "offline"

userId? ​

optional userId?: string


getRootDocId() ​

getRootDocId(): string | null

Get the root document ID for the authenticated user.

Returns ​

string | null


getToken() ​

getToken(): string | null

Get the current JWT auth token.

Returns ​

string | null


getUserId() ​

getUserId(): string | null

Get the current authenticated user's ID.

Returns ​

string | null


handleOAuthCallback() ​

handleOAuthCallback(code, state): Promise<void>

Handle the OAuth callback after the user completes the OAuth flow.

Parameters ​

code ​

string

The authorization code from the OAuth provider

state ​

string

The state parameter for CSRF verification

Returns ​

Promise<void>


isAuthenticated() ​

isAuthenticated(): boolean

Check if the client is currently authenticated.

Returns ​

boolean


logout() ​

logout(options?): Promise<void>

Logout: best-effort server cookie clear, shutdown networking, clear auth state, and optional local eviction.

  • Preserves stored offline grant by default (does not delete it)
  • Clears in-memory offline identity so the client is not considered authenticated

Parameters ​

options? ​

LogoutOptions

Controls logout behavior

Returns ​

Promise<void>


magicLinkRequest() ​

magicLinkRequest(email, options?): Promise<{ success: boolean; }>

Request a magic link email for passwordless authentication.

Parameters ​

email ​

string

The email address to send the magic link to

options? ​

Optional configuration

redirectUri? ​

string

Override the default OAuth redirect URI for the magic link callback

Returns ​

Promise<{ success: boolean; }>

Deprecated ​

Use emailSignInRequest. This is an alias of it — the server issues through the same path and sends the same email, which now also carries a 6-digit code.


magicLinkVerify() ​

magicLinkVerify(token, options?): Promise<{ isNewUser?: boolean; promptAddPasskey?: boolean; user: { email: string; name?: string; userId: string; }; }>

Verify a magic link token and authenticate the user.

Parameters ​

token ​

string

The magic link token from the email URL

options? ​

Optional flow parameters

inviteToken? ​

string

When present, accepts the named invitation server-side during verify and resolves deferred grants to the signing-in user, even when the magic-link email differs from the invited email

Returns ​

Promise<{ isNewUser?: boolean; promptAddPasskey?: boolean; user: { email: string; name?: string; userId: string; }; }>


otpRequest() ​

otpRequest(email): Promise<{ success: boolean; }>

Request a one-time password (OTP) code to be sent to the specified email. The code can be verified using otpVerify().

Parameters ​

email ​

string

The email address to send the OTP code to

Returns ​

Promise<{ success: boolean; }>

Deprecated ​

Use emailSignInRequest. This is an alias of it that carries no redirect target, so the email it sends is code-only.


otpVerify() ​

otpVerify(email, code, options?): Promise<{ isNewUser?: boolean; user: { email: string; name?: string; userId: string; }; }>

Verify a one-time password (OTP) code and authenticate the user. On success, the client will be authenticated and connected.

Parameters ​

email ​

string

The email address the OTP was sent to

code ​

string

The OTP code entered by the user

options? ​

Optional flow parameters

inviteToken? ​

string

When present, accepts the named invitation server-side during verify and resolves deferred grants to the signing-in user, even when the signup email differs from the invited email

Returns ​

Promise<{ isNewUser?: boolean; user: { email: string; name?: string; userId: string; }; }>


passkeyAuthFinish() ​

passkeyAuthFinish(credential, challengeToken): Promise<{ isNewUser?: boolean; user: { email: string; name?: string; userId: string; }; }>

Complete passkey authentication with the browser's credential response.

Parameters ​

credential ​

any

The credential response from the browser's WebAuthn API

challengeToken ​

string

The challenge token returned by passkeyAuthStart()

Returns ​

Promise<{ isNewUser?: boolean; user: { email: string; name?: string; userId: string; }; }>


passkeyAuthStart() ​

passkeyAuthStart(params?): Promise<{ challengeToken: string; options: any; }>

Start the passkey authentication flow, returns challenge options for the browser.

Parameters ​

params? ​

Optional flow parameters

rpId? ​

string

The relying party to run the ceremony against. Must be one of the app's configured passkey relying parties, else the call fails with PASSKEY_RP_NOT_CONFIGURED. Omit it in a browser, where the server derives the relying party from the request's Origin; name it from a native client, which sends no Origin at all.

Returns ​

Promise<{ challengeToken: string; options: any; }>


passkeyDelete() ​

passkeyDelete(passkeyId): Promise<{ success: boolean; }>

Delete a registered passkey by ID.

Parameters ​

passkeyId ​

string

The ID of the passkey to delete

Returns ​

Promise<{ success: boolean; }>


passkeyList() ​

passkeyList(): Promise<{ passkeys: object[]; }>

List all passkeys registered for the current user.

Returns ​

Promise<{ passkeys: object[]; }>


passkeyRegisterFinish() ​

passkeyRegisterFinish(credential, challengeToken, deviceName?, options?): Promise<{ credentialBackedUp?: boolean; invitation?: { grantsResolved: { documents: number; groups: number; }; invitationId: string; }; success: boolean; }>

Complete passkey registration with the browser's credential response.

Parameters ​

credential ​

any

The credential response from the browser's WebAuthn API

challengeToken ​

string

The challenge token returned by passkeyRegisterStart()

deviceName? ​

string

Optional human-readable name for this passkey (e.g. "MacBook Pro")

options? ​

Optional flow parameters

inviteToken? ​

string

When present, accepts the named invitation server-side for the authenticated caller and resolves deferred grants to them

Returns ​

Promise<{ credentialBackedUp?: boolean; invitation?: { grantsResolved: { documents: number; groups: number; }; invitationId: string; }; success: boolean; }>


passkeyRegisterStart() ​

passkeyRegisterStart(params?): Promise<{ challengeToken: string; options: any; }>

Start registering a new passkey for the current user.

Parameters ​

params? ​

Optional flow parameters

rpId? ​

string

The relying party to register the passkey under. Must be one of the app's configured passkey relying parties, else the call fails with PASSKEY_RP_NOT_CONFIGURED. Omit it in a browser; name it from a native client, which sends no Origin header.

Returns ​

Promise<{ challengeToken: string; options: any; }>


passkeyUpdate() ​

passkeyUpdate(passkeyId, params): Promise<{ passkey: { createdAt: string; deviceName: string; lastUsedAt?: string; passkeyId: string; }; }>

Update a passkey's metadata such as its device name.

Parameters ​

passkeyId ​

string

The ID of the passkey to update

params ​

Fields to update

deviceName ​

string

New human-readable name for the passkey

Returns ​

Promise<{ passkey: { createdAt: string; deviceName: string; lastUsedAt?: string; passkeyId: string; }; }>


setToken() ​

setToken(token, options?): void

Manually set the JWT auth token.

Parameters ​

token ​

string | null

The JWT token to use for authentication, or null to clear

options? ​

Optional metadata

cause? ​

string

Reason for the token change (used in event payloads and logging)

Returns ​

void


startOAuthFlow() ​

startOAuthFlow(continueUrl?, options?): Promise<void>

Start the OAuth authentication flow by redirecting to the OAuth provider.

Parameters ​

continueUrl? ​

string

URL to return to after the OAuth flow completes

options? ​

Additional flow options

inviteToken? ​

string

If provided, accepts the invitation server-side on callback and resolves deferred grants to the new user even when OAuth email differs from invited email

waitlist? ​

{ note?: string | null; source?: string | null; }

If provided, enrolls the user in the app's waitlist with optional source and note

waitlist.note? ​

string | null

waitlist.source? ​

string | null

Returns ​

Promise<void>


waitForAuthBootstrap() ​

waitForAuthBootstrap(): Promise<void>

Wait for the initial authentication bootstrap to complete (token refresh, offline unlock, etc.).

Returns ​

Promise<void>


waitForAuthReady() ​

waitForAuthReady(options?): Promise<{ mode: "online" | "offline"; userId: string; }>

Wait until the client is authenticated and return the auth mode and user ID.

Parameters ​

options? ​

WaitForAuthReadyOptions

Optional configuration

Returns ​

Promise<{ mode: "online" | "offline"; userId: string; }>

The authenticated userId and auth mode ("online" or "offline")


waitForUserId() ​

waitForUserId(options?): Promise<string>

Wait until a user ID is available (authenticated).

Parameters ​

options? ​

WaitForUserIdOptions

Optional configuration

Returns ​

Promise<string>


exchangeOAuthCode() ​

static exchangeOAuthCode(params): Promise<string>

Exchange an OAuth authorization code for an access token without constructing a client instance.

Parameters ​

params ​

OAuth exchange parameters

apiUrl ​

string

The API server base URL

appId ​

string

The application ID

code ​

string

The authorization code received from the OAuth provider

refreshProxyBaseUrl? ​

string | null

Optional proxy URL for refresh token cookie handling

refreshProxyCookieMaxAgeSeconds? ​

number

Max age in seconds for the refresh proxy cookie

state ​

string

The state parameter for CSRF verification

Returns ​

Promise<string>

Awareness ​

getAwarenessStates() ​

getAwarenessStates<S>(documentId): Map<string, S>

Get all users' awareness states for a document.

Type Parameters ​

S ​

S = unknown

Parameters ​

documentId ​

string

The document to get awareness states for

Returns ​

Map<string, S>


getLocalAwarenessState() ​

getLocalAwarenessState<S>(documentId): S | null

Get the local user's current awareness state for a document.

Type Parameters ​

S ​

S = unknown

Parameters ​

documentId ​

string

The document to get local awareness for

Returns ​

S | null


removeAwareness() ​

removeAwareness(documentId, clientIds, _reason?): void

Remove awareness states for specific clients.

Parameters ​

documentId ​

string

The document to remove awareness from

clientIds ​

string[]

Array of client IDs whose awareness states should be removed

_reason? ​

string

Optional reason for removal (used for logging)

Returns ​

void


removeAwarenessStates() ​

removeAwarenessStates(documentId, clientIds, _reason?): void

Remove awareness states for specific clients and broadcast the removal to the server.

Parameters ​

documentId ​

string

The document to remove awareness from

clientIds ​

string[]

Array of client IDs whose awareness states should be removed

_reason? ​

string

Optional reason for removal (used for logging)

Returns ​

void


setAwareness() ​

setAwareness<S>(documentId, state): void

Set the local user's awareness state for a document (e.g., cursor position, selection).

Type Parameters ​

S ​

S = unknown

Parameters ​

documentId ​

string

The document to set awareness for

state ​

S

Arbitrary awareness data (cursor, selection, user info) to broadcast to collaborators

Returns ​

void


setLocalAwarenessState() ​

setLocalAwarenessState<S>(documentId, state): void

Set the local awareness state for a document.

Type Parameters ​

S ​

S = unknown

Parameters ​

documentId ​

string

The document to set awareness for

state ​

S

Arbitrary awareness data (cursor, selection, user info) to broadcast to collaborators

Returns ​

void

Blobs ​

getBlobManager() ​

getBlobManager(): BlobManager

Get the blob manager for direct blob operations.

Returns ​

BlobManager


getBlobUploadConcurrency() ​

getBlobUploadConcurrency(): number

Get the current blob upload concurrency limit.

Returns ​

number


setBlobUploadConcurrency() ​

setBlobUploadConcurrency(value): void

Set the maximum number of concurrent blob uploads.

Parameters ​

value ​

number

Maximum number of blob uploads that can run in parallel

Returns ​

void

Configuration ​

getApiUrl() ​

getApiUrl(): string

Get the API base URL.

Returns ​

string


getAppId() ​

getAppId(): string

Get the app ID.

Returns ​

string


getGlobalAdminAppId() ​

getGlobalAdminAppId(): string

Get the global admin app ID.

Returns ​

string


setLogLevel() ​

setLogLevel(level): void

Set the client's log verbosity level.

Parameters ​

level ​

LogLevel

The minimum log level to output (e.g. "debug", "warn", "error")

Returns ​

void

Connection ​

connect() ​

connect(): void

Connect to the WebSocket server.

Returns ​

void


destroy() ​

destroy(): Promise<void>

Destroy the client, disconnecting and cleaning up all resources.

Returns ​

Promise<void>

Overrides ​

Observable.destroy


disconnect() ​

disconnect(): Promise<void>

Disconnect from the WebSocket server.

Returns ​

Promise<void>


fetchBinary() ​

fetchBinary(method, path): Promise<ArrayBuffer>

Fetch a binary (non-JSON) resource from the API using current auth. Used by blob downloads that return raw bytes.

Parameters ​

method ​

string

path ​

string

Returns ​

Promise<ArrayBuffer>


forceReconnect() ​

forceReconnect(): void

Force a WebSocket reconnection.

Returns ​

void


getConnectionId() ​

getConnectionId(): string

Get the unique ID for this client connection.

Returns ​

string


isConnected() ​

isConnected(): boolean

Check if the WebSocket is currently connected.

Returns ​

boolean


makeRequest() ​

makeRequest(method, path, data?, options?): Promise<any>

Make an authenticated HTTP request to the API server.

Parameters ​

method ​

string

HTTP method (GET, POST, PUT, DELETE, etc.)

path ​

string

API endpoint path relative to the app base URL

data? ​

any

Request body payload (sent as JSON)

options? ​

RequestOptions

Additional request options (headers, timeout, etc.)

Returns ​

Promise<any>


setShouldConnect() ​

setShouldConnect(shouldConnect): Promise<void>

Set whether the client should maintain a WebSocket connection.

shouldConnect: true waits out a disconnect that is already in flight and then connects, so a connect issued while the socket is closing does not race the close.

Last writer wins, with one exception. That wait is the only ordering guarantee: it applies to a disconnect already in flight, not to one that arrives afterwards. Calls issued concurrently with no ordering between them settle on whichever reaches the client last, so a disconnect() that lands after setShouldConnect(true) leaves the client disconnected with auto-reconnect off — an explicit disconnect means "stay down" and is not overridden by an earlier connect.

The exception is a coalesced disconnect: a disconnect() issued while another disconnect is still closing joins the one in flight rather than starting a new one, and does not cancel a setShouldConnect(true) already waiting on it. In the sequence disconnect() → setShouldConnect(true) → disconnect(), the client ends up connected even though a disconnect was issued last.

Await one call before making the other when you need a particular outcome.

Parameters ​

shouldConnect ​

boolean

If true, the client will connect and auto-reconnect; if false, it disconnects and stays disconnected

Returns ​

Promise<void>

Events ​

emit() ​

emit<K>(type, args): void

Emit a client event.

Type Parameters ​

K ​

K extends keyof JsBaoEvents

Parameters ​

type ​

K

The event name to emit

args ​

[JsBaoEvents[K]]

The event payload wrapped in an array

Returns ​

void

Overrides ​

Observable.emit


off() ​

off<K>(type, f): void

Unsubscribe from a client event.

Type Parameters ​

K ​

K extends keyof JsBaoEvents

Parameters ​

type ​

K

The event name to stop listening for

f ​

(payload) => void

The callback to remove

Returns ​

void

Overrides ​

Observable.off


on() ​

on<K>(type, f): void

Subscribe to a client event.

Type Parameters ​

K ​

K extends keyof JsBaoEvents

Parameters ​

type ​

K

The event name to listen for

f ​

(payload) => void

Callback invoked when the event fires

Returns ​

void

Overrides ​

Observable.on

Network ​

getNetworkStatus() ​

getNetworkStatus(): object

Get the current network status including connectivity and transport state.

Returns ​

object

Object with network mode, WebSocket transport state, isOnline flag, and optional lastOnlineAt/lastError

connected? ​

optional connected?: boolean

isOnline ​

isOnline: boolean

lastError? ​

optional lastError?: string

lastOnlineAt? ​

optional lastOnlineAt?: string

mode ​

mode: "auto" | "online" | "offline"

reason? ​

optional reason?: NetworkTransitionReason

transport ​

transport: "connected" | "connecting" | "disconnected"


goOffline() ​

goOffline(opts?): Promise<void>

Switch the client to offline mode.

Parameters ​

opts? ​

GoOfflineOptions

Optional configuration

Returns ​

Promise<void>


goOnline() ​

goOnline(): Promise<void>

Switch the client back to online mode.

Returns ​

Promise<void>


isOnline() ​

isOnline(): boolean

Check if the client is currently online.

Returns ​

boolean


setNetworkMode() ​

setNetworkMode(mode): Promise<void>

Set the network mode (auto, online, or offline).

Parameters ​

mode ​

"auto" | "online" | "offline"

"auto" to connect/disconnect based on connectivity, "online" to force connection, "offline" to force disconnection

Returns ​

Promise<void>

Offline & Sync ​

enableOfflineAccess() ​

enableOfflineAccess(options?): Promise<{ enabled: boolean; method?: "largeBlob" | "pin" | "signed"; reason?: string; }>

Enable offline access using passkey or PIN authentication.

Parameters ​

options? ​

EnableOfflineAccessOptions

Controls how offline credentials are created and stored

Returns ​

Promise<{ enabled: boolean; method?: "largeBlob" | "pin" | "signed"; reason?: string; }>

Object with enabled flag, the method used (largeBlob, pin, or signed), and an optional reason if not enabled


evictAllLocal() ​

evictAllLocal(opts?): Promise<void>

Remove all locally stored document data.

Parameters ​

opts? ​

EvictAllLocalOptions

Optional eviction behavior

Returns ​

Promise<void>


evictLocalDocument() ​

evictLocalDocument(documentId, opts?): Promise<void>

Remove a document's local data from storage.

Parameters ​

documentId ​

string

The document to evict

opts? ​

Optional eviction behavior

force? ​

boolean

If true, evicts even if the document has unsynced local changes

storageUser? ​

string | null

Internal

Whose local stores this is about. Defaults to the signed-in user; the sign-out path names the user who is signing OUT, because by then nobody is.

suppressMetadataEvent? ​

boolean

If true, does not emit a documentMetadataChanged event

Returns ​

Promise<void>


getLocalMetadata() ​

getLocalMetadata(documentId): Promise<LocalMetadataEntry | null>

Get locally stored metadata for a document.

Parameters ​

documentId ​

string

The document to get metadata for

Returns ​

Promise<LocalMetadataEntry | null>


getOfflineGrantStatus() ​

getOfflineGrantStatus(): object

Get detailed status of the offline access grant.

Returns ​

object

Object with available flag, optional expiresAt timestamp, daysLeft until expiry, and storage method

available ​

available: boolean

daysLeft? ​

optional daysLeft?: number

expiresAt? ​

optional expiresAt?: string

method? ​

optional method?: "largeBlob" | "pin" | "signed"


getOfflineIdentity() ​

getOfflineIdentity(): { appId: string; email?: string; name?: string; rootDocId: string; userId: string; } | null

Get the offline identity (user info available when offline).

Returns ​

{ appId: string; email?: string; name?: string; rootDocId: string; userId: string; } | null

The offline user identity with userId, appId, rootDocId, and optional email/name, or null if unavailable


getOfflineInfo() ​

getOfflineInfo(documentId): object

Get offline status information for a document.

Parameters ​

documentId ​

string

The document to get offline info for

Returns ​

object

Object with offlineEnabled, hasPersistence, isIdbSyncing flags, optional updatesStoreSize, and hasUnsyncedLocalChanges

hasPersistence ​

hasPersistence: boolean

hasUnsyncedLocalChanges? ​

optional hasUnsyncedLocalChanges?: boolean

isIdbSyncing ​

isIdbSyncing: boolean

offlineEnabled ​

offlineEnabled: boolean

updatesStoreSize? ​

optional updatesStoreSize?: number


hasIndexedDbPersistence() ​

hasIndexedDbPersistence(documentId): Promise<boolean>

Check if a document has IndexedDB persistence.

Parameters ​

documentId ​

string

The document to check for local persistence

Returns ​

Promise<boolean>


hasLocalCopy() ​

hasLocalCopy(documentId): boolean

Check if a document has local data available.

Parameters ​

documentId ​

string

The document to check for local data

Returns ​

boolean


hasOfflineGrantStored() ​

hasOfflineGrantStored(): Promise<boolean>

Check if an offline grant is stored locally.

Returns ​

Promise<boolean>


isDocumentSynced() ​

isDocumentSynced(documentId): boolean

Check if a document's data is synced with the server.

Parameters ​

documentId ​

string

The document to check sync status for

Returns ​

boolean


isOfflineGrantAvailable() ​

isOfflineGrantAvailable(): boolean

Check if an offline access grant is currently active.

Returns ​

boolean


isSynced() ​

isSynced(documentId): boolean

Check if a document is synced with the server.

Parameters ​

documentId ​

string

The document to check sync status for

Returns ​

boolean


listLocalDocuments() ​

listLocalDocuments(): Promise<LocalDocumentEntry[]>

List all documents stored locally.

Returns ​

Promise<LocalDocumentEntry[]>


listLocalDocumentsUnified() ​

listLocalDocumentsUnified(options?): Promise<DocumentInfo<unknown>[]>

List documents with merged local and server metadata.

Parameters ​

options? ​

ListLocalDocumentsOptions

Optional filters

Returns ​

Promise<DocumentInfo<unknown>[]>


renewOfflineGrantOnline() ​

renewOfflineGrantOnline(pinProvider?): Promise<boolean>

Renew the offline access grant while online.

Parameters ​

pinProvider? ​

() => Promise<string>

Async function that prompts for a PIN; required for PIN-based grants

Returns ​

Promise<boolean>


revokeOfflineGrant() ​

revokeOfflineGrant(opts?): Promise<void>

Revoke the offline access grant.

Parameters ​

opts? ​

RevokeOfflineGrantOptions

Optional revocation behavior

Returns ​

Promise<void>


setRetentionPolicy() ​

setRetentionPolicy(opts): void

Configure the local document retention policy.

Parameters ​

opts ​

Retention policy settings

default ​

"persist" | "session"

Default retention mode: "persist" keeps documents across sessions, "session" evicts on sign-out

maxBytes? ​

number

Maximum total bytes of local document data; oldest documents evicted when exceeded

maxDocs? ​

number

Maximum number of documents to keep locally; oldest are evicted first

preserveOnSignOut? ​

boolean

If true, retains local data even when the user signs out

ttlMs? ​

number

Time-to-live in milliseconds; documents older than this are evicted

Returns ​

void


startNetworkSync() ​

startNetworkSync(documentId): Promise<void>

Start network syncing for a document that was opened with deferred sync.

Parameters ​

documentId ​

string

The document to begin syncing with the server

Returns ​

Promise<void>


syncMetadata() ​

syncMetadata(options?): Promise<void>

Sync document metadata with the server.

Parameters ​

options? ​

SyncMetadataOptions

Controls the scope and behavior of the metadata sync

Returns ​

Promise<void>


syncMetadataForDocument() ​

syncMetadataForDocument(documentId, options?): Promise<void>

Sync metadata for a specific document.

Parameters ​

documentId ​

string

The document whose metadata to sync

options? ​

Optional sync behavior controls

background? ​

boolean

If true, silently swallows errors instead of throwing

payload? ​

any

Pre-fetched metadata payload to merge instead of fetching from server

payloadType? ​

"full" | "ids"

Whether the payload contains full metadata objects or just IDs

shouldRetain? ​

(docId) => boolean

Predicate controlling which documents are kept in the local cache

Returns ​

Promise<void>


unlockOffline() ​

unlockOffline(pinProvider?): Promise<boolean>

Unlock offline access using stored credentials.

Parameters ​

pinProvider? ​

() => Promise<string>

Async function that prompts the user for a PIN; required when the offline grant uses PIN-based storage

Returns ​

Promise<boolean>


updateLocalSnapshotFlag() ​

updateLocalSnapshotFlag(documentId, hasSnapshot): Promise<void>

Update the local snapshot flag for a document.

Parameters ​

documentId ​

string

The document to update the snapshot flag for

hasSnapshot ​

boolean

Whether the document has a local IndexedDB snapshot

Returns ​

Promise<void>

Deprecated ​

No longer called internally — hasIndexedDbSnapshot is now ignored in favour of checking live ydoc content via ydocHasData(). Retained for external callers; will be removed in a future major version.


upsertServerDocuments() ​

upsertServerDocuments(items, options?): void

Update local metadata cache with server document data.

Parameters ​

items ​

object[] | undefined

Array of server document records to merge into the local cache

options? ​

Controls how the merge is performed

authoritative? ​

boolean

If true, evicts local entries not present in the server list

payloadType? ​

"full" | "ids"

Whether items contain full metadata or just document IDs

retainIds? ​

Iterable<string, any, any>

Document IDs to keep locally even if missing from the server list

scope? ​

"all" | "single"

Whether to replace all metadata or merge a single document

shouldRetain? ​

(documentId) => boolean

Predicate controlling which documents are kept during eviction

targetDocumentId? ​

string

Specific document ID to update when scope is "single"

Returns ​

void


waitForInitialSync() ​

waitForInitialSync(documentId, timeoutMs?): Promise<void>

Wait until a document's initial sync with the server completes and the local update queue is drained. This does NOT confirm the server received the writes — use waitForWriteConfirmation for that.

Parameters ​

documentId ​

string

The document to wait for

timeoutMs? ​

number = 30000

Maximum time to wait before rejecting (ms, default 30000)

Returns ​

Promise<void>


waitForInSync() ​

waitForInSync(documentId, timeoutMs?, pollMs?): Promise<void>

Wait until the client and server have identical document state. Polls checkStateVector until inSync is true.

Parameters ​

documentId ​

string

The document to check

timeoutMs? ​

number = 5000

Maximum time to wait (ms, default 5000)

pollMs? ​

number = 50

Polling interval (ms, default 50)

Returns ​

Promise<void>


waitForWriteConfirmation() ​

waitForWriteConfirmation(documentId, timeoutMs?, pollMs?): Promise<boolean>

Wait until the server confirms it has all of this client's writes. Polls checkStateVector until includesWrites is true.

Parameters ​

documentId ​

string

The document to check

timeoutMs? ​

number = 5000

Maximum time to wait (ms, default 5000)

pollMs? ​

number = 50

Polling interval (ms, default 50)

Returns ​

Promise<boolean>

Realtime ​

subscribeToChannel() ​

subscribeToChannel(channel, grant): Promise<ChannelSubscription>

Join a channel a server function authorized.

grant is the token ctx.channels.authorize handed back: a signed, short-lived credential naming this app, this channel and this user. The promise resolves on the server's ack FOR THIS CHANNEL, so concurrent subscribes cannot resolve each other, and rejects on the server's uniform refusal — an expired, tampered, cross-app or cross-user grant are deliberately indistinguishable, so the rejection says only that the grant was not accepted.

Calling it again with a fresh grant RENEWS the membership: expiry is the only revocation a channel has, so an app that wants a long-lived channel re-invokes its authorizing function before expiresAt and subscribes again. Frames arrive as client.on("channelMessage", …).

Two calls for the SAME channel run one after the other, so a renewal issued while an earlier subscribe is still in flight is answered on its own merits rather than by whichever frame arrives first.

Parameters ​

channel ​

string

grant ​

string

Returns ​

Promise<ChannelSubscription>


unsubscribeFromChannel() ​

unsubscribeFromChannel(channel): void

Leave a channel. Idempotent, and safe on a closed socket: the registration goes either way, so a reconnect does not bring it back.

A subscribe still in flight, or queued behind one, is cancelled with it: leaving means leaving, so a queued renewal cannot put the membership back afterwards, and a subscribeToChannel promise still waiting for its ack rejects rather than resolving with a subscription to a channel this client has already left.

Parameters ​

channel ​

string

Returns ​

void

Sub-APIs ​

analytics ​

readonly analytics: AnalyticsClient

Analytics client for tracking events and metrics.


blobBuckets ​

blobBuckets: BlobBucketsAPI

Sub-API for managing general-purpose blob buckets (not tied to documents).


cache ​

cache: CacheFacade

Key-value cache facade backed by IndexedDB.


collections ​

collections: CollectionsAPI

Sub-API for managing document collections.


collectionTypeConfigs ​

collectionTypeConfigs: CollectionTypeConfigsAPI

Sub-API for managing collection type configurations.


cronTriggers ​

cronTriggers: CronTriggersAPI

Sub-API for managing cron triggers (workflow schedulers).

Deprecated ​

Schedule a server function instead: declare [[function.triggers.cron]] in its config (see the Server Functions guide).


databases ​

databases: DatabasesAPI

Sub-API for managing databases.

Deprecated ​

Call a server function instead: it reads and writes records with ctx.db and manages databases with ctx.api.databases (see the Working with Databases guide).


databaseTypeConfigs ​

databaseTypeConfigs: DatabaseTypeConfigsAPI

Sub-API for managing database type configurations.


documents ​

documents: DocumentsAPI

Sub-API for managing documents (list, create, get, delete, share).


groups ​

groups: GroupsAPI

Sub-API for managing groups and memberships.


groupTypeConfigs ​

groupTypeConfigs: GroupTypeConfigsAPI

Sub-API for managing group type configurations.


integrations ​

integrations: IntegrationsAPI

Sub-API for managing third-party integrations.

Deprecated ​

Call a server function instead: it calls the integration with ctx.integrations.call (see the Server Functions guide).


invitations ​

invitations: InvitationsAPI

Sub-API for app-level invitations and deferred grants.


locks ​

locks: LocksAPI

Sub-API for the named lock API (acquire/release/renew/status/list).


me ​

me: MeAPI

Sub-API for the current authenticated user's profile and preferences.


notifications ​

notifications: NotificationsAPI

Sub-API for the notification inbox (list, unread count, mark read, send).


prompts ​

prompts: PromptsAPI

Sub-API for managing and executing prompts.

Deprecated ​

Call a server function instead: it runs the prompt with ctx.prompts.run (see the Server Functions guide).


resourceMetadata ​

resourceMetadata: ResourceMetadataAPI

Sub-API for reading and writing typed resource metadata (single + batch).


ruleSets ​

ruleSets: RuleSetsAPI

Sub-API for managing rule sets.


session ​

session: SessionAPI

Sub-API for session management (sign in, sign out, token refresh).


users ​

users: UsersAPI

Sub-API for managing app users.


workflows ​

workflows: WorkflowsAPI

Sub-API for managing and executing workflows.

Deprecated ​

Call a server function instead: client.functions.invoke for a result, or client.functions.start for a long-running run (see the Server Functions guide).

Documentation validated against js-bao-wss-client 3.4.0 · js-bao 0.11.0 · primitive-admin 1.0.62 · primitive-app 3.1.0 — 2026-09-30