@abraca/dabra 2.77.0 → 2.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -584,6 +584,25 @@ declare class AbracadabraClient {
584
584
  searchDocs(query: string, opts?: {
585
585
  limit?: number;
586
586
  }): Promise<DocSearchHit[]>;
587
+ /**
588
+ * Documents that link TO `docId`, via `GET /docs/:id/backlinks`.
589
+ *
590
+ * Served from the server's `doc_links` index, which is rebuilt from each
591
+ * document's CRDT state whenever a snapshot is written. Prefer this over
592
+ * inverting links from a local cache: a client can only invert what it has
593
+ * downloaded, so on a large space a purely local backlink list is silently
594
+ * incomplete rather than empty-and-obviously-wrong.
595
+ *
596
+ * The caller must be able to read the target document, and each hit is
597
+ * cascade-filtered, so this never reveals a document the caller couldn't
598
+ * otherwise see. `limit` is clamped to `[1, 200]` server-side (default 50).
599
+ *
600
+ * Throws on servers that predate the endpoint — callers that need to work
601
+ * against older deployments should catch and fall back to a local index.
602
+ */
603
+ getBacklinks(docId: string, opts?: {
604
+ limit?: number;
605
+ }): Promise<DocBacklink[]>;
587
606
  /**
588
607
  * Query for documents matching a structural predicate. v1 of the
589
608
  * indexed-query layer described in
@@ -1506,6 +1525,19 @@ declare class AbracadabraProvider extends AbracadabraBaseProvider {
1506
1525
  * errors across async await boundaries.
1507
1526
  */
1508
1527
  private flushPendingUpdates;
1528
+ /**
1529
+ * Persist the current merged document state to the offline store.
1530
+ *
1531
+ * This is the ONLY path that persists server-delivered content
1532
+ * (`documentUpdateHandler` skips `origin === this`), so it MUST run for
1533
+ * read-only roles too — otherwise observers/viewers get a permanently
1534
+ * empty offline cache and every cold start waits for a full re-sync.
1535
+ *
1536
+ * Public so short-lived consumers that load a document, read it and
1537
+ * immediately unload it (BackgroundSyncManager) can force the write to
1538
+ * land before teardown instead of racing `destroy()`.
1539
+ */
1540
+ persistSnapshot(): Promise<void>;
1509
1541
  get isConnected(): boolean;
1510
1542
  destroy(): void;
1511
1543
  }
@@ -1696,6 +1728,40 @@ type ConstructableOutgoingMessage = Constructable<AuthenticationMessage> | Const
1696
1728
  type onAuthenticationFailedParameters = {
1697
1729
  reason: string;
1698
1730
  };
1731
+ /**
1732
+ * Why the server refused a local change.
1733
+ *
1734
+ * - `permission` — the resolved role on that document cannot write. The read
1735
+ * subscription stays alive; only the update was dropped.
1736
+ * - `validation` — the update was structurally accepted but rejected by a
1737
+ * server-side gate (schema validation, size/pattern guards). Deliberately
1738
+ * NOT an auth failure: the server sends `SyncStatus(applied=0)` rather than
1739
+ * a permission-denied frame so a transient data error can't bounce a legit
1740
+ * editor off sync.
1741
+ */
1742
+ type WriteRejectionKind = "permission" | "validation";
1743
+ /**
1744
+ * Fired when the server tells us a local change was NOT applied.
1745
+ *
1746
+ * This event exists because the refusal was previously unobservable from
1747
+ * application code. The server has always nacked — `AUTH_PERMISSION_DENIED`
1748
+ * for a role that cannot write, `SyncStatus(applied=0)` for a rejected
1749
+ * update — but the SDK folded the first into a generic
1750
+ * `authenticationFailed` (which apps do not listen to, since on a shared
1751
+ * socket it usually is not one) and dropped the second on the floor entirely.
1752
+ * The write stayed in the unsynced buffer and the UI showed an edit that had
1753
+ * already been refused, so "it saved, then it wasn't there after reload"
1754
+ * became the standard bug report for viewer-role clients.
1755
+ *
1756
+ * The change is NOT lost when this fires: `unsyncedChanges` deliberately does
1757
+ * not decrement, so the update remains queued for retry after whatever caused
1758
+ * the rejection is fixed. Treat this as "surface it", not "discard it".
1759
+ */
1760
+ type onWriteRejectedParameters = {
1761
+ /** Document name (id) whose update was refused. */documentName: string; /** Server-supplied reason where one exists, else a fixed description. */
1762
+ reason: string;
1763
+ kind: WriteRejectionKind;
1764
+ };
1699
1765
  type onAuthenticatedParameters = {
1700
1766
  scope: AuthorizedScope;
1701
1767
  };
@@ -2020,6 +2086,19 @@ interface SearchResult {
2020
2086
  * a backend-specific score (SQLite bm25 vs Postgres ts_rank); the only
2021
2087
  * guarantee is that hits arrive in best-first order.
2022
2088
  */
2089
+ /**
2090
+ * One inbound link, as returned by `GET /docs/:id/backlinks`.
2091
+ *
2092
+ * Deliberately thin: identity plus enough to render a row. Anything richer
2093
+ * (icon, breadcrumb, the sentence the link sits in) lives in the client's own
2094
+ * tree/index — the server index only knows the edge.
2095
+ */
2096
+ interface DocBacklink {
2097
+ doc_id: string;
2098
+ label: string | null;
2099
+ /** Structural role tag (`space`/`page`/`channel`/…), when the doc has one. */
2100
+ kind: string | null;
2101
+ }
2023
2102
  interface DocSearchHit {
2024
2103
  doc_id: string;
2025
2104
  parent_id: string | null;
@@ -2748,6 +2827,11 @@ interface CompleteAbracadabraBaseProviderConfiguration {
2748
2827
  forceSyncInterval: false | number;
2749
2828
  onAuthenticated: (data: onAuthenticatedParameters) => void;
2750
2829
  onAuthenticationFailed: (data: onAuthenticationFailedParameters) => void;
2830
+ /**
2831
+ * The server refused a local change. See {@link onWriteRejectedParameters} —
2832
+ * the change is still queued, not lost.
2833
+ */
2834
+ onWriteRejected: (data: onWriteRejectedParameters) => void;
2751
2835
  onRateLimited: () => void;
2752
2836
  onOpen: (data: onOpenParameters) => void;
2753
2837
  onReconnected: (data: onReconnectedParameters) => void;
@@ -2912,6 +2996,23 @@ declare class AbracadabraBaseProvider extends EventEmitter {
2912
2996
  detach(): void;
2913
2997
  attach(): void;
2914
2998
  permissionDeniedHandler(reason: string): void;
2999
+ /**
3000
+ * The most recent write the server refused, or `null` if it has never
3001
+ * refused one on this provider. Kept as state (not just an event) because
3002
+ * the common consumer question is "is my last edit actually saved?", which
3003
+ * an event fired before the component mounted cannot answer.
3004
+ */
3005
+ lastWriteRejection: onWriteRejectedParameters | null;
3006
+ /** Count of refused writes over this provider's lifetime. */
3007
+ writeRejectionCount: number;
3008
+ /**
3009
+ * Record and announce a server-refused local change.
3010
+ *
3011
+ * Called from both nack paths: the permission-denied auth frame and
3012
+ * `SyncStatus(applied=0)`. Deliberately does NOT touch the unsynced counter
3013
+ * — the update stays queued so a retry can land it once the cause is fixed.
3014
+ */
3015
+ reportWriteRejected(reason: string, kind: WriteRejectionKind): void;
2915
3016
  /**
2916
3017
  * Whether a permission-denied reason reflects a *transient* server condition
2917
3018
  * a retry can clear (a freshly-created doc not yet visible on this replica, or
@@ -6002,4 +6103,4 @@ declare function collectMediaFileBlocks(root: Y.XmlFragment | Y.XmlElement): Med
6002
6103
  */
6003
6104
  declare function reconcileDocCover(treeMap: Y.Map<unknown>, docId: string, fragment: Y.XmlFragment | Y.XmlElement): void;
6004
6105
  //#endregion
6005
- export { AbracadabraBaseProvider, AbracadabraBaseProviderConfiguration, AbracadabraClient, AbracadabraClientConfig, AbracadabraOutgoingMessageArguments, AbracadabraProvider, AbracadabraProviderConfiguration, AbracadabraWS, AbracadabraWSConfiguration, AbracadabraWebRTC, type AbracadabraWebRTCConfiguration, AbracadabraWebSocketConn, AdminConfigField, AdminConfigOriginKind, AuditLogEntry, AuditQueryOpts, AuditVerifyResult, AuthFailureContext, AuthFailureReason, AuthMessageType, AuthorizedScope, AwarenessError, BackgroundSyncManager, type BackgroundSyncManagerOptions, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, type ChatChannel, ChatClient, type ChatClientTransport, type MarkReadInput as ChatMarkReadInput, type ChatMessage, type ChatReadCursor, type ChatReadReceipt, type ChatTypingEvent, type ChildrenPage, CloseEvent, CompleteAbracadabraBaseProviderConfiguration, CompleteAbracadabraWSConfiguration, CompleteHocuspocusProviderConfiguration, CompleteHocuspocusProviderWebsocketConfiguration, type ConnectPolicyResult, ConnectionTimeout, Constructable, ConstructableOutgoingMessage, ContentManager, type CreateNotificationInput, CryptoIdentity, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, type DeleteMessageInput, DevicePairingChannel, type DevicePairingConfig, DeviceRegistrationService, type DeviceServerStatus, type DeviceSessionRecord, type DeviceSessionStorage, type DeviceTier, type DocEncryptionInfo, DocKeyManager, DocSearchHit, type DocSyncState, type DocSyncStatus, type DocumentBlock, DocumentCache, type DocumentCacheOptions, type DocumentContent, DocumentManager, type DocumentManagerConfig, DocumentMeta, type DocumentMetaInfo, type DocumentMetaWire, E2EAbracadabraProvider, E2EEChannel, type E2EEIdentity, E2EOfflineStore, type EditMessageInput, EffectivePermissionEntry, EffectivePermissionsResponse, EffectiveRole, EncryptedChatClient, EncryptedYMap, EncryptedYText, EnvSnapshotExtension, EnvSnapshotItem, EnvSnapshotResponse, type FetchInboxInput, type FetchNotificationsInput, FileBlobStore, FileTransferChannel, FileTransferHandle, type FileTransferMeta, type FileTransferStatus, type FoldedMessage, Forbidden, GEO_TYPE_META_SCHEMAS, type GetChatHistoryInput, HealthStatus, HocusPocusWebSocket, HocuspocusProvider, HocuspocusProviderConfiguration, HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration, HocuspocusWebSocket, type IdentityDeviceEntry, type IdentityDocConfiguration, IdentityDocProvider, type IdentityProfile, type IdentityServerEntry, type IdentitySpaceEntry, type InboxEntry, type MarkReadInput$1 as InboxMarkReadInput, InviteRow, KEY_EXCHANGE_CHANNEL, type KeyAuthClient, Kind, type LoadKeyFileOptions, LocalStorageDeviceSessionStorage, type LoginOrRegisterOptions, ManualSignaling, type ManualSignalingBlob, type MediaFileBlock, type MessageRecord, MessageTooBig, MessageType, MetaFieldType, MetaManager, MetaValidationError, type NodeKeypair, type NotificationReadUpdate, type NotificationRecord, NotificationsClient, OfflineStore, OutgoingMessageArguments, OutgoingMessageInterface, PAGE_TYPES, PageMeta, PageTypeInfo, PageTypeMetaField, type PairingRequest, type PairingResult, PeerConnection, type PeerInfo, type PeerState, PendingSubdoc, PermissionEntry, type PolicyAuthClient, PublicKeyInfo, QUERY_PREFIX, QueryClient, QueryError, type QueryFrame, type QueryKind, type QuerySpec, type QuerySubscriptionHandle, type QuerySubscriptionHandlers, type QueryTransport, RPC_PREFIX, ReadyzStatus, ResetConnection, type RpcCallHandle, type RpcCallOptions, RpcClient, RpcError, type RpcErrorCode, type RpcErrorPayload, type RpcFrame, type RpcHandler, type RpcHandlerContext, type RpcKind, type RpcTarget, type RpcTransport, SERVER_ROOT_ID, type SchemaDocTypeName, type SchemaMetaOf, type SchemaRegistryLike, type SchemaValidatorLike, SearchIndex, SearchResult, type SendChatMessageInput, type SendMessageInput, type SendMessageResult, ServerInfo, type ServerProfile, type ServerRegistry, type SignalingIncoming, type SignalingOutgoing, SignalingSocket, SnapshotCreateResult, SnapshotData, SnapshotFileEntry, SnapshotForkResult, SnapshotMeta, SnapshotRestoreResult, StatesArray, StreamTokenInfo, SubdocMessage, SubdocRegisteredEvent, TYPE_ALIASES, ThumbnailOptions, TokenManager, type TokenManagerOptions, TreeEntry, TreeManager, TreeNode, TreeSearchResult, TypedDocTypeMismatchError, type TypedDocsClient, type TypedTreeEntry, Unauthorized, UploadInfo, UploadMeta, UploadQueueEntry, UploadQueueStatus, UserMetaField, UserProfile, WebSocketStatus, WsReadyStates, YjsDataChannel, addServer, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, defaultKeyFileFor, deriveDmDocId, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, encryptChatContent, encryptField, filenameToLabel, foldRecords, generateMnemonic, isEncryptedContent, isPlaceholderLabel, loadOrCreateKeyFile, loadServerRegistry, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, migrateLegacyDefault, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, onAuthenticatedParameters, onAuthenticationFailedParameters, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onCompactedParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onReconnectedParameters, onServerErrorParameters, onStatelessParameters, onStatusParameters, onSubdocLoadedParameters, onSubdocRegisteredParameters, onSyncedParameters, onUnsyncedChangesParameters, openSyncedProvider, parseFrontmatter, patchEntry, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, removeServer, resolvePageType, resolveServer, saveServerRegistry, serverRegistryPath, setDefault, signChallengeWithSeed, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
6106
+ export { AbracadabraBaseProvider, AbracadabraBaseProviderConfiguration, AbracadabraClient, AbracadabraClientConfig, AbracadabraOutgoingMessageArguments, AbracadabraProvider, AbracadabraProviderConfiguration, AbracadabraWS, AbracadabraWSConfiguration, AbracadabraWebRTC, type AbracadabraWebRTCConfiguration, AbracadabraWebSocketConn, AdminConfigField, AdminConfigOriginKind, AuditLogEntry, AuditQueryOpts, AuditVerifyResult, AuthFailureContext, AuthFailureReason, AuthMessageType, AuthorizedScope, AwarenessError, BackgroundSyncManager, type BackgroundSyncManagerOptions, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, type ChatChannel, ChatClient, type ChatClientTransport, type MarkReadInput as ChatMarkReadInput, type ChatMessage, type ChatReadCursor, type ChatReadReceipt, type ChatTypingEvent, type ChildrenPage, CloseEvent, CompleteAbracadabraBaseProviderConfiguration, CompleteAbracadabraWSConfiguration, CompleteHocuspocusProviderConfiguration, CompleteHocuspocusProviderWebsocketConfiguration, type ConnectPolicyResult, ConnectionTimeout, Constructable, ConstructableOutgoingMessage, ContentManager, type CreateNotificationInput, CryptoIdentity, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, type DeleteMessageInput, DevicePairingChannel, type DevicePairingConfig, DeviceRegistrationService, type DeviceServerStatus, type DeviceSessionRecord, type DeviceSessionStorage, type DeviceTier, DocBacklink, type DocEncryptionInfo, DocKeyManager, DocSearchHit, type DocSyncState, type DocSyncStatus, type DocumentBlock, DocumentCache, type DocumentCacheOptions, type DocumentContent, DocumentManager, type DocumentManagerConfig, DocumentMeta, type DocumentMetaInfo, type DocumentMetaWire, E2EAbracadabraProvider, E2EEChannel, type E2EEIdentity, E2EOfflineStore, type EditMessageInput, EffectivePermissionEntry, EffectivePermissionsResponse, EffectiveRole, EncryptedChatClient, EncryptedYMap, EncryptedYText, EnvSnapshotExtension, EnvSnapshotItem, EnvSnapshotResponse, type FetchInboxInput, type FetchNotificationsInput, FileBlobStore, FileTransferChannel, FileTransferHandle, type FileTransferMeta, type FileTransferStatus, type FoldedMessage, Forbidden, GEO_TYPE_META_SCHEMAS, type GetChatHistoryInput, HealthStatus, HocusPocusWebSocket, HocuspocusProvider, HocuspocusProviderConfiguration, HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration, HocuspocusWebSocket, type IdentityDeviceEntry, type IdentityDocConfiguration, IdentityDocProvider, type IdentityProfile, type IdentityServerEntry, type IdentitySpaceEntry, type InboxEntry, type MarkReadInput$1 as InboxMarkReadInput, InviteRow, KEY_EXCHANGE_CHANNEL, type KeyAuthClient, Kind, type LoadKeyFileOptions, LocalStorageDeviceSessionStorage, type LoginOrRegisterOptions, ManualSignaling, type ManualSignalingBlob, type MediaFileBlock, type MessageRecord, MessageTooBig, MessageType, MetaFieldType, MetaManager, MetaValidationError, type NodeKeypair, type NotificationReadUpdate, type NotificationRecord, NotificationsClient, OfflineStore, OutgoingMessageArguments, OutgoingMessageInterface, PAGE_TYPES, PageMeta, PageTypeInfo, PageTypeMetaField, type PairingRequest, type PairingResult, PeerConnection, type PeerInfo, type PeerState, PendingSubdoc, PermissionEntry, type PolicyAuthClient, PublicKeyInfo, QUERY_PREFIX, QueryClient, QueryError, type QueryFrame, type QueryKind, type QuerySpec, type QuerySubscriptionHandle, type QuerySubscriptionHandlers, type QueryTransport, RPC_PREFIX, ReadyzStatus, ResetConnection, type RpcCallHandle, type RpcCallOptions, RpcClient, RpcError, type RpcErrorCode, type RpcErrorPayload, type RpcFrame, type RpcHandler, type RpcHandlerContext, type RpcKind, type RpcTarget, type RpcTransport, SERVER_ROOT_ID, type SchemaDocTypeName, type SchemaMetaOf, type SchemaRegistryLike, type SchemaValidatorLike, SearchIndex, SearchResult, type SendChatMessageInput, type SendMessageInput, type SendMessageResult, ServerInfo, type ServerProfile, type ServerRegistry, type SignalingIncoming, type SignalingOutgoing, SignalingSocket, SnapshotCreateResult, SnapshotData, SnapshotFileEntry, SnapshotForkResult, SnapshotMeta, SnapshotRestoreResult, StatesArray, StreamTokenInfo, SubdocMessage, SubdocRegisteredEvent, TYPE_ALIASES, ThumbnailOptions, TokenManager, type TokenManagerOptions, TreeEntry, TreeManager, TreeNode, TreeSearchResult, TypedDocTypeMismatchError, type TypedDocsClient, type TypedTreeEntry, Unauthorized, UploadInfo, UploadMeta, UploadQueueEntry, UploadQueueStatus, UserMetaField, UserProfile, WebSocketStatus, WriteRejectionKind, WsReadyStates, YjsDataChannel, addServer, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, defaultKeyFileFor, deriveDmDocId, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, encryptChatContent, encryptField, filenameToLabel, foldRecords, generateMnemonic, isEncryptedContent, isPlaceholderLabel, loadOrCreateKeyFile, loadServerRegistry, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, migrateLegacyDefault, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, onAuthenticatedParameters, onAuthenticationFailedParameters, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onCompactedParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onReconnectedParameters, onServerErrorParameters, onStatelessParameters, onStatusParameters, onSubdocLoadedParameters, onSubdocRegisteredParameters, onSyncedParameters, onUnsyncedChangesParameters, onWriteRejectedParameters, openSyncedProvider, parseFrontmatter, patchEntry, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, removeServer, resolvePageType, resolveServer, saveServerRegistry, serverRegistryPath, setDefault, signChallengeWithSeed, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abraca/dabra",
3
- "version": "2.77.0",
3
+ "version": "2.79.0",
4
4
  "description": "abracadabra provider",
5
5
  "keywords": [
6
6
  "abracadabra",
@@ -41,7 +41,7 @@
41
41
  "yjs": "^13.6.8"
42
42
  },
43
43
  "devDependencies": {
44
- "@abraca/schema": "2.77.0"
44
+ "@abraca/schema": "2.79.0"
45
45
  },
46
46
  "scripts": {
47
47
  "test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
@@ -22,6 +22,8 @@ import type {
22
22
  ConstructableOutgoingMessage,
23
23
  onAuthenticatedParameters,
24
24
  onAuthenticationFailedParameters,
25
+ onWriteRejectedParameters,
26
+ WriteRejectionKind,
25
27
  onAwarenessChangeParameters,
26
28
  onAwarenessUpdateParameters,
27
29
  onCloseParameters,
@@ -90,6 +92,11 @@ export interface CompleteAbracadabraBaseProviderConfiguration {
90
92
 
91
93
  onAuthenticated: (data: onAuthenticatedParameters) => void;
92
94
  onAuthenticationFailed: (data: onAuthenticationFailedParameters) => void;
95
+ /**
96
+ * The server refused a local change. See {@link onWriteRejectedParameters} —
97
+ * the change is still queued, not lost.
98
+ */
99
+ onWriteRejected: (data: onWriteRejectedParameters) => void;
93
100
  onRateLimited: () => void;
94
101
  onOpen: (data: onOpenParameters) => void;
95
102
  onReconnected: (data: onReconnectedParameters) => void;
@@ -126,6 +133,7 @@ export class AbracadabraBaseProvider extends EventEmitter {
126
133
  forceSyncInterval: false,
127
134
  onAuthenticated: () => null,
128
135
  onAuthenticationFailed: () => null,
136
+ onWriteRejected: () => null,
129
137
  onRateLimited: () => null,
130
138
  onOpen: () => null,
131
139
  onReconnected: () => null,
@@ -274,6 +282,7 @@ export class AbracadabraBaseProvider extends EventEmitter {
274
282
 
275
283
  this.on("authenticated", this.configuration.onAuthenticated);
276
284
  this.on("authenticationFailed", this.configuration.onAuthenticationFailed);
285
+ this.on("writeRejected", this.configuration.onWriteRejected);
277
286
  this.on("rateLimited", this.configuration.onRateLimited);
278
287
 
279
288
  this.awareness?.on("update", () => {
@@ -778,6 +787,15 @@ export class AbracadabraBaseProvider extends EventEmitter {
778
787
  }
779
788
 
780
789
  permissionDeniedHandler(reason: string) {
790
+ // A denial that arrives on a socket which has already authenticated AND
791
+ // synced this document is not an authentication problem — it is a write
792
+ // that was refused (see the mid-session note below). Surface it as one so
793
+ // app code has something to listen to that is not `authenticationFailed`,
794
+ // which on a shared socket is usually about somebody else's document.
795
+ if (this._hasEverAuthenticated && this.isSynced) {
796
+ this.reportWriteRejected(reason, "permission");
797
+ }
798
+
781
799
  this.emit("authenticationFailed", { reason });
782
800
  this.isAuthenticated = false;
783
801
 
@@ -834,6 +852,35 @@ export class AbracadabraBaseProvider extends EventEmitter {
834
852
  }
835
853
  }
836
854
 
855
+ /**
856
+ * The most recent write the server refused, or `null` if it has never
857
+ * refused one on this provider. Kept as state (not just an event) because
858
+ * the common consumer question is "is my last edit actually saved?", which
859
+ * an event fired before the component mounted cannot answer.
860
+ */
861
+ public lastWriteRejection: onWriteRejectedParameters | null = null;
862
+
863
+ /** Count of refused writes over this provider's lifetime. */
864
+ public writeRejectionCount = 0;
865
+
866
+ /**
867
+ * Record and announce a server-refused local change.
868
+ *
869
+ * Called from both nack paths: the permission-denied auth frame and
870
+ * `SyncStatus(applied=0)`. Deliberately does NOT touch the unsynced counter
871
+ * — the update stays queued so a retry can land it once the cause is fixed.
872
+ */
873
+ reportWriteRejected(reason: string, kind: WriteRejectionKind) {
874
+ const data: onWriteRejectedParameters = {
875
+ documentName: this.configuration.name,
876
+ reason,
877
+ kind,
878
+ };
879
+ this.lastWriteRejection = data;
880
+ this.writeRejectionCount += 1;
881
+ this.emit("writeRejected", data);
882
+ }
883
+
837
884
  /**
838
885
  * Whether a permission-denied reason reflects a *transient* server condition
839
886
  * a retry can clear (a freshly-created doc not yet visible on this replica, or
@@ -17,6 +17,7 @@ import type {
17
17
  SnapshotCreateResult,
18
18
  SnapshotRestoreResult,
19
19
  SnapshotForkResult,
20
+ DocBacklink,
20
21
  DocSearchHit,
21
22
  AuditLogEntry,
22
23
  AuditQueryOpts,
@@ -675,6 +676,36 @@ export class AbracadabraClient {
675
676
  return res.results;
676
677
  }
677
678
 
679
+ /**
680
+ * Documents that link TO `docId`, via `GET /docs/:id/backlinks`.
681
+ *
682
+ * Served from the server's `doc_links` index, which is rebuilt from each
683
+ * document's CRDT state whenever a snapshot is written. Prefer this over
684
+ * inverting links from a local cache: a client can only invert what it has
685
+ * downloaded, so on a large space a purely local backlink list is silently
686
+ * incomplete rather than empty-and-obviously-wrong.
687
+ *
688
+ * The caller must be able to read the target document, and each hit is
689
+ * cascade-filtered, so this never reveals a document the caller couldn't
690
+ * otherwise see. `limit` is clamped to `[1, 200]` server-side (default 50).
691
+ *
692
+ * Throws on servers that predate the endpoint — callers that need to work
693
+ * against older deployments should catch and fall back to a local index.
694
+ */
695
+ async getBacklinks(
696
+ docId: string,
697
+ opts?: { limit?: number },
698
+ ): Promise<DocBacklink[]> {
699
+ const params = new URLSearchParams();
700
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
701
+ const qs = params.toString();
702
+ const res = await this.request<{ results: DocBacklink[] }>(
703
+ "GET",
704
+ `/docs/${encodeURIComponent(docId)}/backlinks${qs ? `?${qs}` : ""}`,
705
+ );
706
+ return res.results;
707
+ }
708
+
678
709
  /**
679
710
  * Query for documents matching a structural predicate. v1 of the
680
711
  * indexed-query layer described in
@@ -815,10 +815,23 @@ export class AbracadabraProvider extends AbracadabraBaseProvider {
815
815
  const store = this.offlineStore;
816
816
  if (!store) return;
817
817
 
818
+ // Snapshot FIRST, before any awaited IndexedDB round-trip below.
819
+ //
820
+ // This used to run last, and the delay lost the write outright for
821
+ // short-lived providers: BackgroundSyncManager loads a child, awaits
822
+ // "synced", then unloads it in a `finally` — and `unloadChild` →
823
+ // `destroy()` closes the offline store. The `getPendingUpdates()` await
824
+ // here was enough of a gap for the store to be gone by the time the
825
+ // snapshot was written, and the failure is swallowed by `.catch()`.
826
+ // Measured on a real profile: 126 documents marked "synced" by
827
+ // background sync, 11 with a persisted snapshot. That is an empty
828
+ // offline cache for the other 115 — no offline reading, and nothing on
829
+ // disk for the client-side search/backlink index to walk.
830
+ await this.persistSnapshot();
831
+
818
832
  // Flushing queued *local* writes / subdoc registrations over the wire
819
833
  // is only meaningful for writers — a read-only session has none and
820
- // must not send. The snapshot save below is deliberately OUTSIDE this
821
- // guard.
834
+ // must not send.
822
835
  if (this.canWrite) {
823
836
  const updates = await store.getPendingUpdates();
824
837
  if (updates.length > 0) {
@@ -840,11 +853,23 @@ export class AbracadabraProvider extends AbracadabraBaseProvider {
840
853
  }
841
854
  }
842
855
 
843
- // Snapshot the current merged state so the next offline load sees it.
844
- // This is the ONLY path that persists server-delivered content
845
- // (documentUpdateHandler skips origin===this), so it MUST run for
846
- // read-only roles too — otherwise observers/viewers get a permanently
847
- // empty offline cache and every cold start waits for a full re-sync.
856
+ }
857
+
858
+ /**
859
+ * Persist the current merged document state to the offline store.
860
+ *
861
+ * This is the ONLY path that persists server-delivered content
862
+ * (`documentUpdateHandler` skips `origin === this`), so it MUST run for
863
+ * read-only roles too — otherwise observers/viewers get a permanently
864
+ * empty offline cache and every cold start waits for a full re-sync.
865
+ *
866
+ * Public so short-lived consumers that load a document, read it and
867
+ * immediately unload it (BackgroundSyncManager) can force the write to
868
+ * land before teardown instead of racing `destroy()`.
869
+ */
870
+ async persistSnapshot(): Promise<void> {
871
+ const store = this.offlineStore;
872
+ if (!store) return;
848
873
  const snapshot = Y.encodeStateAsUpdate(this.document);
849
874
  await store.saveDocSnapshot(snapshot).catch(() => null);
850
875
  }
@@ -628,6 +628,17 @@ export class BackgroundSyncManager extends EventEmitter {
628
628
  await childProvider.ready;
629
629
  await this._waitForSynced(childProvider);
630
630
 
631
+ // Force the offline snapshot to disk BEFORE the `finally` below
632
+ // unloads (and therefore destroys) this provider. The provider's own
633
+ // "synced" handler also writes one, but that runs concurrently and
634
+ // loses the race often enough that most background-synced documents
635
+ // ended up with an empty offline cache — which is also why the
636
+ // client-side search/backlink index had almost nothing to walk.
637
+ // "Synced" must mean "on disk", or this manager is lying.
638
+ if (typeof (childProvider as any).persistSnapshot === "function") {
639
+ await (childProvider as any).persistSnapshot();
640
+ }
641
+
631
642
  // Emit docSynced while the child is still loaded so listeners can
632
643
  // extract data (search text, file refs) without opening a new IDB.
633
644
  {
@@ -94,7 +94,22 @@ export class MessageReceiver {
94
94
  applySyncStatusMessage(provider: AbracadabraBaseProvider, applied: boolean) {
95
95
  if (applied) {
96
96
  provider.decrementUnsyncedChanges();
97
+ return;
97
98
  }
99
+
100
+ // applied = 0 is the server saying "I did not take that update". It is
101
+ // sent for a write the caller's role isn't allowed to make and for one a
102
+ // server-side gate rejected (schema validation, size/pattern guards).
103
+ //
104
+ // This branch used to be empty. Not decrementing is correct — the change
105
+ // must stay queued rather than be counted as landed — but silence is not:
106
+ // nothing in the SDK, and therefore nothing in any app built on it, could
107
+ // tell that the edit sitting on screen had already been refused. That is
108
+ // the whole "it saved, and then it wasn't there after reload" class.
109
+ provider.reportWriteRejected(
110
+ "server did not apply the update (permission or validation)",
111
+ "validation",
112
+ );
98
113
  }
99
114
 
100
115
  private applyAwarenessMessage(provider: AbracadabraBaseProvider) {
package/src/types.ts CHANGED
@@ -75,6 +75,44 @@ export type onAuthenticationFailedParameters = {
75
75
  reason: string;
76
76
  };
77
77
 
78
+ /**
79
+ * Why the server refused a local change.
80
+ *
81
+ * - `permission` — the resolved role on that document cannot write. The read
82
+ * subscription stays alive; only the update was dropped.
83
+ * - `validation` — the update was structurally accepted but rejected by a
84
+ * server-side gate (schema validation, size/pattern guards). Deliberately
85
+ * NOT an auth failure: the server sends `SyncStatus(applied=0)` rather than
86
+ * a permission-denied frame so a transient data error can't bounce a legit
87
+ * editor off sync.
88
+ */
89
+ export type WriteRejectionKind = "permission" | "validation";
90
+
91
+ /**
92
+ * Fired when the server tells us a local change was NOT applied.
93
+ *
94
+ * This event exists because the refusal was previously unobservable from
95
+ * application code. The server has always nacked — `AUTH_PERMISSION_DENIED`
96
+ * for a role that cannot write, `SyncStatus(applied=0)` for a rejected
97
+ * update — but the SDK folded the first into a generic
98
+ * `authenticationFailed` (which apps do not listen to, since on a shared
99
+ * socket it usually is not one) and dropped the second on the floor entirely.
100
+ * The write stayed in the unsynced buffer and the UI showed an edit that had
101
+ * already been refused, so "it saved, then it wasn't there after reload"
102
+ * became the standard bug report for viewer-role clients.
103
+ *
104
+ * The change is NOT lost when this fires: `unsyncedChanges` deliberately does
105
+ * not decrement, so the update remains queued for retry after whatever caused
106
+ * the rejection is fixed. Treat this as "surface it", not "discard it".
107
+ */
108
+ export type onWriteRejectedParameters = {
109
+ /** Document name (id) whose update was refused. */
110
+ documentName: string;
111
+ /** Server-supplied reason where one exists, else a fixed description. */
112
+ reason: string;
113
+ kind: WriteRejectionKind;
114
+ };
115
+
78
116
  export type onAuthenticatedParameters = {
79
117
  scope: AuthorizedScope;
80
118
  };
@@ -451,6 +489,20 @@ export interface SearchResult {
451
489
  * a backend-specific score (SQLite bm25 vs Postgres ts_rank); the only
452
490
  * guarantee is that hits arrive in best-first order.
453
491
  */
492
+ /**
493
+ * One inbound link, as returned by `GET /docs/:id/backlinks`.
494
+ *
495
+ * Deliberately thin: identity plus enough to render a row. Anything richer
496
+ * (icon, breadcrumb, the sentence the link sits in) lives in the client's own
497
+ * tree/index — the server index only knows the edge.
498
+ */
499
+ export interface DocBacklink {
500
+ doc_id: string;
501
+ label: string | null;
502
+ /** Structural role tag (`space`/`page`/`channel`/…), when the doc has one. */
503
+ kind: string | null;
504
+ }
505
+
454
506
  export interface DocSearchHit {
455
507
  doc_id: string;
456
508
  parent_id: string | null;