New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@univerjs/rpc

Package Overview
Dependencies
Maintainers
0
Versions
267
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@univerjs/rpc - npm Package Compare versions

Comparing version 0.2.11 to 0.2.12

lib/types/controllers/config.schema.d.ts

2

lib/cjs/index.js

@@ -1,1 +0,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;
"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;

@@ -5,3 +5,3 @@ var __defProp = Object.defineProperty;

var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
import { createIdentifier, UniverInstanceType, ICommandService, IUniverInstanceService, ILogService, RxDisposable, OnLifecycle, LifecycleStages, Inject, Injector, toDisposable, CommandType, Disposable, Plugin } from "@univerjs/core";
import { createIdentifier, UniverInstanceType, ICommandService, IUniverInstanceService, ILogService, RxDisposable, OnLifecycle, LifecycleStages, Inject, Injector, toDisposable, CommandType, Disposable, Plugin, IConfigService } from "@univerjs/core";
import { takeUntil, filter, take } from "rxjs/operators";

@@ -443,2 +443,3 @@ import { isObservable, of, BehaviorSubject, firstValueFrom, Observable, shareReplay } from "rxjs";

__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 = /* @__PURE__ */ __name((decorators, target, key, kind) => {

@@ -450,6 +451,8 @@ for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)

let UniverRPCMainThreadPlugin = (_a5 = class extends Plugin {
constructor(_config, _injector) {
constructor(_config = defaultPluginMainThreadConfig, _injector, _configService) {
super();
__publicField(this, "_internalWorker", null);
this._config = _config, this._injector = _injector;
this._config = _config, this._injector = _injector, this._configService = _configService;
const { ...rest } = this._config;
this._configService.setConfig(PLUGIN_CONFIG_KEY_MAIN_THREAD, rest);
}

@@ -460,3 +463,6 @@ dispose() {

onStarting() {
const { workerURL } = this._config, worker = workerURL instanceof Worker ? workerURL : new Worker(workerURL);
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;

@@ -477,8 +483,11 @@ const messageProtocol = createWebWorkerMessagePortOnMain(worker);

UniverRPCMainThreadPlugin = __decorateClass([
__decorateParam(1, Inject(Injector))
__decorateParam(1, Inject(Injector)),
__decorateParam(2, IConfigService)
], UniverRPCMainThreadPlugin);
var _a6;
let UniverRPCWorkerThreadPlugin = (_a6 = class extends Plugin {
constructor(_config, _injector) {
super(), this._config = _config, this._injector = _injector;
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);
}

@@ -499,3 +508,4 @@ onStarting() {

UniverRPCWorkerThreadPlugin = __decorateClass([
__decorateParam(1, Inject(Injector))
__decorateParam(1, Inject(Injector)),
__decorateParam(2, IConfigService)
], UniverRPCWorkerThreadPlugin);

@@ -502,0 +512,0 @@ export {

@@ -16,3 +16,3 @@ /**

*/
export { type IUniverRPCMainThreadConfig, UniverRPCMainThreadPlugin, UniverRPCWorkerThreadPlugin, } from './plugin';
export { UniverRPCMainThreadPlugin, UniverRPCWorkerThreadPlugin, } from './plugin';
export { DataSyncReplicaController } from './controllers/data-sync/data-sync-replica.controller';

@@ -24,1 +24,2 @@ export { DataSyncPrimaryController } from './controllers/data-sync/data-sync-primary.controller';

export { IRemoteSyncService } from './services/remote-instance/remote-instance.service';
export type { IUniverRPCMainThreadConfig, IUniverRPCWorkerThreadConfig } from './controllers/config.schema';

@@ -1,5 +0,3 @@

import { Injector, Plugin } from '@univerjs/core';
export interface IUniverRPCMainThreadConfig {
workerURL: string | URL | Worker;
}
import { IConfigService, Injector, Plugin } from '@univerjs/core';
import { IUniverRPCMainThreadConfig, IUniverRPCWorkerThreadConfig } from './controllers/config.schema';
/**

@@ -12,5 +10,6 @@ * This plugin is used to register the RPC services on the main thread. It

protected readonly _injector: Injector;
private readonly _configService;
static pluginName: string;
private _internalWorker;
constructor(_config: IUniverRPCMainThreadConfig, _injector: Injector);
constructor(_config: Partial<IUniverRPCMainThreadConfig>, _injector: Injector, _configService: IConfigService);
dispose(): void;

@@ -25,5 +24,6 @@ onStarting(): void;

protected readonly _injector: Injector;
private readonly _configService;
static pluginName: string;
constructor(_config: unknown, _injector: Injector);
constructor(_config: Partial<IUniverRPCWorkerThreadConfig>, _injector: Injector, _configService: IConfigService);
onStarting(): void;
}

@@ -1,1 +0,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"})});
(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"})});
{
"name": "@univerjs/rpc",
"version": "0.2.11",
"version": "0.2.12",
"private": false,

@@ -49,3 +49,3 @@ "author": "DreamNum <developer@univer.ai>",

"rxjs": ">=7.0.0",
"@univerjs/core": "0.2.11"
"@univerjs/core": "0.2.12"
},

@@ -57,4 +57,4 @@ "devDependencies": {

"vitest": "^2.0.5",
"@univerjs/shared": "0.2.11",
"@univerjs/core": "0.2.11"
"@univerjs/core": "0.2.12",
"@univerjs/shared": "0.2.12"
},

@@ -61,0 +61,0 @@ "univerSpace": {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc