@abraca/dabra 2.76.0 → 2.78.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
@@ -297,6 +297,13 @@ declare class AbracadabraClient {
297
297
  * a busy server, and a connect burst fires several identical ones.
298
298
  * Keyed by the kind filter; cleared when the request settles. */
299
299
  private readonly rootListInflight;
300
+ /** Cached media-stream grants (`getStreamUrl`), keyed `docId/uploadId`.
301
+ * Re-minted just before expiry and dropped whenever the session token
302
+ * changes — a stream token inherits the identity that minted it. */
303
+ private readonly streamTokens;
304
+ /** In-flight mints, keyed like `streamTokens` — collapses the burst a page
305
+ * of media blocks produces into one request per upload. */
306
+ private readonly streamTokenInflight;
300
307
  constructor(config: AbracadabraClientConfig);
301
308
  get token(): string | null;
302
309
  set token(value: string | null);
@@ -577,6 +584,25 @@ declare class AbracadabraClient {
577
584
  searchDocs(query: string, opts?: {
578
585
  limit?: number;
579
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[]>;
580
606
  /**
581
607
  * Query for documents matching a structural predicate. v1 of the
582
608
  * indexed-query layer described in
@@ -643,6 +669,27 @@ declare class AbracadabraClient {
643
669
  listUploads(docId: string): Promise<UploadInfo[]>;
644
670
  /** Download an upload as a Blob. */
645
671
  getUpload(docId: string, uploadId: string): Promise<Blob>;
672
+ /**
673
+ * Mint a short-lived, read-only token bound to this one upload.
674
+ * Prefer `getStreamUrl`, which caches and reuses the grant.
675
+ */
676
+ createStreamToken(docId: string, uploadId: string): Promise<StreamTokenInfo>;
677
+ /**
678
+ * Absolute URL that streams an upload straight from the server, safe to
679
+ * hand to `<video src>` / `<audio src>`.
680
+ *
681
+ * Unlike `FileBlobStore.getBlobUrl` (which downloads the whole blob into
682
+ * IndexedDB and hands back an object URL), this keeps the bytes on the
683
+ * server so the browser can seek natively over HTTP Range — the difference
684
+ * between "wait for 400 MB" and "scrub instantly". It needs the network,
685
+ * so callers should fall back to `getBlobUrl` when offline.
686
+ *
687
+ * Grants are cached per upload and re-minted shortly before they expire.
688
+ * Throws on servers older than the `stream-token` endpoint (404).
689
+ */
690
+ getStreamUrl(docId: string, uploadId: string): Promise<string>;
691
+ /** Drop any cached stream grant for an upload (or all of them). */
692
+ clearStreamUrl(docId?: string, uploadId?: string): void;
646
693
  /**
647
694
  * Build the request path (with query string) for an upload's thumbnail.
648
695
  * Also the canonical cache key suffix — the query string is deterministic
@@ -1478,6 +1525,19 @@ declare class AbracadabraProvider extends AbracadabraBaseProvider {
1478
1525
  * errors across async await boundaries.
1479
1526
  */
1480
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>;
1481
1541
  get isConnected(): boolean;
1482
1542
  destroy(): void;
1483
1543
  }
@@ -1847,6 +1907,17 @@ interface ThumbnailOptions {
1847
1907
  /** JPEG quality 1–100. */
1848
1908
  q?: number;
1849
1909
  }
1910
+ /** Response of `POST /docs/:docId/uploads/:uploadId/stream-token` — a
1911
+ * short-lived grant that reads exactly one upload and travels in the query
1912
+ * string, so a `<video src>` can Range-seek it without an Authorization
1913
+ * header. `url` is server-relative. */
1914
+ interface StreamTokenInfo {
1915
+ token: string;
1916
+ /** Lifetime in seconds, from the moment the server minted it. */
1917
+ expires_in: number;
1918
+ /** `/docs/<docId>/uploads/<uploadId>?token=…` */
1919
+ url: string;
1920
+ }
1850
1921
  interface PublicKeyInfo {
1851
1922
  id: string;
1852
1923
  publicKey: string;
@@ -1981,6 +2052,19 @@ interface SearchResult {
1981
2052
  * a backend-specific score (SQLite bm25 vs Postgres ts_rank); the only
1982
2053
  * guarantee is that hits arrive in best-first order.
1983
2054
  */
2055
+ /**
2056
+ * One inbound link, as returned by `GET /docs/:id/backlinks`.
2057
+ *
2058
+ * Deliberately thin: identity plus enough to render a row. Anything richer
2059
+ * (icon, breadcrumb, the sentence the link sits in) lives in the client's own
2060
+ * tree/index — the server index only knows the edge.
2061
+ */
2062
+ interface DocBacklink {
2063
+ doc_id: string;
2064
+ label: string | null;
2065
+ /** Structural role tag (`space`/`page`/`channel`/…), when the doc has one. */
2066
+ kind: string | null;
2067
+ }
1984
2068
  interface DocSearchHit {
1985
2069
  doc_id: string;
1986
2070
  parent_id: string | null;
@@ -3397,6 +3481,18 @@ declare class FileBlobStore extends EventEmitter {
3397
3481
  * URL.createObjectURL is unavailable (e.g. Node.js / SSR).
3398
3482
  */
3399
3483
  getBlobUrl(docId: string, uploadId: string): Promise<string | null>;
3484
+ /**
3485
+ * Return a **server** URL that streams an upload with HTTP Range support —
3486
+ * for `<video src>` / `<audio src>`, where `getBlobUrl` would first pull
3487
+ * the entire file into IndexedDB and seeking would stall until it landed.
3488
+ *
3489
+ * Requires a client and the network (the URL points at the server, and
3490
+ * minting its token is a request). Returns `null` when either is missing,
3491
+ * when the server predates the `stream-token` endpoint, or when we're
3492
+ * already known to be offline — callers fall back to `getBlobUrl` for the
3493
+ * cached copy.
3494
+ */
3495
+ getStreamUrl(docId: string, uploadId: string): Promise<string | null>;
3400
3496
  /**
3401
3497
  * Return a local object URL for a **thumbnail** of an image upload.
3402
3498
  * On first call the server renders + caches it and this stores the bytes
@@ -5951,4 +6047,4 @@ declare function collectMediaFileBlocks(root: Y.XmlFragment | Y.XmlElement): Med
5951
6047
  */
5952
6048
  declare function reconcileDocCover(treeMap: Y.Map<unknown>, docId: string, fragment: Y.XmlFragment | Y.XmlElement): void;
5953
6049
  //#endregion
5954
- 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, 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 };
6050
+ 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, 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abraca/dabra",
3
- "version": "2.76.0",
3
+ "version": "2.78.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.76.0"
44
+ "@abraca/schema": "2.78.0"
45
45
  },
46
46
  "scripts": {
47
47
  "test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
@@ -4,6 +4,7 @@ import type {
4
4
  UploadMeta,
5
5
  UploadInfo,
6
6
  ThumbnailOptions,
7
+ StreamTokenInfo,
7
8
  PublicKeyInfo,
8
9
  PermissionEntry,
9
10
  EffectivePermissionsResponse,
@@ -16,6 +17,7 @@ import type {
16
17
  SnapshotCreateResult,
17
18
  SnapshotRestoreResult,
18
19
  SnapshotForkResult,
20
+ DocBacklink,
19
21
  DocSearchHit,
20
22
  AuditLogEntry,
21
23
  AuditQueryOpts,
@@ -119,6 +121,16 @@ export class AbracadabraClient {
119
121
  string,
120
122
  Promise<DocumentMeta[]>
121
123
  >();
124
+ /** Cached media-stream grants (`getStreamUrl`), keyed `docId/uploadId`.
125
+ * Re-minted just before expiry and dropped whenever the session token
126
+ * changes — a stream token inherits the identity that minted it. */
127
+ private readonly streamTokens = new Map<
128
+ string,
129
+ { url: string; expiresAt: number }
130
+ >();
131
+ /** In-flight mints, keyed like `streamTokens` — collapses the burst a page
132
+ * of media blocks produces into one request per upload. */
133
+ private readonly streamTokenInflight = new Map<string, Promise<string>>();
122
134
 
123
135
  constructor(config: AbracadabraClientConfig) {
124
136
  this.baseUrl = config.url.replace(/\/+$/, "");
@@ -140,6 +152,10 @@ export class AbracadabraClient {
140
152
 
141
153
  set token(value: string | null) {
142
154
  this._token = value;
155
+ // Stream grants carry the old identity (and die with it on
156
+ // logout-all) — never serve one across a session change.
157
+ this.streamTokens.clear();
158
+ this.streamTokenInflight.clear();
143
159
  if (this.persistAuth) {
144
160
  if (value) {
145
161
  this.persistToken(value);
@@ -660,6 +676,36 @@ export class AbracadabraClient {
660
676
  return res.results;
661
677
  }
662
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
+
663
709
  /**
664
710
  * Query for documents matching a structural predicate. v1 of the
665
711
  * indexed-query layer described in
@@ -900,6 +946,72 @@ export class AbracadabraClient {
900
946
  return res.blob();
901
947
  }
902
948
 
949
+ /**
950
+ * Mint a short-lived, read-only token bound to this one upload.
951
+ * Prefer `getStreamUrl`, which caches and reuses the grant.
952
+ */
953
+ async createStreamToken(
954
+ docId: string,
955
+ uploadId: string,
956
+ ): Promise<StreamTokenInfo> {
957
+ return this.request<StreamTokenInfo>(
958
+ "POST",
959
+ `/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}/stream-token`,
960
+ );
961
+ }
962
+
963
+ /**
964
+ * Absolute URL that streams an upload straight from the server, safe to
965
+ * hand to `<video src>` / `<audio src>`.
966
+ *
967
+ * Unlike `FileBlobStore.getBlobUrl` (which downloads the whole blob into
968
+ * IndexedDB and hands back an object URL), this keeps the bytes on the
969
+ * server so the browser can seek natively over HTTP Range — the difference
970
+ * between "wait for 400 MB" and "scrub instantly". It needs the network,
971
+ * so callers should fall back to `getBlobUrl` when offline.
972
+ *
973
+ * Grants are cached per upload and re-minted shortly before they expire.
974
+ * Throws on servers older than the `stream-token` endpoint (404).
975
+ */
976
+ async getStreamUrl(docId: string, uploadId: string): Promise<string> {
977
+ const key = `${docId}/${uploadId}`;
978
+ const cached = this.streamTokens.get(key);
979
+ // Re-mint a minute early so a URL handed to a media element doesn't
980
+ // expire mid-request.
981
+ if (cached && cached.expiresAt - 60_000 > Date.now()) return cached.url;
982
+
983
+ // Single-flight: a page full of media blocks resolves the same upload
984
+ // from several components at once, and each mint is a round trip.
985
+ const inflight = this.streamTokenInflight.get(key);
986
+ if (inflight) return inflight;
987
+
988
+ const pending = this.createStreamToken(docId, uploadId)
989
+ .then((info) => {
990
+ const url = `${this.baseUrl}${info.url}`;
991
+ this.streamTokens.set(key, {
992
+ url,
993
+ expiresAt: Date.now() + info.expires_in * 1000,
994
+ });
995
+ return url;
996
+ })
997
+ .finally(() => {
998
+ this.streamTokenInflight.delete(key);
999
+ });
1000
+ this.streamTokenInflight.set(key, pending);
1001
+ return pending;
1002
+ }
1003
+
1004
+ /** Drop any cached stream grant for an upload (or all of them). */
1005
+ clearStreamUrl(docId?: string, uploadId?: string): void {
1006
+ if (docId && uploadId) {
1007
+ this.streamTokens.delete(`${docId}/${uploadId}`);
1008
+ this.streamTokenInflight.delete(`${docId}/${uploadId}`);
1009
+ return;
1010
+ }
1011
+ this.streamTokens.clear();
1012
+ this.streamTokenInflight.clear();
1013
+ }
1014
+
903
1015
  /**
904
1016
  * Build the request path (with query string) for an upload's thumbnail.
905
1017
  * Also the canonical cache key suffix — the query string is deterministic
@@ -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
  {
@@ -153,6 +153,29 @@ export class FileBlobStore extends EventEmitter {
153
153
  );
154
154
  }
155
155
 
156
+ /**
157
+ * Return a **server** URL that streams an upload with HTTP Range support —
158
+ * for `<video src>` / `<audio src>`, where `getBlobUrl` would first pull
159
+ * the entire file into IndexedDB and seeking would stall until it landed.
160
+ *
161
+ * Requires a client and the network (the URL points at the server, and
162
+ * minting its token is a request). Returns `null` when either is missing,
163
+ * when the server predates the `stream-token` endpoint, or when we're
164
+ * already known to be offline — callers fall back to `getBlobUrl` for the
165
+ * cached copy.
166
+ */
167
+ async getStreamUrl(docId: string, uploadId: string): Promise<string | null> {
168
+ if (!this.client) return null;
169
+ if (typeof navigator !== "undefined" && navigator.onLine === false) {
170
+ return null;
171
+ }
172
+ try {
173
+ return await this.client.getStreamUrl(docId, uploadId);
174
+ } catch {
175
+ return null;
176
+ }
177
+ }
178
+
156
179
  /**
157
180
  * Return a local object URL for a **thumbnail** of an image upload.
158
181
  * On first call the server renders + caches it and this stores the bytes
package/src/types.ts CHANGED
@@ -292,6 +292,18 @@ export interface ThumbnailOptions {
292
292
  q?: number;
293
293
  }
294
294
 
295
+ /** Response of `POST /docs/:docId/uploads/:uploadId/stream-token` — a
296
+ * short-lived grant that reads exactly one upload and travels in the query
297
+ * string, so a `<video src>` can Range-seek it without an Authorization
298
+ * header. `url` is server-relative. */
299
+ export interface StreamTokenInfo {
300
+ token: string;
301
+ /** Lifetime in seconds, from the moment the server minted it. */
302
+ expires_in: number;
303
+ /** `/docs/<docId>/uploads/<uploadId>?token=…` */
304
+ url: string;
305
+ }
306
+
295
307
  export interface PublicKeyInfo {
296
308
  id: string;
297
309
  publicKey: string;
@@ -439,6 +451,20 @@ export interface SearchResult {
439
451
  * a backend-specific score (SQLite bm25 vs Postgres ts_rank); the only
440
452
  * guarantee is that hits arrive in best-first order.
441
453
  */
454
+ /**
455
+ * One inbound link, as returned by `GET /docs/:id/backlinks`.
456
+ *
457
+ * Deliberately thin: identity plus enough to render a row. Anything richer
458
+ * (icon, breadcrumb, the sentence the link sits in) lives in the client's own
459
+ * tree/index — the server index only knows the edge.
460
+ */
461
+ export interface DocBacklink {
462
+ doc_id: string;
463
+ label: string | null;
464
+ /** Structural role tag (`space`/`page`/`channel`/…), when the doc has one. */
465
+ kind: string | null;
466
+ }
467
+
442
468
  export interface DocSearchHit {
443
469
  doc_id: string;
444
470
  parent_id: string | null;