@univerjs/rpc 0.4.2 → 0.5.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var __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"),PLUGIN_CONFIG_KEY_MAIN_THREAD="rpc.main-thread.config",defaultPluginMainThreadConfig={},PLUGIN_CONFIG_KEY_WORKER_THREAD="rpc.worker-thread.config",defaultPluginWorkerThreadConfig={};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([__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([__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=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;
1
+ "use strict";var O=Object.defineProperty;var $=(i,t,e)=>t in i?O(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var l=(i,t,e)=>$(i,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@univerjs/core"),u=require("rxjs/operators"),_=require("rxjs"),N="rpc.main-thread.config",x={},k="rpc.worker-thread.config",L={};var H=Object.defineProperty,A=Object.getOwnPropertyDescriptor,T=(i,t,e,n)=>{for(var s=n>1?void 0:n?A(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(n?c(t,e,s):c(s))||s);return n&&s&&H(t,e,s),s},f=(i,t)=>(e,n)=>t(e,n,i);const g="rpc.remote-sync.service",v=o.createIdentifier(g);exports.RemoteSyncPrimaryService=class{constructor(t){this._commandService=t}async syncMutation(t){return this._commandService.syncExecuteCommand(t.mutationInfo.id,t.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}};exports.RemoteSyncPrimaryService=T([f(0,o.ICommandService)],exports.RemoteSyncPrimaryService);const R="univer.remote-instance-service",m=o.createIdentifier(R);exports.WebWorkerRemoteInstanceService=class{constructor(t,e,n){this._univerInstanceService=t,this._commandService=e,this._logService=n}whenReady(){return Promise.resolve(!0)}async syncMutation(t){return this._applyMutation(t.mutationInfo)}async createInstance(t){const{type:e,snapshot:n}=t;try{switch(e){case o.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(o.UniverInstanceType.UNIVER_SHEET,n),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(t){return this._univerInstanceService.disposeUnit(t.unitID)}_applyMutation(t){const{id:e,params:n}=t;return this._commandService.syncExecuteCommand(e,n,{onlyLocal:!0,fromSync:!0})}};exports.WebWorkerRemoteInstanceService=T([f(0,o.IUniverInstanceService),f(1,o.ICommandService),f(2,o.ILogService)],exports.WebWorkerRemoteInstanceService);function U(i){const t=i;return new class{call(e,n){const s=t[e];if(typeof s=="function"){let r=s.apply(t,[n]);return r instanceof Promise||(r=Promise.resolve(r)),r}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,n){const s=t[e];if(typeof s=="function"){const r=s.apply(t,n);return _.isObservable(r)?r:_.of(r)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function E(i){return new Proxy({},{get(t,e){if(e!=="dispose")return function(...n){return V(e)?i.subscribe(e,n[0]):i.call(e,n[0])}}})}function V(i){return i.endsWith("$")}class q extends o.RxDisposable{constructor(e){super();l(this,"_initialized",new _.BehaviorSubject(!1));l(this,"_lastRequestCounter",0);l(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onMessage(n))}dispose(){this._pendingRequests.clear()}getChannel(e){const n=this;return{call(s,r){return n._disposed?Promise.reject():n._remoteCall(e,s,r)},subscribe(s,r){if(n._disposed)throw new Error("[ChannelClient]: client is disposed!");return n._remoteSubscribe(e,s,r)}}}_whenReady(){return _.firstValueFrom(this._initialized.pipe(u.filter(e=>e),u.take(1)))}async _remoteCall(e,n,s){await this._whenReady();const r=++this._lastRequestCounter,h={seq:r,type:100,channelName:e,method:n,args:s},a=this;return new Promise((b,d)=>{const D={handle(I){switch(I.type){case 201:a._pendingRequests.delete(r),b(I.data);break;case 202:a._pendingRequests.delete(r),d(I.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(r,D),this._sendRequest(h)})}_remoteSubscribe(e,n,s){return new _.Observable(r=>{let c=-1;return this._whenReady().then(()=>{c=++this._lastRequestCounter;const a={seq:c,type:101,channelName:e,method:n,args:s},b={handle(d){switch(d.type){case 300:r.next(d.data);break;case 301:r.error(d.data);break;case 302:r.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(c,b),this._sendRequest(a)}),()=>{if(c===-1)return;const h={type:102,seq:c,channelName:e,method:n};this._sendRequest(h)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var n;switch(e.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(n=this._pendingRequests.get(e.seq))==null||n.handle(e);break}}}class W extends o.RxDisposable{constructor(e){super();l(this,"_channels",new Map);l(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onRequest(n)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,n){this._channels.set(e,n)}_onRequest(e){switch(e.type){case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_onMethodCall(e){const{channelName:n,method:s,args:r}=e,c=this._channels.get(n);let h;try{if(!c)throw new Error(`[ChannelServer]: Channel ${n} not found!`);h=c.call(s,r)}catch(a){h=Promise.reject(a)}h.then(a=>{this._sendResponse({seq:e.seq,type:201,data:a})}).catch(a=>{a instanceof Error?this._sendResponse({seq:e.seq,type:202,data:a.message}):this._sendResponse({seq:e.seq,type:202,data:String(a)})})}_onSubscribe(e){const{channelName:n,seq:s}=e,r=this._channels.get(n);try{if(!r)throw new Error(`[ChannelServer]: Channel ${n} not found!`);const h=r.subscribe(e.method,e.args).subscribe({next:a=>{this._sendResponse({seq:s,type:300,data:a})},error:a=>{this._sendResponse({seq:s,type:301,data:a.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,h)}catch(c){c instanceof Error?this._sendResponse({seq:e.seq,type:301,data:c.message}):this._sendResponse({seq:e.seq,type:301,data:String(c)})}}_onUnsubscribe(e){const n=this._subscriptions.get(e.seq);n&&(n.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const S=o.createIdentifier("IRPCChannelService");class M{constructor(t){l(this,"_client");l(this,"_server");this._client=new q(t),this._server=new W(t)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(t){return this._client.getChannel(t)}registerChannel(t,e){this._server.registerChannel(t,e)}}var F=Object.defineProperty,G=Object.getOwnPropertyDescriptor,z=(i,t,e,n)=>{for(var s=n>1?void 0:n?G(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(n?c(t,e,s):c(s))||s);return n&&s&&F(t,e,s),s},p=(i,t)=>(e,n)=>t(e,n,i);exports.DataSyncPrimaryController=class extends o.RxDisposable{constructor(e,n,s,r,c){super();l(this,"_remoteInstanceService");l(this,"_syncingUnits",new Set);l(this,"_syncingMutations",new Set);this._injector=e,this._commandService=n,this._univerInstanceService=s,this._rpcChannelService=r,this._remoteSyncService=c,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),o.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(g,U(this._remoteSyncService)),this._injector.add([m,{useFactory:()=>E(this._rpcChannelService.requestChannel(R))}]),this._remoteInstanceService=this._injector.get(m)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(o.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:o.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(o.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{const{type:s,params:r,id:c}=e,h=(r==null?void 0:r.unitId)||"";s===o.CommandType.MUTATION&&(!h||this._syncingUnits.has(h))&&!(n!=null&&n.fromSync)&&this._syncingMutations.has(c)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}};exports.DataSyncPrimaryController=z([p(0,o.Inject(o.Injector)),p(1,o.ICommandService),p(2,o.IUniverInstanceService),p(3,S),p(4,v)],exports.DataSyncPrimaryController);var Y=Object.defineProperty,B=Object.getOwnPropertyDescriptor,K=(i,t,e,n)=>{for(var s=n>1?void 0:n?B(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(n?c(t,e,s):c(s))||s);return n&&s&&Y(t,e,s),s},y=(i,t)=>(e,n)=>t(e,n,i);exports.DataSyncReplicaController=class extends o.Disposable{constructor(e,n,s,r){super();l(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=n,this._commandService=s,this._rpcChannelService=r,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(R,U(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>E(this._rpcChannelService.requestChannel(g))}]),this._remoteSyncService=this._injector.get(v)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{e.type===o.CommandType.MUTATION&&!(n!=null&&n.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}};exports.DataSyncReplicaController=K([y(0,o.Inject(o.Injector)),y(1,m),y(2,o.ICommandService),y(3,S)],exports.DataSyncReplicaController);function J(){return{send(i){postMessage(i)},onMessage:new _.Observable(i=>{const t=e=>{i.next(e.data)};return addEventListener("message",t),()=>removeEventListener("message",t)}).pipe(_.shareReplay(1))}}function Q(i){return{send(t){i.postMessage(t)},onMessage:new _.Observable(t=>{const e=n=>{t.next(n.data)};return i.addEventListener("message",e),()=>i.removeEventListener("message",e)}).pipe(_.shareReplay(1))}}var X=Object.defineProperty,Z=Object.getOwnPropertyDescriptor,j=(i,t,e,n)=>{for(var s=n>1?void 0:n?Z(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(n?c(t,e,s):c(s))||s);return n&&s&&X(t,e,s),s},C=(i,t)=>(e,n)=>t(e,n,i),P;exports.UniverRPCMainThreadPlugin=(P=class extends o.Plugin{constructor(e=x,n,s){super();l(this,"_internalWorker",null);this._config=e,this._injector=n,this._configService=s;const{...r}=this._config;this._configService.setConfig(N,r)}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL:e}=this._config;if(!e)throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");const n=e instanceof Worker?e:new Worker(e);this._internalWorker=e instanceof Worker?null:n;const s=Q(n);[[S,{useFactory:()=>new M(s)}],[exports.DataSyncPrimaryController],[v,{useClass:exports.RemoteSyncPrimaryService}]].forEach(c=>this._injector.add(c)),this._injector.get(exports.DataSyncPrimaryController)}},l(P,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),P);exports.UniverRPCMainThreadPlugin=j([C(1,o.Inject(o.Injector)),C(2,o.IConfigService)],exports.UniverRPCMainThreadPlugin);var w;exports.UniverRPCWorkerThreadPlugin=(w=class extends o.Plugin{constructor(t=L,e,n){super(),this._config=t,this._injector=e,this._configService=n;const{...s}=this._config;this._configService.setConfig(k,s)}onStarting(){[[exports.DataSyncReplicaController],[S,{useFactory:()=>new M(J())}],[m,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(t=>this._injector.add(t)),this._injector.get(exports.DataSyncReplicaController)}},l(w,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),w);exports.UniverRPCWorkerThreadPlugin=j([C(1,o.Inject(o.Injector)),C(2,o.IConfigService)],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=q;exports.ChannelServer=W;exports.ChannelService=M;exports.IRPCChannelService=S;exports.IRemoteInstanceService=m;exports.IRemoteSyncService=v;exports.RemoteInstanceServiceName=R;exports.RemoteSyncServiceName=g;exports.fromModule=U;exports.toModule=E;
package/lib/es/index.js CHANGED
@@ -1,207 +1,201 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value;
3
- var __name = (target, value) => __defProp(target, "name", { value, configurable: !0 });
4
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
5
- import { createIdentifier, UniverInstanceType, ICommandService, IUniverInstanceService, ILogService, RxDisposable, Inject, Injector, toDisposable, CommandType, Disposable, Plugin, IConfigService } from "@univerjs/core";
6
- import { takeUntil, filter, take } from "rxjs/operators";
7
- import { isObservable, of, BehaviorSubject, firstValueFrom, Observable, shareReplay } from "rxjs";
8
- const PLUGIN_CONFIG_KEY_MAIN_THREAD = "rpc.main-thread.config", defaultPluginMainThreadConfig = {}, PLUGIN_CONFIG_KEY_WORKER_THREAD = "rpc.worker-thread.config", defaultPluginWorkerThreadConfig = {};
9
- var __defProp$3 = Object.defineProperty, __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor, __decorateClass$3 = /* @__PURE__ */ __name((decorators, target, key, kind) => {
10
- for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
11
- (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
12
- return kind && result && __defProp$3(target, key, result), result;
13
- }, "__decorateClass$3"), __decorateParam$3 = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam$3");
14
- const RemoteSyncServiceName = "rpc.remote-sync.service", IRemoteSyncService = createIdentifier(RemoteSyncServiceName);
15
- var _a;
16
- let RemoteSyncPrimaryService = (_a = class {
17
- constructor(_commandService) {
18
- this._commandService = _commandService;
19
- }
20
- async syncMutation(params) {
21
- return this._commandService.syncExecuteCommand(params.mutationInfo.id, params.mutationInfo.params, {
1
+ var K = Object.defineProperty;
2
+ var J = (s, t, e) => t in s ? K(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
+ var a = (s, t, e) => J(s, typeof t != "symbol" ? t + "" : t, e);
4
+ import { createIdentifier as O, UniverInstanceType as u, ICommandService as b, IUniverInstanceService as x, ILogService as Q, RxDisposable as j, Inject as C, Injector as R, toDisposable as X, CommandType as L, Disposable as Z, Plugin as H, IConfigService as k } from "@univerjs/core";
5
+ import { takeUntil as v, filter as ee, take as te } from "rxjs/operators";
6
+ import { isObservable as ne, of as se, BehaviorSubject as re, firstValueFrom as ie, Observable as $, shareReplay as A } from "rxjs";
7
+ const ce = "rpc.main-thread.config", oe = {}, ae = "rpc.worker-thread.config", he = {};
8
+ var _e = Object.defineProperty, le = Object.getOwnPropertyDescriptor, V = (s, t, e, n) => {
9
+ for (var r = n > 1 ? void 0 : n ? le(t, e) : t, i = s.length - 1, c; i >= 0; i--)
10
+ (c = s[i]) && (r = (n ? c(t, e, r) : c(r)) || r);
11
+ return n && r && _e(t, e, r), r;
12
+ }, p = (s, t) => (e, n) => t(e, n, s);
13
+ const T = "rpc.remote-sync.service", f = O(T);
14
+ let M = class {
15
+ constructor(s) {
16
+ this._commandService = s;
17
+ }
18
+ async syncMutation(s) {
19
+ return this._commandService.syncExecuteCommand(s.mutationInfo.id, s.mutationInfo.params, {
22
20
  onlyLocal: !0,
23
21
  fromSync: !0
24
22
  });
25
23
  }
26
- }, __name(_a, "RemoteSyncPrimaryService"), _a);
27
- RemoteSyncPrimaryService = __decorateClass$3([
28
- __decorateParam$3(0, ICommandService)
29
- ], RemoteSyncPrimaryService);
30
- const RemoteInstanceServiceName = "univer.remote-instance-service", IRemoteInstanceService = createIdentifier(RemoteInstanceServiceName);
31
- var _a2;
32
- let WebWorkerRemoteInstanceService = (_a2 = class {
33
- constructor(_univerInstanceService, _commandService, _logService) {
34
- this._univerInstanceService = _univerInstanceService, this._commandService = _commandService, this._logService = _logService;
24
+ };
25
+ M = V([
26
+ p(0, b)
27
+ ], M);
28
+ const W = "univer.remote-instance-service", m = O(W);
29
+ let q = class {
30
+ constructor(s, t, e) {
31
+ this._univerInstanceService = s, this._commandService = t, this._logService = e;
35
32
  }
36
33
  whenReady() {
37
34
  return Promise.resolve(!0);
38
35
  }
39
- async syncMutation(params) {
40
- return this._applyMutation(params.mutationInfo);
36
+ async syncMutation(s) {
37
+ return this._applyMutation(s.mutationInfo);
41
38
  }
42
- async createInstance(params) {
43
- const { type, snapshot } = params;
39
+ async createInstance(s) {
40
+ const { type: t, snapshot: e } = s;
44
41
  try {
45
- switch (type) {
46
- case UniverInstanceType.UNIVER_SHEET:
47
- return this._univerInstanceService.createUnit(UniverInstanceType.UNIVER_SHEET, snapshot), !0;
42
+ switch (t) {
43
+ case u.UNIVER_SHEET:
44
+ return this._univerInstanceService.createUnit(u.UNIVER_SHEET, e), !0;
48
45
  default:
49
46
  throw new Error(
50
- `[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`
47
+ `[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${t}.`
51
48
  );
52
49
  }
53
- } catch (err) {
54
- throw err instanceof Error ? err : new TypeError(`${err}`);
50
+ } catch (n) {
51
+ throw n instanceof Error ? n : new TypeError(`${n}`);
55
52
  }
56
53
  }
57
- async disposeInstance(params) {
58
- return this._univerInstanceService.disposeUnit(params.unitID);
54
+ async disposeInstance(s) {
55
+ return this._univerInstanceService.disposeUnit(s.unitID);
59
56
  }
60
- _applyMutation(mutationInfo) {
61
- const { id, params: mutationParams } = mutationInfo;
62
- return this._commandService.syncExecuteCommand(id, mutationParams, {
57
+ _applyMutation(s) {
58
+ const { id: t, params: e } = s;
59
+ return this._commandService.syncExecuteCommand(t, e, {
63
60
  onlyLocal: !0,
64
61
  fromSync: !0
65
62
  });
66
63
  }
67
- }, __name(_a2, "WebWorkerRemoteInstanceService"), _a2);
68
- WebWorkerRemoteInstanceService = __decorateClass$3([
69
- __decorateParam$3(0, IUniverInstanceService),
70
- __decorateParam$3(1, ICommandService),
71
- __decorateParam$3(2, ILogService)
72
- ], WebWorkerRemoteInstanceService);
73
- function fromModule(module) {
74
- const handler = module;
64
+ };
65
+ q = V([
66
+ p(0, x),
67
+ p(1, b),
68
+ p(2, Q)
69
+ ], q);
70
+ function F(s) {
71
+ const t = s;
75
72
  return new class {
76
- call(method, args) {
77
- const target = handler[method];
78
- if (typeof target == "function") {
79
- let res = target.apply(handler, [args]);
80
- return res instanceof Promise || (res = Promise.resolve(res)), res;
73
+ call(e, n) {
74
+ const r = t[e];
75
+ if (typeof r == "function") {
76
+ let i = r.apply(t, [n]);
77
+ return i instanceof Promise || (i = Promise.resolve(i)), i;
81
78
  }
82
- throw new Error(`[RPC]: method not found for ${method}!`);
79
+ throw new Error(`[RPC]: method not found for ${e}!`);
83
80
  }
84
- subscribe(eventMethod, args) {
85
- const target = handler[eventMethod];
86
- if (typeof target == "function") {
87
- const res = target.apply(handler, args);
88
- return isObservable(res) ? res : of(res);
81
+ subscribe(e, n) {
82
+ const r = t[e];
83
+ if (typeof r == "function") {
84
+ const i = r.apply(t, n);
85
+ return ne(i) ? i : se(i);
89
86
  }
90
- throw new Error(`[RPC]: observable method not found for ${eventMethod}!`);
87
+ throw new Error(`[RPC]: observable method not found for ${e}!`);
91
88
  }
92
89
  }();
93
90
  }
94
- __name(fromModule, "fromModule");
95
- function toModule(channel) {
91
+ function G(s) {
96
92
  return new Proxy({}, {
97
- get(_, propKey) {
98
- if (propKey !== "dispose")
99
- return function(...args) {
100
- return propertyIsEventSource(propKey) ? channel.subscribe(propKey, args[0]) : channel.call(propKey, args[0]);
93
+ get(t, e) {
94
+ if (e !== "dispose")
95
+ return function(...n) {
96
+ return ue(e) ? s.subscribe(e, n[0]) : s.call(e, n[0]);
101
97
  };
102
98
  }
103
99
  });
104
100
  }
105
- __name(toModule, "toModule");
106
- function propertyIsEventSource(name) {
107
- return name.endsWith("$");
101
+ function ue(s) {
102
+ return s.endsWith("$");
108
103
  }
109
- __name(propertyIsEventSource, "propertyIsEventSource");
110
- const _ChannelClient = class _ChannelClient extends RxDisposable {
111
- constructor(_protocol) {
104
+ class de extends j {
105
+ constructor(e) {
112
106
  super();
113
- __publicField(this, "_initialized", new BehaviorSubject(!1));
114
- __publicField(this, "_lastRequestCounter", 0);
115
- __publicField(this, "_pendingRequests", /* @__PURE__ */ new Map());
116
- this._protocol = _protocol, this._protocol.onMessage.pipe(takeUntil(this.dispose$)).subscribe((message) => this._onMessage(message));
107
+ a(this, "_initialized", new re(!1));
108
+ a(this, "_lastRequestCounter", 0);
109
+ a(this, "_pendingRequests", /* @__PURE__ */ new Map());
110
+ this._protocol = e, this._protocol.onMessage.pipe(v(this.dispose$)).subscribe((n) => this._onMessage(n));
117
111
  }
118
112
  dispose() {
119
113
  this._pendingRequests.clear();
120
114
  }
121
- getChannel(channelName) {
122
- const self = this;
115
+ getChannel(e) {
116
+ const n = this;
123
117
  return {
124
- call(method, args) {
125
- return self._disposed ? Promise.reject() : self._remoteCall(channelName, method, args);
118
+ call(r, i) {
119
+ return n._disposed ? Promise.reject() : n._remoteCall(e, r, i);
126
120
  },
127
- subscribe(eventMethod, args) {
128
- if (self._disposed)
121
+ subscribe(r, i) {
122
+ if (n._disposed)
129
123
  throw new Error("[ChannelClient]: client is disposed!");
130
- return self._remoteSubscribe(channelName, eventMethod, args);
124
+ return n._remoteSubscribe(e, r, i);
131
125
  }
132
126
  };
133
127
  }
134
128
  _whenReady() {
135
- return firstValueFrom(
129
+ return ie(
136
130
  this._initialized.pipe(
137
- filter((v) => v),
138
- take(1)
131
+ ee((e) => e),
132
+ te(1)
139
133
  )
140
134
  );
141
135
  }
142
- async _remoteCall(channelName, method, args) {
136
+ async _remoteCall(e, n, r) {
143
137
  await this._whenReady();
144
- const sequence = ++this._lastRequestCounter, request = { seq: sequence, type: 100, channelName, method, args }, client = this;
145
- return new Promise((resolve, reject) => {
146
- const responseHandler = {
147
- handle(response) {
148
- switch (response.type) {
138
+ const i = ++this._lastRequestCounter, h = { seq: i, type: 100, channelName: e, method: n, args: r }, o = this;
139
+ return new Promise((w, _) => {
140
+ const B = {
141
+ handle(P) {
142
+ switch (P.type) {
149
143
  case 201:
150
- client._pendingRequests.delete(sequence), resolve(response.data);
144
+ o._pendingRequests.delete(i), w(P.data);
151
145
  break;
152
146
  case 202:
153
- client._pendingRequests.delete(sequence), reject(response.data);
147
+ o._pendingRequests.delete(i), _(P.data);
154
148
  break;
155
149
  default:
156
150
  throw new Error("[ChannelClient]: unknown response type!");
157
151
  }
158
152
  }
159
153
  };
160
- this._pendingRequests.set(sequence, responseHandler), this._sendRequest(request);
154
+ this._pendingRequests.set(i, B), this._sendRequest(h);
161
155
  });
162
156
  }
163
- _remoteSubscribe(channelName, method, args) {
164
- return new Observable((subscriber) => {
165
- let sequence = -1;
157
+ _remoteSubscribe(e, n, r) {
158
+ return new $((i) => {
159
+ let c = -1;
166
160
  return this._whenReady().then(() => {
167
- sequence = ++this._lastRequestCounter;
168
- const request = { seq: sequence, type: 101, channelName, method, args }, responseHandler = {
169
- handle(response) {
170
- switch (response.type) {
161
+ c = ++this._lastRequestCounter;
162
+ const o = { seq: c, type: 101, channelName: e, method: n, args: r }, w = {
163
+ handle(_) {
164
+ switch (_.type) {
171
165
  case 300:
172
- subscriber.next(response.data);
166
+ i.next(_.data);
173
167
  break;
174
168
  case 301:
175
- subscriber.error(response.data);
169
+ i.error(_.data);
176
170
  break;
177
171
  case 302:
178
- subscriber.complete();
172
+ i.complete();
179
173
  break;
180
174
  default:
181
175
  throw new Error("[ChannelClient]: unknown response type!");
182
176
  }
183
177
  }
184
178
  };
185
- this._pendingRequests.set(sequence, responseHandler), this._sendRequest(request);
179
+ this._pendingRequests.set(c, w), this._sendRequest(o);
186
180
  }), () => {
187
- if (sequence === -1)
181
+ if (c === -1)
188
182
  return;
189
- const cancelSubscriptionRequest = {
183
+ const h = {
190
184
  type: 102,
191
- seq: sequence,
192
- channelName,
193
- method
185
+ seq: c,
186
+ channelName: e,
187
+ method: n
194
188
  };
195
- this._sendRequest(cancelSubscriptionRequest);
189
+ this._sendRequest(h);
196
190
  };
197
191
  });
198
192
  }
199
- _sendRequest(request) {
200
- this._protocol.send(request);
193
+ _sendRequest(e) {
194
+ this._protocol.send(e);
201
195
  }
202
- _onMessage(response) {
203
- var _a7;
204
- switch (response.type) {
196
+ _onMessage(e) {
197
+ var n;
198
+ switch (e.type) {
205
199
  case 0:
206
200
  this._initialized.next(!0);
207
201
  break;
@@ -210,19 +204,17 @@ const _ChannelClient = class _ChannelClient extends RxDisposable {
210
204
  case 300:
211
205
  case 302:
212
206
  case 301:
213
- (_a7 = this._pendingRequests.get(response.seq)) == null || _a7.handle(response);
207
+ (n = this._pendingRequests.get(e.seq)) == null || n.handle(e);
214
208
  break;
215
209
  }
216
210
  }
217
- };
218
- __name(_ChannelClient, "ChannelClient");
219
- let ChannelClient = _ChannelClient;
220
- const _ChannelServer = class _ChannelServer extends RxDisposable {
221
- constructor(_protocol) {
211
+ }
212
+ class pe extends j {
213
+ constructor(e) {
222
214
  super();
223
- __publicField(this, "_channels", /* @__PURE__ */ new Map());
224
- __publicField(this, "_subscriptions", /* @__PURE__ */ new Map());
225
- this._protocol = _protocol, this._protocol.onMessage.pipe(takeUntil(this.dispose$)).subscribe((message) => this._onRequest(message)), this._sendResponse({
215
+ a(this, "_channels", /* @__PURE__ */ new Map());
216
+ a(this, "_subscriptions", /* @__PURE__ */ new Map());
217
+ this._protocol = e, this._protocol.onMessage.pipe(v(this.dispose$)).subscribe((n) => this._onRequest(n)), this._sendResponse({
226
218
  seq: -1,
227
219
  type: 0
228
220
  /* INITIALIZE */
@@ -231,291 +223,286 @@ const _ChannelServer = class _ChannelServer extends RxDisposable {
231
223
  dispose() {
232
224
  super.dispose(), this._subscriptions.clear(), this._channels.clear();
233
225
  }
234
- registerChannel(channelName, channel) {
235
- this._channels.set(channelName, channel);
226
+ registerChannel(e, n) {
227
+ this._channels.set(e, n);
236
228
  }
237
- _onRequest(request) {
238
- switch (request.type) {
229
+ _onRequest(e) {
230
+ switch (e.type) {
239
231
  case 100:
240
- this._onMethodCall(request);
232
+ this._onMethodCall(e);
241
233
  break;
242
234
  case 101:
243
- this._onSubscribe(request);
235
+ this._onSubscribe(e);
244
236
  break;
245
237
  case 102:
246
- this._onUnsubscribe(request);
238
+ this._onUnsubscribe(e);
247
239
  break;
248
240
  }
249
241
  }
250
- _onMethodCall(request) {
251
- const { channelName, method, args } = request, channel = this._channels.get(channelName);
252
- let promise;
242
+ _onMethodCall(e) {
243
+ const { channelName: n, method: r, args: i } = e, c = this._channels.get(n);
244
+ let h;
253
245
  try {
254
- if (!channel)
255
- throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);
256
- promise = channel.call(method, args);
257
- } catch (err) {
258
- promise = Promise.reject(err);
246
+ if (!c)
247
+ throw new Error(`[ChannelServer]: Channel ${n} not found!`);
248
+ h = c.call(r, i);
249
+ } catch (o) {
250
+ h = Promise.reject(o);
259
251
  }
260
- promise.then((data) => {
261
- this._sendResponse({ seq: request.seq, type: 201, data });
262
- }).catch((err) => {
263
- err instanceof Error ? this._sendResponse({ seq: request.seq, type: 202, data: err.message }) : this._sendResponse({ seq: request.seq, type: 202, data: String(err) });
252
+ h.then((o) => {
253
+ this._sendResponse({ seq: e.seq, type: 201, data: o });
254
+ }).catch((o) => {
255
+ o instanceof Error ? this._sendResponse({ seq: e.seq, type: 202, data: o.message }) : this._sendResponse({ seq: e.seq, type: 202, data: String(o) });
264
256
  });
265
257
  }
266
- _onSubscribe(request) {
267
- const { channelName, seq } = request, channel = this._channels.get(channelName);
258
+ _onSubscribe(e) {
259
+ const { channelName: n, seq: r } = e, i = this._channels.get(n);
268
260
  try {
269
- if (!channel)
270
- throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);
271
- const subscription = channel.subscribe(request.method, request.args).subscribe({
272
- next: /* @__PURE__ */ __name((data) => {
273
- this._sendResponse({ seq, type: 300, data });
274
- }, "next"),
275
- error: /* @__PURE__ */ __name((err) => {
276
- this._sendResponse({ seq, type: 301, data: err.message }), this._sendResponse({
277
- seq,
261
+ if (!i)
262
+ throw new Error(`[ChannelServer]: Channel ${n} not found!`);
263
+ const h = i.subscribe(e.method, e.args).subscribe({
264
+ next: (o) => {
265
+ this._sendResponse({ seq: r, type: 300, data: o });
266
+ },
267
+ error: (o) => {
268
+ this._sendResponse({ seq: r, type: 301, data: o.message }), this._sendResponse({
269
+ seq: r,
278
270
  type: 302
279
271
  /* SUBSCRIBE_COMPLETE */
280
272
  });
281
- }, "error"),
282
- complete: /* @__PURE__ */ __name(() => {
273
+ },
274
+ complete: () => {
283
275
  this._sendResponse({
284
- seq,
276
+ seq: r,
285
277
  type: 302
286
278
  /* SUBSCRIBE_COMPLETE */
287
279
  });
288
- }, "complete")
280
+ }
289
281
  });
290
- this._subscriptions.set(request.seq, subscription);
291
- } catch (err) {
292
- err instanceof Error ? this._sendResponse({ seq: request.seq, type: 301, data: err.message }) : this._sendResponse({ seq: request.seq, type: 301, data: String(err) });
282
+ this._subscriptions.set(e.seq, h);
283
+ } catch (c) {
284
+ c instanceof Error ? this._sendResponse({ seq: e.seq, type: 301, data: c.message }) : this._sendResponse({ seq: e.seq, type: 301, data: String(c) });
293
285
  }
294
286
  }
295
- _onUnsubscribe(request) {
296
- const subscription = this._subscriptions.get(request.seq);
297
- subscription && (subscription.unsubscribe(), this._subscriptions.delete(request.seq));
287
+ _onUnsubscribe(e) {
288
+ const n = this._subscriptions.get(e.seq);
289
+ n && (n.unsubscribe(), this._subscriptions.delete(e.seq));
298
290
  }
299
- _sendResponse(response) {
300
- this._protocol.send(response);
291
+ _sendResponse(e) {
292
+ this._protocol.send(e);
301
293
  }
302
- };
303
- __name(_ChannelServer, "ChannelServer");
304
- let ChannelServer = _ChannelServer;
305
- const IRPCChannelService = createIdentifier("IRPCChannelService"), _ChannelService = class _ChannelService {
306
- constructor(_messageProtocol) {
307
- __publicField(this, "_client");
308
- __publicField(this, "_server");
309
- this._client = new ChannelClient(_messageProtocol), this._server = new ChannelServer(_messageProtocol);
294
+ }
295
+ const I = O("IRPCChannelService");
296
+ class z {
297
+ constructor(t) {
298
+ a(this, "_client");
299
+ a(this, "_server");
300
+ this._client = new de(t), this._server = new pe(t);
310
301
  }
311
302
  dispose() {
312
303
  this._client.dispose(), this._server.dispose();
313
304
  }
314
- requestChannel(name) {
315
- return this._client.getChannel(name);
305
+ requestChannel(t) {
306
+ return this._client.getChannel(t);
316
307
  }
317
- registerChannel(name, channel) {
318
- this._server.registerChannel(name, channel);
308
+ registerChannel(t, e) {
309
+ this._server.registerChannel(t, e);
319
310
  }
320
- };
321
- __name(_ChannelService, "ChannelService");
322
- let ChannelService = _ChannelService;
323
- var __defProp$2 = Object.defineProperty, __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor, __decorateClass$2 = /* @__PURE__ */ __name((decorators, target, key, kind) => {
324
- for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
325
- (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
326
- return kind && result && __defProp$2(target, key, result), result;
327
- }, "__decorateClass$2"), __decorateParam$2 = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam$2"), _a3;
328
- let DataSyncPrimaryController = (_a3 = class extends RxDisposable {
329
- constructor(_injector, _commandService, _univerInstanceService, _rpcChannelService, _remoteSyncService) {
311
+ }
312
+ var ve = Object.defineProperty, fe = Object.getOwnPropertyDescriptor, me = (s, t, e, n) => {
313
+ for (var r = n > 1 ? void 0 : n ? fe(t, e) : t, i = s.length - 1, c; i >= 0; i--)
314
+ (c = s[i]) && (r = (n ? c(t, e, r) : c(r)) || r);
315
+ return n && r && ve(t, e, r), r;
316
+ }, l = (s, t) => (e, n) => t(e, n, s);
317
+ let g = class extends j {
318
+ constructor(t, e, n, r, i) {
330
319
  super();
331
- __publicField(this, "_remoteInstanceService");
332
- __publicField(this, "_syncingUnits", /* @__PURE__ */ new Set());
333
- __publicField(this, "_syncingMutations", /* @__PURE__ */ new Set());
334
- this._injector = _injector, this._commandService = _commandService, this._univerInstanceService = _univerInstanceService, this._rpcChannelService = _rpcChannelService, this._remoteSyncService = _remoteSyncService, this._initRPCChannels(), this._init();
320
+ a(this, "_remoteInstanceService");
321
+ a(this, "_syncingUnits", /* @__PURE__ */ new Set());
322
+ a(this, "_syncingMutations", /* @__PURE__ */ new Set());
323
+ this._injector = t, this._commandService = e, this._univerInstanceService = n, this._rpcChannelService = r, this._remoteSyncService = i, this._initRPCChannels(), this._init();
335
324
  }
336
- registerSyncingMutations(mutation) {
337
- this._syncingMutations.add(mutation.id);
325
+ registerSyncingMutations(t) {
326
+ this._syncingMutations.add(t.id);
338
327
  }
339
328
  /**
340
329
  * Only spreadsheets would be synced to the web worker in normal situations. If you would like to
341
330
  * sync other types of documents, you should manually call this method with that document's id.
342
331
  */
343
- syncUnit(unitId) {
344
- return this._syncingUnits.add(unitId), toDisposable(() => this._syncingUnits.delete(unitId));
332
+ syncUnit(t) {
333
+ return this._syncingUnits.add(t), X(() => this._syncingUnits.delete(t));
345
334
  }
346
335
  _initRPCChannels() {
347
- this._rpcChannelService.registerChannel(RemoteSyncServiceName, fromModule(this._remoteSyncService)), this._injector.add([
348
- IRemoteInstanceService,
349
- { useFactory: /* @__PURE__ */ __name(() => toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)), "useFactory") }
350
- ]), this._remoteInstanceService = this._injector.get(IRemoteInstanceService);
336
+ this._rpcChannelService.registerChannel(T, F(this._remoteSyncService)), this._injector.add([
337
+ m,
338
+ { useFactory: () => G(this._rpcChannelService.requestChannel(W)) }
339
+ ]), this._remoteInstanceService = this._injector.get(m);
351
340
  }
352
341
  _init() {
353
- this._univerInstanceService.getTypeOfUnitAdded$(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((sheet) => {
354
- this._syncingUnits.add(sheet.getUnitId()), this._remoteInstanceService.createInstance({
355
- unitID: sheet.getUnitId(),
356
- type: UniverInstanceType.UNIVER_SHEET,
357
- snapshot: sheet.getSnapshot()
342
+ this._univerInstanceService.getTypeOfUnitAdded$(u.UNIVER_SHEET).pipe(v(this.dispose$)).subscribe((t) => {
343
+ this._syncingUnits.add(t.getUnitId()), this._remoteInstanceService.createInstance({
344
+ unitID: t.getUnitId(),
345
+ type: u.UNIVER_SHEET,
346
+ snapshot: t.getSnapshot()
358
347
  });
359
- }), this._univerInstanceService.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((workbook) => {
360
- this._syncingUnits.delete(workbook.getUnitId()), this._remoteInstanceService.disposeInstance({
361
- unitID: workbook.getUnitId()
348
+ }), this._univerInstanceService.getTypeOfUnitDisposed$(u.UNIVER_SHEET).pipe(v(this.dispose$)).subscribe((t) => {
349
+ this._syncingUnits.delete(t.getUnitId()), this._remoteInstanceService.disposeInstance({
350
+ unitID: t.getUnitId()
362
351
  });
363
- }), this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo, options) => {
364
- const { type, params, id } = commandInfo, unitId = (params == null ? void 0 : params.unitId) || "";
365
- type === CommandType.MUTATION && // only sync mutations to the worker thread
366
- (!unitId || this._syncingUnits.has(unitId)) && // do not sync mutations from the web worker back to the web worker
367
- !(options != null && options.fromSync) && // do not sync mutations those are not meant to be synced
368
- this._syncingMutations.has(id) && this._remoteInstanceService.syncMutation({ mutationInfo: commandInfo });
352
+ }), this.disposeWithMe(this._commandService.onCommandExecuted((t, e) => {
353
+ const { type: n, params: r, id: i } = t, c = (r == null ? void 0 : r.unitId) || "";
354
+ n === L.MUTATION && // only sync mutations to the worker thread
355
+ (!c || this._syncingUnits.has(c)) && // do not sync mutations from the web worker back to the web worker
356
+ !(e != null && e.fromSync) && // do not sync mutations those are not meant to be synced
357
+ this._syncingMutations.has(i) && this._remoteInstanceService.syncMutation({ mutationInfo: t });
369
358
  }));
370
359
  }
371
- }, __name(_a3, "DataSyncPrimaryController"), _a3);
372
- DataSyncPrimaryController = __decorateClass$2([
373
- __decorateParam$2(0, Inject(Injector)),
374
- __decorateParam$2(1, ICommandService),
375
- __decorateParam$2(2, IUniverInstanceService),
376
- __decorateParam$2(3, IRPCChannelService),
377
- __decorateParam$2(4, IRemoteSyncService)
378
- ], DataSyncPrimaryController);
379
- var __defProp$1 = Object.defineProperty, __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor, __decorateClass$1 = /* @__PURE__ */ __name((decorators, target, key, kind) => {
380
- for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
381
- (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
382
- return kind && result && __defProp$1(target, key, result), result;
383
- }, "__decorateClass$1"), __decorateParam$1 = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam$1"), _a4;
384
- let DataSyncReplicaController = (_a4 = class extends Disposable {
385
- constructor(_injector, _remoteInstanceService, _commandService, _rpcChannelService) {
360
+ };
361
+ g = me([
362
+ l(0, C(R)),
363
+ l(1, b),
364
+ l(2, x),
365
+ l(3, I),
366
+ l(4, f)
367
+ ], g);
368
+ var ge = Object.defineProperty, ye = Object.getOwnPropertyDescriptor, Se = (s, t, e, n) => {
369
+ for (var r = n > 1 ? void 0 : n ? ye(t, e) : t, i = s.length - 1, c; i >= 0; i--)
370
+ (c = s[i]) && (r = (n ? c(t, e, r) : c(r)) || r);
371
+ return n && r && ge(t, e, r), r;
372
+ }, d = (s, t) => (e, n) => t(e, n, s);
373
+ let y = class extends Z {
374
+ constructor(t, e, n, r) {
386
375
  super();
387
- __publicField(this, "_remoteSyncService");
388
- this._injector = _injector, this._remoteInstanceService = _remoteInstanceService, this._commandService = _commandService, this._rpcChannelService = _rpcChannelService, this._initRPCChannels(), this._init();
376
+ a(this, "_remoteSyncService");
377
+ this._injector = t, this._remoteInstanceService = e, this._commandService = n, this._rpcChannelService = r, this._initRPCChannels(), this._init();
389
378
  }
390
379
  _initRPCChannels() {
391
- this._rpcChannelService.registerChannel(RemoteInstanceServiceName, fromModule(this._remoteInstanceService)), this._injector.add([
392
- IRemoteSyncService,
393
- { useFactory: /* @__PURE__ */ __name(() => toModule(this._rpcChannelService.requestChannel(RemoteSyncServiceName)), "useFactory") }
394
- ]), this._remoteSyncService = this._injector.get(IRemoteSyncService);
380
+ this._rpcChannelService.registerChannel(W, F(this._remoteInstanceService)), this._injector.add([
381
+ f,
382
+ { useFactory: () => G(this._rpcChannelService.requestChannel(T)) }
383
+ ]), this._remoteSyncService = this._injector.get(f);
395
384
  }
396
385
  _init() {
397
386
  this.disposeWithMe(
398
387
  // Mutations executed on the main thread should be synced to the worker thread.
399
- this._commandService.onCommandExecuted((commandInfo, options) => {
400
- commandInfo.type === CommandType.MUTATION && !(options != null && options.fromSync) && this._remoteSyncService.syncMutation({
401
- mutationInfo: commandInfo
388
+ this._commandService.onCommandExecuted((t, e) => {
389
+ t.type === L.MUTATION && !(e != null && e.fromSync) && this._remoteSyncService.syncMutation({
390
+ mutationInfo: t
402
391
  });
403
392
  })
404
393
  );
405
394
  }
406
- }, __name(_a4, "DataSyncReplicaController"), _a4);
407
- DataSyncReplicaController = __decorateClass$1([
408
- __decorateParam$1(0, Inject(Injector)),
409
- __decorateParam$1(1, IRemoteInstanceService),
410
- __decorateParam$1(2, ICommandService),
411
- __decorateParam$1(3, IRPCChannelService)
412
- ], DataSyncReplicaController);
413
- function createWebWorkerMessagePortOnWorker() {
395
+ };
396
+ y = Se([
397
+ d(0, C(R)),
398
+ d(1, m),
399
+ d(2, b),
400
+ d(3, I)
401
+ ], y);
402
+ function be() {
414
403
  return {
415
- send(message) {
416
- postMessage(message);
404
+ send(s) {
405
+ postMessage(s);
417
406
  },
418
- onMessage: new Observable((subscriber) => {
419
- const handler = /* @__PURE__ */ __name((event) => {
420
- subscriber.next(event.data);
421
- }, "handler");
422
- return addEventListener("message", handler), () => removeEventListener("message", handler);
423
- }).pipe(shareReplay(1))
407
+ onMessage: new $((s) => {
408
+ const t = (e) => {
409
+ s.next(e.data);
410
+ };
411
+ return addEventListener("message", t), () => removeEventListener("message", t);
412
+ }).pipe(A(1))
424
413
  };
425
414
  }
426
- __name(createWebWorkerMessagePortOnWorker, "createWebWorkerMessagePortOnWorker");
427
- function createWebWorkerMessagePortOnMain(worker) {
415
+ function Ce(s) {
428
416
  return {
429
- send(message) {
430
- worker.postMessage(message);
417
+ send(t) {
418
+ s.postMessage(t);
431
419
  },
432
- onMessage: new Observable((subscriber) => {
433
- const handler = /* @__PURE__ */ __name((event) => {
434
- subscriber.next(event.data);
435
- }, "handler");
436
- return worker.addEventListener("message", handler), () => worker.removeEventListener("message", handler);
437
- }).pipe(shareReplay(1))
420
+ onMessage: new $((t) => {
421
+ const e = (n) => {
422
+ t.next(n.data);
423
+ };
424
+ return s.addEventListener("message", e), () => s.removeEventListener("message", e);
425
+ }).pipe(A(1))
438
426
  };
439
427
  }
440
- __name(createWebWorkerMessagePortOnMain, "createWebWorkerMessagePortOnMain");
441
- var __defProp2 = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = /* @__PURE__ */ __name((decorators, target, key, kind) => {
442
- for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
443
- (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
444
- return kind && result && __defProp2(target, key, result), result;
445
- }, "__decorateClass"), __decorateParam = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam"), _a5;
446
- let UniverRPCMainThreadPlugin = (_a5 = class extends Plugin {
447
- constructor(_config = defaultPluginMainThreadConfig, _injector, _configService) {
428
+ var Re = Object.defineProperty, Ie = Object.getOwnPropertyDescriptor, Y = (s, t, e, n) => {
429
+ for (var r = n > 1 ? void 0 : n ? Ie(t, e) : t, i = s.length - 1, c; i >= 0; i--)
430
+ (c = s[i]) && (r = (n ? c(t, e, r) : c(r)) || r);
431
+ return n && r && Re(t, e, r), r;
432
+ }, S = (s, t) => (e, n) => t(e, n, s), E;
433
+ let D = (E = class extends H {
434
+ constructor(t = oe, e, n) {
448
435
  super();
449
- __publicField(this, "_internalWorker", null);
450
- this._config = _config, this._injector = _injector, this._configService = _configService;
451
- const { ...rest } = this._config;
452
- this._configService.setConfig(PLUGIN_CONFIG_KEY_MAIN_THREAD, rest);
436
+ a(this, "_internalWorker", null);
437
+ this._config = t, this._injector = e, this._configService = n;
438
+ const { ...r } = this._config;
439
+ this._configService.setConfig(ce, r);
453
440
  }
454
441
  dispose() {
455
442
  super.dispose(), this._internalWorker && (this._internalWorker.terminate(), this._internalWorker = null);
456
443
  }
457
444
  onStarting() {
458
- const { workerURL } = this._config;
459
- if (!workerURL)
445
+ const { workerURL: t } = this._config;
446
+ if (!t)
460
447
  throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");
461
- const worker = workerURL instanceof Worker ? workerURL : new Worker(workerURL);
462
- this._internalWorker = workerURL instanceof Worker ? null : worker;
463
- const messageProtocol = createWebWorkerMessagePortOnMain(worker);
448
+ const e = t instanceof Worker ? t : new Worker(t);
449
+ this._internalWorker = t instanceof Worker ? null : e;
450
+ const n = Ce(e);
464
451
  [
465
452
  [
466
- IRPCChannelService,
453
+ I,
467
454
  {
468
- useFactory: /* @__PURE__ */ __name(() => new ChannelService(messageProtocol), "useFactory")
455
+ useFactory: () => new z(n)
469
456
  }
470
457
  ],
471
- [DataSyncPrimaryController],
472
- [IRemoteSyncService, { useClass: RemoteSyncPrimaryService }]
473
- ].forEach((dependency) => this._injector.add(dependency)), this._injector.get(DataSyncPrimaryController);
474
- }
475
- }, __name(_a5, "UniverRPCMainThreadPlugin"), __publicField(_a5, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN"), _a5);
476
- UniverRPCMainThreadPlugin = __decorateClass([
477
- __decorateParam(1, Inject(Injector)),
478
- __decorateParam(2, IConfigService)
479
- ], UniverRPCMainThreadPlugin);
480
- var _a6;
481
- let UniverRPCWorkerThreadPlugin = (_a6 = class extends Plugin {
482
- constructor(_config = defaultPluginWorkerThreadConfig, _injector, _configService) {
483
- super(), this._config = _config, this._injector = _injector, this._configService = _configService;
484
- const { ...rest } = this._config;
485
- this._configService.setConfig(PLUGIN_CONFIG_KEY_WORKER_THREAD, rest);
458
+ [g],
459
+ [f, { useClass: M }]
460
+ ].forEach((i) => this._injector.add(i)), this._injector.get(g);
461
+ }
462
+ }, a(E, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN"), E);
463
+ D = Y([
464
+ S(1, C(R)),
465
+ S(2, k)
466
+ ], D);
467
+ var U;
468
+ let N = (U = class extends H {
469
+ constructor(s = he, t, e) {
470
+ super(), this._config = s, this._injector = t, this._configService = e;
471
+ const { ...n } = this._config;
472
+ this._configService.setConfig(ae, n);
486
473
  }
487
474
  onStarting() {
488
475
  [
489
- [DataSyncReplicaController],
476
+ [y],
490
477
  [
491
- IRPCChannelService,
478
+ I,
492
479
  {
493
- useFactory: /* @__PURE__ */ __name(() => new ChannelService(createWebWorkerMessagePortOnWorker()), "useFactory")
480
+ useFactory: () => new z(be())
494
481
  }
495
482
  ],
496
- [IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }]
497
- ].forEach((dependency) => this._injector.add(dependency)), this._injector.get(DataSyncReplicaController);
498
- }
499
- }, __name(_a6, "UniverRPCWorkerThreadPlugin"), __publicField(_a6, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN"), _a6);
500
- UniverRPCWorkerThreadPlugin = __decorateClass([
501
- __decorateParam(1, Inject(Injector)),
502
- __decorateParam(2, IConfigService)
503
- ], UniverRPCWorkerThreadPlugin);
483
+ [m, { useClass: q }]
484
+ ].forEach((s) => this._injector.add(s)), this._injector.get(y);
485
+ }
486
+ }, a(U, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN"), U);
487
+ N = Y([
488
+ S(1, C(R)),
489
+ S(2, k)
490
+ ], N);
504
491
  export {
505
- ChannelClient,
506
- ChannelServer,
507
- ChannelService,
508
- DataSyncPrimaryController,
509
- DataSyncReplicaController,
510
- IRPCChannelService,
511
- IRemoteInstanceService,
512
- IRemoteSyncService,
513
- RemoteInstanceServiceName,
514
- RemoteSyncPrimaryService,
515
- RemoteSyncServiceName,
516
- UniverRPCMainThreadPlugin,
517
- UniverRPCWorkerThreadPlugin,
518
- WebWorkerRemoteInstanceService,
519
- fromModule,
520
- toModule
492
+ de as ChannelClient,
493
+ pe as ChannelServer,
494
+ z as ChannelService,
495
+ g as DataSyncPrimaryController,
496
+ y as DataSyncReplicaController,
497
+ I as IRPCChannelService,
498
+ m as IRemoteInstanceService,
499
+ f as IRemoteSyncService,
500
+ W as RemoteInstanceServiceName,
501
+ M as RemoteSyncPrimaryService,
502
+ T as RemoteSyncServiceName,
503
+ D as UniverRPCMainThreadPlugin,
504
+ N as UniverRPCWorkerThreadPlugin,
505
+ q as WebWorkerRemoteInstanceService,
506
+ F as fromModule,
507
+ G as toModule
521
508
  };
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;const PLUGIN_CONFIG_KEY_MAIN_THREAD="rpc.main-thread.config",defaultPluginMainThreadConfig={},PLUGIN_CONFIG_KEY_WORKER_THREAD="rpc.worker-thread.config",defaultPluginWorkerThreadConfig={};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([__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([__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=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"})});
1
+ (function(r,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs/operators"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs/operators","rxjs"],a):(r=typeof globalThis<"u"?globalThis:r||self,a(r.UniverRpc={},r.UniverCore,r.rxjs.operators,r.rxjs))})(this,function(r,a,u,d){"use strict";var x=Object.defineProperty;var ee=(r,a,u)=>a in r?x(r,a,{enumerable:!0,configurable:!0,writable:!0,value:u}):r[a]=u;var l=(r,a,u)=>ee(r,typeof a!="symbol"?a+"":a,u);var U,E;const O="rpc.main-thread.config",$={},N="rpc.worker-thread.config",k={};var L=Object.defineProperty,H=Object.getOwnPropertyDescriptor,q=(c,t,e,n)=>{for(var s=n>1?void 0:n?H(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&L(t,e,s),s},f=(c,t)=>(e,n)=>t(e,n,c);const C="rpc.remote-sync.service",v=a.createIdentifier(C);r.RemoteSyncPrimaryService=class{constructor(t){this._commandService=t}async syncMutation(t){return this._commandService.syncExecuteCommand(t.mutationInfo.id,t.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},r.RemoteSyncPrimaryService=q([f(0,a.ICommandService)],r.RemoteSyncPrimaryService);const R="univer.remote-instance-service",p=a.createIdentifier(R);r.WebWorkerRemoteInstanceService=class{constructor(t,e,n){this._univerInstanceService=t,this._commandService=e,this._logService=n}whenReady(){return Promise.resolve(!0)}async syncMutation(t){return this._applyMutation(t.mutationInfo)}async createInstance(t){const{type:e,snapshot:n}=t;try{switch(e){case a.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(a.UniverInstanceType.UNIVER_SHEET,n),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(t){return this._univerInstanceService.disposeUnit(t.unitID)}_applyMutation(t){const{id:e,params:n}=t;return this._commandService.syncExecuteCommand(e,n,{onlyLocal:!0,fromSync:!0})}},r.WebWorkerRemoteInstanceService=q([f(0,a.IUniverInstanceService),f(1,a.ICommandService),f(2,a.ILogService)],r.WebWorkerRemoteInstanceService);function b(c){const t=c;return new class{call(e,n){const s=t[e];if(typeof s=="function"){let i=s.apply(t,[n]);return i instanceof Promise||(i=Promise.resolve(i)),i}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,n){const s=t[e];if(typeof s=="function"){const i=s.apply(t,n);return d.isObservable(i)?i:d.of(i)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function P(c){return new Proxy({},{get(t,e){if(e!=="dispose")return function(...n){return A(e)?c.subscribe(e,n[0]):c.call(e,n[0])}}})}function A(c){return c.endsWith("$")}class W extends a.RxDisposable{constructor(e){super();l(this,"_initialized",new d.BehaviorSubject(!1));l(this,"_lastRequestCounter",0);l(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onMessage(n))}dispose(){this._pendingRequests.clear()}getChannel(e){const n=this;return{call(s,i){return n._disposed?Promise.reject():n._remoteCall(e,s,i)},subscribe(s,i){if(n._disposed)throw new Error("[ChannelClient]: client is disposed!");return n._remoteSubscribe(e,s,i)}}}_whenReady(){return d.firstValueFrom(this._initialized.pipe(u.filter(e=>e),u.take(1)))}async _remoteCall(e,n,s){await this._whenReady();const i=++this._lastRequestCounter,_={seq:i,type:100,channelName:e,method:n,args:s},h=this;return new Promise((M,y)=>{const Z={handle(T){switch(T.type){case 201:h._pendingRequests.delete(i),M(T.data);break;case 202:h._pendingRequests.delete(i),y(T.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(i,Z),this._sendRequest(_)})}_remoteSubscribe(e,n,s){return new d.Observable(i=>{let o=-1;return this._whenReady().then(()=>{o=++this._lastRequestCounter;const h={seq:o,type:101,channelName:e,method:n,args:s},M={handle(y){switch(y.type){case 300:i.next(y.data);break;case 301:i.error(y.data);break;case 302:i.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(o,M),this._sendRequest(h)}),()=>{if(o===-1)return;const _={type:102,seq:o,channelName:e,method:n};this._sendRequest(_)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var n;switch(e.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(n=this._pendingRequests.get(e.seq))==null||n.handle(e);break}}}class j extends a.RxDisposable{constructor(e){super();l(this,"_channels",new Map);l(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onRequest(n)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,n){this._channels.set(e,n)}_onRequest(e){switch(e.type){case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_onMethodCall(e){const{channelName:n,method:s,args:i}=e,o=this._channels.get(n);let _;try{if(!o)throw new Error(`[ChannelServer]: Channel ${n} not found!`);_=o.call(s,i)}catch(h){_=Promise.reject(h)}_.then(h=>{this._sendResponse({seq:e.seq,type:201,data:h})}).catch(h=>{h instanceof Error?this._sendResponse({seq:e.seq,type:202,data:h.message}):this._sendResponse({seq:e.seq,type:202,data:String(h)})})}_onSubscribe(e){const{channelName:n,seq:s}=e,i=this._channels.get(n);try{if(!i)throw new Error(`[ChannelServer]: Channel ${n} not found!`);const _=i.subscribe(e.method,e.args).subscribe({next:h=>{this._sendResponse({seq:s,type:300,data:h})},error:h=>{this._sendResponse({seq:s,type:301,data:h.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,_)}catch(o){o instanceof Error?this._sendResponse({seq:e.seq,type:301,data:o.message}):this._sendResponse({seq:e.seq,type:301,data:String(o)})}}_onUnsubscribe(e){const n=this._subscriptions.get(e.seq);n&&(n.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const m=a.createIdentifier("IRPCChannelService");class w{constructor(t){l(this,"_client");l(this,"_server");this._client=new W(t),this._server=new j(t)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(t){return this._client.getChannel(t)}registerChannel(t,e){this._server.registerChannel(t,e)}}var V=Object.defineProperty,F=Object.getOwnPropertyDescriptor,G=(c,t,e,n)=>{for(var s=n>1?void 0:n?F(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&V(t,e,s),s},S=(c,t)=>(e,n)=>t(e,n,c);r.DataSyncPrimaryController=class extends a.RxDisposable{constructor(e,n,s,i,o){super();l(this,"_remoteInstanceService");l(this,"_syncingUnits",new Set);l(this,"_syncingMutations",new Set);this._injector=e,this._commandService=n,this._univerInstanceService=s,this._rpcChannelService=i,this._remoteSyncService=o,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),a.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(C,b(this._remoteSyncService)),this._injector.add([p,{useFactory:()=>P(this._rpcChannelService.requestChannel(R))}]),this._remoteInstanceService=this._injector.get(p)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:a.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{const{type:s,params:i,id:o}=e,_=(i==null?void 0:i.unitId)||"";s===a.CommandType.MUTATION&&(!_||this._syncingUnits.has(_))&&!(n!=null&&n.fromSync)&&this._syncingMutations.has(o)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}},r.DataSyncPrimaryController=G([S(0,a.Inject(a.Injector)),S(1,a.ICommandService),S(2,a.IUniverInstanceService),S(3,m),S(4,v)],r.DataSyncPrimaryController);var z=Object.defineProperty,Y=Object.getOwnPropertyDescriptor,B=(c,t,e,n)=>{for(var s=n>1?void 0:n?Y(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&z(t,e,s),s},g=(c,t)=>(e,n)=>t(e,n,c);r.DataSyncReplicaController=class extends a.Disposable{constructor(e,n,s,i){super();l(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=n,this._commandService=s,this._rpcChannelService=i,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(R,b(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>P(this._rpcChannelService.requestChannel(C))}]),this._remoteSyncService=this._injector.get(v)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{e.type===a.CommandType.MUTATION&&!(n!=null&&n.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}},r.DataSyncReplicaController=B([g(0,a.Inject(a.Injector)),g(1,p),g(2,a.ICommandService),g(3,m)],r.DataSyncReplicaController);function K(){return{send(c){postMessage(c)},onMessage:new d.Observable(c=>{const t=e=>{c.next(e.data)};return addEventListener("message",t),()=>removeEventListener("message",t)}).pipe(d.shareReplay(1))}}function J(c){return{send(t){c.postMessage(t)},onMessage:new d.Observable(t=>{const e=n=>{t.next(n.data)};return c.addEventListener("message",e),()=>c.removeEventListener("message",e)}).pipe(d.shareReplay(1))}}var Q=Object.defineProperty,X=Object.getOwnPropertyDescriptor,D=(c,t,e,n)=>{for(var s=n>1?void 0:n?X(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&Q(t,e,s),s},I=(c,t)=>(e,n)=>t(e,n,c);r.UniverRPCMainThreadPlugin=(U=class extends a.Plugin{constructor(e=$,n,s){super();l(this,"_internalWorker",null);this._config=e,this._injector=n,this._configService=s;const{...i}=this._config;this._configService.setConfig(O,i)}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL:e}=this._config;if(!e)throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");const n=e instanceof Worker?e:new Worker(e);this._internalWorker=e instanceof Worker?null:n;const s=J(n);[[m,{useFactory:()=>new w(s)}],[r.DataSyncPrimaryController],[v,{useClass:r.RemoteSyncPrimaryService}]].forEach(o=>this._injector.add(o)),this._injector.get(r.DataSyncPrimaryController)}},l(U,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),U),r.UniverRPCMainThreadPlugin=D([I(1,a.Inject(a.Injector)),I(2,a.IConfigService)],r.UniverRPCMainThreadPlugin),r.UniverRPCWorkerThreadPlugin=(E=class extends a.Plugin{constructor(t=k,e,n){super(),this._config=t,this._injector=e,this._configService=n;const{...s}=this._config;this._configService.setConfig(N,s)}onStarting(){[[r.DataSyncReplicaController],[m,{useFactory:()=>new w(K())}],[p,{useClass:r.WebWorkerRemoteInstanceService}]].forEach(t=>this._injector.add(t)),this._injector.get(r.DataSyncReplicaController)}},l(E,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),E),r.UniverRPCWorkerThreadPlugin=D([I(1,a.Inject(a.Injector)),I(2,a.IConfigService)],r.UniverRPCWorkerThreadPlugin),r.ChannelClient=W,r.ChannelServer=j,r.ChannelService=w,r.IRPCChannelService=m,r.IRemoteInstanceService=p,r.IRemoteSyncService=v,r.RemoteInstanceServiceName=R,r.RemoteSyncServiceName=C,r.fromModule=b,r.toModule=P,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/rpc",
3
- "version": "0.4.2",
3
+ "version": "0.5.0-alpha.0",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -32,8 +32,7 @@
32
32
  },
33
33
  "./lib/*": "./lib/*"
34
34
  },
35
- "main": "./lib/cjs/index.js",
36
- "module": "./lib/es/index.js",
35
+ "main": "./lib/es/index.js",
37
36
  "types": "./lib/types/index.d.ts",
38
37
  "publishConfig": {
39
38
  "access": "public"
@@ -48,16 +47,17 @@
48
47
  "rxjs": ">=7.0.0"
49
48
  },
50
49
  "dependencies": {
51
- "@univerjs/core": "0.4.2"
50
+ "@vitejs/plugin-react": "4.3.3",
51
+ "@univerjs/core": "0.5.0-alpha.0"
52
52
  },
53
53
  "devDependencies": {
54
54
  "rxjs": "^7.8.1",
55
55
  "typescript": "^5.6.3",
56
- "vite": "^5.4.8",
57
- "vitest": "^2.1.2",
58
- "@univerjs-infra/shared": "0.4.2"
56
+ "vite": "^5.4.10",
57
+ "vitest": "^2.1.4",
58
+ "@univerjs-infra/shared": "0.5.0-alpha.0"
59
59
  },
60
- "univerSpace": {
60
+ "space": {
61
61
  ".": {
62
62
  "import": "./lib/es/index.js",
63
63
  "require": "./lib/cjs/index.js",
@@ -72,6 +72,7 @@
72
72
  },
73
73
  "scripts": {
74
74
  "lint:types": "tsc --noEmit",
75
- "build": "tsc && vite build"
76
- }
75
+ "build": "tsx build.ts"
76
+ },
77
+ "module": "./lib/es/index.js"
77
78
  }