@univerjs/rpc 0.2.10 → 0.2.12

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 __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const core=require("@univerjs/core"),operators=require("rxjs/operators"),rxjs=require("rxjs");var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$3(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$3(target,key,result),result},"__decorateClass$3"),__decorateParam$3=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$3");const RemoteSyncServiceName="rpc.remote-sync.service",IRemoteSyncService=core.createIdentifier(RemoteSyncServiceName);var _a;exports.RemoteSyncPrimaryService=(_a=class{constructor(_commandService){this._commandService=_commandService}async syncMutation(params){return this._commandService.syncExecuteCommand(params.mutationInfo.id,params.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},__name(_a,"RemoteSyncPrimaryService"),_a);exports.RemoteSyncPrimaryService=__decorateClass$3([__decorateParam$3(0,core.ICommandService)],exports.RemoteSyncPrimaryService);const RemoteInstanceServiceName="univer.remote-instance-service",IRemoteInstanceService=core.createIdentifier(RemoteInstanceServiceName);var _a2;exports.WebWorkerRemoteInstanceService=(_a2=class{constructor(_univerInstanceService,_commandService,_logService){this._univerInstanceService=_univerInstanceService,this._commandService=_commandService,this._logService=_logService}whenReady(){return Promise.resolve(!0)}async syncMutation(params){return this._applyMutation(params.mutationInfo)}async createInstance(params){const{type,snapshot}=params;try{switch(type){case core.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(core.UniverInstanceType.UNIVER_SHEET,snapshot),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`)}}catch(err){throw err instanceof Error?err:new TypeError(`${err}`)}}async disposeInstance(params){return this._univerInstanceService.disposeUnit(params.unitID)}_applyMutation(mutationInfo){const{id,params:mutationParams}=mutationInfo;return this._commandService.syncExecuteCommand(id,mutationParams,{onlyLocal:!0,fromSync:!0})}},__name(_a2,"WebWorkerRemoteInstanceService"),_a2);exports.WebWorkerRemoteInstanceService=__decorateClass$3([__decorateParam$3(0,core.IUniverInstanceService),__decorateParam$3(1,core.ICommandService),__decorateParam$3(2,core.ILogService)],exports.WebWorkerRemoteInstanceService);function fromModule(module2){const handler=module2;return new class{call(method,args){const target=handler[method];if(typeof target=="function"){let res=target.apply(handler,[args]);return res instanceof Promise||(res=Promise.resolve(res)),res}throw new Error(`[RPC]: method not found for ${method}!`)}subscribe(eventMethod,args){const target=handler[eventMethod];if(typeof target=="function"){const res=target.apply(handler,args);return rxjs.isObservable(res)?res:rxjs.of(res)}throw new Error(`[RPC]: observable method not found for ${eventMethod}!`)}}}__name(fromModule,"fromModule");function toModule(channel){return new Proxy({},{get(_,propKey){if(propKey!=="dispose")return function(...args){return propertyIsEventSource(propKey)?channel.subscribe(propKey,args[0]):channel.call(propKey,args[0])}}})}__name(toModule,"toModule");function propertyIsEventSource(name){return name.endsWith("$")}__name(propertyIsEventSource,"propertyIsEventSource");const _ChannelClient=class _ChannelClient extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_initialized",new rxjs.BehaviorSubject(!1));__publicField(this,"_lastRequestCounter",0);__publicField(this,"_pendingRequests",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onMessage(message))}dispose(){this._pendingRequests.clear()}getChannel(channelName){const self=this;return{call(method,args){return self._disposed?Promise.reject():self._remoteCall(channelName,method,args)},subscribe(eventMethod,args){if(self._disposed)throw new Error("[ChannelClient]: client is disposed!");return self._remoteSubscribe(channelName,eventMethod,args)}}}_whenReady(){return rxjs.firstValueFrom(this._initialized.pipe(operators.filter(v=>v),operators.take(1)))}async _remoteCall(channelName,method,args){await this._whenReady();const sequence=++this._lastRequestCounter,request={seq:sequence,type:100,channelName,method,args},client=this;return new Promise((resolve,reject)=>{const responseHandler={handle(response){switch(response.type){case 201:client._pendingRequests.delete(sequence),resolve(response.data);break;case 202:client._pendingRequests.delete(sequence),reject(response.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)})}_remoteSubscribe(channelName,method,args){return new rxjs.Observable(subscriber=>{let sequence=-1;return this._whenReady().then(()=>{sequence=++this._lastRequestCounter;const request={seq:sequence,type:101,channelName,method,args},responseHandler={handle(response){switch(response.type){case 300:subscriber.next(response.data);break;case 301:subscriber.error(response.data);break;case 302:subscriber.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)}),()=>{if(sequence===-1)return;const cancelSubscriptionRequest={type:102,seq:sequence,channelName,method};this._sendRequest(cancelSubscriptionRequest)}})}_sendRequest(request){this._protocol.send(request)}_onMessage(response){var _a7;switch(response.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(_a7=this._pendingRequests.get(response.seq))==null||_a7.handle(response);break}}};__name(_ChannelClient,"ChannelClient");let ChannelClient=_ChannelClient;const _ChannelServer=class _ChannelServer extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_channels",new Map);__publicField(this,"_subscriptions",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onRequest(message)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(channelName,channel){this._channels.set(channelName,channel)}_onRequest(request){switch(request.type){case 100:this._onMethodCall(request);break;case 101:this._onSubscribe(request);break;case 102:this._onUnsubscribe(request);break}}_onMethodCall(request){const{channelName,method,args}=request,channel=this._channels.get(channelName);let promise;try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);promise=channel.call(method,args)}catch(err){promise=Promise.reject(err)}promise.then(data=>{this._sendResponse({seq:request.seq,type:201,data})}).catch(err=>{err instanceof Error?this._sendResponse({seq:request.seq,type:202,data:err.message}):this._sendResponse({seq:request.seq,type:202,data:String(err)})})}_onSubscribe(request){const{channelName,seq}=request,channel=this._channels.get(channelName);try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);const subscription=channel.subscribe(request.method,request.args).subscribe({next:__name(data=>{this._sendResponse({seq,type:300,data})},"next"),error:__name(err=>{this._sendResponse({seq,type:301,data:err.message}),this._sendResponse({seq,type:302})},"error"),complete:__name(()=>{this._sendResponse({seq,type:302})},"complete")});this._subscriptions.set(request.seq,subscription)}catch(err){err instanceof Error?this._sendResponse({seq:request.seq,type:301,data:err.message}):this._sendResponse({seq:request.seq,type:301,data:String(err)})}}_onUnsubscribe(request){const subscription=this._subscriptions.get(request.seq);subscription&&(subscription.unsubscribe(),this._subscriptions.delete(request.seq))}_sendResponse(response){this._protocol.send(response)}};__name(_ChannelServer,"ChannelServer");let ChannelServer=_ChannelServer;const IRPCChannelService=core.createIdentifier("IRPCChannelService"),_ChannelService=class _ChannelService{constructor(_messageProtocol){__publicField(this,"_client");__publicField(this,"_server");this._client=new ChannelClient(_messageProtocol),this._server=new ChannelServer(_messageProtocol)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(name){return this._client.getChannel(name)}registerChannel(name,channel){this._server.registerChannel(name,channel)}};__name(_ChannelService,"ChannelService");let ChannelService=_ChannelService;var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$2(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$2(target,key,result),result},"__decorateClass$2"),__decorateParam$2=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$2"),_a3;exports.DataSyncPrimaryController=(_a3=class extends core.RxDisposable{constructor(_injector,_commandService,_univerInstanceService,_rpcChannelService,_remoteSyncService){super();__publicField(this,"_remoteInstanceService");__publicField(this,"_syncingUnits",new Set);__publicField(this,"_syncingMutations",new Set);this._injector=_injector,this._commandService=_commandService,this._univerInstanceService=_univerInstanceService,this._rpcChannelService=_rpcChannelService,this._remoteSyncService=_remoteSyncService,this._initRPCChannels(),this._init()}registerSyncingMutations(mutation){this._syncingMutations.add(mutation.id)}syncUnit(unitId){return this._syncingUnits.add(unitId),core.toDisposable(()=>this._syncingUnits.delete(unitId))}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteSyncServiceName,fromModule(this._remoteSyncService)),this._injector.add([IRemoteInstanceService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)),"useFactory")}]),this._remoteInstanceService=this._injector.get(IRemoteInstanceService)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(sheet=>{this._syncingUnits.add(sheet.getUnitId()),this._remoteInstanceService.createInstance({unitID:sheet.getUnitId(),type:core.UniverInstanceType.UNIVER_SHEET,snapshot:sheet.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(workbook=>{this._syncingUnits.delete(workbook.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:workbook.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{const{type,params,id}=commandInfo,unitId=(params==null?void 0:params.unitId)||"";type===core.CommandType.MUTATION&&(!unitId||this._syncingUnits.has(unitId))&&!(options!=null&&options.fromSync)&&this._syncingMutations.has(id)&&this._remoteInstanceService.syncMutation({mutationInfo:commandInfo})}))}},__name(_a3,"DataSyncPrimaryController"),_a3);exports.DataSyncPrimaryController=__decorateClass$2([core.OnLifecycle(core.LifecycleStages.Starting,exports.DataSyncPrimaryController),__decorateParam$2(0,core.Inject(core.Injector)),__decorateParam$2(1,core.ICommandService),__decorateParam$2(2,core.IUniverInstanceService),__decorateParam$2(3,IRPCChannelService),__decorateParam$2(4,IRemoteSyncService)],exports.DataSyncPrimaryController);var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1"),_a4;exports.DataSyncReplicaController=(_a4=class extends core.Disposable{constructor(_injector,_remoteInstanceService,_commandService,_rpcChannelService){super();__publicField(this,"_remoteSyncService");this._injector=_injector,this._remoteInstanceService=_remoteInstanceService,this._commandService=_commandService,this._rpcChannelService=_rpcChannelService,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteInstanceServiceName,fromModule(this._remoteInstanceService)),this._injector.add([IRemoteSyncService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteSyncServiceName)),"useFactory")}]),this._remoteSyncService=this._injector.get(IRemoteSyncService)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{commandInfo.type===core.CommandType.MUTATION&&!(options!=null&&options.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:commandInfo})}))}},__name(_a4,"DataSyncReplicaController"),_a4);exports.DataSyncReplicaController=__decorateClass$1([core.OnLifecycle(core.LifecycleStages.Starting,exports.DataSyncReplicaController),__decorateParam$1(0,core.Inject(core.Injector)),__decorateParam$1(1,IRemoteInstanceService),__decorateParam$1(2,core.ICommandService),__decorateParam$1(3,IRPCChannelService)],exports.DataSyncReplicaController);function createWebWorkerMessagePortOnWorker(){return{send(message){postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return addEventListener("message",handler),()=>removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnWorker,"createWebWorkerMessagePortOnWorker");function createWebWorkerMessagePortOnMain(worker){return{send(message){worker.postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return worker.addEventListener("message",handler),()=>worker.removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnMain,"createWebWorkerMessagePortOnMain");var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam"),_a5;exports.UniverRPCMainThreadPlugin=(_a5=class extends core.Plugin{constructor(_config,_injector){super();__publicField(this,"_internalWorker",null);this._config=_config,this._injector=_injector}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL}=this._config,worker=workerURL instanceof Worker?workerURL:new Worker(workerURL);this._internalWorker=workerURL instanceof Worker?null:worker;const messageProtocol=createWebWorkerMessagePortOnMain(worker);[[IRPCChannelService,{useFactory:__name(()=>new ChannelService(messageProtocol),"useFactory")}],[exports.DataSyncPrimaryController],[IRemoteSyncService,{useClass:exports.RemoteSyncPrimaryService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports.DataSyncPrimaryController)}},__name(_a5,"UniverRPCMainThreadPlugin"),__publicField(_a5,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),_a5);exports.UniverRPCMainThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports.UniverRPCMainThreadPlugin);var _a6;exports.UniverRPCWorkerThreadPlugin=(_a6=class extends core.Plugin{constructor(_config,_injector){super(),this._config=_config,this._injector=_injector}onStarting(){[[exports.DataSyncReplicaController],[IRPCChannelService,{useFactory:__name(()=>new ChannelService(createWebWorkerMessagePortOnWorker()),"useFactory")}],[IRemoteInstanceService,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports.DataSyncReplicaController)}},__name(_a6,"UniverRPCWorkerThreadPlugin"),__publicField(_a6,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),_a6);exports.UniverRPCWorkerThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=ChannelClient;exports.ChannelServer=ChannelServer;exports.ChannelService=ChannelService;exports.IRPCChannelService=IRPCChannelService;exports.IRemoteInstanceService=IRemoteInstanceService;exports.IRemoteSyncService=IRemoteSyncService;exports.RemoteInstanceServiceName=RemoteInstanceServiceName;exports.RemoteSyncServiceName=RemoteSyncServiceName;exports.fromModule=fromModule;exports.toModule=toModule;
1
+ "use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const core=require("@univerjs/core"),operators=require("rxjs/operators"),rxjs=require("rxjs");var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$3(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$3(target,key,result),result},"__decorateClass$3"),__decorateParam$3=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$3");const RemoteSyncServiceName="rpc.remote-sync.service",IRemoteSyncService=core.createIdentifier(RemoteSyncServiceName);var _a;exports.RemoteSyncPrimaryService=(_a=class{constructor(_commandService){this._commandService=_commandService}async syncMutation(params){return this._commandService.syncExecuteCommand(params.mutationInfo.id,params.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},__name(_a,"RemoteSyncPrimaryService"),_a);exports.RemoteSyncPrimaryService=__decorateClass$3([__decorateParam$3(0,core.ICommandService)],exports.RemoteSyncPrimaryService);const RemoteInstanceServiceName="univer.remote-instance-service",IRemoteInstanceService=core.createIdentifier(RemoteInstanceServiceName);var _a2;exports.WebWorkerRemoteInstanceService=(_a2=class{constructor(_univerInstanceService,_commandService,_logService){this._univerInstanceService=_univerInstanceService,this._commandService=_commandService,this._logService=_logService}whenReady(){return Promise.resolve(!0)}async syncMutation(params){return this._applyMutation(params.mutationInfo)}async createInstance(params){const{type,snapshot}=params;try{switch(type){case core.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(core.UniverInstanceType.UNIVER_SHEET,snapshot),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`)}}catch(err){throw err instanceof Error?err:new TypeError(`${err}`)}}async disposeInstance(params){return this._univerInstanceService.disposeUnit(params.unitID)}_applyMutation(mutationInfo){const{id,params:mutationParams}=mutationInfo;return this._commandService.syncExecuteCommand(id,mutationParams,{onlyLocal:!0,fromSync:!0})}},__name(_a2,"WebWorkerRemoteInstanceService"),_a2);exports.WebWorkerRemoteInstanceService=__decorateClass$3([__decorateParam$3(0,core.IUniverInstanceService),__decorateParam$3(1,core.ICommandService),__decorateParam$3(2,core.ILogService)],exports.WebWorkerRemoteInstanceService);function fromModule(module2){const handler=module2;return new class{call(method,args){const target=handler[method];if(typeof target=="function"){let res=target.apply(handler,[args]);return res instanceof Promise||(res=Promise.resolve(res)),res}throw new Error(`[RPC]: method not found for ${method}!`)}subscribe(eventMethod,args){const target=handler[eventMethod];if(typeof target=="function"){const res=target.apply(handler,args);return rxjs.isObservable(res)?res:rxjs.of(res)}throw new Error(`[RPC]: observable method not found for ${eventMethod}!`)}}}__name(fromModule,"fromModule");function toModule(channel){return new Proxy({},{get(_,propKey){if(propKey!=="dispose")return function(...args){return propertyIsEventSource(propKey)?channel.subscribe(propKey,args[0]):channel.call(propKey,args[0])}}})}__name(toModule,"toModule");function propertyIsEventSource(name){return name.endsWith("$")}__name(propertyIsEventSource,"propertyIsEventSource");const _ChannelClient=class _ChannelClient extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_initialized",new rxjs.BehaviorSubject(!1));__publicField(this,"_lastRequestCounter",0);__publicField(this,"_pendingRequests",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onMessage(message))}dispose(){this._pendingRequests.clear()}getChannel(channelName){const self=this;return{call(method,args){return self._disposed?Promise.reject():self._remoteCall(channelName,method,args)},subscribe(eventMethod,args){if(self._disposed)throw new Error("[ChannelClient]: client is disposed!");return self._remoteSubscribe(channelName,eventMethod,args)}}}_whenReady(){return rxjs.firstValueFrom(this._initialized.pipe(operators.filter(v=>v),operators.take(1)))}async _remoteCall(channelName,method,args){await this._whenReady();const sequence=++this._lastRequestCounter,request={seq:sequence,type:100,channelName,method,args},client=this;return new Promise((resolve,reject)=>{const responseHandler={handle(response){switch(response.type){case 201:client._pendingRequests.delete(sequence),resolve(response.data);break;case 202:client._pendingRequests.delete(sequence),reject(response.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)})}_remoteSubscribe(channelName,method,args){return new rxjs.Observable(subscriber=>{let sequence=-1;return this._whenReady().then(()=>{sequence=++this._lastRequestCounter;const request={seq:sequence,type:101,channelName,method,args},responseHandler={handle(response){switch(response.type){case 300:subscriber.next(response.data);break;case 301:subscriber.error(response.data);break;case 302:subscriber.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)}),()=>{if(sequence===-1)return;const cancelSubscriptionRequest={type:102,seq:sequence,channelName,method};this._sendRequest(cancelSubscriptionRequest)}})}_sendRequest(request){this._protocol.send(request)}_onMessage(response){var _a7;switch(response.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(_a7=this._pendingRequests.get(response.seq))==null||_a7.handle(response);break}}};__name(_ChannelClient,"ChannelClient");let ChannelClient=_ChannelClient;const _ChannelServer=class _ChannelServer extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_channels",new Map);__publicField(this,"_subscriptions",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onRequest(message)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(channelName,channel){this._channels.set(channelName,channel)}_onRequest(request){switch(request.type){case 100:this._onMethodCall(request);break;case 101:this._onSubscribe(request);break;case 102:this._onUnsubscribe(request);break}}_onMethodCall(request){const{channelName,method,args}=request,channel=this._channels.get(channelName);let promise;try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);promise=channel.call(method,args)}catch(err){promise=Promise.reject(err)}promise.then(data=>{this._sendResponse({seq:request.seq,type:201,data})}).catch(err=>{err instanceof Error?this._sendResponse({seq:request.seq,type:202,data:err.message}):this._sendResponse({seq:request.seq,type:202,data:String(err)})})}_onSubscribe(request){const{channelName,seq}=request,channel=this._channels.get(channelName);try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);const subscription=channel.subscribe(request.method,request.args).subscribe({next:__name(data=>{this._sendResponse({seq,type:300,data})},"next"),error:__name(err=>{this._sendResponse({seq,type:301,data:err.message}),this._sendResponse({seq,type:302})},"error"),complete:__name(()=>{this._sendResponse({seq,type:302})},"complete")});this._subscriptions.set(request.seq,subscription)}catch(err){err instanceof Error?this._sendResponse({seq:request.seq,type:301,data:err.message}):this._sendResponse({seq:request.seq,type:301,data:String(err)})}}_onUnsubscribe(request){const subscription=this._subscriptions.get(request.seq);subscription&&(subscription.unsubscribe(),this._subscriptions.delete(request.seq))}_sendResponse(response){this._protocol.send(response)}};__name(_ChannelServer,"ChannelServer");let ChannelServer=_ChannelServer;const IRPCChannelService=core.createIdentifier("IRPCChannelService"),_ChannelService=class _ChannelService{constructor(_messageProtocol){__publicField(this,"_client");__publicField(this,"_server");this._client=new ChannelClient(_messageProtocol),this._server=new ChannelServer(_messageProtocol)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(name){return this._client.getChannel(name)}registerChannel(name,channel){this._server.registerChannel(name,channel)}};__name(_ChannelService,"ChannelService");let ChannelService=_ChannelService;var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$2(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$2(target,key,result),result},"__decorateClass$2"),__decorateParam$2=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$2"),_a3;exports.DataSyncPrimaryController=(_a3=class extends core.RxDisposable{constructor(_injector,_commandService,_univerInstanceService,_rpcChannelService,_remoteSyncService){super();__publicField(this,"_remoteInstanceService");__publicField(this,"_syncingUnits",new Set);__publicField(this,"_syncingMutations",new Set);this._injector=_injector,this._commandService=_commandService,this._univerInstanceService=_univerInstanceService,this._rpcChannelService=_rpcChannelService,this._remoteSyncService=_remoteSyncService,this._initRPCChannels(),this._init()}registerSyncingMutations(mutation){this._syncingMutations.add(mutation.id)}syncUnit(unitId){return this._syncingUnits.add(unitId),core.toDisposable(()=>this._syncingUnits.delete(unitId))}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteSyncServiceName,fromModule(this._remoteSyncService)),this._injector.add([IRemoteInstanceService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)),"useFactory")}]),this._remoteInstanceService=this._injector.get(IRemoteInstanceService)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(sheet=>{this._syncingUnits.add(sheet.getUnitId()),this._remoteInstanceService.createInstance({unitID:sheet.getUnitId(),type:core.UniverInstanceType.UNIVER_SHEET,snapshot:sheet.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(workbook=>{this._syncingUnits.delete(workbook.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:workbook.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{const{type,params,id}=commandInfo,unitId=(params==null?void 0:params.unitId)||"";type===core.CommandType.MUTATION&&(!unitId||this._syncingUnits.has(unitId))&&!(options!=null&&options.fromSync)&&this._syncingMutations.has(id)&&this._remoteInstanceService.syncMutation({mutationInfo:commandInfo})}))}},__name(_a3,"DataSyncPrimaryController"),_a3);exports.DataSyncPrimaryController=__decorateClass$2([core.OnLifecycle(core.LifecycleStages.Starting,exports.DataSyncPrimaryController),__decorateParam$2(0,core.Inject(core.Injector)),__decorateParam$2(1,core.ICommandService),__decorateParam$2(2,core.IUniverInstanceService),__decorateParam$2(3,IRPCChannelService),__decorateParam$2(4,IRemoteSyncService)],exports.DataSyncPrimaryController);var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1"),_a4;exports.DataSyncReplicaController=(_a4=class extends core.Disposable{constructor(_injector,_remoteInstanceService,_commandService,_rpcChannelService){super();__publicField(this,"_remoteSyncService");this._injector=_injector,this._remoteInstanceService=_remoteInstanceService,this._commandService=_commandService,this._rpcChannelService=_rpcChannelService,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteInstanceServiceName,fromModule(this._remoteInstanceService)),this._injector.add([IRemoteSyncService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteSyncServiceName)),"useFactory")}]),this._remoteSyncService=this._injector.get(IRemoteSyncService)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{commandInfo.type===core.CommandType.MUTATION&&!(options!=null&&options.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:commandInfo})}))}},__name(_a4,"DataSyncReplicaController"),_a4);exports.DataSyncReplicaController=__decorateClass$1([core.OnLifecycle(core.LifecycleStages.Starting,exports.DataSyncReplicaController),__decorateParam$1(0,core.Inject(core.Injector)),__decorateParam$1(1,IRemoteInstanceService),__decorateParam$1(2,core.ICommandService),__decorateParam$1(3,IRPCChannelService)],exports.DataSyncReplicaController);function createWebWorkerMessagePortOnWorker(){return{send(message){postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return addEventListener("message",handler),()=>removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnWorker,"createWebWorkerMessagePortOnWorker");function createWebWorkerMessagePortOnMain(worker){return{send(message){worker.postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return worker.addEventListener("message",handler),()=>worker.removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnMain,"createWebWorkerMessagePortOnMain");const PLUGIN_CONFIG_KEY_MAIN_THREAD="rpc.main-thread.config",defaultPluginMainThreadConfig={},PLUGIN_CONFIG_KEY_WORKER_THREAD="rpc.worker-thread.config",defaultPluginWorkerThreadConfig={};var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam"),_a5;exports.UniverRPCMainThreadPlugin=(_a5=class extends core.Plugin{constructor(_config=defaultPluginMainThreadConfig,_injector,_configService){super();__publicField(this,"_internalWorker",null);this._config=_config,this._injector=_injector,this._configService=_configService;const{...rest}=this._config;this._configService.setConfig(PLUGIN_CONFIG_KEY_MAIN_THREAD,rest)}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL}=this._config;if(!workerURL)throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");const worker=workerURL instanceof Worker?workerURL:new Worker(workerURL);this._internalWorker=workerURL instanceof Worker?null:worker;const messageProtocol=createWebWorkerMessagePortOnMain(worker);[[IRPCChannelService,{useFactory:__name(()=>new ChannelService(messageProtocol),"useFactory")}],[exports.DataSyncPrimaryController],[IRemoteSyncService,{useClass:exports.RemoteSyncPrimaryService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports.DataSyncPrimaryController)}},__name(_a5,"UniverRPCMainThreadPlugin"),__publicField(_a5,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),_a5);exports.UniverRPCMainThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector)),__decorateParam(2,core.IConfigService)],exports.UniverRPCMainThreadPlugin);var _a6;exports.UniverRPCWorkerThreadPlugin=(_a6=class extends core.Plugin{constructor(_config=defaultPluginWorkerThreadConfig,_injector,_configService){super(),this._config=_config,this._injector=_injector,this._configService=_configService;const{...rest}=this._config;this._configService.setConfig(PLUGIN_CONFIG_KEY_WORKER_THREAD,rest)}onStarting(){[[exports.DataSyncReplicaController],[IRPCChannelService,{useFactory:__name(()=>new ChannelService(createWebWorkerMessagePortOnWorker()),"useFactory")}],[IRemoteInstanceService,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports.DataSyncReplicaController)}},__name(_a6,"UniverRPCWorkerThreadPlugin"),__publicField(_a6,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),_a6);exports.UniverRPCWorkerThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector)),__decorateParam(2,core.IConfigService)],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=ChannelClient;exports.ChannelServer=ChannelServer;exports.ChannelService=ChannelService;exports.IRPCChannelService=IRPCChannelService;exports.IRemoteInstanceService=IRemoteInstanceService;exports.IRemoteSyncService=IRemoteSyncService;exports.RemoteInstanceServiceName=RemoteInstanceServiceName;exports.RemoteSyncServiceName=RemoteSyncServiceName;exports.fromModule=fromModule;exports.toModule=toModule;
package/lib/es/index.js CHANGED
@@ -2,7 +2,7 @@ var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value;
3
3
  var __name = (target, value) => __defProp(target, "name", { value, configurable: !0 });
4
4
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
5
- import { createIdentifier, UniverInstanceType, ICommandService, IUniverInstanceService, ILogService, RxDisposable, OnLifecycle, LifecycleStages, Inject, Injector, toDisposable, CommandType, Disposable, Plugin } from "@univerjs/core";
5
+ import { createIdentifier, UniverInstanceType, ICommandService, IUniverInstanceService, ILogService, RxDisposable, OnLifecycle, LifecycleStages, Inject, Injector, toDisposable, CommandType, Disposable, Plugin, IConfigService } from "@univerjs/core";
6
6
  import { takeUntil, filter, take } from "rxjs/operators";
7
7
  import { isObservable, of, BehaviorSubject, firstValueFrom, Observable, shareReplay } from "rxjs";
8
8
  var __defProp$3 = Object.defineProperty, __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor, __decorateClass$3 = /* @__PURE__ */ __name((decorators, target, key, kind) => {
@@ -439,22 +439,28 @@ function createWebWorkerMessagePortOnMain(worker) {
439
439
  };
440
440
  }
441
441
  __name(createWebWorkerMessagePortOnMain, "createWebWorkerMessagePortOnMain");
442
+ const PLUGIN_CONFIG_KEY_MAIN_THREAD = "rpc.main-thread.config", defaultPluginMainThreadConfig = {}, PLUGIN_CONFIG_KEY_WORKER_THREAD = "rpc.worker-thread.config", defaultPluginWorkerThreadConfig = {};
442
443
  var __defProp2 = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = /* @__PURE__ */ __name((decorators, target, key, kind) => {
443
444
  for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
444
445
  (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
445
446
  return kind && result && __defProp2(target, key, result), result;
446
447
  }, "__decorateClass"), __decorateParam = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam"), _a5;
447
448
  let UniverRPCMainThreadPlugin = (_a5 = class extends Plugin {
448
- constructor(_config, _injector) {
449
+ constructor(_config = defaultPluginMainThreadConfig, _injector, _configService) {
449
450
  super();
450
451
  __publicField(this, "_internalWorker", null);
451
- this._config = _config, this._injector = _injector;
452
+ this._config = _config, this._injector = _injector, this._configService = _configService;
453
+ const { ...rest } = this._config;
454
+ this._configService.setConfig(PLUGIN_CONFIG_KEY_MAIN_THREAD, rest);
452
455
  }
453
456
  dispose() {
454
457
  super.dispose(), this._internalWorker && (this._internalWorker.terminate(), this._internalWorker = null);
455
458
  }
456
459
  onStarting() {
457
- const { workerURL } = this._config, worker = workerURL instanceof Worker ? workerURL : new Worker(workerURL);
460
+ const { workerURL } = this._config;
461
+ if (!workerURL)
462
+ throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");
463
+ const worker = workerURL instanceof Worker ? workerURL : new Worker(workerURL);
458
464
  this._internalWorker = workerURL instanceof Worker ? null : worker;
459
465
  const messageProtocol = createWebWorkerMessagePortOnMain(worker);
460
466
  [
@@ -470,12 +476,15 @@ let UniverRPCMainThreadPlugin = (_a5 = class extends Plugin {
470
476
  }
471
477
  }, __name(_a5, "UniverRPCMainThreadPlugin"), __publicField(_a5, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN"), _a5);
472
478
  UniverRPCMainThreadPlugin = __decorateClass([
473
- __decorateParam(1, Inject(Injector))
479
+ __decorateParam(1, Inject(Injector)),
480
+ __decorateParam(2, IConfigService)
474
481
  ], UniverRPCMainThreadPlugin);
475
482
  var _a6;
476
483
  let UniverRPCWorkerThreadPlugin = (_a6 = class extends Plugin {
477
- constructor(_config, _injector) {
478
- super(), this._config = _config, this._injector = _injector;
484
+ constructor(_config = defaultPluginWorkerThreadConfig, _injector, _configService) {
485
+ super(), this._config = _config, this._injector = _injector, this._configService = _configService;
486
+ const { ...rest } = this._config;
487
+ this._configService.setConfig(PLUGIN_CONFIG_KEY_WORKER_THREAD, rest);
479
488
  }
480
489
  onStarting() {
481
490
  [
@@ -491,7 +500,8 @@ let UniverRPCWorkerThreadPlugin = (_a6 = class extends Plugin {
491
500
  }
492
501
  }, __name(_a6, "UniverRPCWorkerThreadPlugin"), __publicField(_a6, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN"), _a6);
493
502
  UniverRPCWorkerThreadPlugin = __decorateClass([
494
- __decorateParam(1, Inject(Injector))
503
+ __decorateParam(1, Inject(Injector)),
504
+ __decorateParam(2, IConfigService)
495
505
  ], UniverRPCWorkerThreadPlugin);
496
506
  export {
497
507
  ChannelClient,
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export declare const PLUGIN_CONFIG_KEY_MAIN_THREAD = "rpc.main-thread.config";
17
+ export declare const configSymbolMainThread: unique symbol;
18
+ export interface IUniverRPCMainThreadConfig {
19
+ workerURL?: string | URL | Worker;
20
+ }
21
+ export declare const defaultPluginMainThreadConfig: IUniverRPCMainThreadConfig;
22
+ export declare const PLUGIN_CONFIG_KEY_WORKER_THREAD = "rpc.worker-thread.config";
23
+ export declare const configSymbolWorkerThread: unique symbol;
24
+ export interface IUniverRPCWorkerThreadConfig {
25
+ }
26
+ export declare const defaultPluginWorkerThreadConfig: IUniverRPCWorkerThreadConfig;
@@ -13,10 +13,11 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- export { type IUniverRPCMainThreadConfig, UniverRPCMainThreadPlugin, UniverRPCWorkerThreadPlugin, } from './plugin';
16
+ export { UniverRPCMainThreadPlugin, UniverRPCWorkerThreadPlugin, } from './plugin';
17
17
  export { DataSyncReplicaController } from './controllers/data-sync/data-sync-replica.controller';
18
18
  export { DataSyncPrimaryController } from './controllers/data-sync/data-sync-primary.controller';
19
19
  export { IRemoteInstanceService, WebWorkerRemoteInstanceService, RemoteInstanceServiceName, RemoteSyncPrimaryService, RemoteSyncServiceName, } from './services/remote-instance/remote-instance.service';
20
20
  export { ChannelService, IRPCChannelService } from './services/rpc/channel.service';
21
21
  export { ChannelClient, ChannelServer, type IMessageProtocol, fromModule, toModule } from './services/rpc/rpc.service';
22
22
  export { IRemoteSyncService } from './services/remote-instance/remote-instance.service';
23
+ export type { IUniverRPCMainThreadConfig, IUniverRPCWorkerThreadConfig } from './controllers/config.schema';
@@ -1,7 +1,5 @@
1
- import { Injector, Plugin } from '@univerjs/core';
2
- export interface IUniverRPCMainThreadConfig {
3
- workerURL: string | URL | Worker;
4
- }
1
+ import { IConfigService, Injector, Plugin } from '@univerjs/core';
2
+ import { IUniverRPCMainThreadConfig, IUniverRPCWorkerThreadConfig } from './controllers/config.schema';
5
3
  /**
6
4
  * This plugin is used to register the RPC services on the main thread. It
7
5
  * is also responsible for booting up the Web Worker instance of Univer.
@@ -9,9 +7,10 @@ export interface IUniverRPCMainThreadConfig {
9
7
  export declare class UniverRPCMainThreadPlugin extends Plugin {
10
8
  private readonly _config;
11
9
  protected readonly _injector: Injector;
10
+ private readonly _configService;
12
11
  static pluginName: string;
13
12
  private _internalWorker;
14
- constructor(_config: IUniverRPCMainThreadConfig, _injector: Injector);
13
+ constructor(_config: Partial<IUniverRPCMainThreadConfig>, _injector: Injector, _configService: IConfigService);
15
14
  dispose(): void;
16
15
  onStarting(): void;
17
16
  }
@@ -21,7 +20,8 @@ export declare class UniverRPCMainThreadPlugin extends Plugin {
21
20
  export declare class UniverRPCWorkerThreadPlugin extends Plugin {
22
21
  private readonly _config;
23
22
  protected readonly _injector: Injector;
23
+ private readonly _configService;
24
24
  static pluginName: string;
25
- constructor(_config: unknown, _injector: Injector);
25
+ constructor(_config: Partial<IUniverRPCWorkerThreadConfig>, _injector: Injector, _configService: IConfigService);
26
26
  onStarting(): void;
27
27
  }
package/lib/umd/index.js CHANGED
@@ -1 +1 @@
1
- (function(global,factory){typeof exports=="object"&&typeof module<"u"?factory(exports,require("@univerjs/core"),require("rxjs/operators"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs/operators","rxjs"],factory):(global=typeof globalThis<"u"?globalThis:global||self,factory(global.UniverRpc={},global.UniverCore,global.rxjs.operators,global.rxjs))})(this,function(exports2,core,operators,rxjs){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);var _a,_b,_c,_d,_e,_f;var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$3(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$3(target,key,result),result},"__decorateClass$3"),__decorateParam$3=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$3");const RemoteSyncServiceName="rpc.remote-sync.service",IRemoteSyncService=core.createIdentifier(RemoteSyncServiceName);exports2.RemoteSyncPrimaryService=(_a=class{constructor(_commandService){this._commandService=_commandService}async syncMutation(params){return this._commandService.syncExecuteCommand(params.mutationInfo.id,params.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},__name(_a,"RemoteSyncPrimaryService"),_a),exports2.RemoteSyncPrimaryService=__decorateClass$3([__decorateParam$3(0,core.ICommandService)],exports2.RemoteSyncPrimaryService);const RemoteInstanceServiceName="univer.remote-instance-service",IRemoteInstanceService=core.createIdentifier(RemoteInstanceServiceName);exports2.WebWorkerRemoteInstanceService=(_b=class{constructor(_univerInstanceService,_commandService,_logService){this._univerInstanceService=_univerInstanceService,this._commandService=_commandService,this._logService=_logService}whenReady(){return Promise.resolve(!0)}async syncMutation(params){return this._applyMutation(params.mutationInfo)}async createInstance(params){const{type,snapshot}=params;try{switch(type){case core.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(core.UniverInstanceType.UNIVER_SHEET,snapshot),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`)}}catch(err){throw err instanceof Error?err:new TypeError(`${err}`)}}async disposeInstance(params){return this._univerInstanceService.disposeUnit(params.unitID)}_applyMutation(mutationInfo){const{id,params:mutationParams}=mutationInfo;return this._commandService.syncExecuteCommand(id,mutationParams,{onlyLocal:!0,fromSync:!0})}},__name(_b,"WebWorkerRemoteInstanceService"),_b),exports2.WebWorkerRemoteInstanceService=__decorateClass$3([__decorateParam$3(0,core.IUniverInstanceService),__decorateParam$3(1,core.ICommandService),__decorateParam$3(2,core.ILogService)],exports2.WebWorkerRemoteInstanceService);function fromModule(module2){const handler=module2;return new class{call(method,args){const target=handler[method];if(typeof target=="function"){let res=target.apply(handler,[args]);return res instanceof Promise||(res=Promise.resolve(res)),res}throw new Error(`[RPC]: method not found for ${method}!`)}subscribe(eventMethod,args){const target=handler[eventMethod];if(typeof target=="function"){const res=target.apply(handler,args);return rxjs.isObservable(res)?res:rxjs.of(res)}throw new Error(`[RPC]: observable method not found for ${eventMethod}!`)}}}__name(fromModule,"fromModule");function toModule(channel){return new Proxy({},{get(_,propKey){if(propKey!=="dispose")return function(...args){return propertyIsEventSource(propKey)?channel.subscribe(propKey,args[0]):channel.call(propKey,args[0])}}})}__name(toModule,"toModule");function propertyIsEventSource(name){return name.endsWith("$")}__name(propertyIsEventSource,"propertyIsEventSource");const _ChannelClient=class _ChannelClient extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_initialized",new rxjs.BehaviorSubject(!1));__publicField(this,"_lastRequestCounter",0);__publicField(this,"_pendingRequests",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onMessage(message))}dispose(){this._pendingRequests.clear()}getChannel(channelName){const self2=this;return{call(method,args){return self2._disposed?Promise.reject():self2._remoteCall(channelName,method,args)},subscribe(eventMethod,args){if(self2._disposed)throw new Error("[ChannelClient]: client is disposed!");return self2._remoteSubscribe(channelName,eventMethod,args)}}}_whenReady(){return rxjs.firstValueFrom(this._initialized.pipe(operators.filter(v=>v),operators.take(1)))}async _remoteCall(channelName,method,args){await this._whenReady();const sequence=++this._lastRequestCounter,request={seq:sequence,type:100,channelName,method,args},client=this;return new Promise((resolve,reject)=>{const responseHandler={handle(response){switch(response.type){case 201:client._pendingRequests.delete(sequence),resolve(response.data);break;case 202:client._pendingRequests.delete(sequence),reject(response.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)})}_remoteSubscribe(channelName,method,args){return new rxjs.Observable(subscriber=>{let sequence=-1;return this._whenReady().then(()=>{sequence=++this._lastRequestCounter;const request={seq:sequence,type:101,channelName,method,args},responseHandler={handle(response){switch(response.type){case 300:subscriber.next(response.data);break;case 301:subscriber.error(response.data);break;case 302:subscriber.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)}),()=>{if(sequence===-1)return;const cancelSubscriptionRequest={type:102,seq:sequence,channelName,method};this._sendRequest(cancelSubscriptionRequest)}})}_sendRequest(request){this._protocol.send(request)}_onMessage(response){var _a2;switch(response.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(_a2=this._pendingRequests.get(response.seq))==null||_a2.handle(response);break}}};__name(_ChannelClient,"ChannelClient");let ChannelClient=_ChannelClient;const _ChannelServer=class _ChannelServer extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_channels",new Map);__publicField(this,"_subscriptions",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onRequest(message)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(channelName,channel){this._channels.set(channelName,channel)}_onRequest(request){switch(request.type){case 100:this._onMethodCall(request);break;case 101:this._onSubscribe(request);break;case 102:this._onUnsubscribe(request);break}}_onMethodCall(request){const{channelName,method,args}=request,channel=this._channels.get(channelName);let promise;try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);promise=channel.call(method,args)}catch(err){promise=Promise.reject(err)}promise.then(data=>{this._sendResponse({seq:request.seq,type:201,data})}).catch(err=>{err instanceof Error?this._sendResponse({seq:request.seq,type:202,data:err.message}):this._sendResponse({seq:request.seq,type:202,data:String(err)})})}_onSubscribe(request){const{channelName,seq}=request,channel=this._channels.get(channelName);try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);const subscription=channel.subscribe(request.method,request.args).subscribe({next:__name(data=>{this._sendResponse({seq,type:300,data})},"next"),error:__name(err=>{this._sendResponse({seq,type:301,data:err.message}),this._sendResponse({seq,type:302})},"error"),complete:__name(()=>{this._sendResponse({seq,type:302})},"complete")});this._subscriptions.set(request.seq,subscription)}catch(err){err instanceof Error?this._sendResponse({seq:request.seq,type:301,data:err.message}):this._sendResponse({seq:request.seq,type:301,data:String(err)})}}_onUnsubscribe(request){const subscription=this._subscriptions.get(request.seq);subscription&&(subscription.unsubscribe(),this._subscriptions.delete(request.seq))}_sendResponse(response){this._protocol.send(response)}};__name(_ChannelServer,"ChannelServer");let ChannelServer=_ChannelServer;const IRPCChannelService=core.createIdentifier("IRPCChannelService"),_ChannelService=class _ChannelService{constructor(_messageProtocol){__publicField(this,"_client");__publicField(this,"_server");this._client=new ChannelClient(_messageProtocol),this._server=new ChannelServer(_messageProtocol)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(name){return this._client.getChannel(name)}registerChannel(name,channel){this._server.registerChannel(name,channel)}};__name(_ChannelService,"ChannelService");let ChannelService=_ChannelService;var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$2(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$2(target,key,result),result},"__decorateClass$2"),__decorateParam$2=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$2");exports2.DataSyncPrimaryController=(_c=class extends core.RxDisposable{constructor(_injector,_commandService,_univerInstanceService,_rpcChannelService,_remoteSyncService){super();__publicField(this,"_remoteInstanceService");__publicField(this,"_syncingUnits",new Set);__publicField(this,"_syncingMutations",new Set);this._injector=_injector,this._commandService=_commandService,this._univerInstanceService=_univerInstanceService,this._rpcChannelService=_rpcChannelService,this._remoteSyncService=_remoteSyncService,this._initRPCChannels(),this._init()}registerSyncingMutations(mutation){this._syncingMutations.add(mutation.id)}syncUnit(unitId){return this._syncingUnits.add(unitId),core.toDisposable(()=>this._syncingUnits.delete(unitId))}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteSyncServiceName,fromModule(this._remoteSyncService)),this._injector.add([IRemoteInstanceService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)),"useFactory")}]),this._remoteInstanceService=this._injector.get(IRemoteInstanceService)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(sheet=>{this._syncingUnits.add(sheet.getUnitId()),this._remoteInstanceService.createInstance({unitID:sheet.getUnitId(),type:core.UniverInstanceType.UNIVER_SHEET,snapshot:sheet.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(workbook=>{this._syncingUnits.delete(workbook.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:workbook.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{const{type,params,id}=commandInfo,unitId=(params==null?void 0:params.unitId)||"";type===core.CommandType.MUTATION&&(!unitId||this._syncingUnits.has(unitId))&&!(options!=null&&options.fromSync)&&this._syncingMutations.has(id)&&this._remoteInstanceService.syncMutation({mutationInfo:commandInfo})}))}},__name(_c,"DataSyncPrimaryController"),_c),exports2.DataSyncPrimaryController=__decorateClass$2([core.OnLifecycle(core.LifecycleStages.Starting,exports2.DataSyncPrimaryController),__decorateParam$2(0,core.Inject(core.Injector)),__decorateParam$2(1,core.ICommandService),__decorateParam$2(2,core.IUniverInstanceService),__decorateParam$2(3,IRPCChannelService),__decorateParam$2(4,IRemoteSyncService)],exports2.DataSyncPrimaryController);var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1");exports2.DataSyncReplicaController=(_d=class extends core.Disposable{constructor(_injector,_remoteInstanceService,_commandService,_rpcChannelService){super();__publicField(this,"_remoteSyncService");this._injector=_injector,this._remoteInstanceService=_remoteInstanceService,this._commandService=_commandService,this._rpcChannelService=_rpcChannelService,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteInstanceServiceName,fromModule(this._remoteInstanceService)),this._injector.add([IRemoteSyncService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteSyncServiceName)),"useFactory")}]),this._remoteSyncService=this._injector.get(IRemoteSyncService)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{commandInfo.type===core.CommandType.MUTATION&&!(options!=null&&options.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:commandInfo})}))}},__name(_d,"DataSyncReplicaController"),_d),exports2.DataSyncReplicaController=__decorateClass$1([core.OnLifecycle(core.LifecycleStages.Starting,exports2.DataSyncReplicaController),__decorateParam$1(0,core.Inject(core.Injector)),__decorateParam$1(1,IRemoteInstanceService),__decorateParam$1(2,core.ICommandService),__decorateParam$1(3,IRPCChannelService)],exports2.DataSyncReplicaController);function createWebWorkerMessagePortOnWorker(){return{send(message){postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return addEventListener("message",handler),()=>removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnWorker,"createWebWorkerMessagePortOnWorker");function createWebWorkerMessagePortOnMain(worker){return{send(message){worker.postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return worker.addEventListener("message",handler),()=>worker.removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnMain,"createWebWorkerMessagePortOnMain");var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam");exports2.UniverRPCMainThreadPlugin=(_e=class extends core.Plugin{constructor(_config,_injector){super();__publicField(this,"_internalWorker",null);this._config=_config,this._injector=_injector}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL}=this._config,worker=workerURL instanceof Worker?workerURL:new Worker(workerURL);this._internalWorker=workerURL instanceof Worker?null:worker;const messageProtocol=createWebWorkerMessagePortOnMain(worker);[[IRPCChannelService,{useFactory:__name(()=>new ChannelService(messageProtocol),"useFactory")}],[exports2.DataSyncPrimaryController],[IRemoteSyncService,{useClass:exports2.RemoteSyncPrimaryService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports2.DataSyncPrimaryController)}},__name(_e,"UniverRPCMainThreadPlugin"),__publicField(_e,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),_e),exports2.UniverRPCMainThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports2.UniverRPCMainThreadPlugin),exports2.UniverRPCWorkerThreadPlugin=(_f=class extends core.Plugin{constructor(_config,_injector){super(),this._config=_config,this._injector=_injector}onStarting(){[[exports2.DataSyncReplicaController],[IRPCChannelService,{useFactory:__name(()=>new ChannelService(createWebWorkerMessagePortOnWorker()),"useFactory")}],[IRemoteInstanceService,{useClass:exports2.WebWorkerRemoteInstanceService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports2.DataSyncReplicaController)}},__name(_f,"UniverRPCWorkerThreadPlugin"),__publicField(_f,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),_f),exports2.UniverRPCWorkerThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports2.UniverRPCWorkerThreadPlugin),exports2.ChannelClient=ChannelClient,exports2.ChannelServer=ChannelServer,exports2.ChannelService=ChannelService,exports2.IRPCChannelService=IRPCChannelService,exports2.IRemoteInstanceService=IRemoteInstanceService,exports2.IRemoteSyncService=IRemoteSyncService,exports2.RemoteInstanceServiceName=RemoteInstanceServiceName,exports2.RemoteSyncServiceName=RemoteSyncServiceName,exports2.fromModule=fromModule,exports2.toModule=toModule,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
1
+ (function(global,factory){typeof exports=="object"&&typeof module<"u"?factory(exports,require("@univerjs/core"),require("rxjs/operators"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs/operators","rxjs"],factory):(global=typeof globalThis<"u"?globalThis:global||self,factory(global.UniverRpc={},global.UniverCore,global.rxjs.operators,global.rxjs))})(this,function(exports2,core,operators,rxjs){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);var _a,_b,_c,_d,_e,_f;var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$3(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$3(target,key,result),result},"__decorateClass$3"),__decorateParam$3=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$3");const RemoteSyncServiceName="rpc.remote-sync.service",IRemoteSyncService=core.createIdentifier(RemoteSyncServiceName);exports2.RemoteSyncPrimaryService=(_a=class{constructor(_commandService){this._commandService=_commandService}async syncMutation(params){return this._commandService.syncExecuteCommand(params.mutationInfo.id,params.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},__name(_a,"RemoteSyncPrimaryService"),_a),exports2.RemoteSyncPrimaryService=__decorateClass$3([__decorateParam$3(0,core.ICommandService)],exports2.RemoteSyncPrimaryService);const RemoteInstanceServiceName="univer.remote-instance-service",IRemoteInstanceService=core.createIdentifier(RemoteInstanceServiceName);exports2.WebWorkerRemoteInstanceService=(_b=class{constructor(_univerInstanceService,_commandService,_logService){this._univerInstanceService=_univerInstanceService,this._commandService=_commandService,this._logService=_logService}whenReady(){return Promise.resolve(!0)}async syncMutation(params){return this._applyMutation(params.mutationInfo)}async createInstance(params){const{type,snapshot}=params;try{switch(type){case core.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(core.UniverInstanceType.UNIVER_SHEET,snapshot),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`)}}catch(err){throw err instanceof Error?err:new TypeError(`${err}`)}}async disposeInstance(params){return this._univerInstanceService.disposeUnit(params.unitID)}_applyMutation(mutationInfo){const{id,params:mutationParams}=mutationInfo;return this._commandService.syncExecuteCommand(id,mutationParams,{onlyLocal:!0,fromSync:!0})}},__name(_b,"WebWorkerRemoteInstanceService"),_b),exports2.WebWorkerRemoteInstanceService=__decorateClass$3([__decorateParam$3(0,core.IUniverInstanceService),__decorateParam$3(1,core.ICommandService),__decorateParam$3(2,core.ILogService)],exports2.WebWorkerRemoteInstanceService);function fromModule(module2){const handler=module2;return new class{call(method,args){const target=handler[method];if(typeof target=="function"){let res=target.apply(handler,[args]);return res instanceof Promise||(res=Promise.resolve(res)),res}throw new Error(`[RPC]: method not found for ${method}!`)}subscribe(eventMethod,args){const target=handler[eventMethod];if(typeof target=="function"){const res=target.apply(handler,args);return rxjs.isObservable(res)?res:rxjs.of(res)}throw new Error(`[RPC]: observable method not found for ${eventMethod}!`)}}}__name(fromModule,"fromModule");function toModule(channel){return new Proxy({},{get(_,propKey){if(propKey!=="dispose")return function(...args){return propertyIsEventSource(propKey)?channel.subscribe(propKey,args[0]):channel.call(propKey,args[0])}}})}__name(toModule,"toModule");function propertyIsEventSource(name){return name.endsWith("$")}__name(propertyIsEventSource,"propertyIsEventSource");const _ChannelClient=class _ChannelClient extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_initialized",new rxjs.BehaviorSubject(!1));__publicField(this,"_lastRequestCounter",0);__publicField(this,"_pendingRequests",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onMessage(message))}dispose(){this._pendingRequests.clear()}getChannel(channelName){const self2=this;return{call(method,args){return self2._disposed?Promise.reject():self2._remoteCall(channelName,method,args)},subscribe(eventMethod,args){if(self2._disposed)throw new Error("[ChannelClient]: client is disposed!");return self2._remoteSubscribe(channelName,eventMethod,args)}}}_whenReady(){return rxjs.firstValueFrom(this._initialized.pipe(operators.filter(v=>v),operators.take(1)))}async _remoteCall(channelName,method,args){await this._whenReady();const sequence=++this._lastRequestCounter,request={seq:sequence,type:100,channelName,method,args},client=this;return new Promise((resolve,reject)=>{const responseHandler={handle(response){switch(response.type){case 201:client._pendingRequests.delete(sequence),resolve(response.data);break;case 202:client._pendingRequests.delete(sequence),reject(response.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)})}_remoteSubscribe(channelName,method,args){return new rxjs.Observable(subscriber=>{let sequence=-1;return this._whenReady().then(()=>{sequence=++this._lastRequestCounter;const request={seq:sequence,type:101,channelName,method,args},responseHandler={handle(response){switch(response.type){case 300:subscriber.next(response.data);break;case 301:subscriber.error(response.data);break;case 302:subscriber.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)}),()=>{if(sequence===-1)return;const cancelSubscriptionRequest={type:102,seq:sequence,channelName,method};this._sendRequest(cancelSubscriptionRequest)}})}_sendRequest(request){this._protocol.send(request)}_onMessage(response){var _a2;switch(response.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(_a2=this._pendingRequests.get(response.seq))==null||_a2.handle(response);break}}};__name(_ChannelClient,"ChannelClient");let ChannelClient=_ChannelClient;const _ChannelServer=class _ChannelServer extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_channels",new Map);__publicField(this,"_subscriptions",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onRequest(message)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(channelName,channel){this._channels.set(channelName,channel)}_onRequest(request){switch(request.type){case 100:this._onMethodCall(request);break;case 101:this._onSubscribe(request);break;case 102:this._onUnsubscribe(request);break}}_onMethodCall(request){const{channelName,method,args}=request,channel=this._channels.get(channelName);let promise;try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);promise=channel.call(method,args)}catch(err){promise=Promise.reject(err)}promise.then(data=>{this._sendResponse({seq:request.seq,type:201,data})}).catch(err=>{err instanceof Error?this._sendResponse({seq:request.seq,type:202,data:err.message}):this._sendResponse({seq:request.seq,type:202,data:String(err)})})}_onSubscribe(request){const{channelName,seq}=request,channel=this._channels.get(channelName);try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);const subscription=channel.subscribe(request.method,request.args).subscribe({next:__name(data=>{this._sendResponse({seq,type:300,data})},"next"),error:__name(err=>{this._sendResponse({seq,type:301,data:err.message}),this._sendResponse({seq,type:302})},"error"),complete:__name(()=>{this._sendResponse({seq,type:302})},"complete")});this._subscriptions.set(request.seq,subscription)}catch(err){err instanceof Error?this._sendResponse({seq:request.seq,type:301,data:err.message}):this._sendResponse({seq:request.seq,type:301,data:String(err)})}}_onUnsubscribe(request){const subscription=this._subscriptions.get(request.seq);subscription&&(subscription.unsubscribe(),this._subscriptions.delete(request.seq))}_sendResponse(response){this._protocol.send(response)}};__name(_ChannelServer,"ChannelServer");let ChannelServer=_ChannelServer;const IRPCChannelService=core.createIdentifier("IRPCChannelService"),_ChannelService=class _ChannelService{constructor(_messageProtocol){__publicField(this,"_client");__publicField(this,"_server");this._client=new ChannelClient(_messageProtocol),this._server=new ChannelServer(_messageProtocol)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(name){return this._client.getChannel(name)}registerChannel(name,channel){this._server.registerChannel(name,channel)}};__name(_ChannelService,"ChannelService");let ChannelService=_ChannelService;var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$2(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$2(target,key,result),result},"__decorateClass$2"),__decorateParam$2=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$2");exports2.DataSyncPrimaryController=(_c=class extends core.RxDisposable{constructor(_injector,_commandService,_univerInstanceService,_rpcChannelService,_remoteSyncService){super();__publicField(this,"_remoteInstanceService");__publicField(this,"_syncingUnits",new Set);__publicField(this,"_syncingMutations",new Set);this._injector=_injector,this._commandService=_commandService,this._univerInstanceService=_univerInstanceService,this._rpcChannelService=_rpcChannelService,this._remoteSyncService=_remoteSyncService,this._initRPCChannels(),this._init()}registerSyncingMutations(mutation){this._syncingMutations.add(mutation.id)}syncUnit(unitId){return this._syncingUnits.add(unitId),core.toDisposable(()=>this._syncingUnits.delete(unitId))}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteSyncServiceName,fromModule(this._remoteSyncService)),this._injector.add([IRemoteInstanceService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)),"useFactory")}]),this._remoteInstanceService=this._injector.get(IRemoteInstanceService)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(sheet=>{this._syncingUnits.add(sheet.getUnitId()),this._remoteInstanceService.createInstance({unitID:sheet.getUnitId(),type:core.UniverInstanceType.UNIVER_SHEET,snapshot:sheet.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(workbook=>{this._syncingUnits.delete(workbook.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:workbook.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{const{type,params,id}=commandInfo,unitId=(params==null?void 0:params.unitId)||"";type===core.CommandType.MUTATION&&(!unitId||this._syncingUnits.has(unitId))&&!(options!=null&&options.fromSync)&&this._syncingMutations.has(id)&&this._remoteInstanceService.syncMutation({mutationInfo:commandInfo})}))}},__name(_c,"DataSyncPrimaryController"),_c),exports2.DataSyncPrimaryController=__decorateClass$2([core.OnLifecycle(core.LifecycleStages.Starting,exports2.DataSyncPrimaryController),__decorateParam$2(0,core.Inject(core.Injector)),__decorateParam$2(1,core.ICommandService),__decorateParam$2(2,core.IUniverInstanceService),__decorateParam$2(3,IRPCChannelService),__decorateParam$2(4,IRemoteSyncService)],exports2.DataSyncPrimaryController);var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1");exports2.DataSyncReplicaController=(_d=class extends core.Disposable{constructor(_injector,_remoteInstanceService,_commandService,_rpcChannelService){super();__publicField(this,"_remoteSyncService");this._injector=_injector,this._remoteInstanceService=_remoteInstanceService,this._commandService=_commandService,this._rpcChannelService=_rpcChannelService,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteInstanceServiceName,fromModule(this._remoteInstanceService)),this._injector.add([IRemoteSyncService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteSyncServiceName)),"useFactory")}]),this._remoteSyncService=this._injector.get(IRemoteSyncService)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{commandInfo.type===core.CommandType.MUTATION&&!(options!=null&&options.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:commandInfo})}))}},__name(_d,"DataSyncReplicaController"),_d),exports2.DataSyncReplicaController=__decorateClass$1([core.OnLifecycle(core.LifecycleStages.Starting,exports2.DataSyncReplicaController),__decorateParam$1(0,core.Inject(core.Injector)),__decorateParam$1(1,IRemoteInstanceService),__decorateParam$1(2,core.ICommandService),__decorateParam$1(3,IRPCChannelService)],exports2.DataSyncReplicaController);function createWebWorkerMessagePortOnWorker(){return{send(message){postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return addEventListener("message",handler),()=>removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnWorker,"createWebWorkerMessagePortOnWorker");function createWebWorkerMessagePortOnMain(worker){return{send(message){worker.postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return worker.addEventListener("message",handler),()=>worker.removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnMain,"createWebWorkerMessagePortOnMain");const PLUGIN_CONFIG_KEY_MAIN_THREAD="rpc.main-thread.config",defaultPluginMainThreadConfig={},PLUGIN_CONFIG_KEY_WORKER_THREAD="rpc.worker-thread.config",defaultPluginWorkerThreadConfig={};var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam");exports2.UniverRPCMainThreadPlugin=(_e=class extends core.Plugin{constructor(_config=defaultPluginMainThreadConfig,_injector,_configService){super();__publicField(this,"_internalWorker",null);this._config=_config,this._injector=_injector,this._configService=_configService;const{...rest}=this._config;this._configService.setConfig(PLUGIN_CONFIG_KEY_MAIN_THREAD,rest)}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL}=this._config;if(!workerURL)throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");const worker=workerURL instanceof Worker?workerURL:new Worker(workerURL);this._internalWorker=workerURL instanceof Worker?null:worker;const messageProtocol=createWebWorkerMessagePortOnMain(worker);[[IRPCChannelService,{useFactory:__name(()=>new ChannelService(messageProtocol),"useFactory")}],[exports2.DataSyncPrimaryController],[IRemoteSyncService,{useClass:exports2.RemoteSyncPrimaryService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports2.DataSyncPrimaryController)}},__name(_e,"UniverRPCMainThreadPlugin"),__publicField(_e,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),_e),exports2.UniverRPCMainThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector)),__decorateParam(2,core.IConfigService)],exports2.UniverRPCMainThreadPlugin),exports2.UniverRPCWorkerThreadPlugin=(_f=class extends core.Plugin{constructor(_config=defaultPluginWorkerThreadConfig,_injector,_configService){super(),this._config=_config,this._injector=_injector,this._configService=_configService;const{...rest}=this._config;this._configService.setConfig(PLUGIN_CONFIG_KEY_WORKER_THREAD,rest)}onStarting(){[[exports2.DataSyncReplicaController],[IRPCChannelService,{useFactory:__name(()=>new ChannelService(createWebWorkerMessagePortOnWorker()),"useFactory")}],[IRemoteInstanceService,{useClass:exports2.WebWorkerRemoteInstanceService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports2.DataSyncReplicaController)}},__name(_f,"UniverRPCWorkerThreadPlugin"),__publicField(_f,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),_f),exports2.UniverRPCWorkerThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector)),__decorateParam(2,core.IConfigService)],exports2.UniverRPCWorkerThreadPlugin),exports2.ChannelClient=ChannelClient,exports2.ChannelServer=ChannelServer,exports2.ChannelService=ChannelService,exports2.IRPCChannelService=IRPCChannelService,exports2.IRemoteInstanceService=IRemoteInstanceService,exports2.IRemoteSyncService=IRemoteSyncService,exports2.RemoteInstanceServiceName=RemoteInstanceServiceName,exports2.RemoteSyncServiceName=RemoteSyncServiceName,exports2.fromModule=fromModule,exports2.toModule=toModule,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/rpc",
3
- "version": "0.2.10",
3
+ "version": "0.2.12",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -46,15 +46,15 @@
46
46
  ],
47
47
  "peerDependencies": {
48
48
  "rxjs": ">=7.0.0",
49
- "@univerjs/core": "0.2.10"
49
+ "@univerjs/core": "0.2.12"
50
50
  },
51
51
  "devDependencies": {
52
52
  "rxjs": "^7.8.1",
53
53
  "typescript": "^5.5.4",
54
54
  "vite": "^5.4.2",
55
55
  "vitest": "^2.0.5",
56
- "@univerjs/core": "0.2.10",
57
- "@univerjs/shared": "0.2.10"
56
+ "@univerjs/core": "0.2.12",
57
+ "@univerjs/shared": "0.2.12"
58
58
  },
59
59
  "univerSpace": {
60
60
  ".": {