Skip to content

PeerborneDocument

Defined in: packages/core/src/peerborne-document.ts:913

DocType

ChangesType

ChangeFnType

PrivateKey

PublicKey

DocumentKey

new PeerborneDocument<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>(swarm, documentPath, _userKey, _userPublicKey, _crdtProvider, _authProvider, _aclProvider, _keychainProvider, _changesSerializer, _syncMessageSerializer, _loadMessageSerializer): PeerborneDocument<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>

Defined in: packages/core/src/peerborne-document.ts:1441

Peerborne<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>

Peerborne swarm that this document belongs to.

string

Path of the document.

PrivateKey

Private key identifying the current user.

PublicKey

Private key identifying the current user.

CRDTProvider<DocType, ChangesType, ChangeFnType>

CRDTProvider handles reading/writing CRDT document data and metadata.

AuthProvider<PrivateKey, PublicKey, DocumentKey>

AuthProvider handles signing/verification and encryption/decryption.

ACLProvider<ChangesType, PublicKey>

ACLProvider handles read/write ACL operations.

KeychainProvider<ChangesType, DocumentKey>

KeychainProvider handles read/write ACL operations.

ChangesSerializer<ChangesType>

ChangesSerializer is responsible for serializing/deserializing CRDT changes.

SyncMessageSerializer<ChangesType>

SyncMessageSerializer is responsible for serializing/deserializing CRDTSyncMessages.

LoadMessageSerializer

LoadMessageSerializer is responsible for serializing/deserializing CRDTLoadMessages.

PeerborneDocument<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>

readonly documentPath: string

Defined in: packages/core/src/peerborne-document.ts:1457

Path of the document.


readonly swarm: Peerborne<DocType, ChangesType, ChangeFnType, PrivateKey, PublicKey, DocumentKey>

Defined in: packages/core/src/peerborne-document.ts:1445

Peerborne swarm that this document belongs to.

get document(): DocType

Defined in: packages/core/src/peerborne-document.ts:927

DocType


get historyVisibility(): HistoryVisibility

Defined in: packages/core/src/peerborne-document.ts:1267

HistoryVisibility

set historyVisibility(value): void

Defined in: packages/core/src/peerborne-document.ts:1263

Set the history visibility for this document. This filters distributed epoch keys; it does not redact retained CRDT operations or provide a historical-content confidentiality boundary.

HistoryVisibility

void


get invitationEpoch(): Uint8Array<ArrayBufferLike> | undefined

Defined in: packages/core/src/peerborne-document.ts:9562

Test/inspection helper: returns a copy of the recorded invitation epoch, or undefined if no Welcome has been processed (e.g. founding member). The returned Uint8Array is a defensive copy so external callers cannot mutate the document’s internal state and alter subsequent since_invited filtering behavior.

Uint8Array<ArrayBufferLike> | undefined


get latestSnapshot(): CRDTSnapshotNode<ChangesType> | undefined

Defined in: packages/core/src/peerborne-document.ts:7322

Returns the current snapshot, if one exists.

CRDTSnapshotNode<ChangesType> | undefined


get libp2p(): Libp2p

Defined in: packages/core/src/peerborne-document.ts:1435

Libp2p


get pendingWelcomesCount(): number

Defined in: packages/core/src/peerborne-document.ts:9541

Internal

Test/inspection helper: number of BeeKEM Welcomes currently parked in the pending-welcomes buffer awaiting a readers-ACL update.

exposed only for unit tests.

number


get pendingWelcomesRetainedBytes(): number

Defined in: packages/core/src/peerborne-document.ts:9551

Internal

Test/inspection helper: exact number of serialized Welcome bytes retained by the pending-welcomes buffer.

exposed only for unit tests.

number

acceptInvitationBootstrap(bundle, issuerPublicKey, role, founderAddress): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:8482

Internal

Apply a recipient-bound invitation bootstrap and activate the document without invoking normal first-load/new-document detection.

The outer invitation acceptance must be verified against issuerPublicKey before this method is called. This method independently verifies the enclosed bootstrap signature against that exact key. It may only run on the reserved candidate created by Peerborne.acceptInvitation; failures discard that unexposed instance rather than returning partial provider state to application code.

InvitationBootstrapBundle

PublicKey

"reader" | "editor"

string

Promise<void>


addChange(changeFn): void

Defined in: packages/core/src/peerborne-document.ts:7082

Queue a change function within an active transaction. Must be called between startChange() and endChange().

ChangeFnType

void


addReader(reader, readerKemPublicKey): Promise<BeeKEMWelcomeV2>

Defined in: packages/core/src/peerborne-document.ts:7820

Add a new user as a valid reader. Users are identified by their public keys.

After updating the readers ACL, this attempts to send a BeeKEM Welcome to the new reader so they receive (a) the keychain changes appropriate for the document’s historyVisibility setting (so they can decrypt at least the current state), and (b) the invitation epoch ID they should record for subsequent since_invited history filtering. The Welcome is delivered via the beekemWelcomeV2 protocol to every currently-connected peer; the receiving document ignores Welcomes addressed to a different reader.

The BeeKEM registration is prepared on a detached tree and the reader ACL is claimed before publication. Live authorization is granted only after publication resolves, in the same synchronous turn that installs the prepared tree and identity caches.

The initial release supports the first reader plus exact retries for that identity. After removeReader advances the BeeKEM tree, adding a replacement is rejected before ACL or BeeKEM state changes.

CONFIDENTIALITY: the Welcome’s keychain delta is sealed with ECIES (P-256 ECDH + AES-256-GCM) under readerKemPublicKey, so only the intended recipient can decrypt it. The recipient binding (welcomeRecipient) is the authorization gate; the sealed payload is the confidentiality gate. See _sendBeeKEMWelcome for the full construction.

PublicKey

User’s identity (signing) public key.

Uint8Array

Raw SEC1-uncompressed P-256 ECDH public key (65 bytes) of the reader’s KEM key pair. The reader must hold the matching private key (see setKemKeyPair). The Welcome is sealed to this key; the library never broadcasts an un-sealed Welcome.

Promise<BeeKEMWelcomeV2>

The BeeKEM Welcome used for this reader.


addWriter(writer): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:7516

Grant write authorization to an existing explicit reader. Users are identified by their public keys. Call addReader() before promoting a new writer so a later removeWriter() can safely return them to read-only access without misrepresenting retained document-key access as revocation.

Promotion also requires the target’s identity-bound reader KEM public key and a matching live BeeKEM leaf. That binding is recorded in memory when this document instance adds the reader; readers added before this instance was opened cannot be promoted. Requires AuthProvider.serializePublicKey.

The local ACL commits only after GossipSub publication resolves. A rejected publish rolls back local DAG bookkeeping, but transport rejection is delivery-ambiguous: a remote peer may already have received the delta. This is a local publication boundary, not a distributed transaction.

PublicKey

User’s public key

Promise<void>


assertCanCreateInitialInvitation(): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:1127

Internal

Validate the deliberately narrow initial membership topology.

Promise<void>


buildInvitationBootstrap(reader, readerKemPublicKey, role, assertCanMutate?): Promise<InvitationBootstrapBundle>

Defined in: packages/core/src/peerborne-document.ts:8077

Internal

Grant an invitation recipient access and construct the encrypted material returned by the invitation join protocol. The caller is responsible for signing the outer acceptance and enforcing single-use offer semantics. Membership work is not transactional: an error after mutation begins can leave partial or complete recipient membership without a returned bundle. Only an exact, same-process retry is eligible to complete and attest that state. It publishes only the membership deltas that are still missing; committed ACL nodes reach the recipient through the signed bootstrap tree.

PublicKey

Uint8Array

"reader" | "editor"

() => void

Promise<InvitationBootstrapBundle>


change(changeFn, message?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:7286

Applies a new local change (defined by changeFn) to the peerborne document and updates all peers.

ChangeFnType

A function that makes changes to the current CRDT document.

string

An optional change message/description to include.

Promise<void>


close(): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:6525

Disconnects from this peerborne document. Running this method disconnects from the document pubsub topic.

Multiple open PeerborneDocument instances sharing the same documentPath are not supported. Cleanup is instance-safe, so a failed or stale instance does not unregister a newer live document.

Promise<void>


create(): Promise<boolean>

Defined in: packages/core/src/peerborne-document.ts:6250

Create a new document under an application-owned path without querying peers.

Promise<boolean>


createInvitation(options): Promise<InvitationOfferV1>

Defined in: packages/core/src/peerborne-document.ts:1119

Create a signed public offer for an online, distinct-identity join. The offer contains only public metadata and is safe to encode in a URL fragment. The inviter must remain online until the recipient accepts it.

CreateInvitationOptions

Promise<InvitationOfferV1>


endChange(message?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:7162

End the transaction and apply all queued changes atomically. This sends a single sync message for all batched changes.

On failure (from any step: write check, CRDT apply, or network publish), the transaction is aborted and the document reference is rolled back. For immutable CRDT providers (e.g. Automerge), rollback is reliable because localChange() returns a new document object.

Known limitation — in-place mutating providers: For CRDT providers that mutate in place (e.g. Yjs), rollback does NOT undo mutations. Yjs’s localChange() mutates the document object directly and returns the same reference, so restoring the saved reference after failure has no effect — the mutations have already been applied to the shared Y.Doc. Callers using Yjs should treat a failed transaction as leaving the local document in a potentially inconsistent state and consider re-syncing from peers.

Known limitation — concurrent remote changes during rollback: The rollback sets _document back to the snapshot captured when endChange() is called (before applying the pending change functions). Because _makeChange() is async and the node remains subscribed to pubsub throughout, remote sync messages may arrive and be applied to _document between the start of the transaction and the point of failure. Rolling back to the original snapshot reverts those remote changes as well, not just the local batch. This is acceptable because the CRDT layer guarantees eventual consistency — the reverted remote changes will be re-applied on the next sync cycle or document load. If transaction failure is critical, callers should re-sync the document after a failed transaction (e.g. call load() or wait for the next pubsub round) to ensure remote state is promptly restored.

Known limitation — partial internal state on failure: If _makeChange() fails partway through (e.g. encryption succeeds but pubsub publish throws), _hashes may retain CIDs for the rolled-back change (see below). Other counters and bookkeeping fields (_lastSyncMessage, _documentChangeCount, _changesSinceSnapshot, _recentTips) ARE restored from snapshots captured before _makeChange() — see the “Internal metadata rollback” section below for details.

Specifically, _hashes may retain CIDs for the rolled-back change. Because _hashes is used to skip already-seen changes during sync, any CID added before the failure will cause that change to be silently skipped if it arrives again via pubsub or load(). This means the rolled-back change is effectively “lost” from this peer’s perspective until _hashes is rebuilt. Callers should call load() after a failed transaction to re-sync the full document state from a peer and restore consistency. A new transaction must be started after a failure.

Internal metadata rollback: On failure, _lastSyncMessage, _documentChangeCount, _changesSinceSnapshot, and _recentTips are restored from snapshots captured before _makeChange(). (_recentTips is bounded to MAX_RECENT_TIPS entries so the snapshot is a cheap shallow array copy.) For _hashes and _referencedAncestors, all entries added to each Set after its pre-attempt size are removed. Because the node remains subscribed to pubsub during the async transaction, this may include CIDs appended by concurrent remote syncs, not just local ones. This is acceptable because CRDT convergence guarantees those remote CIDs will be re-added on the next sync cycle or document load. The approach is O(n) iteration but O(delta) memory — no full array clone — and avoids disrupting any concurrent sync iteration that clear() would break. A new transaction must be started after a failure.

string

Promise<void>

If any step in the commit pipeline fails.


getKemPublicKeyRaw(): Uint8Array<ArrayBufferLike> | undefined

Defined in: packages/core/src/peerborne-document.ts:1110

Returns the raw SEC1-uncompressed bytes (65 bytes) of the installed ECDH public key, or undefined if no key pair has been set via setKemKeyPair. The bytes are what inviters pass to addReader(reader, readerKemPublicKey).

The raw bytes are cached on setKemKeyPair, so this is a synchronous lookup. A defensive copy of the cached Uint8Array is returned so callers cannot accidentally mutate the document’s internal state (e.g. raw[0] = ...), which would otherwise cause hard-to-debug Welcome drops/mismatches on the receive path.

Uint8Array<ArrayBufferLike> | undefined


getReaders(): Promise<PublicKey[]>

Defined in: packages/core/src/peerborne-document.ts:7749

Returns a list of all public keys with read access.

Deduplicates users that appear in both reader and writer ACLs, which can occur due to concurrent edits or manual addition to both lists.

Promise<PublicKey[]>

List of public keys with read access.


getWriters(): Promise<PublicKey[]>

Defined in: packages/core/src/peerborne-document.ts:7490

Get list of writers.

Promise<PublicKey[]>

List of public keys with write access.


handleBeeKEMPathUpdateRequestData(payload, admission?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:10231

Internal

Handle an inbound beekemPathUpdateV2 payload (already de-framed of the path-prefix header by the shared handler in peerborne.ts).

Validates the writer signature, deserializes the carried PathUpdateV2, applies it to the local BeeKEM tree via processPathUpdate, and installs the resulting document key under the supplied epoch ID. Mirrors the wire framing used by handleBeeKEMWelcomeRequestData.

SECURITY: the writer signature is always verified, regardless of the swarm-wide enableSigning toggle. An unsigned or invalid-signature PathUpdateV2 is dropped without applying any state change. The receiver also validates that the epoch ID it derives locally matches the sender’s pathUpdateEpochId — a mismatch indicates either a peer with stale local BeeKEM state or a tampered payload, and is treated as a hard error.

Invoked by the shared protocol handler in peerborne.ts.

Uint8Array

SharedProtocolHandlerAdmission

Promise<void>


handleBeeKEMWelcomeRequestData(payload, admission?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:9020

Internal

Handles an incoming BeeKEM Welcome message with pre-read payload. Called by the shared protocol handler in Peerborne after the document path header has been stripped and the document looked up in the registry.

Verifies the writer signature on the message, merges the included keychain changes so future blocks can be decrypted, and records the welcomeEpochId as _invitationEpoch so subsequent since_invited history responses are correctly filtered.

Uint8Array

The serialized sync message (without the document path header that the shared handler already stripped).

SharedProtocolHandlerAdmission

Promise<void>


handleInvitationCatchUpRequestData(message, stream, admission?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:3079

CRDTLoadRequest

ProtocolWriteStream

SharedProtocolHandlerAdmission

Promise<void>


handleLoadRequestData(message, stream, admission?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:3071

CRDTLoadRequest

ProtocolWriteStream

SharedProtocolHandlerAdmission

Promise<void>


handleSecurityAdvertiseRequestData(message, stream, admission?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:4477

Internal

Handles an initial-load quorum security-advertise request with pre-read stream data. Called by the shared protocol handler in Peerborne after reading and routing.

Closes the “no quorum protocol for verifying initial document state” gap tracked under issue #189 §5.4 item 2 (also bulleted in #186). The wire protocol is securityAdvertiseV1 (see wire-protocols.ts); this method returns either an empty payload (decline) or an encrypted CRDTSyncMessage whose only populated payload field is tipsHash. The loader on the other side compares hashes across multiple peers and requires Q-of-K agreement before accepting any peer’s full document state. See load-quorum.ts for the decision logic.

Authorization mirrors the doc-load / snapshot-load handlers: when signing is enabled the requester must sign the document path with a key that appears in the readers or writers ACL. The response is encrypted under the document’s current key so a peer that does not already possess the key cannot use the tip hash as an oracle (key delivery is handled by the BeeKEM Welcome path).

CRDTLoadRequest

The deserialized load request (already parsed by the shared handler).

ProtocolWriteStream

The stream object for sending the response.

SharedProtocolHandlerAdmission

Promise<void>


handleSnapshotLoadRequestData(message, stream, admission?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:4372

Internal

Handles a snapshot-load request with pre-read stream data. Called by the shared protocol handler in Peerborne after reading and routing.

CRDTLoadRequest

The deserialized load request (already parsed by the shared handler).

ProtocolWriteStream

The stream object for sending the response.

SharedProtocolHandlerAdmission

Promise<void>


hasChange(cid): boolean

Defined in: packages/core/src/peerborne-document.ts:7378

Check whether a CID is known to this document (i.e. present in the in-memory _hashes set). Useful for callers that want to confirm a change exists before attempting a lazy load.

Note: returning true only proves the CID has been observed (it is tracked in _hashes for sync-message dedup). It does NOT guarantee the underlying block is locally available — after gcAfterPrune runs, the CID remains in _hashes even though the block has been removed from the blockstore. Callers should therefore still handle loadChangeBlock(cid) resolving to undefined (and may need to fall back to dialing peers).

string

boolean


historySize(): number

Defined in: packages/core/src/peerborne-document.ts:7314

Returns the total number of change nodes (including ACL nodes) tracked in the current document history. This is a count of all known CIDs, not the depth of the longest path in the DAG.

number


load(preferredPeer?): Promise<boolean>

Defined in: packages/core/src/peerborne-document.ts:6054

Load existing state using the current V4 protocol. Before network requests, capture a fresh challenge, canonical trusted writer authorities, and locally resolved control/group commitments. A first load requires resolveTrustedDocumentWriters; every normal load requires resolveLoadSecurityCommitments. A remote response cannot supply its own trust root. Signing is mandatory.

Quorum selection counts each authenticated authority once. The selected response must match the captured challenge and tuple; its derived frontier and complete manifest must match the agreed digest before mutation. Quorum loads prefetch the served tree’s CIDs before applying state. With loadQuorumEnabled false, one trusted signed V4 response may be selected; challenge, tuple, signature, and frontier checks still apply.

string | PeerId

Optional peer to try first (typically a PeerId from a pubsub message sender), matched against the last /p2p/<id> segment of each connection’s multiaddr.

Promise<boolean>

true after successful loading; false if no usable response is available without a quorum decision. Neither result authorizes creation.

If required agreement or bound delivery fails.

If no peer served the document and a response was discarded because writer authorization changed while it was being applied. The load can be retried.

If trust configuration is absent or bootstrap application left incomplete state. Discard an instance with incomplete application.


loadChangeBlock(cid): Promise<ChangesType | undefined>

Defined in: packages/core/src/peerborne-document.ts:7351

Lazy-load a historical change block by CID.

Used to fetch change data on demand for history-visibility consumers (e.g. audit UI, diff viewers) when the change has been pruned from the in-memory sync tree but the block is still present in the Helia blockstore. The returned ChangesType is the deserialized, decrypted payload.

Returns undefined when:

  • The CID is not in _hashes (we have never seen this change).
  • The block is missing from the blockstore (e.g. it was GC’d locally and no peer has re-served it yet). Callers that need stronger guarantees can fall back to dialing peers via the existing sync protocols.

Throws when:

  • The CID is malformed.
  • The block is present locally but decryption fails (wrong/missing keychain entry) or the payload fails to deserialize (corrupted data). These are treated as hard errors so callers can distinguish a recoverable “missing block” condition from a stronger data-integrity issue.

string

CID string of the change block to load.

Promise<ChangesType | undefined>

The deserialized change payload, or undefined if unavailable.


open(): Promise<boolean>

Defined in: packages/core/src/peerborne-document.ts:6240

Open an existing document, or activate verified invitation state. A failed or empty load never creates a document. Use create() with an application-owned path to explicitly authorize founding a new document.

Promise<boolean>

true when existing state is activated.

If state cannot be loaded or another activation is running.


removeReader(reader): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:9608

Remove a user as a valid reader. Users are identified by their public keys.

The target must first be downgraded from writer. Revocation resolves the target’s identity-bound KEM key to one unique live BeeKEM leaf, stages any reader-ACL delta, and performs the tree rotation on a clone. An already absent ACL row does not suppress a still-live leaf: the cryptographic removal proceeds.

The new local epoch key is staged before publication. Every participating provider must supply a commit claim: all fallible work finishes before publication, then captured nonthrowing finalizers install ACL, keychain, tree, and identity-cache state in one synchronous turn. A publication failure after valid claims leaves compliant providers on their original state. An invoked claim that throws or returns a malformed/asynchronous record, or a finalizer that throws or returns a value, violates the provider contract and poisons this document instance because partial application cannot be ruled out.

PathUpdateV2 delivery remains best effort after the local transition. A surviving member that misses it needs an explicit recipient-bound recovery or re-invitation; an ordinary load is encrypted under the unknown new key. BeeKEM state is not persisted across restarts. These are cooperative local-API invariants. Incoming raw ACL deltas are not yet checked against replicated identity/KEM transition records.

PublicKey

User’s public key.

Promise<void>

If the BeeKEM tree has no record of this reader (e.g. addReader did not seed a leaf for them, or BeeKEM membership was lost). Callers must surface this rather than silently degrading: a removeReader that “succeeded” without rotating the key would leave the removed reader with full ongoing access.

If identity/KEM/tree state is missing or divergent, a required commit claim is unavailable, or ACL publication fails.

If the target is not an explicit reader and has no identity-bound KEM or leaf record, unless the live BeeKEM tree holds only the local leaf. Removing a non-member is not a no-op while any remote leaf remains, because the absent records cannot prove it was revoked.


removeWriter(writer, options?): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:7646

Remove a user’s explicit write authorization while preserving their explicit reader authorization. A writer without explicit reader membership is rejected: this operation does not rotate document keys, so silently removing its only ACL row would misrepresent retained read access as full revocation. To fully revoke an editor, first downgrade it here, then call removeReader so the reader-removal flow rotates the BeeKEM epoch.

The local ACL commits only after GossipSub publication resolves. A rejected publish rolls back local DAG bookkeeping, but transport rejection is delivery-ambiguous: a remote peer may already have received the delta. This is a local publication boundary, not a distributed transaction.

PublicKey

User’s public key

RemoveWriterOptions

Set requireRemainingWriter to reject removal of the last writer with LastWriterRemovalError.

Promise<void>


setKemKeyPair(keyPair): Promise<void>

Defined in: packages/core/src/peerborne-document.ts:1067

Install the recipient-side ECDH (P-256) key pair used to open incoming BeeKEM Welcome sealed payloads. The application is responsible for persisting and re-supplying this key pair across sessions; the matching raw public key (see getKemPublicKeyRaw) must be communicated out-of-band to any writer who will invite this user, so they can pass it to addReader(reader, readerKemPublicKey).

Idempotent: calling with the same key pair more than once is fine. Pass undefined to clear (subsequent Welcomes will be dropped).

Validation: the key pair MUST be an ECDH P-256 pair, and the private key MUST have 'deriveBits' in its key usages so eciesOpen can perform the ECDH step. The public key MUST be raw-exportable (the inviter-side flow ships those bytes as the welcomeRecipientKemPublicKey field). Mismatches are rejected here with a descriptive error rather than silently accepted and surfaced as a generic WebCrypto failure later in the Welcome receive path.

Async because it eagerly exports the public key to raw bytes via crypto.subtle.exportKey and caches them for the receive path.

CryptoKeyPair | undefined

Promise<void>


snapshot(): Promise<CRDTSnapshotNode<ChangesType> | undefined>

Defined in: packages/core/src/peerborne-document.ts:7393

Creates a snapshot of the current document state.

The snapshot compacts all current change nodes into a single state representation. Requires CRDTProvider.getSnapshot() to be implemented.

Promise<CRDTSnapshotNode<ChangesType> | undefined>

The created snapshot node, or undefined if the provider does not support snapshots.

If the current user does not have write access to this document. Only writers are authorized to create snapshots.


startChange(): void

Defined in: packages/core/src/peerborne-document.ts:7069

Start a change transaction. Changes made via addChange() will be batched and applied atomically when endChange() is called.

void


subscribe(id, handler, originFilter?): void

Defined in: packages/core/src/peerborne-document.ts:7025

Subscribes a change handler to the document. Use this method to receive real-time updates to the document.

string

A unique id for this handler. Used to unsubscribe this handler.

PeerborneDocumentChangeHandler<DocType, PublicKey>

A function that is called when a change is received.

"all" | "remote" | "local"

Determines what kinds of change events trigger the handler. ‘remote’ indicates that the change was received from a remote peer. ‘local’ indicates that the change was received from the local document. ‘all’ indicates that all changes should be handled.

void


sync(message): Promise<boolean>

Defined in: packages/core/src/peerborne-document.ts:6574

Given a sync message containing a list of hashes:

  • Fetch new changes that are only hashes (missing change itself) from the blockstore (using the hash).
  • Apply new changes to the existing CRDT document.

OrdinarySyncMessage<ChangesType>

A sync message to apply.

Promise<boolean>

true if the message was applied successfully, false if rejected due to auth failure.

BREAKING CHANGE: Return type changed from Promise<void> to Promise<boolean>. TypeScript callers with explicit Promise<void> type annotations will need to update. Callers should now check the returned boolean to determine whether the message was applied successfully. The former public verifySignature bypass was also removed; ordinary sync always verifies signatures when signing is enabled. Protocol handlers that already verified a specialized message use an internal boundary.


unsubscribe(id): void

Defined in: packages/core/src/peerborne-document.ts:7053

Unsubscribes a change handler from the document.

string

The id of the handler to unsubscribe.

void