@apollo-office/rpc 1.0.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.
@@ -0,0 +1,701 @@
1
+ import { CommandType, Disposable, ICommandService, IConfigService, ILogService, IUniverInstanceService, Inject, Injector, Plugin, RxDisposable, UniverInstanceType, createIdentifier, merge, toDisposable } from "@apollo-office/core";
2
+ import { filter, take, takeUntil } from "rxjs/operators";
3
+ import { BehaviorSubject, Observable, firstValueFrom, isObservable, of, shareReplay } from "rxjs";
4
+
5
+ //#region src/config/config.ts
6
+ /**
7
+ * Copyright 2023-present DreamNum Co., Ltd.
8
+ *
9
+ * Licensed under the Apache License, Version 2.0 (the "License");
10
+ * you may not use this file except in compliance with the License.
11
+ * You may obtain a copy of the License at
12
+ *
13
+ * http://www.apache.org/licenses/LICENSE-2.0
14
+ *
15
+ * Unless required by applicable law or agreed to in writing, software
16
+ * distributed under the License is distributed on an "AS IS" BASIS,
17
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ * See the License for the specific language governing permissions and
19
+ * limitations under the License.
20
+ */
21
+ const PLUGIN_CONFIG_KEY_MAIN_THREAD = "rpc.main-thread.config";
22
+ const configSymbolMainThread = Symbol(PLUGIN_CONFIG_KEY_MAIN_THREAD);
23
+ const defaultPluginMainThreadConfig = {};
24
+ const PLUGIN_CONFIG_KEY_WORKER_THREAD = "rpc.worker-thread.config";
25
+ const configSymbolWorkerThread = Symbol(PLUGIN_CONFIG_KEY_WORKER_THREAD);
26
+ const defaultPluginWorkerThreadConfig = {};
27
+
28
+ //#endregion
29
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/decorateParam.js
30
+ function __decorateParam(paramIndex, decorator) {
31
+ return function(target, key) {
32
+ decorator(target, key, paramIndex);
33
+ };
34
+ }
35
+
36
+ //#endregion
37
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/decorate.js
38
+ function __decorate(decorators, target, key, desc) {
39
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
40
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
41
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
42
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
43
+ }
44
+
45
+ //#endregion
46
+ //#region src/services/remote-instance/remote-instance.service.ts
47
+ const RemoteSyncServiceName = "rpc.remote-sync.service";
48
+ /**
49
+ * This service is provided by the primary Univer.
50
+ *
51
+ * Replica Univer could call this service to update mutations back to the primary Univer.
52
+ */
53
+ const IRemoteSyncService = createIdentifier(RemoteSyncServiceName);
54
+ let RemoteSyncPrimaryService = class RemoteSyncPrimaryService {
55
+ constructor(_commandService) {
56
+ this._commandService = _commandService;
57
+ }
58
+ async syncMutation(params, options) {
59
+ const { fromCollab, ...restOptions } = options || {};
60
+ return this._commandService.syncExecuteCommand(params.mutationInfo.id, params.mutationInfo.params, {
61
+ ...restOptions,
62
+ onlyLocal: true,
63
+ fromSync: true
64
+ });
65
+ }
66
+ };
67
+ RemoteSyncPrimaryService = __decorate([__decorateParam(0, ICommandService)], RemoteSyncPrimaryService);
68
+ const RemoteInstanceServiceName = "univer.remote-instance-service";
69
+ /**
70
+ * This service is provided by the replica Univer.
71
+ *
72
+ * Primary univer could call this service to init and dispose univer business instances
73
+ * and sync mutations to replica univer.
74
+ */
75
+ const IRemoteInstanceService = createIdentifier(RemoteInstanceServiceName);
76
+ let WebWorkerRemoteInstanceService = class WebWorkerRemoteInstanceService {
77
+ constructor(_univerInstanceService, _commandService, _logService) {
78
+ this._univerInstanceService = _univerInstanceService;
79
+ this._commandService = _commandService;
80
+ this._logService = _logService;
81
+ }
82
+ whenReady() {
83
+ return Promise.resolve(true);
84
+ }
85
+ async syncMutation(params, options) {
86
+ return this._applyMutation(params.mutationInfo, options);
87
+ }
88
+ async createInstance(params) {
89
+ this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${params.unitID}`);
90
+ const { type, snapshot } = params;
91
+ try {
92
+ switch (type) {
93
+ case UniverInstanceType.UNIVER_SHEET:
94
+ this._univerInstanceService.createUnit(UniverInstanceType.UNIVER_SHEET, snapshot);
95
+ return true;
96
+ default: throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`);
97
+ }
98
+ } catch (err) {
99
+ if (err instanceof Error) throw err;
100
+ else throw new TypeError(`${err}`);
101
+ }
102
+ }
103
+ async disposeInstance(params) {
104
+ this._logService.debug(`[WebWorkerRemoteInstanceService]: Disposing instance with id ${params.unitID}`);
105
+ return this._univerInstanceService.disposeUnit(params.unitID);
106
+ }
107
+ _applyMutation(mutationInfo, options) {
108
+ const { id, params: mutationParams } = mutationInfo;
109
+ const { fromCollab, ...restOptions } = options || {};
110
+ return this._commandService.syncExecuteCommand(id, mutationParams, {
111
+ ...restOptions,
112
+ onlyLocal: true,
113
+ fromSync: true
114
+ });
115
+ }
116
+ };
117
+ WebWorkerRemoteInstanceService = __decorate([
118
+ __decorateParam(0, IUniverInstanceService),
119
+ __decorateParam(1, ICommandService),
120
+ __decorateParam(2, ILogService)
121
+ ], WebWorkerRemoteInstanceService);
122
+
123
+ //#endregion
124
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/typeof.js
125
+ function _typeof(o) {
126
+ "@babel/helpers - typeof";
127
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
128
+ return typeof o;
129
+ } : function(o) {
130
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
131
+ }, _typeof(o);
132
+ }
133
+
134
+ //#endregion
135
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/toPrimitive.js
136
+ function toPrimitive(t, r) {
137
+ if ("object" != _typeof(t) || !t) return t;
138
+ var e = t[Symbol.toPrimitive];
139
+ if (void 0 !== e) {
140
+ var i = e.call(t, r || "default");
141
+ if ("object" != _typeof(i)) return i;
142
+ throw new TypeError("@@toPrimitive must return a primitive value.");
143
+ }
144
+ return ("string" === r ? String : Number)(t);
145
+ }
146
+
147
+ //#endregion
148
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/toPropertyKey.js
149
+ function toPropertyKey(t) {
150
+ var i = toPrimitive(t, "string");
151
+ return "symbol" == _typeof(i) ? i : i + "";
152
+ }
153
+
154
+ //#endregion
155
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/defineProperty.js
156
+ function _defineProperty(e, r, t) {
157
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
158
+ value: t,
159
+ enumerable: !0,
160
+ configurable: !0,
161
+ writable: !0
162
+ }) : e[r] = t, e;
163
+ }
164
+
165
+ //#endregion
166
+ //#region src/services/rpc/rpc.service.ts
167
+ /**
168
+ * Wrapper a service or a controller into a channel so it could be invoked by
169
+ * a remote client. When the protocol is called, it would forward to the
170
+ * underlying service or controller.
171
+ *
172
+ * @param module the wrapper service or controller
173
+ * @returns the channel instance
174
+ */
175
+ function fromModule(module) {
176
+ const handler = module;
177
+ return new class {
178
+ call(method, args) {
179
+ const target = handler[method];
180
+ if (typeof target === "function") {
181
+ let res = args ? target.apply(handler, args) : target.call(handler);
182
+ if (!(res instanceof Promise)) res = Promise.resolve(res);
183
+ return res;
184
+ }
185
+ throw new Error(`[RPC]: method not found for ${method}!`);
186
+ }
187
+ subscribe(eventMethod, args) {
188
+ const target = handler[eventMethod];
189
+ if (typeof target === "function") {
190
+ const res = args ? target.apply(handler, args) : target.call(handler);
191
+ if (!isObservable(res)) return of(res);
192
+ return res;
193
+ }
194
+ throw new Error(`[RPC]: observable method not found for ${eventMethod}!`);
195
+ }
196
+ }();
197
+ }
198
+ /**
199
+ * Wrap a channel into a service or a controller so it could be invoked by
200
+ * the upper layer modules. When the service or controller is called, it would
201
+ * request the remote server by calling the channel.
202
+ *
203
+ * @param channel
204
+ * @returns A proxy object that forwards calls/subscriptions to the remote channel.
205
+ */
206
+ function toModule(channel) {
207
+ return new Proxy({}, { get(_, propKey) {
208
+ if (propKey === "dispose") return;
209
+ return function(...args) {
210
+ if (propertyIsEventSource(propKey)) return channel.subscribe(propKey, args);
211
+ return channel.call(propKey, args);
212
+ };
213
+ } });
214
+ }
215
+ function propertyIsEventSource(name) {
216
+ return name.endsWith("$");
217
+ }
218
+ /**
219
+ * This method provides implementation for `IChannel` and is responsible for
220
+ * transforming a local calling to a RPC calling.
221
+ */
222
+ var ChannelClient = class extends RxDisposable {
223
+ constructor(_protocol) {
224
+ super();
225
+ this._protocol = _protocol;
226
+ _defineProperty(this, "_initialized", new BehaviorSubject(false));
227
+ _defineProperty(this, "_lastRequestCounter", 0);
228
+ _defineProperty(this, "_pendingRequests", /* @__PURE__ */ new Map());
229
+ this._protocol.send({ type: 50 });
230
+ this._protocol.onMessage.pipe(takeUntil(this.dispose$)).subscribe((message) => this._onMessage(message));
231
+ }
232
+ dispose() {
233
+ this._pendingRequests.clear();
234
+ }
235
+ getChannel(channelName) {
236
+ return {
237
+ call: (method, args) => {
238
+ if (this._disposed) return Promise.reject(/* @__PURE__ */ new Error("[ChannelClient]: client is disposed!"));
239
+ return this._remoteCall(channelName, method, args);
240
+ },
241
+ subscribe: (eventMethod, args) => {
242
+ if (this._disposed) throw new Error("[ChannelClient]: client is disposed!");
243
+ return this._remoteSubscribe(channelName, eventMethod, args);
244
+ }
245
+ };
246
+ }
247
+ _whenReady() {
248
+ return firstValueFrom(this._initialized.pipe(filter((v) => v), take(1)));
249
+ }
250
+ _remoteCall(channelName, method, args) {
251
+ if (this._initialized.getValue()) return this._doRemoteCall(channelName, method, args);
252
+ return this._whenReady().then(() => this._doRemoteCall(channelName, method, args));
253
+ }
254
+ _doRemoteCall(channelName, method, args) {
255
+ const sequence = ++this._lastRequestCounter;
256
+ const request = {
257
+ seq: sequence,
258
+ type: 100,
259
+ channelName,
260
+ method,
261
+ args
262
+ };
263
+ const pendingRequests = this._pendingRequests;
264
+ return new Promise((resolve, reject) => {
265
+ this._pendingRequests.set(sequence, { handle(response) {
266
+ switch (response.type) {
267
+ case 201:
268
+ pendingRequests.delete(sequence);
269
+ resolve(response.data);
270
+ break;
271
+ case 202:
272
+ pendingRequests.delete(sequence);
273
+ reject(response.data);
274
+ break;
275
+ default: throw new Error("[ChannelClient]: unknown response type!");
276
+ }
277
+ } });
278
+ this._sendRequest(request);
279
+ });
280
+ }
281
+ _remoteSubscribe(channelName, method, args) {
282
+ return new Observable((subscriber) => {
283
+ let sequence = -1;
284
+ const doSubscribe = () => {
285
+ sequence = ++this._lastRequestCounter;
286
+ const request = {
287
+ seq: sequence,
288
+ type: 101,
289
+ channelName,
290
+ method,
291
+ args
292
+ };
293
+ this._pendingRequests.set(sequence, { handle(response) {
294
+ switch (response.type) {
295
+ case 300:
296
+ subscriber.next(response.data);
297
+ break;
298
+ case 301:
299
+ subscriber.error(response.data);
300
+ break;
301
+ case 302:
302
+ subscriber.complete();
303
+ break;
304
+ default: throw new Error("[ChannelClient]: unknown response type!");
305
+ }
306
+ } });
307
+ this._sendRequest(request);
308
+ };
309
+ if (this._initialized.getValue()) doSubscribe();
310
+ else this._whenReady().then(doSubscribe);
311
+ return () => {
312
+ if (sequence === -1) return;
313
+ const cancelSubscriptionRequest = {
314
+ type: 102,
315
+ seq: sequence,
316
+ channelName,
317
+ method
318
+ };
319
+ this._sendRequest(cancelSubscriptionRequest);
320
+ };
321
+ });
322
+ }
323
+ _sendRequest(request) {
324
+ this._protocol.send(request);
325
+ }
326
+ _onMessage(response) {
327
+ const { type: responseType, seq } = response;
328
+ switch (responseType) {
329
+ case 0:
330
+ this._initialized.next(true);
331
+ break;
332
+ case 201:
333
+ case 202:
334
+ case 300:
335
+ case 302:
336
+ case 301: {
337
+ var _pendingRequests$get;
338
+ const { _pendingRequests } = this;
339
+ (_pendingRequests$get = _pendingRequests.get(seq)) === null || _pendingRequests$get === void 0 || _pendingRequests$get.handle(response);
340
+ responseType !== 300 && _pendingRequests.delete(seq);
341
+ break;
342
+ }
343
+ }
344
+ }
345
+ };
346
+ var ChannelServer = class extends RxDisposable {
347
+ constructor(_protocol) {
348
+ super();
349
+ this._protocol = _protocol;
350
+ _defineProperty(this, "_channels", /* @__PURE__ */ new Map());
351
+ _defineProperty(this, "_subscriptions", /* @__PURE__ */ new Map());
352
+ this._protocol.onMessage.pipe(takeUntil(this.dispose$)).subscribe((message) => this._onRequest(message));
353
+ this._sendInitialize();
354
+ }
355
+ dispose() {
356
+ super.dispose();
357
+ this._subscriptions.clear();
358
+ this._channels.clear();
359
+ }
360
+ registerChannel(channelName, channel) {
361
+ this._channels.set(channelName, channel);
362
+ }
363
+ _onRequest(request) {
364
+ switch (request.type) {
365
+ case 50:
366
+ this._sendInitialize();
367
+ break;
368
+ case 100:
369
+ this._onMethodCall(request);
370
+ break;
371
+ case 101:
372
+ this._onSubscribe(request);
373
+ break;
374
+ case 102:
375
+ this._onUnsubscribe(request);
376
+ break;
377
+ default: break;
378
+ }
379
+ }
380
+ _sendInitialize() {
381
+ this._sendResponse({
382
+ seq: -1,
383
+ type: 0
384
+ });
385
+ }
386
+ _onMethodCall(request) {
387
+ const { channelName, method, args } = request;
388
+ const channel = this._channels.get(channelName);
389
+ let promise;
390
+ try {
391
+ if (!channel) throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);
392
+ promise = args ? channel.call(method, args) : channel.call(method);
393
+ } catch (err) {
394
+ promise = Promise.reject(err instanceof Error ? err : new Error(String(err)));
395
+ }
396
+ promise.then((data) => {
397
+ this._sendResponse({
398
+ seq: request.seq,
399
+ type: 201,
400
+ data
401
+ });
402
+ }).catch((err) => {
403
+ if (err instanceof Error) this._sendResponse({
404
+ seq: request.seq,
405
+ type: 202,
406
+ data: err.message
407
+ });
408
+ else this._sendResponse({
409
+ seq: request.seq,
410
+ type: 202,
411
+ data: String(err)
412
+ });
413
+ });
414
+ }
415
+ _onSubscribe(request) {
416
+ const { channelName, seq } = request;
417
+ const channel = this._channels.get(channelName);
418
+ try {
419
+ if (!channel) throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);
420
+ const subscription = channel.subscribe(request.method, request.args).subscribe({
421
+ next: (data) => {
422
+ this._sendResponse({
423
+ seq,
424
+ type: 300,
425
+ data
426
+ });
427
+ },
428
+ error: (err) => {
429
+ this._sendResponse({
430
+ seq,
431
+ type: 301,
432
+ data: err.message
433
+ });
434
+ this._sendResponse({
435
+ seq,
436
+ type: 302
437
+ });
438
+ },
439
+ complete: () => {
440
+ this._sendResponse({
441
+ seq,
442
+ type: 302
443
+ });
444
+ }
445
+ });
446
+ this._subscriptions.set(request.seq, subscription);
447
+ } catch (err) {
448
+ if (err instanceof Error) this._sendResponse({
449
+ seq: request.seq,
450
+ type: 301,
451
+ data: err.message
452
+ });
453
+ else this._sendResponse({
454
+ seq: request.seq,
455
+ type: 301,
456
+ data: String(err)
457
+ });
458
+ }
459
+ }
460
+ _onUnsubscribe(request) {
461
+ const subscription = this._subscriptions.get(request.seq);
462
+ if (subscription) {
463
+ subscription.unsubscribe();
464
+ this._subscriptions.delete(request.seq);
465
+ }
466
+ }
467
+ _sendResponse(response) {
468
+ this._protocol.send(response);
469
+ }
470
+ };
471
+
472
+ //#endregion
473
+ //#region src/services/rpc/channel.service.ts
474
+ const IRPCChannelService = createIdentifier("IRPCChannelService");
475
+ /**
476
+ * This service is responsible for managing the RPC channels.
477
+ */
478
+ var ChannelService = class {
479
+ constructor(_messageProtocol) {
480
+ _defineProperty(this, "_client", void 0);
481
+ _defineProperty(this, "_server", void 0);
482
+ this._client = new ChannelClient(_messageProtocol);
483
+ this._server = new ChannelServer(_messageProtocol);
484
+ }
485
+ dispose() {
486
+ this._client.dispose();
487
+ this._server.dispose();
488
+ }
489
+ requestChannel(name) {
490
+ return this._client.getChannel(name);
491
+ }
492
+ registerChannel(name, channel) {
493
+ this._server.registerChannel(name, channel);
494
+ }
495
+ };
496
+
497
+ //#endregion
498
+ //#region src/controllers/data-sync/data-sync-primary.controller.ts
499
+ let DataSyncPrimaryController = class DataSyncPrimaryController extends RxDisposable {
500
+ constructor(_injector, _commandService, _univerInstanceService, _rpcChannelService, _remoteSyncService) {
501
+ super();
502
+ this._injector = _injector;
503
+ this._commandService = _commandService;
504
+ this._univerInstanceService = _univerInstanceService;
505
+ this._rpcChannelService = _rpcChannelService;
506
+ this._remoteSyncService = _remoteSyncService;
507
+ _defineProperty(this, "_remoteInstanceService", void 0);
508
+ _defineProperty(this, "_syncingUnits", /* @__PURE__ */ new Set());
509
+ _defineProperty(this, "_syncingMutations", /* @__PURE__ */ new Set());
510
+ this._initRPCChannels();
511
+ this._init();
512
+ }
513
+ registerSyncingMutations(mutation) {
514
+ this._syncingMutations.add(mutation.id);
515
+ }
516
+ /**
517
+ * Only spreadsheets would be synced to the web worker in normal situations. If you would like to
518
+ * sync other types of documents, you should manually call this method with that document's id.
519
+ */
520
+ syncUnit(unitId) {
521
+ this._syncingUnits.add(unitId);
522
+ return toDisposable(() => this._syncingUnits.delete(unitId));
523
+ }
524
+ _initRPCChannels() {
525
+ this._rpcChannelService.registerChannel(RemoteSyncServiceName, fromModule(this._remoteSyncService));
526
+ this._injector.add([IRemoteInstanceService, { useFactory: () => toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)) }]);
527
+ this._remoteInstanceService = this._injector.get(IRemoteInstanceService);
528
+ }
529
+ _init() {
530
+ this._univerInstanceService.getTypeOfUnitAdded$(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((event) => {
531
+ const { unit: sheet } = event;
532
+ this._syncingUnits.add(sheet.getUnitId());
533
+ this._remoteInstanceService.createInstance({
534
+ unitID: sheet.getUnitId(),
535
+ type: UniverInstanceType.UNIVER_SHEET,
536
+ snapshot: sheet.getSnapshot()
537
+ });
538
+ });
539
+ this._univerInstanceService.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((workbook) => {
540
+ this._syncingUnits.delete(workbook.getUnitId());
541
+ this._remoteInstanceService.disposeInstance({ unitID: workbook.getUnitId() });
542
+ });
543
+ this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo, options) => {
544
+ const { type, params, id } = commandInfo;
545
+ const unitId = (params === null || params === void 0 ? void 0 : params.unitId) || "";
546
+ if (type === CommandType.MUTATION && (!unitId || this._syncingUnits.has(unitId)) && !(options === null || options === void 0 ? void 0 : options.fromSync) && this._syncingMutations.has(id)) this._remoteInstanceService.syncMutation({ mutationInfo: commandInfo }, options);
547
+ }));
548
+ }
549
+ };
550
+ DataSyncPrimaryController = __decorate([
551
+ __decorateParam(0, Inject(Injector)),
552
+ __decorateParam(1, ICommandService),
553
+ __decorateParam(2, IUniverInstanceService),
554
+ __decorateParam(3, IRPCChannelService),
555
+ __decorateParam(4, IRemoteSyncService)
556
+ ], DataSyncPrimaryController);
557
+
558
+ //#endregion
559
+ //#region src/controllers/data-sync/data-sync-replica.controller.ts
560
+ let DataSyncReplicaController = class DataSyncReplicaController extends Disposable {
561
+ constructor(_injector, _remoteInstanceService, _commandService, _rpcChannelService) {
562
+ super();
563
+ this._injector = _injector;
564
+ this._remoteInstanceService = _remoteInstanceService;
565
+ this._commandService = _commandService;
566
+ this._rpcChannelService = _rpcChannelService;
567
+ _defineProperty(this, "_remoteSyncService", void 0);
568
+ this._initRPCChannels();
569
+ this._init();
570
+ }
571
+ _initRPCChannels() {
572
+ this._rpcChannelService.registerChannel(RemoteInstanceServiceName, fromModule(this._remoteInstanceService));
573
+ this._injector.add([IRemoteSyncService, { useFactory: () => toModule(this._rpcChannelService.requestChannel(RemoteSyncServiceName)) }]);
574
+ this._remoteSyncService = this._injector.get(IRemoteSyncService);
575
+ }
576
+ _init() {
577
+ this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo, options) => {
578
+ if (commandInfo.type === CommandType.MUTATION && !(options === null || options === void 0 ? void 0 : options.fromSync)) this._remoteSyncService.syncMutation({ mutationInfo: commandInfo }, options);
579
+ }));
580
+ }
581
+ };
582
+ DataSyncReplicaController = __decorate([
583
+ __decorateParam(0, Inject(Injector)),
584
+ __decorateParam(1, IRemoteInstanceService),
585
+ __decorateParam(2, ICommandService),
586
+ __decorateParam(3, IRPCChannelService)
587
+ ], DataSyncReplicaController);
588
+
589
+ //#endregion
590
+ //#region package.json
591
+ var name = "@apollo-office/rpc";
592
+ var version = "0.25.1";
593
+
594
+ //#endregion
595
+ //#region src/services/rpc/implementations/web-worker-rpc.service.ts
596
+ /**
597
+ * Generate an `IMessageProtocol` on the web worker.
598
+ * @returns A protocol wrapper around worker global messaging APIs.
599
+ */
600
+ function createWebWorkerMessagePortOnWorker() {
601
+ return {
602
+ send(message) {
603
+ postMessage(message);
604
+ },
605
+ onMessage: new Observable((subscriber) => {
606
+ const handler = (event) => {
607
+ subscriber.next(event.data);
608
+ };
609
+ addEventListener("message", handler);
610
+ return () => removeEventListener("message", handler);
611
+ }).pipe(shareReplay({
612
+ bufferSize: 1,
613
+ refCount: true
614
+ }))
615
+ };
616
+ }
617
+ /**
618
+ * Generate an `IMessageProtocol` on the main thread side.
619
+ * @param worker The Web Worker object
620
+ * @returns A protocol wrapper around the given worker messaging APIs.
621
+ */
622
+ function createWebWorkerMessagePortOnMain(worker) {
623
+ return {
624
+ send(message) {
625
+ worker.postMessage(message);
626
+ },
627
+ onMessage: new Observable((subscriber) => {
628
+ const handler = (event) => {
629
+ subscriber.next(event.data);
630
+ };
631
+ worker.addEventListener("message", handler);
632
+ return () => worker.removeEventListener("message", handler);
633
+ }).pipe(shareReplay({
634
+ bufferSize: 1,
635
+ refCount: true
636
+ }))
637
+ };
638
+ }
639
+
640
+ //#endregion
641
+ //#region src/plugin.ts
642
+ let UniverRPCMainThreadPlugin = class UniverRPCMainThreadPlugin extends Plugin {
643
+ constructor(_config = defaultPluginMainThreadConfig, _injector, _configService) {
644
+ super();
645
+ this._config = _config;
646
+ this._injector = _injector;
647
+ this._configService = _configService;
648
+ _defineProperty(this, "_internalWorker", null);
649
+ const { ...rest } = merge({}, defaultPluginMainThreadConfig, this._config);
650
+ this._configService.setConfig(PLUGIN_CONFIG_KEY_MAIN_THREAD, rest);
651
+ }
652
+ dispose() {
653
+ super.dispose();
654
+ if (this._internalWorker) {
655
+ this._internalWorker.terminate();
656
+ this._internalWorker = null;
657
+ }
658
+ }
659
+ onStarting() {
660
+ const { workerURL } = this._config;
661
+ if (!workerURL) throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");
662
+ const worker = workerURL instanceof Worker ? workerURL : new Worker(workerURL);
663
+ this._internalWorker = workerURL instanceof Worker ? null : worker;
664
+ const messageProtocol = createWebWorkerMessagePortOnMain(worker);
665
+ [
666
+ [IRPCChannelService, { useFactory: () => new ChannelService(messageProtocol) }],
667
+ [DataSyncPrimaryController],
668
+ [IRemoteSyncService, { useClass: RemoteSyncPrimaryService }]
669
+ ].forEach((dependency) => this._injector.add(dependency));
670
+ this._injector.get(DataSyncPrimaryController);
671
+ }
672
+ };
673
+ _defineProperty(UniverRPCMainThreadPlugin, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN");
674
+ _defineProperty(UniverRPCMainThreadPlugin, "packageName", name);
675
+ _defineProperty(UniverRPCMainThreadPlugin, "version", version);
676
+ UniverRPCMainThreadPlugin = __decorate([__decorateParam(1, Inject(Injector)), __decorateParam(2, IConfigService)], UniverRPCMainThreadPlugin);
677
+ let UniverRPCWorkerThreadPlugin = class UniverRPCWorkerThreadPlugin extends Plugin {
678
+ constructor(_config = defaultPluginWorkerThreadConfig, _injector, _configService) {
679
+ super();
680
+ this._config = _config;
681
+ this._injector = _injector;
682
+ this._configService = _configService;
683
+ const { ...rest } = merge({}, defaultPluginWorkerThreadConfig, this._config);
684
+ this._configService.setConfig(PLUGIN_CONFIG_KEY_WORKER_THREAD, rest);
685
+ }
686
+ onStarting() {
687
+ [
688
+ [DataSyncReplicaController],
689
+ [IRPCChannelService, { useFactory: () => new ChannelService(createWebWorkerMessagePortOnWorker()) }],
690
+ [IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }]
691
+ ].forEach((dependency) => this._injector.add(dependency));
692
+ this._injector.get(DataSyncReplicaController);
693
+ }
694
+ };
695
+ _defineProperty(UniverRPCWorkerThreadPlugin, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN");
696
+ _defineProperty(UniverRPCWorkerThreadPlugin, "packageName", name);
697
+ _defineProperty(UniverRPCWorkerThreadPlugin, "version", version);
698
+ UniverRPCWorkerThreadPlugin = __decorate([__decorateParam(1, Inject(Injector)), __decorateParam(2, IConfigService)], UniverRPCWorkerThreadPlugin);
699
+
700
+ //#endregion
701
+ export { ChannelClient, ChannelServer, ChannelService, DataSyncPrimaryController, DataSyncReplicaController, IRPCChannelService, IRemoteInstanceService, IRemoteSyncService, PLUGIN_CONFIG_KEY_MAIN_THREAD, PLUGIN_CONFIG_KEY_WORKER_THREAD, RemoteInstanceServiceName, RemoteSyncPrimaryService, RemoteSyncServiceName, UniverRPCMainThreadPlugin, UniverRPCWorkerThreadPlugin, WebWorkerRemoteInstanceService, fromModule, toModule };