@univerjs/rpc 0.12.4-experimental.20251211-e01e32a → 0.12.4-insiders.20251211-c28f914

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 $=Object.defineProperty;var x=(i,t,e)=>t in i?$(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var l=(i,t,e)=>x(i,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@univerjs/core"),u=require("rxjs/operators"),_=require("rxjs"),L="rpc.main-thread.config",W={},T="rpc.worker-thread.config",k={};var H=Object.getOwnPropertyDescriptor,D=(i,t,e,n)=>{for(var s=n>1?void 0:n?H(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},g=(i,t)=>(e,n)=>t(e,n,i);const R="rpc.remote-sync.service",v=o.createIdentifier(R);exports.RemoteSyncPrimaryService=class{constructor(t){this._commandService=t}async syncMutation(t){return this._commandService.syncExecuteCommand(t.mutationInfo.id,t.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}};exports.RemoteSyncPrimaryService=D([g(0,o.ICommandService)],exports.RemoteSyncPrimaryService);const I="univer.remote-instance-service",m=o.createIdentifier(I);exports.WebWorkerRemoteInstanceService=class{constructor(t,e,n){this._univerInstanceService=t,this._commandService=e,this._logService=n}whenReady(){return Promise.resolve(!0)}async syncMutation(t){return this._applyMutation(t.mutationInfo)}async createInstance(t){this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${t.unitID}`);const{type:e,snapshot:n}=t;try{switch(e){case o.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(o.UniverInstanceType.UNIVER_SHEET,n),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(t){return this._logService.debug(`[WebWorkerRemoteInstanceService]: Disposing instance with id ${t.unitID}`),this._univerInstanceService.disposeUnit(t.unitID)}_applyMutation(t){const{id:e,params:n}=t;return this._commandService.syncExecuteCommand(e,n,{onlyLocal:!0,fromSync:!0})}};exports.WebWorkerRemoteInstanceService=D([g(0,o.IUniverInstanceService),g(1,o.ICommandService),g(2,o.ILogService)],exports.WebWorkerRemoteInstanceService);function U(i){const t=i;return new class{call(e,n){const s=t[e];if(typeof s=="function"){let r=n?s.apply(t,n):s.call(t);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=n?s.apply(t,n):s.call(t);return _.isObservable(r)?r:_.of(r)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function E(i){return new Proxy({},{get(t,e){if(e!=="dispose")return function(...n){return A(e)?i.subscribe(e,n):i.call(e,n)}}})}function A(i){return i.endsWith("$")}class q extends o.RxDisposable{constructor(e){super();l(this,"_initialized",new _.BehaviorSubject(!1));l(this,"_lastRequestCounter",0);l(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.send({type:50}),this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onMessage(n))}dispose(){this._pendingRequests.clear()}getChannel(e){const n=this;return{call(s,r){return n._disposed?Promise.reject():n._remoteCall(e,s,r)},subscribe(s,r){if(n._disposed)throw new Error("[ChannelClient]: client is disposed!");return n._remoteSubscribe(e,s,r)}}}_whenReady(){return _.firstValueFrom(this._initialized.pipe(u.filter(e=>e),u.take(1)))}async _remoteCall(e,n,s){await this._whenReady();const r=++this._lastRequestCounter,h={seq:r,type:100,channelName:e,method:n,args:s},a=this;return new Promise((f,d)=>{const N={handle(b){switch(b.type){case 201:a._pendingRequests.delete(r),f(b.data);break;case 202:a._pendingRequests.delete(r),d(b.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(r,N),this._sendRequest(h)})}_remoteSubscribe(e,n,s){return new _.Observable(r=>{let c=-1;return this._whenReady().then(()=>{c=++this._lastRequestCounter;const a={seq:c,type:101,channelName:e,method:n,args:s},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(a)}),()=>{if(c===-1)return;const h={type:102,seq:c,channelName:e,method:n};this._sendRequest(h)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var r;const{type:n,seq:s}=e;switch(n){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:{const{_pendingRequests:c}=this;(r=c.get(s))==null||r.handle(e),n!==300&&c.delete(s);break}}}}class O extends o.RxDisposable{constructor(e){super();l(this,"_channels",new Map);l(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onRequest(n)),this._sendInitialize()}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,n){this._channels.set(e,n)}_onRequest(e){switch(e.type){case 50:this._sendInitialize();break;case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_sendInitialize(){this._sendResponse({seq:-1,type:0})}_onMethodCall(e){const{channelName:n,method:s,args:r}=e,c=this._channels.get(n);let h;try{if(!c)throw new Error(`[ChannelServer]: Channel ${n} not found!`);h=r?c.call(s,r):c.call(s)}catch(a){h=Promise.reject(a)}h.then(a=>{this._sendResponse({seq:e.seq,type:201,data:a})}).catch(a=>{a instanceof Error?this._sendResponse({seq:e.seq,type:202,data:a.message}):this._sendResponse({seq:e.seq,type:202,data:String(a)})})}_onSubscribe(e){const{channelName:n,seq:s}=e,r=this._channels.get(n);try{if(!r)throw new Error(`[ChannelServer]: Channel ${n} not found!`);const h=r.subscribe(e.method,e.args).subscribe({next:a=>{this._sendResponse({seq:s,type:300,data:a})},error:a=>{this._sendResponse({seq:s,type:301,data:a.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,h)}catch(c){c instanceof Error?this._sendResponse({seq:e.seq,type:301,data:c.message}):this._sendResponse({seq:e.seq,type:301,data:String(c)})}}_onUnsubscribe(e){const n=this._subscriptions.get(e.seq);n&&(n.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const S=o.createIdentifier("IRPCChannelService");class M{constructor(t){l(this,"_client");l(this,"_server");this._client=new q(t),this._server=new 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 F=Object.getOwnPropertyDescriptor,G=(i,t,e,n)=>{for(var s=n>1?void 0:n?F(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},p=(i,t)=>(e,n)=>t(e,n,i);exports.DataSyncPrimaryController=class extends o.RxDisposable{constructor(e,n,s,r,c){super();l(this,"_remoteInstanceService");l(this,"_syncingUnits",new Set);l(this,"_syncingMutations",new Set);this._injector=e,this._commandService=n,this._univerInstanceService=s,this._rpcChannelService=r,this._remoteSyncService=c,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),o.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(R,U(this._remoteSyncService)),this._injector.add([m,{useFactory:()=>E(this._rpcChannelService.requestChannel(I))}]),this._remoteInstanceService=this._injector.get(m)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(o.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:o.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(o.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{const{type:s,params:r,id:c}=e,h=(r==null?void 0:r.unitId)||"";s===o.CommandType.MUTATION&&(!h||this._syncingUnits.has(h))&&!(n!=null&&n.fromSync)&&this._syncingMutations.has(c)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}};exports.DataSyncPrimaryController=G([p(0,o.Inject(o.Injector)),p(1,o.ICommandService),p(2,o.IUniverInstanceService),p(3,S),p(4,v)],exports.DataSyncPrimaryController);var V=Object.getOwnPropertyDescriptor,z=(i,t,e,n)=>{for(var s=n>1?void 0:n?V(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},y=(i,t)=>(e,n)=>t(e,n,i);exports.DataSyncReplicaController=class extends o.Disposable{constructor(e,n,s,r){super();l(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=n,this._commandService=s,this._rpcChannelService=r,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(I,U(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>E(this._rpcChannelService.requestChannel(R))}]),this._remoteSyncService=this._injector.get(v)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{e.type===o.CommandType.MUTATION&&!(n!=null&&n.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}};exports.DataSyncReplicaController=z([y(0,o.Inject(o.Injector)),y(1,m),y(2,o.ICommandService),y(3,S)],exports.DataSyncReplicaController);function K(){return{send(i){postMessage(i)},onMessage:new _.Observable(i=>{const t=e=>{i.next(e.data)};return addEventListener("message",t),()=>removeEventListener("message",t)}).pipe(_.shareReplay(1))}}function Y(i){return{send(t){i.postMessage(t)},onMessage:new _.Observable(t=>{const e=n=>{t.next(n.data)};return i.addEventListener("message",e),()=>i.removeEventListener("message",e)}).pipe(_.shareReplay(1))}}var B=Object.getOwnPropertyDescriptor,j=(i,t,e,n)=>{for(var s=n>1?void 0:n?B(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},C=(i,t)=>(e,n)=>t(e,n,i),P;exports.UniverRPCMainThreadPlugin=(P=class extends o.Plugin{constructor(e=W,n,s){super();l(this,"_internalWorker",null);this._config=e,this._injector=n,this._configService=s;const{...r}=o.merge({},W,this._config);this._configService.setConfig(L,r)}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL:e}=this._config;if(!e)throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");const n=e instanceof Worker?e:new Worker(e);this._internalWorker=e instanceof Worker?null:n;const s=Y(n);[[S,{useFactory:()=>new M(s)}],[exports.DataSyncPrimaryController],[v,{useClass:exports.RemoteSyncPrimaryService}]].forEach(c=>this._injector.add(c)),this._injector.get(exports.DataSyncPrimaryController)}},l(P,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),P);exports.UniverRPCMainThreadPlugin=j([C(1,o.Inject(o.Injector)),C(2,o.IConfigService)],exports.UniverRPCMainThreadPlugin);var w;exports.UniverRPCWorkerThreadPlugin=(w=class extends o.Plugin{constructor(t=k,e,n){super(),this._config=t,this._injector=e,this._configService=n;const{...s}=o.merge({},k,this._config);this._configService.setConfig(T,s)}onStarting(){[[exports.DataSyncReplicaController],[S,{useFactory:()=>new M(K())}],[m,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(t=>this._injector.add(t)),this._injector.get(exports.DataSyncReplicaController)}},l(w,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),w);exports.UniverRPCWorkerThreadPlugin=j([C(1,o.Inject(o.Injector)),C(2,o.IConfigService)],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=q;exports.ChannelServer=O;exports.ChannelService=M;exports.IRPCChannelService=S;exports.IRemoteInstanceService=m;exports.IRemoteSyncService=v;exports.PLUGIN_CONFIG_KEY_WORKER_THREAD=T;exports.RemoteInstanceServiceName=I;exports.RemoteSyncServiceName=R;exports.fromModule=U;exports.toModule=E;
1
+ "use strict";var x=Object.defineProperty;var L=(i,t,e)=>t in i?x(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var l=(i,t,e)=>L(i,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@univerjs/core"),u=require("rxjs/operators"),_=require("rxjs"),k="rpc.main-thread.config",W={},D="rpc.worker-thread.config",T={};var H=Object.getOwnPropertyDescriptor,q=(i,t,e,n)=>{for(var s=n>1?void 0:n?H(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},g=(i,t)=>(e,n)=>t(e,n,i);const R="rpc.remote-sync.service",v=o.createIdentifier(R);exports.RemoteSyncPrimaryService=class{constructor(t){this._commandService=t}async syncMutation(t){return this._commandService.syncExecuteCommand(t.mutationInfo.id,t.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}};exports.RemoteSyncPrimaryService=q([g(0,o.ICommandService)],exports.RemoteSyncPrimaryService);const I="univer.remote-instance-service",m=o.createIdentifier(I);exports.WebWorkerRemoteInstanceService=class{constructor(t,e,n){this._univerInstanceService=t,this._commandService=e,this._logService=n}whenReady(){return Promise.resolve(!0)}async syncMutation(t){return this._applyMutation(t.mutationInfo)}async createInstance(t){this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${t.unitID}`);const{type:e,snapshot:n}=t;try{switch(e){case o.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(o.UniverInstanceType.UNIVER_SHEET,n),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(t){return this._logService.debug(`[WebWorkerRemoteInstanceService]: Disposing instance with id ${t.unitID}`),this._univerInstanceService.disposeUnit(t.unitID)}_applyMutation(t){const{id:e,params:n}=t;return this._commandService.syncExecuteCommand(e,n,{onlyLocal:!0,fromSync:!0})}};exports.WebWorkerRemoteInstanceService=q([g(0,o.IUniverInstanceService),g(1,o.ICommandService),g(2,o.ILogService)],exports.WebWorkerRemoteInstanceService);function E(i){const t=i;return new class{call(e,n){const s=t[e];if(typeof s=="function"){let r=n?s.apply(t,n):s.call(t);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=n?s.apply(t,n):s.call(t);return _.isObservable(r)?r:_.of(r)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function U(i){return new Proxy({},{get(t,e){if(e!=="dispose")return function(...n){return A(e)?i.subscribe(e,n):i.call(e,n)}}})}function A(i){return i.endsWith("$")}class O extends o.RxDisposable{constructor(e){super();l(this,"_initialized",new _.BehaviorSubject(!1));l(this,"_lastRequestCounter",0);l(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.send({type:50}),this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onMessage(n))}dispose(){this._pendingRequests.clear()}getChannel(e){const n=this;return{call(s,r){return n._disposed?Promise.reject():n._remoteCall(e,s,r)},subscribe(s,r){if(n._disposed)throw new Error("[ChannelClient]: client is disposed!");return n._remoteSubscribe(e,s,r)}}}_whenReady(){return _.firstValueFrom(this._initialized.pipe(u.filter(e=>e),u.take(1)))}async _remoteCall(e,n,s){await this._whenReady();const r=++this._lastRequestCounter,h={seq:r,type:100,channelName:e,method:n,args:s},a=this;return new Promise((f,d)=>{const $={handle(b){switch(b.type){case 201:a._pendingRequests.delete(r),f(b.data);break;case 202:a._pendingRequests.delete(r),d(b.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(r,$),this._sendRequest(h)})}_remoteSubscribe(e,n,s){return new _.Observable(r=>{let c=-1;return this._whenReady().then(()=>{c=++this._lastRequestCounter;const a={seq:c,type:101,channelName:e,method:n,args:s},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(a)}),()=>{if(c===-1)return;const h={type:102,seq:c,channelName:e,method:n};this._sendRequest(h)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var r;const{type:n,seq:s}=e;switch(n){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:{const{_pendingRequests:c}=this;(r=c.get(s))==null||r.handle(e),n!==300&&c.delete(s);break}}}}class j extends o.RxDisposable{constructor(e){super();l(this,"_channels",new Map);l(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onRequest(n)),this._sendInitialize()}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,n){this._channels.set(e,n)}_onRequest(e){switch(e.type){case 50:this._sendInitialize();break;case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_sendInitialize(){this._sendResponse({seq:-1,type:0})}_onMethodCall(e){const{channelName:n,method:s,args:r}=e,c=this._channels.get(n);let h;try{if(!c)throw new Error(`[ChannelServer]: Channel ${n} not found!`);h=r?c.call(s,r):c.call(s)}catch(a){h=Promise.reject(a)}h.then(a=>{this._sendResponse({seq:e.seq,type:201,data:a})}).catch(a=>{a instanceof Error?this._sendResponse({seq:e.seq,type:202,data:a.message}):this._sendResponse({seq:e.seq,type:202,data:String(a)})})}_onSubscribe(e){const{channelName:n,seq:s}=e,r=this._channels.get(n);try{if(!r)throw new Error(`[ChannelServer]: Channel ${n} not found!`);const h=r.subscribe(e.method,e.args).subscribe({next:a=>{this._sendResponse({seq:s,type:300,data:a})},error:a=>{this._sendResponse({seq:s,type:301,data:a.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,h)}catch(c){c instanceof Error?this._sendResponse({seq:e.seq,type:301,data:c.message}):this._sendResponse({seq:e.seq,type:301,data:String(c)})}}_onUnsubscribe(e){const n=this._subscriptions.get(e.seq);n&&(n.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const S=o.createIdentifier("IRPCChannelService");class M{constructor(t){l(this,"_client");l(this,"_server");this._client=new O(t),this._server=new j(t)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(t){return this._client.getChannel(t)}registerChannel(t,e){this._server.registerChannel(t,e)}}var G=Object.getOwnPropertyDescriptor,F=(i,t,e,n)=>{for(var s=n>1?void 0:n?G(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},p=(i,t)=>(e,n)=>t(e,n,i);exports.DataSyncPrimaryController=class extends o.RxDisposable{constructor(e,n,s,r,c){super();l(this,"_remoteInstanceService");l(this,"_syncingUnits",new Set);l(this,"_syncingMutations",new Set);this._injector=e,this._commandService=n,this._univerInstanceService=s,this._rpcChannelService=r,this._remoteSyncService=c,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),o.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(R,E(this._remoteSyncService)),this._injector.add([m,{useFactory:()=>U(this._rpcChannelService.requestChannel(I))}]),this._remoteInstanceService=this._injector.get(m)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(o.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:o.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(o.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{const{type:s,params:r,id:c}=e,h=(r==null?void 0:r.unitId)||"";s===o.CommandType.MUTATION&&(!h||this._syncingUnits.has(h))&&!(n!=null&&n.fromSync)&&this._syncingMutations.has(c)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}};exports.DataSyncPrimaryController=F([p(0,o.Inject(o.Injector)),p(1,o.ICommandService),p(2,o.IUniverInstanceService),p(3,S),p(4,v)],exports.DataSyncPrimaryController);var V=Object.getOwnPropertyDescriptor,z=(i,t,e,n)=>{for(var s=n>1?void 0:n?V(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},y=(i,t)=>(e,n)=>t(e,n,i);exports.DataSyncReplicaController=class extends o.Disposable{constructor(e,n,s,r){super();l(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=n,this._commandService=s,this._rpcChannelService=r,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(I,E(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,n)=>{e.type===o.CommandType.MUTATION&&!(n!=null&&n.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}};exports.DataSyncReplicaController=z([y(0,o.Inject(o.Injector)),y(1,m),y(2,o.ICommandService),y(3,S)],exports.DataSyncReplicaController);function K(){return{send(i){postMessage(i)},onMessage:new _.Observable(i=>{const t=e=>{i.next(e.data)};return addEventListener("message",t),()=>removeEventListener("message",t)}).pipe(_.shareReplay(1))}}function Y(i){return{send(t){i.postMessage(t)},onMessage:new _.Observable(t=>{const e=n=>{t.next(n.data)};return i.addEventListener("message",e),()=>i.removeEventListener("message",e)}).pipe(_.shareReplay(1))}}var B=Object.getOwnPropertyDescriptor,N=(i,t,e,n)=>{for(var s=n>1?void 0:n?B(t,e):t,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=c(s)||s);return s},C=(i,t)=>(e,n)=>t(e,n,i),P;exports.UniverRPCMainThreadPlugin=(P=class extends o.Plugin{constructor(e=W,n,s){super();l(this,"_internalWorker",null);this._config=e,this._injector=n,this._configService=s;const{...r}=o.merge({},W,this._config);this._configService.setConfig(k,r)}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL:e}=this._config;if(!e)throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");const n=e instanceof Worker?e:new Worker(e);this._internalWorker=e instanceof Worker?null:n;const s=Y(n);[[S,{useFactory:()=>new M(s)}],[exports.DataSyncPrimaryController],[v,{useClass:exports.RemoteSyncPrimaryService}]].forEach(c=>this._injector.add(c)),this._injector.get(exports.DataSyncPrimaryController)}},l(P,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),P);exports.UniverRPCMainThreadPlugin=N([C(1,o.Inject(o.Injector)),C(2,o.IConfigService)],exports.UniverRPCMainThreadPlugin);var w;exports.UniverRPCWorkerThreadPlugin=(w=class extends o.Plugin{constructor(t=T,e,n){super(),this._config=t,this._injector=e,this._configService=n;const{...s}=o.merge({},T,this._config);this._configService.setConfig(D,s)}onStarting(){[[exports.DataSyncReplicaController],[S,{useFactory:()=>new M(K())}],[m,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(t=>this._injector.add(t)),this._injector.get(exports.DataSyncReplicaController)}},l(w,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),w);exports.UniverRPCWorkerThreadPlugin=N([C(1,o.Inject(o.Injector)),C(2,o.IConfigService)],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=O;exports.ChannelServer=j;exports.ChannelService=M;exports.IRPCChannelService=S;exports.IRemoteInstanceService=m;exports.IRemoteSyncService=v;exports.PLUGIN_CONFIG_KEY_MAIN_THREAD=k;exports.PLUGIN_CONFIG_KEY_WORKER_THREAD=D;exports.RemoteInstanceServiceName=I;exports.RemoteSyncServiceName=R;exports.fromModule=E;exports.toModule=U;
package/lib/es/index.js CHANGED
@@ -518,6 +518,7 @@ export {
518
518
  I as IRPCChannelService,
519
519
  m as IRemoteInstanceService,
520
520
  g as IRemoteSyncService,
521
+ he as PLUGIN_CONFIG_KEY_MAIN_THREAD,
521
522
  le as PLUGIN_CONFIG_KEY_WORKER_THREAD,
522
523
  D as RemoteInstanceServiceName,
523
524
  M as RemoteSyncPrimaryService,
package/lib/index.js CHANGED
@@ -518,6 +518,7 @@ export {
518
518
  I as IRPCChannelService,
519
519
  m as IRemoteInstanceService,
520
520
  g as IRemoteSyncService,
521
+ he as PLUGIN_CONFIG_KEY_MAIN_THREAD,
521
522
  le as PLUGIN_CONFIG_KEY_WORKER_THREAD,
522
523
  D as RemoteInstanceServiceName,
523
524
  M as RemoteSyncPrimaryService,
@@ -14,7 +14,7 @@
14
14
  * limitations under the License.
15
15
  */
16
16
  export type { IUniverRPCMainThreadConfig, IUniverRPCWorkerThreadConfig } from './controllers/config.schema';
17
- export { PLUGIN_CONFIG_KEY_WORKER_THREAD } from './controllers/config.schema';
17
+ export { PLUGIN_CONFIG_KEY_MAIN_THREAD, PLUGIN_CONFIG_KEY_WORKER_THREAD } from './controllers/config.schema';
18
18
  export { DataSyncPrimaryController } from './controllers/data-sync/data-sync-primary.controller';
19
19
  export { DataSyncReplicaController } from './controllers/data-sync/data-sync-replica.controller';
20
20
  export { UniverRPCMainThreadPlugin, UniverRPCWorkerThreadPlugin, } from './plugin';
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,u,d){"use strict";var J=Object.defineProperty;var Q=(r,a,u)=>a in r?J(r,a,{enumerable:!0,configurable:!0,writable:!0,value:u}):r[a]=u;var h=(r,a,u)=>Q(r,typeof a!="symbol"?a+"":a,u);var U,E;const $="rpc.main-thread.config",W={},k="rpc.worker-thread.config",D={};var L=Object.getOwnPropertyDescriptor,q=(c,t,e,n)=>{for(var s=n>1?void 0:n?L(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=o(s)||s);return s},g=(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([g(0,a.ICommandService)],r.RemoteSyncPrimaryService);const f="univer.remote-instance-service",p=a.createIdentifier(f);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){this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${t.unitID}`);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._logService.debug(`[WebWorkerRemoteInstanceService]: Disposing instance with id ${t.unitID}`),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([g(0,a.IUniverInstanceService),g(1,a.ICommandService),g(2,a.ILogService)],r.WebWorkerRemoteInstanceService);function b(c){const t=c;return new class{call(e,n){const s=t[e];if(typeof s=="function"){let i=n?s.apply(t,n):s.call(t);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=n?s.apply(t,n):s.call(t);return d.isObservable(i)?i:d.of(i)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function P(c){return new Proxy({},{get(t,e){if(e!=="dispose")return function(...n){return H(e)?c.subscribe(e,n):c.call(e,n)}}})}function H(c){return c.endsWith("$")}class O 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.send({type:50}),this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onMessage(n))}dispose(){this._pendingRequests.clear()}getChannel(e){const n=this;return{call(s,i){return n._disposed?Promise.reject():n._remoteCall(e,s,i)},subscribe(s,i){if(n._disposed)throw new Error("[ChannelClient]: client is disposed!");return n._remoteSubscribe(e,s,i)}}}_whenReady(){return d.firstValueFrom(this._initialized.pipe(u.filter(e=>e),u.take(1)))}async _remoteCall(e,n,s){await this._whenReady();const i=++this._lastRequestCounter,_={seq:i,type:100,channelName:e,method:n,args:s},l=this;return new Promise((M,S)=>{const B={handle(T){switch(T.type){case 201:l._pendingRequests.delete(i),M(T.data);break;case 202:l._pendingRequests.delete(i),S(T.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(i,B),this._sendRequest(_)})}_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},M={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,M),this._sendRequest(l)}),()=>{if(o===-1)return;const _={type:102,seq:o,channelName:e,method:n};this._sendRequest(_)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var i;const{type:n,seq:s}=e;switch(n){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:{const{_pendingRequests:o}=this;(i=o.get(s))==null||i.handle(e),n!==300&&o.delete(s);break}}}}class j extends a.RxDisposable{constructor(e){super();h(this,"_channels",new Map);h(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onRequest(n)),this._sendInitialize()}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,n){this._channels.set(e,n)}_onRequest(e){switch(e.type){case 50:this._sendInitialize();break;case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_sendInitialize(){this._sendResponse({seq:-1,type:0})}_onMethodCall(e){const{channelName:n,method:s,args:i}=e,o=this._channels.get(n);let _;try{if(!o)throw new Error(`[ChannelServer]: Channel ${n} not found!`);_=i?o.call(s,i):o.call(s)}catch(l){_=Promise.reject(l)}_.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 _=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,_)}catch(o){o instanceof Error?this._sendResponse({seq:e.seq,type:301,data:o.message}):this._sendResponse({seq:e.seq,type:301,data:String(o)})}}_onUnsubscribe(e){const n=this._subscriptions.get(e.seq);n&&(n.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const m=a.createIdentifier("IRPCChannelService");class w{constructor(t){h(this,"_client");h(this,"_server");this._client=new O(t),this._server=new j(t)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(t){return this._client.getChannel(t)}registerChannel(t,e){this._server.registerChannel(t,e)}}var 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=o(s)||s);return s},y=(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,b(this._remoteSyncService)),this._injector.add([p,{useFactory:()=>P(this._rpcChannelService.requestChannel(f))}]),this._remoteInstanceService=this._injector.get(p)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:a.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{const{type:s,params:i,id:o}=e,_=(i==null?void 0:i.unitId)||"";s===a.CommandType.MUTATION&&(!_||this._syncingUnits.has(_))&&!(n!=null&&n.fromSync)&&this._syncingMutations.has(o)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}},r.DataSyncPrimaryController=F([y(0,a.Inject(a.Injector)),y(1,a.ICommandService),y(2,a.IUniverInstanceService),y(3,m),y(4,v)],r.DataSyncPrimaryController);var G=Object.getOwnPropertyDescriptor,V=(c,t,e,n)=>{for(var s=n>1?void 0:n?G(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=o(s)||s);return s},R=(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(f,b(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>P(this._rpcChannelService.requestChannel(C))}]),this._remoteSyncService=this._injector.get(v)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{e.type===a.CommandType.MUTATION&&!(n!=null&&n.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}},r.DataSyncReplicaController=V([R(0,a.Inject(a.Injector)),R(1,p),R(2,a.ICommandService),R(3,m)],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 K(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 Y=Object.getOwnPropertyDescriptor,N=(c,t,e,n)=>{for(var s=n>1?void 0:n?Y(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=o(s)||s);return s},I=(c,t)=>(e,n)=>t(e,n,c);r.UniverRPCMainThreadPlugin=(U=class extends a.Plugin{constructor(e=W,n,s){super();h(this,"_internalWorker",null);this._config=e,this._injector=n,this._configService=s;const{...i}=a.merge({},W,this._config);this._configService.setConfig($,i)}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL:e}=this._config;if(!e)throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");const n=e instanceof Worker?e:new Worker(e);this._internalWorker=e instanceof Worker?null:n;const s=K(n);[[m,{useFactory:()=>new w(s)}],[r.DataSyncPrimaryController],[v,{useClass:r.RemoteSyncPrimaryService}]].forEach(o=>this._injector.add(o)),this._injector.get(r.DataSyncPrimaryController)}},h(U,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),U),r.UniverRPCMainThreadPlugin=N([I(1,a.Inject(a.Injector)),I(2,a.IConfigService)],r.UniverRPCMainThreadPlugin),r.UniverRPCWorkerThreadPlugin=(E=class extends a.Plugin{constructor(t=D,e,n){super(),this._config=t,this._injector=e,this._configService=n;const{...s}=a.merge({},D,this._config);this._configService.setConfig(k,s)}onStarting(){[[r.DataSyncReplicaController],[m,{useFactory:()=>new w(z())}],[p,{useClass:r.WebWorkerRemoteInstanceService}]].forEach(t=>this._injector.add(t)),this._injector.get(r.DataSyncReplicaController)}},h(E,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),E),r.UniverRPCWorkerThreadPlugin=N([I(1,a.Inject(a.Injector)),I(2,a.IConfigService)],r.UniverRPCWorkerThreadPlugin),r.ChannelClient=O,r.ChannelServer=j,r.ChannelService=w,r.IRPCChannelService=m,r.IRemoteInstanceService=p,r.IRemoteSyncService=v,r.PLUGIN_CONFIG_KEY_WORKER_THREAD=k,r.RemoteInstanceServiceName=f,r.RemoteSyncServiceName=C,r.fromModule=b,r.toModule=P,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(r,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs/operators"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs/operators","rxjs"],a):(r=typeof globalThis<"u"?globalThis:r||self,a(r.UniverRpc={},r.UniverCore,r.rxjs.operators,r.rxjs))})(this,(function(r,a,u,d){"use strict";var J=Object.defineProperty;var Q=(r,a,u)=>a in r?J(r,a,{enumerable:!0,configurable:!0,writable:!0,value:u}):r[a]=u;var h=(r,a,u)=>Q(r,typeof a!="symbol"?a+"":a,u);var U,E;const W="rpc.main-thread.config",k={},D="rpc.worker-thread.config",q={};var L=Object.getOwnPropertyDescriptor,O=(c,t,e,n)=>{for(var s=n>1?void 0:n?L(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=o(s)||s);return s},g=(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=O([g(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){this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${t.unitID}`);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._logService.debug(`[WebWorkerRemoteInstanceService]: Disposing instance with id ${t.unitID}`),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=O([g(0,a.IUniverInstanceService),g(1,a.ICommandService),g(2,a.ILogService)],r.WebWorkerRemoteInstanceService);function b(c){const t=c;return new class{call(e,n){const s=t[e];if(typeof s=="function"){let i=n?s.apply(t,n):s.call(t);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=n?s.apply(t,n):s.call(t);return d.isObservable(i)?i:d.of(i)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function P(c){return new Proxy({},{get(t,e){if(e!=="dispose")return function(...n){return H(e)?c.subscribe(e,n):c.call(e,n)}}})}function H(c){return c.endsWith("$")}class j 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.send({type:50}),this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onMessage(n))}dispose(){this._pendingRequests.clear()}getChannel(e){const n=this;return{call(s,i){return n._disposed?Promise.reject():n._remoteCall(e,s,i)},subscribe(s,i){if(n._disposed)throw new Error("[ChannelClient]: client is disposed!");return n._remoteSubscribe(e,s,i)}}}_whenReady(){return d.firstValueFrom(this._initialized.pipe(u.filter(e=>e),u.take(1)))}async _remoteCall(e,n,s){await this._whenReady();const i=++this._lastRequestCounter,_={seq:i,type:100,channelName:e,method:n,args:s},l=this;return new Promise((M,S)=>{const B={handle(T){switch(T.type){case 201:l._pendingRequests.delete(i),M(T.data);break;case 202:l._pendingRequests.delete(i),S(T.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(i,B),this._sendRequest(_)})}_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},M={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,M),this._sendRequest(l)}),()=>{if(o===-1)return;const _={type:102,seq:o,channelName:e,method:n};this._sendRequest(_)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var i;const{type:n,seq:s}=e;switch(n){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:{const{_pendingRequests:o}=this;(i=o.get(s))==null||i.handle(e),n!==300&&o.delete(s);break}}}}class N extends a.RxDisposable{constructor(e){super();h(this,"_channels",new Map);h(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(u.takeUntil(this.dispose$)).subscribe(n=>this._onRequest(n)),this._sendInitialize()}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,n){this._channels.set(e,n)}_onRequest(e){switch(e.type){case 50:this._sendInitialize();break;case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_sendInitialize(){this._sendResponse({seq:-1,type:0})}_onMethodCall(e){const{channelName:n,method:s,args:i}=e,o=this._channels.get(n);let _;try{if(!o)throw new Error(`[ChannelServer]: Channel ${n} not found!`);_=i?o.call(s,i):o.call(s)}catch(l){_=Promise.reject(l)}_.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 _=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,_)}catch(o){o instanceof Error?this._sendResponse({seq:e.seq,type:301,data:o.message}):this._sendResponse({seq:e.seq,type:301,data:String(o)})}}_onUnsubscribe(e){const n=this._subscriptions.get(e.seq);n&&(n.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const m=a.createIdentifier("IRPCChannelService");class w{constructor(t){h(this,"_client");h(this,"_server");this._client=new j(t),this._server=new N(t)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(t){return this._client.getChannel(t)}registerChannel(t,e){this._server.registerChannel(t,e)}}var A=Object.getOwnPropertyDescriptor,G=(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=o(s)||s);return s},y=(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,b(this._remoteSyncService)),this._injector.add([p,{useFactory:()=>P(this._rpcChannelService.requestChannel(R))}]),this._remoteInstanceService=this._injector.get(p)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:a.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).pipe(u.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{const{type:s,params:i,id:o}=e,_=(i==null?void 0:i.unitId)||"";s===a.CommandType.MUTATION&&(!_||this._syncingUnits.has(_))&&!(n!=null&&n.fromSync)&&this._syncingMutations.has(o)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}},r.DataSyncPrimaryController=G([y(0,a.Inject(a.Injector)),y(1,a.ICommandService),y(2,a.IUniverInstanceService),y(3,m),y(4,v)],r.DataSyncPrimaryController);var F=Object.getOwnPropertyDescriptor,V=(c,t,e,n)=>{for(var s=n>1?void 0:n?F(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=o(s)||s);return s},f=(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,b(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>P(this._rpcChannelService.requestChannel(C))}]),this._remoteSyncService=this._injector.get(v)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{e.type===a.CommandType.MUTATION&&!(n!=null&&n.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}},r.DataSyncReplicaController=V([f(0,a.Inject(a.Injector)),f(1,p),f(2,a.ICommandService),f(3,m)],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 K(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 Y=Object.getOwnPropertyDescriptor,$=(c,t,e,n)=>{for(var s=n>1?void 0:n?Y(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=o(s)||s);return s},I=(c,t)=>(e,n)=>t(e,n,c);r.UniverRPCMainThreadPlugin=(U=class extends a.Plugin{constructor(e=k,n,s){super();h(this,"_internalWorker",null);this._config=e,this._injector=n,this._configService=s;const{...i}=a.merge({},k,this._config);this._configService.setConfig(W,i)}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL:e}=this._config;if(!e)throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");const n=e instanceof Worker?e:new Worker(e);this._internalWorker=e instanceof Worker?null:n;const s=K(n);[[m,{useFactory:()=>new w(s)}],[r.DataSyncPrimaryController],[v,{useClass:r.RemoteSyncPrimaryService}]].forEach(o=>this._injector.add(o)),this._injector.get(r.DataSyncPrimaryController)}},h(U,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),U),r.UniverRPCMainThreadPlugin=$([I(1,a.Inject(a.Injector)),I(2,a.IConfigService)],r.UniverRPCMainThreadPlugin),r.UniverRPCWorkerThreadPlugin=(E=class extends a.Plugin{constructor(t=q,e,n){super(),this._config=t,this._injector=e,this._configService=n;const{...s}=a.merge({},q,this._config);this._configService.setConfig(D,s)}onStarting(){[[r.DataSyncReplicaController],[m,{useFactory:()=>new w(z())}],[p,{useClass:r.WebWorkerRemoteInstanceService}]].forEach(t=>this._injector.add(t)),this._injector.get(r.DataSyncReplicaController)}},h(E,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),E),r.UniverRPCWorkerThreadPlugin=$([I(1,a.Inject(a.Injector)),I(2,a.IConfigService)],r.UniverRPCWorkerThreadPlugin),r.ChannelClient=j,r.ChannelServer=N,r.ChannelService=w,r.IRPCChannelService=m,r.IRemoteInstanceService=p,r.IRemoteSyncService=v,r.PLUGIN_CONFIG_KEY_MAIN_THREAD=W,r.PLUGIN_CONFIG_KEY_WORKER_THREAD=D,r.RemoteInstanceServiceName=R,r.RemoteSyncServiceName=C,r.fromModule=b,r.toModule=P,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/rpc",
3
- "version": "0.12.4-experimental.20251211-e01e32a",
3
+ "version": "0.12.4-insiders.20251211-c28f914",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -47,7 +47,7 @@
47
47
  "rxjs": ">=7.0.0"
48
48
  },
49
49
  "dependencies": {
50
- "@univerjs/core": "0.12.4-experimental.20251211-e01e32a"
50
+ "@univerjs/core": "0.12.4-insiders.20251211-c28f914"
51
51
  },
52
52
  "devDependencies": {
53
53
  "rxjs": "^7.8.2",