@abraca/dabra 2.102.0 → 2.103.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/abracadabra-provider.cjs +6673 -6543
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/esm/AbracadabraBaseProvider.js +558 -0
- package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
- package/dist/esm/AbracadabraClient.js +1424 -0
- package/dist/esm/AbracadabraClient.js.map +1 -0
- package/dist/esm/AbracadabraProvider.js +547 -0
- package/dist/esm/AbracadabraProvider.js.map +1 -0
- package/dist/esm/AbracadabraWS.js +398 -0
- package/dist/esm/AbracadabraWS.js.map +1 -0
- package/dist/esm/BackgroundSyncManager.js +571 -0
- package/dist/esm/BackgroundSyncManager.js.map +1 -0
- package/dist/esm/BackgroundSyncPersistence.js +62 -0
- package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
- package/dist/esm/ChatClient.js +176 -0
- package/dist/esm/ChatClient.js.map +1 -0
- package/dist/esm/CloseEvents.js +45 -0
- package/dist/esm/CloseEvents.js.map +1 -0
- package/dist/esm/ContentManager.js +153 -0
- package/dist/esm/ContentManager.js.map +1 -0
- package/dist/esm/CoverReconcile.js +124 -0
- package/dist/esm/CoverReconcile.js.map +1 -0
- package/dist/esm/CryptoIdentityKeystore.js +580 -0
- package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
- package/dist/esm/DeviceRegistrationService.js +158 -0
- package/dist/esm/DeviceRegistrationService.js.map +1 -0
- package/dist/esm/DocConverters.js +1300 -0
- package/dist/esm/DocConverters.js.map +1 -0
- package/dist/esm/DocKeyManager.js +145 -0
- package/dist/esm/DocKeyManager.js.map +1 -0
- package/dist/esm/DocTypes.js +792 -0
- package/dist/esm/DocTypes.js.map +1 -0
- package/dist/esm/DocUtils.js +180 -0
- package/dist/esm/DocUtils.js.map +1 -0
- package/dist/esm/DocumentCache.js +131 -0
- package/dist/esm/DocumentCache.js.map +1 -0
- package/dist/esm/DocumentManager.js +240 -0
- package/dist/esm/DocumentManager.js.map +1 -0
- package/dist/esm/E2EAbracadabraProvider.js +273 -0
- package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
- package/dist/esm/E2EOfflineStore.js +53 -0
- package/dist/esm/E2EOfflineStore.js.map +1 -0
- package/dist/esm/EncryptedChatClient.js +156 -0
- package/dist/esm/EncryptedChatClient.js.map +1 -0
- package/dist/esm/EncryptedY.js +115 -0
- package/dist/esm/EncryptedY.js.map +1 -0
- package/dist/esm/EventEmitter.js +40 -0
- package/dist/esm/EventEmitter.js.map +1 -0
- package/dist/esm/FileBlobStore.js +410 -0
- package/dist/esm/FileBlobStore.js.map +1 -0
- package/dist/esm/IdentityDoc.js +413 -0
- package/dist/esm/IdentityDoc.js.map +1 -0
- package/dist/esm/IncomingMessage.js +39 -0
- package/dist/esm/IncomingMessage.js.map +1 -0
- package/dist/esm/LifecycleGate.js +124 -0
- package/dist/esm/LifecycleGate.js.map +1 -0
- package/dist/esm/MessageReceiver.js +86 -0
- package/dist/esm/MessageReceiver.js.map +1 -0
- package/dist/esm/MessageSender.js +19 -0
- package/dist/esm/MessageSender.js.map +1 -0
- package/dist/esm/MetaManager.js +112 -0
- package/dist/esm/MetaManager.js.map +1 -0
- package/dist/esm/MnemonicKeyDerivation.js +137 -0
- package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
- package/dist/esm/NodeConnect.js +63 -0
- package/dist/esm/NodeConnect.js.map +1 -0
- package/dist/esm/NodeIdentity.js +212 -0
- package/dist/esm/NodeIdentity.js.map +1 -0
- package/dist/esm/NotificationsClient.js +136 -0
- package/dist/esm/NotificationsClient.js.map +1 -0
- package/dist/esm/OfflineStore.js +291 -0
- package/dist/esm/OfflineStore.js.map +1 -0
- package/dist/esm/OutgoingMessage.js +18 -0
- package/dist/esm/OutgoingMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
- package/dist/esm/PerfCounters.js +336 -0
- package/dist/esm/PerfCounters.js.map +1 -0
- package/dist/esm/QueryClient.js +117 -0
- package/dist/esm/QueryClient.js.map +1 -0
- package/dist/esm/RpcClient.js +456 -0
- package/dist/esm/RpcClient.js.map +1 -0
- package/dist/esm/SchemaTypes.js +38 -0
- package/dist/esm/SchemaTypes.js.map +1 -0
- package/dist/esm/SearchIndex.js +167 -0
- package/dist/esm/SearchIndex.js.map +1 -0
- package/dist/esm/ServerRegistry.js +139 -0
- package/dist/esm/ServerRegistry.js.map +1 -0
- package/dist/esm/ServerReset.js +170 -0
- package/dist/esm/ServerReset.js.map +1 -0
- package/dist/esm/TokenManager.js +236 -0
- package/dist/esm/TokenManager.js.map +1 -0
- package/dist/esm/TreeManager.js +655 -0
- package/dist/esm/TreeManager.js.map +1 -0
- package/dist/esm/TreeTimestamps.js +61 -0
- package/dist/esm/TreeTimestamps.js.map +1 -0
- package/dist/esm/auth.js +43 -0
- package/dist/esm/auth.js.map +1 -0
- package/dist/esm/awarenessStatesToArray.js +13 -0
- package/dist/esm/awarenessStatesToArray.js.map +1 -0
- package/dist/esm/docIds.js +53 -0
- package/dist/esm/docIds.js.map +1 -0
- package/dist/esm/encryptedContent.js +21 -0
- package/dist/esm/encryptedContent.js.map +1 -0
- package/dist/esm/index.js +61 -0
- package/dist/esm/messageRecord.js +64 -0
- package/dist/esm/messageRecord.js.map +1 -0
- package/dist/esm/sync/BroadcastChannelSync.js +160 -0
- package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
- package/dist/esm/types.js +54 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
- package/dist/esm/webrtc/DataChannelRouter.js +124 -0
- package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
- package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
- package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
- package/dist/esm/webrtc/E2EEChannel.js +137 -0
- package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
- package/dist/esm/webrtc/FileTransferChannel.js +250 -0
- package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
- package/dist/esm/webrtc/ManualSignaling.js +161 -0
- package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
- package/dist/esm/webrtc/PeerConnection.js +96 -0
- package/dist/esm/webrtc/PeerConnection.js.map +1 -0
- package/dist/esm/webrtc/SignalingSocket.js +274 -0
- package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
- package/dist/esm/webrtc/YjsDataChannel.js +135 -0
- package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
- package/dist/esm/webrtc/types.js +29 -0
- package/dist/esm/webrtc/types.js.map +1 -0
- package/dist/esm/x25519Convert.js +69 -0
- package/dist/esm/x25519Convert.js.map +1 -0
- package/dist/index.d.ts +26 -11
- package/package.json +6 -4
- package/dist/abracadabra-provider.esm.js +0 -14860
- package/dist/abracadabra-provider.esm.js.map +0 -1
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
//#region packages/provider/src/BackgroundSyncPersistence.ts
|
|
2
|
+
const DB_VERSION = 1;
|
|
3
|
+
function idbAvailable() {
|
|
4
|
+
return typeof globalThis !== "undefined" && "indexedDB" in globalThis;
|
|
5
|
+
}
|
|
6
|
+
function openDb(serverOrigin) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
const req = globalThis.indexedDB.open(`abracadabra:bgsync:${serverOrigin}`, DB_VERSION);
|
|
9
|
+
req.onupgradeneeded = (event) => {
|
|
10
|
+
const db = event.target.result;
|
|
11
|
+
if (!db.objectStoreNames.contains("sync_state")) db.createObjectStore("sync_state", { keyPath: "docId" });
|
|
12
|
+
};
|
|
13
|
+
req.onsuccess = () => resolve(req.result);
|
|
14
|
+
req.onerror = () => reject(req.error);
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
function idbPromise(request) {
|
|
18
|
+
return new Promise((resolve, reject) => {
|
|
19
|
+
request.onsuccess = () => resolve(request.result);
|
|
20
|
+
request.onerror = () => reject(request.error);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
var BackgroundSyncPersistence = class {
|
|
24
|
+
constructor(serverOrigin) {
|
|
25
|
+
this.dbPromise = null;
|
|
26
|
+
this.serverOrigin = serverOrigin;
|
|
27
|
+
}
|
|
28
|
+
getDb() {
|
|
29
|
+
if (!idbAvailable()) return Promise.resolve(null);
|
|
30
|
+
if (!this.dbPromise) this.dbPromise = openDb(this.serverOrigin).catch(() => null);
|
|
31
|
+
return this.dbPromise;
|
|
32
|
+
}
|
|
33
|
+
async getState(docId) {
|
|
34
|
+
const db = await this.getDb();
|
|
35
|
+
if (!db) return null;
|
|
36
|
+
return await idbPromise(db.transaction("sync_state", "readonly").objectStore("sync_state").get(docId)) ?? null;
|
|
37
|
+
}
|
|
38
|
+
async getAllStates() {
|
|
39
|
+
const db = await this.getDb();
|
|
40
|
+
if (!db) return [];
|
|
41
|
+
return new Promise((resolve, reject) => {
|
|
42
|
+
const req = db.transaction("sync_state", "readonly").objectStore("sync_state").getAll();
|
|
43
|
+
req.onsuccess = () => resolve(req.result);
|
|
44
|
+
req.onerror = () => reject(req.error);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
async setState(state) {
|
|
48
|
+
const db = await this.getDb();
|
|
49
|
+
if (!db) return;
|
|
50
|
+
await idbPromise(db.transaction("sync_state", "readwrite").objectStore("sync_state").put(state));
|
|
51
|
+
}
|
|
52
|
+
async deleteState(docId) {
|
|
53
|
+
const db = await this.getDb();
|
|
54
|
+
if (!db) return;
|
|
55
|
+
await idbPromise(db.transaction("sync_state", "readwrite").objectStore("sync_state").delete(docId));
|
|
56
|
+
}
|
|
57
|
+
destroy() {}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
//#endregion
|
|
61
|
+
export { BackgroundSyncPersistence };
|
|
62
|
+
//# sourceMappingURL=BackgroundSyncPersistence.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BackgroundSyncPersistence.js","names":[],"sources":["../../src/BackgroundSyncPersistence.ts"],"sourcesContent":["/**\n * BackgroundSyncPersistence\n *\n * Minimal IndexedDB store (`abracadabra:bgsync:{serverOrigin}`) that persists\n * per-document sync state across page reloads. A single object store,\n * `sync_state`, is keyed by `docId`.\n *\n * Falls back to a no-op when IndexedDB is unavailable (SSR / Node.js).\n */\n\n/**\n * Background-sync lifecycle status.\n *\n * - `pending` — never synced; queued for first attempt.\n * - `syncing` — attempt in progress (transient, not persisted as terminal).\n * - `synced` — last attempt succeeded; `lastSynced` is set.\n * - `retrying` — a *transient* failure (timeout, network) that has NOT yet\n * crossed the failure threshold. Will be retried silently;\n * the UI should treat this calmly and NOT count it as an error.\n * - `error` — a transient failure that has recurred past the threshold\n * (`consecutiveFailures >= FAILURE_THRESHOLD`). Genuinely\n * needs attention; this is what the UI surfaces as red.\n * - `unavailable` — a *permanent* failure (doc deleted/forbidden/invalid id —\n * 404/403/410/422). Not retried, and not surfaced as an error.\n * - `skipped` — E2E doc we can't sync (no keystore). Benign.\n */\nexport type DocSyncStatus =\n\t| \"pending\"\n\t| \"syncing\"\n\t| \"synced\"\n\t| \"retrying\"\n\t| \"error\"\n\t| \"unavailable\"\n\t| \"skipped\";\n\nexport interface DocSyncState {\n\tdocId: string;\n\t/** Current lifecycle status of this document's background sync. */\n\tstatus: DocSyncStatus;\n\t/** Unix ms of the last successful sync, or null if never synced. */\n\tlastSynced: number | null;\n\t/**\n\t * Human-readable message for the most recent failure. Populated for\n\t * `retrying`, `error`, and `unavailable` — cleared on a successful sync.\n\t */\n\terror?: string;\n\t/**\n\t * Count of consecutive failed attempts. Reset to 0 on success. Drives the\n\t * `retrying` → `error` escalation so a single transient blip never nags.\n\t */\n\tconsecutiveFailures?: number;\n\t/** Whether the document uses E2E encryption. */\n\tisE2E: boolean;\n}\n\nconst DB_VERSION = 1;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(serverOrigin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(\n\t\t\t`abracadabra:bgsync:${serverOrigin}`,\n\t\t\tDB_VERSION,\n\t\t);\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tif (!db.objectStoreNames.contains(\"sync_state\")) {\n\t\t\t\tdb.createObjectStore(\"sync_state\", { keyPath: \"docId\" });\n\t\t\t}\n\t\t};\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction idbPromise<T>(request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error);\n\t});\n}\n\nexport class BackgroundSyncPersistence {\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate readonly serverOrigin: string;\n\n\tconstructor(serverOrigin: string) {\n\t\tthis.serverOrigin = serverOrigin;\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.serverOrigin).catch(() => null);\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\tasync getState(docId: string): Promise<DocSyncState | null> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return null;\n\t\tconst tx = db.transaction(\"sync_state\", \"readonly\");\n\t\tconst result = await idbPromise<DocSyncState | undefined>(\n\t\t\ttx.objectStore(\"sync_state\").get(docId),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\tasync getAllStates(): Promise<DocSyncState[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"sync_state\", \"readonly\");\n\t\t\tconst req = tx.objectStore(\"sync_state\").getAll();\n\t\t\treq.onsuccess = () => resolve(req.result as DocSyncState[]);\n\t\t\treq.onerror = () => reject(req.error);\n\t\t});\n\t}\n\n\tasync setState(state: DocSyncState): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"sync_state\", \"readwrite\");\n\t\tawait idbPromise(tx.objectStore(\"sync_state\").put(state));\n\t}\n\n\tasync deleteState(docId: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\t\tconst tx = db.transaction(\"sync_state\", \"readwrite\");\n\t\tawait idbPromise(tx.objectStore(\"sync_state\").delete(docId));\n\t}\n\n\tdestroy(): void {\n\t\t// No cleanup needed — shared IDB connection managed by browser\n\t}\n}\n"],"mappings":";AAuDA,MAAM,aAAa;AAEnB,SAAS,eAAwB;AAChC,QAAO,OAAO,eAAe,eAAe,eAAe;;AAG5D,SAAS,OAAO,cAA4C;AAC3D,Q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AS,OAAoC;EAClD,MAAM,KAAK,MAAM,KAAK,OAAO;AAC7B,MAAI,CAAC,GAAI;AAET,QAAM,WADK,GAAG,YAAY,cAAc,YAAY,CAChC,YAAY,aAAa,CAAC,IAAI,MAAM,CAAC;;CAG1D,MAAM,YAAY,OAA8B;EAC/C,MAAM,KAAK,MAAM,KAAK,OAAO;AAC7B,MAAI,CAAC,GAAI;AAET,QAAM,WADK,GAAG,YAAY,cAAc,YAAY,CAChC,YAAY,aAAa,CAAC,OAAO,MAAM,CAAC;;CAG7D,UAAgB"}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import EventEmitter from "./EventEmitter.js";
|
|
2
|
+
|
|
3
|
+
//#region packages/provider/src/ChatClient.ts
|
|
4
|
+
const DEFAULT_TIMEOUT_MS = 1e4;
|
|
5
|
+
/**
|
|
6
|
+
* Thin façade over the `messages:*` stateless protocol.
|
|
7
|
+
*
|
|
8
|
+
* The unified messages model stores chat history as Y.Array entries on
|
|
9
|
+
* `kind = "channel-period"` child docs of channel/dm docs (and notifications
|
|
10
|
+
* as entries on a per-user `kind = "inbox"` doc). Reading history, listing
|
|
11
|
+
* channels, observing real-time messages, and tracking read cursors are all
|
|
12
|
+
* Y.Doc-shaped operations that the SDK consumer performs via
|
|
13
|
+
* `AbracadabraClient` + `AbracadabraProvider` directly — not through this
|
|
14
|
+
* façade. ChatClient handles only the *write-and-validate* path (sends,
|
|
15
|
+
* edits, deletes, typing, mark-read), where the server is the sole authority
|
|
16
|
+
* over the channel-period Y.Array.
|
|
17
|
+
*
|
|
18
|
+
* Events emitted:
|
|
19
|
+
* - `typing` → ChatTypingEvent (typing broadcast on the channel doc)
|
|
20
|
+
*
|
|
21
|
+
* For incoming-message observation, the consumer opens an
|
|
22
|
+
* `AbracadabraProvider` on the active period doc and observes its
|
|
23
|
+
* `messages` Y.Array directly. The dashboard's `useChat` composable does
|
|
24
|
+
* this; the integration tests do this; external consumers should mirror
|
|
25
|
+
* the pattern.
|
|
26
|
+
*/
|
|
27
|
+
var ChatClient = class extends EventEmitter {
|
|
28
|
+
constructor(provider, options) {
|
|
29
|
+
super();
|
|
30
|
+
this.pending = /* @__PURE__ */ new Map();
|
|
31
|
+
this.provider = provider;
|
|
32
|
+
this.responseTimeoutMs = options?.responseTimeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
33
|
+
this.boundOnStateless = (data) => this.handleStateless(data.payload);
|
|
34
|
+
this.boundOnServerError = (data) => this.handleServerError(data);
|
|
35
|
+
this.provider.on("stateless", this.boundOnStateless);
|
|
36
|
+
this.provider.on("serverError", this.boundOnServerError);
|
|
37
|
+
}
|
|
38
|
+
destroy() {
|
|
39
|
+
this.provider.off("stateless", this.boundOnStateless);
|
|
40
|
+
this.provider.off("serverError", this.boundOnServerError);
|
|
41
|
+
for (const queue of this.pending.values()) for (const p of queue) {
|
|
42
|
+
clearTimeout(p.timer);
|
|
43
|
+
p.reject(/* @__PURE__ */ new Error("ChatClient destroyed"));
|
|
44
|
+
}
|
|
45
|
+
this.pending.clear();
|
|
46
|
+
this.removeAllListeners();
|
|
47
|
+
}
|
|
48
|
+
/** Send a chat message. Resolves with the server-assigned id, ts, and signatures. */
|
|
49
|
+
send(input) {
|
|
50
|
+
const promise = this.enqueue("messages:send");
|
|
51
|
+
this.provider.sendStateless(JSON.stringify({
|
|
52
|
+
type: "messages:send",
|
|
53
|
+
channel_doc_id: input.channel_doc_id,
|
|
54
|
+
content: input.content,
|
|
55
|
+
mentions: input.mentions ?? [],
|
|
56
|
+
...input.reply_to !== void 0 ? { reply_to: input.reply_to } : {},
|
|
57
|
+
...input.sig !== void 0 ? { sig: input.sig } : {},
|
|
58
|
+
...input.ts_hint !== void 0 ? { ts_hint: input.ts_hint } : {}
|
|
59
|
+
}));
|
|
60
|
+
return promise;
|
|
61
|
+
}
|
|
62
|
+
/** Edit a previously-sent message. Append-only — server records an `edit` entry. */
|
|
63
|
+
edit(input) {
|
|
64
|
+
const promise = this.enqueue("messages:edit");
|
|
65
|
+
this.provider.sendStateless(JSON.stringify({
|
|
66
|
+
type: "messages:edit",
|
|
67
|
+
channel_doc_id: input.channel_doc_id,
|
|
68
|
+
message_id: input.message_id,
|
|
69
|
+
content: input.content,
|
|
70
|
+
...input.sig !== void 0 ? { sig: input.sig } : {}
|
|
71
|
+
}));
|
|
72
|
+
return promise;
|
|
73
|
+
}
|
|
74
|
+
/** Delete a message. Append-only — server records a `tombstone` entry. */
|
|
75
|
+
delete(input) {
|
|
76
|
+
const promise = this.enqueue("messages:delete");
|
|
77
|
+
this.provider.sendStateless(JSON.stringify({
|
|
78
|
+
type: "messages:delete",
|
|
79
|
+
channel_doc_id: input.channel_doc_id,
|
|
80
|
+
message_id: input.message_id
|
|
81
|
+
}));
|
|
82
|
+
return promise;
|
|
83
|
+
}
|
|
84
|
+
/** Broadcast a typing indicator on a channel. Fire-and-forget. */
|
|
85
|
+
typing(channel_doc_id) {
|
|
86
|
+
this.provider.sendStateless(JSON.stringify({
|
|
87
|
+
type: "messages:typing",
|
|
88
|
+
channel_doc_id
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
/** Mark a (period, message) position as read for the calling user. Fire-and-forget. */
|
|
92
|
+
markRead(input) {
|
|
93
|
+
this.provider.sendStateless(JSON.stringify({
|
|
94
|
+
type: "messages:mark_read",
|
|
95
|
+
channel_doc_id: input.channel_doc_id,
|
|
96
|
+
period_id: input.period_id,
|
|
97
|
+
message_id: input.message_id,
|
|
98
|
+
...input.ts !== void 0 ? { ts: input.ts } : {}
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
/** Observe typing broadcasts. */
|
|
102
|
+
onTyping(fn) {
|
|
103
|
+
return this.on("typing", fn);
|
|
104
|
+
}
|
|
105
|
+
enqueue(source) {
|
|
106
|
+
return new Promise((resolve, reject) => {
|
|
107
|
+
const entry = {
|
|
108
|
+
resolve,
|
|
109
|
+
reject,
|
|
110
|
+
timer: setTimeout(() => {
|
|
111
|
+
this.removePending(source, entry);
|
|
112
|
+
reject(/* @__PURE__ */ new Error(`ChatClient: timeout waiting for ${source} ack`));
|
|
113
|
+
}, this.responseTimeoutMs)
|
|
114
|
+
};
|
|
115
|
+
const queue = this.pending.get(source) ?? [];
|
|
116
|
+
queue.push(entry);
|
|
117
|
+
this.pending.set(source, queue);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
removePending(source, entry) {
|
|
121
|
+
const queue = this.pending.get(source);
|
|
122
|
+
if (!queue) return;
|
|
123
|
+
const idx = queue.indexOf(entry);
|
|
124
|
+
if (idx >= 0) queue.splice(idx, 1);
|
|
125
|
+
if (queue.length === 0) this.pending.delete(source);
|
|
126
|
+
}
|
|
127
|
+
resolveNext(source, value) {
|
|
128
|
+
const queue = this.pending.get(source);
|
|
129
|
+
if (!queue || queue.length === 0) return false;
|
|
130
|
+
const next = queue.shift();
|
|
131
|
+
if (queue.length === 0) this.pending.delete(source);
|
|
132
|
+
clearTimeout(next.timer);
|
|
133
|
+
next.resolve(value);
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
rejectNext(source, err) {
|
|
137
|
+
const queue = this.pending.get(source);
|
|
138
|
+
if (!queue || queue.length === 0) return false;
|
|
139
|
+
const next = queue.shift();
|
|
140
|
+
if (queue.length === 0) this.pending.delete(source);
|
|
141
|
+
clearTimeout(next.timer);
|
|
142
|
+
next.reject(err);
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
handleStateless(payload) {
|
|
146
|
+
let parsed;
|
|
147
|
+
try {
|
|
148
|
+
parsed = JSON.parse(payload);
|
|
149
|
+
} catch {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const type = parsed?.type;
|
|
153
|
+
if (typeof type !== "string") return;
|
|
154
|
+
if (type === "messages:ok" && typeof parsed.source === "string") {
|
|
155
|
+
this.resolveNext(parsed.source, parsed.meta);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (type === "messages:typing") {
|
|
159
|
+
this.emit("typing", {
|
|
160
|
+
channel: parsed.channel_doc_id,
|
|
161
|
+
sender_id: parsed.user_id,
|
|
162
|
+
sender_name: null
|
|
163
|
+
});
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
handleServerError(data) {
|
|
168
|
+
if (typeof data.source !== "string" || !data.source.startsWith("messages:")) return;
|
|
169
|
+
if (data.source === "messages:inbox_fetch" || data.source === "messages:inbox_mark_read") return;
|
|
170
|
+
this.rejectNext(data.source, /* @__PURE__ */ new Error(`${data.code ?? "error"}: ${data.message ?? "messages request failed"}`));
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
//#endregion
|
|
175
|
+
export { ChatClient };
|
|
176
|
+
//# sourceMappingURL=ChatClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ChatClient.js","names":[],"sources":["../../src/ChatClient.ts"],"sourcesContent":["import EventEmitter from \"./EventEmitter.ts\";\nimport type {\n ChatTypingEvent,\n SendChatMessageInput as _LegacySendInput,\n GetChatHistoryInput as _LegacyHistoryInput,\n} from \"./types.ts\";\n\n// Legacy alias re-exports kept for type-import compat with consumers that\n// import these names from `@abraca/dabra`. The old shapes still describe\n// the wire the dashboard's own reactive layer reads/writes; this client\n// itself no longer uses them as method inputs.\nexport type _ReExportedTypes = _LegacySendInput | _LegacyHistoryInput;\n\n/**\n * Minimal provider surface ChatClient needs. Matches `AbracadabraBaseProvider`.\n */\nexport interface ChatClientTransport {\n sendStateless(payload: string): void;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n on(event: string, fn: Function): unknown;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n off(event: string, fn?: Function): unknown;\n}\n\ntype PendingResolver<T> = {\n resolve: (value: T) => void;\n reject: (err: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/**\n * Send a chat message into a channel doc.\n *\n * `channel_doc_id` is the UUID of the channel/dm doc — `documents.id` for\n * a row with `kind = \"channel\"` or `kind = \"dm\"`. Group channels under a\n * Space pass the channel doc's id; DMs pass the DM doc's id (callers\n * resolve \"the DM doc between user A and user B\" via their own path —\n * typically `client.listChildren(serverRootId)` filtered by `kind === \"dm\"`\n * with both pubkeys in `permissions`).\n */\nexport interface SendMessageInput {\n channel_doc_id: string;\n content: string;\n /** Cleartext recipient pubkeys for server-side mention fan-out. */\n mentions?: string[];\n /** Message id this is a reply to. */\n reply_to?: string;\n /**\n * Optional Ed25519 signature over the canonical envelope, base64url. When\n * server config `[messages].require_client_sig = true`, sends without a\n * sig are rejected. Default-config servers accept unsigned sends — the\n * threat model relies on JWT-bound session auth + the server's own\n * `server_sig` over `(msg_id, period_id, ts, sig)`.\n */\n sig?: string;\n /** Client-side timestamp (ms) for skew-tolerance check. Optional. */\n ts_hint?: number;\n}\n\nexport interface SendMessageResult {\n message_id: string;\n period_id: string;\n ts: number;\n server_sig: string;\n}\n\nexport interface EditMessageInput {\n channel_doc_id: string;\n message_id: string;\n content: string;\n sig?: string;\n}\n\nexport interface DeleteMessageInput {\n channel_doc_id: string;\n message_id: string;\n}\n\nexport interface MarkReadInput {\n channel_doc_id: string;\n period_id: string;\n message_id: string;\n /** Unix milliseconds. Defaults to server time. */\n ts?: number;\n}\n\n/**\n * Thin façade over the `messages:*` stateless protocol.\n *\n * The unified messages model stores chat history as Y.Array entries on\n * `kind = \"channel-period\"` child docs of channel/dm docs (and notifications\n * as entries on a per-user `kind = \"inbox\"` doc). Reading history, listing\n * channels, observing real-time messages, and tracking read cursors are all\n * Y.Doc-shaped operations that the SDK consumer performs via\n * `AbracadabraClient` + `AbracadabraProvider` directly — not through this\n * façade. ChatClient handles only the *write-and-validate* path (sends,\n * edits, deletes, typing, mark-read), where the server is the sole authority\n * over the channel-period Y.Array.\n *\n * Events emitted:\n * - `typing` → ChatTypingEvent (typing broadcast on the channel doc)\n *\n * For incoming-message observation, the consumer opens an\n * `AbracadabraProvider` on the active period doc and observes its\n * `messages` Y.Array directly. The dashboard's `useChat` composable does\n * this; the integration tests do this; external consumers should mirror\n * the pattern.\n */\nexport class ChatClient extends EventEmitter {\n private readonly provider: ChatClientTransport;\n private readonly responseTimeoutMs: number;\n\n // FIFO of promises waiting on a typed `messages:ok` reply (keyed by source).\n private readonly pending: Map<string, PendingResolver<any>[]> = new Map();\n\n private readonly boundOnStateless: (data: { payload: string }) => void;\n private readonly boundOnServerError: (data: {\n source: string;\n code: string;\n message: string;\n meta?: unknown;\n }) => void;\n\n constructor(provider: ChatClientTransport, options?: { responseTimeoutMs?: number }) {\n super();\n this.provider = provider;\n this.responseTimeoutMs = options?.responseTimeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.boundOnStateless = (data) => this.handleStateless(data.payload);\n this.boundOnServerError = (data) => this.handleServerError(data);\n this.provider.on(\"stateless\", this.boundOnStateless);\n // BaseProvider intercepts `{type:\"error\",source,code}` frames and emits\n // them as `serverError`, not `stateless` — so request/response code paths\n // must listen here to learn about rejections.\n this.provider.on(\"serverError\", this.boundOnServerError);\n }\n\n destroy(): void {\n this.provider.off(\"stateless\", this.boundOnStateless);\n this.provider.off(\"serverError\", this.boundOnServerError);\n for (const queue of this.pending.values()) {\n for (const p of queue) {\n clearTimeout(p.timer);\n p.reject(new Error(\"ChatClient destroyed\"));\n }\n }\n this.pending.clear();\n this.removeAllListeners();\n }\n\n // ── Outgoing requests ──────────────────────────────────────────────────────\n\n /** Send a chat message. Resolves with the server-assigned id, ts, and signatures. */\n send(input: SendMessageInput): Promise<SendMessageResult> {\n const promise = this.enqueue<SendMessageResult>(\"messages:send\");\n this.provider.sendStateless(\n JSON.stringify({\n type: \"messages:send\",\n channel_doc_id: input.channel_doc_id,\n content: input.content,\n mentions: input.mentions ?? [],\n ...(input.reply_to !== undefined ? { reply_to: input.reply_to } : {}),\n ...(input.sig !== undefined ? { sig: input.sig } : {}),\n ...(input.ts_hint !== undefined ? { ts_hint: input.ts_hint } : {}),\n }),\n );\n return promise;\n }\n\n /** Edit a previously-sent message. Append-only — server records an `edit` entry. */\n edit(input: EditMessageInput): Promise<void> {\n const promise = this.enqueue<void>(\"messages:edit\");\n this.provider.sendStateless(\n JSON.stringify({\n type: \"messages:edit\",\n channel_doc_id: input.channel_doc_id,\n message_id: input.message_id,\n content: input.content,\n ...(input.sig !== undefined ? { sig: input.sig } : {}),\n }),\n );\n return promise;\n }\n\n /** Delete a message. Append-only — server records a `tombstone` entry. */\n delete(input: DeleteMessageInput): Promise<void> {\n const promise = this.enqueue<void>(\"messages:delete\");\n this.provider.sendStateless(\n JSON.stringify({\n type: \"messages:delete\",\n channel_doc_id: input.channel_doc_id,\n message_id: input.message_id,\n }),\n );\n return promise;\n }\n\n /** Broadcast a typing indicator on a channel. Fire-and-forget. */\n typing(channel_doc_id: string): void {\n this.provider.sendStateless(\n JSON.stringify({ type: \"messages:typing\", channel_doc_id }),\n );\n }\n\n /** Mark a (period, message) position as read for the calling user. Fire-and-forget. */\n markRead(input: MarkReadInput): void {\n this.provider.sendStateless(\n JSON.stringify({\n type: \"messages:mark_read\",\n channel_doc_id: input.channel_doc_id,\n period_id: input.period_id,\n message_id: input.message_id,\n ...(input.ts !== undefined ? { ts: input.ts } : {}),\n }),\n );\n }\n\n // ── Typed event subscription helpers ──────────────────────────────────────\n\n /** Observe typing broadcasts. */\n onTyping(fn: (e: ChatTypingEvent) => void): this {\n return this.on(\"typing\", fn) as this;\n }\n\n // ── Internals ─────────────────────────────────────────────────────────────\n\n private enqueue<T>(source: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.removePending(source, entry);\n reject(new Error(`ChatClient: timeout waiting for ${source} ack`));\n }, this.responseTimeoutMs);\n const entry: PendingResolver<T> = { resolve, reject, timer };\n const queue = this.pending.get(source) ?? [];\n queue.push(entry);\n this.pending.set(source, queue);\n });\n }\n\n private removePending(source: string, entry: PendingResolver<any>): void {\n const queue = this.pending.get(source);\n if (!queue) return;\n const idx = queue.indexOf(entry);\n if (idx >= 0) queue.splice(idx, 1);\n if (queue.length === 0) this.pending.delete(source);\n }\n\n private resolveNext<T>(source: string, value: T): boolean {\n const queue = this.pending.get(source);\n if (!queue || queue.length === 0) return false;\n const next = queue.shift()!;\n if (queue.length === 0) this.pending.delete(source);\n clearTimeout(next.timer);\n next.resolve(value);\n return true;\n }\n\n private rejectNext(source: string, err: Error): boolean {\n const queue = this.pending.get(source);\n if (!queue || queue.length === 0) return false;\n const next = queue.shift()!;\n if (queue.length === 0) this.pending.delete(source);\n clearTimeout(next.timer);\n next.reject(err);\n return true;\n }\n\n private handleStateless(payload: string): void {\n let parsed: any;\n try {\n parsed = JSON.parse(payload);\n } catch {\n return;\n }\n const type: unknown = parsed?.type;\n if (typeof type !== \"string\") return;\n\n // Server emits `messages:ok` acks with a `source` matching the originating\n // request type. Use that to resolve the matching pending promise.\n if (type === \"messages:ok\" && typeof parsed.source === \"string\") {\n this.resolveNext(parsed.source, parsed.meta);\n return;\n }\n if (type === \"messages:typing\") {\n // The server includes channel_doc_id + user_id; the legacy\n // ChatTypingEvent shape has `channel`, so emit it as the new doc id —\n // consumers that want the old `group:<id>` form can prefix locally.\n this.emit(\"typing\", {\n channel: parsed.channel_doc_id,\n sender_id: parsed.user_id,\n sender_name: null,\n } as ChatTypingEvent);\n return;\n }\n }\n\n private handleServerError(data: {\n source: string;\n code: string;\n message: string;\n meta?: unknown;\n }): void {\n if (typeof data.source !== \"string\" || !data.source.startsWith(\"messages:\")) return;\n if (data.source === \"messages:inbox_fetch\" || data.source === \"messages:inbox_mark_read\") {\n // Inbox traffic belongs to NotificationsClient — let it handle its own errors.\n return;\n }\n this.rejectNext(\n data.source,\n new Error(`${data.code ?? \"error\"}: ${data.message ?? \"messages request failed\"}`),\n );\n }\n}\n"],"mappings":";;;AA8BA,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;AAgF3B,IAAa,aAAb,cAAgC,aAAa;CAe3C,YAAY,UAA+B,SAA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+
* that is too large.
|
|
5
|
+
* See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code
|
|
6
|
+
*/
|
|
7
|
+
const MessageTooBig = {
|
|
8
|
+
code: 1009,
|
|
9
|
+
reason: "Message Too Big"
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* The server successfully processed the request, asks that the requester reset
|
|
13
|
+
* its document view, and is not returning any content.
|
|
14
|
+
*/
|
|
15
|
+
const ResetConnection = {
|
|
16
|
+
code: 4205,
|
|
17
|
+
reason: "Reset Connection"
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Similar to Forbidden, but specifically for use when authentication is required and has
|
|
21
|
+
* failed or has not yet been provided.
|
|
22
|
+
*/
|
|
23
|
+
const Unauthorized = {
|
|
24
|
+
code: 4401,
|
|
25
|
+
reason: "Unauthorized"
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* The request contained valid data and was understood by the server, but the server
|
|
29
|
+
* is refusing action.
|
|
30
|
+
*/
|
|
31
|
+
const Forbidden = {
|
|
32
|
+
code: 4403,
|
|
33
|
+
reason: "Forbidden"
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* The server timed out waiting for the request.
|
|
37
|
+
*/
|
|
38
|
+
const ConnectionTimeout = {
|
|
39
|
+
code: 4408,
|
|
40
|
+
reason: "Connection Timeout"
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
//#endregion
|
|
44
|
+
export { ConnectionTimeout, Forbidden, MessageTooBig, ResetConnection, Unauthorized };
|
|
45
|
+
//# sourceMappingURL=CloseEvents.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CloseEvents.js","names":[],"sources":["../../src/CloseEvents.ts"],"sourcesContent":["export interface CloseEvent {\n\tcode: number;\n\treason: string;\n}\n\n/**\n * The server is terminating the connection because a data frame was received\n * that is too large.\n * See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n */\nexport const MessageTooBig: CloseEvent = {\n\tcode: 1009,\n\treason: \"Message Too Big\",\n};\n\n/**\n * The server successfully processed the request, asks that the requester reset\n * its document view, and is not returning any content.\n */\nexport const ResetConnection: CloseEvent = {\n\tcode: 4205,\n\treason: \"Reset Connection\",\n};\n\n/**\n * Similar to Forbidden, but specifically for use when authentication is required and has\n * failed or has not yet been provided.\n */\nexport const Unauthorized: CloseEvent = {\n\tcode: 4401,\n\treason: \"Unauthorized\",\n};\n\n/**\n * The request contained valid data and was understood by the server, but the server\n * is refusing action.\n */\nexport const Forbidden: CloseEvent = {\n\tcode: 4403,\n\treason: \"Forbidden\",\n};\n\n/**\n * The server timed out waiting for the request.\n */\nexport const ConnectionTimeout: CloseEvent = {\n\tcode: 4408,\n\treason: \"Connection Timeout\",\n};\n"],"mappings":";;;;;;AAUA,MAAa,gBAA4B;CACxC,MAAM;CACN,QAAQ;CACR;;;;;AAMD,MAAa,kBAA8B;CAC1C,MAAM;CACN,QAAQ;CACR;;;;;AAMD,MAAa,eAA2B;CACvC,MAAM;CACN,QAAQ;CACR;;;;;AAMD,MAAa,YAAwB;CACpC,MAAM;CACN,QAAQ;CACR;;;;AAKD,MAAa,oBAAgC;CAC5C,MAAM;CACN,QAAQ;CACR"}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { patchEntry, toPlain } from "./DocUtils.js";
|
|
2
|
+
import { reconcileDocCover } from "./CoverReconcile.js";
|
|
3
|
+
import { buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, parseFrontmatter, populateYDocFromMarkdown, readBlocksFromFragment, yjsToMarkdown } from "./DocConverters.js";
|
|
4
|
+
import "yjs";
|
|
5
|
+
|
|
6
|
+
//#region packages/provider/src/ContentManager.ts
|
|
7
|
+
var ContentManager = class {
|
|
8
|
+
constructor(dm) {
|
|
9
|
+
this.dm = dm;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Read document content as markdown.
|
|
13
|
+
*
|
|
14
|
+
* Returns the markdown body, tree-derived label/type/meta, and immediate
|
|
15
|
+
* children. `title` mirrors `label` (the tree entry's display name) — it
|
|
16
|
+
* is *not* derived from a TipTap `documentHeader`, and the markdown body
|
|
17
|
+
* does NOT include YAML frontmatter. Callers that want frontmatter-style
|
|
18
|
+
* round-tripping should serialise `meta`/`type` themselves on top of the
|
|
19
|
+
* returned markdown.
|
|
20
|
+
*/
|
|
21
|
+
async read(docId) {
|
|
22
|
+
const fragment = (await this.dm.getChildProvider(docId)).document.getXmlFragment("default");
|
|
23
|
+
const treeMap = this.dm.getTreeMap();
|
|
24
|
+
let label = "Untitled";
|
|
25
|
+
let type;
|
|
26
|
+
let meta;
|
|
27
|
+
const childrenWithOrder = [];
|
|
28
|
+
if (treeMap) {
|
|
29
|
+
const raw = treeMap.get(docId);
|
|
30
|
+
if (raw) {
|
|
31
|
+
const entry = toPlain(raw);
|
|
32
|
+
label = entry.label || label;
|
|
33
|
+
type = entry.type;
|
|
34
|
+
meta = entry.meta;
|
|
35
|
+
}
|
|
36
|
+
treeMap.forEach((rawChild, id) => {
|
|
37
|
+
const value = toPlain(rawChild);
|
|
38
|
+
if (value && value.parentId === docId) childrenWithOrder.push({
|
|
39
|
+
id,
|
|
40
|
+
label: value.label || "Untitled",
|
|
41
|
+
type: value.type,
|
|
42
|
+
meta: value.meta,
|
|
43
|
+
order: value.order ?? 0
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
childrenWithOrder.sort((a, b) => a.order - b.order);
|
|
47
|
+
}
|
|
48
|
+
const children = childrenWithOrder.map(({ id, label, type, meta }) => ({
|
|
49
|
+
id,
|
|
50
|
+
label,
|
|
51
|
+
type,
|
|
52
|
+
meta
|
|
53
|
+
}));
|
|
54
|
+
const { markdown } = yjsToMarkdown(fragment);
|
|
55
|
+
return {
|
|
56
|
+
label,
|
|
57
|
+
type,
|
|
58
|
+
meta,
|
|
59
|
+
title: label,
|
|
60
|
+
markdown,
|
|
61
|
+
children
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Write markdown content to a document.
|
|
66
|
+
* Supports optional YAML frontmatter for title and metadata.
|
|
67
|
+
*
|
|
68
|
+
* @param mode - "replace" clears existing content first (default),
|
|
69
|
+
* "append" adds to the end.
|
|
70
|
+
*/
|
|
71
|
+
async write(docId, markdown, mode = "replace") {
|
|
72
|
+
const doc = (await this.dm.getChildProvider(docId)).document;
|
|
73
|
+
const fragment = doc.getXmlFragment("default");
|
|
74
|
+
const { title, meta, body } = parseFrontmatter(markdown);
|
|
75
|
+
if (title || Object.keys(meta).length > 0) {
|
|
76
|
+
const treeMap = this.dm.getTreeMap();
|
|
77
|
+
const rootDoc = this.dm.rootDocument;
|
|
78
|
+
if (treeMap && rootDoc) {
|
|
79
|
+
const entry = treeMap.get(docId);
|
|
80
|
+
if (entry) rootDoc.transact(() => {
|
|
81
|
+
const cur = toPlain(entry);
|
|
82
|
+
const patch = { updatedAt: Date.now() };
|
|
83
|
+
if (title) patch.label = title;
|
|
84
|
+
if (Object.keys(meta).length > 0) patch.meta = {
|
|
85
|
+
...cur.meta ?? {},
|
|
86
|
+
...meta
|
|
87
|
+
};
|
|
88
|
+
patchEntry(treeMap, docId, patch);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (mode === "replace") doc.transact(() => {
|
|
93
|
+
while (fragment.length > 0) fragment.delete(0);
|
|
94
|
+
});
|
|
95
|
+
populateYDocFromMarkdown(fragment, body || markdown, title || "Untitled");
|
|
96
|
+
const reconcileTree = this.dm.getTreeMap();
|
|
97
|
+
if (reconcileTree) reconcileDocCover(reconcileTree, docId, fragment);
|
|
98
|
+
}
|
|
99
|
+
async _appendElements(docId, els) {
|
|
100
|
+
const doc = (await this.dm.getChildProvider(docId)).document;
|
|
101
|
+
const fragment = doc.getXmlFragment("default");
|
|
102
|
+
doc.transact(() => {
|
|
103
|
+
fragment.insert(fragment.length, els);
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
async appendHeading(docId, text, opts) {
|
|
107
|
+
return this._appendElements(docId, [buildHeadingElement(text, opts?.level)]);
|
|
108
|
+
}
|
|
109
|
+
async appendParagraph(docId, text) {
|
|
110
|
+
return this._appendElements(docId, [buildParagraphElement(text)]);
|
|
111
|
+
}
|
|
112
|
+
async appendBulletList(docId, items) {
|
|
113
|
+
return this._appendElements(docId, [buildBulletListElement(items)]);
|
|
114
|
+
}
|
|
115
|
+
async appendOrderedList(docId, items) {
|
|
116
|
+
return this._appendElements(docId, [buildOrderedListElement(items)]);
|
|
117
|
+
}
|
|
118
|
+
async appendTaskList(docId, items) {
|
|
119
|
+
return this._appendElements(docId, [buildTaskListElement(items)]);
|
|
120
|
+
}
|
|
121
|
+
async appendCodeBlock(docId, code, opts) {
|
|
122
|
+
return this._appendElements(docId, [buildCodeBlockElement(code, opts?.language)]);
|
|
123
|
+
}
|
|
124
|
+
async appendBlockquote(docId, text) {
|
|
125
|
+
return this._appendElements(docId, [buildBlockquoteElement(text)]);
|
|
126
|
+
}
|
|
127
|
+
async appendHorizontalRule(docId) {
|
|
128
|
+
return this._appendElements(docId, [buildHorizontalRuleElement()]);
|
|
129
|
+
}
|
|
130
|
+
async appendMarkdown(docId, markdown) {
|
|
131
|
+
return this._appendElements(docId, buildBlocksFromMarkdown(markdown));
|
|
132
|
+
}
|
|
133
|
+
async getBlocks(docId) {
|
|
134
|
+
return readBlocksFromFragment((await this.dm.getChildProvider(docId)).document.getXmlFragment("default"));
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Get the raw Y.XmlFragment for a document (the 'default' fragment
|
|
138
|
+
* that TipTap uses for document content).
|
|
139
|
+
*/
|
|
140
|
+
async getFragment(docId) {
|
|
141
|
+
return (await this.dm.getChildProvider(docId)).document.getXmlFragment("default");
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Get the raw Y.Doc for a document (synced).
|
|
145
|
+
*/
|
|
146
|
+
async getDoc(docId) {
|
|
147
|
+
return (await this.dm.getChildProvider(docId)).document;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
//#endregion
|
|
152
|
+
export { ContentManager };
|
|
153
|
+
//# sourceMappingURL=ContentManager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ContentManager.js","names":[],"sources":["../../src/ContentManager.ts"],"sourcesContent":["/**\n * ContentManager — read/write document content via markdown ↔ Y.js conversion.\n *\n * Extracted from `mcp/tools/content.ts` and `cli/commands/content.ts`.\n */\nimport * as Y from \"yjs\";\nimport type { PageMeta } from \"./DocTypes.ts\";\nimport { toPlain, patchEntry } from \"./DocUtils.ts\";\nimport { reconcileDocCover } from \"./CoverReconcile.ts\";\nimport {\n\tyjsToMarkdown,\n\tpopulateYDocFromMarkdown,\n\tparseFrontmatter,\n\tbuildHeadingElement,\n\tbuildParagraphElement,\n\tbuildBulletListElement,\n\tbuildOrderedListElement,\n\tbuildTaskListElement,\n\tbuildCodeBlockElement,\n\tbuildBlockquoteElement,\n\tbuildHorizontalRuleElement,\n\tbuildBlocksFromMarkdown,\n\treadBlocksFromFragment,\n\ttype DocumentBlock,\n} from \"./DocConverters.ts\";\nexport type { DocumentBlock } from \"./DocConverters.ts\";\nimport type { DocumentManager } from \"./DocumentManager.ts\";\n\nexport interface DocumentContent {\n\tlabel: string;\n\ttype?: string;\n\tmeta?: PageMeta;\n\ttitle: string;\n\tmarkdown: string;\n\tchildren: Array<{\n\t\tid: string;\n\t\tlabel: string;\n\t\ttype?: string;\n\t\tmeta?: PageMeta;\n\t}>;\n}\n\nexport class ContentManager {\n\tconstructor(private dm: DocumentManager) {}\n\n\t/**\n\t * Read document content as markdown.\n\t *\n\t * Returns the markdown body, tree-derived label/type/meta, and immediate\n\t * children. `title` mirrors `label` (the tree entry's display name) — it\n\t * is *not* derived from a TipTap `documentHeader`, and the markdown body\n\t * does NOT include YAML frontmatter. Callers that want frontmatter-style\n\t * round-tripping should serialise `meta`/`type` themselves on top of the\n\t * returned markdown.\n\t */\n\tasync read(docId: string): Promise<DocumentContent> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\tconst fragment = provider.document.getXmlFragment(\"default\");\n\n\t\t// Get tree metadata + immediate children\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tlet label = \"Untitled\";\n\t\tlet type: string | undefined;\n\t\tlet meta: PageMeta | undefined;\n\t\tconst childrenWithOrder: Array<{\n\t\t\tid: string;\n\t\t\tlabel: string;\n\t\t\ttype?: string;\n\t\t\tmeta?: PageMeta;\n\t\t\torder: number;\n\t\t}> = [];\n\n\t\tif (treeMap) {\n\t\t\tconst raw = treeMap.get(docId);\n\t\t\tif (raw) {\n\t\t\t\tconst entry = toPlain(raw) as Record<string, unknown>;\n\t\t\t\tlabel = (entry.label as string) || label;\n\t\t\t\ttype = entry.type as string | undefined;\n\t\t\t\tmeta = entry.meta as PageMeta | undefined;\n\t\t\t}\n\t\t\t// Collect immediate children sorted by order\n\t\t\ttreeMap.forEach((rawChild: unknown, id: string) => {\n\t\t\t\tconst value = toPlain(rawChild) as Record<string, unknown>;\n\t\t\t\tif (value && value.parentId === docId) {\n\t\t\t\t\tchildrenWithOrder.push({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tlabel: (value.label as string) || \"Untitled\",\n\t\t\t\t\t\ttype: value.type as string | undefined,\n\t\t\t\t\t\tmeta: value.meta as PageMeta | undefined,\n\t\t\t\t\t\torder: (value.order as number) ?? 0,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t\tchildrenWithOrder.sort((a, b) => a.order - b.order);\n\t\t}\n\n\t\tconst children = childrenWithOrder.map(({ id, label, type, meta }) => ({\n\t\t\tid,\n\t\t\tlabel,\n\t\t\ttype,\n\t\t\tmeta,\n\t\t}));\n\n\t\tconst { markdown } = yjsToMarkdown(fragment);\n\t\tconst title = label;\n\n\t\treturn { label, type, meta, title, markdown, children };\n\t}\n\n\t/**\n\t * Write markdown content to a document.\n\t * Supports optional YAML frontmatter for title and metadata.\n\t *\n\t * @param mode - \"replace\" clears existing content first (default),\n\t * \"append\" adds to the end.\n\t */\n\tasync write(\n\t\tdocId: string,\n\t\tmarkdown: string,\n\t\tmode: \"replace\" | \"append\" = \"replace\",\n\t): Promise<void> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\tconst doc = provider.document;\n\t\tconst fragment = doc.getXmlFragment(\"default\");\n\n\t\t// Parse optional frontmatter\n\t\tconst { title, meta, body } = parseFrontmatter(markdown);\n\n\t\t// Update tree metadata if frontmatter provided title or meta\n\t\tif (title || Object.keys(meta).length > 0) {\n\t\t\tconst treeMap = this.dm.getTreeMap();\n\t\t\tconst rootDoc = this.dm.rootDocument;\n\t\t\tif (treeMap && rootDoc) {\n\t\t\t\tconst entry = treeMap.get(docId);\n\t\t\t\tif (entry) {\n\t\t\t\t\trootDoc.transact(() => {\n\t\t\t\t\t\tconst cur = toPlain(entry) as Record<\n\t\t\t\t\t\t\tstring,\n\t\t\t\t\t\t\tunknown\n\t\t\t\t\t\t>;\n\t\t\t\t\t\tconst patch: Record<string, unknown> = {\n\t\t\t\t\t\t\tupdatedAt: Date.now(),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif (title) patch.label = title;\n\t\t\t\t\t\tif (Object.keys(meta).length > 0) {\n\t\t\t\t\t\t\tpatch.meta = {\n\t\t\t\t\t\t\t\t...((cur.meta as Record<string, unknown>) ??\n\t\t\t\t\t\t\t\t\t{}),\n\t\t\t\t\t\t\t\t...meta,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpatchEntry(treeMap, docId, patch);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (mode === \"replace\") {\n\t\t\t// Clear existing content\n\t\t\tdoc.transact(() => {\n\t\t\t\twhile (fragment.length > 0) {\n\t\t\t\t\tfragment.delete(0);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t// Write new content\n\t\tconst contentToWrite = body || markdown;\n\t\tconst fallbackTitle = title || \"Untitled\";\n\t\tpopulateYDocFromMarkdown(fragment, contentToWrite, fallbackTitle);\n\n\t\t// Reconcile the cover against the media blocks now in the body, so a\n\t\t// write that removed (or added) the cover's image keeps the persisted\n\t\t// cover metadata honest — the editor is no longer the only path that\n\t\t// does this. Cheap no-op when the cover is already valid.\n\t\tconst reconcileTree = this.dm.getTreeMap();\n\t\tif (reconcileTree) reconcileDocCover(reconcileTree, docId, fragment);\n\t}\n\n\tprivate async _appendElements(docId: string, els: Y.XmlElement[]): Promise<void> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\tconst doc = provider.document;\n\t\tconst fragment = doc.getXmlFragment(\"default\");\n\t\tdoc.transact(() => {\n\t\t\tfragment.insert(fragment.length, els);\n\t\t});\n\t}\n\n\tasync appendHeading(docId: string, text: string, opts?: { level?: 1|2|3|4|5|6 }): Promise<void> {\n\t\treturn this._appendElements(docId, [buildHeadingElement(text, opts?.level)]);\n\t}\n\n\tasync appendParagraph(docId: string, text: string): Promise<void> {\n\t\treturn this._appendElements(docId, [buildParagraphElement(text)]);\n\t}\n\n\tasync appendBulletList(docId: string, items: string[]): Promise<void> {\n\t\treturn this._appendElements(docId, [buildBulletListElement(items)]);\n\t}\n\n\tasync appendOrderedList(docId: string, items: string[]): Promise<void> {\n\t\treturn this._appendElements(docId, [buildOrderedListElement(items)]);\n\t}\n\n\tasync appendTaskList(docId: string, items: Array<{ text: string; checked?: boolean }>): Promise<void> {\n\t\treturn this._appendElements(docId, [buildTaskListElement(items)]);\n\t}\n\n\tasync appendCodeBlock(docId: string, code: string, opts?: { language?: string }): Promise<void> {\n\t\treturn this._appendElements(docId, [buildCodeBlockElement(code, opts?.language)]);\n\t}\n\n\tasync appendBlockquote(docId: string, text: string): Promise<void> {\n\t\treturn this._appendElements(docId, [buildBlockquoteElement(text)]);\n\t}\n\n\tasync appendHorizontalRule(docId: string): Promise<void> {\n\t\treturn this._appendElements(docId, [buildHorizontalRuleElement()]);\n\t}\n\n\tasync appendMarkdown(docId: string, markdown: string): Promise<void> {\n\t\treturn this._appendElements(docId, buildBlocksFromMarkdown(markdown));\n\t}\n\n\tasync getBlocks(docId: string): Promise<DocumentBlock[]> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\treturn readBlocksFromFragment(provider.document.getXmlFragment(\"default\"));\n\t}\n\n\t/**\n\t * Get the raw Y.XmlFragment for a document (the 'default' fragment\n\t * that TipTap uses for document content).\n\t */\n\tasync getFragment(docId: string): Promise<Y.XmlFragment> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\treturn provider.document.getXmlFragment(\"default\");\n\t}\n\n\t/**\n\t * Get the raw Y.Doc for a document (synced).\n\t */\n\tasync getDoc(docId: string): Promise<Y.Doc> {\n\t\tconst provider = await this.dm.getChildProvider(docId);\n\t\treturn provider.document;\n\t}\n}\n"],"mappings":";;;;;;AA0CA,IAAa,iBAAb,MAA4B;CAC3B,YAAY,AAAQ,IAAqB;EAArB;;;;;;;;;;;;CAYpB,MAAM,KAAK,OAAyC;EAEnD,MAAM,YADW,MAAM,KAAK,GAAG,iBAAiB,MAAM,EAC5B,SAAS,eAAe,UAAU;EAG5D,MAAM,UAAU,KAAK,GAAG,YAAY;EACpC,IAAI,QAAQ;EACZ,IAAI;EACJ,IAAI;EACJ,MAAM,oBAMD,EAAE;AAEP,MAAI,SAAS;GACZ,MAAM,MAAM,QAAQ,IAAI,MAAM;AAC9B,OAAI,KAAK;IACR,MAAM,QAAQ,QAAQ,IAAI;AAC1B,YAAS,MAAM,SAAoB;AACnC,WAAO,MAAM;AACb,WAAO,MAAM;;AAGd,WAAQ,SAAS,UAAmB,OAAe;IAClD,MAAM,QAAQ,QAAQ,SAAS;AAC/B,QAAI,SAAS,MAAM,aAAa,MAC/B,mBAAkB,KAAK;KACtB;KACA,OAAQ,MAAM,SAAoB;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C;AAExD,UADiB,MAAM,KAAK,GAAG,iBAAiB,MAAM,EACtC,SAAS,eAAe,UAAU;;;;;CAMnD,MAAM,OAAO,OAA+B;AAE3C,UADiB,MAAM,KAAK,GAAG,iBAAiB,MAAM,EACtC"}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { patchEntry, toPlain } from "./DocUtils.js";
|
|
2
|
+
import * as Y from "yjs";
|
|
3
|
+
|
|
4
|
+
//#region packages/provider/src/CoverReconcile.ts
|
|
5
|
+
/**
|
|
6
|
+
* CoverReconcile — keep a document's cover-image metadata in sync with the
|
|
7
|
+
* image/video file blocks that actually live in its content.
|
|
8
|
+
*
|
|
9
|
+
* The cover (`meta.coverUploadId` / `coverDocId` / `coverMimeType` on the
|
|
10
|
+
* doc's own tree entry) is *persisted* metadata, not derived live — the
|
|
11
|
+
* kanban/gallery/table views read it without loading each card's content.
|
|
12
|
+
* Historically the only thing that reconciled it was cou-sh's TipTap editor
|
|
13
|
+
* (`reconcileCover` in DocRenderer.vue), so any write that did NOT go through
|
|
14
|
+
* that editor — MCP `write_document`, `@abraca/convert`, the CLI, another SDK
|
|
15
|
+
* — could leave an orphaned cover pointing at an image the body no longer
|
|
16
|
+
* contains. This is the shared, write-path-level reconciliation so every
|
|
17
|
+
* content write through the SDK keeps the cover honest.
|
|
18
|
+
*
|
|
19
|
+
* Semantics mirror cou-sh's editor reconciler exactly:
|
|
20
|
+
* - cover set + still references a present image/video → leave it (a
|
|
21
|
+
* user-chosen cover is preserved as long as its image is in the doc);
|
|
22
|
+
* - cover set + its image is gone, others remain → swap to the first;
|
|
23
|
+
* - cover set + no image/video remains → clear the three cover keys;
|
|
24
|
+
* - no cover + at least one image/video → adopt the first as the cover.
|
|
25
|
+
*/
|
|
26
|
+
const EXT_MIME = {
|
|
27
|
+
png: "image/png",
|
|
28
|
+
jpg: "image/jpeg",
|
|
29
|
+
jpeg: "image/jpeg",
|
|
30
|
+
gif: "image/gif",
|
|
31
|
+
webp: "image/webp",
|
|
32
|
+
avif: "image/avif",
|
|
33
|
+
svg: "image/svg+xml",
|
|
34
|
+
bmp: "image/bmp",
|
|
35
|
+
heic: "image/heic",
|
|
36
|
+
heif: "image/heif",
|
|
37
|
+
mp4: "video/mp4",
|
|
38
|
+
webm: "video/webm",
|
|
39
|
+
mov: "video/quicktime",
|
|
40
|
+
m4v: "video/x-m4v",
|
|
41
|
+
ogv: "video/ogg",
|
|
42
|
+
mkv: "video/x-matroska"
|
|
43
|
+
};
|
|
44
|
+
function attr(node, name) {
|
|
45
|
+
const v = node.getAttribute(name);
|
|
46
|
+
return typeof v === "string" && v ? v : void 0;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Resolve a file node's mime type. A `fileBlock` may carry the mime under
|
|
50
|
+
* `mimeType` (cou-sh's TipTap/y-prosemirror node attr) or `mime` (the
|
|
51
|
+
* `@abraca/convert` markdown path), and may carry neither — in which case we
|
|
52
|
+
* infer it from the filename/src extension (the convert sidecar `src` is
|
|
53
|
+
* `.abracadabra/files/<id>-<filename>`). Returns "" when it can't be
|
|
54
|
+
* classified as image/video.
|
|
55
|
+
*/
|
|
56
|
+
function resolveMime(node) {
|
|
57
|
+
const explicit = attr(node, "mimeType") ?? attr(node, "mime");
|
|
58
|
+
if (explicit) return explicit;
|
|
59
|
+
return EXT_MIME[(attr(node, "filename") ?? attr(node, "src") ?? "").split(".").pop()?.toLowerCase() ?? ""] ?? "";
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Recursively collect image/video `fileBlock` nodes from a Y.XmlFragment (or
|
|
63
|
+
* element subtree), in document order. Mirrors the TipTap
|
|
64
|
+
* `doc.descendants()` walk used by cou-sh — fileBlocks may be nested inside
|
|
65
|
+
* other block nodes, so this recurses rather than scanning only top level.
|
|
66
|
+
*/
|
|
67
|
+
function collectMediaFileBlocks(root) {
|
|
68
|
+
const out = [];
|
|
69
|
+
const visit = (node) => {
|
|
70
|
+
if (node instanceof Y.XmlElement && node.nodeName === "fileBlock") {
|
|
71
|
+
const uploadId = attr(node, "uploadId") ?? attr(node, "upload-id");
|
|
72
|
+
if (uploadId) {
|
|
73
|
+
const mimeType = resolveMime(node);
|
|
74
|
+
if (mimeType.startsWith("image/") || mimeType.startsWith("video/")) out.push({
|
|
75
|
+
uploadId,
|
|
76
|
+
docId: attr(node, "docId") ?? "",
|
|
77
|
+
mimeType
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (node instanceof Y.XmlElement || node instanceof Y.XmlFragment) for (let i = 0; i < node.length; i++) visit(node.get(i));
|
|
82
|
+
};
|
|
83
|
+
visit(root);
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Reconcile the cover metadata of `docId`'s tree entry against the media file
|
|
88
|
+
* blocks currently present in `fragment`. No-op when the entry is missing or
|
|
89
|
+
* the cover is already valid, so it is safe (and cheap) to call after every
|
|
90
|
+
* content write. The `treeMap` is the root doc-tree Y.Map; the cover lives on
|
|
91
|
+
* the doc's OWN self-entry (`treeMap.get(docId).meta`).
|
|
92
|
+
*/
|
|
93
|
+
function reconcileDocCover(treeMap, docId, fragment) {
|
|
94
|
+
const raw = treeMap.get(docId);
|
|
95
|
+
if (!raw) return;
|
|
96
|
+
const meta = toPlain(raw).meta ?? {};
|
|
97
|
+
const currentCoverId = meta.coverUploadId;
|
|
98
|
+
const media = collectMediaFileBlocks(fragment);
|
|
99
|
+
if (currentCoverId && media.some((b) => b.uploadId === currentCoverId)) return;
|
|
100
|
+
if (media.length > 0) {
|
|
101
|
+
const best = media[0];
|
|
102
|
+
if (currentCoverId === best.uploadId && meta.coverDocId === (best.docId || docId) && meta.coverMimeType === best.mimeType) return;
|
|
103
|
+
patchEntry(treeMap, docId, {
|
|
104
|
+
meta: {
|
|
105
|
+
...meta,
|
|
106
|
+
coverUploadId: best.uploadId,
|
|
107
|
+
coverDocId: best.docId || docId,
|
|
108
|
+
coverMimeType: best.mimeType
|
|
109
|
+
},
|
|
110
|
+
updatedAt: Date.now()
|
|
111
|
+
});
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (!currentCoverId && !meta.coverDocId && !meta.coverMimeType) return;
|
|
115
|
+
const { coverUploadId: _cu, coverDocId: _cd, coverMimeType: _cm, ...rest } = meta;
|
|
116
|
+
patchEntry(treeMap, docId, {
|
|
117
|
+
meta: rest,
|
|
118
|
+
updatedAt: Date.now()
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
//#endregion
|
|
123
|
+
export { collectMediaFileBlocks, reconcileDocCover };
|
|
124
|
+
//# sourceMappingURL=CoverReconcile.js.map
|