"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubProcessProxy=void 0;const processService_1=require("./processService"),customError_1=require("../customError"),singletontask_1=require("../singletontask"),debug_1=require("../debug");class SubProcessProxy{constructor(s,e,t,r,o=8891,i){this.project=s,this.entryPath=e,this.passData=t,this.initOptions=r,this.inspectPort=o,this.progressUpdate=i,this.taskMap=new Map,this.taskId=0,this.init=async()=>{this.process=await this.forkProcess()},this.onMessage=s=>{var e,t;if(this._cpPromise&&("ready"===s.type&&(clearTimeout(this._cpPromise.timer),null===(e=this._cpPromise)||void 0===e||e.resolve()),"noReady"===s.type&&this._cpPromise.reject(new Error(s.error.message))),"progress"===s.type){const e=this.taskMap.get(s.taskId);(null==e?void 0:e.progressUpdate)&&e.progressUpdate(s.id,s.status,s.message)}if("log"===s.type&&(null===(t=this.progressUpdate)||void 0===t||t.call(this,s.id||"",s.status,s.text)),"response"===s.type){const{id:e,data:t,error:r}=s;r?this.onResponse(e,void 0,r):this.onResponse(e,t,void 0)}}}async ready(){var s;return this._checkReadyTask||(this._checkReadyTask=new singletontask_1.SingletonTask(this.init)),await(null===(s=this._checkReadyTask)||void 0===s?void 0:s.getResult(!0))}async sendProcessMessage(s){await this.ready(),this.process.send(s)}destroy(){var s;null===(s=this.process)||void 0===s||s.kill("SIGTERM"),this.process=void 0,this._checkReadyTask=void 0}async forkProcess(){const s=await this.project.serialize(),e={type:"init",data:{passData:this.passData,projectInfo:s,options:this.initOptions}};if((0,debug_1.shouldRunInMainProcess)()){const s=require("../../modules/corecompiler/processHandler");return await s.initHandler(e),s.onMessage(this.onMessage),{send:e=>{(0,debug_1.shouldRunInMainProcess)()&&s.messageHandler(e)},kill:e=>(s.destroy(),!0)}}return await(0,processService_1.forkProcess)(this,this.entryPath,this.project.projectPath,e,this.inspectPort)}onResponse(s,e,t){const r=this.taskMap.get(s);this.taskMap.delete(s),r?t?(t=new customError_1.CustomError(t),r.reject(t)):r.resolve(e):console.error(`child process task: ${s} not found`)}async sendEvent(s,e){this.sendProcessMessage({type:"event",name:s,data:e})}async runTask(s,e,t){return new Promise((r,o)=>{const i={name:s,data:e,resolve:r,reject:o,progressUpdate:t};this.taskId+=1,this.taskMap.set(this.taskId,i),this.sendProcessMessage({type:"request",id:this.taskId,name:s,data:e})})}}exports.SubProcessProxy=SubProcessProxy;