import{Runtime as s}from"../root/root.js";class e{dispose(){}setNotify(s){}}const t=self,o=new class{constructor(s){this._port=s,this._port.onmessage=this._onMessage.bind(this),this._port.onerror=console.error}setHandlers(s,e){this._messageHandler=s,this._closeHandler=e}send(s){return this._port.postMessage(s),Promise.resolve()}close(){return Promise.resolve()}_onMessage(s){this._messageHandler(s.data)}}(t);[].push(new class{constructor(s){this._objects=new Map,this._lastObjectId=1,this._port=s,this._port.setHandlers(this._dispatchMessageWrapped.bind(this),this._connectionClosed.bind(this))}_dispatchMessageWrapped(s){let e;try{if(e=JSON.parse(s),!(e instanceof Object))return void this._sendErrorResponse(e.id,"Malformed message");this._dispatchMessage(e)}catch(s){this._sendErrorResponse(e?e.id:"",s.toString()+" "+s.stack)}}_dispatchMessage(t){const o=t.method.split("."),i=o[0],r=o[1];if("create"===r){const o=s.Runtime.instance().extensions(e).filter(s=>s.descriptor().name===i);if(!o.length)return void this._sendErrorResponse(t.id,"Could not resolve service '"+i+"'");o[0].instance().then(s=>{const e=String(this._lastObjectId++);s.setNotify(this._notify.bind(this,e,i)),this._objects.set(e,s),this._sendResponse(t.id,{id:e})})}else if("dispose"===r){const s=this._objects.get(t.params.id);if(!s)return void console.error("Could not look up object with id for "+JSON.stringify(t));this._objects.delete(t.params.id),s.dispose().then(()=>this._sendResponse(t.id,{}))}else{if(!t.params)return void console.error("No params in the message: "+JSON.stringify(t));const s=this._objects.get(t.params.id);if(!s)return void console.error("Could not look up object with id for "+JSON.stringify(t));if(!(s[r]instanceof Function))return void console.error("Handler for '"+r+"' is missing.");s[r](t.params).then(s=>this._sendResponse(t.id,s))}}_connectionClosed(){for(const s of this._objects.values())s.dispose();this._objects.clear()}_notify(s,e,t,o){o.id=s;const i={method:e+"."+t,params:o};this._port.send(JSON.stringify(i))}_sendResponse(s,e){const t={id:s,result:e};this._port.send(JSON.stringify(t))}_sendErrorResponse(s,e){const t={id:s,error:e};this._port.send(JSON.stringify(t))}}(o)),self.Service=e;
