@univerjs/rpc 0.2.4-alpha.0 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var W=Object.defineProperty;var $=(i,n,e)=>n in i?W(i,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[n]=e;var l=(i,n,e)=>$(i,typeof n!="symbol"?n+"":n,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@univerjs/core"),_=require("rxjs/operators"),u=require("rxjs");var x=Object.defineProperty,N=Object.getOwnPropertyDescriptor,M=(i,n,e,t)=>{for(var s=t>1?void 0:t?N(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&x(n,e,s),s},C=(i,n)=>(e,t)=>n(e,t,i);const R="rpc.remote-sync.service",v=a.createIdentifier(R);exports.RemoteSyncPrimaryService=class{constructor(n){this._commandService=n}async syncMutation(n){return this._commandService.syncExecuteCommand(n.mutationInfo.id,n.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}};exports.RemoteSyncPrimaryService=M([C(0,a.ICommandService)],exports.RemoteSyncPrimaryService);const b="univer.remote-instance-service",y=a.createIdentifier(b);exports.WebWorkerRemoteInstanceService=class{constructor(n,e,t){this._univerInstanceService=n,this._commandService=e,this._logService=t}whenReady(){return Promise.resolve(!0)}async syncMutation(n){return this._applyMutation(n.mutationInfo)}async createInstance(n){const{type:e,snapshot:t}=n;try{switch(e){case a.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(a.UniverInstanceType.UNIVER_SHEET,t),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(n){return this._univerInstanceService.disposeUnit(n.unitID)}_applyMutation(n){const{id:e,params:t}=n;return this._commandService.syncExecuteCommand(e,t,{onlyLocal:!0,fromSync:!0})}};exports.WebWorkerRemoteInstanceService=M([C(0,a.IUniverInstanceService),C(1,a.ICommandService),C(2,a.ILogService)],exports.WebWorkerRemoteInstanceService);function w(i){const n=i;return new class{call(e,t){const s=n[e];if(typeof s=="function"){let r=s.apply(n,[t]);return r instanceof Promise||(r=Promise.resolve(r)),r}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,t){const s=n[e];if(typeof s=="function"){const r=s.apply(n,t);return u.isObservable(r)?r:u.of(r)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function U(i){return new Proxy({},{get(n,e){if(e!=="dispose")return function(...t){return L(e)?i.subscribe(e,t[0]):i.call(e,t[0])}}})}function L(i){return i.endsWith("$")}class q extends a.RxDisposable{constructor(e){super();l(this,"_initialized",new u.BehaviorSubject(!1));l(this,"_lastRequestCounter",0);l(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.onMessage.pipe(_.takeUntil(this.dispose$)).subscribe(t=>this._onMessage(t))}dispose(){this._pendingRequests.clear()}getChannel(e){const t=this;return{call(s,r){return t._disposed?Promise.reject():t._remoteCall(e,s,r)},subscribe(s,r){if(t._disposed)throw new Error("[ChannelClient]: client is disposed!");return t._remoteSubscribe(e,s,r)}}}_whenReady(){return u.firstValueFrom(this._initialized.pipe(_.filter(e=>e),_.take(1)))}async _remoteCall(e,t,s){await this._whenReady();const r=++this._lastRequestCounter,h={seq:r,type:100,channelName:e,method:t,args:s},o=this;return new Promise((f,d)=>{const j={handle(g){switch(g.type){case 201:o._pendingRequests.delete(r),f(g.data);break;case 202:o._pendingRequests.delete(r),d(g.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(r,j),this._sendRequest(h)})}_remoteSubscribe(e,t,s){return new u.Observable(r=>{let c=-1;return this._whenReady().then(()=>{c=++this._lastRequestCounter;const o={seq:c,type:101,channelName:e,method:t,args:s},f={handle(d){switch(d.type){case 300:r.next(d.data);break;case 301:r.error(d.data);break;case 302:r.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(c,f),this._sendRequest(o)}),()=>{if(c===-1)return;const h={type:102,seq:c,channelName:e,method:t};this._sendRequest(h)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var t;switch(e.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(t=this._pendingRequests.get(e.seq))==null||t.handle(e);break}}}class D extends a.RxDisposable{constructor(e){super();l(this,"_channels",new Map);l(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(_.takeUntil(this.dispose$)).subscribe(t=>this._onRequest(t)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,t){this._channels.set(e,t)}_onRequest(e){switch(e.type){case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_onMethodCall(e){const{channelName:t,method:s,args:r}=e,c=this._channels.get(t);let h;try{if(!c)throw new Error(`[ChannelServer]: Channel ${t} not found!`);h=c.call(s,r)}catch(o){h=Promise.reject(o)}h.then(o=>{this._sendResponse({seq:e.seq,type:201,data:o})}).catch(o=>{o instanceof Error?this._sendResponse({seq:e.seq,type:202,data:o.message}):this._sendResponse({seq:e.seq,type:202,data:String(o)})})}_onSubscribe(e){const{channelName:t,seq:s}=e,r=this._channels.get(t);try{if(!r)throw new Error(`[ChannelServer]: Channel ${t} not found!`);const h=r.subscribe(e.method,e.args).subscribe({next:o=>{this._sendResponse({seq:s,type:300,data:o})},error:o=>{this._sendResponse({seq:s,type:301,data:o.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,h)}catch(c){c instanceof Error?this._sendResponse({seq:e.seq,type:301,data:c.message}):this._sendResponse({seq:e.seq,type:301,data:String(c)})}}_onUnsubscribe(e){const t=this._subscriptions.get(e.seq);t&&(t.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const m=a.createIdentifier("IRPCChannelService");class E{constructor(n){l(this,"_client");l(this,"_server");this._client=new q(n),this._server=new D(n)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(n){return this._client.getChannel(n)}registerChannel(n,e){this._server.registerChannel(n,e)}}var k=Object.defineProperty,H=Object.getOwnPropertyDescriptor,V=(i,n,e,t)=>{for(var s=t>1?void 0:t?H(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&k(n,e,s),s},p=(i,n)=>(e,t)=>n(e,t,i);exports.DataSyncPrimaryController=class extends a.RxDisposable{constructor(e,t,s,r,c){super();l(this,"_remoteInstanceService");l(this,"_syncingUnits",new Set);l(this,"_syncingMutations",new Set);this._injector=e,this._commandService=t,this._univerInstanceService=s,this._rpcChannelService=r,this._remoteSyncService=c,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),a.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(R,w(this._remoteSyncService)),this._injector.add([y,{useFactory:()=>U(this._rpcChannelService.requestChannel(b))}]),this._remoteInstanceService=this._injector.get(y)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET).pipe(_.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:a.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).pipe(_.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{const{type:s,params:r,id:c}=e,h=(r==null?void 0:r.unitId)||"";s===a.CommandType.MUTATION&&(!h||this._syncingUnits.has(h))&&!(t!=null&&t.fromSync)&&this._syncingMutations.has(c)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}};exports.DataSyncPrimaryController=V([a.OnLifecycle(a.LifecycleStages.Starting,exports.DataSyncPrimaryController),p(0,a.Inject(a.Injector)),p(1,a.ICommandService),p(2,a.IUniverInstanceService),p(3,m),p(4,v)],exports.DataSyncPrimaryController);var A=Object.defineProperty,F=Object.getOwnPropertyDescriptor,z=(i,n,e,t)=>{for(var s=t>1?void 0:t?F(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&A(n,e,s),s},S=(i,n)=>(e,t)=>n(e,t,i);exports.DataSyncReplicaController=class extends a.Disposable{constructor(e,t,s,r){super();l(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=t,this._commandService=s,this._rpcChannelService=r,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(b,w(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>U(this._rpcChannelService.requestChannel(R))}]),this._remoteSyncService=this._injector.get(v)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{e.type===a.CommandType.MUTATION&&!(t!=null&&t.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}};exports.DataSyncReplicaController=z([a.OnLifecycle(a.LifecycleStages.Starting,exports.DataSyncReplicaController),S(0,a.Inject(a.Injector)),S(1,y),S(2,a.ICommandService),S(3,m)],exports.DataSyncReplicaController);function G(){return{send(i){postMessage(i)},onMessage:new u.Observable(i=>{const n=e=>{i.next(e.data)};return addEventListener("message",n),()=>removeEventListener("message",n)}).pipe(u.shareReplay(1))}}function B(i){return{send(n){i.postMessage(n)},onMessage:new u.Observable(n=>{const e=t=>{n.next(t.data)};return i.addEventListener("message",e),()=>i.removeEventListener("message",e)}).pipe(u.shareReplay(1))}}var J=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,O=(i,n,e,t)=>{for(var s=t>1?void 0:t?Q(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&J(n,e,s),s},T=(i,n)=>(e,t)=>n(e,t,i),I;exports.UniverRPCMainThreadPlugin=(I=class extends a.Plugin{constructor(n,e){super(),this._config=n,this._injector=e}async onStarting(n){const{workerURL:e}=this._config,t=e instanceof Worker?e:new Worker(e),s=B(t);[[m,{useFactory:()=>new E(s)}],[exports.DataSyncPrimaryController],[v,{useClass:exports.RemoteSyncPrimaryService}]].forEach(c=>n.add(c)),n.get(exports.DataSyncPrimaryController)}},l(I,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),I);exports.UniverRPCMainThreadPlugin=O([T(1,a.Inject(a.Injector))],exports.UniverRPCMainThreadPlugin);var P;exports.UniverRPCWorkerThreadPlugin=(P=class extends a.Plugin{constructor(n,e){super(),this._config=n,this._injector=e}onStarting(n){[[exports.DataSyncReplicaController],[m,{useFactory:()=>new E(G())}],[y,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(e=>n.add(e)),n.get(exports.DataSyncReplicaController)}},l(P,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),P);exports.UniverRPCWorkerThreadPlugin=O([T(1,a.Inject(a.Injector))],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=q;exports.ChannelServer=D;exports.ChannelService=E;exports.IRPCChannelService=m;exports.IRemoteInstanceService=y;exports.IRemoteSyncService=v;exports.RemoteInstanceServiceName=b;exports.RemoteSyncServiceName=R;exports.fromModule=w;exports.toModule=U;
1
+ "use strict";var $=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;
package/lib/es/index.js CHANGED
@@ -1,15 +1,16 @@
1
1
  var X = Object.defineProperty;
2
2
  var Y = (n, t, e) => t in n ? X(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
- var o = (n, t, e) => Y(n, typeof t != "symbol" ? t + "" : t, e);
4
- import { createIdentifier as q, UniverInstanceType as u, ICommandService as b, IUniverInstanceService as N, ILogService as Z, RxDisposable as O, OnLifecycle as W, LifecycleStages as L, Inject as g, Injector as C, toDisposable as K, CommandType as H, Disposable as ee, Plugin as V } from "@univerjs/core";
3
+ var a = (n, t, e) => Y(n, typeof t != "symbol" ? t + "" : t, e);
4
+ import { UniverInstanceType as u, ICommandService as b, IUniverInstanceService as N, ILogService as Z, RxDisposable as q, OnLifecycle as W, LifecycleStages as L, toDisposable as K, CommandType as H, Disposable as ee, Plugin as V } from "@univerjs/core";
5
+ import { createIdentifier as O, Inject as g, Injector as C } from "@wendellhu/redi";
5
6
  import { takeUntil as y, filter as te, take as se } from "rxjs/operators";
6
7
  import { isObservable as ne, of as re, BehaviorSubject as ie, firstValueFrom as ce, Observable as $, shareReplay as A } from "rxjs";
7
- var ae = Object.defineProperty, oe = Object.getOwnPropertyDescriptor, F = (n, t, e, s) => {
8
- for (var r = s > 1 ? void 0 : s ? oe(t, e) : t, i = n.length - 1, c; i >= 0; i--)
8
+ var oe = Object.defineProperty, ae = Object.getOwnPropertyDescriptor, F = (n, t, e, s) => {
9
+ for (var r = s > 1 ? void 0 : s ? ae(t, e) : t, i = n.length - 1, c; i >= 0; i--)
9
10
  (c = n[i]) && (r = (s ? c(t, e, r) : c(r)) || r);
10
- return s && r && ae(t, e, r), r;
11
+ return s && r && oe(t, e, r), r;
11
12
  }, m = (n, t) => (e, s) => t(e, s, n);
12
- const j = "rpc.remote-sync.service", f = q(j);
13
+ const j = "rpc.remote-sync.service", f = O(j);
13
14
  let U = class {
14
15
  constructor(n) {
15
16
  this._commandService = n;
@@ -24,7 +25,7 @@ let U = class {
24
25
  U = F([
25
26
  m(0, b)
26
27
  ], U);
27
- const D = "univer.remote-instance-service", S = q(D);
28
+ const D = "univer.remote-instance-service", S = O(D);
28
29
  let M = class {
29
30
  constructor(n, t, e) {
30
31
  this._univerInstanceService = n, this._commandService = t, this._logService = e;
@@ -100,12 +101,12 @@ function G(n) {
100
101
  function he(n) {
101
102
  return n.endsWith("$");
102
103
  }
103
- class _e extends O {
104
+ class _e extends q {
104
105
  constructor(e) {
105
106
  super();
106
- o(this, "_initialized", new ie(!1));
107
- o(this, "_lastRequestCounter", 0);
108
- o(this, "_pendingRequests", /* @__PURE__ */ new Map());
107
+ a(this, "_initialized", new ie(!1));
108
+ a(this, "_lastRequestCounter", 0);
109
+ a(this, "_pendingRequests", /* @__PURE__ */ new Map());
109
110
  this._protocol = e, this._protocol.onMessage.pipe(y(this.dispose$)).subscribe((s) => this._onMessage(s));
110
111
  }
111
112
  dispose() {
@@ -134,16 +135,16 @@ class _e extends O {
134
135
  }
135
136
  async _remoteCall(e, s, r) {
136
137
  await this._whenReady();
137
- const i = ++this._lastRequestCounter, h = { seq: i, type: 100, channelName: e, method: s, args: r }, a = this;
138
+ const i = ++this._lastRequestCounter, h = { seq: i, type: 100, channelName: e, method: s, args: r }, o = this;
138
139
  return new Promise((I, _) => {
139
140
  const Q = {
140
141
  handle(w) {
141
142
  switch (w.type) {
142
143
  case 201:
143
- a._pendingRequests.delete(i), I(w.data);
144
+ o._pendingRequests.delete(i), I(w.data);
144
145
  break;
145
146
  case 202:
146
- a._pendingRequests.delete(i), _(w.data);
147
+ o._pendingRequests.delete(i), _(w.data);
147
148
  break;
148
149
  default:
149
150
  throw new Error("[ChannelClient]: unknown response type!");
@@ -158,7 +159,7 @@ class _e extends O {
158
159
  let c = -1;
159
160
  return this._whenReady().then(() => {
160
161
  c = ++this._lastRequestCounter;
161
- const a = { seq: c, type: 101, channelName: e, method: s, args: r }, I = {
162
+ const o = { seq: c, type: 101, channelName: e, method: s, args: r }, I = {
162
163
  handle(_) {
163
164
  switch (_.type) {
164
165
  case 300:
@@ -175,7 +176,7 @@ class _e extends O {
175
176
  }
176
177
  }
177
178
  };
178
- this._pendingRequests.set(c, I), this._sendRequest(a);
179
+ this._pendingRequests.set(c, I), this._sendRequest(o);
179
180
  }), () => {
180
181
  if (c === -1)
181
182
  return;
@@ -208,11 +209,11 @@ class _e extends O {
208
209
  }
209
210
  }
210
211
  }
211
- class le extends O {
212
+ class le extends q {
212
213
  constructor(e) {
213
214
  super();
214
- o(this, "_channels", /* @__PURE__ */ new Map());
215
- o(this, "_subscriptions", /* @__PURE__ */ new Map());
215
+ a(this, "_channels", /* @__PURE__ */ new Map());
216
+ a(this, "_subscriptions", /* @__PURE__ */ new Map());
216
217
  this._protocol = e, this._protocol.onMessage.pipe(y(this.dispose$)).subscribe((s) => this._onRequest(s)), this._sendResponse({
217
218
  seq: -1,
218
219
  type: 0
@@ -245,13 +246,13 @@ class le extends O {
245
246
  if (!c)
246
247
  throw new Error(`[ChannelServer]: Channel ${s} not found!`);
247
248
  h = c.call(r, i);
248
- } catch (a) {
249
- h = Promise.reject(a);
249
+ } catch (o) {
250
+ h = Promise.reject(o);
250
251
  }
251
- h.then((a) => {
252
- this._sendResponse({ seq: e.seq, type: 201, data: a });
253
- }).catch((a) => {
254
- a instanceof Error ? this._sendResponse({ seq: e.seq, type: 202, data: a.message }) : this._sendResponse({ seq: e.seq, type: 202, data: String(a) });
252
+ h.then((o) => {
253
+ this._sendResponse({ seq: e.seq, type: 201, data: o });
254
+ }).catch((o) => {
255
+ o instanceof Error ? this._sendResponse({ seq: e.seq, type: 202, data: o.message }) : this._sendResponse({ seq: e.seq, type: 202, data: String(o) });
255
256
  });
256
257
  }
257
258
  _onSubscribe(e) {
@@ -260,11 +261,11 @@ class le extends O {
260
261
  if (!i)
261
262
  throw new Error(`[ChannelServer]: Channel ${s} not found!`);
262
263
  const h = i.subscribe(e.method, e.args).subscribe({
263
- next: (a) => {
264
- this._sendResponse({ seq: r, type: 300, data: a });
264
+ next: (o) => {
265
+ this._sendResponse({ seq: r, type: 300, data: o });
265
266
  },
266
- error: (a) => {
267
- this._sendResponse({ seq: r, type: 301, data: a.message }), this._sendResponse({
267
+ error: (o) => {
268
+ this._sendResponse({ seq: r, type: 301, data: o.message }), this._sendResponse({
268
269
  seq: r,
269
270
  type: 302
270
271
  /* SUBSCRIBE_COMPLETE */
@@ -291,11 +292,11 @@ class le extends O {
291
292
  this._protocol.send(e);
292
293
  }
293
294
  }
294
- const R = q("IRPCChannelService");
295
+ const R = O("IRPCChannelService");
295
296
  class B {
296
297
  constructor(t) {
297
- o(this, "_client");
298
- o(this, "_server");
298
+ a(this, "_client");
299
+ a(this, "_server");
299
300
  this._client = new _e(t), this._server = new le(t);
300
301
  }
301
302
  dispose() {
@@ -313,12 +314,12 @@ var ue = Object.defineProperty, pe = Object.getOwnPropertyDescriptor, de = (n, t
313
314
  (c = n[i]) && (r = (s ? c(t, e, r) : c(r)) || r);
314
315
  return s && r && ue(t, e, r), r;
315
316
  }, l = (n, t) => (e, s) => t(e, s, n);
316
- let p = class extends O {
317
+ let p = class extends q {
317
318
  constructor(t, e, s, r, i) {
318
319
  super();
319
- o(this, "_remoteInstanceService");
320
- o(this, "_syncingUnits", /* @__PURE__ */ new Set());
321
- o(this, "_syncingMutations", /* @__PURE__ */ new Set());
320
+ a(this, "_remoteInstanceService");
321
+ a(this, "_syncingUnits", /* @__PURE__ */ new Set());
322
+ a(this, "_syncingMutations", /* @__PURE__ */ new Set());
322
323
  this._injector = t, this._commandService = e, this._univerInstanceService = s, this._rpcChannelService = r, this._remoteSyncService = i, this._initRPCChannels(), this._init();
323
324
  }
324
325
  registerSyncingMutations(t) {
@@ -373,7 +374,7 @@ var ve = Object.defineProperty, me = Object.getOwnPropertyDescriptor, ye = (n, t
373
374
  let d = class extends ee {
374
375
  constructor(t, e, s, r) {
375
376
  super();
376
- o(this, "_remoteSyncService");
377
+ a(this, "_remoteSyncService");
377
378
  this._injector = t, this._remoteInstanceService = e, this._commandService = s, this._rpcChannelService = r, this._initRPCChannels(), this._init();
378
379
  }
379
380
  _initRPCChannels() {
@@ -448,7 +449,7 @@ let x = (P = class extends V {
448
449
  [f, { useClass: U }]
449
450
  ].forEach((i) => n.add(i)), n.get(p);
450
451
  }
451
- }, o(P, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN"), P);
452
+ }, a(P, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN"), P);
452
453
  x = k([
453
454
  J(1, g(C))
454
455
  ], x);
@@ -469,7 +470,7 @@ let T = (E = class extends V {
469
470
  [S, { useClass: M }]
470
471
  ].forEach((t) => n.add(t)), n.get(d);
471
472
  }
472
- }, o(E, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN"), E);
473
+ }, a(E, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN"), E);
473
474
  T = k([
474
475
  J(1, g(C))
475
476
  ], T);
@@ -1,4 +1,5 @@
1
- import { IDisposable, IMutation, ICommandService, Injector, IUniverInstanceService, RxDisposable } from '@univerjs/core';
1
+ import { IMutation, ICommandService, IUniverInstanceService, RxDisposable } from '@univerjs/core';
2
+ import { IDisposable, Injector } from '@wendellhu/redi';
2
3
  import { IRemoteSyncService } from '../../services/remote-instance/remote-instance.service';
3
4
  import { IRPCChannelService } from '../../services/rpc/channel.service';
4
5
 
@@ -1,4 +1,5 @@
1
- import { Disposable, ICommandService, Injector } from '@univerjs/core';
1
+ import { Disposable, ICommandService } from '@univerjs/core';
2
+ import { Injector } from '@wendellhu/redi';
2
3
  import { IRemoteInstanceService } from '../../services/remote-instance/remote-instance.service';
3
4
  import { IRPCChannelService } from '../../services/rpc/channel.service';
4
5
 
@@ -1,4 +1,5 @@
1
- import { Injector, Plugin } from '@univerjs/core';
1
+ import { Plugin } from '@univerjs/core';
2
+ import { Injector } from '@wendellhu/redi';
2
3
 
3
4
  export interface IUniverRPCMainThreadConfig {
4
5
  workerURL: string | URL | Worker;
@@ -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('@univerjs/core').IdentifierDecorator<IRemoteSyncService>;
13
+ export declare const IRemoteSyncService: import('@wendellhu/redi').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('@univerjs/core').IdentifierDecorator<IRemoteInstanceService>;
33
+ export declare const IRemoteInstanceService: import('@wendellhu/redi').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 '@univerjs/core';
1
+ import { IDisposable } from '@wendellhu/redi';
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('@univerjs/core').IdentifierDecorator<IRPCChannelService>;
8
+ export declare const IRPCChannelService: import('@wendellhu/redi').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(r,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs/operators"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs/operators","rxjs"],a):(r=typeof globalThis<"u"?globalThis:r||self,a(r.UniverRpc={},r.UniverCore,r.rxjs.operators,r.rxjs))})(this,function(r,a,_,d){"use strict";var X=Object.defineProperty;var Y=(r,a,_)=>a in r?X(r,a,{enumerable:!0,configurable:!0,writable:!0,value:_}):r[a]=_;var h=(r,a,_)=>Y(r,typeof a!="symbol"?a+"":a,_);var w,U;var W=Object.defineProperty,$=Object.getOwnPropertyDescriptor,q=(c,t,e,n)=>{for(var s=n>1?void 0:n?$(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&W(t,e,s),s},f=(c,t)=>(e,n)=>t(e,n,c);const C="rpc.remote-sync.service",v=a.createIdentifier(C);r.RemoteSyncPrimaryService=class{constructor(t){this._commandService=t}async syncMutation(t){return this._commandService.syncExecuteCommand(t.mutationInfo.id,t.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},r.RemoteSyncPrimaryService=q([f(0,a.ICommandService)],r.RemoteSyncPrimaryService);const R="univer.remote-instance-service",p=a.createIdentifier(R);r.WebWorkerRemoteInstanceService=class{constructor(t,e,n){this._univerInstanceService=t,this._commandService=e,this._logService=n}whenReady(){return Promise.resolve(!0)}async syncMutation(t){return this._applyMutation(t.mutationInfo)}async createInstance(t){const{type:e,snapshot:n}=t;try{switch(e){case a.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(a.UniverInstanceType.UNIVER_SHEET,n),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(t){return this._univerInstanceService.disposeUnit(t.unitID)}_applyMutation(t){const{id:e,params:n}=t;return this._commandService.syncExecuteCommand(e,n,{onlyLocal:!0,fromSync:!0})}},r.WebWorkerRemoteInstanceService=q([f(0,a.IUniverInstanceService),f(1,a.ICommandService),f(2,a.ILogService)],r.WebWorkerRemoteInstanceService);function g(c){const t=c;return new class{call(e,n){const s=t[e];if(typeof s=="function"){let i=s.apply(t,[n]);return i instanceof Promise||(i=Promise.resolve(i)),i}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,n){const s=t[e];if(typeof s=="function"){const i=s.apply(t,n);return d.isObservable(i)?i:d.of(i)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function I(c){return new Proxy({},{get(t,e){if(e!=="dispose")return function(...n){return N(e)?c.subscribe(e,n[0]):c.call(e,n[0])}}})}function N(c){return c.endsWith("$")}class D extends a.RxDisposable{constructor(e){super();h(this,"_initialized",new d.BehaviorSubject(!1));h(this,"_lastRequestCounter",0);h(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.onMessage.pipe(_.takeUntil(this.dispose$)).subscribe(n=>this._onMessage(n))}dispose(){this._pendingRequests.clear()}getChannel(e){const n=this;return{call(s,i){return n._disposed?Promise.reject():n._remoteCall(e,s,i)},subscribe(s,i){if(n._disposed)throw new Error("[ChannelClient]: client is disposed!");return n._remoteSubscribe(e,s,i)}}}_whenReady(){return d.firstValueFrom(this._initialized.pipe(_.filter(e=>e),_.take(1)))}async _remoteCall(e,n,s){await this._whenReady();const i=++this._lastRequestCounter,u={seq:i,type:100,channelName:e,method:n,args:s},l=this;return new Promise((E,S)=>{const Q={handle(M){switch(M.type){case 201:l._pendingRequests.delete(i),E(M.data);break;case 202:l._pendingRequests.delete(i),S(M.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(i,Q),this._sendRequest(u)})}_remoteSubscribe(e,n,s){return new d.Observable(i=>{let o=-1;return this._whenReady().then(()=>{o=++this._lastRequestCounter;const l={seq:o,type:101,channelName:e,method:n,args:s},E={handle(S){switch(S.type){case 300:i.next(S.data);break;case 301:i.error(S.data);break;case 302:i.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(o,E),this._sendRequest(l)}),()=>{if(o===-1)return;const u={type:102,seq:o,channelName:e,method:n};this._sendRequest(u)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var n;switch(e.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(n=this._pendingRequests.get(e.seq))==null||n.handle(e);break}}}class O extends a.RxDisposable{constructor(e){super();h(this,"_channels",new Map);h(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(_.takeUntil(this.dispose$)).subscribe(n=>this._onRequest(n)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,n){this._channels.set(e,n)}_onRequest(e){switch(e.type){case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_onMethodCall(e){const{channelName:n,method:s,args:i}=e,o=this._channels.get(n);let u;try{if(!o)throw new Error(`[ChannelServer]: Channel ${n} not found!`);u=o.call(s,i)}catch(l){u=Promise.reject(l)}u.then(l=>{this._sendResponse({seq:e.seq,type:201,data:l})}).catch(l=>{l instanceof Error?this._sendResponse({seq:e.seq,type:202,data:l.message}):this._sendResponse({seq:e.seq,type:202,data:String(l)})})}_onSubscribe(e){const{channelName:n,seq:s}=e,i=this._channels.get(n);try{if(!i)throw new Error(`[ChannelServer]: Channel ${n} not found!`);const u=i.subscribe(e.method,e.args).subscribe({next:l=>{this._sendResponse({seq:s,type:300,data:l})},error:l=>{this._sendResponse({seq:s,type:301,data:l.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,u)}catch(o){o instanceof Error?this._sendResponse({seq:e.seq,type:301,data:o.message}):this._sendResponse({seq:e.seq,type:301,data:String(o)})}}_onUnsubscribe(e){const n=this._subscriptions.get(e.seq);n&&(n.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const y=a.createIdentifier("IRPCChannelService");class P{constructor(t){h(this,"_client");h(this,"_server");this._client=new D(t),this._server=new O(t)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(t){return this._client.getChannel(t)}registerChannel(t,e){this._server.registerChannel(t,e)}}var L=Object.defineProperty,k=Object.getOwnPropertyDescriptor,H=(c,t,e,n)=>{for(var s=n>1?void 0:n?k(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&L(t,e,s),s},m=(c,t)=>(e,n)=>t(e,n,c);r.DataSyncPrimaryController=class extends a.RxDisposable{constructor(e,n,s,i,o){super();h(this,"_remoteInstanceService");h(this,"_syncingUnits",new Set);h(this,"_syncingMutations",new Set);this._injector=e,this._commandService=n,this._univerInstanceService=s,this._rpcChannelService=i,this._remoteSyncService=o,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),a.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(C,g(this._remoteSyncService)),this._injector.add([p,{useFactory:()=>I(this._rpcChannelService.requestChannel(R))}]),this._remoteInstanceService=this._injector.get(p)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET).pipe(_.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:a.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).pipe(_.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{const{type:s,params:i,id:o}=e,u=(i==null?void 0:i.unitId)||"";s===a.CommandType.MUTATION&&(!u||this._syncingUnits.has(u))&&!(n!=null&&n.fromSync)&&this._syncingMutations.has(o)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}},r.DataSyncPrimaryController=H([a.OnLifecycle(a.LifecycleStages.Starting,r.DataSyncPrimaryController),m(0,a.Inject(a.Injector)),m(1,a.ICommandService),m(2,a.IUniverInstanceService),m(3,y),m(4,v)],r.DataSyncPrimaryController);var V=Object.defineProperty,A=Object.getOwnPropertyDescriptor,F=(c,t,e,n)=>{for(var s=n>1?void 0:n?A(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&V(t,e,s),s},b=(c,t)=>(e,n)=>t(e,n,c);r.DataSyncReplicaController=class extends a.Disposable{constructor(e,n,s,i){super();h(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=n,this._commandService=s,this._rpcChannelService=i,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(R,g(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>I(this._rpcChannelService.requestChannel(C))}]),this._remoteSyncService=this._injector.get(v)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{e.type===a.CommandType.MUTATION&&!(n!=null&&n.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}},r.DataSyncReplicaController=F([a.OnLifecycle(a.LifecycleStages.Starting,r.DataSyncReplicaController),b(0,a.Inject(a.Injector)),b(1,p),b(2,a.ICommandService),b(3,y)],r.DataSyncReplicaController);function z(){return{send(c){postMessage(c)},onMessage:new d.Observable(c=>{const t=e=>{c.next(e.data)};return addEventListener("message",t),()=>removeEventListener("message",t)}).pipe(d.shareReplay(1))}}function G(c){return{send(t){c.postMessage(t)},onMessage:new d.Observable(t=>{const e=n=>{t.next(n.data)};return c.addEventListener("message",e),()=>c.removeEventListener("message",e)}).pipe(d.shareReplay(1))}}var B=Object.defineProperty,J=Object.getOwnPropertyDescriptor,T=(c,t,e,n)=>{for(var s=n>1?void 0:n?J(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&B(t,e,s),s},j=(c,t)=>(e,n)=>t(e,n,c);r.UniverRPCMainThreadPlugin=(w=class extends a.Plugin{constructor(t,e){super(),this._config=t,this._injector=e}async onStarting(t){const{workerURL:e}=this._config,n=e instanceof Worker?e:new Worker(e),s=G(n);[[y,{useFactory:()=>new P(s)}],[r.DataSyncPrimaryController],[v,{useClass:r.RemoteSyncPrimaryService}]].forEach(o=>t.add(o)),t.get(r.DataSyncPrimaryController)}},h(w,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),w),r.UniverRPCMainThreadPlugin=T([j(1,a.Inject(a.Injector))],r.UniverRPCMainThreadPlugin),r.UniverRPCWorkerThreadPlugin=(U=class extends a.Plugin{constructor(t,e){super(),this._config=t,this._injector=e}onStarting(t){[[r.DataSyncReplicaController],[y,{useFactory:()=>new P(z())}],[p,{useClass:r.WebWorkerRemoteInstanceService}]].forEach(e=>t.add(e)),t.get(r.DataSyncReplicaController)}},h(U,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),U),r.UniverRPCWorkerThreadPlugin=T([j(1,a.Inject(a.Injector))],r.UniverRPCWorkerThreadPlugin),r.ChannelClient=D,r.ChannelServer=O,r.ChannelService=P,r.IRPCChannelService=y,r.IRemoteInstanceService=p,r.IRemoteSyncService=v,r.RemoteInstanceServiceName=R,r.RemoteSyncServiceName=C,r.fromModule=g,r.toModule=I,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})});
1
+ (function(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"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/rpc",
3
- "version": "0.2.4-alpha.0",
3
+ "version": "0.2.4",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -45,16 +45,18 @@
45
45
  "lib"
46
46
  ],
47
47
  "peerDependencies": {
48
+ "@wendellhu/redi": "0.16.0",
48
49
  "rxjs": ">=7.0.0",
49
- "@univerjs/core": "0.2.4-alpha.0"
50
+ "@univerjs/core": "0.2.4"
50
51
  },
51
52
  "devDependencies": {
53
+ "@wendellhu/redi": "0.16.0",
52
54
  "rxjs": "^7.8.1",
53
55
  "typescript": "^5.5.3",
54
56
  "vite": "^5.3.4",
55
57
  "vitest": "^2.0.3",
56
- "@univerjs/core": "0.2.4-alpha.0",
57
- "@univerjs/shared": "0.2.4-alpha.0"
58
+ "@univerjs/core": "0.2.4",
59
+ "@univerjs/shared": "0.2.4"
58
60
  },
59
61
  "univerSpace": {
60
62
  ".": {