@univerjs/rpc 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var x=Object.defineProperty;var L=(i,n,e)=>n in i?x(i,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[n]=e;var l=(i,n,e)=>L(i,typeof n!="symbol"?n+"":n,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@univerjs/core"),u=require("rxjs/operators"),_=require("rxjs"),D="rpc.main-thread.config",T={},q="rpc.worker-thread.config",k={};var H=Object.getOwnPropertyDescriptor,O=(i,n,e,t)=>{for(var s=t>1?void 0:t?H(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},g=(i,n)=>(e,t)=>n(e,t,i);const R="rpc.remote-sync.service",v=o.createIdentifier(R);exports.RemoteSyncPrimaryService=class{constructor(n){this._commandService=n}async syncMutation(n,e){const{fromCollab:t,...s}=e||{};return this._commandService.syncExecuteCommand(n.mutationInfo.id,n.mutationInfo.params,{...s,onlyLocal:!0,fromSync:!0})}};exports.RemoteSyncPrimaryService=O([g(0,o.ICommandService)],exports.RemoteSyncPrimaryService);const I="univer.remote-instance-service",m=o.createIdentifier(I);exports.WebWorkerRemoteInstanceService=class{constructor(n,e,t){this._univerInstanceService=n,this._commandService=e,this._logService=t}whenReady(){return Promise.resolve(!0)}async syncMutation(n,e){return this._applyMutation(n.mutationInfo,e)}async createInstance(n){this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${n.unitID}`);const{type:e,snapshot:t}=n;try{if(e===o.UniverInstanceType.UNIVER_SHEET)return this._univerInstanceService.createUnit(o.UniverInstanceType.UNIVER_SHEET,t),!0;throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(n){return this._logService.debug(`[WebWorkerRemoteInstanceService]: Disposing instance with id ${n.unitID}`),this._univerInstanceService.disposeUnit(n.unitID)}_applyMutation(n,e){const{id:t,params:s}=n,{fromCollab:r,...c}=e||{};return this._commandService.syncExecuteCommand(t,s,{...c,onlyLocal:!0,fromSync:!0})}};exports.WebWorkerRemoteInstanceService=O([g(0,o.IUniverInstanceService),g(1,o.ICommandService),g(2,o.ILogService)],exports.WebWorkerRemoteInstanceService);function U(i){const n=i;return new class{call(e,t){const s=n[e];if(typeof s=="function"){let r=t?s.apply(n,t):s.call(n);return r instanceof Promise||(r=Promise.resolve(r)),r}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,t){const s=n[e];if(typeof s=="function"){const r=t?s.apply(n,t):s.call(n);return _.isObservable(r)?r:_.of(r)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function M(i){return new Proxy({},{get(n,e){if(e!=="dispose")return function(...t){return A(e)?i.subscribe(e,t):i.call(e,t)}}})}function A(i){return i.endsWith("$")}class j extends o.RxDisposable{constructor(e){super();l(this,"_initialized",new _.BehaviorSubject(!1));l(this,"_lastRequestCounter",0);l(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.send({type:50}),this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(t=>this._onMessage(t))}dispose(){this._pendingRequests.clear()}getChannel(e){const t=this;return{call(s,r){return t._disposed?Promise.reject():t._remoteCall(e,s,r)},subscribe(s,r){if(t._disposed)throw new Error("[ChannelClient]: client is disposed!");return t._remoteSubscribe(e,s,r)}}}_whenReady(){return _.firstValueFrom(this._initialized.pipe(u.filter(e=>e),u.take(1)))}_remoteCall(e,t,s){return this._initialized.getValue()?this._doRemoteCall(e,t,s):this._whenReady().then(()=>this._doRemoteCall(e,t,s))}_doRemoteCall(e,t,s){const r=++this._lastRequestCounter,h={seq:r,type:100,channelName:e,method:t,args:s},a=this;return new Promise((f,b)=>{const d={handle(P){switch(P.type){case 201:a._pendingRequests.delete(r),f(P.data);break;case 202:a._pendingRequests.delete(r),b(P.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(r,d),this._sendRequest(h)})}_remoteSubscribe(e,t,s){return new _.Observable(r=>{let c=-1;const h=()=>{c=++this._lastRequestCounter;const f={seq:c,type:101,channelName:e,method:t,args:s},b={handle(d){switch(d.type){case 300:r.next(d.data);break;case 301:r.error(d.data);break;case 302:r.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(c,b),this._sendRequest(f)};return this._initialized.getValue()?h():this._whenReady().then(h),()=>{if(c===-1)return;const a={type:102,seq:c,channelName:e,method:t};this._sendRequest(a)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var r;const{type:t,seq:s}=e;switch(t){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:{const{_pendingRequests:c}=this;(r=c.get(s))==null||r.handle(e),t!==300&&c.delete(s);break}}}}class N extends o.RxDisposable{constructor(e){super();l(this,"_channels",new Map);l(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(t=>this._onRequest(t)),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 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:t,method:s,args:r}=e,c=this._channels.get(t);let h;try{if(!c)throw new Error(`[ChannelServer]: Channel ${t} not found!`);h=r?c.call(s,r):c.call(s)}catch(a){h=Promise.reject(a)}h.then(a=>{this._sendResponse({seq:e.seq,type:201,data:a})}).catch(a=>{a instanceof Error?this._sendResponse({seq:e.seq,type:202,data:a.message}):this._sendResponse({seq:e.seq,type:202,data:String(a)})})}_onSubscribe(e){const{channelName:t,seq:s}=e,r=this._channels.get(t);try{if(!r)throw new Error(`[ChannelServer]: Channel ${t} not found!`);const h=r.subscribe(e.method,e.args).subscribe({next:a=>{this._sendResponse({seq:s,type:300,data:a})},error:a=>{this._sendResponse({seq:s,type:301,data:a.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,h)}catch(c){c instanceof Error?this._sendResponse({seq:e.seq,type:301,data:c.message}):this._sendResponse({seq:e.seq,type:301,data:String(c)})}}_onUnsubscribe(e){const t=this._subscriptions.get(e.seq);t&&(t.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const S=o.createIdentifier("IRPCChannelService");class W{constructor(n){l(this,"_client");l(this,"_server");this._client=new j(n),this._server=new N(n)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(n){return this._client.getChannel(n)}registerChannel(n,e){this._server.registerChannel(n,e)}}var G=Object.getOwnPropertyDescriptor,V=(i,n,e,t)=>{for(var s=t>1?void 0:t?G(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},p=(i,n)=>(e,t)=>n(e,t,i);exports.DataSyncPrimaryController=class extends o.RxDisposable{constructor(e,t,s,r,c){super();l(this,"_remoteInstanceService");l(this,"_syncingUnits",new Set);l(this,"_syncingMutations",new Set);this._injector=e,this._commandService=t,this._univerInstanceService=s,this._rpcChannelService=r,this._remoteSyncService=c,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),o.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(R,U(this._remoteSyncService)),this._injector.add([m,{useFactory:()=>M(this._rpcChannelService.requestChannel(I))}]),this._remoteInstanceService=this._injector.get(m)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(o.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:o.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(o.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,t)=>{const{type:s,params:r,id:c}=e,h=(r==null?void 0:r.unitId)||"";s===o.CommandType.MUTATION&&(!h||this._syncingUnits.has(h))&&!(t!=null&&t.fromSync)&&this._syncingMutations.has(c)&&this._remoteInstanceService.syncMutation({mutationInfo:e},t)}))}};exports.DataSyncPrimaryController=V([p(0,o.Inject(o.Injector)),p(1,o.ICommandService),p(2,o.IUniverInstanceService),p(3,S),p(4,v)],exports.DataSyncPrimaryController);var F=Object.getOwnPropertyDescriptor,z=(i,n,e,t)=>{for(var s=t>1?void 0:t?F(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},y=(i,n)=>(e,t)=>n(e,t,i);exports.DataSyncReplicaController=class extends o.Disposable{constructor(e,t,s,r){super();l(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=t,this._commandService=s,this._rpcChannelService=r,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(I,U(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>M(this._rpcChannelService.requestChannel(R))}]),this._remoteSyncService=this._injector.get(v)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{e.type===o.CommandType.MUTATION&&!(t!=null&&t.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e},t)}))}};exports.DataSyncReplicaController=z([y(0,o.Inject(o.Injector)),y(1,m),y(2,o.ICommandService),y(3,S)],exports.DataSyncReplicaController);function K(){return{send(i){postMessage(i)},onMessage:new _.Observable(i=>{const n=e=>{i.next(e.data)};return addEventListener("message",n),()=>removeEventListener("message",n)}).pipe(_.shareReplay(1))}}function Y(i){return{send(n){i.postMessage(n)},onMessage:new _.Observable(n=>{const e=t=>{n.next(t.data)};return i.addEventListener("message",e),()=>i.removeEventListener("message",e)}).pipe(_.shareReplay(1))}}var B=Object.getOwnPropertyDescriptor,$=(i,n,e,t)=>{for(var s=t>1?void 0:t?B(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},C=(i,n)=>(e,t)=>n(e,t,i),w;exports.UniverRPCMainThreadPlugin=(w=class extends o.Plugin{constructor(e=T,t,s){super();l(this,"_internalWorker",null);this._config=e,this._injector=t,this._configService=s;const{...r}=o.merge({},T,this._config);this._configService.setConfig(D,r)}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 t=e instanceof Worker?e:new Worker(e);this._internalWorker=e instanceof Worker?null:t;const s=Y(t);[[S,{useFactory:()=>new W(s)}],[exports.DataSyncPrimaryController],[v,{useClass:exports.RemoteSyncPrimaryService}]].forEach(c=>this._injector.add(c)),this._injector.get(exports.DataSyncPrimaryController)}},l(w,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),w);exports.UniverRPCMainThreadPlugin=$([C(1,o.Inject(o.Injector)),C(2,o.IConfigService)],exports.UniverRPCMainThreadPlugin);var E;exports.UniverRPCWorkerThreadPlugin=(E=class extends o.Plugin{constructor(n=k,e,t){super(),this._config=n,this._injector=e,this._configService=t;const{...s}=o.merge({},k,this._config);this._configService.setConfig(q,s)}onStarting(){[[exports.DataSyncReplicaController],[S,{useFactory:()=>new W(K())}],[m,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(n=>this._injector.add(n)),this._injector.get(exports.DataSyncReplicaController)}},l(E,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),E);exports.UniverRPCWorkerThreadPlugin=$([C(1,o.Inject(o.Injector)),C(2,o.IConfigService)],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=j;exports.ChannelServer=N;exports.ChannelService=W;exports.IRPCChannelService=S;exports.IRemoteInstanceService=m;exports.IRemoteSyncService=v;exports.PLUGIN_CONFIG_KEY_MAIN_THREAD=D;exports.PLUGIN_CONFIG_KEY_WORKER_THREAD=q;exports.RemoteInstanceServiceName=I;exports.RemoteSyncServiceName=R;exports.fromModule=U;exports.toModule=M;
1
+ "use strict";var L=Object.defineProperty;var H=(i,n,e)=>n in i?L(i,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[n]=e;var l=(i,n,e)=>H(i,typeof n!="symbol"?n+"":n,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@univerjs/core"),u=require("rxjs/operators"),_=require("rxjs"),q="rpc.main-thread.config",T={},O="rpc.worker-thread.config",D={};var A=Object.getOwnPropertyDescriptor,j=(i,n,e,t)=>{for(var s=t>1?void 0:t?A(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},R=(i,n)=>(e,t)=>n(e,t,i);const b="rpc.remote-sync.service",S=o.createIdentifier(b);exports.RemoteSyncPrimaryService=class{constructor(n){this._commandService=n}async syncMutation(n,e){const{fromCollab:t,...s}=e||{};return this._commandService.syncExecuteCommand(n.mutationInfo.id,n.mutationInfo.params,{...s,onlyLocal:!0,fromSync:!0})}};exports.RemoteSyncPrimaryService=j([R(0,o.ICommandService)],exports.RemoteSyncPrimaryService);const P="univer.remote-instance-service",y=o.createIdentifier(P);exports.WebWorkerRemoteInstanceService=class{constructor(n,e,t){this._univerInstanceService=n,this._commandService=e,this._logService=t}whenReady(){return Promise.resolve(!0)}async syncMutation(n,e){return this._applyMutation(n.mutationInfo,e)}async createInstance(n){this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${n.unitID}`);const{type:e,snapshot:t}=n;try{if(e===o.UniverInstanceType.UNIVER_SHEET)return this._univerInstanceService.createUnit(o.UniverInstanceType.UNIVER_SHEET,t),!0;throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(n){return this._logService.debug(`[WebWorkerRemoteInstanceService]: Disposing instance with id ${n.unitID}`),this._univerInstanceService.disposeUnit(n.unitID)}_applyMutation(n,e){const{id:t,params:s}=n,{fromCollab:r,...c}=e||{};return this._commandService.syncExecuteCommand(t,s,{...c,onlyLocal:!0,fromSync:!0})}};exports.WebWorkerRemoteInstanceService=j([R(0,o.IUniverInstanceService),R(1,o.ICommandService),R(2,o.ILogService)],exports.WebWorkerRemoteInstanceService);function M(i){const n=i;return new class{call(e,t){const s=n[e];if(typeof s=="function"){let r=t?s.apply(n,t):s.call(n);return r instanceof Promise||(r=Promise.resolve(r)),r}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,t){const s=n[e];if(typeof s=="function"){const r=t?s.apply(n,t):s.call(n);return _.isObservable(r)?r:_.of(r)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function k(i){return new Proxy({},{get(n,e){if(e!=="dispose")return function(...t){return G(e)?i.subscribe(e,t):i.call(e,t)}}})}function G(i){return i.endsWith("$")}class N extends o.RxDisposable{constructor(e){super();l(this,"_initialized",new _.BehaviorSubject(!1));l(this,"_lastRequestCounter",0);l(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.send({type:50}),this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(t=>this._onMessage(t))}dispose(){this._pendingRequests.clear()}getChannel(e){return{call:(t,s)=>this._disposed?Promise.reject(new Error("[ChannelClient]: client is disposed!")):this._remoteCall(e,t,s),subscribe:(t,s)=>{if(this._disposed)throw new Error("[ChannelClient]: client is disposed!");return this._remoteSubscribe(e,t,s)}}}_whenReady(){return _.firstValueFrom(this._initialized.pipe(u.filter(e=>e),u.take(1)))}_remoteCall(e,t,s){return this._initialized.getValue()?this._doRemoteCall(e,t,s):this._whenReady().then(()=>this._doRemoteCall(e,t,s))}_doRemoteCall(e,t,s){const r=++this._lastRequestCounter,h={seq:r,type:100,channelName:e,method:t,args:s},a=this._pendingRequests;return new Promise((w,E)=>{const d={handle(U){switch(U.type){case 201:a.delete(r),w(U.data);break;case 202:a.delete(r),E(U.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(r,d),this._sendRequest(h)})}_remoteSubscribe(e,t,s){return new _.Observable(r=>{let c=-1;const h=()=>{c=++this._lastRequestCounter;const w={seq:c,type:101,channelName:e,method:t,args:s},E={handle(d){switch(d.type){case 300:r.next(d.data);break;case 301:r.error(d.data);break;case 302:r.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(c,E),this._sendRequest(w)};return this._initialized.getValue()?h():this._whenReady().then(h),()=>{if(c===-1)return;const a={type:102,seq:c,channelName:e,method:t};this._sendRequest(a)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var r;const{type:t,seq:s}=e;switch(t){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:{const{_pendingRequests:c}=this;(r=c.get(s))==null||r.handle(e),t!==300&&c.delete(s);break}}}}class $ extends o.RxDisposable{constructor(e){super();l(this,"_channels",new Map);l(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(t=>this._onRequest(t)),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 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:t,method:s,args:r}=e,c=this._channels.get(t);let h;try{if(!c)throw new Error(`[ChannelServer]: Channel ${t} not found!`);h=r?c.call(s,r):c.call(s)}catch(a){h=Promise.reject(a instanceof Error?a:new Error(String(a)))}h.then(a=>{this._sendResponse({seq:e.seq,type:201,data:a})}).catch(a=>{a instanceof Error?this._sendResponse({seq:e.seq,type:202,data:a.message}):this._sendResponse({seq:e.seq,type:202,data:String(a)})})}_onSubscribe(e){const{channelName:t,seq:s}=e,r=this._channels.get(t);try{if(!r)throw new Error(`[ChannelServer]: Channel ${t} not found!`);const h=r.subscribe(e.method,e.args).subscribe({next:a=>{this._sendResponse({seq:s,type:300,data:a})},error:a=>{this._sendResponse({seq:s,type:301,data:a.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,h)}catch(c){c instanceof Error?this._sendResponse({seq:e.seq,type:301,data:c.message}):this._sendResponse({seq:e.seq,type:301,data:String(c)})}}_onUnsubscribe(e){const t=this._subscriptions.get(e.seq);t&&(t.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const g=o.createIdentifier("IRPCChannelService");class W{constructor(n){l(this,"_client");l(this,"_server");this._client=new N(n),this._server=new $(n)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(n){return this._client.getChannel(n)}registerChannel(n,e){this._server.registerChannel(n,e)}}var V=Object.getOwnPropertyDescriptor,F=(i,n,e,t)=>{for(var s=t>1?void 0:t?V(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},p=(i,n)=>(e,t)=>n(e,t,i);exports.DataSyncPrimaryController=class extends o.RxDisposable{constructor(e,t,s,r,c){super();l(this,"_remoteInstanceService");l(this,"_syncingUnits",new Set);l(this,"_syncingMutations",new Set);this._injector=e,this._commandService=t,this._univerInstanceService=s,this._rpcChannelService=r,this._remoteSyncService=c,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),o.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(b,M(this._remoteSyncService)),this._injector.add([y,{useFactory:()=>k(this._rpcChannelService.requestChannel(P))}]),this._remoteInstanceService=this._injector.get(y)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(o.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:o.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(o.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,t)=>{const{type:s,params:r,id:c}=e,h=(r==null?void 0:r.unitId)||"";s===o.CommandType.MUTATION&&(!h||this._syncingUnits.has(h))&&!(t!=null&&t.fromSync)&&this._syncingMutations.has(c)&&this._remoteInstanceService.syncMutation({mutationInfo:e},t)}))}};exports.DataSyncPrimaryController=F([p(0,o.Inject(o.Injector)),p(1,o.ICommandService),p(2,o.IUniverInstanceService),p(3,g),p(4,S)],exports.DataSyncPrimaryController);var z=Object.getOwnPropertyDescriptor,K=(i,n,e,t)=>{for(var s=t>1?void 0:t?z(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},C=(i,n)=>(e,t)=>n(e,t,i);exports.DataSyncReplicaController=class extends o.Disposable{constructor(e,t,s,r){super();l(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=t,this._commandService=s,this._rpcChannelService=r,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(P,M(this._remoteInstanceService)),this._injector.add([S,{useFactory:()=>k(this._rpcChannelService.requestChannel(b))}]),this._remoteSyncService=this._injector.get(S)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{e.type===o.CommandType.MUTATION&&!(t!=null&&t.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e},t)}))}};exports.DataSyncReplicaController=K([C(0,o.Inject(o.Injector)),C(1,y),C(2,o.ICommandService),C(3,g)],exports.DataSyncReplicaController);const Y="@univerjs/rpc",B="0.17.0",I={name:Y,version:B};function J(){return{send(i){postMessage(i)},onMessage:new _.Observable(i=>{const n=e=>{i.next(e.data)};return addEventListener("message",n),()=>removeEventListener("message",n)}).pipe(_.shareReplay(1))}}function Q(i){return{send(n){i.postMessage(n)},onMessage:new _.Observable(n=>{const e=t=>{n.next(t.data)};return i.addEventListener("message",e),()=>i.removeEventListener("message",e)}).pipe(_.shareReplay(1))}}var X=Object.getOwnPropertyDescriptor,x=(i,n,e,t)=>{for(var s=t>1?void 0:t?X(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},f=(i,n)=>(e,t)=>n(e,t,i),v;exports.UniverRPCMainThreadPlugin=(v=class extends o.Plugin{constructor(e=T,t,s){super();l(this,"_internalWorker",null);this._config=e,this._injector=t,this._configService=s;const{...r}=o.merge({},T,this._config);this._configService.setConfig(q,r)}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 t=e instanceof Worker?e:new Worker(e);this._internalWorker=e instanceof Worker?null:t;const s=Q(t);[[g,{useFactory:()=>new W(s)}],[exports.DataSyncPrimaryController],[S,{useClass:exports.RemoteSyncPrimaryService}]].forEach(c=>this._injector.add(c)),this._injector.get(exports.DataSyncPrimaryController)}},l(v,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),l(v,"packageName",I.name),l(v,"version",I.version),v);exports.UniverRPCMainThreadPlugin=x([f(1,o.Inject(o.Injector)),f(2,o.IConfigService)],exports.UniverRPCMainThreadPlugin);var m;exports.UniverRPCWorkerThreadPlugin=(m=class extends o.Plugin{constructor(n=D,e,t){super(),this._config=n,this._injector=e,this._configService=t;const{...s}=o.merge({},D,this._config);this._configService.setConfig(O,s)}onStarting(){[[exports.DataSyncReplicaController],[g,{useFactory:()=>new W(J())}],[y,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(n=>this._injector.add(n)),this._injector.get(exports.DataSyncReplicaController)}},l(m,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),l(m,"packageName",I.name),l(m,"version",I.version),m);exports.UniverRPCWorkerThreadPlugin=x([f(1,o.Inject(o.Injector)),f(2,o.IConfigService)],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=N;exports.ChannelServer=$;exports.ChannelService=W;exports.IRPCChannelService=g;exports.IRemoteInstanceService=y;exports.IRemoteSyncService=S;exports.PLUGIN_CONFIG_KEY_MAIN_THREAD=q;exports.PLUGIN_CONFIG_KEY_WORKER_THREAD=O;exports.RemoteInstanceServiceName=P;exports.RemoteSyncServiceName=b;exports.fromModule=M;exports.toModule=k;
package/lib/es/index.js CHANGED
@@ -1,17 +1,17 @@
1
- var X = Object.defineProperty;
2
- var Z = (s, t, e) => t in s ? X(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
- var a = (s, t, e) => Z(s, typeof t != "symbol" ? t + "" : t, e);
4
- import { createIdentifier as O, UniverInstanceType as u, ICommandService as b, IUniverInstanceService as H, ILogService as ee, RxDisposable as W, Inject as C, Injector as R, toDisposable as te, CommandType as V, Disposable as ne, IConfigService as A, Plugin as z, merge as F } from "@univerjs/core";
5
- import { takeUntil as v, filter as se, take as re } from "rxjs/operators";
6
- import { BehaviorSubject as ie, firstValueFrom as oe, Observable as T, isObservable as ce, of as ae, shareReplay as G } from "rxjs";
7
- const he = "rpc.main-thread.config", j = {}, le = "rpc.worker-thread.config", N = {};
8
- var _e = Object.getOwnPropertyDescriptor, Y = (s, t, e, n) => {
9
- for (var r = n > 1 ? void 0 : n ? _e(t, e) : t, i = s.length - 1, o; i >= 0; i--)
1
+ var Z = Object.defineProperty;
2
+ var ee = (s, t, e) => t in s ? Z(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
+ var a = (s, t, e) => ee(s, typeof t != "symbol" ? t + "" : t, e);
4
+ import { createIdentifier as W, UniverInstanceType as p, ICommandService as I, IUniverInstanceService as V, ILogService as te, RxDisposable as T, Inject as w, Injector as E, toDisposable as ne, CommandType as A, Disposable as se, IConfigService as z, Plugin as F, merge as G } from "@univerjs/core";
5
+ import { takeUntil as g, filter as re, take as ie } from "rxjs/operators";
6
+ import { BehaviorSubject as oe, firstValueFrom as ce, Observable as D, isObservable as ae, of as he, shareReplay as Y } from "rxjs";
7
+ const le = "rpc.main-thread.config", N = {}, _e = "rpc.worker-thread.config", x = {};
8
+ var ue = Object.getOwnPropertyDescriptor, B = (s, t, e, n) => {
9
+ for (var r = n > 1 ? void 0 : n ? ue(t, e) : t, i = s.length - 1, o; i >= 0; i--)
10
10
  (o = s[i]) && (r = o(r) || r);
11
11
  return r;
12
- }, p = (s, t) => (e, n) => t(e, n, s);
13
- const D = "rpc.remote-sync.service", g = O(D);
14
- let q = class {
12
+ }, m = (s, t) => (e, n) => t(e, n, s);
13
+ const $ = "rpc.remote-sync.service", f = W($);
14
+ let k = class {
15
15
  constructor(s) {
16
16
  this._commandService = s;
17
17
  }
@@ -24,11 +24,11 @@ let q = class {
24
24
  });
25
25
  }
26
26
  };
27
- q = Y([
28
- p(0, b)
29
- ], q);
30
- const $ = "univer.remote-instance-service", m = O($);
31
- let k = class {
27
+ k = B([
28
+ m(0, I)
29
+ ], k);
30
+ const j = "univer.remote-instance-service", y = W(j);
31
+ let O = class {
32
32
  constructor(s, t, e) {
33
33
  this._univerInstanceService = s, this._commandService = t, this._logService = e;
34
34
  }
@@ -42,8 +42,8 @@ let k = class {
42
42
  this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${s.unitID}`);
43
43
  const { type: t, snapshot: e } = s;
44
44
  try {
45
- if (t === u.UNIVER_SHEET)
46
- return this._univerInstanceService.createUnit(u.UNIVER_SHEET, e), !0;
45
+ if (t === p.UNIVER_SHEET)
46
+ return this._univerInstanceService.createUnit(p.UNIVER_SHEET, e), !0;
47
47
  throw new Error(
48
48
  `[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${t}.`
49
49
  );
@@ -63,12 +63,12 @@ let k = class {
63
63
  });
64
64
  }
65
65
  };
66
- k = Y([
67
- p(0, H),
68
- p(1, b),
69
- p(2, ee)
70
- ], k);
71
- function B(s) {
66
+ O = B([
67
+ m(0, V),
68
+ m(1, I),
69
+ m(2, te)
70
+ ], O);
71
+ function K(s) {
72
72
  const t = s;
73
73
  return new class {
74
74
  call(e, n) {
@@ -83,57 +83,54 @@ function B(s) {
83
83
  const r = t[e];
84
84
  if (typeof r == "function") {
85
85
  const i = n ? r.apply(t, n) : r.call(t);
86
- return ce(i) ? i : ae(i);
86
+ return ae(i) ? i : he(i);
87
87
  }
88
88
  throw new Error(`[RPC]: observable method not found for ${e}!`);
89
89
  }
90
90
  }();
91
91
  }
92
- function K(s) {
92
+ function J(s) {
93
93
  return new Proxy({}, {
94
94
  get(t, e) {
95
95
  if (e !== "dispose")
96
96
  return function(...n) {
97
- return ue(e) ? s.subscribe(e, n) : s.call(e, n);
97
+ return de(e) ? s.subscribe(e, n) : s.call(e, n);
98
98
  };
99
99
  }
100
100
  });
101
101
  }
102
- function ue(s) {
102
+ function de(s) {
103
103
  return s.endsWith("$");
104
104
  }
105
- class de extends W {
105
+ class pe extends T {
106
106
  constructor(e) {
107
107
  super();
108
- a(this, "_initialized", new ie(!1));
108
+ a(this, "_initialized", new oe(!1));
109
109
  a(this, "_lastRequestCounter", 0);
110
110
  a(this, "_pendingRequests", /* @__PURE__ */ new Map());
111
111
  this._protocol = e, this._protocol.send({
112
112
  type: 50
113
113
  /* REQUEST_INITIALIZATION */
114
- }), this._protocol.onMessage.pipe(v(this.dispose$)).subscribe((n) => this._onMessage(n));
114
+ }), this._protocol.onMessage.pipe(g(this.dispose$)).subscribe((n) => this._onMessage(n));
115
115
  }
116
116
  dispose() {
117
117
  this._pendingRequests.clear();
118
118
  }
119
119
  getChannel(e) {
120
- const n = this;
121
120
  return {
122
- call(r, i) {
123
- return n._disposed ? Promise.reject() : n._remoteCall(e, r, i);
124
- },
125
- subscribe(r, i) {
126
- if (n._disposed)
121
+ call: (n, r) => this._disposed ? Promise.reject(new Error("[ChannelClient]: client is disposed!")) : this._remoteCall(e, n, r),
122
+ subscribe: (n, r) => {
123
+ if (this._disposed)
127
124
  throw new Error("[ChannelClient]: client is disposed!");
128
- return n._remoteSubscribe(e, r, i);
125
+ return this._remoteSubscribe(e, n, r);
129
126
  }
130
127
  };
131
128
  }
132
129
  _whenReady() {
133
- return oe(
130
+ return ce(
134
131
  this._initialized.pipe(
135
- se((e) => e),
136
- re(1)
132
+ re((e) => e),
133
+ ie(1)
137
134
  )
138
135
  );
139
136
  }
@@ -141,16 +138,16 @@ class de extends W {
141
138
  return this._initialized.getValue() ? this._doRemoteCall(e, n, r) : this._whenReady().then(() => this._doRemoteCall(e, n, r));
142
139
  }
143
140
  _doRemoteCall(e, n, r) {
144
- const i = ++this._lastRequestCounter, h = { seq: i, type: 100, channelName: e, method: n, args: r }, c = this;
145
- return new Promise((w, E) => {
141
+ const i = ++this._lastRequestCounter, h = { seq: i, type: 100, channelName: e, method: n, args: r }, c = this._pendingRequests;
142
+ return new Promise((U, M) => {
146
143
  const l = {
147
- handle(P) {
148
- switch (P.type) {
144
+ handle(q) {
145
+ switch (q.type) {
149
146
  case 201:
150
- c._pendingRequests.delete(i), w(P.data);
147
+ c.delete(i), U(q.data);
151
148
  break;
152
149
  case 202:
153
- c._pendingRequests.delete(i), E(P.data);
150
+ c.delete(i), M(q.data);
154
151
  break;
155
152
  default:
156
153
  throw new Error("[ChannelClient]: unknown response type!");
@@ -161,11 +158,11 @@ class de extends W {
161
158
  });
162
159
  }
163
160
  _remoteSubscribe(e, n, r) {
164
- return new T((i) => {
161
+ return new D((i) => {
165
162
  let o = -1;
166
163
  const h = () => {
167
164
  o = ++this._lastRequestCounter;
168
- const w = { seq: o, type: 101, channelName: e, method: n, args: r }, E = {
165
+ const U = { seq: o, type: 101, channelName: e, method: n, args: r }, M = {
169
166
  handle(l) {
170
167
  switch (l.type) {
171
168
  case 300:
@@ -182,7 +179,7 @@ class de extends W {
182
179
  }
183
180
  }
184
181
  };
185
- this._pendingRequests.set(o, E), this._sendRequest(w);
182
+ this._pendingRequests.set(o, M), this._sendRequest(U);
186
183
  };
187
184
  return this._initialized.getValue() ? h() : this._whenReady().then(h), () => {
188
185
  if (o === -1)
@@ -219,12 +216,12 @@ class de extends W {
219
216
  }
220
217
  }
221
218
  }
222
- class pe extends W {
219
+ class ve extends T {
223
220
  constructor(e) {
224
221
  super();
225
222
  a(this, "_channels", /* @__PURE__ */ new Map());
226
223
  a(this, "_subscriptions", /* @__PURE__ */ new Map());
227
- this._protocol = e, this._protocol.onMessage.pipe(v(this.dispose$)).subscribe((n) => this._onRequest(n)), this._sendInitialize();
224
+ this._protocol = e, this._protocol.onMessage.pipe(g(this.dispose$)).subscribe((n) => this._onRequest(n)), this._sendInitialize();
228
225
  }
229
226
  dispose() {
230
227
  super.dispose(), this._subscriptions.clear(), this._channels.clear();
@@ -263,7 +260,7 @@ class pe extends W {
263
260
  throw new Error(`[ChannelServer]: Channel ${n} not found!`);
264
261
  h = i ? o.call(r, i) : o.call(r);
265
262
  } catch (c) {
266
- h = Promise.reject(c);
263
+ h = Promise.reject(c instanceof Error ? c : new Error(String(c)));
267
264
  }
268
265
  h.then((c) => {
269
266
  this._sendResponse({ seq: e.seq, type: 201, data: c });
@@ -308,12 +305,12 @@ class pe extends W {
308
305
  this._protocol.send(e);
309
306
  }
310
307
  }
311
- const I = O("IRPCChannelService");
312
- class J {
308
+ const P = W("IRPCChannelService");
309
+ class Q {
313
310
  constructor(t) {
314
311
  a(this, "_client");
315
312
  a(this, "_server");
316
- this._client = new de(t), this._server = new pe(t);
313
+ this._client = new pe(t), this._server = new ve(t);
317
314
  }
318
315
  dispose() {
319
316
  this._client.dispose(), this._server.dispose();
@@ -325,12 +322,12 @@ class J {
325
322
  this._server.registerChannel(t, e);
326
323
  }
327
324
  }
328
- var ve = Object.getOwnPropertyDescriptor, ge = (s, t, e, n) => {
329
- for (var r = n > 1 ? void 0 : n ? ve(t, e) : t, i = s.length - 1, o; i >= 0; i--)
325
+ var me = Object.getOwnPropertyDescriptor, ge = (s, t, e, n) => {
326
+ for (var r = n > 1 ? void 0 : n ? me(t, e) : t, i = s.length - 1, o; i >= 0; i--)
330
327
  (o = s[i]) && (r = o(r) || r);
331
328
  return r;
332
329
  }, _ = (s, t) => (e, n) => t(e, n, s);
333
- let f = class extends W {
330
+ let S = class extends T {
334
331
  constructor(t, e, n, r, i) {
335
332
  super();
336
333
  a(this, "_remoteInstanceService");
@@ -346,117 +343,123 @@ let f = class extends W {
346
343
  * sync other types of documents, you should manually call this method with that document's id.
347
344
  */
348
345
  syncUnit(t) {
349
- return this._syncingUnits.add(t), te(() => this._syncingUnits.delete(t));
346
+ return this._syncingUnits.add(t), ne(() => this._syncingUnits.delete(t));
350
347
  }
351
348
  _initRPCChannels() {
352
- this._rpcChannelService.registerChannel(D, B(this._remoteSyncService)), this._injector.add([
353
- m,
354
- { useFactory: () => K(this._rpcChannelService.requestChannel($)) }
355
- ]), this._remoteInstanceService = this._injector.get(m);
349
+ this._rpcChannelService.registerChannel($, K(this._remoteSyncService)), this._injector.add([
350
+ y,
351
+ // eslint-disable-next-line react/no-unnecessary-use-prefix
352
+ { useFactory: () => J(this._rpcChannelService.requestChannel(j)) }
353
+ ]), this._remoteInstanceService = this._injector.get(y);
356
354
  }
357
355
  _init() {
358
- this._univerInstanceService.getTypeOfUnitAdded$(u.UNIVER_SHEET).pipe(v(this.dispose$)).subscribe((t) => {
356
+ this._univerInstanceService.getTypeOfUnitAdded$(p.UNIVER_SHEET).pipe(g(this.dispose$)).subscribe((t) => {
359
357
  this._syncingUnits.add(t.getUnitId()), this._remoteInstanceService.createInstance({
360
358
  unitID: t.getUnitId(),
361
- type: u.UNIVER_SHEET,
359
+ type: p.UNIVER_SHEET,
362
360
  snapshot: t.getSnapshot()
363
361
  });
364
- }), this._univerInstanceService.getTypeOfUnitDisposed$(u.UNIVER_SHEET).pipe(v(this.dispose$)).subscribe((t) => {
362
+ }), this._univerInstanceService.getTypeOfUnitDisposed$(p.UNIVER_SHEET).pipe(g(this.dispose$)).subscribe((t) => {
365
363
  this._syncingUnits.delete(t.getUnitId()), this._remoteInstanceService.disposeInstance({
366
364
  unitID: t.getUnitId()
367
365
  });
368
366
  }), this.disposeWithMe(this._commandService.onCommandExecuted((t, e) => {
369
367
  const { type: n, params: r, id: i } = t, o = (r == null ? void 0 : r.unitId) || "";
370
- n === V.MUTATION && // only sync mutations to the worker thread
368
+ n === A.MUTATION && // only sync mutations to the worker thread
371
369
  (!o || this._syncingUnits.has(o)) && // do not sync mutations from the web worker back to the web worker
372
370
  !(e != null && e.fromSync) && // do not sync mutations those are not meant to be synced
373
371
  this._syncingMutations.has(i) && this._remoteInstanceService.syncMutation({ mutationInfo: t }, e);
374
372
  }));
375
373
  }
376
374
  };
377
- f = ge([
378
- _(0, C(R)),
379
- _(1, b),
380
- _(2, H),
381
- _(3, I),
382
- _(4, g)
383
- ], f);
384
- var me = Object.getOwnPropertyDescriptor, fe = (s, t, e, n) => {
385
- for (var r = n > 1 ? void 0 : n ? me(t, e) : t, i = s.length - 1, o; i >= 0; i--)
375
+ S = ge([
376
+ _(0, w(E)),
377
+ _(1, I),
378
+ _(2, V),
379
+ _(3, P),
380
+ _(4, f)
381
+ ], S);
382
+ var fe = Object.getOwnPropertyDescriptor, ye = (s, t, e, n) => {
383
+ for (var r = n > 1 ? void 0 : n ? fe(t, e) : t, i = s.length - 1, o; i >= 0; i--)
386
384
  (o = s[i]) && (r = o(r) || r);
387
385
  return r;
388
- }, d = (s, t) => (e, n) => t(e, n, s);
389
- let y = class extends ne {
386
+ }, v = (s, t) => (e, n) => t(e, n, s);
387
+ let C = class extends se {
390
388
  constructor(t, e, n, r) {
391
389
  super();
392
390
  a(this, "_remoteSyncService");
393
391
  this._injector = t, this._remoteInstanceService = e, this._commandService = n, this._rpcChannelService = r, this._initRPCChannels(), this._init();
394
392
  }
395
393
  _initRPCChannels() {
396
- this._rpcChannelService.registerChannel($, B(this._remoteInstanceService)), this._injector.add([
397
- g,
398
- { useFactory: () => K(this._rpcChannelService.requestChannel(D)) }
399
- ]), this._remoteSyncService = this._injector.get(g);
394
+ this._rpcChannelService.registerChannel(j, K(this._remoteInstanceService)), this._injector.add([
395
+ f,
396
+ // eslint-disable-next-line react/no-unnecessary-use-prefix
397
+ { useFactory: () => J(this._rpcChannelService.requestChannel($)) }
398
+ ]), this._remoteSyncService = this._injector.get(f);
400
399
  }
401
400
  _init() {
402
401
  this.disposeWithMe(
403
402
  // Mutations executed on the main thread should be synced to the worker thread.
404
403
  this._commandService.onCommandExecuted((t, e) => {
405
- t.type === V.MUTATION && !(e != null && e.fromSync) && this._remoteSyncService.syncMutation({
404
+ t.type === A.MUTATION && !(e != null && e.fromSync) && this._remoteSyncService.syncMutation({
406
405
  mutationInfo: t
407
406
  }, e);
408
407
  })
409
408
  );
410
409
  }
411
410
  };
412
- y = fe([
413
- d(0, C(R)),
414
- d(1, m),
415
- d(2, b),
416
- d(3, I)
417
- ], y);
418
- function ye() {
411
+ C = ye([
412
+ v(0, w(E)),
413
+ v(1, y),
414
+ v(2, I),
415
+ v(3, P)
416
+ ], C);
417
+ const Se = "@univerjs/rpc", Ce = "0.17.0", b = {
418
+ name: Se,
419
+ version: Ce
420
+ };
421
+ function be() {
419
422
  return {
420
423
  send(s) {
421
424
  postMessage(s);
422
425
  },
423
- onMessage: new T((s) => {
426
+ onMessage: new D((s) => {
424
427
  const t = (e) => {
425
428
  s.next(e.data);
426
429
  };
427
430
  return addEventListener("message", t), () => removeEventListener("message", t);
428
- }).pipe(G(1))
431
+ }).pipe(Y(1))
429
432
  };
430
433
  }
431
- function Se(s) {
434
+ function Re(s) {
432
435
  return {
433
436
  send(t) {
434
437
  s.postMessage(t);
435
438
  },
436
- onMessage: new T((t) => {
439
+ onMessage: new D((t) => {
437
440
  const e = (n) => {
438
441
  t.next(n.data);
439
442
  };
440
443
  return s.addEventListener("message", e), () => s.removeEventListener("message", e);
441
- }).pipe(G(1))
444
+ }).pipe(Y(1))
442
445
  };
443
446
  }
444
- var be = Object.getOwnPropertyDescriptor, Q = (s, t, e, n) => {
445
- for (var r = n > 1 ? void 0 : n ? be(t, e) : t, i = s.length - 1, o; i >= 0; i--)
447
+ var Ie = Object.getOwnPropertyDescriptor, X = (s, t, e, n) => {
448
+ for (var r = n > 1 ? void 0 : n ? Ie(t, e) : t, i = s.length - 1, o; i >= 0; i--)
446
449
  (o = s[i]) && (r = o(r) || r);
447
450
  return r;
448
- }, S = (s, t) => (e, n) => t(e, n, s), U;
449
- let x = (U = class extends z {
450
- constructor(t = j, e, n) {
451
+ }, R = (s, t) => (e, n) => t(e, n, s), u;
452
+ let L = (u = class extends F {
453
+ constructor(t = N, e, n) {
451
454
  super();
452
455
  a(this, "_internalWorker", null);
453
456
  this._config = t, this._injector = e, this._configService = n;
454
- const { ...r } = F(
457
+ const { ...r } = G(
455
458
  {},
456
- j,
459
+ N,
457
460
  this._config
458
461
  );
459
- this._configService.setConfig(he, r);
462
+ this._configService.setConfig(le, r);
460
463
  }
461
464
  dispose() {
462
465
  super.dispose(), this._internalWorker && (this._internalWorker.terminate(), this._internalWorker = null);
@@ -467,68 +470,70 @@ let x = (U = class extends z {
467
470
  throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");
468
471
  const e = t instanceof Worker ? t : new Worker(t);
469
472
  this._internalWorker = t instanceof Worker ? null : e;
470
- const n = Se(e);
473
+ const n = Re(e);
471
474
  [
472
475
  [
473
- I,
476
+ P,
474
477
  {
475
- useFactory: () => new J(n)
478
+ // eslint-disable-next-line react/no-unnecessary-use-prefix
479
+ useFactory: () => new Q(n)
476
480
  }
477
481
  ],
478
- [f],
479
- [g, { useClass: q }]
480
- ].forEach((i) => this._injector.add(i)), this._injector.get(f);
481
- }
482
- }, a(U, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN"), U);
483
- x = Q([
484
- S(1, C(R)),
485
- S(2, A)
486
- ], x);
487
- var M;
488
- let L = (M = class extends z {
489
- constructor(s = N, t, e) {
482
+ [S],
483
+ [f, { useClass: k }]
484
+ ].forEach((i) => this._injector.add(i)), this._injector.get(S);
485
+ }
486
+ }, a(u, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN"), a(u, "packageName", b.name), a(u, "version", b.version), u);
487
+ L = X([
488
+ R(1, w(E)),
489
+ R(2, z)
490
+ ], L);
491
+ var d;
492
+ let H = (d = class extends F {
493
+ constructor(s = x, t, e) {
490
494
  super(), this._config = s, this._injector = t, this._configService = e;
491
- const { ...n } = F(
495
+ const { ...n } = G(
492
496
  {},
493
- N,
497
+ x,
494
498
  this._config
495
499
  );
496
- this._configService.setConfig(le, n);
500
+ this._configService.setConfig(_e, n);
497
501
  }
498
502
  onStarting() {
499
503
  [
500
- [y],
504
+ [C],
501
505
  [
502
- I,
506
+ P,
503
507
  {
504
- useFactory: () => new J(ye())
508
+ // eslint-disable-next-line react/no-unnecessary-use-prefix
509
+ useFactory: () => new Q(be())
505
510
  }
506
511
  ],
507
- [m, { useClass: k }]
508
- ].forEach((s) => this._injector.add(s)), this._injector.get(y);
509
- }
510
- }, a(M, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN"), M);
511
- L = Q([
512
- S(1, C(R)),
513
- S(2, A)
514
- ], L);
512
+ [y, { useClass: O }]
513
+ ].forEach((s) => this._injector.add(s)), this._injector.get(C);
514
+ }
515
+ }, a(d, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN"), a(d, "packageName", b.name), a(d, "version", b.version), d);
516
+ H = X([
517
+ R(1, w(E)),
518
+ R(2, z)
519
+ ], H);
515
520
  export {
516
- de as ChannelClient,
517
- pe as ChannelServer,
518
- J as ChannelService,
519
- f as DataSyncPrimaryController,
520
- y as DataSyncReplicaController,
521
- I as IRPCChannelService,
522
- m as IRemoteInstanceService,
523
- g as IRemoteSyncService,
524
- he as PLUGIN_CONFIG_KEY_MAIN_THREAD,
525
- le as PLUGIN_CONFIG_KEY_WORKER_THREAD,
526
- $ as RemoteInstanceServiceName,
527
- q as RemoteSyncPrimaryService,
528
- D as RemoteSyncServiceName,
529
- x as UniverRPCMainThreadPlugin,
530
- L as UniverRPCWorkerThreadPlugin,
531
- k as WebWorkerRemoteInstanceService,
532
- B as fromModule,
533
- K as toModule
521
+ pe as ChannelClient,
522
+ ve as ChannelServer,
523
+ Q as ChannelService,
524
+ S as DataSyncPrimaryController,
525
+ C as DataSyncReplicaController,
526
+ P as IRPCChannelService,
527
+ y as IRemoteInstanceService,
528
+ f as IRemoteSyncService,
529
+ le as PLUGIN_CONFIG_KEY_MAIN_THREAD,
530
+ _e as PLUGIN_CONFIG_KEY_WORKER_THREAD,
531
+ j as RemoteInstanceServiceName,
532
+ k as RemoteSyncPrimaryService,
533
+ $ as RemoteSyncServiceName,
534
+ L as UniverRPCMainThreadPlugin,
535
+ H as UniverRPCWorkerThreadPlugin,
536
+ O as WebWorkerRemoteInstanceService,
537
+ K as fromModule,
538
+ J as toModule
534
539
  };
package/lib/index.js CHANGED
@@ -1,17 +1,17 @@
1
- var X = Object.defineProperty;
2
- var Z = (s, t, e) => t in s ? X(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
- var a = (s, t, e) => Z(s, typeof t != "symbol" ? t + "" : t, e);
4
- import { createIdentifier as O, UniverInstanceType as u, ICommandService as b, IUniverInstanceService as H, ILogService as ee, RxDisposable as W, Inject as C, Injector as R, toDisposable as te, CommandType as V, Disposable as ne, IConfigService as A, Plugin as z, merge as F } from "@univerjs/core";
5
- import { takeUntil as v, filter as se, take as re } from "rxjs/operators";
6
- import { BehaviorSubject as ie, firstValueFrom as oe, Observable as T, isObservable as ce, of as ae, shareReplay as G } from "rxjs";
7
- const he = "rpc.main-thread.config", j = {}, le = "rpc.worker-thread.config", N = {};
8
- var _e = Object.getOwnPropertyDescriptor, Y = (s, t, e, n) => {
9
- for (var r = n > 1 ? void 0 : n ? _e(t, e) : t, i = s.length - 1, o; i >= 0; i--)
1
+ var Z = Object.defineProperty;
2
+ var ee = (s, t, e) => t in s ? Z(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
+ var a = (s, t, e) => ee(s, typeof t != "symbol" ? t + "" : t, e);
4
+ import { createIdentifier as W, UniverInstanceType as p, ICommandService as I, IUniverInstanceService as V, ILogService as te, RxDisposable as T, Inject as w, Injector as E, toDisposable as ne, CommandType as A, Disposable as se, IConfigService as z, Plugin as F, merge as G } from "@univerjs/core";
5
+ import { takeUntil as g, filter as re, take as ie } from "rxjs/operators";
6
+ import { BehaviorSubject as oe, firstValueFrom as ce, Observable as D, isObservable as ae, of as he, shareReplay as Y } from "rxjs";
7
+ const le = "rpc.main-thread.config", N = {}, _e = "rpc.worker-thread.config", x = {};
8
+ var ue = Object.getOwnPropertyDescriptor, B = (s, t, e, n) => {
9
+ for (var r = n > 1 ? void 0 : n ? ue(t, e) : t, i = s.length - 1, o; i >= 0; i--)
10
10
  (o = s[i]) && (r = o(r) || r);
11
11
  return r;
12
- }, p = (s, t) => (e, n) => t(e, n, s);
13
- const D = "rpc.remote-sync.service", g = O(D);
14
- let q = class {
12
+ }, m = (s, t) => (e, n) => t(e, n, s);
13
+ const $ = "rpc.remote-sync.service", f = W($);
14
+ let k = class {
15
15
  constructor(s) {
16
16
  this._commandService = s;
17
17
  }
@@ -24,11 +24,11 @@ let q = class {
24
24
  });
25
25
  }
26
26
  };
27
- q = Y([
28
- p(0, b)
29
- ], q);
30
- const $ = "univer.remote-instance-service", m = O($);
31
- let k = class {
27
+ k = B([
28
+ m(0, I)
29
+ ], k);
30
+ const j = "univer.remote-instance-service", y = W(j);
31
+ let O = class {
32
32
  constructor(s, t, e) {
33
33
  this._univerInstanceService = s, this._commandService = t, this._logService = e;
34
34
  }
@@ -42,8 +42,8 @@ let k = class {
42
42
  this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${s.unitID}`);
43
43
  const { type: t, snapshot: e } = s;
44
44
  try {
45
- if (t === u.UNIVER_SHEET)
46
- return this._univerInstanceService.createUnit(u.UNIVER_SHEET, e), !0;
45
+ if (t === p.UNIVER_SHEET)
46
+ return this._univerInstanceService.createUnit(p.UNIVER_SHEET, e), !0;
47
47
  throw new Error(
48
48
  `[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${t}.`
49
49
  );
@@ -63,12 +63,12 @@ let k = class {
63
63
  });
64
64
  }
65
65
  };
66
- k = Y([
67
- p(0, H),
68
- p(1, b),
69
- p(2, ee)
70
- ], k);
71
- function B(s) {
66
+ O = B([
67
+ m(0, V),
68
+ m(1, I),
69
+ m(2, te)
70
+ ], O);
71
+ function K(s) {
72
72
  const t = s;
73
73
  return new class {
74
74
  call(e, n) {
@@ -83,57 +83,54 @@ function B(s) {
83
83
  const r = t[e];
84
84
  if (typeof r == "function") {
85
85
  const i = n ? r.apply(t, n) : r.call(t);
86
- return ce(i) ? i : ae(i);
86
+ return ae(i) ? i : he(i);
87
87
  }
88
88
  throw new Error(`[RPC]: observable method not found for ${e}!`);
89
89
  }
90
90
  }();
91
91
  }
92
- function K(s) {
92
+ function J(s) {
93
93
  return new Proxy({}, {
94
94
  get(t, e) {
95
95
  if (e !== "dispose")
96
96
  return function(...n) {
97
- return ue(e) ? s.subscribe(e, n) : s.call(e, n);
97
+ return de(e) ? s.subscribe(e, n) : s.call(e, n);
98
98
  };
99
99
  }
100
100
  });
101
101
  }
102
- function ue(s) {
102
+ function de(s) {
103
103
  return s.endsWith("$");
104
104
  }
105
- class de extends W {
105
+ class pe extends T {
106
106
  constructor(e) {
107
107
  super();
108
- a(this, "_initialized", new ie(!1));
108
+ a(this, "_initialized", new oe(!1));
109
109
  a(this, "_lastRequestCounter", 0);
110
110
  a(this, "_pendingRequests", /* @__PURE__ */ new Map());
111
111
  this._protocol = e, this._protocol.send({
112
112
  type: 50
113
113
  /* REQUEST_INITIALIZATION */
114
- }), this._protocol.onMessage.pipe(v(this.dispose$)).subscribe((n) => this._onMessage(n));
114
+ }), this._protocol.onMessage.pipe(g(this.dispose$)).subscribe((n) => this._onMessage(n));
115
115
  }
116
116
  dispose() {
117
117
  this._pendingRequests.clear();
118
118
  }
119
119
  getChannel(e) {
120
- const n = this;
121
120
  return {
122
- call(r, i) {
123
- return n._disposed ? Promise.reject() : n._remoteCall(e, r, i);
124
- },
125
- subscribe(r, i) {
126
- if (n._disposed)
121
+ call: (n, r) => this._disposed ? Promise.reject(new Error("[ChannelClient]: client is disposed!")) : this._remoteCall(e, n, r),
122
+ subscribe: (n, r) => {
123
+ if (this._disposed)
127
124
  throw new Error("[ChannelClient]: client is disposed!");
128
- return n._remoteSubscribe(e, r, i);
125
+ return this._remoteSubscribe(e, n, r);
129
126
  }
130
127
  };
131
128
  }
132
129
  _whenReady() {
133
- return oe(
130
+ return ce(
134
131
  this._initialized.pipe(
135
- se((e) => e),
136
- re(1)
132
+ re((e) => e),
133
+ ie(1)
137
134
  )
138
135
  );
139
136
  }
@@ -141,16 +138,16 @@ class de extends W {
141
138
  return this._initialized.getValue() ? this._doRemoteCall(e, n, r) : this._whenReady().then(() => this._doRemoteCall(e, n, r));
142
139
  }
143
140
  _doRemoteCall(e, n, r) {
144
- const i = ++this._lastRequestCounter, h = { seq: i, type: 100, channelName: e, method: n, args: r }, c = this;
145
- return new Promise((w, E) => {
141
+ const i = ++this._lastRequestCounter, h = { seq: i, type: 100, channelName: e, method: n, args: r }, c = this._pendingRequests;
142
+ return new Promise((U, M) => {
146
143
  const l = {
147
- handle(P) {
148
- switch (P.type) {
144
+ handle(q) {
145
+ switch (q.type) {
149
146
  case 201:
150
- c._pendingRequests.delete(i), w(P.data);
147
+ c.delete(i), U(q.data);
151
148
  break;
152
149
  case 202:
153
- c._pendingRequests.delete(i), E(P.data);
150
+ c.delete(i), M(q.data);
154
151
  break;
155
152
  default:
156
153
  throw new Error("[ChannelClient]: unknown response type!");
@@ -161,11 +158,11 @@ class de extends W {
161
158
  });
162
159
  }
163
160
  _remoteSubscribe(e, n, r) {
164
- return new T((i) => {
161
+ return new D((i) => {
165
162
  let o = -1;
166
163
  const h = () => {
167
164
  o = ++this._lastRequestCounter;
168
- const w = { seq: o, type: 101, channelName: e, method: n, args: r }, E = {
165
+ const U = { seq: o, type: 101, channelName: e, method: n, args: r }, M = {
169
166
  handle(l) {
170
167
  switch (l.type) {
171
168
  case 300:
@@ -182,7 +179,7 @@ class de extends W {
182
179
  }
183
180
  }
184
181
  };
185
- this._pendingRequests.set(o, E), this._sendRequest(w);
182
+ this._pendingRequests.set(o, M), this._sendRequest(U);
186
183
  };
187
184
  return this._initialized.getValue() ? h() : this._whenReady().then(h), () => {
188
185
  if (o === -1)
@@ -219,12 +216,12 @@ class de extends W {
219
216
  }
220
217
  }
221
218
  }
222
- class pe extends W {
219
+ class ve extends T {
223
220
  constructor(e) {
224
221
  super();
225
222
  a(this, "_channels", /* @__PURE__ */ new Map());
226
223
  a(this, "_subscriptions", /* @__PURE__ */ new Map());
227
- this._protocol = e, this._protocol.onMessage.pipe(v(this.dispose$)).subscribe((n) => this._onRequest(n)), this._sendInitialize();
224
+ this._protocol = e, this._protocol.onMessage.pipe(g(this.dispose$)).subscribe((n) => this._onRequest(n)), this._sendInitialize();
228
225
  }
229
226
  dispose() {
230
227
  super.dispose(), this._subscriptions.clear(), this._channels.clear();
@@ -263,7 +260,7 @@ class pe extends W {
263
260
  throw new Error(`[ChannelServer]: Channel ${n} not found!`);
264
261
  h = i ? o.call(r, i) : o.call(r);
265
262
  } catch (c) {
266
- h = Promise.reject(c);
263
+ h = Promise.reject(c instanceof Error ? c : new Error(String(c)));
267
264
  }
268
265
  h.then((c) => {
269
266
  this._sendResponse({ seq: e.seq, type: 201, data: c });
@@ -308,12 +305,12 @@ class pe extends W {
308
305
  this._protocol.send(e);
309
306
  }
310
307
  }
311
- const I = O("IRPCChannelService");
312
- class J {
308
+ const P = W("IRPCChannelService");
309
+ class Q {
313
310
  constructor(t) {
314
311
  a(this, "_client");
315
312
  a(this, "_server");
316
- this._client = new de(t), this._server = new pe(t);
313
+ this._client = new pe(t), this._server = new ve(t);
317
314
  }
318
315
  dispose() {
319
316
  this._client.dispose(), this._server.dispose();
@@ -325,12 +322,12 @@ class J {
325
322
  this._server.registerChannel(t, e);
326
323
  }
327
324
  }
328
- var ve = Object.getOwnPropertyDescriptor, ge = (s, t, e, n) => {
329
- for (var r = n > 1 ? void 0 : n ? ve(t, e) : t, i = s.length - 1, o; i >= 0; i--)
325
+ var me = Object.getOwnPropertyDescriptor, ge = (s, t, e, n) => {
326
+ for (var r = n > 1 ? void 0 : n ? me(t, e) : t, i = s.length - 1, o; i >= 0; i--)
330
327
  (o = s[i]) && (r = o(r) || r);
331
328
  return r;
332
329
  }, _ = (s, t) => (e, n) => t(e, n, s);
333
- let f = class extends W {
330
+ let S = class extends T {
334
331
  constructor(t, e, n, r, i) {
335
332
  super();
336
333
  a(this, "_remoteInstanceService");
@@ -346,117 +343,123 @@ let f = class extends W {
346
343
  * sync other types of documents, you should manually call this method with that document's id.
347
344
  */
348
345
  syncUnit(t) {
349
- return this._syncingUnits.add(t), te(() => this._syncingUnits.delete(t));
346
+ return this._syncingUnits.add(t), ne(() => this._syncingUnits.delete(t));
350
347
  }
351
348
  _initRPCChannels() {
352
- this._rpcChannelService.registerChannel(D, B(this._remoteSyncService)), this._injector.add([
353
- m,
354
- { useFactory: () => K(this._rpcChannelService.requestChannel($)) }
355
- ]), this._remoteInstanceService = this._injector.get(m);
349
+ this._rpcChannelService.registerChannel($, K(this._remoteSyncService)), this._injector.add([
350
+ y,
351
+ // eslint-disable-next-line react/no-unnecessary-use-prefix
352
+ { useFactory: () => J(this._rpcChannelService.requestChannel(j)) }
353
+ ]), this._remoteInstanceService = this._injector.get(y);
356
354
  }
357
355
  _init() {
358
- this._univerInstanceService.getTypeOfUnitAdded$(u.UNIVER_SHEET).pipe(v(this.dispose$)).subscribe((t) => {
356
+ this._univerInstanceService.getTypeOfUnitAdded$(p.UNIVER_SHEET).pipe(g(this.dispose$)).subscribe((t) => {
359
357
  this._syncingUnits.add(t.getUnitId()), this._remoteInstanceService.createInstance({
360
358
  unitID: t.getUnitId(),
361
- type: u.UNIVER_SHEET,
359
+ type: p.UNIVER_SHEET,
362
360
  snapshot: t.getSnapshot()
363
361
  });
364
- }), this._univerInstanceService.getTypeOfUnitDisposed$(u.UNIVER_SHEET).pipe(v(this.dispose$)).subscribe((t) => {
362
+ }), this._univerInstanceService.getTypeOfUnitDisposed$(p.UNIVER_SHEET).pipe(g(this.dispose$)).subscribe((t) => {
365
363
  this._syncingUnits.delete(t.getUnitId()), this._remoteInstanceService.disposeInstance({
366
364
  unitID: t.getUnitId()
367
365
  });
368
366
  }), this.disposeWithMe(this._commandService.onCommandExecuted((t, e) => {
369
367
  const { type: n, params: r, id: i } = t, o = (r == null ? void 0 : r.unitId) || "";
370
- n === V.MUTATION && // only sync mutations to the worker thread
368
+ n === A.MUTATION && // only sync mutations to the worker thread
371
369
  (!o || this._syncingUnits.has(o)) && // do not sync mutations from the web worker back to the web worker
372
370
  !(e != null && e.fromSync) && // do not sync mutations those are not meant to be synced
373
371
  this._syncingMutations.has(i) && this._remoteInstanceService.syncMutation({ mutationInfo: t }, e);
374
372
  }));
375
373
  }
376
374
  };
377
- f = ge([
378
- _(0, C(R)),
379
- _(1, b),
380
- _(2, H),
381
- _(3, I),
382
- _(4, g)
383
- ], f);
384
- var me = Object.getOwnPropertyDescriptor, fe = (s, t, e, n) => {
385
- for (var r = n > 1 ? void 0 : n ? me(t, e) : t, i = s.length - 1, o; i >= 0; i--)
375
+ S = ge([
376
+ _(0, w(E)),
377
+ _(1, I),
378
+ _(2, V),
379
+ _(3, P),
380
+ _(4, f)
381
+ ], S);
382
+ var fe = Object.getOwnPropertyDescriptor, ye = (s, t, e, n) => {
383
+ for (var r = n > 1 ? void 0 : n ? fe(t, e) : t, i = s.length - 1, o; i >= 0; i--)
386
384
  (o = s[i]) && (r = o(r) || r);
387
385
  return r;
388
- }, d = (s, t) => (e, n) => t(e, n, s);
389
- let y = class extends ne {
386
+ }, v = (s, t) => (e, n) => t(e, n, s);
387
+ let C = class extends se {
390
388
  constructor(t, e, n, r) {
391
389
  super();
392
390
  a(this, "_remoteSyncService");
393
391
  this._injector = t, this._remoteInstanceService = e, this._commandService = n, this._rpcChannelService = r, this._initRPCChannels(), this._init();
394
392
  }
395
393
  _initRPCChannels() {
396
- this._rpcChannelService.registerChannel($, B(this._remoteInstanceService)), this._injector.add([
397
- g,
398
- { useFactory: () => K(this._rpcChannelService.requestChannel(D)) }
399
- ]), this._remoteSyncService = this._injector.get(g);
394
+ this._rpcChannelService.registerChannel(j, K(this._remoteInstanceService)), this._injector.add([
395
+ f,
396
+ // eslint-disable-next-line react/no-unnecessary-use-prefix
397
+ { useFactory: () => J(this._rpcChannelService.requestChannel($)) }
398
+ ]), this._remoteSyncService = this._injector.get(f);
400
399
  }
401
400
  _init() {
402
401
  this.disposeWithMe(
403
402
  // Mutations executed on the main thread should be synced to the worker thread.
404
403
  this._commandService.onCommandExecuted((t, e) => {
405
- t.type === V.MUTATION && !(e != null && e.fromSync) && this._remoteSyncService.syncMutation({
404
+ t.type === A.MUTATION && !(e != null && e.fromSync) && this._remoteSyncService.syncMutation({
406
405
  mutationInfo: t
407
406
  }, e);
408
407
  })
409
408
  );
410
409
  }
411
410
  };
412
- y = fe([
413
- d(0, C(R)),
414
- d(1, m),
415
- d(2, b),
416
- d(3, I)
417
- ], y);
418
- function ye() {
411
+ C = ye([
412
+ v(0, w(E)),
413
+ v(1, y),
414
+ v(2, I),
415
+ v(3, P)
416
+ ], C);
417
+ const Se = "@univerjs/rpc", Ce = "0.17.0", b = {
418
+ name: Se,
419
+ version: Ce
420
+ };
421
+ function be() {
419
422
  return {
420
423
  send(s) {
421
424
  postMessage(s);
422
425
  },
423
- onMessage: new T((s) => {
426
+ onMessage: new D((s) => {
424
427
  const t = (e) => {
425
428
  s.next(e.data);
426
429
  };
427
430
  return addEventListener("message", t), () => removeEventListener("message", t);
428
- }).pipe(G(1))
431
+ }).pipe(Y(1))
429
432
  };
430
433
  }
431
- function Se(s) {
434
+ function Re(s) {
432
435
  return {
433
436
  send(t) {
434
437
  s.postMessage(t);
435
438
  },
436
- onMessage: new T((t) => {
439
+ onMessage: new D((t) => {
437
440
  const e = (n) => {
438
441
  t.next(n.data);
439
442
  };
440
443
  return s.addEventListener("message", e), () => s.removeEventListener("message", e);
441
- }).pipe(G(1))
444
+ }).pipe(Y(1))
442
445
  };
443
446
  }
444
- var be = Object.getOwnPropertyDescriptor, Q = (s, t, e, n) => {
445
- for (var r = n > 1 ? void 0 : n ? be(t, e) : t, i = s.length - 1, o; i >= 0; i--)
447
+ var Ie = Object.getOwnPropertyDescriptor, X = (s, t, e, n) => {
448
+ for (var r = n > 1 ? void 0 : n ? Ie(t, e) : t, i = s.length - 1, o; i >= 0; i--)
446
449
  (o = s[i]) && (r = o(r) || r);
447
450
  return r;
448
- }, S = (s, t) => (e, n) => t(e, n, s), U;
449
- let x = (U = class extends z {
450
- constructor(t = j, e, n) {
451
+ }, R = (s, t) => (e, n) => t(e, n, s), u;
452
+ let L = (u = class extends F {
453
+ constructor(t = N, e, n) {
451
454
  super();
452
455
  a(this, "_internalWorker", null);
453
456
  this._config = t, this._injector = e, this._configService = n;
454
- const { ...r } = F(
457
+ const { ...r } = G(
455
458
  {},
456
- j,
459
+ N,
457
460
  this._config
458
461
  );
459
- this._configService.setConfig(he, r);
462
+ this._configService.setConfig(le, r);
460
463
  }
461
464
  dispose() {
462
465
  super.dispose(), this._internalWorker && (this._internalWorker.terminate(), this._internalWorker = null);
@@ -467,68 +470,70 @@ let x = (U = class extends z {
467
470
  throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");
468
471
  const e = t instanceof Worker ? t : new Worker(t);
469
472
  this._internalWorker = t instanceof Worker ? null : e;
470
- const n = Se(e);
473
+ const n = Re(e);
471
474
  [
472
475
  [
473
- I,
476
+ P,
474
477
  {
475
- useFactory: () => new J(n)
478
+ // eslint-disable-next-line react/no-unnecessary-use-prefix
479
+ useFactory: () => new Q(n)
476
480
  }
477
481
  ],
478
- [f],
479
- [g, { useClass: q }]
480
- ].forEach((i) => this._injector.add(i)), this._injector.get(f);
481
- }
482
- }, a(U, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN"), U);
483
- x = Q([
484
- S(1, C(R)),
485
- S(2, A)
486
- ], x);
487
- var M;
488
- let L = (M = class extends z {
489
- constructor(s = N, t, e) {
482
+ [S],
483
+ [f, { useClass: k }]
484
+ ].forEach((i) => this._injector.add(i)), this._injector.get(S);
485
+ }
486
+ }, a(u, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN"), a(u, "packageName", b.name), a(u, "version", b.version), u);
487
+ L = X([
488
+ R(1, w(E)),
489
+ R(2, z)
490
+ ], L);
491
+ var d;
492
+ let H = (d = class extends F {
493
+ constructor(s = x, t, e) {
490
494
  super(), this._config = s, this._injector = t, this._configService = e;
491
- const { ...n } = F(
495
+ const { ...n } = G(
492
496
  {},
493
- N,
497
+ x,
494
498
  this._config
495
499
  );
496
- this._configService.setConfig(le, n);
500
+ this._configService.setConfig(_e, n);
497
501
  }
498
502
  onStarting() {
499
503
  [
500
- [y],
504
+ [C],
501
505
  [
502
- I,
506
+ P,
503
507
  {
504
- useFactory: () => new J(ye())
508
+ // eslint-disable-next-line react/no-unnecessary-use-prefix
509
+ useFactory: () => new Q(be())
505
510
  }
506
511
  ],
507
- [m, { useClass: k }]
508
- ].forEach((s) => this._injector.add(s)), this._injector.get(y);
509
- }
510
- }, a(M, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN"), M);
511
- L = Q([
512
- S(1, C(R)),
513
- S(2, A)
514
- ], L);
512
+ [y, { useClass: O }]
513
+ ].forEach((s) => this._injector.add(s)), this._injector.get(C);
514
+ }
515
+ }, a(d, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN"), a(d, "packageName", b.name), a(d, "version", b.version), d);
516
+ H = X([
517
+ R(1, w(E)),
518
+ R(2, z)
519
+ ], H);
515
520
  export {
516
- de as ChannelClient,
517
- pe as ChannelServer,
518
- J as ChannelService,
519
- f as DataSyncPrimaryController,
520
- y as DataSyncReplicaController,
521
- I as IRPCChannelService,
522
- m as IRemoteInstanceService,
523
- g as IRemoteSyncService,
524
- he as PLUGIN_CONFIG_KEY_MAIN_THREAD,
525
- le as PLUGIN_CONFIG_KEY_WORKER_THREAD,
526
- $ as RemoteInstanceServiceName,
527
- q as RemoteSyncPrimaryService,
528
- D as RemoteSyncServiceName,
529
- x as UniverRPCMainThreadPlugin,
530
- L as UniverRPCWorkerThreadPlugin,
531
- k as WebWorkerRemoteInstanceService,
532
- B as fromModule,
533
- K as toModule
521
+ pe as ChannelClient,
522
+ ve as ChannelServer,
523
+ Q as ChannelService,
524
+ S as DataSyncPrimaryController,
525
+ C as DataSyncReplicaController,
526
+ P as IRPCChannelService,
527
+ y as IRemoteInstanceService,
528
+ f as IRemoteSyncService,
529
+ le as PLUGIN_CONFIG_KEY_MAIN_THREAD,
530
+ _e as PLUGIN_CONFIG_KEY_WORKER_THREAD,
531
+ j as RemoteInstanceServiceName,
532
+ k as RemoteSyncPrimaryService,
533
+ $ as RemoteSyncServiceName,
534
+ L as UniverRPCMainThreadPlugin,
535
+ H as UniverRPCWorkerThreadPlugin,
536
+ O as WebWorkerRemoteInstanceService,
537
+ K as fromModule,
538
+ J as toModule
534
539
  };
@@ -13,8 +13,8 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- export type { IUniverRPCMainThreadConfig, IUniverRPCWorkerThreadConfig } from './controllers/config.schema';
17
- export { PLUGIN_CONFIG_KEY_MAIN_THREAD, PLUGIN_CONFIG_KEY_WORKER_THREAD } from './controllers/config.schema';
16
+ export type { IUniverRPCMainThreadConfig, IUniverRPCWorkerThreadConfig } from './config/config';
17
+ export { PLUGIN_CONFIG_KEY_MAIN_THREAD, PLUGIN_CONFIG_KEY_WORKER_THREAD } from './config/config';
18
18
  export { DataSyncPrimaryController } from './controllers/data-sync/data-sync-primary.controller';
19
19
  export { DataSyncReplicaController } from './controllers/data-sync/data-sync-replica.controller';
20
20
  export { UniverRPCMainThreadPlugin, UniverRPCWorkerThreadPlugin, } from './plugin';
@@ -1,4 +1,4 @@
1
- import { IUniverRPCMainThreadConfig, IUniverRPCWorkerThreadConfig } from './controllers/config.schema';
1
+ import { IUniverRPCMainThreadConfig, IUniverRPCWorkerThreadConfig } from './config/config';
2
2
  import { IConfigService, Injector, Plugin } from '@univerjs/core';
3
3
  /**
4
4
  * This plugin is used to register the RPC services on the main thread. It
@@ -9,6 +9,8 @@ export declare class UniverRPCMainThreadPlugin extends Plugin {
9
9
  protected readonly _injector: Injector;
10
10
  private readonly _configService;
11
11
  static pluginName: string;
12
+ static packageName: string;
13
+ static version: string;
12
14
  private _internalWorker;
13
15
  constructor(_config: Partial<IUniverRPCMainThreadConfig> | undefined, _injector: Injector, _configService: IConfigService);
14
16
  dispose(): void;
@@ -22,6 +24,8 @@ export declare class UniverRPCWorkerThreadPlugin extends Plugin {
22
24
  protected readonly _injector: Injector;
23
25
  private readonly _configService;
24
26
  static pluginName: string;
27
+ static packageName: string;
28
+ static version: string;
25
29
  constructor(_config: Partial<IUniverRPCWorkerThreadConfig> | undefined, _injector: Injector, _configService: IConfigService);
26
30
  onStarting(): void;
27
31
  }
@@ -1,11 +1,12 @@
1
1
  import { IMessageProtocol } from '../rpc.service';
2
2
  /**
3
3
  * Generate an `IMessageProtocol` on the web worker.
4
+ * @returns A protocol wrapper around worker global messaging APIs.
4
5
  */
5
6
  export declare function createWebWorkerMessagePortOnWorker(): IMessageProtocol;
6
7
  /**
7
8
  * Generate an `IMessageProtocol` on the main thread side.
8
9
  * @param worker The Web Worker object
9
- * @returns
10
+ * @returns A protocol wrapper around the given worker messaging APIs.
10
11
  */
11
12
  export declare function createWebWorkerMessagePortOnMain(worker: Worker): IMessageProtocol;
@@ -28,7 +28,7 @@ export declare function fromModule(module: unknown): IChannel;
28
28
  * request the remote server by calling the channel.
29
29
  *
30
30
  * @param channel
31
- * @returns
31
+ * @returns A proxy object that forwards calls/subscriptions to the remote channel.
32
32
  */
33
33
  export declare function toModule<T extends object>(channel: IChannel): T;
34
34
  export interface IChannelClient {
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 J=Object.defineProperty;var Q=(r,a,u)=>a in r?J(r,a,{enumerable:!0,configurable:!0,writable:!0,value:u}):r[a]=u;var h=(r,a,u)=>Q(r,typeof a!="symbol"?a+"":a,u);var U,E;const k="rpc.main-thread.config",D={},q="rpc.worker-thread.config",O={};var H=Object.getOwnPropertyDescriptor,j=(c,s,e,n)=>{for(var t=n>1?void 0:n?H(s,e):s,i=c.length-1,o;i>=0;i--)(o=c[i])&&(t=o(t)||t);return t},g=(c,s)=>(e,n)=>s(e,n,c);const C="rpc.remote-sync.service",v=a.createIdentifier(C);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=j([g(0,a.ICommandService)],r.RemoteSyncPrimaryService);const f="univer.remote-instance-service",m=a.createIdentifier(f);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=j([g(0,a.IUniverInstanceService),g(1,a.ICommandService),g(2,a.ILogService)],r.WebWorkerRemoteInstanceService);function b(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 P(c){return new Proxy({},{get(s,e){if(e!=="dispose")return function(...n){return A(e)?c.subscribe(e,n):c.call(e,n)}}})}function A(c){return c.endsWith("$")}class N 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){const n=this;return{call(t,i){return n._disposed?Promise.reject():n._remoteCall(e,t,i)},subscribe(t,i){if(n._disposed)throw new Error("[ChannelClient]: client is disposed!");return n._remoteSubscribe(e,t,i)}}}_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;return new Promise((M,T)=>{const y={handle(W){switch(W.type){case 201:l._pendingRequests.delete(i),M(W.data);break;case 202:l._pendingRequests.delete(i),T(W.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(i,y),this._sendRequest(_)})}_remoteSubscribe(e,n,t){return new d.Observable(i=>{let o=-1;const _=()=>{o=++this._lastRequestCounter;const M={seq:o,type:101,channelName:e,method:n,args:t},T={handle(y){switch(y.type){case 300:i.next(y.data);break;case 301:i.error(y.data);break;case 302:i.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(o,T),this._sendRequest(M)};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 $ 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)}_.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 w{constructor(s){h(this,"_client");h(this,"_server");this._client=new N(s),this._server=new $(s)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(s){return this._client.getChannel(s)}registerChannel(s,e){this._server.registerChannel(s,e)}}var G=Object.getOwnPropertyDescriptor,V=(c,s,e,n)=>{for(var t=n>1?void 0:n?G(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(C,b(this._remoteSyncService)),this._injector.add([m,{useFactory:()=>P(this._rpcChannelService.requestChannel(f))}]),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=V([S(0,a.Inject(a.Injector)),S(1,a.ICommandService),S(2,a.IUniverInstanceService),S(3,p),S(4,v)],r.DataSyncPrimaryController);var F=Object.getOwnPropertyDescriptor,z=(c,s,e,n)=>{for(var t=n>1?void 0:n?F(s,e):s,i=c.length-1,o;i>=0;i--)(o=c[i])&&(t=o(t)||t);return t},R=(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(f,b(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>P(this._rpcChannelService.requestChannel(C))}]),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=z([R(0,a.Inject(a.Injector)),R(1,m),R(2,a.ICommandService),R(3,p)],r.DataSyncReplicaController);function K(){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 Y(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 B=Object.getOwnPropertyDescriptor,L=(c,s,e,n)=>{for(var t=n>1?void 0:n?B(s,e):s,i=c.length-1,o;i>=0;i--)(o=c[i])&&(t=o(t)||t);return t},I=(c,s)=>(e,n)=>s(e,n,c);r.UniverRPCMainThreadPlugin=(U=class extends a.Plugin{constructor(e=D,n,t){super();h(this,"_internalWorker",null);this._config=e,this._injector=n,this._configService=t;const{...i}=a.merge({},D,this._config);this._configService.setConfig(k,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=Y(n);[[p,{useFactory:()=>new w(t)}],[r.DataSyncPrimaryController],[v,{useClass:r.RemoteSyncPrimaryService}]].forEach(o=>this._injector.add(o)),this._injector.get(r.DataSyncPrimaryController)}},h(U,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),U),r.UniverRPCMainThreadPlugin=L([I(1,a.Inject(a.Injector)),I(2,a.IConfigService)],r.UniverRPCMainThreadPlugin),r.UniverRPCWorkerThreadPlugin=(E=class extends a.Plugin{constructor(s=O,e,n){super(),this._config=s,this._injector=e,this._configService=n;const{...t}=a.merge({},O,this._config);this._configService.setConfig(q,t)}onStarting(){[[r.DataSyncReplicaController],[p,{useFactory:()=>new w(K())}],[m,{useClass:r.WebWorkerRemoteInstanceService}]].forEach(s=>this._injector.add(s)),this._injector.get(r.DataSyncReplicaController)}},h(E,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),E),r.UniverRPCWorkerThreadPlugin=L([I(1,a.Inject(a.Injector)),I(2,a.IConfigService)],r.UniverRPCWorkerThreadPlugin),r.ChannelClient=N,r.ChannelServer=$,r.ChannelService=w,r.IRPCChannelService=p,r.IRemoteInstanceService=m,r.IRemoteSyncService=v,r.PLUGIN_CONFIG_KEY_MAIN_THREAD=k,r.PLUGIN_CONFIG_KEY_WORKER_THREAD=q,r.RemoteInstanceServiceName=f,r.RemoteSyncServiceName=C,r.fromModule=b,r.toModule=P,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})}));
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"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/rpc",
3
- "version": "0.16.1",
3
+ "version": "0.17.0",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -47,14 +47,14 @@
47
47
  "rxjs": ">=7.0.0"
48
48
  },
49
49
  "dependencies": {
50
- "@univerjs/core": "0.16.1"
50
+ "@univerjs/core": "0.17.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "rxjs": "^7.8.2",
54
54
  "typescript": "^5.9.3",
55
55
  "vite": "^7.3.1",
56
56
  "vitest": "^4.0.18",
57
- "@univerjs-infra/shared": "0.16.1"
57
+ "@univerjs-infra/shared": "0.17.0"
58
58
  },
59
59
  "scripts": {
60
60
  "test": "vitest run",