@univerjs/rpc 0.17.0 → 0.18.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.
@@ -1,10 +1,25 @@
1
- import { IDisposable } from '@univerjs/core';
2
- import { IChannel, IMessageProtocol } from './rpc.service';
1
+ /**
2
+ * Copyright 2023-present DreamNum Co., Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { IDisposable } from '@univerjs/core';
17
+ import type { IChannel, IMessageProtocol } from './rpc.service';
3
18
  export interface IRPCChannelService {
4
19
  requestChannel(name: string): IChannel;
5
20
  registerChannel(name: string, channel: IChannel): void;
6
21
  }
7
- export declare const IRPCChannelService: import('@wendellhu/redi').IdentifierDecorator<IRPCChannelService>;
22
+ export declare const IRPCChannelService: import("@wendellhu/redi").IdentifierDecorator<IRPCChannelService>;
8
23
  /**
9
24
  * This service is responsible for managing the RPC channels.
10
25
  */
@@ -1,4 +1,19 @@
1
- import { IMessageProtocol } from '../rpc.service';
1
+ /**
2
+ * Copyright 2023-present DreamNum Co., Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { IMessageProtocol } from '../rpc.service';
2
17
  /**
3
18
  * Generate an `IMessageProtocol` on the web worker.
4
19
  * @returns A protocol wrapper around worker global messaging APIs.
@@ -1,3 +1,18 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Co., Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
1
16
  import { RxDisposable } from '@univerjs/core';
2
17
  import { Observable } from 'rxjs';
3
18
  /** This protocol is for transferring data from the two peer univer instance running in different locations. */
package/lib/umd/index.js CHANGED
@@ -1 +1 @@
1
- (function(r,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs/operators"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs/operators","rxjs"],a):(r=typeof globalThis<"u"?globalThis:r||self,a(r.UniverRpc={},r.UniverCore,r.rxjs.operators,r.rxjs))})(this,(function(r,a,u,d){"use strict";var Q=Object.defineProperty;var X=(r,a,u)=>a in r?Q(r,a,{enumerable:!0,configurable:!0,writable:!0,value:u}):r[a]=u;var h=(r,a,u)=>X(r,typeof a!="symbol"?a+"":a,u);var y,g;const D="rpc.main-thread.config",q={},O="rpc.worker-thread.config",j={};var A=Object.getOwnPropertyDescriptor,N=(c,s,e,n)=>{for(var t=n>1?void 0:n?A(s,e):s,i=c.length-1,o;i>=0;i--)(o=c[i])&&(t=o(t)||t);return t},f=(c,s)=>(e,n)=>s(e,n,c);const R="rpc.remote-sync.service",v=a.createIdentifier(R);r.RemoteSyncPrimaryService=class{constructor(s){this._commandService=s}async syncMutation(s,e){const{fromCollab:n,...t}=e||{};return this._commandService.syncExecuteCommand(s.mutationInfo.id,s.mutationInfo.params,{...t,onlyLocal:!0,fromSync:!0})}},r.RemoteSyncPrimaryService=N([f(0,a.ICommandService)],r.RemoteSyncPrimaryService);const I="univer.remote-instance-service",m=a.createIdentifier(I);r.WebWorkerRemoteInstanceService=class{constructor(s,e,n){this._univerInstanceService=s,this._commandService=e,this._logService=n}whenReady(){return Promise.resolve(!0)}async syncMutation(s,e){return this._applyMutation(s.mutationInfo,e)}async createInstance(s){this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${s.unitID}`);const{type:e,snapshot:n}=s;try{if(e===a.UniverInstanceType.UNIVER_SHEET)return this._univerInstanceService.createUnit(a.UniverInstanceType.UNIVER_SHEET,n),!0;throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}catch(t){throw t instanceof Error?t:new TypeError(`${t}`)}}async disposeInstance(s){return this._logService.debug(`[WebWorkerRemoteInstanceService]: Disposing instance with id ${s.unitID}`),this._univerInstanceService.disposeUnit(s.unitID)}_applyMutation(s,e){const{id:n,params:t}=s,{fromCollab:i,...o}=e||{};return this._commandService.syncExecuteCommand(n,t,{...o,onlyLocal:!0,fromSync:!0})}},r.WebWorkerRemoteInstanceService=N([f(0,a.IUniverInstanceService),f(1,a.ICommandService),f(2,a.ILogService)],r.WebWorkerRemoteInstanceService);function E(c){const s=c;return new class{call(e,n){const t=s[e];if(typeof t=="function"){let i=n?t.apply(s,n):t.call(s);return i instanceof Promise||(i=Promise.resolve(i)),i}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,n){const t=s[e];if(typeof t=="function"){const i=n?t.apply(s,n):t.call(s);return d.isObservable(i)?i:d.of(i)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function U(c){return new Proxy({},{get(s,e){if(e!=="dispose")return function(...n){return G(e)?c.subscribe(e,n):c.call(e,n)}}})}function G(c){return c.endsWith("$")}class $ extends a.RxDisposable{constructor(e){super();h(this,"_initialized",new d.BehaviorSubject(!1));h(this,"_lastRequestCounter",0);h(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.send({type:50}),this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onMessage(n))}dispose(){this._pendingRequests.clear()}getChannel(e){return{call:(n,t)=>this._disposed?Promise.reject(new Error("[ChannelClient]: client is disposed!")):this._remoteCall(e,n,t),subscribe:(n,t)=>{if(this._disposed)throw new Error("[ChannelClient]: client is disposed!");return this._remoteSubscribe(e,n,t)}}}_whenReady(){return d.firstValueFrom(this._initialized.pipe(u.filter(e=>e),u.take(1)))}_remoteCall(e,n,t){return this._initialized.getValue()?this._doRemoteCall(e,n,t):this._whenReady().then(()=>this._doRemoteCall(e,n,t))}_doRemoteCall(e,n,t){const i=++this._lastRequestCounter,_={seq:i,type:100,channelName:e,method:n,args:t},l=this._pendingRequests;return new Promise((k,T)=>{const C={handle(W){switch(W.type){case 201:l.delete(i),k(W.data);break;case 202:l.delete(i),T(W.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(i,C),this._sendRequest(_)})}_remoteSubscribe(e,n,t){return new d.Observable(i=>{let o=-1;const _=()=>{o=++this._lastRequestCounter;const k={seq:o,type:101,channelName:e,method:n,args:t},T={handle(C){switch(C.type){case 300:i.next(C.data);break;case 301:i.error(C.data);break;case 302:i.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(o,T),this._sendRequest(k)};return this._initialized.getValue()?_():this._whenReady().then(_),()=>{if(o===-1)return;const l={type:102,seq:o,channelName:e,method:n};this._sendRequest(l)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var i;const{type:n,seq:t}=e;switch(n){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:{const{_pendingRequests:o}=this;(i=o.get(t))==null||i.handle(e),n!==300&&o.delete(t);break}}}}class L extends a.RxDisposable{constructor(e){super();h(this,"_channels",new Map);h(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onRequest(n)),this._sendInitialize()}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,n){this._channels.set(e,n)}_onRequest(e){switch(e.type){case 50:this._sendInitialize();break;case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_sendInitialize(){this._sendResponse({seq:-1,type:0})}_onMethodCall(e){const{channelName:n,method:t,args:i}=e,o=this._channels.get(n);let _;try{if(!o)throw new Error(`[ChannelServer]: Channel ${n} not found!`);_=i?o.call(t,i):o.call(t)}catch(l){_=Promise.reject(l instanceof Error?l:new Error(String(l)))}_.then(l=>{this._sendResponse({seq:e.seq,type:201,data:l})}).catch(l=>{l instanceof Error?this._sendResponse({seq:e.seq,type:202,data:l.message}):this._sendResponse({seq:e.seq,type:202,data:String(l)})})}_onSubscribe(e){const{channelName:n,seq:t}=e,i=this._channels.get(n);try{if(!i)throw new Error(`[ChannelServer]: Channel ${n} not found!`);const _=i.subscribe(e.method,e.args).subscribe({next:l=>{this._sendResponse({seq:t,type:300,data:l})},error:l=>{this._sendResponse({seq:t,type:301,data:l.message}),this._sendResponse({seq:t,type:302})},complete:()=>{this._sendResponse({seq:t,type:302})}});this._subscriptions.set(e.seq,_)}catch(o){o instanceof Error?this._sendResponse({seq:e.seq,type:301,data:o.message}):this._sendResponse({seq:e.seq,type:301,data:String(o)})}}_onUnsubscribe(e){const n=this._subscriptions.get(e.seq);n&&(n.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const p=a.createIdentifier("IRPCChannelService");class M{constructor(s){h(this,"_client");h(this,"_server");this._client=new $(s),this._server=new L(s)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(s){return this._client.getChannel(s)}registerChannel(s,e){this._server.registerChannel(s,e)}}var V=Object.getOwnPropertyDescriptor,F=(c,s,e,n)=>{for(var t=n>1?void 0:n?V(s,e):s,i=c.length-1,o;i>=0;i--)(o=c[i])&&(t=o(t)||t);return t},S=(c,s)=>(e,n)=>s(e,n,c);r.DataSyncPrimaryController=class extends a.RxDisposable{constructor(e,n,t,i,o){super();h(this,"_remoteInstanceService");h(this,"_syncingUnits",new Set);h(this,"_syncingMutations",new Set);this._injector=e,this._commandService=n,this._univerInstanceService=t,this._rpcChannelService=i,this._remoteSyncService=o,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),a.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(R,E(this._remoteSyncService)),this._injector.add([m,{useFactory:()=>U(this._rpcChannelService.requestChannel(I))}]),this._remoteInstanceService=this._injector.get(m)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:a.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{const{type:t,params:i,id:o}=e,_=(i==null?void 0:i.unitId)||"";t===a.CommandType.MUTATION&&(!_||this._syncingUnits.has(_))&&!(n!=null&&n.fromSync)&&this._syncingMutations.has(o)&&this._remoteInstanceService.syncMutation({mutationInfo:e},n)}))}},r.DataSyncPrimaryController=F([S(0,a.Inject(a.Injector)),S(1,a.ICommandService),S(2,a.IUniverInstanceService),S(3,p),S(4,v)],r.DataSyncPrimaryController);var z=Object.getOwnPropertyDescriptor,K=(c,s,e,n)=>{for(var t=n>1?void 0:n?z(s,e):s,i=c.length-1,o;i>=0;i--)(o=c[i])&&(t=o(t)||t);return t},b=(c,s)=>(e,n)=>s(e,n,c);r.DataSyncReplicaController=class extends a.Disposable{constructor(e,n,t,i){super();h(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=n,this._commandService=t,this._rpcChannelService=i,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(I,E(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>U(this._rpcChannelService.requestChannel(R))}]),this._remoteSyncService=this._injector.get(v)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{e.type===a.CommandType.MUTATION&&!(n!=null&&n.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e},n)}))}},r.DataSyncReplicaController=K([b(0,a.Inject(a.Injector)),b(1,m),b(2,a.ICommandService),b(3,p)],r.DataSyncReplicaController);const P={name:"@univerjs/rpc",version:"0.17.0"};function Y(){return{send(c){postMessage(c)},onMessage:new d.Observable(c=>{const s=e=>{c.next(e.data)};return addEventListener("message",s),()=>removeEventListener("message",s)}).pipe(d.shareReplay(1))}}function B(c){return{send(s){c.postMessage(s)},onMessage:new d.Observable(s=>{const e=n=>{s.next(n.data)};return c.addEventListener("message",e),()=>c.removeEventListener("message",e)}).pipe(d.shareReplay(1))}}var J=Object.getOwnPropertyDescriptor,H=(c,s,e,n)=>{for(var t=n>1?void 0:n?J(s,e):s,i=c.length-1,o;i>=0;i--)(o=c[i])&&(t=o(t)||t);return t},w=(c,s)=>(e,n)=>s(e,n,c);r.UniverRPCMainThreadPlugin=(y=class extends a.Plugin{constructor(e=q,n,t){super();h(this,"_internalWorker",null);this._config=e,this._injector=n,this._configService=t;const{...i}=a.merge({},q,this._config);this._configService.setConfig(D,i)}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL:e}=this._config;if(!e)throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");const n=e instanceof Worker?e:new Worker(e);this._internalWorker=e instanceof Worker?null:n;const t=B(n);[[p,{useFactory:()=>new M(t)}],[r.DataSyncPrimaryController],[v,{useClass:r.RemoteSyncPrimaryService}]].forEach(o=>this._injector.add(o)),this._injector.get(r.DataSyncPrimaryController)}},h(y,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),h(y,"packageName",P.name),h(y,"version",P.version),y),r.UniverRPCMainThreadPlugin=H([w(1,a.Inject(a.Injector)),w(2,a.IConfigService)],r.UniverRPCMainThreadPlugin),r.UniverRPCWorkerThreadPlugin=(g=class extends a.Plugin{constructor(s=j,e,n){super(),this._config=s,this._injector=e,this._configService=n;const{...t}=a.merge({},j,this._config);this._configService.setConfig(O,t)}onStarting(){[[r.DataSyncReplicaController],[p,{useFactory:()=>new M(Y())}],[m,{useClass:r.WebWorkerRemoteInstanceService}]].forEach(s=>this._injector.add(s)),this._injector.get(r.DataSyncReplicaController)}},h(g,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),h(g,"packageName",P.name),h(g,"version",P.version),g),r.UniverRPCWorkerThreadPlugin=H([w(1,a.Inject(a.Injector)),w(2,a.IConfigService)],r.UniverRPCWorkerThreadPlugin),r.ChannelClient=$,r.ChannelServer=L,r.ChannelService=M,r.IRPCChannelService=p,r.IRemoteInstanceService=m,r.IRemoteSyncService=v,r.PLUGIN_CONFIG_KEY_MAIN_THREAD=D,r.PLUGIN_CONFIG_KEY_WORKER_THREAD=O,r.RemoteInstanceServiceName=I,r.RemoteSyncServiceName=R,r.fromModule=E,r.toModule=U,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`@univerjs/core`),require(`rxjs/operators`),require(`rxjs`)):typeof define==`function`&&define.amd?define([`exports`,`@univerjs/core`,`rxjs/operators`,`rxjs`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverRpc={},e.UniverCore,e.rxjs.operators,e.rxjs))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let i=`rpc.main-thread.config`;Symbol(i);let a={},o=`rpc.worker-thread.config`;Symbol(o);let s={};function c(e,t){return function(n,r){t(n,r,e)}}function l(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let u=`rpc.remote-sync.service`,d=(0,t.createIdentifier)(u),f=class{constructor(e){this._commandService=e}async syncMutation(e,t){let{fromCollab:n,...r}=t||{};return this._commandService.syncExecuteCommand(e.mutationInfo.id,e.mutationInfo.params,{...r,onlyLocal:!0,fromSync:!0})}};f=l([c(0,t.ICommandService)],f);let p=`univer.remote-instance-service`,m=(0,t.createIdentifier)(p),h=class{constructor(e,t,n){this._univerInstanceService=e,this._commandService=t,this._logService=n}whenReady(){return Promise.resolve(!0)}async syncMutation(e,t){return this._applyMutation(e.mutationInfo,t)}async createInstance(e){this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${e.unitID}`);let{type:n,snapshot:r}=e;try{switch(n){case t.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(t.UniverInstanceType.UNIVER_SHEET,r),!0;default:throw Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${n}.`)}}catch(e){throw e instanceof Error?e:TypeError(`${e}`)}}async disposeInstance(e){return this._logService.debug(`[WebWorkerRemoteInstanceService]: Disposing instance with id ${e.unitID}`),this._univerInstanceService.disposeUnit(e.unitID)}_applyMutation(e,t){let{id:n,params:r}=e,{fromCollab:i,...a}=t||{};return this._commandService.syncExecuteCommand(n,r,{...a,onlyLocal:!0,fromSync:!0})}};h=l([c(0,t.IUniverInstanceService),c(1,t.ICommandService),c(2,t.ILogService)],h);function g(e){"@babel/helpers - typeof";return g=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},g(e)}function _(e,t){if(g(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(g(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function v(e){var t=_(e,`string`);return g(t)==`symbol`?t:t+``}function y(e,t,n){return(t=v(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function b(e){let t=e;return new class{call(e,n){let r=t[e];if(typeof r==`function`){let e=n?r.apply(t,n):r.call(t);return e instanceof Promise||(e=Promise.resolve(e)),e}throw Error(`[RPC]: method not found for ${e}!`)}subscribe(e,n){let i=t[e];if(typeof i==`function`){let e=n?i.apply(t,n):i.call(t);return(0,r.isObservable)(e)?e:(0,r.of)(e)}throw Error(`[RPC]: observable method not found for ${e}!`)}}}function x(e){return new Proxy({},{get(t,n){if(n!==`dispose`)return function(...t){return S(n)?e.subscribe(n,t):e.call(n,t)}}})}function S(e){return e.endsWith(`$`)}var C=function(e){return e[e.REQUEST_INITIALIZATION=50]=`REQUEST_INITIALIZATION`,e[e.CALL=100]=`CALL`,e[e.SUBSCRIBE=101]=`SUBSCRIBE`,e[e.UNSUBSCRIBE=102]=`UNSUBSCRIBE`,e}(C||{}),w=function(e){return e[e.INITIALIZE=0]=`INITIALIZE`,e[e.CALL_SUCCESS=201]=`CALL_SUCCESS`,e[e.CALL_FAILURE=202]=`CALL_FAILURE`,e[e.SUBSCRIBE_NEXT=300]=`SUBSCRIBE_NEXT`,e[e.SUBSCRIBE_ERROR=301]=`SUBSCRIBE_ERROR`,e[e.SUBSCRIBE_COMPLETE=302]=`SUBSCRIBE_COMPLETE`,e}(w||{}),T=class extends t.RxDisposable{constructor(e){super(),this._protocol=e,y(this,`_initialized`,new r.BehaviorSubject(!1)),y(this,`_lastRequestCounter`,0),y(this,`_pendingRequests`,new Map),this._protocol.send({type:C.REQUEST_INITIALIZATION}),this._protocol.onMessage.pipe((0,n.takeUntil)(this.dispose$)).subscribe(e=>this._onMessage(e))}dispose(){this._pendingRequests.clear()}getChannel(e){return{call:(t,n)=>this._disposed?Promise.reject(Error(`[ChannelClient]: client is disposed!`)):this._remoteCall(e,t,n),subscribe:(t,n)=>{if(this._disposed)throw Error(`[ChannelClient]: client is disposed!`);return this._remoteSubscribe(e,t,n)}}}_whenReady(){return(0,r.firstValueFrom)(this._initialized.pipe((0,n.filter)(e=>e),(0,n.take)(1)))}_remoteCall(e,t,n){return this._initialized.getValue()?this._doRemoteCall(e,t,n):this._whenReady().then(()=>this._doRemoteCall(e,t,n))}_doRemoteCall(e,t,n){let r=++this._lastRequestCounter,i={seq:r,type:C.CALL,channelName:e,method:t,args:n},a=this._pendingRequests;return new Promise((e,t)=>{this._pendingRequests.set(r,{handle(n){switch(n.type){case w.CALL_SUCCESS:a.delete(r),e(n.data);break;case w.CALL_FAILURE:a.delete(r),t(n.data);break;default:throw Error(`[ChannelClient]: unknown response type!`)}}}),this._sendRequest(i)})}_remoteSubscribe(e,t,n){return new r.Observable(r=>{let i=-1,a=()=>{i=++this._lastRequestCounter;let a=C.SUBSCRIBE,o={seq:i,type:a,channelName:e,method:t,args:n};this._pendingRequests.set(i,{handle(e){switch(e.type){case w.SUBSCRIBE_NEXT:r.next(e.data);break;case w.SUBSCRIBE_ERROR:r.error(e.data);break;case w.SUBSCRIBE_COMPLETE:r.complete();break;default:throw Error(`[ChannelClient]: unknown response type!`)}}}),this._sendRequest(o)};return this._initialized.getValue()?a():this._whenReady().then(a),()=>{if(i===-1)return;let n={type:C.UNSUBSCRIBE,seq:i,channelName:e,method:t};this._sendRequest(n)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){let{type:t,seq:n}=e;switch(t){case w.INITIALIZE:this._initialized.next(!0);break;case w.CALL_SUCCESS:case w.CALL_FAILURE:case w.SUBSCRIBE_NEXT:case w.SUBSCRIBE_COMPLETE:case w.SUBSCRIBE_ERROR:{var r;let{_pendingRequests:i}=this;(r=i.get(n))==null||r.handle(e),t!==w.SUBSCRIBE_NEXT&&i.delete(n);break}}}},E=class extends t.RxDisposable{constructor(e){super(),this._protocol=e,y(this,`_channels`,new Map),y(this,`_subscriptions`,new Map),this._protocol.onMessage.pipe((0,n.takeUntil)(this.dispose$)).subscribe(e=>this._onRequest(e)),this._sendInitialize()}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,t){this._channels.set(e,t)}_onRequest(e){switch(e.type){case C.REQUEST_INITIALIZATION:this._sendInitialize();break;case C.CALL:this._onMethodCall(e);break;case C.SUBSCRIBE:this._onSubscribe(e);break;case C.UNSUBSCRIBE:this._onUnsubscribe(e);break;default:break}}_sendInitialize(){this._sendResponse({seq:-1,type:w.INITIALIZE})}_onMethodCall(e){let{channelName:t,method:n,args:r}=e,i=this._channels.get(t),a;try{if(!i)throw Error(`[ChannelServer]: Channel ${t} not found!`);a=r?i.call(n,r):i.call(n)}catch(e){a=Promise.reject(e instanceof Error?e:Error(String(e)))}a.then(t=>{this._sendResponse({seq:e.seq,type:w.CALL_SUCCESS,data:t})}).catch(t=>{t instanceof Error?this._sendResponse({seq:e.seq,type:w.CALL_FAILURE,data:t.message}):this._sendResponse({seq:e.seq,type:w.CALL_FAILURE,data:String(t)})})}_onSubscribe(e){let{channelName:t,seq:n}=e,r=this._channels.get(t);try{if(!r)throw Error(`[ChannelServer]: Channel ${t} not found!`);let i=r.subscribe(e.method,e.args).subscribe({next:e=>{this._sendResponse({seq:n,type:w.SUBSCRIBE_NEXT,data:e})},error:e=>{this._sendResponse({seq:n,type:w.SUBSCRIBE_ERROR,data:e.message}),this._sendResponse({seq:n,type:w.SUBSCRIBE_COMPLETE})},complete:()=>{this._sendResponse({seq:n,type:w.SUBSCRIBE_COMPLETE})}});this._subscriptions.set(e.seq,i)}catch(t){t instanceof Error?this._sendResponse({seq:e.seq,type:w.SUBSCRIBE_ERROR,data:t.message}):this._sendResponse({seq:e.seq,type:w.SUBSCRIBE_ERROR,data:String(t)})}}_onUnsubscribe(e){let t=this._subscriptions.get(e.seq);t&&(t.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}};let D=(0,t.createIdentifier)(`IRPCChannelService`);var O=class{constructor(e){y(this,`_client`,void 0),y(this,`_server`,void 0),this._client=new T(e),this._server=new E(e)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(e){return this._client.getChannel(e)}registerChannel(e,t){this._server.registerChannel(e,t)}};let k=class extends t.RxDisposable{constructor(e,t,n,r,i){super(),this._injector=e,this._commandService=t,this._univerInstanceService=n,this._rpcChannelService=r,this._remoteSyncService=i,y(this,`_remoteInstanceService`,void 0),y(this,`_syncingUnits`,new Set),y(this,`_syncingMutations`,new Set),this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),(0,t.toDisposable)(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(u,b(this._remoteSyncService)),this._injector.add([m,{useFactory:()=>x(this._rpcChannelService.requestChannel(p))}]),this._remoteInstanceService=this._injector.get(m)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(t.UniverInstanceType.UNIVER_SHEET).pipe((0,n.takeUntil)(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:t.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(t.UniverInstanceType.UNIVER_SHEET).pipe((0,n.takeUntil)(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{let{type:r,params:i,id:a}=e,o=(i==null?void 0:i.unitId)||``;r===t.CommandType.MUTATION&&(!o||this._syncingUnits.has(o))&&!(n!=null&&n.fromSync)&&this._syncingMutations.has(a)&&this._remoteInstanceService.syncMutation({mutationInfo:e},n)}))}};k=l([c(0,(0,t.Inject)(t.Injector)),c(1,t.ICommandService),c(2,t.IUniverInstanceService),c(3,D),c(4,d)],k);let A=class extends t.Disposable{constructor(e,t,n,r){super(),this._injector=e,this._remoteInstanceService=t,this._commandService=n,this._rpcChannelService=r,y(this,`_remoteSyncService`,void 0),this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(p,b(this._remoteInstanceService)),this._injector.add([d,{useFactory:()=>x(this._rpcChannelService.requestChannel(u))}]),this._remoteSyncService=this._injector.get(d)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{e.type===t.CommandType.MUTATION&&!(n!=null&&n.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e},n)}))}};A=l([c(0,(0,t.Inject)(t.Injector)),c(1,m),c(2,t.ICommandService),c(3,D)],A);var j=`@univerjs/rpc`,M=`0.18.0`;function N(){return{send(e){postMessage(e)},onMessage:new r.Observable(e=>{let t=t=>{e.next(t.data)};return addEventListener(`message`,t),()=>removeEventListener(`message`,t)}).pipe((0,r.shareReplay)(1))}}function P(e){return{send(t){e.postMessage(t)},onMessage:new r.Observable(t=>{let n=e=>{t.next(e.data)};return e.addEventListener(`message`,n),()=>e.removeEventListener(`message`,n)}).pipe((0,r.shareReplay)(1))}}let F=class extends t.Plugin{constructor(e=a,n,r){super(),this._config=e,this._injector=n,this._configService=r,y(this,`_internalWorker`,null);let{...o}=(0,t.merge)({},a,this._config);this._configService.setConfig(i,o)}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){let{workerURL:e}=this._config;if(!e)throw Error(`[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.`);let t=e instanceof Worker?e:new Worker(e);this._internalWorker=e instanceof Worker?null:t;let n=P(t);[[D,{useFactory:()=>new O(n)}],[k],[d,{useClass:f}]].forEach(e=>this._injector.add(e)),this._injector.get(k)}};y(F,`pluginName`,`UNIVER_RPC_MAIN_THREAD_PLUGIN`),y(F,`packageName`,j),y(F,`version`,M),F=l([c(1,(0,t.Inject)(t.Injector)),c(2,t.IConfigService)],F);let I=class extends t.Plugin{constructor(e=s,n,r){super(),this._config=e,this._injector=n,this._configService=r;let{...i}=(0,t.merge)({},s,this._config);this._configService.setConfig(o,i)}onStarting(){[[A],[D,{useFactory:()=>new O(N())}],[m,{useClass:h}]].forEach(e=>this._injector.add(e)),this._injector.get(A)}};y(I,`pluginName`,`UNIVER_RPC_WORKER_THREAD_PLUGIN`),y(I,`packageName`,j),y(I,`version`,M),I=l([c(1,(0,t.Inject)(t.Injector)),c(2,t.IConfigService)],I),e.ChannelClient=T,e.ChannelServer=E,e.ChannelService=O,Object.defineProperty(e,`DataSyncPrimaryController`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`DataSyncReplicaController`,{enumerable:!0,get:function(){return A}}),e.IRPCChannelService=D,e.IRemoteInstanceService=m,e.IRemoteSyncService=d,e.PLUGIN_CONFIG_KEY_MAIN_THREAD=i,e.PLUGIN_CONFIG_KEY_WORKER_THREAD=o,e.RemoteInstanceServiceName=p,Object.defineProperty(e,`RemoteSyncPrimaryService`,{enumerable:!0,get:function(){return f}}),e.RemoteSyncServiceName=u,Object.defineProperty(e,`UniverRPCMainThreadPlugin`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(e,`UniverRPCWorkerThreadPlugin`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(e,`WebWorkerRemoteInstanceService`,{enumerable:!0,get:function(){return h}}),e.fromModule=b,e.toModule=x});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/rpc",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -47,21 +47,22 @@
47
47
  "rxjs": ">=7.0.0"
48
48
  },
49
49
  "dependencies": {
50
- "@univerjs/core": "0.17.0"
50
+ "@univerjs/core": "0.18.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "rxjs": "^7.8.2",
54
54
  "typescript": "^5.9.3",
55
- "vite": "^7.3.1",
56
- "vitest": "^4.0.18",
57
- "@univerjs-infra/shared": "0.17.0"
55
+ "vitest": "^4.1.0",
56
+ "@univerjs-infra/shared": "0.18.0"
58
57
  },
59
58
  "scripts": {
60
59
  "test": "vitest run",
61
60
  "test:watch": "vitest",
62
61
  "coverage": "vitest run --coverage",
63
62
  "typecheck": "tsc --noEmit",
64
- "build": "univer-cli build"
63
+ "build:bundle": "univer-cli build",
64
+ "build:types": "tsc -p tsconfig.node.json",
65
+ "build": "pnpm run build:bundle && pnpm run build:types"
65
66
  },
66
67
  "module": "./lib/es/index.js"
67
68
  }