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