import type { PeerState } from "../PeerState.js"; import type { RawCoValue } from "../coValue.js"; import type { LoadMode } from "../queue/OutgoingLoadQueue.js"; import { type ControlledAccountOrAgent } from "../coValues/account.js"; import type { RawGroup } from "../coValues/group.js"; import { CryptoProvider, Hash, KeyID, KeySecret, Signature, SignerID } from "../crypto/crypto.js"; import { AgentID, RawCoID, SessionID, TransactionID } from "../ids.js"; import { JsonObject, JsonValue } from "../jsonValue.js"; import { LocalNode, ResolveAccountAgentError } from "../localNode.js"; import { KnownStateMessage, NewContentMessage, PeerID } from "../sync.js"; import { CoValueHeader, Transaction, VerifiedState } from "./verifiedState.js"; import { MergeCommit, BranchPointerCommit, BranchStartCommit } from "./branching.js"; import { type RawAccountID } from "../coValues/account.js"; import { CoValueFrontier, CoValueKnownState, KnownStateSessions } from "../knownState.js"; export declare function idforHeader(header: CoValueHeader, crypto: CryptoProvider): RawCoID; export declare function enablePermissionErrors(): void; export declare class VerifiedTransaction { coValueId: RawCoID; dispatchTransaction: (transaction: VerifiedTransaction) => void; author: RawAccountID | AgentID; currentTxID: TransactionID; sourceTxID: TransactionID | undefined; tx: Transaction; currentMadeAt: number; sourceTxMadeAt: number | undefined; changes: JsonValue[] | undefined; meta: JsonObject | undefined; isValid: boolean; validationErrorMessage: string | undefined; previous: VerifiedTransaction | undefined; stage: "to-validate" | "validated" | "processed"; constructor(coValueId: RawCoID, sessionID: SessionID, txIndex: number, tx: Transaction, branchId: RawCoID | undefined, parsingCache: { changes: JsonValue[]; meta: JsonObject | undefined; } | undefined, previous: VerifiedTransaction | undefined, dispatchTransaction: (transaction: VerifiedTransaction) => void); get txID(): TransactionID; get madeAt(): number; isValidTransactionWithChanges(): this is { changes: JsonValue[]; isValid: true; }; isProcessable(includeInvalidMetaTransactions: boolean): this is { changes: JsonValue[]; }; markValid(): void; markInvalid(errorMessage: string, attributes?: Record): void; markAsProcessed(): void; markAsToValidate(): void; } export type DecryptedTransaction = Omit & { changes: JsonValue[]; }; export type AvailableCoValueCore = CoValueCore & { verified: VerifiedState; }; export declare class CoValueCore { #private; readonly node: LocalNode; private readonly crypto; isDeleted: boolean; id: RawCoID; private _verified; /** Holds the fundamental syncable content of a CoValue, * consisting of the header (verified by hash -> RawCoID) * and the sessions (verified by signature). * * It does not do any *validation* or *decryption* and as such doesn't * depend on other CoValues or the LocalNode. * * `CoValueCore.verified` may be null when a CoValue is requested to be * loaded but no content has been received from storage or peers yet. * In this case, it acts as a centralised entry to keep track of peer loading * state and to subscribe to its content when it does become available. */ get verified(): VerifiedState | null; private readonly loadingStatuses; private _cachedContent?; readonly listeners: Set<(core: CoValueCore, unsub: () => void) => void>; private counter; constructor(id: RawCoID, node: LocalNode); get loadingState(): "available" | "garbageCollected" | "onlyKnownState" | "loading" | "unknown" | "unavailable"; hasMissingDependencies(): boolean; isAvailable(): this is AvailableCoValueCore; isKnownStateAvailable(): boolean; isCompletelyDownloaded(): boolean; isStreaming(): boolean; hasVerifiedContent(): this is AvailableCoValueCore; /** * Returns the CoValue data as NewContentMessage objects, excluding the transactions that are part of the given known state. * * Used to serialize the CoValue data to send it to peers and storage. */ newContentSince(knownState?: CoValueKnownState): NewContentMessage[] | undefined; isErroredInPeer(peerId: PeerID): boolean; getErroredInPeerError(peerId: PeerID): unknown; waitFor(opts: { predicate: (value: CoValueCore) => boolean; onSuccess: (value: CoValueCore) => void; }): void; waitForAsync(callback: (value: CoValueCore) => boolean): Promise; waitForAvailableOrUnavailable(): Promise; waitForAvailable(): Promise; waitForFullStreaming(): Promise; getLoadingStateForPeer(peerId: PeerID): "available" | "unknown" | "unavailable" | "pending" | "errored"; private updateCounter; /** * Removes the CoValue content from memory but keeps a shell with cached knownState. * This enables accurate LOAD requests during peer reconciliation. * * @returns true if the coValue was successfully unmounted, false otherwise */ unmount(): boolean; /** * Decrements the counter for the current loading state. * Used during unmount to properly track state transitions. * @internal */ decrementLoadingStateCounter(): void; markNotFoundInPeer(peerId: PeerID): void; markFoundInPeer(peerId: PeerID, previousState: string): void; /** * Clean up cached state when CoValue becomes available. * Called after the CoValue transitions from garbageCollected/onlyKnownState to available. */ private cleanupLastKnownState; /** * Initialize this CoValueCore as a garbageCollected shell. * Called when creating a replacement CoValueCore after unmounting. */ setGarbageCollectedState(knownState: CoValueKnownState): void; missingDependencies: Set<`co_z${string}`>; isCircularDependency(dependency: CoValueCore): boolean; newContentQueue: { msg: NewContentMessage; from: PeerState | "storage" | "import"; }[]; /** * Add a new content to the queue and handle it when the dependencies are available */ addNewContentToQueue(msg: NewContentMessage, from: PeerState | "storage" | "import"): void; addDependencyFromHeader(header: CoValueHeader): void; provideHeader(header: CoValueHeader, streamingKnownState?: KnownStateSessions, skipVerify?: boolean): boolean; markErrored(peerId: PeerID, error: unknown): void; markPending(peerId: PeerID): void; contentInClonedNodeWithDifferentAccount(account: ControlledAccountOrAgent): Promise; /** * Returns the known state considering the known state of the streaming source * * Used to correctly manage the content & subscriptions during the content streaming process */ knownStateWithStreaming(): CoValueKnownState; /** * Returns the known state of the CoValue * * For garbageCollected/onlyKnownState CoValues, returns the cached knownState. */ knownState(): CoValueKnownState; /** * Returns a new frontier object from the CoValue's known state */ frontier(): CoValueFrontier; /** * Returns a known state message to signal to the peer that the coValue doesn't need to be synced anymore * * Implemented to be backward compatible with clients that don't support deleted coValues */ stopSyncingKnownStateMessage(peerKnownState: CoValueKnownState | undefined): KnownStateMessage; get meta(): JsonValue; nextTransactionID(): TransactionID; addDependenciesFromContentMessage(newContent: NewContentMessage): void; /** * Apply new transactions that were not generated by the current node to the CoValue */ tryAddTransactions(sessionID: SessionID, newTransactions: Transaction[], newSignature: Signature, skipVerify?: boolean): { readonly type: "DeleteTransactionRejected"; readonly id: `co_z${string}`; readonly sessionID: `sealer_z${string}/signer_z${string}_session_d${string}$` | `${RawAccountID}_session_d${string}$`; readonly reason: "InvalidDeleteTransaction"; readonly error: Error; readonly author?: undefined; } | { readonly type: "DeleteTransactionRejected"; readonly id: `co_z${string}`; readonly sessionID: `sealer_z${string}/signer_z${string}_session_d${string}$` | `${RawAccountID}_session_d${string}$`; readonly reason: "CoValueNotDeletable"; readonly error: Error; readonly author?: undefined; } | { readonly type: "DeleteTransactionRejected"; readonly id: `co_z${string}`; readonly sessionID: SessionID; readonly author: `sealer_z${string}/signer_z${string}` | RawAccountID; readonly reason: "CoValueNotDeletable" | "NotAdmin" | "CannotVerifyPermissions"; readonly error: Error; } | { readonly type: "CoValueDeleted"; readonly id: `co_z${string}`; readonly error: Error; } | { readonly type: "ResolveAccountAgentError"; readonly id: `co_z${string}`; readonly error: unknown; } | { type: string; id: `co_z${string}`; error: undefined; } | { readonly type: "InvalidSignature"; readonly id: `co_z${string}`; readonly error: unknown; } | undefined; notifyDependants(): void; invalidateDependants(): void; private processNewTransactions; private scheduleNotifyUpdate; scheduleContentRebuild(): void; pauseNotifyUpdate(): void; resumeNotifyUpdate(): void; private notifyUpdate; subscribe(listener: (core: CoValueCore, unsub: () => void) => void, immediateInvoke?: boolean): () => void; validateDeletePermissions(): { ok: boolean; reason: string; message: string; } | { ok: boolean; reason?: undefined; message?: undefined; }; /** * Creates a delete marker transaction for this CoValue and sets the coValue as deleted * * Constraints: * - Account and Group CoValues cannot be deleted. * - Only admins can delete a coValue. */ deleteCoValue(): void; /** * Creates a new transaction with local changes and syncs it to all peers */ makeTransaction(changes: JsonValue[], privacy: "private" | "trusting", meta?: JsonObject, madeAt?: number): boolean; addDependenciesFromNewTransaction(transaction: Transaction): void; getCurrentContent(options?: { ignorePrivateTransactions: true; }): RawCoValue; branchStart: BranchStartCommit["from"] | undefined; mergeCommits: MergeCommit[]; branches: BranchPointerCommit[]; earliestTxMadeAt: number; latestTxMadeAt: number; resetParsedTransactions(): void; verifiedTransactions: VerifiedTransaction[]; toValidateTransactions: VerifiedTransaction[]; toDecryptTransactions: VerifiedTransaction[]; toParseMetaTransactions: VerifiedTransaction[]; toProcessTransactions: VerifiedTransaction[]; private verifiedTransactionsKnownSessions; private lastVerifiedTransactionBySessionID; private parsingCache; /** * Loads the new transaction from the SessionMap into verifiedTransactions as a VerifiedTransaction. * * If the transaction is already loaded from the SessionMap in the past, it will not be loaded again. * * Used to have a fast way to iterate over the CoValue transactions, and track their validation/decoding state. * @internal * */ loadVerifiedTransactionsFromLogs(): void; dispatchTransaction: (transaction: VerifiedTransaction) => void; /** * Iterates over the verifiedTransactions and marks them as valid or invalid, based on the group membership of the authors of the transactions . */ private determineValidTransactions; /** * Parses the meta information of a transaction, and set the branchStart and mergeCommits. */ private parseMetaInformation; /** * Loads the new transactions from SessionMap and: * - Validates each transaction based on the group membership of the authors * - Decodes the changes & meta for each transaction * - Parses the meta information of the transaction */ private parseNewTransactions; /** * Returns the valid transactions matching the criteria specified in the options */ getValidTransactions(options?: { ignorePrivateTransactions: boolean; from?: CoValueKnownState["sessions"]; to?: CoValueKnownState["sessions"]; knownTransactions?: Record; includeInvalidMetaTransactions?: boolean; skipBranchSource?: boolean; }): DecryptedTransaction[]; /** * The CoValues that this CoValue depends on. * We currently track dependencies for: * - Ownership (a CoValue depends on its account/group owner) * - Group membership (a group depends on its direct account/group members) * - Sessions (a CoValue depends on Accounts that made changes to it) * - Branches (a branched CoValue depends on its branch source) * See {@link dependant} for the CoValues that depend on this CoValue. */ dependencies: Set; incompleteDependencies: Set; private addDependency; /** * The CoValues that depend on this CoValue. * This is the inverse relationship of {@link dependencies}. */ dependant: Set; private addDependant; isGroupOrAccount(): boolean; isGroup(): boolean; createBranch(name: string, ownerId?: RawCoID): CoValueCore; mergeBranch(): CoValueCore; getBranch(name: string, ownerId?: RawCoID): CoValueCore; getCurrentBranchName(): string | undefined; getCurrentBranchSourceId(): `co_z${string}` | undefined; isBranched(): boolean; hasBranch(name: string, ownerId?: RawCoID): boolean; getMergeCommits(): MergeCommit[]; getValidSortedTransactions(options?: { ignorePrivateTransactions: boolean; knownTransactions?: Record; includeInvalidMetaTransactions?: boolean; }): DecryptedTransaction[]; compareTransactions(a: Pick, b: Pick): number; getCurrentReadKey(): { secret: KeySecret | undefined; id: KeyID; }; readKeyCache: Map<`key_z${string}`, `keySecret_z${string}`>; getReadKey(keyID: KeyID): KeySecret | undefined; safeGetGroup(): RawGroup | undefined; getGroup(): RawGroup; getTx(txID: TransactionID): Transaction | undefined; getDependedOnCoValues(): Set; waitForSync(options?: { timeout?: number; }): Promise; load(peers: PeerState[], mode?: LoadMode): void; loadFromStorage(done?: (found: boolean) => void): void; /** * Lazily load only the knownState from storage without loading full transaction data. * This is useful for checking if a peer needs new content before committing to a full load. * * If found in storage, marks the CoValue as onlyKnownState and caches the knownState. * This enables accurate LOAD requests during peer reconciliation. * * @param done - Callback with the storage knownState, or undefined if not found in storage */ getKnownStateFromStorage(done: (knownState: CoValueKnownState | undefined) => void): void; loadFromPeers(peers: PeerState[], mode?: LoadMode): void; private internalLoadFromPeer; } export type InvalidHashError = { type: "InvalidHash"; id: RawCoID; expectedNewHash: Hash; givenExpectedNewHash: Hash; }; export type InvalidSignatureError = { type: "InvalidSignature"; id: RawCoID; newSignature: Signature; sessionID: SessionID; signerID: SignerID | undefined; }; export type TriedToAddTransactionsWithoutVerifiedStateErrpr = { type: "TriedToAddTransactionsWithoutVerifiedState"; id: RawCoID; }; export type TriedToAddTransactionsWithoutSignerIDError = { type: "TriedToAddTransactionsWithoutSignerID"; id: RawCoID; sessionID: SessionID; }; export type DeleteTransactionRejectedError = { type: "DeleteTransactionRejected"; id: RawCoID; sessionID: SessionID; author: RawAccountID | AgentID; reason: "NotAdmin" | "CoValueNotDeletable" | "CannotVerifyPermissions"; error: Error; }; export type TryAddTransactionsError = TriedToAddTransactionsWithoutVerifiedStateErrpr | TriedToAddTransactionsWithoutSignerIDError | ResolveAccountAgentError | InvalidHashError | InvalidSignatureError | DeleteTransactionRejectedError; //# sourceMappingURL=coValueCore.d.ts.map