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