@cool-office/collaboration-client 1.2.1 → 1.2.2

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.
Files changed (76) hide show
  1. package/lib/cjs/chunk-4MGIQFAJ.js +40 -0
  2. package/lib/cjs/chunk-JHTS3PZO.js +1882 -0
  3. package/lib/cjs/facade.js +98 -0
  4. package/lib/cjs/index.js +37 -1329
  5. package/lib/cjs/locale/ar-SA.js +25 -0
  6. package/lib/cjs/locale/ca-ES.js +25 -0
  7. package/lib/cjs/locale/de-DE.js +25 -0
  8. package/lib/cjs/locale/en-US.js +25 -0
  9. package/lib/cjs/locale/es-ES.js +25 -0
  10. package/lib/cjs/locale/fa-IR.js +25 -0
  11. package/lib/cjs/locale/fr-FR.js +25 -0
  12. package/lib/cjs/locale/id-ID.js +25 -0
  13. package/lib/cjs/locale/it-IT.js +25 -0
  14. package/lib/cjs/locale/ja-JP.js +25 -0
  15. package/lib/cjs/locale/ko-KR.js +25 -0
  16. package/lib/cjs/locale/pl-PL.js +25 -0
  17. package/lib/cjs/locale/pt-BR.js +25 -0
  18. package/lib/cjs/locale/ru-RU.js +25 -0
  19. package/lib/cjs/locale/sk-SK.js +25 -0
  20. package/lib/cjs/locale/vi-VN.js +25 -0
  21. package/lib/cjs/locale/zh-CN.js +25 -0
  22. package/lib/cjs/locale/zh-HK.js +25 -0
  23. package/lib/cjs/locale/zh-TW.js +25 -0
  24. package/lib/es/chunk-4MGIQFAJ.js +16 -0
  25. package/lib/es/chunk-JHTS3PZO.js +1832 -0
  26. package/lib/es/facade.js +80 -0
  27. package/lib/es/index.js +38 -1302
  28. package/lib/es/locale/ar-SA.js +7 -0
  29. package/lib/es/locale/ca-ES.js +7 -0
  30. package/lib/es/locale/de-DE.js +7 -0
  31. package/lib/es/locale/en-US.js +7 -0
  32. package/lib/es/locale/es-ES.js +7 -0
  33. package/lib/es/locale/fa-IR.js +7 -0
  34. package/lib/es/locale/fr-FR.js +7 -0
  35. package/lib/es/locale/id-ID.js +7 -0
  36. package/lib/es/locale/it-IT.js +7 -0
  37. package/lib/es/locale/ja-JP.js +7 -0
  38. package/lib/es/locale/ko-KR.js +7 -0
  39. package/lib/es/locale/pl-PL.js +7 -0
  40. package/lib/es/locale/pt-BR.js +7 -0
  41. package/lib/es/locale/ru-RU.js +7 -0
  42. package/lib/es/locale/sk-SK.js +7 -0
  43. package/lib/es/locale/vi-VN.js +7 -0
  44. package/lib/es/locale/zh-CN.js +7 -0
  45. package/lib/es/locale/zh-HK.js +7 -0
  46. package/lib/es/locale/zh-TW.js +7 -0
  47. package/lib/types/src/assets.d.ts +41 -0
  48. package/lib/types/src/authorization.d.ts +31 -0
  49. package/lib/types/src/document-recovery.d.ts +3 -3
  50. package/lib/types/src/document-undo.d.ts +3 -1
  51. package/lib/types/src/facade/index.d.ts +46 -0
  52. package/lib/types/src/index.d.ts +14 -12
  53. package/lib/types/src/locale/ar-SA.d.ts +20 -0
  54. package/lib/types/src/locale/ca-ES.d.ts +20 -0
  55. package/lib/types/src/locale/de-DE.d.ts +20 -0
  56. package/lib/types/src/locale/en-US.d.ts +20 -0
  57. package/lib/types/src/locale/es-ES.d.ts +20 -0
  58. package/lib/types/src/locale/fa-IR.d.ts +20 -0
  59. package/lib/types/src/locale/fr-FR.d.ts +20 -0
  60. package/lib/types/src/locale/id-ID.d.ts +20 -0
  61. package/lib/types/src/locale/it-IT.d.ts +20 -0
  62. package/lib/types/src/locale/ja-JP.d.ts +20 -0
  63. package/lib/types/src/locale/ko-KR.d.ts +20 -0
  64. package/lib/types/src/locale/pl-PL.d.ts +20 -0
  65. package/lib/types/src/locale/pt-BR.d.ts +20 -0
  66. package/lib/types/src/locale/ru-RU.d.ts +20 -0
  67. package/lib/types/src/locale/sk-SK.d.ts +20 -0
  68. package/lib/types/src/locale/vi-VN.d.ts +20 -0
  69. package/lib/types/src/locale/zh-CN.d.ts +20 -0
  70. package/lib/types/src/locale/zh-HK.d.ts +20 -0
  71. package/lib/types/src/locale/zh-TW.d.ts +20 -0
  72. package/lib/types/src/revision-recovery.d.ts +12 -4
  73. package/lib/types/src/session.d.ts +7 -2
  74. package/lib/types/src/socket.d.ts +6 -6
  75. package/lib/types/src/workspace.d.ts +100 -0
  76. package/package.json +134 -2
package/lib/es/index.js CHANGED
@@ -1,14 +1,31 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __decorateClass = (decorators, target, key, kind) => {
4
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
- if (decorator = decorators[i])
7
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
- if (kind && result) __defProp(target, key, result);
9
- return result;
10
- };
11
- var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
1
+ import {
2
+ COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY,
3
+ CollaborationAttachmentIoService,
4
+ CollaborationController,
5
+ CollaborationImageIoService,
6
+ CollaborationRevisionRecovery,
7
+ CollaborationRevisionRecoveryService,
8
+ CollaborationSession,
9
+ CollaborationSessionService,
10
+ CollaborationSocketService,
11
+ CollaborationStatus,
12
+ CollaborationUIEventId,
13
+ CollaborationUIEventService,
14
+ CommentService,
15
+ DEFAULT_SNAPSHOT_SERVER_URL,
16
+ DocumentCollaborationRecovery,
17
+ DocumentCollaborationUndoService,
18
+ IAttachmentIoService,
19
+ ICollaborationSocketService,
20
+ MemberService,
21
+ SNAPSHOT_URL_KEY,
22
+ SessionStatus,
23
+ SnapshotServerOverHTTPService,
24
+ UniverCollaborationClientPlugin,
25
+ deserializeToCombResponse,
26
+ serializeCombRequest
27
+ } from "./chunk-JHTS3PZO.js";
28
+ import "./chunk-4MGIQFAJ.js";
12
29
 
13
30
  // src/changeset-submitter.ts
14
31
  import { HTTPResponseError } from "@cool-office/network";
@@ -137,1314 +154,33 @@ var ChangesetSubmitter = class {
137
154
  }
138
155
  }
139
156
  };
140
-
141
- // src/document-recovery.ts
142
- import { applyDocumentChange, DOCUMENT_EDIT, documentEdit, readDocumentChanges, replaceDocumentContents } from "@cool-office/collaboration/document";
143
- import { Disposable as Disposable3, JSON1, JSONX as JSONX2, Tools } from "@cool-office/core";
144
- import { ErrorCode as ErrorCode2 } from "@cool-office/protocol";
145
- import { BehaviorSubject as BehaviorSubject2 } from "rxjs";
146
-
147
- // src/document-object-resources.ts
148
- import { JSONX } from "@cool-office/core";
149
- var descriptors = [
150
- { prefix: "docs-code.mutation.", set: "set-config", remove: "remove-config", name: "DOC_CODE_PLUGIN", collection: "codes", key: "blockId" },
151
- { prefix: "docs-callout.mutation.", set: "set-config", remove: "remove-config", name: "DOC_CALLOUT_PLUGIN", collection: "callouts", key: "blockId" },
152
- { prefix: "docs-latex.mutation.", set: "set-formula", remove: "remove-formula", name: "DOC_LATEX_PLUGIN", collection: "formulas", key: "rangeId" }
153
- ];
154
- function isDocumentObjectMutation(id) {
155
- return descriptors.some((item) => id === item.prefix + item.set || id === item.prefix + item.remove);
156
- }
157
- function documentObjectEdit(before, id, params, resources) {
158
- const descriptor = descriptors.find((item) => id === item.prefix + item.set || id === item.prefix + item.remove);
159
- if (!descriptor) return void 0;
160
- const hook = resources?.getAllResourceHooks().find((item) => item.pluginName === descriptor.name);
161
- const key = params[descriptor.key];
162
- if (!hook || typeof key !== "string" || !key) throw new Error("Document object resource is unavailable");
163
- const entries = before.resources ?? [];
164
- const index = entries.findIndex((item) => item.name === descriptor.name);
165
- const entry = entries[index];
166
- const saved = entry ? JSON.parse(entry.data) : {};
167
- const oldItems = saved[descriptor.collection] ?? {};
168
- const items = { ...oldItems };
169
- const live = JSON.parse(hook.toJson(before.id))[descriptor.collection];
170
- if (Object.hasOwn(live, key)) Object.defineProperty(items, key, { value: live[key], enumerable: true, configurable: true });
171
- else if (Object.hasOwn(items, key)) delete items[key];
172
- else return null;
173
- const data = JSON.stringify({ ...saved, [descriptor.collection]: items });
174
- if (entry?.data === data) return null;
175
- const json = JSONX.getInstance();
176
- if (entry) return json.replaceOp(["resources", index, "data"], true, data);
177
- const resource = { name: descriptor.name, data };
178
- return before.resources ? json.insertOp(["resources", entries.length], resource) : json.insertOp(["resources"], [resource]);
179
- }
180
- function refreshDocumentObjectResources(unitID, before, after, manager) {
181
- if (!manager || before === after) return;
182
- for (const { name, collection } of descriptors) {
183
- const previous = before?.find((item) => item.name === name)?.data;
184
- const current = after?.find((item) => item.name === name)?.data;
185
- if (previous === current) continue;
186
- const hook = manager.getAllResourceHooks().find((item) => item.pluginName === name);
187
- if (hook) hook.onLoad(unitID, hook.parseJson(current ?? JSON.stringify({ [collection]: {} })));
188
- }
189
- }
190
-
191
- // src/session.ts
192
- import { Disposable as Disposable2, IConfigService as IConfigService3, Inject as Inject3 } from "@cool-office/core";
193
- import { CmdRspCode as CmdRspCode2, CombCmd as CombCmd2 } from "@cool-office/protocol";
194
- import { BehaviorSubject, Subject as Subject2, Subscription } from "rxjs";
195
-
196
- // src/snapshot-server.ts
197
- import { IConfigService, Inject } from "@cool-office/core";
198
- import { HTTPService } from "@cool-office/network";
199
- var DEFAULT_SNAPSHOT_SERVER_URL = "/universer-api/snapshot";
200
- var SNAPSHOT_URL_KEY = "SNAPSHOT_URL_KEY";
201
- var COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY = "collaboration-client.config";
202
- function asBytes(value) {
203
- if (value instanceof Uint8Array) return value;
204
- if (typeof value !== "string" || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) throw new Error("Invalid base64 snapshot data");
205
- const text = atob(value);
206
- return Uint8Array.from(text, (character) => character.charCodeAt(0));
207
- }
208
- function decodeSnapshot(snapshot) {
209
- if (!snapshot) return snapshot;
210
- const result = { ...snapshot };
211
- if (snapshot.workbook) {
212
- const sheets = Object.fromEntries(Object.entries(snapshot.workbook.sheets).map(([id, sheet]) => [id, { ...sheet, originalMeta: asBytes(sheet.originalMeta) }]));
213
- result.workbook = { ...snapshot.workbook, sheets, originalMeta: asBytes(snapshot.workbook.originalMeta) };
214
- }
215
- for (const key of ["doc", "slide", "board", "pdf"]) {
216
- const meta = snapshot[key];
217
- if (meta) result[key] = { ...meta, originalMeta: asBytes(meta.originalMeta) };
218
- }
219
- return result;
220
- }
221
- function segment(value) {
222
- if (!value) throw new Error("Unit or block ID is required");
223
- return encodeURIComponent(value);
224
- }
225
- var SnapshotServerOverHTTPService = class {
226
- constructor(_configService, _httpService) {
227
- this._configService = _configService;
228
- this._httpService = _httpService;
229
- }
230
- _prefix() {
231
- const config = this._configService.getConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY);
232
- return (config?.snapshotServerUrl ?? DEFAULT_SNAPSHOT_SERVER_URL).replace(/\/$/, "");
233
- }
234
- getSnapshotAPIPath() {
235
- return (this._configService.getConfig(SNAPSHOT_URL_KEY) ?? this._prefix()).replace(/\/$/, "");
236
- }
237
- async getUnitOnRev(_context, params) {
238
- const response = await this._httpService.get(`${this.getSnapshotAPIPath()}/${params.type}/unit/${segment(params.unitID)}/rev/${params.revision ?? 0}`);
239
- return { ...response.body, snapshot: decodeSnapshot(response.body.snapshot) };
240
- }
241
- async getSheetBlock(_context, params) {
242
- const response = await this._httpService.get(`${this._prefix()}/${params.type}/unit/${segment(params.unitID)}/block/${segment(params.blockID)}`);
243
- return { ...response.body, block: response.body.block ? { ...response.body.block, data: asBytes(response.body.block.data) } : void 0 };
244
- }
245
- async getDeserializedSheetBlock(_context, params) {
246
- return (await this._httpService.get(`${this._prefix()}/block/${params.type}/unit/${segment(params.unitID)}/block/${segment(params.blockID)}`)).body;
247
- }
248
- async fetchMissingChangesets(_context, params) {
249
- const query = new URLSearchParams({ from: String(params.from), to: String(params.to) });
250
- return (await this._httpService.get(`${this._prefix()}/${params.type}/unit/${segment(params.unitID)}/fetchmissing?${query}`)).body;
251
- }
252
- async getResourcesRequest(_context, params) {
253
- return (await this._httpService.get(`${DEFAULT_SNAPSHOT_SERVER_URL}/${params.type}/unit/${segment(params.unitID)}/resources`, { params: { resourceId: JSON.stringify(params.resourceIDs) } })).body;
254
- }
255
- saveSnapshot() {
256
- throw new Error("This method should not be called on the client side!");
257
- }
258
- updateSnapshot() {
259
- throw new Error("This method should not be called on the client side!");
260
- }
261
- saveSheetBlock() {
262
- throw new Error("This method should not be called on the client side!");
263
- }
264
- saveChangeset() {
265
- throw new Error("This method should not be called on the client side!");
266
- }
267
- copyFileMeta() {
268
- throw new Error("This method should not be called on the client side!");
269
- }
270
- getLatestCsReqIdBySid() {
271
- throw new Error("This method should not be called on the client side!");
272
- }
273
- };
274
- SnapshotServerOverHTTPService = __decorateClass([
275
- __decorateParam(0, IConfigService),
276
- __decorateParam(1, Inject(HTTPService))
277
- ], SnapshotServerOverHTTPService);
278
-
279
- // src/socket.ts
280
- import { createIdentifier, Disposable, IConfigService as IConfigService2, Inject as Inject2, Injector, ILogService } from "@cool-office/core";
281
- import { HTTPEventType, HTTPService as HTTPService2, ISocketService } from "@cool-office/network";
282
- import { CmdRspCode, CombCmd, ErrorCode } from "@cool-office/protocol";
283
- import { filter, firstValueFrom, Subject, timeout } from "rxjs";
284
- var ICollaborationSocketService = createIdentifier("univer-pro.collaboration-client-socket-service");
285
- var outboundFields = { update_cursor: "updateCursorEvent", users_leave: "leaveEvent", users_enter: "joinEvent", "liveshare.new_host": "liveShareNewHost", "liveshare.operation": "liveShareOperation", "liveshare.terminate": "liveShareTerminate", "liveshare.request_host": "liveShareRequestHost" };
286
- var inboundFields = { permission_rej: "permissionRejEvent", changeset_ack: "csAckEvent", new_changesets: "newCsEvent", changeset_rej: "csRejEvent", changeset_should_retry: "csShouldRetryEvent", update_cursor: "updateCursorEvent", users_enter: "joinEvent", users_leave: "leaveEvent", "liveshare.new_host": "liveShareNewHost", "liveshare.operation": "liveShareOperation", "liveshare.fetch_operations": "liveShareOperation", "liveshare.terminate": "liveShareNewHost", comment_update: "commentUpdateEvent", update_permission_obj: "updatePermissionObjEvent", should_close_conn: "shouldCloseConn", "uniscript.run": "uniscriptRunEvent" };
287
- var changeEvents = /* @__PURE__ */ new Set(["permission_rej", "changeset_ack", "new_changesets", "changeset_rej", "changeset_should_retry"]);
288
- function serializeCombRequest(event) {
289
- const { cmd, routeKey, data } = event;
290
- if (cmd === CombCmd.HELLO || cmd === CombCmd.HEARTBEAT) return JSON.stringify({ cmd, routeKey });
291
- if (cmd === CombCmd.JOIN) return JSON.stringify({ cmd, routeKey, joinReq: data });
292
- if (cmd === CombCmd.LEAVE) return JSON.stringify({ cmd, routeKey, leaveReq: data });
293
- if (cmd === CombCmd.INGEST && data && typeof data.eventID === "string") {
294
- const field = outboundFields[data.eventID];
295
- return JSON.stringify({ cmd, routeKey, collaMsg: { eventID: data.eventID, ...field ? { [field]: data.data } : {} } });
296
- }
297
- throw new Error("Unsupported collaboration request");
298
- }
299
- function deserializeToCombResponse(event) {
300
- if (typeof event.data !== "string") throw new Error("Collaboration response must be text");
301
- const response = JSON.parse(event.data);
302
- if (!response || typeof response !== "object" || !Number.isSafeInteger(response.cmd)) throw new Error("Invalid collaboration response");
303
- if (response.cmd === CombCmd.HELLO || response.cmd === CombCmd.HEARTBEAT) return { ...response, data: response.infoRsp };
304
- if (response.cmd === CombCmd.JOIN) return { ...response, data: response.joinRsp };
305
- if (response.cmd !== CombCmd.RECV || !response.collaMsg || typeof response.collaMsg.eventID !== "string") return response;
306
- const message = response.collaMsg, field = inboundFields[message.eventID];
307
- if (!field) return response;
308
- const value = message[field];
309
- return { ...response, data: { ...message, data: changeEvents.has(message.eventID) ? value?.cs : value } };
310
- }
311
- var CollaborationSocketService = class extends Disposable {
312
- constructor(_injector, _httpService, _configService, _logService, _snapshotServerService) {
313
- super();
314
- this._injector = _injector;
315
- this._httpService = _httpService;
316
- this._configService = _configService;
317
- this._logService = _logService;
318
- this._snapshotServerService = _snapshotServerService;
319
- }
320
- _doCreateSocket(url) {
321
- const source = this._injector.get(ISocketService).createSocket(url);
322
- if (!source) throw new Error("Could not create collaboration socket");
323
- const messages = new Subject(), errors = new Subject(), closed = new Subject(), subscriptions = [];
324
- let disposed = false;
325
- const close = () => {
326
- if (disposed) return;
327
- disposed = true;
328
- source.close();
329
- subscriptions.forEach((subscription) => subscription.unsubscribe());
330
- messages.complete();
331
- errors.complete();
332
- closed.complete();
333
- };
334
- subscriptions.push(source.close$.subscribe((event) => closed.next(event)), source.error$.subscribe((event) => errors.next(event)), source.message$.subscribe((event) => {
335
- try {
336
- messages.next(deserializeToCombResponse(event));
337
- } catch {
338
- errors.next(new Event("Invalid collaboration message"));
339
- close();
340
- }
341
- }));
342
- const socket = {
343
- memberID: "",
344
- open$: source.open$,
345
- error$: errors.asObservable(),
346
- close$: closed.asObservable(),
347
- message$: messages.asObservable(),
348
- close,
349
- send: (event, options) => {
350
- if (disposed) throw new Error("Collaboration socket is closed");
351
- if (event.cmd === CombCmd.INGEST && event.data?.eventID === "submit_changeset") return this._submitChangeset(socket, event.data.data, options?.timeout ?? 12e4);
352
- if (event.cmd === CombCmd.INGEST && event.data?.eventID === "fetch_missing") {
353
- const request = event.data.data;
354
- void this._snapshotServerService.fetchMissingChangesets({}, { unitID: request.unitID, type: request.unitType, from: request.from, to: request.to }).then((result) => {
355
- if (result.error && result.error.code !== ErrorCode.OK) throw new Error(result.error.message || "Cannot fetch missing changes");
356
- if (!disposed) messages.next({ cmd: CombCmd.RECV, code: CmdRspCode.OK, routeKey: request.unitID, routeType: "", data: { eventID: "pseudo_fetch_missing_result", data: { changesets: result.changesets } } });
357
- }).catch((error) => {
358
- this._logService.error(error);
359
- if (!disposed) {
360
- errors.next(new Event("connection error"));
361
- closed.next(new Event("connection error"));
362
- close();
363
- }
364
- });
365
- return;
366
- }
367
- source.send(serializeCombRequest(event));
368
- }
369
- };
370
- this.disposeWithMe({ dispose: close });
371
- return socket;
372
- }
373
- async _submitChangeset(socket, request, timeoutMs) {
374
- const config = this._configService.getConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY);
375
- const prefix = (config?.collabSubmitChangesetUrl ?? "/universer-api/comb").replace(/\/$/, "");
376
- const changeset = { ...request.changeset, mutations: request.changeset.mutations.map((mutation) => ({ id: mutation.id, data: JSON.stringify(mutation.params ?? {}) })) };
377
- const payload = { unitID: request.unitID, memberID: socket.memberID, type: request.unitType, changeset };
378
- const result = await firstValueFrom(this._httpService.stream("POST", `${prefix}/${request.unitType}/unit/${encodeURIComponent(request.unitID)}/new_changes`, { body: payload }).pipe(filter((item) => item.type === HTTPEventType.Response), timeout(timeoutMs)));
379
- if ("body" in result && result.body?.error?.code !== void 0 && result.body.error.code !== ErrorCode.OK) throw new Error(result.body.error.message || "Changeset submission failed");
380
- }
381
- };
382
- CollaborationSocketService = __decorateClass([
383
- __decorateParam(0, Inject2(Injector)),
384
- __decorateParam(1, Inject2(HTTPService2)),
385
- __decorateParam(2, IConfigService2),
386
- __decorateParam(3, ILogService),
387
- __decorateParam(4, Inject2(SnapshotServerOverHTTPService))
388
- ], CollaborationSocketService);
389
-
390
- // src/session.ts
391
- var SessionStatus = /* @__PURE__ */ ((SessionStatus2) => {
392
- SessionStatus2[SessionStatus2["IDLE"] = 0] = "IDLE";
393
- SessionStatus2[SessionStatus2["JOINING"] = 1] = "JOINING";
394
- SessionStatus2[SessionStatus2["OFFLINE"] = 2] = "OFFLINE";
395
- SessionStatus2[SessionStatus2["ONLINE"] = 3] = "ONLINE";
396
- return SessionStatus2;
397
- })(SessionStatus || {});
398
- var CollaborationSession = class {
399
- constructor(unitID, _service) {
400
- this.unitID = unitID;
401
- this._service = _service;
402
- this._status = new BehaviorSubject(0 /* IDLE */);
403
- this._events = new Subject2();
404
- this.sessionStatus$ = this._status.asObservable();
405
- this.event$ = this._events.asObservable();
406
- this._closed = false;
407
- this._joinedBefore = false;
408
- this._requiresResync = false;
409
- }
410
- get sessionStatus() {
411
- return this._status.value;
412
- }
413
- get requiresResync() {
414
- return this._requiresResync;
415
- }
416
- /** Call only after the consumer has reconciled the missed server revisions and pending edits. */
417
- markResynced() {
418
- if (this.sessionStatus !== 3 /* ONLINE */) throw new Error("Collaboration session is not online");
419
- this._requiresResync = false;
420
- }
421
- getMemberID() {
422
- return this._service.memberID;
423
- }
424
- async send(event, _unitID, options) {
425
- if (this._closed || this.sessionStatus !== 3 /* ONLINE */) throw new Error("Collaboration session is not online");
426
- if (_unitID !== this.unitID) throw new Error("Collaboration session unit mismatch");
427
- if (this._requiresResync && event.eventID === "submit_changeset") throw new Error("Reconcile missed changes before submitting edits");
428
- await this._service.send({ cmd: CombCmd2.INGEST, routeKey: this.unitID, data: event }, options);
429
- }
430
- close() {
431
- if (!this._closed) this._service.closeSession(this.unitID);
432
- }
433
- dispose() {
434
- this.close();
435
- }
436
- /** @internal */
437
- setStatus(status) {
438
- if (!this._closed && this._status.value !== status) this._status.next(status);
439
- }
440
- /** @internal */
441
- emit(event) {
442
- if (!this._closed) this._events.next(event);
443
- }
444
- /** @internal */
445
- joined() {
446
- if (this._joinedBefore) this._requiresResync = true;
447
- this._joinedBefore = true;
448
- this.setStatus(3 /* ONLINE */);
449
- if (this._requiresResync) this.emit({ eventID: "requires_resync" });
450
- }
451
- /** @internal */
452
- finish() {
453
- if (this._closed) return;
454
- this._closed = true;
455
- this._events.complete();
456
- this._status.complete();
457
- }
458
- };
459
- var CollaborationSessionService = class extends Disposable2 {
460
- constructor(_configService, _socketService) {
461
- super();
462
- this._configService = _configService;
463
- this._socketService = _socketService;
464
- this._sessions = /* @__PURE__ */ new Map();
465
- this._status = new BehaviorSubject(0 /* IDLE */);
466
- this._socketState = new BehaviorSubject(null);
467
- this.status$ = this._status.asObservable();
468
- this.socket$ = this._socketState.asObservable();
469
- this._socket = null;
470
- this._subscriptions = new Subscription();
471
- this._ready = false;
472
- this._connecting = false;
473
- this._online = true;
474
- this._generation = 0;
475
- this._retryCount = 0;
476
- this._retryTimer = null;
477
- this._handshakeTimer = null;
478
- this._heartbeatTimer = null;
479
- this._heartbeatTimeout = null;
480
- }
481
- get memberID() {
482
- return this._ready ? this._socket?.memberID ?? null : null;
483
- }
484
- async requireSession(unitID) {
485
- if (this._disposed) throw new Error("Collaboration session service is disposed");
486
- if (!unitID) throw new Error("Unit ID is required");
487
- let session = this._sessions.get(unitID);
488
- if (!session) {
489
- session = new CollaborationSession(unitID, this);
490
- this._sessions.set(unitID, session);
491
- if (this._ready) this._join(session);
492
- else if (this._online && !this._retryTimer && !this._socket && !this._connecting) this._scheduleReconnect();
493
- }
494
- return session;
495
- }
496
- closeSession(unitID) {
497
- const session = this._sessions.get(unitID);
498
- if (!session) return;
499
- this._sessions.delete(unitID);
500
- if (this._ready) {
501
- try {
502
- void this._socket?.send({ cmd: CombCmd2.LEAVE, routeKey: unitID, data: { roomID: unitID } });
503
- } catch {
504
- }
505
- }
506
- session.finish();
507
- if (!this._sessions.size) {
508
- this._disconnect();
509
- this._status.next(0 /* IDLE */);
510
- }
511
- }
512
- reconnect() {
513
- if (this._disposed) return;
514
- this._retryCount = 0;
515
- this._disconnect();
516
- if (this._sessions.size && this._online) this._scheduleReconnect();
517
- }
518
- /** Browser network signals are hints only; reconnection still requires a successful handshake. */
519
- setOnline(online) {
520
- if (this._disposed || this._online === online) return;
521
- this._online = online;
522
- if (!online) this._disconnect();
523
- else this.reconnect();
524
- }
525
- async send(event, options) {
526
- if (!this._ready || !this._socket) throw new Error("Collaboration connection is not ready");
527
- await this._socket.send(event, options);
528
- }
529
- dispose() {
530
- if (this._disposed) return;
531
- this._disconnect();
532
- for (const session of this._sessions.values()) session.finish();
533
- this._sessions.clear();
534
- this._status.complete();
535
- this._socketState.complete();
536
- super.dispose();
537
- }
538
- _scheduleReconnect() {
539
- if (this._disposed || !this._online || !this._sessions.size || this._retryTimer || this._connecting) return;
540
- const max = this._configService.getConfig("RETRY_CONNECTING_MAX_COUNT") ?? 3;
541
- if (this._retryCount >= max) return;
542
- const config = this._configService.getConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY);
543
- const delay = this._retryCount === 0 ? 0 : Math.min(config?.maxReconnectInterval ?? 2147483647, (config?.retryConnectingInterval ?? 2e4) * 2 ** this._retryCount);
544
- this._retryCount++;
545
- this._retryTimer = setTimeout(() => {
546
- this._retryTimer = null;
547
- void this._connect();
548
- }, delay);
549
- }
550
- async _connect() {
551
- const generation = ++this._generation;
552
- this._connecting = true;
553
- const config = this._configService.getConfig(COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY);
554
- this._status.next(1 /* JOINING */);
555
- try {
556
- const socket = await this._socketService.createSocket(config?.collabWebSocketUrl ?? "ws://127.0.0.1:8000/universer-api/comb/connect");
557
- if (generation !== this._generation || this._disposed || !this._sessions.size || !this._online) {
558
- socket?.close();
559
- return;
560
- }
561
- this._connecting = false;
562
- if (!socket) throw new Error("Unable to create collaboration socket");
563
- this._socket = socket;
564
- this._subscriptions = new Subscription();
565
- this._subscriptions.add(socket.open$.subscribe(() => {
566
- try {
567
- void socket.send({ cmd: CombCmd2.HELLO, routeKey: "" });
568
- } catch {
569
- this._failed(generation);
570
- }
571
- }));
572
- this._subscriptions.add(socket.error$.subscribe(() => this._failed(generation)));
573
- this._subscriptions.add(socket.close$.subscribe(() => this._failed(generation)));
574
- this._subscriptions.add(socket.message$.subscribe((event) => this._onMessage(generation, event)));
575
- this._handshakeTimer = setTimeout(() => this._failed(generation), 2e4);
576
- } catch {
577
- this._failed(generation);
578
- }
579
- }
580
- _onMessage(generation, event) {
581
- if (generation !== this._generation || !this._socket) return;
582
- if (!this._ready && event.cmd === CombCmd2.HELLO) {
583
- if ((event.code ?? CmdRspCode2.OK) !== CmdRspCode2.OK || typeof event.data?.memberID !== "string" || !event.data.memberID) {
584
- this._failed(generation);
585
- return;
586
- }
587
- this._clear("_handshakeTimer");
588
- this._socket.memberID = event.data.memberID;
589
- this._ready = true;
590
- this._retryCount = 0;
591
- this._socketState.next(this._socket);
592
- this._status.next(3 /* ONLINE */);
593
- for (const session2 of this._sessions.values()) this._join(session2);
594
- this._scheduleHeartbeat(generation);
595
- return;
596
- }
597
- if (!this._ready) return;
598
- if (event.cmd === CombCmd2.HEARTBEAT) {
599
- this._clear("_heartbeatTimeout");
600
- this._scheduleHeartbeat(generation);
601
- return;
602
- }
603
- const session = this._sessions.get(event.routeKey);
604
- if (event.cmd === CombCmd2.JOIN && session) {
605
- if ((event.code ?? CmdRspCode2.OK) === CmdRspCode2.OK && event.data?.roomInfos?.[event.routeKey]) session.joined();
606
- else session.setStatus(2 /* OFFLINE */);
607
- } else if (event.cmd === CombCmd2.RECV && session && event.data && typeof event.data.eventID === "string") {
608
- session.emit(event.data);
609
- }
610
- }
611
- _join(session) {
612
- session.setStatus(1 /* JOINING */);
613
- try {
614
- void this._socket?.send({ cmd: CombCmd2.JOIN, routeKey: session.unitID, data: { rooms: [{ roomID: session.unitID }] } });
615
- } catch {
616
- this._failed(this._generation);
617
- }
618
- }
619
- _scheduleHeartbeat(generation) {
620
- this._clear("_heartbeatTimer");
621
- this._heartbeatTimer = setTimeout(() => {
622
- if (!this._ready || generation !== this._generation) return;
623
- try {
624
- void this._socket?.send({ cmd: CombCmd2.HEARTBEAT, routeKey: "" });
625
- } catch {
626
- this._failed(generation);
627
- return;
628
- }
629
- this._heartbeatTimeout = setTimeout(() => this._failed(generation), this._configService.getConfig("HEARTBEAT_TIMEOUT") ?? 2e4);
630
- }, this._configService.getConfig("HEARTBEAT_INTERVAL") ?? 3e4);
631
- }
632
- _failed(generation) {
633
- if (generation !== this._generation || this._disposed) return;
634
- this._disconnect();
635
- this._scheduleReconnect();
636
- }
637
- _disconnect() {
638
- this._generation++;
639
- this._ready = false;
640
- this._connecting = false;
641
- this._subscriptions.unsubscribe();
642
- this._subscriptions = new Subscription();
643
- this._clear("_retryTimer");
644
- this._clear("_handshakeTimer");
645
- this._clear("_heartbeatTimer");
646
- this._clear("_heartbeatTimeout");
647
- const socket = this._socket;
648
- this._socket = null;
649
- socket?.close();
650
- this._socketState.next(null);
651
- if (this._sessions.size) {
652
- this._status.next(2 /* OFFLINE */);
653
- for (const session of this._sessions.values()) session.setStatus(2 /* OFFLINE */);
654
- }
655
- }
656
- _clear(name) {
657
- const timer = this[name];
658
- if (timer !== null) clearTimeout(timer);
659
- this[name] = null;
660
- }
661
- };
662
- CollaborationSessionService = __decorateClass([
663
- __decorateParam(0, IConfigService3),
664
- __decorateParam(1, Inject3(ICollaborationSocketService))
665
- ], CollaborationSessionService);
666
-
667
- // src/document-recovery.ts
668
- var DocumentCollaborationRecovery = class extends Disposable3 {
669
- constructor(options, _commands, _snapshots, _sessions, _model, _connection, _remove) {
670
- super();
671
- this.options = options;
672
- this._commands = _commands;
673
- this._snapshots = _snapshots;
674
- this._sessions = _sessions;
675
- this._model = _model;
676
- this._connection = _connection;
677
- this._remove = _remove;
678
- this._state = new BehaviorSubject2("connecting");
679
- this.status$ = this._state.asObservable();
680
- this._queue = [];
681
- this._sid = crypto.randomUUID();
682
- this._next = 1;
683
- this._reason = null;
684
- this._conflictRemote = null;
685
- this._closed = false;
686
- this._ready = false;
687
- this._pulling = false;
688
- this._accessPending = false;
689
- this._generation = 0;
690
- this._sending = 0;
691
- this._buffer = [];
692
- this._storageError = false;
693
- if (!options.userID || _model.getRev() !== options.revision) throw new Error("Authenticated document and loaded revision are required");
694
- this._confirmed = structuredClone(_model.getSnapshot());
695
- this._grant = _connection.initialAccess;
696
- }
697
- get status() {
698
- return this._state.value;
699
- }
700
- get revision() {
701
- return this._confirmed.rev;
702
- }
703
- get hasWritePending() {
704
- return !!this._queue.length || !!this._reason;
705
- }
706
- get conflictReason() {
707
- return this._reason;
708
- }
709
- get canPublishConflict() {
710
- return this._grant === "write" && !this._storageError;
711
- }
712
- getUnrecoverableDraft() {
713
- if (!this._storageError) return;
714
- try {
715
- const key = this._connection.recoveryKey;
716
- return key && sessionStorage.getItem(key) || JSON.stringify(this.getLocalDocument(), null, 2);
717
- } catch {
718
- return JSON.stringify(this.getLocalDocument(), null, 2);
719
- }
720
- }
721
- getPendingEdits() {
722
- return { edits: this._queue.map((item) => ({ id: DOCUMENT_EDIT, params: { unitId: this.options.unitID, actions: structuredClone(item.op) } })), incomplete: !!this._reason, awaitingConfirmation: !!this._queue[0]?.sent };
723
- }
724
- getLocalDocument() {
725
- return structuredClone(this._model.getSnapshot());
726
- }
727
- getConfirmedDocument() {
728
- return structuredClone(this._confirmed);
729
- }
730
- getProposedDocument() {
731
- const local = this.getLocalDocument();
732
- if (!this._conflictBase) return local;
733
- try {
734
- const draft2 = this._queue.reduce((op, item) => JSONX2.compose(op, item.op), null);
735
- if (!replaceDocumentContents(applyDocumentChange(this._conflictBase, draft2), local) && !replaceDocumentContents(applyDocumentChange(this._conflictBase, this._conflictRemote), this._confirmed)) {
736
- return structuredClone(applyDocumentChange(this._confirmed, JSON1.type.transformNoConflict(draft2, this._conflictRemote, "left")));
737
- }
738
- } catch {
739
- }
740
- const proposed = this.getConfirmedDocument();
741
- const base = this._conflictBase;
742
- const draft = local;
743
- for (const field of /* @__PURE__ */ new Set([...Object.keys(base), ...Object.keys(draft)])) {
744
- if (field === "id" || field === "rev" || field === "disabled" || Tools.diffValue(base[field], draft[field])) continue;
745
- if (draft[field] === void 0) delete proposed[field];
746
- else proposed[field] = draft[field];
747
- }
748
- return proposed;
749
- }
750
- markUnitUnavailable() {
751
- if (this.hasWritePending) this._conflict("The document was closed");
752
- }
753
- async start() {
754
- this._restore();
755
- this._connection.setAccess(this._reason ? "read" : this._grant);
756
- this.disposeWithMe(this._commands.onCommandExecuted((command) => {
757
- if (this._batch?.trigger === command.id) this._finishObjectCommand();
758
- }));
759
- this.disposeWithMe(this._commands.onMutationExecutedForCollab((command, execution) => {
760
- const params = command.params;
761
- if (execution?.fromCollab || execution?.onlyLocal || execution?.fromChangeset || params?.unitId !== this.options.unitID) return;
762
- try {
763
- if (this._reason || this._grant !== "write" || execution?.syncOnly) throw new Error("The pending document needs review");
764
- const settings = isDocumentObjectMutation(command.id);
765
- const trigger = params.trigger ?? command.id;
766
- const compound = settings || /^(docs-(code|callout|latex)\.command\.|univer\.command\.(undo|redo)$)/.test(trigger);
767
- if (!compound) {
768
- this._enqueue(documentEdit(this.options.unitID, command.id, params));
769
- return;
770
- }
771
- if (this._batch && this._batch.trigger !== trigger) this._finishObjectCommand();
772
- if (!this._batch) {
773
- const batch = this._batch = { trigger, body: null, settings: [] };
774
- queueMicrotask(() => {
775
- if (this._batch === batch) this._finishObjectCommand();
776
- });
777
- }
778
- if (settings) this._batch.settings.push({ id: command.id, params });
779
- else this._batch.body = JSONX2.compose(this._batch.body, documentEdit(this.options.unitID, command.id, params));
780
- } catch (error) {
781
- this._conflict(String(error));
782
- }
783
- }));
784
- const session = await this._sessions.requireSession(this.options.unitID);
785
- if (this._closed) return;
786
- this._session = session;
787
- const events = session.event$.subscribe((event) => {
788
- const data = event.data;
789
- if (event.eventID === "changeset_ack" || event.eventID === "new_changesets") {
790
- this._buffer.push(...Array.isArray(data) ? data : [data]);
791
- if (this._ready && !this._pulling) this._drain();
792
- } else if (data?.sid === this._sid && data.reqId === this._queue[0]?.reqId) {
793
- if (event.eventID === "changeset_should_retry") {
794
- this._clearSend();
795
- void this._pull();
796
- }
797
- if (event.eventID === "changeset_rej" || event.eventID === "permission_rej") {
798
- this._clearSend();
799
- this._conflict(event.eventID === "permission_rej" ? "Document permission changed" : "The document edits require review");
800
- void this._refreshAccess();
801
- }
802
- }
803
- });
804
- const status = session.sessionStatus$.subscribe((state) => {
805
- this._generation++;
806
- this._pulling = false;
807
- this._ready = false;
808
- this._clearSend();
809
- if (state === 3 /* ONLINE */) void this._pull();
810
- else this._update();
811
- });
812
- const interval = setInterval(() => {
813
- void this._refreshAccess();
814
- }, 2e3);
815
- this.disposeWithMe(() => {
816
- events.unsubscribe();
817
- status.unsubscribe();
818
- clearInterval(interval);
819
- });
820
- }
821
- /** The caller shows the two snapshots and supplies the revision the user actually reviewed. */
822
- async resolveDocumentConflict(choice, reviewedRevision) {
823
- if (!this._reason || this._session?.sessionStatus !== 3 /* ONLINE */ || this._pulling || this._storageError && choice === "local") return false;
824
- await this._refreshAccess();
825
- await this._pull();
826
- if (!this._ready || reviewedRevision !== this.revision || this._closed || this._grant === "none" || choice === "local" && this._grant !== "write") return false;
827
- const local = this.getLocalDocument();
828
- try {
829
- const target = choice === "remote" ? this._confirmed : this.getProposedDocument();
830
- const op = replaceDocumentContents(this._confirmed, target);
831
- applyDocumentChange(this._confirmed, op);
832
- this._apply(replaceDocumentContents(local, target));
833
- this._model.setRev(this.revision);
834
- this._queue = choice === "local" && op ? [{ reqId: this._next++, op, reviewed: true }] : [];
835
- if (choice === "remote") this._storageError = false;
836
- this._reason = null;
837
- this._conflictBase = void 0;
838
- this._conflictRemote = null;
839
- this._save();
840
- this._connection.setAccess(this._grant);
841
- this._update();
842
- this._submit();
843
- return true;
844
- } catch (error) {
845
- this._conflict(String(error));
846
- return false;
847
- }
848
- }
849
- async _refreshAccess() {
850
- if (this._closed || this._accessPending) return;
851
- this._accessPending = true;
852
- try {
853
- const grant = await this._connection.access();
854
- if (this._closed || grant === this._grant) return;
855
- const previous = this._grant;
856
- this._grant = grant;
857
- if (grant !== "write" && this._queue.length) this._conflict("Document permission changed");
858
- this._connection.setAccess(this._reason && grant === "write" ? "read" : grant);
859
- if (previous === "none" && grant !== "none") this._sessions.reconnect();
860
- this._update(true);
861
- } catch {
862
- } finally {
863
- this._accessPending = false;
864
- }
865
- }
866
- async _pull() {
867
- if (this._closed || this._pulling || this._session?.sessionStatus !== 3 /* ONLINE */ || this._grant === "none") return;
868
- const generation = this._generation;
869
- this._pulling = true;
870
- this._update();
871
- try {
872
- const result = await this._snapshots.fetchMissingChangesets({}, { unitID: this.options.unitID, type: 1, from: this.revision, to: 0 });
873
- if (this._closed || generation !== this._generation) return;
874
- if (result.error && result.error.code !== ErrorCode2.OK || !Array.isArray(result.changesets)) throw new Error("Unable to read document revisions");
875
- this._buffer.push(...result.changesets);
876
- this._ready = true;
877
- if (this._session.requiresResync) this._session.markResynced();
878
- this._pulling = false;
879
- this._drain();
880
- } catch {
881
- if (!this._closed && generation === this._generation) {
882
- this._pulling = false;
883
- this._ready = false;
884
- this._sessions.reconnect();
885
- }
886
- }
887
- }
888
- _drain() {
889
- this._buffer.sort((a, b) => a.revision - b.revision);
890
- while (this._buffer.length) {
891
- const change = this._buffer[0];
892
- if (change.revision <= this.revision) {
893
- this._buffer.shift();
894
- continue;
895
- }
896
- if (change.revision > this.revision + 1) {
897
- void this._pull();
898
- return;
899
- }
900
- if (change.baseRev !== this.revision || change.type !== 1 || change.unitID !== this.options.unitID) {
901
- this._conflict("Invalid document revision");
902
- return;
903
- }
904
- this._buffer.shift();
905
- const before = this._confirmed;
906
- let op = null;
907
- const paused = !!this._reason;
908
- try {
909
- op = readDocumentChanges(change.unitID, change.mutations);
910
- const next = applyDocumentChange(before, op);
911
- this._confirmed = { ...next, rev: change.revision };
912
- if (paused) this._conflictRemote = JSONX2.compose(this._conflictRemote, op);
913
- const first = this._queue[0];
914
- if (change.userID === this.options.userID && change.sid === this._sid && change.reqId === first?.reqId && first) {
915
- this._clearSend();
916
- if (!this._reason && !Tools.diffValue(first.op, op) && !Tools.diffValue(applyDocumentChange(before, first.op), next)) {
917
- throw new Error("The confirmed edit differs from the pending edit");
918
- }
919
- this._queue.shift();
920
- } else if (!this._reason) {
921
- let remote = op;
922
- const queue = this._queue.map((item) => {
923
- if (item.reviewed) throw new Error("The reviewed version changed");
924
- const local = JSONX2.transform(item.op, remote, "right") ?? null;
925
- remote = JSONX2.transform(remote, item.op, "left") ?? null;
926
- return { ...item, op: local };
927
- });
928
- this._apply(remote);
929
- this._queue = queue;
930
- }
931
- this._model.setRev(change.revision);
932
- this._save();
933
- } catch (error) {
934
- if (!paused && this._confirmed !== before) this._conflictRemote = op;
935
- this._conflict(String(error), before);
936
- }
937
- }
938
- this._update();
939
- this._submit();
940
- }
941
- _apply(op, localResource = false) {
942
- if (!op) return;
943
- if (!localResource) this._connection.beforeRemote?.(op, this._model.getSnapshot());
944
- const previousResources = this._model.getSnapshot().resources;
945
- const title = this._model.getSnapshot().title;
946
- const result = this._commands.syncExecuteCommand(DOCUMENT_EDIT, {
947
- unitId: this.options.unitID,
948
- actions: structuredClone(op),
949
- noHistory: true,
950
- noNeedSetTextRange: true
951
- }, { fromCollab: true, fromChangeset: true });
952
- if (!result || !result.actions?.length) throw new Error("The editor could not apply this document revision");
953
- if (!localResource) refreshDocumentObjectResources(this.options.unitID, previousResources, this._model.getSnapshot().resources, this._connection.resources);
954
- const updated = this._model.getSnapshot().title;
955
- if (typeof updated === "string" && updated !== title) this._model.setName(updated);
956
- }
957
- _finishObjectCommand() {
958
- const batch = this._batch;
959
- this._batch = void 0;
960
- if (!batch || this._closed) return;
961
- try {
962
- let op = batch.body;
963
- for (const item of batch.settings) {
964
- const edit = documentObjectEdit(this._model.getSnapshot(), item.id, item.params, this._connection.resources);
965
- if (!edit) continue;
966
- const resource = documentEdit(this.options.unitID, DOCUMENT_EDIT, { unitId: this.options.unitID, actions: edit });
967
- this._apply(resource, true);
968
- op = JSONX2.compose(op, resource);
969
- }
970
- this._enqueue(op);
971
- } catch (error) {
972
- this._conflict(String(error));
973
- }
974
- }
975
- _enqueue(op) {
976
- if (!op) return;
977
- this._queue.push({ reqId: this._next++, op: structuredClone(op) });
978
- this._save();
979
- this._update();
980
- this._submit();
981
- }
982
- _submit() {
983
- const first = this._queue[0];
984
- const memberID = this._session?.getMemberID();
985
- if (this._closed || !first || !memberID || !this._ready || this._pulling || this._sending || this._reason || this._grant !== "write") return;
986
- first.sent ??= { base: this.revision, op: structuredClone(first.op) };
987
- try {
988
- this._save();
989
- } catch (error) {
990
- this._conflict(String(error));
991
- return;
992
- }
993
- const request = first.reqId;
994
- this._sending = request;
995
- const changeset = { unitID: this.options.unitID, type: 1, baseRev: first.sent.base, revision: 0, userID: this.options.userID, memberID, sid: this._sid, reqId: request, mutations: [{ id: DOCUMENT_EDIT, params: { unitId: this.options.unitID, actions: first.sent.op, ...first.reviewed ? { requireCurrentRevision: true } : {} } }] };
996
- const generation = this._generation;
997
- const reconnect = () => {
998
- if (!this._closed && this._sending === request && generation === this._generation) this._sessions.reconnect();
999
- };
1000
- this._ackTimer = setTimeout(reconnect, 2e4);
1001
- void this._session.send({ eventID: "submit_changeset", data: { unitID: this.options.unitID, unitType: 1, changeset } }, this.options.unitID).catch(reconnect);
1002
- }
1003
- _clearSend() {
1004
- clearTimeout(this._ackTimer);
1005
- this._sending = 0;
1006
- }
1007
- _update(accessChanged = false) {
1008
- const next = this._grant === "none" ? "denied" : this._reason ? "conflict" : this._session?.sessionStatus === 2 /* OFFLINE */ ? "offline" : !this._ready ? "connecting" : this._pulling ? "recovering" : this._queue.length ? "pending" : this._grant === "read" ? "readonly" : "synced";
1009
- if (accessChanged || next !== this.status) this._state.next(next);
1010
- }
1011
- _conflict(reason, base = this._confirmed) {
1012
- this._reason ??= reason;
1013
- this._conflictBase ??= base;
1014
- if (!this._closed) this._connection.setAccess(this._grant === "none" ? "none" : "read");
1015
- try {
1016
- this._save();
1017
- } catch {
1018
- }
1019
- this._update();
1020
- }
1021
- _save() {
1022
- const key = this._connection.recoveryKey;
1023
- if (!key) return;
1024
- if (this._storageError) throw new Error("Cannot save the pending document");
1025
- try {
1026
- if (!this.hasWritePending) {
1027
- sessionStorage.removeItem(key);
1028
- return;
1029
- }
1030
- const checkpoint = { version: 1, sid: this._sid, next: this._next, confirmed: this._confirmed, queue: this._queue, conflict: this._reason, ...this._reason ? { local: this.getLocalDocument(), conflictBase: this._conflictBase, conflictRemote: this._conflictRemote } : {} };
1031
- sessionStorage.setItem(key, JSON.stringify(checkpoint));
1032
- } catch {
1033
- this._storageError = true;
1034
- throw new Error("Cannot save the pending document");
1035
- }
1036
- }
1037
- _restore() {
1038
- const key = this._connection.recoveryKey;
1039
- if (!key) return;
1040
- try {
1041
- const raw = sessionStorage.getItem(key);
1042
- if (!raw) return;
1043
- const checkpoint = JSON.parse(raw);
1044
- if (checkpoint.version !== 1 || checkpoint.confirmed.id !== this.options.unitID || !Number.isSafeInteger(checkpoint.confirmed.rev) || !Number.isSafeInteger(checkpoint.next) || !checkpoint.sid || !Array.isArray(checkpoint.queue)) {
1045
- throw new Error("Invalid pending document");
1046
- }
1047
- const local = checkpoint.local ?? checkpoint.queue.reduce((doc, item) => applyDocumentChange(doc, item.op), checkpoint.confirmed);
1048
- this._apply(replaceDocumentContents(this.getLocalDocument(), local));
1049
- this._model.setRev(checkpoint.confirmed.rev);
1050
- this._confirmed = checkpoint.confirmed;
1051
- this._queue = checkpoint.queue;
1052
- this._sid = checkpoint.sid;
1053
- this._next = checkpoint.next;
1054
- this._reason = checkpoint.conflict;
1055
- this._conflictBase = checkpoint.conflictBase;
1056
- this._conflictRemote = checkpoint.conflictRemote ?? null;
1057
- } catch {
1058
- this._storageError = true;
1059
- this._reason = "The saved edits could not be loaded";
1060
- }
1061
- }
1062
- dispose() {
1063
- if (this._closed) return;
1064
- this._closed = true;
1065
- this._generation++;
1066
- this._clearSend();
1067
- this._state.complete();
1068
- this._remove();
1069
- super.dispose();
1070
- }
1071
- };
1072
-
1073
- // src/document-undo.ts
1074
- import { applyDocumentChange as applyDocumentChange2, DOCUMENT_EDIT as DOCUMENT_EDIT2, documentEdit as documentEdit2 } from "@cool-office/collaboration/document";
1075
- import { JSONX as JSONX3, LocalUndoRedoService } from "@cool-office/core";
1076
- var DocumentCollaborationUndoService = class extends LocalUndoRedoService {
1077
- transformDocumentHistory(unitID, remote, before) {
1078
- const after = applyDocumentChange2(before, remote);
1079
- this._transformStack(unitID, this._getUndoStack(unitID), "undoMutations", remote, after);
1080
- this._transformStack(unitID, this._getRedoStack(unitID), "redoMutations", remote, after);
1081
- this._updateStatus();
1082
- }
1083
- _transformStack(unitID, stack, forward, remote, document) {
1084
- const backward = forward === "undoMutations" ? "redoMutations" : "undoMutations";
1085
- const compose = (items) => items.reduce((op, item) => JSONX3.compose(op, documentEdit2(unitID, item.id, item.params)), null);
1086
- const mutation = (op, template) => [{ id: DOCUMENT_EDIT2, params: { unitId: unitID, actions: op, trigger: template?.params?.trigger, noNeedSetTextRange: true } }];
1087
- if (!stack) return;
1088
- for (let i = stack.length - 1; i >= 0 && remote; i--) {
1089
- const item = stack[i];
1090
- try {
1091
- const action = compose(item[forward]);
1092
- const next = JSONX3.transform(action, remote, "right") ?? null;
1093
- remote = JSONX3.transform(remote, action, "left") ?? null;
1094
- if (!next) {
1095
- stack.splice(i, 1);
1096
- continue;
1097
- }
1098
- const inverse = JSONX3.invertWithDoc(structuredClone(next), structuredClone(document));
1099
- document = applyDocumentChange2(document, next);
1100
- item[forward] = mutation(next, item[forward][0]);
1101
- item[backward] = mutation(inverse, item[backward][0]);
1102
- } catch {
1103
- stack.splice(0, i + 1);
1104
- break;
1105
- }
1106
- }
1107
- }
1108
- };
1109
-
1110
- // src/revision-recovery.ts
1111
- import { acceptsSheetRevision } from "@cool-office/collaboration/sheet-objects";
1112
- import { Disposable as Disposable4, ICommandService, Inject as Inject4, IUniverInstanceService } from "@cool-office/core";
1113
- import { ErrorCode as ErrorCode3 } from "@cool-office/protocol";
1114
- import { BehaviorSubject as BehaviorSubject3, Subscription as Subscription2 } from "rxjs";
1115
- var CollaborationRevisionRecovery = class extends Disposable4 {
1116
- constructor(options, _commands, _snapshots, _sessions, _instances, _onDispose) {
1117
- super();
1118
- this.options = options;
1119
- this._commands = _commands;
1120
- this._snapshots = _snapshots;
1121
- this._sessions = _sessions;
1122
- this._instances = _instances;
1123
- this._onDispose = _onDispose;
1124
- this._status = new BehaviorSubject3("connecting");
1125
- this.status$ = this._status.asObservable();
1126
- this._subscriptions = new Subscription2();
1127
- this._pending = [];
1128
- this._session = null;
1129
- this._generation = 0;
1130
- this._localDirty = false;
1131
- this._closed = false;
1132
- this._reason = null;
1133
- this._localEdits = [];
1134
- this._inflight = null;
1135
- this._ackTimer = null;
1136
- this._nextRequest = 1;
1137
- this._sid = globalThis.crypto?.randomUUID?.() ?? "";
1138
- this._untrackedLocalEdit = false;
1139
- if (!options.unitID || !Number.isSafeInteger(options.revision) || options.revision < 0) throw new Error("A unit and its loaded revision are required");
1140
- const unit = this._instances.getUnit(options.unitID);
1141
- if (!unit || unit.type !== options.unitType || unit.getRev() !== options.revision) throw new Error("Loaded unit does not match the supplied type and revision");
1142
- this._revision = options.revision;
1143
- this.disposeWithMe(this._commands.onMutationExecutedForCollab((command, execution) => this._localMutation(command, execution)));
1144
- }
1145
- get revision() {
1146
- return this._revision;
1147
- }
1148
- get status() {
1149
- return this._status.value;
1150
- }
1151
- get conflictReason() {
1152
- return this._reason;
1153
- }
1154
- get hasWritePending() {
1155
- return this._localEdits.length > 0 || this._untrackedLocalEdit;
1156
- }
1157
- /** Retains in-memory pending edits when the editor closes the bound unit. */
1158
- markUnitUnavailable() {
1159
- this._conflict("The bound unit was closed");
1160
- }
1161
- /** Memory-only copy for the caller to preserve or inspect before disposing the unit. */
1162
- getPendingEdits() {
1163
- return { edits: structuredClone(this._localEdits), incomplete: this._untrackedLocalEdit, awaitingConfirmation: this._inflight !== null };
1164
- }
1165
- async start() {
1166
- if (this._closed || this._session) throw new Error("Recovery has already started or was disposed");
1167
- const session = await this._sessions.requireSession(this.options.unitID);
1168
- if (this._closed) return;
1169
- this._session = session;
1170
- this._subscriptions.add(session.event$.subscribe((event) => {
1171
- if (event.eventID === "changeset_ack") {
1172
- this._ack(event.data);
1173
- return;
1174
- }
1175
- if (event.eventID === "changeset_should_retry" || event.eventID === "changeset_rej" || event.eventID === "permission_rej") {
1176
- this._conflict("Server rejected or could not safely apply the local edit");
1177
- return;
1178
- }
1179
- if (event.eventID === "new_changesets" && event.data) {
1180
- if (this.hasWritePending) {
1181
- this._conflict("Remote changes arrived while local edits were pending");
1182
- return;
1183
- }
1184
- const incoming = Array.isArray(event.data) ? event.data : [event.data];
1185
- this._pending.push(...incoming);
1186
- if (this.status === "synced") {
1187
- const revision = this._pending[0]?.revision;
1188
- if (Number.isSafeInteger(revision) && revision > this._revision + 1) void this._recover();
1189
- else this._drain();
1190
- }
1191
- }
1192
- }));
1193
- this._subscriptions.add(session.sessionStatus$.subscribe((status) => {
1194
- if (this.status === "conflict") return;
1195
- if (status === 3 /* ONLINE */) {
1196
- void this._recover();
1197
- } else if (status === 2 /* OFFLINE */) {
1198
- this._generation++;
1199
- if (this.hasWritePending) this._conflict("Connection lost before local edits were acknowledged");
1200
- else this._status.next("offline");
1201
- }
1202
- }));
1203
- }
1204
- dispose() {
1205
- if (this._closed) return;
1206
- this._closed = true;
1207
- this._generation++;
1208
- this._clearAckTimer();
1209
- this._subscriptions.unsubscribe();
1210
- this._status.complete();
1211
- this._onDispose?.();
1212
- super.dispose();
1213
- }
1214
- _localMutation(command, execution) {
1215
- if (this._closed || execution?.fromCollab || execution?.fromChangeset || execution?.onlyLocal) return;
1216
- const params = command.params;
1217
- const id = params?.unitId ?? params?.unitID;
1218
- if (typeof id === "string" && id !== this.options.unitID) return;
1219
- if (!params || typeof command.id !== "string") {
1220
- this._untrackedLocalEdit = true;
1221
- this._localDirty = true;
1222
- this._conflict("Local mutation could not be recorded");
1223
- return;
1224
- }
1225
- let edit;
1226
- try {
1227
- edit = { id: command.id, params: JSON.parse(JSON.stringify(command.params)) };
1228
- } catch {
1229
- this._untrackedLocalEdit = true;
1230
- this._localDirty = true;
1231
- this._conflict("Local mutation could not be recorded");
1232
- return;
1233
- }
1234
- this._localEdits.push(edit);
1235
- this._localDirty = true;
1236
- if (this.status !== "synced" && this.status !== "pending" || execution?.syncOnly || id !== this.options.unitID || !this._acceptsLocal(edit) || !this.options.userID || !this._sid) {
1237
- this._conflict("Local edit cannot be synchronized safely");
1238
- return;
1239
- }
1240
- this._submitNext();
1241
- }
1242
- _withinSheet(id, params) {
1243
- const sheet = typeof params.subUnitId === "string" && this._instances.getUnit(this.options.unitID, 2)?.getSheetBySheetId(params.subUnitId);
1244
- return !!sheet && acceptsSheetRevision(id, params, this.options.unitID, sheet.getSheetId(), { rowCount: sheet.getRowCount(), columnCount: sheet.getColumnCount() });
1245
- }
1246
- _acceptsLocal(edit) {
1247
- if (this.options.sheetObjects && edit.id !== "sheet.mutation.set-range-values") return this._withinSheet(edit.id, edit.params);
1248
- if (this.options.unitType !== 2 || edit.id !== "sheet.mutation.set-range-values") return false;
1249
- const params = edit.params;
1250
- if (Object.keys(params).some((key) => !["unitId", "subUnitId", "cellValue", "sourceFormulaData", "isOverrideStyle", "trigger", "__splitChunk__"].includes(key))) return false;
1251
- if (params.unitId !== this.options.unitID || typeof params.subUnitId !== "string" || !params.cellValue || typeof params.cellValue !== "object" || params.sourceFormulaData || params.isOverrideStyle) return false;
1252
- const workbook = this._instances.getUnit(this.options.unitID);
1253
- const sheet = workbook?.getSheetBySheetId?.(params.subUnitId);
1254
- if (!sheet) return false;
1255
- let count = 0;
1256
- for (const [rowText, columns] of Object.entries(params.cellValue)) {
1257
- const row = Number(rowText);
1258
- if (!Number.isSafeInteger(row) || row < 0 || !columns || typeof columns !== "object" || Array.isArray(columns)) return false;
1259
- for (const [columnText, value] of Object.entries(columns)) {
1260
- const column = Number(columnText);
1261
- if (!Number.isSafeInteger(column) || column < 0 || !value || typeof value !== "object" || Array.isArray(value)) return false;
1262
- const cell = value;
1263
- if (Object.keys(cell).some((key) => key !== "v" && key !== "t") || !("v" in cell) || "t" in cell && cell.t !== null && ![1, 2, 3, 4].includes(cell.t)) return false;
1264
- const v = cell.v;
1265
- if (!(v === null || typeof v === "string" || typeof v === "number" && Number.isFinite(v))) return false;
1266
- const actual = sheet.getCellRaw(row, column);
1267
- if ((actual?.v ?? null) !== v || "t" in cell && (actual?.t ?? null) !== cell.t || actual?.f || actual?.si || actual?.p) return false;
1268
- if (++count > 1e4) return false;
1269
- }
1270
- }
1271
- return count > 0;
1272
- }
1273
- _submitNext() {
1274
- const edit = this._localEdits[0];
1275
- const session = this._session;
1276
- const memberID = session?.getMemberID();
1277
- if (!edit || this._inflight || this.status !== "synced" && this.status !== "pending") return;
1278
- if (!session || !memberID || !this.options.userID) {
1279
- this._conflict("Collaboration identity is unavailable");
1280
- return;
1281
- }
1282
- const inflight = { edit, sid: this._sid, reqId: this._nextRequest++, baseRev: this._revision, memberID };
1283
- this._inflight = inflight;
1284
- this._status.next("pending");
1285
- const changeset = { unitID: this.options.unitID, type: this.options.unitType, baseRev: inflight.baseRev, revision: 0, userID: this.options.userID, memberID, sid: inflight.sid, reqId: inflight.reqId, mutations: [edit] };
1286
- this._ackTimer = setTimeout(() => {
1287
- if (this._inflight === inflight) this._conflict("Server acknowledgement timed out");
1288
- }, 2e4);
1289
- void session.send({ eventID: "submit_changeset", data: { unitID: this.options.unitID, unitType: this.options.unitType, changeset } }, this.options.unitID).catch(() => {
1290
- if (this._inflight === inflight) this._conflict("Local edit submission failed or its result is unknown");
1291
- });
1292
- }
1293
- _ack(change) {
1294
- const inflight = this._inflight;
1295
- if (!inflight || this.status === "conflict") return;
1296
- if (!change || change.unitID !== this.options.unitID || change.type !== this.options.unitType || change.sid !== inflight.sid || change.reqId !== inflight.reqId || change.memberID !== inflight.memberID || change.baseRev !== inflight.baseRev || change.revision !== inflight.baseRev + 1) {
1297
- this._conflict("Unexpected acknowledgement");
1298
- return;
1299
- }
1300
- const unit = this._instances.getUnit(this.options.unitID);
1301
- if (!unit || unit.getRev() !== this._revision) {
1302
- this._conflict("Local revision changed before acknowledgement");
1303
- return;
1304
- }
1305
- try {
1306
- unit.setRev(change.revision);
1307
- } catch {
1308
- this._conflict("Could not update the local revision");
1309
- return;
1310
- }
1311
- this._clearAckTimer();
1312
- this._revision = change.revision;
1313
- this._localEdits.shift();
1314
- this._inflight = null;
1315
- this._localDirty = this._localEdits.length > 0;
1316
- if (!this._localDirty) this._status.next("synced");
1317
- this._submitNext();
1318
- }
1319
- _clearAckTimer() {
1320
- if (this._ackTimer !== null) clearTimeout(this._ackTimer);
1321
- this._ackTimer = null;
1322
- }
1323
- async _recover() {
1324
- if (this._closed || this._localDirty || this.status === "conflict") return;
1325
- const generation = ++this._generation;
1326
- this._status.next("recovering");
1327
- try {
1328
- const result = await this._snapshots.fetchMissingChangesets({}, { unitID: this.options.unitID, type: this.options.unitType, from: this._revision, to: 0 });
1329
- if (generation !== this._generation || this._closed || this._isConflict()) return;
1330
- if (result.error && result.error.code !== ErrorCode3.OK) throw new Error(result.error.message || "Could not fetch missing revisions");
1331
- if (!Array.isArray(result.changesets)) throw new Error("Missing changeset list");
1332
- this._pending.push(...result.changesets);
1333
- if (!this._drain()) return;
1334
- if (this._session?.sessionStatus !== 3 /* ONLINE */) return;
1335
- if (this._session.requiresResync) this._session.markResynced();
1336
- this._status.next("synced");
1337
- } catch (error) {
1338
- if (generation === this._generation && !this._closed) this._conflict(error instanceof Error ? error.message : "Failed to recover revisions");
1339
- }
1340
- }
1341
- _drain() {
1342
- this._pending.sort((a, b) => a.revision - b.revision);
1343
- while (this._pending.length && this.status !== "conflict") {
1344
- const change = this._pending.shift();
1345
- if (!Number.isSafeInteger(change.revision)) {
1346
- this._conflict("Invalid revision");
1347
- return false;
1348
- }
1349
- if (change.revision <= this._revision) continue;
1350
- if (change.unitID !== this.options.unitID || change.type !== this.options.unitType || change.baseRev !== this._revision || change.revision !== this._revision + 1) {
1351
- this._conflict("Missing or inconsistent revision");
1352
- return false;
1353
- }
1354
- if (!Array.isArray(change.mutations) || change.mutations.length !== 1) {
1355
- this._conflict("Unsupported multi-mutation revision");
1356
- return false;
1357
- }
1358
- const mutation = change.mutations[0];
1359
- try {
1360
- const unit = this._instances.getUnit(this.options.unitID);
1361
- if (!unit || unit.getRev() !== this._revision) throw new Error("Local revision changed before remote mutation");
1362
- if (!mutation || typeof mutation.id !== "string" || typeof mutation.data !== "string") throw new Error("Invalid mutation");
1363
- const params = JSON.parse(mutation.data);
1364
- if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("Invalid mutation parameters");
1365
- const target = params.unitId ?? params.unitID;
1366
- if (target !== this.options.unitID) throw new Error("Mutation target is ambiguous");
1367
- if (this.options.sheetObjects && !this._withinSheet(mutation.id, params)) throw new Error("Unsupported workbook object revision");
1368
- if (!this._commands.syncExecuteCommand(mutation.id, params, { fromCollab: true, fromChangeset: true })) throw new Error("Mutation could not be applied");
1369
- if (this._localDirty || this._isConflict()) return false;
1370
- if (unit.getRev() !== this._revision) throw new Error("Local revision changed during remote mutation");
1371
- unit.setRev(change.revision);
1372
- this._revision = change.revision;
1373
- } catch (error) {
1374
- this._conflict(error instanceof Error ? error.message : "Failed to apply mutation");
1375
- return false;
1376
- }
1377
- }
1378
- return this.status !== "conflict";
1379
- }
1380
- _conflict(reason) {
1381
- if (this._closed || this.status === "conflict") return;
1382
- this._generation++;
1383
- this._clearAckTimer();
1384
- this._reason = reason;
1385
- this._status.next("conflict");
1386
- }
1387
- _isConflict() {
1388
- return this._status.value === "conflict";
1389
- }
1390
- };
1391
- var CollaborationRevisionRecoveryService = class {
1392
- constructor(_commands, _snapshots, _sessions, _instances) {
1393
- this._commands = _commands;
1394
- this._snapshots = _snapshots;
1395
- this._sessions = _sessions;
1396
- this._instances = _instances;
1397
- this._active = new BehaviorSubject3(/* @__PURE__ */ new Map());
1398
- this.active$ = this._active.asObservable();
1399
- }
1400
- get(unitID) {
1401
- return this._active.value.get(unitID);
1402
- }
1403
- async attach(options) {
1404
- if (this._active.value.has(options.unitID)) throw new Error("A collaboration recovery is already attached to this unit");
1405
- const remove = () => {
1406
- if (this._active.value.get(options.unitID) !== recovery) return;
1407
- const next2 = new Map(this._active.value);
1408
- next2.delete(options.unitID);
1409
- this._active.next(next2);
1410
- };
1411
- const model = this._instances.getUnit(options.unitID, 1);
1412
- const recovery = options.unitType === 1 && options.document && model ? new DocumentCollaborationRecovery(options, this._commands, this._snapshots, this._sessions, model, options.document, remove) : new CollaborationRevisionRecovery(options, this._commands, this._snapshots, this._sessions, this._instances, remove);
1413
- const next = new Map(this._active.value);
1414
- next.set(options.unitID, recovery);
1415
- this._active.next(next);
1416
- try {
1417
- await recovery.start();
1418
- return recovery;
1419
- } catch (error) {
1420
- recovery.dispose();
1421
- throw error;
1422
- }
1423
- }
1424
- };
1425
- CollaborationRevisionRecoveryService = __decorateClass([
1426
- __decorateParam(0, Inject4(ICommandService)),
1427
- __decorateParam(1, Inject4(SnapshotServerOverHTTPService)),
1428
- __decorateParam(2, Inject4(CollaborationSessionService)),
1429
- __decorateParam(3, IUniverInstanceService)
1430
- ], CollaborationRevisionRecoveryService);
1431
157
  export {
1432
158
  COLLABORATION_CLIENT_PLUGIN_CONFIG_KEY,
1433
159
  ChangesetSubmitter,
160
+ CollaborationAttachmentIoService,
161
+ CollaborationController,
162
+ CollaborationImageIoService,
1434
163
  CollaborationRevisionRecovery,
1435
164
  CollaborationRevisionRecoveryService,
1436
165
  CollaborationSession,
1437
166
  CollaborationSessionService,
1438
167
  CollaborationSocketService,
168
+ CollaborationStatus,
169
+ CollaborationUIEventId,
170
+ CollaborationUIEventService,
171
+ CommentService,
1439
172
  DEFAULT_ACK_TIMEOUT,
1440
173
  DEFAULT_SNAPSHOT_SERVER_URL,
1441
174
  DocumentCollaborationRecovery,
1442
175
  DocumentCollaborationUndoService,
176
+ IAttachmentIoService,
1443
177
  ICollaborationSocketService,
1444
178
  MAX_ACK_TIMEOUT,
179
+ MemberService,
1445
180
  SNAPSHOT_URL_KEY,
1446
181
  SessionStatus,
1447
182
  SnapshotServerOverHTTPService,
183
+ UniverCollaborationClientPlugin,
1448
184
  deserializeToCombResponse,
1449
185
  serializeCombRequest
1450
186
  };