@kemu-io/edge-runtime 1.8.0 → 1.8.1
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/package.json +1 -1
- package/runner.js +1 -1
package/package.json
CHANGED
package/runner.js
CHANGED
|
@@ -9,4 +9,4 @@ r.version="2.30.1",function(e){t=e}(jt),r.fn=An,r.min=function(){return Ft("isBe
|
|
|
9
9
|
*/
|
|
10
10
|
var e=$,t=I,n=_y(),r=l,o=D,s={};by=s;var a=["daily","test","m","h","custom"],c="YYYYMMDDHHmm";function u(t,n){if(t.hash===r.createHash(t.hashType).update(t.name+"LOG_FILE"+t.date).digest("hex"))try{e.existsSync(t.name)&&e.unlinkSync(t.name)}catch(e){n&&console.error(new Date,"[FileStreamRotator] Could not remove old log file: ",t.name)}}s.getFrequency=function(e){var t=e.toLowerCase().match(/^(\d+)([mh])$/);if(t)return function(e,t){if("number"==typeof t){switch(e){case"m":if(t<0||t>60)return!1;break;case"h":if(t<0||t>24)return!1}return{type:e,digit:t}}}(t[2],parseInt(t[1]));var n=function(e){switch(e){case"custom":case"daily":return{type:e,digit:void 0};case"test":return{type:e,digit:0}}return!1}(e);return n||!1},s.parseFileSize=function(e){if(e&&"string"==typeof e){var t=e.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/);if(t)switch(t[2]){case"k":return 1024*t[1];case"m":return 1024*t[1]*1024;case"g":return 1024*t[1]*1024*1024}}return null},s.getDate=function(e,t,r){t=t||c;let i=r?n.utc():n().local();if(e&&-1!==a.indexOf(e.type))switch(e.type){case"m":var o=Math.floor(i.minutes()/e.digit)*e.digit;return i.minutes(o).format(t);case"h":var s=Math.floor(i.hour()/e.digit)*e.digit;return i.hour(s).format(t);case"daily":case"custom":case"test":return i.format(t)}return i.format(t)},s.setAuditLog=function(n,r,i){var o=null;if(n){var s=n.toString().substr(-1),a=n.toString().match(/^(\d+)/);if(Number(a[1])>0){var c=t.dirname(i.replace(/%DATE%.+/,"_filename"));try{if(r){var l=t.resolve(r);o=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}else l=t.resolve(c+"/.audit.json"),o=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}catch(n){if("ENOENT"!==n.code)return null;o={keep:{days:!1,amount:Number(a[1])},auditLog:r||c+"/.audit.json",files:[]}}o.keep={days:"d"===s,amount:Number(a[1])}}}return o},s.writeAuditLog=function(t,n){try{d(t.auditLog),e.writeFileSync(t.auditLog,JSON.stringify(t,null,4))}catch(e){n&&console.error(new Date,"[FileStreamRotator] Failed to store log audit at:",t.auditLog,"Error:",e)}},s.addLogToAudit=function(e,t,i,o){if(t&&t.files){if(-1!==t.files.findIndex((function(t){return t.name===e})))return t;var a=Date.now();if(t.files.push({date:a,name:e,hash:r.createHash(t.hashType).update(e+"LOG_FILE"+a).digest("hex")}),t.keep.days){var c=n().subtract(t.keep.amount,"days").valueOf(),l=t.files.filter((function(e){return e.date>c||(e.hashType=t.hashType,u(e,o),i.emit("logRemoved",e),!1)}));t.files=l}else{var d=t.files.splice(-t.keep.amount);t.files.length>0&&t.files.filter((function(e){return e.hashType=t.hashType,u(e,o),i.emit("logRemoved",e),!1})),t.files=d}s.writeAuditLog(t,o)}return t},s.getStream=function(r){var l=null,u=null,f=this;if(!r.filename)return console.error(new Date,"[FileStreamRotator] No filename supplied. Defaulting to STDOUT"),process.stdout;r.frequency&&(l=f.getFrequency(r.frequency));let p=f.setAuditLog(r.max_logs,r.audit_file,r.filename);null!=p&&(p.hashType=void 0!==r.audit_hash_type?r.audit_hash_type:"md5"),f.verbose=void 0===r.verbose||r.verbose;var g=null,m=0,y=0;r.size&&(g=s.parseFileSize(r.size));var v=r.date_format||c;l&&"daily"==l.type&&(r.date_format||(v="YYYY-MM-DD"),n().format(v)==n().endOf("day").format(v)&&n().format(v)!=n().add(1,"day").format(v)||(f.verbose&&console.log(new Date,"[FileStreamRotator] Changing type to custom as date format changes more often than once a day or not every day"),l.type="custom")),l&&(u=r.frequency?f.getDate(l,v,r.utc):""),r.create_symlink=r.create_symlink||!1,r.extension=r.extension||"";var b=r.filename,w=null,S=b+(u?"."+u:"");if(b.match(/%DATE%/)&&(S=b.replace(/%DATE%/g,u||f.getDate(null,v,r.utc))),g){var _=null,I=S;if(p&&p.files&&p.files instanceof Array&&p.files.length>0){var x=p.files[p.files.length-1].name;if(x.match(I)){var k=x.match(I+"\\.(\\d+)");k&&(I=x,m=k[1])}}for(0==m&&I==S&&(I+=r.extension);e.existsSync(I);)_=I,m++,I=S+"."+m+r.extension;if(_){var E=e.statSync(_);E.size<g&&(I=_,m--,y=E.size)}S=I}else S+=r.extension;f.verbose&&console.log(new Date,"[FileStreamRotator] Logging to: ",S),d(S);var C=r.file_options||{flags:"a"},$=e.createWriteStream(S,C);if(u&&l&&a.indexOf(l.type)>-1||g>0){f.verbose&&console.log(new Date,"[FileStreamRotator] Rotating file: ",l?l.type:"",g?"size: "+g:"");var O,N=new o;return N.auditLog=p,N.end=function(){$.end.apply($,arguments)},h($,N),N.on("close",(function(){O&&O.close()})),N.on("new",(function(n){N.auditLog=f.addLogToAudit(n,N.auditLog,N,f.verbose),r.create_symlink&&function(n,r,i){let o=r||"current.log",s=t.dirname(n),a=t.basename(n),c=s+"/"+o;try{e.lstatSync(c).isSymbolicLink()&&(e.unlinkSync(c),e.symlinkSync(a,c))}catch(n){if(n&&"ENOENT"==n.code)try{e.symlinkSync(a,c)}catch(n){i&&console.error(new Date,"[FileStreamRotator] Could not create symlink file: ",c," -> ",a)}}}(n,r.symlink_name,f.verbose),r.watch_log&&N.emit("addWatcher",n)})),N.on("addWatcher",(function(t){O&&O.close(),r.watch_log&&(O=function(t,n){if(!t)return null;try{return e.lstatSync(t),e.watch(t,(function(n){if("rename"==n)try{e.lstatSync(t)}catch(e){!function(e,t){N.emit("createLog",t)}(0,t)}}))}catch(e){n&&console.log(new Date,"[FileStreamRotator] Could not add watcher for "+t)}}(t,f.verbose))})),N.on("createLog",(function(t){try{e.lstatSync(t)}catch(n){$&&"function"==$.end&&$.end(),$=e.createWriteStream(t,C),N.emit("new",t),h($,N)}})),N.write=function(t,n){var o=l?this.getDate(l,v,r.utc):u;if(o!=u||g&&y>g){var s=b+(u&&l?"."+o:"");b.match(/%DATE%/)&&u&&(s=b.replace(/%DATE%/g,o)),g&&y>g?s+="."+ ++m+r.extension:(m=0,s+=r.extension),y=0,f.verbose&&console.log(new Date,i.format("[FileStreamRotator] Changing logs from %s to %s",S,s)),u=o,w=S,S=s,!0===r.end_stream?$.end():$.destroy(),d(S),$=e.createWriteStream(s,C),N.emit("new",s),N.emit("rotate",w,s),h($,N)}$.write(t,n),y+=Buffer.byteLength(t,n)}.bind(this),process.nextTick((function(){N.emit("new",S)})),N.emit("new",S),N}return f.verbose&&console.log(new Date,"[FileStreamRotator] File won't be rotated: ",r.frequency,r.size),process.nextTick((function(){$.emit("new",S)})),$};var d=function(n){t.dirname(n).split(t.sep).reduce((function(n,r){if(n+=r+t.sep,!e.existsSync(n))try{e.mkdirSync(n)}catch(n){if("EEXIST"!==n.code)throw n}return n}),"")},h=function(e,t){e.on("close",(function(){t.emit("close")})),e.on("finish",(function(){t.emit("finish")})),e.on("error",(function(e){t.emit("error",e)})),e.on("open",(function(e){t.emit("open",e)}))};return by}const xy=$,ky=N,Ey=I,Cy=i,$y=j,Oy=yy.exports,Ny=rh.MESSAGE,Ty=M.PassThrough,Ay=Op,My={json:!1,colorize:!1,eol:ky.EOL,logstash:null,prettyPrint:!1,label:null,stringify:!1,depth:null,showLevel:!0,timestamp:()=>(new Date).toISOString()},Py=function(e){if(e=e||{},Ay.call(this,e),this.options=Object.assign({},My,e),e.stream)!function(t){Array.prototype.slice.call(arguments,1).forEach((n=>{if(e[n])throw new Error("Cannot set "+n+" and "+t+" together")}))}("stream","filename","maxsize"),this.logStream=new Ty,this.logStream.pipe(e.stream);else{if(this.filename=e.filename?Ey.basename(e.filename):"winston.log",this.dirname=e.dirname||Ey.dirname(e.filename),t=this.filename,/["<>|:*?\\/\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test(t)||!function(e){return!/["<>|\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test(e)}(this.dirname))throw new Error("Your path or filename contain an invalid character.");this.logStream=Iy().getStream({filename:Ey.join(this.dirname,this.filename),frequency:e.frequency?e.frequency:"custom",date_format:e.datePattern?e.datePattern:"YYYY-MM-DD",verbose:!1,size:function(e){if(e&&"string"==typeof e){if(e.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/))return e}else if(e&&Number.isInteger(e)){const t=Math.round(e/1024);return 0===t?"1k":t+"k"}return null}(e.maxSize),max_logs:e.maxFiles,end_stream:!0,audit_file:e.auditFile?e.auditFile:Ey.join(this.dirname,"."+Oy(e)+"-audit.json"),file_options:e.options?e.options:{flags:"a"},utc:!!e.utc&&e.utc,extension:e.extension?e.extension:"",create_symlink:!!e.createSymlink&&e.createSymlink,symlink_name:e.symlinkName?e.symlinkName:"current.log",watch_log:!!e.watchLog&&e.watchLog,audit_hash_type:e.auditHashType?e.auditHashType:"sha256"}),this.logStream.on("new",(e=>{this.emit("new",e)})),this.logStream.on("rotate",((e,t)=>{this.emit("rotate",e,t)})),this.logStream.on("logRemoved",(t=>{if(e.zippedArchive){const e=t.name+".gz";try{xy.unlinkSync(e)}catch(t){if("ENOENT"!==t.code)return t.message=`Error occurred while removing ${e}: ${t.message}`,void this.emit("error",t)}this.emit("logRemoved",e)}else this.emit("logRemoved",t.name)})),e.zippedArchive&&this.logStream.on("rotate",(e=>{try{if(!xy.existsSync(e))return}catch(t){return t.message=`Error occurred while checking existence of ${e}: ${t.message}`,void this.emit("error",t)}try{if(xy.existsSync(`${e}.gz`))return}catch(t){return t.message=`Error occurred while checking existence of ${e}.gz: ${t.message}`,void this.emit("error",t)}const t=$y.createGzip(),n=xy.createReadStream(e);n.on("error",(t=>{t.message=`Error occurred while reading ${e}: ${t.message}`,this.emit("error",t)}));const r=xy.createWriteStream(e+".gz");r.on("error",(t=>{t.message=`Error occurred while writing ${e}.gz: ${t.message}`,this.emit("error",t)})),n.pipe(t).pipe(r).on("finish",(()=>{try{xy.unlinkSync(e)}catch(t){if("ENOENT"!==t.code)return t.message=`Error occurred while removing ${e}: ${t.message}`,void this.emit("error",t)}this.emit("archive",e+".gz")}))})),e.watchLog&&this.logStream.on("addWatcher",(e=>{this.emit("addWatcher",e)}))}var t};var Dy=Py;Cy.inherits(Py,Ay),Py.prototype.name="dailyRotateFile";const jy=function(){};Py.prototype.log=function(e,t){t=t||jy,this.logStream.write(e[Ny]+this.options.eol),this.emit("logged",e),t(null,!0)},Py.prototype.close=function(){this.logStream&&this.logStream.end((()=>{this.emit("finish")}))},Py.prototype.query=function(e,t){if("function"==typeof e&&(t=e,e={}),!this.options.json)throw new Error("query() may not be used without the json option being set to true");if(!this.filename)throw new Error("query() may not be used when initializing with a stream");let n=[];(e=e||{}).rows=e.rows||e.limit||10,e.start=e.start||0,e.until=e.until||new Date,"object"!=typeof e.until&&(e.until=new Date(e.until)),e.from=e.from||e.until-864e5,"object"!=typeof e.from&&(e.from=new Date(e.from)),e.order=e.order||"desc";const r=(()=>{const e=new RegExp(this.filename.replace("%DATE%",".*"),"i");return xy.readdirSync(this.dirname).filter((t=>Ey.basename(t).match(e)))})();0===r.length&&t&&t(null,n);const i=o=>{if(!o)return;const s=Ey.join(this.dirname,o);let a,c="";if(o.endsWith(".gz")){a=new Ty;const e=xy.createReadStream(s);e.on("error",(e=>{e.message=`Error occurred while reading ${s}: ${e.message}`,a.emit("error",e)})),e.pipe($y.createGunzip()).pipe(a)}else a=xy.createReadStream(s,{encoding:"utf8"});function l(t,r){try{const r=JSON.parse(t);if(!r||"object"!=typeof r)return;const i=new Date(r.timestamp);if(e.from&&i<e.from||e.until&&i>e.until||e.level&&e.level!==r.level)return;n.push(r)}catch(e){r||a.emit("error",e)}}a.on("error",(e=>{if(a.readable&&a.destroy(),t)return"ENOENT"===e.code?t(null,n):t(e)})),a.on("data",(e=>{const t=(e=(c+e).split(/\n+/)).length-1;for(let n=0;n<t;n++)l(e[n]);c=e[t]})),a.on("end",(()=>{if(c&&l(c,!0),r.length)i(r.shift());else if(t){n.sort(((e,t)=>{const n=new Date(e.timestamp).getTime(),r=new Date(t.timestamp).getTime();return n>r?1:n<r?-1:0})),"desc"===e.order&&(n=n.reverse());const r=e.start||0,i=e.limit||n.length;n=n.slice(r,r+i),e.fields&&(n=n.map((t=>{const n={};return e.fields.forEach((e=>{n[e]=t[e]})),n}))),t(null,n)}}))};i(r.shift())};const Ry=Dy;kd.transports.DailyRotateFile=Ry;var Ly=ad(Ry);const Fy=Date.now();let Uy=Math.ceil(Fy/1e3);var By=()=>Uy+=1;const Wy=x(T(),"kemu-user-services"),Gy=x(T(),"kemu-test-services"),Vy="KMU-CB-v1",Yy=process.env.HUB_PKG_VERSION||'"1.10.1"';var Hy;!function(e){e.input="input",e.counter="counter",e.play="play",e.elapsed="elapsed",e.ifGate="ifGate",e.skipEvent="skipEvent",e.between="between",e.map="map",e.parser="parser",e.slider="slider",e.suspend="suspend",e.display="display",e.pixelfy="pixelfy",e.json="json",e.arrayItem="arrayItem",e.extractImage="extractImage",e.imageConvolution="imageConvolution",e.firstEvent="firstEvent",e.pixelDraw="pixelDraw",e.randomBetween="randomBetween",e.arrayCombine="arrayCombine",e.clock="clock",e.multiplication="multiplication",e.object="object",e.widgetGroup="widgetGroup",e.script="script",e.base64ToImageData="base64ToImageData",e.jsonParse="jsonParse",e.text="text",e.imageCrop="imageCrop",e.imageResize="imageResize",e.value="value",e.imageWarp="imageWarp",e.widgetBundle="widgetBundle",e.sequence="sequence",e.variable="variable",e.hubService="hubService"}(Hy||(Hy={}));const zy=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>ju[e])):ju[e.type]}),qy=async e=>{try{return await S(e,"utf-8")}catch(e){return null}},Ky=e=>{if(e&&e.startsWith(Vy)){const t=e.slice(9),n=decodeURI(t);return qu(n)}return null},Jy=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(zy)}:{},...e.outputs?{outputs:e.outputs.map(zy)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(zy)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(zy)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},o=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const i of t.customWidgets){const t=await qy(x(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const o=t.startsWith(Vy)?t:`${Vy}${t}`,s=Ky(o);if(!s){n(`Custom widget file "${i}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(s).filter((e=>e.type===Hy.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${i}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${i}" does not contain a top level widgetGroup`);continue}const l=c.state,u={name:l.name,color:l.color,description:l.description,contents:o,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}return r})(t,e,n?.log);if(o.length?i.customWidgets=o:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await S(x(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},Zy=async e=>{try{return await y(e,v.F_OK),!0}catch{return!1}};let Xy=null,Qy=null;const ev=()=>Xy||Wy,tv=()=>Qy||Gy;let nv=null;const rv={setGlobalUserId:e=>nv?.setGlobalUserId?.(e),captureError:e=>nv?.captureError?.(e),flushMessages:async()=>nv?.flushMessages?.(),isEnabled:()=>!!nv};var iv={...rv,setTracker:e=>{nv=e}};const ov=xd("servicesManager"),sv={};let av=null,cv=null,lv=null,uv=!1;class dv extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const hv=async e=>{try{return await y(e),!0}catch{return!1}},fv=async e=>{if(!av)throw new Error('IPC config not set, call "setHubIpcConfig" first.');let t;if(e.info.internal)if("linux"===A()){const n=process.env.XDG_STATE_HOME||I.join(T(),".local","state");t=I.join(n,"kemu-hub","service-logs",e.info.name);try{await m(t,{recursive:!0})}catch(n){ov(`Failed to create log directory ${t}, falling back to service path`),t=e.info.path}}else t=e.info.path;else t=I.join(e.info.path,"..");const n=e.logsEnabled?((e,t)=>{const n=my.createLogger({level:"info",format:my.format.combine(my.format.timestamp(),my.format.errors({stack:!0}),my.format.json()),defaultMeta:{service:e},transports:[new Ly({filename:I.join(t,"service-%DATE%.log"),datePattern:"YYYY-MM-DD",maxSize:"5m",maxFiles:"5d",auditFile:I.join(t,".service-log-audit.json")})]});return n.getLastLogs=async(n=100)=>{try{const r=I.join(t,".service-log-audit.json"),i=await g.readFile(r,"utf-8"),o=qu(i);if(!o)return console.warn(`Missing audit file for ${e}, skipping log retrieval.`),[];const s=async e=>(await g.readFile(e,"utf-8")).split("\n").filter((e=>e.trim())),a=[],c=[...o.files].reverse();for(const e of c){const t=await s(e.name);if(a.push(...t),a.length>=n)break}return a}catch(t){return console.warn(`Failed to read service logs for ${e}: `,t),[]}},n})(e.info.name,t):null,r=t=>{if(!e.devMode){const{childProcess:r,...i}=e;iv.isEnabled()&&iv.captureError({error:t,data:{logs:n?.getLastLogs(),service:{...i,spawnargs:r?.spawnargs,info:void 0,name:e.info.name,version:e.info.version}}})}};try{if(e.info.processor===Lu.Javascript){ov(`Spawning service ${e.info.name} with sessionId ${e.info.sessionId}`);const t=I.join(e.info.path,"processor.js"),i=I.join(e.info.path,"processor.mjs"),o=await hv(t)?t:i,s=[`--sessionId=${e.info.sessionId.toString()}`,`--ipcSpace=${av.appSpace}`,`--ipcId=${av?.id}`,`--recipePath=${av.recipePath||""}`];if(e.info.internal&&s.push("--internal=true"),!lv)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const a=await lv({name:e.info.name,version:e.info.version,requiredSecrets:e.info.requiredSecrets||{}}),c=Object.entries(e.info.requiredSecrets||{}).filter((([e,t])=>null==a[e]&&!t.optional)).map((([e])=>e));if(c?.length)throw new dv(`Missing required environment variables: ${c.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,i)=>{if(!cv)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const c=cv({args:[o,...s],serviceInfo:{name:e.info.name,version:e.info.version},options:{env:{...a}}});c.stdout.on("data",(t=>{const r=t.toString().trim();r&&(n?.info(r),ov(`[${e.info.name}] - stdout: ${r}`))})),c.stderr.on("data",(t=>{const i=t.toString().trim();i&&(n?.error(i),r(new Error(i)),ov(`[${e.info.name}] - stderr: ${i}`))})),c.on("exit",(t=>{const r=`exited with code ${t}`;n?.info(r,{code:t}),ov(`[${e.info.name}] ${r}`)})),c.on("spawn",(()=>{const r=`spawned with PID ${c.pid}`;n?.info(r,{pid:c.pid}),ov(`[${e.info.name}] ${r}`),t(c)})),c.on("error",(t=>{n?.error(`[${e.info.name}] error`,t),ov(`[${e.info.name}] error: ${t}`),r(t),i(new dv(`Error spawning service ${e.info.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.info.processor}`}catch(t){if(r(t),t instanceof dv)throw t;throw`Error spawning service ${e.info.name}: ${t}`}},pv=e=>e?.name?e?.version?e?.description?e?.processor?[Lu.Javascript,Lu.Executable,Lu.Python].includes(e?.processor)?null:"Invalid processor":"Missing processor":"Missing description":"Missing version":"Missing name",gv=async(e,t)=>{const n=I.join(e,"manifest.json");if(!await hv(n)){const t=`Missing manifest for service ${e}. Aborting.`;return ov(t),{error:t}}const r=await S(n,"utf-8"),i=qu(r),o=pv(i);if(!i||o){const t=`Invalid service manifest [${e}]: ${o}. Aborting.`;return ov(t),{error:t}}let s;if(delete i.internal,t?.singleServiceName&&i.name!==t.singleServiceName)return{error:`Skipping service ${i.name} as it does not match the singleServiceName option`};await Promise.all([(async()=>{if(i.widgetUI)try{s=await S(I.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return ov(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await qy(I.join(e,i.svgIcon));if(!t)return{error:`Error loading icon for service ${i.name}`};i.svgIcon=t}})(),(async()=>{if(i.subServices?.length)for(const t of i.subServices){const n=I.join(e,t),{error:r,service:o}=await gv(n);r?ov(`Error loading sub-service ${t}: ${r}`):o&&(o.info.parentService={name:i.name,version:i.version})}delete i.subServices})(),(async()=>{if(i.variants?.length)for(const t of i.variants)if(t.svgIcon)try{const n=await S(I.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){ov(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=By(),c=t?.fixedSession||a;ov(`Loaded service ${i.name} with sessionId ${c}`);const l=await Jy(i,e,{widgetUIContents:s});return mv(l),sv[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null,logsEnabled:t?.logsEnabled},{service:sv[c]}},mv=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=h("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},yv=async e=>{try{return e.childProcess=await fv(e),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return ov(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof dv?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},vv=e=>{const{path:t,...n}=e.info;return{...n}},bv=()=>Object.values(sv).filter((e=>"running"===e.status)).map(vv),wv=e=>{if(!e?.kill)return ov(`Failed to kill service ${e?.pid} because it is not a child process`),!1;let t=e.kill("SIGINT");return t||(ov(`Failed to send SIGINT to service ${e.pid} using SIGINT`),t=e.kill("SIGTERM"),t||(ov(`Failed to send SIGTERM to service ${e.pid} using SIGTERM`),t=e.kill("SIGKILL"),t||ov(`Failed to send SIGKILL to service ${e.pid} using SIGKILL`))),t},Sv=async e=>{const{serviceName:t,version:n,force:r,timeout:i=15e3}=e,o=Object.values(sv).find((t=>t.info.name===e.serviceName&&t.info.version===e.version));if(!o)return null;if(o.info.internal&&!r)throw`Cannot stop internal service ${t}`;if(o.childProcess){ov(`Stopping service "${t} (v${n})"`);const r=new Promise(((e,n)=>{const r=setTimeout((()=>{n(new Error(`Timeout waiting for service ${t} to stop after ${i}ms`))}),i);o.childProcess.once("exit",((n,i)=>{clearTimeout(r),ov(`Service ${t} process exited with code ${n} and signal ${i}`),e()})),o.childProcess.once("error",(n=>{clearTimeout(r),ov(`Service ${t} process error: ${n.message}`),e()}))}));wv(o.childProcess);try{await r,ov(`Service ${t} process successfully terminated`)}catch(e){ov(`Warning: ${e instanceof Error?e.message:"Unknown error"} while waiting for service ${t} to stop`)}}return o.status="stopped",ov(`Service ${t} stopped`),o},_v=e=>e.info.internal?e.info.path:I.join(e.info.path,".."),Iv=e=>!!e.internal;var xv={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await Zy(e))return void ov(`Failed to load services from "${e}". Directory does not exist.`);const n=(await b(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));ov(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],o=I.join(e,i),{error:s,service:a}=await gv(`${o}${t?.internalServices?"":"/dist"}`,{...t,logsEnabled:Array.isArray(t?.enableLogs)?t?.enableLogs.includes(i):t?.enableLogs});s&&ov(`Failed to load service ${o}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(ov("Initializing services"),!av)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in sv){const n=sv[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?ov(`Service ${n.info.name} is in the noSpawningList. Skipping.`):yv(n)}ov("Services initialized")},setServiceStatus:(e,t)=>{const n=sv[e];return n?(n.status=t,!0):(ov(`Service with serviceId ${e} not found`),!1)},getActiveServices:bv,getMatchingService:(e,t)=>{const n=Object.values(sv).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(nd(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>sv[e]||null,killAllServices:()=>{for(const e in sv){const t=sv[e];if(t.childProcess)try{ov(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),wv(t.childProcess)}catch(e){ov(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await Jy(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};sv[e]=r,mv(sv[e].info)},setServiceManifest:(e,t,n)=>{const r=sv[e];if(!r)return ov(`Service with sessionId ${e} not found`),!1;const i=pv(t);if(i)return ov(`Invalid manifest for service ${r.info.name}: ${i}`),!1;mv(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(sv).filter((e=>e.devMode));for(const i of r)if(i.info.name===e&&i.status===n&&i.info.version===t)return i;return null},getInternalServices:()=>bv().filter((e=>e.internal)),getAllServices:()=>Object.values(sv),stopService:Sv,uninstallService:async(e,t)=>{ov(`Uninstalling service ${e} v${t}`);const n=await Sv({serviceName:e,version:t});if(!n)return!1;ov(`Service ${e} stopped. Removing from disk...`);const r=_v(n),i=ev();return r.startsWith(i)?(await w(r,{recursive:!0,force:!0,maxRetries:3}),ov(`Service ${e} successfully removed from disk`),(e=>{sv[e],delete sv[e]})(n.info.sessionId),!0):(ov(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(sv).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{av={...e}},setEnableServiceLogsConfig:e=>{uv=e},loadAndLaunch:async(e,t,n)=>{const r=E(e,t),{error:i,service:o}=await gv(r,{logsEnabled:uv});if(i||!o)return{errorMsg:i};try{o.info.internal=!!n,o.childProcess=await fv(o),o.status="started"}catch(e){o.status="error",e instanceof dv?(ov(`Service spawning error: ${e.message} (${e.code})`),o.errorMsg=e.message,o.errorCode=e.code):(ov(`Error launching service ${o.info.name}: ${e}`),o.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:o,errorCode:o.errorCode,errorMsg:o.errorMsg}},getServiceRootDirectory:_v,setSpawnNodeFunction:e=>{cv=e},setGetSecretsFunction:e=>{lv=e},restartService:async(e,t)=>{ov(`Restarting service ${e} v${t}`);const n=await Sv({serviceName:e,version:t,force:!0});return!!n&&yv(n)},getFailedServices:()=>Object.values(sv).filter((e=>"error"===e.status)).map((e=>({...vv(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Iv,isNotInternalKemuService:e=>!Iv(e),isNotDevService:e=>!e.devMode};class kv{constructor(){}appspace="app.";socketRoot="/tmp/";id=N.hostname();encoding="utf8";rawBuffer=!1;sync=!1;unlink=!0;delimiter="\f";silent=!1;logDepth=5;logInColor=!0;logger=console.log.bind(console);maxConnections=100;retry=500;maxRetries=1/0;stopRetrying=!1;IPType=function(){const e=N.networkInterfaces();let t="";return e&&Array.isArray(e)&&e.length>0&&(t=e[Object.keys(e)[0]][0].family),t}();tls=!1;networkHost="IPv6"==this.IPType?"::1":"127.0.0.1";networkPort=8e3;readableAll=!1;writableAll=!1;interface={localAddress:!1,localPort:!1,family:!1,hints:!1,lookup:!1}}class Ev{constructor(e){e||(e=new kv),this.delimiter=e.delimiter}format(e){return e.data||!1===e.data||0===e.data||(e.data={}),e.data._maxListeners&&(e.data={}),e.JSON+this.delimiter}parse(e){let t=e.split(this.delimiter);return t.pop(),t}}var Cv=ad((function(){Object.defineProperties(this,{data:{enumerable:!0,get:function(){return t},set:function(e){t=e}},type:{enumerable:!0,get:function(){return e},set:function(t){e=t}},load:{enumerable:!0,writable:!1,value:function(n){try{n=JSON.parse(n),e=n.type,t=n.data}catch(r){e="error",t={message:"Invalid JSON response format",err:r,response:n}}}},JSON:{enumerable:!0,get:function(){return JSON.stringify({type:e,data:t})}}});var e="",t={}})),$v=ad((function(){Object.defineProperties(this,{add:{enumerable:!0,writable:!1,value:function(){for(var n in arguments)e.push(arguments[n]);t||this.stop||!this.autoRun||this.next()}},next:{enumerable:!0,writable:!1,value:function(){t=!0,e.length<1||this.stop?t=!1:e.shift().bind(this)()}},clear:{enumerable:!0,writable:!1,value:function(){return e=[]}},contents:{enumerable:!1,get:function(){return e},set:function(t){return e=t}},autoRun:{enumerable:!0,writable:!0,value:!0},stop:{enumerable:!0,writable:!0,value:!1}});var e=[],t=!1}));class Ov{}class Nv{}const Tv=new class{constructor(e=!0){this.strict=e}throw(e,t){let n=new TypeError;if(n.message=`expected type of ${e} to be ${t}`,!this.strict)return!1;throw n}typeCheck(e,t){return typeof e===t||this.throw(typeof e,t)}instanceCheck(e=new Ov,t=Nv){return e instanceof t||this.throw(typeof e,t.name)}symbolStringCheck(e,t){return Object.prototype.toString.call(e)==`[object ${t}]`||this.throw(Object.prototype.toString.call(e),`[object ${t}]`)}compare(e,t,n){return e==t||this.throw(typeof e,n)}finite(e){return!!isFinite(e)||this.throw(typeof e,"finite")}NaN(e){return this.number(e)?!!isNaN(e)||this.throw(typeof e,"NaN"):this.number(e)}null(e){return this.compare(e,null,"null")}array(e){return this.instanceCheck(e,Array)}boolean(e){return this.typeCheck(e,"boolean")}bigint(e){return this.typeCheck(e,"bigint")}date(e){return this.instanceCheck(e,Date)}generator(e){return this.symbolStringCheck(e,"Generator")}asyncGenerator(e){return this.symbolStringCheck(e,"AsyncGenerator")}globalThis(e){return this.compare(e,globalThis,"explicitly globalThis, not window, global nor self")}infinity(e){return this.compare(e,1/0,"Infinity")}map(e){return this.instanceCheck(e,Map)}weakMap(e){return this.instanceCheck(e,WeakMap)}number(e){return this.typeCheck(e,"number")}object(e){return this.typeCheck(e,"object")}promise(e){return this.instanceCheck(e,Promise)}regExp(e){return this.instanceCheck(e,RegExp)}undefined(e){return this.typeCheck(e,"undefined")}set(e){return this.instanceCheck(e,Set)}weakSet(e){return this.instanceCheck(e,WeakSet)}string(e){return this.typeCheck(e,"string")}symbol(e){return this.typeCheck(e,"symbol")}function(e){return this.typeCheck(e,"function")}asyncFunction(e){return this.symbolStringCheck(e,"AsyncFunction")}generatorFunction(e){return this.symbolStringCheck(e,"GeneratorFunction")}asyncGeneratorFunction(e){return this.symbolStringCheck(e,"AsyncGeneratorFunction")}error(e){return this.instanceCheck(e,Error)}evalError(e){return this.instanceCheck(e,EvalError)}rangeError(e){return this.instanceCheck(e,RangeError)}referenceError(e){return this.instanceCheck(e,ReferenceError)}syntaxError(e){return this.instanceCheck(e,SyntaxError)}typeError(e){return this.instanceCheck(e,TypeError)}URIError(e){return this.instanceCheck(e,URIError)}bigInt64Array(e){return this.instanceCheck(e,BigInt64Array)}bigUint64Array(e){return this.instanceCheck(e,BigUint64Array)}float32Array(e){return this.instanceCheck(e,Float32Array)}float64Array(e){return this.instanceCheck(e,Float64Array)}int8Array(e){return this.instanceCheck(e,Int8Array)}int16Array(e){return this.instanceCheck(e,Int16Array)}int32Array(e){return this.instanceCheck(e,Int32Array)}uint8Array(e){return this.instanceCheck(e,Uint8Array)}uint8ClampedArray(e){return this.instanceCheck(e,Uint8ClampedArray)}uint16Array(e){return this.instanceCheck(e,Uint16Array)}uint32Array(e){return this.instanceCheck(e,Uint32Array)}arrayBuffer(e){return this.instanceCheck(e,ArrayBuffer)}dataView(e){return this.instanceCheck(e,DataView)}sharedArrayBuffer(e){return this.instanceCheck(e,function(){try{return SharedArrayBuffer}catch{return Ov}}())}intlDateTimeFormat(e){return this.instanceCheck(e,Intl.DateTimeFormat)}intlCollator(e){return this.instanceCheck(e,Intl.Collator)}intlDisplayNames(e){return this.instanceCheck(e,Intl.DisplayNames)}intlListFormat(e){return this.instanceCheck(e,Intl.ListFormat)}intlLocale(e){return this.instanceCheck(e,Intl.Locale)}intlNumberFormat(e){return this.instanceCheck(e,Intl.NumberFormat)}intlPluralRules(e){return this.instanceCheck(e,Intl.PluralRules)}intlRelativeTimeFormat(e){return this.instanceCheck(e,Intl.RelativeTimeFormat)}intlRelativeTimeFormat(e){return this.instanceCheck(e,Intl.RelativeTimeFormat)}finalizationRegistry(e){return this.instanceCheck(e,FinalizationRegistry)}weakRef(e){return this.instanceCheck(e,WeakRef)}};class Av{constructor(){}on(e,t,n=!1){return Tv.string(e),Tv.function(t),Tv.boolean(n),"*"==e&&(e=this.#e),this.#t[e]||(this.#t[e]=[]),t[this.#n]=n,this.#t[e].push(t),this}once(e,t){return this.on(e,t,!0)}off(e="*",t="*"){if(Tv.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Tv.function(t);const n=this.#t[e];for(;n.includes(t);)n.splice(n.indexOf(t),1);return n.length<1&&delete this.#t[e],this}emit(e,...t){Tv.string(e);const n=this.#t[this.#e]||[];if(this.#r(this.#e.toString(),n,e,...t),!this.#t[e])return this;const r=this.#t[e];return this.#r(e,r,...t),this}reset(){this.off(this.#e.toString());for(let e in this.#t)this.off(e);return this}get list(){return Object.assign({},this.#t)}#r=(e,t,...n)=>{Tv.string(e),Tv.array(t);const r=[];for(let e of t)e(...n),e[this.#n]&&r.push(e);for(let t of r)this.off(e,t)};#e=Symbol.for("event-pubsub-all");#n=Symbol.for("event-pubsub-once");#t={}}let Mv=new Ev;class Pv extends Av{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Mv=new Ev(this.config)}Client=Pv;queue=new $v;socket=!1;connect=Rv;emit=Dv;retriesRemaining=0;explicitlyDisconnected=!1}function Dv(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Cv;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Mv.format(n),this.config.sync?this.queue.add(jv.bind(this,n)):this.socket.write(n)}function jv(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Rv(){let e=this;if(e.log("requested connection to ",e.id,e.path),!this.path)return void e.log("\n\n######\nerror: ",e.id," client has not specified socket path it wishes to connect to.");const t={};if(e.port)if(t.host=e.path,t.port=e.port,e.config.interface.localAddress&&(t.localAddress=e.config.interface.localAddress),e.config.interface.localPort&&(t.localPort=e.config.interface.localPort),e.config.interface.family&&(t.family=e.config.interface.family),e.config.interface.hints&&(t.hints=e.config.interface.hints),e.config.interface.lookup&&(t.lookup=e.config.interface.lookup),e.config.tls){if(e.log("Connecting client via TLS to",e.path,e.port,e.config.tls),e.config.tls.private&&(e.config.tls.key=$.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=$.readFileSync(e.config.tls.public)),e.config.tls.trustedConnections){"string"==typeof e.config.tls.trustedConnections&&(e.config.tls.trustedConnections=[e.config.tls.trustedConnections]),e.config.tls.ca=[];for(let t=0;t<e.config.tls.trustedConnections.length;t++)e.config.tls.ca.push($.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=B.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=U.connect(t);else e.log("Connecting client on Unix Socket :",e.path),t.path=e.path,"win32"!==process.platform||e.path.startsWith("\\\\.\\pipe\\")||(t.path=t.path.replace(/^\//,""),t.path=t.path.replace(/\//g,"-"),t.path=`\\\\.\\pipe\\${t.path}`),e.socket=U.connect(t);e.socket.setEncoding(this.config.encoding),e.socket.on("error",(function(t){e.log("\n\n######\nerror: ",t),e.publish("error",t)})),e.socket.on("connect",(function(){e.publish("connect"),e.retriesRemaining=e.config.maxRetries,e.log("retrying reset")})),e.socket.on("close",(function(){if(e.log("connection closed",e.id,e.path,e.retriesRemaining,"tries remaining of",e.config.maxRetries),e.config.stopRetrying||e.retriesRemaining<1||e.explicitlyDisconnected)return e.publish("disconnect"),e.log(e.config.id,"exceeded connection rety amount of"," or stopRetrying flag set."),e.socket.destroy(),e.publish("destroy"),void(e=void 0);setTimeout(function(){e.explicitlyDisconnected||(e.retriesRemaining--,e.connect())}.bind(null,e),e.config.retry),e.publish("disconnect")})),e.socket.on("data",(function(t){if(e.log("## received events ##"),e.config.rawBuffer){if(e.publish("data",Buffer.from(t,e.config.encoding)),!e.config.sync)return;return void e.queue.next()}if(this.ipcBuffer||(this.ipcBuffer=""),(t=this.ipcBuffer+=t).slice(-1)!=Mv.delimiter||-1==t.indexOf(Mv.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Mv.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Cv;r.load(n[t]),e.log("detected event",r.type,r.data),e.publish(r.type,r.data)}e.config.sync&&e.queue.next()}))}let Lv=new Ev;class Fv extends Av{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Lv=new Ev(this.config),this.on("close",Wv.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Uv;broadcast=Bv;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?$.unlink(this.path,Hv.bind(this)):Hv.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Uv(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Cv;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Lv.format(r),this.udp4||this.udp6)return e.address&&e.port?void this.server.write(r,e):(this.log("Attempting to emit to a single UDP socket without supplying socket address or port. Redispatching event as broadcast to all connected sockets"),void this.broadcast(t,n));e.write(r)}function Bv(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Cv;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Lv.format(n),this.udp4||this.udp6)for(let e=1,t=this.sockets.length;e<t;e++)this.server.write(n,this.sockets[e]);else for(let e=0,t=this.sockets.length;e<t;e++)this.sockets[e].write(n)}function Wv(){for(let e=0,t=this.sockets.length;e<t;e++){let t=this.sockets[e],n=!1;if(!t||!t.readable)return t.id&&(n=t.id),this.log("socket disconnected",n.toString()),t&&t.destroy&&t.destroy(),this.sockets.splice(e,1),void this.publish("socket.disconnected",t,n)}}function Gv(e,t,n){let r=this.udp4||this.udp6?n:e;if(this.config.rawBuffer)return t=Buffer.from(t,this.config.encoding),void this.publish("data",t,r);if(r.ipcBuffer||(r.ipcBuffer=""),(t=r.ipcBuffer+=t).slice(-1)==Lv.delimiter&&-1!=t.indexOf(Lv.delimiter))for(r.ipcBuffer="",t=Lv.parse(t);t.length>0;){let e=new Cv;e.load(t.shift()),e.data&&e.data.id&&(r.id=e.data.id),this.log("received event of : ",e.type,e.data),this.publish(e.type,e.data,r)}else this.log("Messages are large, You may want to consider smaller messages.")}function Vv(e){this.publish("close",e)}function Yv(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",Vv.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",Gv.bind(this,e)),e.on("message",function(t,n){if(!n)return;let r;this.log("Received UDP message from ",n.address,n.port),r=this.config.rawSocket?Buffer.from(t,this.config.encoding):t.toString(),e.emit("data",r,n)}.bind(this)),this.publish("connect",e),this.config.rawBuffer}function Hv(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=W.createSocket(this.udp4?"udp4":"udp6"),this.server.write=qv.bind(this),this.server.on("listening",function(){Yv.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?zv.bind(this)():this.server=U.createServer(Yv.bind(this))),this.server.on("error",function(e){this.log("server error",e),this.publish("error",e)}.bind(this)),this.server.maxConnections=this.config.maxConnections,this.port?this.udp4||this.udp6?(this.log("starting server as",this.udp4?"udp4":"udp6"),this.server.bind(this.port,this.path),void this.onStart({address:this.path,port:this.port})):(this.log("starting server as",this.config.tls?"TLS":"TCP"),void this.server.listen(this.port,this.path,this.onStart.bind(this))):(this.log("starting server as","Unix || Windows Socket"),"win32"===process.platform&&(this.path=this.path.replace(/^\//,""),this.path=this.path.replace(/\//g,"-"),this.path=`\\\\.\\pipe\\${this.path}`),void this.server.listen({path:this.path,readableAll:this.config.readableAll,writableAll:this.config.writableAll},this.onStart.bind(this)))}function zv(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=$.readFileSync(this.config.tls.private):this.config.tls.key=$.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=$.readFileSync(this.config.tls.public):this.config.tls.cert=$.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=$.readFileSync(this.config.tls.dhparam)),this.config.tls.trustedConnections){"string"==typeof this.config.tls.trustedConnections&&(this.config.tls.trustedConnections=[this.config.tls.trustedConnections]),this.config.tls.ca=[];for(let e=0;e<this.config.tls.trustedConnections.length;e++)this.config.tls.ca.push($.readFileSync(this.config.tls.trustedConnections[e]))}this.server=B.createServer(this.config.tls,Yv.bind(this))}function qv(e,t){let n=Buffer.from(e,this.config.encoding);this.server.send(n,0,n.length,t.port,t.address,(function(e){e&&(this.log("error writing data to socket",e),this.publish("error",(function(e){this.publish("error",e)})))}))}class Kv{constructor(){}config=new kv;of={};server=!1;get connectTo(){return tb}get connectToNet(){return nb}get disconnect(){return Zv}get serve(){return Xv}get serveNet(){return eb}get log(){return Jv}set connectTo(e){return tb}set connectToNet(e){return nb}set disconnect(e){return Zv}set serve(e){return Xv}set serveNet(e){return eb}set log(e){return Jv}}function Jv(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=i.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function Zv(e){this.of[e]&&(this.of[e].explicitlyDisconnected=!0,this.of[e].off("*","*"),this.of[e].socket&&this.of[e].socket.destroy&&this.of[e].socket.destroy(),delete this.of[e])}function Xv(e,t){"function"==typeof e&&(t=e,e=!1),e||(this.log("Server path not specified, so defaulting to","ipc.config.socketRoot + ipc.config.appspace + ipc.config.id",this.config.socketRoot+this.config.appspace+this.config.id),e=this.config.socketRoot+this.config.appspace+this.config.id),t||(t=Qv),this.server=new Fv(e,this.config,Jv),this.server.on("start",t)}function Qv(){}function eb(e,t,n,r){"number"==typeof e&&(r=n,n=t,t=e,e=!1),"function"==typeof e&&(r=e,n=!1,e=!1,t=!1),e||(this.log("Server host not specified, so defaulting to","ipc.config.networkHost",this.config.networkHost),e=this.config.networkHost),"udp4"!=e.toLowerCase()&&"udp6"!=e.toLowerCase()||(r=t,n=e.toLowerCase(),t=!1,e=this.config.networkHost),"string"==typeof t&&(r=n,n=t,t=!1),"function"==typeof t&&(r=t,n=!1,t=!1),t||(this.log("Server port not specified, so defaulting to","ipc.config.networkPort",this.config.networkPort),t=this.config.networkPort),"function"==typeof n&&(r=n,n=!1),r||(r=Qv),this.server=new Fv(e,this.config,Jv,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function tb(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=Qv),e){if(t||(this.log("Service path not specified, so defaulting to","ipc.config.socketRoot + ipc.config.appspace + id",(this.config.socketRoot+this.config.appspace+e).data),t=this.config.socketRoot+this.config.appspace+e),this.of[e]){if(!this.of[e].socket.destroyed)return this.log("Already Connected to",e,"- So executing success without connection"),void n();this.of[e].socket.destroy()}this.of[e]=new Pv(this.config,this.log),this.of[e].id=e,this.of[e].socket&&(this.of[e].socket.id=e),this.of[e].path=t,this.of[e].connect(),n(this)}else this.log("Service id required","Requested service connection without specifying service id. Aborting connection attempt")}function nb(e,t,n,r){if(e){if("number"==typeof t&&(r=n,n=t,t=!1),"function"==typeof t&&(r=t,t=!1,n=!1),t||(this.log("Server host not specified, so defaulting to","ipc.config.networkHost",this.config.networkHost),t=this.config.networkHost),"function"==typeof n&&(r=n,n=!1),n||(this.log("Server port not specified, so defaulting to","ipc.config.networkPort",this.config.networkPort),n=this.config.networkPort),"string"==typeof r&&(UDPType=r,r=!1),r||(r=Qv),this.of[e]){if(!this.of[e].socket.destroyed)return this.log("Already Connected to",e,"- So executing success without connection"),void r();this.of[e].socket.destroy()}this.of[e]=new Pv(this.config,this.log),this.of[e].id=e,this.of[e].socket&&(this.of[e].socket.id=e),this.of[e].path=t,this.of[e].port=n,this.of[e].connect(),r(this)}else this.log("Service id required","Requested service connection without specifying service id. Aborting connection attempt")}const rb=new class extends Kv{constructor(){super()}IPC=Kv};const ib=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),ob=e=>{try{return JSON.parse(e)}catch(e){return null}},sb="undefined"!=typeof window,ab={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},cb={protocolPrefix:4,txtLength:4},lb=Object.values(ab).reduce(((e,t)=>e+t),0),ub=Object.values(cb).reduce(((e,t)=>e+t),0),db=["width","height","colorSpace"],hb=(e,t)=>{const n={},r=[];let i=0,o=Array.isArray(e)?[]:{};const s=(e,o)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,o=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":o?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=s(e[n],`${o}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,o=e instanceof Float32Array,s=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":o?"Float32Array":s?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${o}"`);for(const n in e)Object.hasOwn(e,n)||db.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${o}`),t[n]=s(e[n],`${o.length?`${o}.`:""}${n}`);return t}return e}n[o]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};o=s(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else a=Buffer.concat(r);else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:o}:null},fb=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const o=t.startsWith("[")&&t.endsWith("]"),s=e===r.length-1;if(o){t=t.slice(1,-1);const o=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);s?i[o]=n:(i[o]||(i[o]=r[e+1].startsWith("[")?[]:{}),i=i[o])}else s?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},pb=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const o in n)if(Object.hasOwn(n,o)){const{index:s,length:a,binaryType:c}=n[o];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(s,s+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(s,s+a));break;case"Int8Array":l=new Int8Array(t.subarray(s,s+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(s,s+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a):t.slice(s,s+a);break;case"Uint8Array":l=i?t.slice(s,s+a):new Uint8Array(t.slice(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(s,s+a));break;case"Int8Array":l=new Int8Array(t.slice(s,s+a))}l&&fb(e,o,l)}return e},gb=e=>Id(e),mb="KMSG",yb="KCMD",vb=gb("klProtocol");var bb={encode:(e,t,n)=>{const r={json:e.json},i=hb(r.json,"Buffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=ab.protocolPrefix+ab.protocolVersion+ab.jsonLength+ab.binaryLength+ab.fromServiceId+ab.toServiceId+ab.sentAt+l+s,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(mb,f),f+=ab.protocolPrefix,d.writeUInt8(1,f),f+=ab.protocolVersion,d.writeUInt32LE(l,f),f+=ab.jsonLength,d.writeUInt32LE(s,f),f+=ab.binaryLength,d.writeUInt32LE(t,f),f+=ab.fromServiceId,d.writeUInt32LE(n,f),f+=ab.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=ab.sentAt,c.copy(d,f),f+=l,o&&s&&o.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,ab.protocolPrefix);if(t+=ab.protocolPrefix,n!==mb)return null;if(e.byteLength<lb)return vb(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=ab.protocolVersion;const i=e.readUInt32LE(t);t+=ab.jsonLength;const o=e.readUInt32LE(t);t+=ab.binaryLength;const s=e.readUInt32LE(t);t+=ab.fromServiceId;const a=e.readUInt32LE(t);t+=ab.toServiceId;const c=e.readBigInt64LE(t);t+=ab.sentAt;const l=i+o,u=e.subarray(t,t+l),d=e.subarray(0,lb);let h=null;return e.byteLength-lb-i-o>0&&(h=e.subarray(lb+i+o)),{header:{protocolVersion:r,jsonLength:i,binaryLength:o,fromServiceId:s,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:h}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),i=ob(n);if(!i?.json)return vb("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&pb(i.json,r,i.jsonBinaryMap);const o=Buffer.concat([e.headerPackage,t]);let s=o,a=null;const c=lb+e.jsonLength+e.binaryLength;return o.byteLength>c&&(a=o.subarray(c),s=o.subarray(0,c)),{message:{json:i.json,rawMessage:s},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<lb)return vb("Invalid Header Size"),e;let n=0;return n+=ab.protocolPrefix,n+=ab.protocolVersion,n+=ab.jsonLength,n+=ab.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=ab.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,i=ub+r,o=Buffer.alloc(i);return o.write(yb,t),t+=cb.protocolPrefix,o.writeUint32LE(r,t),t+=cb.txtLength,n.copy(o,t),o},decodeCommand:e=>{let t=0;if(e.byteLength<ub)return{command:null};const n=e.toString("utf-8",t,cb.protocolPrefix);if(t+=cb.protocolPrefix,n!==yb)return{command:null};const r=e.readUInt32LE(t);t+=cb.txtLength;const i=e.toString("utf-8",t,t+r),o=e.byteLength-ub-r;let s=null;o>0&&(s=e.subarray(ub+r));let a=0;return o<0&&(a=Math.abs(o)),{command:i,remainingData:s,missing:a}}};const wb="KMSG",Sb="KCMD",_b=gb("klProtocol"),Ib=new TextEncoder;var xb={encode:(e,t,n)=>{const r={json:e.json},i=hb(e.json,"ArrayBuffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Ib.encode(a),l=c.byteLength,u=new ArrayBuffer(ab.protocolPrefix+ab.protocolVersion+ab.jsonLength+ab.binaryLength+ab.fromServiceId+ab.toServiceId+ab.sentAt+l+s),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=wb.charCodeAt(e);return d.setUint8(p,1),p+=ab.protocolVersion,d.setUint32(p,l,!0),p+=ab.jsonLength,d.setUint32(p,s,!0),p+=ab.binaryLength,d.setUint32(p,t,!0),p+=ab.fromServiceId,d.setUint32(p,n,!0),p+=ab.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=ab.sentAt,h.set(c,p),p+=l,o&&s&&h.set(new Uint8Array(o),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<ab.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==wb)return null;if(e.byteLength<lb)return _b.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=ab.protocolVersion;const o=t.getUint32(n,!0);n+=ab.jsonLength;const s=t.getUint32(n,!0);n+=ab.binaryLength;const a=t.getUint32(n,!0);n+=ab.fromServiceId;const c=t.getUint32(n,!0);n+=ab.toServiceId;const l=t.getBigInt64(n,!0);n+=ab.sentAt;const u=o+s,d=e.slice(n,n+u),h=new Uint8Array(e,0,lb);let f=null;return e.byteLength-lb-o-s>0&&(f=new Uint8Array(e,lb+o+s).slice().buffer),{header:{protocolVersion:i,jsonLength:o,binaryLength:s,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:h.slice().buffer},remaining:f}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const o=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),s=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=ob(o);if(!a?.json)return _b.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&s.byteLength&&pb(a.json,s,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=lb+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...s.length?{binaryData:s.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<lb)return _b("Invalid Header Size"),e;let n=0;n+=ab.protocolPrefix,n+=ab.protocolVersion,n+=ab.jsonLength,n+=ab.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=ab.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Ib.encode(e),r=n.byteLength,i=new ArrayBuffer(ub+r),o=new DataView(i),s=new Uint8Array(i);for(let e=0;e<4;++e)s[t++]=Sb.charCodeAt(e);return o.setUint32(t,r,!0),t+=cb.txtLength,s.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<ub)return{command:null};let r="";for(let e=0;e<cb.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Sb)return{command:null};const i=t.getUint32(n,!0);n+=cb.txtLength;const o=e.byteLength-ub-i,s=new Uint8Array(e,n,Math.min(i,e.byteLength-ub)),a=(new TextDecoder).decode(s);let c=null;o>0&&(c=e.slice(ub+i));let l=0;return o<0&&(l=Math.abs(o)),{command:a,remainingData:c,missing:l}}};const kb=gb("klTransmissionManager"),Eb=()=>{const e=(t,n,r,i)=>{let o=n,s=null;const a=t instanceof ArrayBuffer;if(kb(`RAW: ${t.toString()}`),!o||o.partialHeaderData){let c;if(a?(c=o?.partialHeaderData?new Uint8Array([...new Uint8Array(o.partialHeaderData),...new Uint8Array(t)]).buffer:t,s=xb.decodeHeader(c)):(c=o?.partialHeaderData?Buffer.concat([o.partialHeaderData,t]):t,s=bb.decodeHeader(c)),!s){const{command:t,missing:o,remainingData:s}=a?xb.decodeCommand(c):bb.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):kb(o?`ERROR: Missing ${o} bytes to complete the command. This partial command will be aborted.`:`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`),s?(kb(`${s.byteLength} bytes remain after processing command. Re-analyzing...`),e(s,n,r,i)):void 0}if(s.partialHeader)return o={firstPackageAt:Date.now(),partialHeaderData:c},r(o);if(!s.header)return kb(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=s.header;o={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:s.remaining}},r(o)}else o.header&&o.header.totalBytesReceived<o.header.totalBytesExpected&&(o.header.packages.push(t),o.header.totalBytesReceived+=t.byteLength,r(o));if(o.header&&o.header.totalBytesReceived>=o.header.totalBytesExpected){const t=Date.now()-o.header.sentAt.getTime(),n=Date.now()-o.firstPackageAt;kb(`Received ${o.header.totalBytesReceived} of ${o.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const s=a?xb.decodeFullKlMessage(o.header):bb.decodeFullKlMessage(o.header),c=o.header.totalBytesReceived,l=o.header.remaining;r(null),s&&i({klMessage:s.message,complete:!0,sourceServiceId:o.header.fromServiceId,targetServiceId:o.header.toServiceId,rawMessage:s.message.rawMessage});let u=l;if(s?.remaining&&(u=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),o=new Uint8Array(t),s=new Uint8Array(r);return s.set(i),s.set(o,i.length),r})(l,s.remaining):s.remaining:l?Buffer.concat([l,s.remaining]):s.remaining),u)return kb(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,i)}};return e};rb.config={...rb.config,id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const Cb={info:xd("ipcServer:info"),data:xd("ipcServer:data")};let $b,Ob,Nb,Tb,Ab={};const Mb=Eb(),Pb=e=>{Ab[e]&&(Cb.info(`Client disconnected [${e}]`),delete Ab[e],Ob&&Ob(e))};var Db=(e,t)=>{const n=Ab[e];if(!n)return Cb.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=ib)return Cb.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=bb.encodeCommand(t);return n.socket.write(r),!0},jb=(e,t)=>{const n=Ab[e];return!!n&&(Cb.info(`Renaming socket id [${e}] to [${t}]`),delete Ab[e],n.socket.id=t,Ab[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Pb(t),n.socket.on("close",n.disconnectHandler),!0)};let Rb=bb;sb&&(Rb=xb);var Lb,Fb=Rb;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Lb||(Lb={}));let Ub=Math.ceil(Date.now()/1e3);var Bb={exports:{}};const Wb=["nodebuffer","arraybuffer","fragments"],Gb="undefined"!=typeof Blob;Gb&&Wb.push("blob");var Vb={BINARY_TYPES:Wb,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Gb,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:Yb}=Vb,Hb=Buffer[Symbol.species];function zb(e,t,n,r,i){for(let o=0;o<i;o++)n[r+o]=e[o]^t[3&o]}function qb(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(Bb.exports={concat:function(e,t){if(0===e.length)return Yb;if(1===e.length)return e[0];const n=Buffer.allocUnsafe(t);let r=0;for(let t=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return r<t?new Hb(n.buffer,n.byteOffset,r):n},mask:zb,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let n;return t instanceof ArrayBuffer?n=new Hb(t):ArrayBuffer.isView(t)?n=new Hb(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:qb},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Bb.exports.mask=function(t,n,r,i,o){o<48?zb(t,n,r,i,o):e.mask(t,n,r,i,o)},Bb.exports.unmask=function(t,n){t.length<32?qb(t,n):e.unmask(t,n)}}catch(I){}var Kb=Bb.exports;const Jb=Symbol("kDone"),Zb=Symbol("kRun"),Xb=j,Qb=Kb,ew=class{constructor(e){this[Jb]=()=>{this.pending--,this[Zb]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Zb]()}[Zb](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Jb])}}},{kStatusCode:tw}=Vb,nw=Buffer[Symbol.species],rw=Buffer.from([0,0,255,255]),iw=Symbol("permessage-deflate"),ow=Symbol("total-length"),sw=Symbol("callback"),aw=Symbol("buffers"),cw=Symbol("error");let lw;var uw=class{constructor(e,t,n){if(this._maxPayload=0|n,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!lw){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;lw=new ew(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[sw];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,n=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(n.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?n.client_max_window_bits=t.clientMaxWindowBits:!0!==n.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete n.client_max_window_bits,n}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let n=e[t];if(n.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(n=n[0],"client_max_window_bits"===t){if(!0!==n){const e=+n;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${n}`)}else if("server_max_window_bits"===t){const e=+n;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==n)throw new TypeError(`Invalid value for parameter "${t}": ${n}`)}e[t]=n}))})),e}decompress(e,t,n){lw.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){lw.add((r=>{this._compress(e,t,((e,t)=>{r(),n(e,t)}))}))}_decompress(e,t,n){const r=this._isServer?"client":"server";if(!this._inflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?Xb.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Xb.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[iw]=this,this._inflate[ow]=0,this._inflate[aw]=[],this._inflate.on("error",fw),this._inflate.on("data",hw)}this._inflate[sw]=n,this._inflate.write(e),t&&this._inflate.write(rw),this._inflate.flush((()=>{const e=this._inflate[cw];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=Qb.concat(this._inflate[aw],this._inflate[ow]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ow]=0,this._inflate[aw]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),n(null,i)}))}_compress(e,t,n){const r=this._isServer?"server":"client";if(!this._deflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?Xb.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Xb.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[ow]=0,this._deflate[aw]=[],this._deflate.on("data",dw)}this._deflate[sw]=n,this._deflate.write(e),this._deflate.flush(Xb.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Qb.concat(this._deflate[aw],this._deflate[ow]);t&&(e=new nw(e.buffer,e.byteOffset,e.length-4)),this._deflate[sw]=null,this._deflate[ow]=0,this._deflate[aw]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function dw(e){this[aw].push(e),this[ow]+=e.length}function hw(e){this[ow]+=e.length,this[iw]._maxPayload<1||this[ow]<=this[iw]._maxPayload?this[aw].push(e):(this[cw]=new RangeError("Max payload size exceeded"),this[cw].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[cw][tw]=1009,this.removeListener("data",hw),this.reset())}function fw(e){this[iw]._inflate=null,e[tw]=1007,this[sw](e)}var pw={exports:{}};const{isUtf8:gw}=P,{hasBlob:mw}=Vb;function yw(e){const t=e.length;let n=0;for(;n<t;)if(128&e[n])if(192==(224&e[n])){if(n+1===t||128!=(192&e[n+1])||192==(254&e[n]))return!1;n+=2}else if(224==(240&e[n])){if(n+2>=t||128!=(192&e[n+1])||128!=(192&e[n+2])||224===e[n]&&128==(224&e[n+1])||237===e[n]&&160==(224&e[n+1]))return!1;n+=3}else{if(240!=(248&e[n]))return!1;if(n+3>=t||128!=(192&e[n+1])||128!=(192&e[n+2])||128!=(192&e[n+3])||240===e[n]&&128==(240&e[n+1])||244===e[n]&&e[n+1]>143||e[n]>244)return!1;n+=4}else n++;return!0}if(pw.exports={isBlob:function(e){return mw&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:yw,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},gw)pw.exports.isValidUTF8=function(e){return e.length<24?yw(e):gw(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");pw.exports.isValidUTF8=function(t){return t.length<32?yw(t):e(t)}}catch(I){}var vw=pw.exports;const{Writable:bw}=M,ww=uw,{BINARY_TYPES:Sw,EMPTY_BUFFER:_w,kStatusCode:Iw,kWebSocket:xw}=Vb,{concat:kw,toArrayBuffer:Ew,unmask:Cw}=Kb,{isValidStatusCode:$w,isValidUTF8:Ow}=vw,Nw=Buffer[Symbol.species];const{randomFillSync:Tw}=l,Aw=uw,{EMPTY_BUFFER:Mw,kWebSocket:Pw,NOOP:Dw}=Vb,{isBlob:jw,isValidStatusCode:Rw}=vw,{mask:Lw,toBuffer:Fw}=Kb,Uw=Symbol("kByteLength"),Bw=Buffer.alloc(4),Ww=8192;let Gw,Vw=Ww;function Yw(e,t,n){"function"==typeof n&&n(t);for(let n=0;n<e._queue.length;n++){const r=e._queue[n],i=r[r.length-1];"function"==typeof i&&i(t)}}function Hw(e,t,n){Yw(e,t,n),e.onerror(t)}const{kForOnEventAttribute:zw,kListener:qw}=Vb,Kw=Symbol("kCode"),Jw=Symbol("kData"),Zw=Symbol("kError"),Xw=Symbol("kMessage"),Qw=Symbol("kReason"),eS=Symbol("kTarget"),tS=Symbol("kType"),nS=Symbol("kWasClean");class rS{constructor(e){this[eS]=null,this[tS]=e}get target(){return this[eS]}get type(){return this[tS]}}Object.defineProperty(rS.prototype,"target",{enumerable:!0}),Object.defineProperty(rS.prototype,"type",{enumerable:!0});class iS extends rS{constructor(e,t={}){super(e),this[Kw]=void 0===t.code?0:t.code,this[Qw]=void 0===t.reason?"":t.reason,this[nS]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Kw]}get reason(){return this[Qw]}get wasClean(){return this[nS]}}Object.defineProperty(iS.prototype,"code",{enumerable:!0}),Object.defineProperty(iS.prototype,"reason",{enumerable:!0}),Object.defineProperty(iS.prototype,"wasClean",{enumerable:!0});class oS extends rS{constructor(e,t={}){super(e),this[Zw]=void 0===t.error?null:t.error,this[Xw]=void 0===t.message?"":t.message}get error(){return this[Zw]}get message(){return this[Xw]}}Object.defineProperty(oS.prototype,"error",{enumerable:!0}),Object.defineProperty(oS.prototype,"message",{enumerable:!0});class sS extends rS{constructor(e,t={}){super(e),this[Jw]=void 0===t.data?null:t.data}get data(){return this[Jw]}}Object.defineProperty(sS.prototype,"data",{enumerable:!0});const aS={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[zw]&&r[qw]===t&&!r[zw])return;let r;if("message"===e)r=function(e,n){const r=new sS("message",{data:n?e:e.toString()});r[eS]=this,lS(t,this,r)};else if("close"===e)r=function(e,n){const r=new iS("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[eS]=this,lS(t,this,r)};else if("error"===e)r=function(e){const n=new oS("error",{error:e,message:e.message});n[eS]=this,lS(t,this,n)};else{if("open"!==e)return;r=function(){const e=new rS("open");e[eS]=this,lS(t,this,e)}}r[zw]=!!n[zw],r[qw]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[qw]===t&&!n[zw]){this.removeListener(e,n);break}}};var cS={CloseEvent:iS,ErrorEvent:oS,Event:rS,EventTarget:aS,MessageEvent:sS};function lS(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:uS}=vw;function dS(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var hS={format:function(e){return Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>[t].concat(Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let n,r,i=Object.create(null),o=!1,s=!1,a=!1,c=-1,l=-1,u=-1,d=0;for(;d<e.length;d++)if(l=e.charCodeAt(d),void 0===n)if(-1===u&&1===uS[l])-1===c&&(c=d);else if(0===d||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);const r=e.slice(c,u);44===l?(dS(t,r,i),i=Object.create(null)):n=r,c=u=-1}}else-1===u&&-1!==c&&(u=d);else if(void 0===r)if(-1===u&&1===uS[l])-1===c&&(c=d);else if(32===l||9===l)-1===u&&-1!==c&&(u=d);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d),dS(i,e.slice(c,u),!0),44===l&&(dS(t,n,i),i=Object.create(null),n=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${d}`);r=e.slice(c,d),c=u=-1}else if(s){if(1!==uS[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:o||(o=!0),s=!1}else if(a)if(1===uS[l])-1===c&&(c=d);else if(34===l&&-1!==c)a=!1,u=d;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${d}`);s=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===uS[l])-1===c&&(c=d);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);let s=e.slice(c,u);o&&(s=s.replace(/\\/g,""),o=!1),dS(i,r,s),44===l&&(dS(t,n,i),i=Object.create(null),n=void 0),r=void 0,c=u=-1}}else-1===u&&(u=d);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===u&&(u=d);const h=e.slice(c,u);return void 0===n?dS(t,h,i):(void 0===r?dS(i,h,!0):dS(i,r,o?h.replace(/\\/g,""):h),dS(t,n,i)),t}};const fS=D,pS=F,gS=L,mS=U,yS=B,{randomBytes:vS,createHash:bS}=l,{URL:wS}=G,SS=uw,_S=class extends bw{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Sw[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[xw]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(8===this._opcode&&0==this._state)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Nw(t.buffer,t.byteOffset+e,t.length-e),new Nw(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new Nw(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0])return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));const n=!(64&~t[0]);if(!n||this._extensions[ww.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(n)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=n}else{if(!(this._opcode>7&&this._opcode<11))return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(n)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked)return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),n=t.readUInt32BE(0);n>Math.pow(2,21)-1?e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=_w;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&Cw(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[ww.extensionName].decompress(e,this._fin,((e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(n)}this.dataMessage(t),0===this._state&&this.startLoop(t)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?kw(n,t):"arraybuffer"===this._binaryType?Ew(kw(n,t)):"blob"===this._binaryType?new Blob(n):n,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!0),this._state=0,this.startLoop(e)})))}else{const r=kw(n,t);if(!this._skipUTF8Validation&&!Ow(r)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,_w),this.end();else{const n=e.readUInt16BE(0);if(!$w(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Nw(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ow(r)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",n,r),this.end()}this._state=0}}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;const o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Iw]=r,o}},IS=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=Dw,this[Pw]=void 0}static frame(e,t){let n,r,i=!1,o=2,s=!1;t.mask&&(n=t.maskBuffer||Bw,t.generateMask?t.generateMask(n):(Vw===Ww&&(void 0===Gw&&(Gw=Buffer.alloc(Ww)),Tw(Gw,0,Ww),Vw=0),n[0]=Gw[Vw++],n[1]=Gw[Vw++],n[2]=Gw[Vw++],n[3]=Gw[Vw++]),s=!(n[0]|n[1]|n[2]|n[3]),o=6),"string"==typeof e?r=t.mask&&!s||void 0===t[Uw]?(e=Buffer.from(e)).length:t[Uw]:(r=e.length,i=t.mask&&t.readOnly&&!s);let a=r;r>=65536?(o+=8,a=127):r>125&&(o+=2,a=126);const c=Buffer.allocUnsafe(i?r+o:o);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(r,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(r,4,6)),t.mask?(c[1]|=128,c[o-4]=n[0],c[o-3]=n[1],c[o-2]=n[2],c[o-1]=n[3],s?[c,e]:i?(Lw(e,n,c,o,r),[c]):(Lw(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let o;if(void 0===t)o=Mw;else{if("number"!=typeof t||!Rw(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==n&&n.length){const e=Buffer.byteLength(n);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),"string"==typeof n?o.write(n,2):o.set(n,2)}else o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0)}const s={[Uw]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(e.frame(o,s),i)}ping(t,n,r){let i,o;if("string"==typeof t?(i=Buffer.byteLength(t),o=!1):jw(t)?(i=t.size,o=!1):(i=(t=Fw(t)).length,o=Fw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Uw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};jw(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,s,r]):this.getBlobData(t,!1,s,r):0!==this._state?this.enqueue([this.dispatch,t,!1,s,r]):this.sendFrame(e.frame(t,s),r)}pong(t,n,r){let i,o;if("string"==typeof t?(i=Buffer.byteLength(t),o=!1):jw(t)?(i=t.size,o=!1):(i=(t=Fw(t)).length,o=Fw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Uw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};jw(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,s,r]):this.getBlobData(t,!1,s,r):0!==this._state?this.enqueue([this.dispatch,t,!1,s,r]):this.sendFrame(e.frame(t,s),r)}send(e,t,n){const r=this._extensions[Aw.extensionName];let i,o,s=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),o=!1):jw(e)?(i=e.size,o=!1):(i=(e=Fw(e)).length,o=Fw.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=i>=r._threshold),this._compress=a):(a=!1,s=0),t.fin&&(this._firstFragment=!0);const c={[Uw]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:o,rsv1:a};jw(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):0!==this._state?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(t,n,r,i){this._bufferedBytes+=r[Uw],this._state=2,t.arrayBuffer().then((t=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(Yw,this,e,i)}this._bufferedBytes-=r[Uw];const o=Fw(t);n?this.dispatch(o,n,r,i):(this._state=0,this.sendFrame(e.frame(o,r),i),this.dequeue())})).catch((e=>{process.nextTick(Hw,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const o=this._extensions[Aw.extensionName];this._bufferedBytes+=r[Uw],this._state=1,o.compress(t,r.fin,((t,n)=>{this._socket.destroyed?Yw(this,new Error("The socket was closed while data was being compressed"),i):(this._bufferedBytes-=r[Uw],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue())}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Uw],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Uw],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}},{isBlob:xS}=vw,{BINARY_TYPES:kS,EMPTY_BUFFER:ES,GUID:CS,kForOnEventAttribute:$S,kListener:OS,kStatusCode:NS,kWebSocket:TS,NOOP:AS}=Vb,{EventTarget:{addEventListener:MS,removeEventListener:PS}}=cS,{format:DS,parse:jS}=hS,{toBuffer:RS}=Kb,LS=3e4,FS=Symbol("kAborted"),US=[8,13],BS=["CONNECTING","OPEN","CLOSING","CLOSED"],WS=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let GS=class e extends fS{constructor(t,n,r){super(),this._binaryType=kS[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ES,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==t?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===n?n=[]:Array.isArray(n)||("object"==typeof n&&null!==n?(r=n,n=[]):n=[n]),YS(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){kS.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){const i=new _S({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new IS(t,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=t,i[TS]=this,o[TS]=this,t[TS]=this,i.on("conclude",ZS),i.on("drain",XS),i.on("error",QS),i.on("message",t_),i.on("ping",n_),i.on("pong",r_),o.onerror=o_,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",a_),t.on("data",c_),t.on("end",l_),t.on("error",u_),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=e.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[SS.extensionName]&&this._extensions[SS.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this.readyState!==e.CLOSING?(this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),s_(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";KS(this,this._req,e)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(r=t,t=n=void 0):"function"==typeof n&&(r=n,n=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===n&&(n=!this._isServer),this._sender.ping(t||ES,n,r)):JS(this,t,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(r=t,t=n=void 0):"function"==typeof n&&(r=n,n=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===n&&(n=!this._isServer),this._sender.pong(t||ES,n,r)):JS(this,t,r)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof n&&(r=n,n={}),"number"==typeof t&&(t=t.toString()),this.readyState!==e.OPEN)return void JS(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[SS.extensionName]||(i.compress=!1),this._sender.send(t||ES,i,r)}terminate(){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this._socket&&(this._readyState=e.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";KS(this,this._req,e)}}};Object.defineProperty(GS,"CONNECTING",{enumerable:!0,value:BS.indexOf("CONNECTING")}),Object.defineProperty(GS.prototype,"CONNECTING",{enumerable:!0,value:BS.indexOf("CONNECTING")}),Object.defineProperty(GS,"OPEN",{enumerable:!0,value:BS.indexOf("OPEN")}),Object.defineProperty(GS.prototype,"OPEN",{enumerable:!0,value:BS.indexOf("OPEN")}),Object.defineProperty(GS,"CLOSING",{enumerable:!0,value:BS.indexOf("CLOSING")}),Object.defineProperty(GS.prototype,"CLOSING",{enumerable:!0,value:BS.indexOf("CLOSING")}),Object.defineProperty(GS,"CLOSED",{enumerable:!0,value:BS.indexOf("CLOSED")}),Object.defineProperty(GS.prototype,"CLOSED",{enumerable:!0,value:BS.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(GS.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(GS.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[$S])return t[OS];return null},set(t){for(const t of this.listeners(e))if(t[$S]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[$S]:!0})}})})),GS.prototype.addEventListener=MS,GS.prototype.removeEventListener=PS;var VS=GS;function YS(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:US[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=i.autoPong,!US.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${US.join(", ")})`);let o;if(t instanceof wS)o=t;else try{o=new wS(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===o.protocol?o.protocol="ws:":"https:"===o.protocol&&(o.protocol="wss:"),e._url=o.href;const s="wss:"===o.protocol,a="ws+unix:"===o.protocol;let c;if("ws:"===o.protocol||s||a?a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void HS(e,t)}const l=s?443:80,u=vS(16).toString("base64"),d=s?pS.request:gS.request,h=new Set;let f,p;if(i.createConnection=i.createConnection||(s?qS:zS),i.defaultPort=i.defaultPort||l,i.port=o.port||l,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(f=new SS(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=DS({[SS.extensionName]:f.offer()})),n.length){for(const e of n){if("string"!=typeof e||!WS.test(e)||h.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(e)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=s,e._originalHostOrSocketPath=a?i.socketPath:o.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&o.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=e._req=d(i),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=d(i);i.timeout&&p.on("timeout",(()=>{KS(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[FS]||(p=e._req=null,HS(e,t))})),p.on("response",(o=>{const s=o.headers.location,a=o.statusCode;if(s&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void KS(e,p,"Maximum redirects exceeded");let o;p.abort();try{o=new wS(s,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${s}`);return void HS(e,n)}YS(e,o,n,r)}else e.emit("unexpected-response",p,o)||KS(e,p,`Unexpected server response: ${o.statusCode}`)})),p.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==GS.CONNECTING)return;p=e._req=null;const o=t.headers.upgrade;if(void 0===o||"websocket"!==o.toLowerCase())return void KS(e,n,"Invalid Upgrade header");const s=bS("sha1").update(u+CS).digest("base64");if(t.headers["sec-websocket-accept"]!==s)return void KS(e,n,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?h.size?h.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":h.size&&(c="Server sent no subprotocol"),c)return void KS(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!f)return void KS(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");let r;try{r=jS(l)}catch(t){return void KS(e,n,"Invalid Sec-WebSocket-Extensions header")}const i=Object.keys(r);if(1!==i.length||i[0]!==SS.extensionName)return void KS(e,n,"Server indicated an extension that was not requested");try{f.accept(r[SS.extensionName])}catch(t){return void KS(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[SS.extensionName]=f}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(p,e):p.end()}function HS(e,t){e._readyState=GS.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function zS(e){return e.path=e.socketPath,mS.connect(e)}function qS(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=mS.isIP(e.host)?"":e.host),yS.connect(e)}function KS(e,t,n){e._readyState=GS.CLOSING;const r=new Error(n);Error.captureStackTrace(r,KS),t.setHeader?(t[FS]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(HS,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function JS(e,t,n){if(t){const n=xS(t)?t.size:RS(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${BS[e.readyState]})`);process.nextTick(n,t)}}function ZS(e,t){const n=this[TS];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[TS]&&(n._socket.removeListener("data",c_),process.nextTick(i_,n._socket),1005===e?n.close():n.close(e,t))}function XS(){const e=this[TS];e.isPaused||e._socket.resume()}function QS(e){const t=this[TS];void 0!==t._socket[TS]&&(t._socket.removeListener("data",c_),process.nextTick(i_,t._socket),t.close(e[NS])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function e_(){this[TS].emitClose()}function t_(e,t){this[TS].emit("message",e,t)}function n_(e){const t=this[TS];t._autoPong&&t.pong(e,!this._isServer,AS),t.emit("ping",e)}function r_(e){this[TS].emit("pong",e)}function i_(e){e.resume()}function o_(e){const t=this[TS];t.readyState!==GS.CLOSED&&(t.readyState===GS.OPEN&&(t._readyState=GS.CLOSING,s_(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function s_(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),LS)}function a_(){const e=this[TS];let t;this.removeListener("close",a_),this.removeListener("data",c_),this.removeListener("end",l_),e._readyState=GS.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[TS]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",e_),e._receiver.on("finish",e_))}function c_(e){this[TS]._receiver.write(e)||this.pause()}function l_(){const e=this[TS];e._readyState=GS.CLOSING,e._receiver.end(),this.end()}function u_(){const e=this[TS];this.removeListener("error",u_),this.on("error",AS),e&&(e._readyState=GS.CLOSING,this.destroy())}const{tokenChars:d_}=vw;var h_={parse:function(e){const t=new Set;let n=-1,r=-1,i=0;for(;i<e.length;i++){const o=e.charCodeAt(i);if(-1===r&&1===d_[o])-1===n&&(n=i);else if(0===i||32!==o&&9!==o){if(44!==o)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${i}`);-1===r&&(r=i);const o=e.slice(n,r);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);t.add(o),n=r=-1}}else-1===r&&-1!==n&&(r=i)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const o=e.slice(n,i);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}};const f_=D,p_=L,{createHash:g_}=l,m_=hS,y_=uw,v_=h_,b_=VS,{GUID:w_,kWebSocket:S_}=Vb,__=/^[+/0-9A-Za-z]{22}==$/;function I_(e){e._state=2,e.emit("close")}function x_(){this.destroy()}function k_(e,t,n,r){n=n||p_.STATUS_CODES[t],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${p_.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function E_(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,E_),e.emit("wsClientError",r,n,t)}else k_(n,r,i)}var C_=ad(class extends f_{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:b_,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=p_.createServer(((e,t)=>{const n=p_.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),t.end(n)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const n of Object.keys(t))e.on(n,t[n]);return function(){for(const n of Object.keys(t))e.removeListener(n,t[n])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(I_,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(I_,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{I_(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on("error",x_);const i=e.headers["sec-websocket-key"],o=e.headers.upgrade,s=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void E_(this,e,t,405,"Invalid HTTP method");if(void 0===o||"websocket"!==o.toLowerCase())return void E_(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!__.test(i))return void E_(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(8!==s&&13!==s)return void E_(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header");if(!this.shouldHandle(e))return void k_(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=v_.parse(a)}catch(n){return void E_(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&void 0!==l){const r=new y_(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=m_.parse(l);e[y_.extensionName]&&(r.accept(e[y_.extensionName]),u[y_.extensionName]=r)}catch(n){return void E_(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[8===s?"sec-websocket-origin":"origin"],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((o,s,a,l)=>{if(!o)return k_(t,s||401,a,l);this.completeUpgrade(u,i,c,e,t,n,r)}));if(!this.options.verifyClient(o))return k_(t,401)}this.completeUpgrade(u,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,o,s){if(!i.readable||!i.writable)return i.destroy();if(i[S_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return k_(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${g_("sha1").update(t+w_).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(n.size){const e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[y_.extensionName]){const t=e[y_.extensionName].params,n=m_.format({[y_.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${n}`),c._extensions=e}this.emit("headers",a,r),i.write(a.concat("\r\n").join("\r\n")),i.removeListener("error",x_),c.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(I_,this)}))),s(c,r)}});const $_=xd("websocketServer"),O_={},N_=Eb();let T_,A_,M_,P_,D_;const j_=["https://app.kemu.io","https://dev.kemu.io","https://stage.kemu.io","https://local.kemu.io:3003"],R_=e=>{const t=O_[e];t&&t.socket.close()};var L_=e=>{D_=new C_({port:e,maxPayload:1048576e3,verifyClient:(e,t)=>{const n=e.req.headers.origin;n&&j_.includes(n)?t(!0):t(!1,401,"Origin not allowed")}}),D_.on("connection",(e=>{const t=By();$_(`New client connected. Registered as "${t}"`),e.id=t,O_[t]={socket:e,activeMessage:null},T_&&T_(t),e.on("message",(t=>{if(t instanceof Buffer){const n=O_[e.id];N_(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),$_(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{R_(n.socket.id)};if(t.command)return $_(`Received command from client [${n.socket.id}]: ${t.command}`),void(M_&&M_(n.socket.id,t.command,r,i));t.klMessage&&P_&&P_({send:r,terminateWebsocket:i,websocketId:n.socket.id,transmission:{sourceServiceId:t.sourceServiceId??-1,targetServiceId:t.targetServiceId??-1,rawMessage:t.rawMessage},json:t.klMessage.json})}))}})),e.on("close",(()=>{$_(`Client disconnected: ${e.id}`),A_&&A_(e.id),delete O_[e.id]})),e.on("error",(()=>{$_(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},F_=e=>{T_=e},U_=e=>{A_=e},B_=e=>{M_=e},W_=(e,t)=>{const n=O_[e];if(!n)return $_(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=ib)return $_("Message is too long to be a command. Use sendMessage instead."),!1;const r=bb.encodeCommand(t);return n.socket.send(r),!0},G_=e=>P_=e,V_=R_;const Y_=xd("stopService"),H_=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=xv.getAllServiceVersions(t);Y_(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await xv.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},z_=xd("removeService"),q_=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=xv.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),z_(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await xv.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},K_=xd("launchService"),J_=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});if(!n)return e.reply({error:"No service version provided"});const r=`${t}@${n}/dist`;try{const i=ev();K_(`Loading service ${t}@${n} from ${i}`);const{errorMsg:o,service:s,errorCode:a}=await xv.loadAndLaunch(i,r,!1);if(o||"started"!==s?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${o||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,u=async()=>{const r=s.status;return"running"===r?(K_(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(K_(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${s.errorMsg||"failed to initiate"}"`}):Date.now()-c>l?e.reply({error:"Timeout waiting for service to start"}):(K_("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return K_(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},Z_=xd("getMatchingServices"),X_=async e=>{const t=e.args[0],n=[],r=[];Z_(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=xv.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:xv.getServiceRootDirectory(t)}):r.push({name:e,version:i})}Z_(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},Q_=xd("getSecretsValues");let eI;var tI=async e=>{const t=e.args[0].services;if(!eI)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");Q_(`Checking for secrets values for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=[];for(const e of t){const t=e.secrets,r=await eI({name:e.name,version:e.version,requiredSecrets:t.reduce(((e,t)=>(e[t]={optional:!1,description:""},e)),{})});n.push({name:e.name,version:e.version,secrets:t.map((e=>({name:e,value:r[e]})))})}const r=[{services:n}];e.reply({success:r})},nI=e=>{eI=e};const rI=xd("getMappedSecrets");let iI;var oI=async e=>{const t=e.args[0].services;rI(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await iI(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})};const sI=xd("getServiceContents"),aI=({reply:e,args:t})=>{const[n]=t;sI(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=xv.getMatchingService(n.serviceName,n.version);if(r)return e({success:[{serviceName:r.info.name,serviceVersion:r.info.version,uiContent:r.info.widgetUIContents,uiContentsChecksum:r.info.uiContentChecksum}]});sI(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let cI={globalApiKey:void 0,environment:"production"};const lI=()=>({...cI}),uI=xd("apis"),dI=()=>{const e=lI();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},hI=async(e,t,n={})=>{try{const r=await fetch(e,{method:"POST",body:JSON.stringify(t),headers:{...n}});return r.ok?{data:await r.json(),statusCode:r.status,success:!0}:{statusCode:r.status,error:await r.text(),success:!1}}catch(e){return{statusCode:500,error:e instanceof Error?e.message:"Internal server error",success:!1}}},fI={},pI=async e=>{const t=(e=>{const t=fI[e],n=Date.now()-(t?.lastCheckedAt.getTime()??0);return t&&n<3e5?t.features:null})(e);if(t)return{valid:!0,features:t,error:null};const{valid:n,features:r,error:i}=await(async e=>{const{data:t,error:n}=await hI(`${dI()}/v1/organization/validate/apiKey`,{apiKey:e},{"Content-Type":"application/json"});return n?(uI(`Error validating Kemu API key: ${n}`),{valid:!1,features:{},error:n}):t?.features?{valid:!0,features:t.features,error:null}:{valid:!1,features:{},error:"No features returned from the server"}})(e);return n&&(fI[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}};function gI(e){return"number"==typeof e||!!/^0x[0-9a-f]+$/i.test(e)||/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function mI(e,t){return"constructor"===t&&"function"==typeof e[t]||"__proto__"===t}var yI=ad((function(e,t){t||(t={});var n={bools:{},strings:{},unknownFn:null};"function"==typeof t.unknown&&(n.unknownFn=t.unknown),"boolean"==typeof t.boolean&&t.boolean?n.allBools=!0:[].concat(t.boolean).filter(Boolean).forEach((function(e){n.bools[e]=!0}));var r={};function i(e){return r[e].some((function(e){return n.bools[e]}))}Object.keys(t.alias||{}).forEach((function(e){r[e]=[].concat(t.alias[e]),r[e].forEach((function(t){r[t]=[e].concat(r[e].filter((function(e){return t!==e})))}))})),[].concat(t.string).filter(Boolean).forEach((function(e){n.strings[e]=!0,r[e]&&[].concat(r[e]).forEach((function(e){n.strings[e]=!0}))}));var o=t.default||{},s={_:[]};function a(e,t,r){for(var i=e,o=0;o<t.length-1;o++){var s=t[o];if(mI(i,s))return;void 0===i[s]&&(i[s]={}),i[s]!==Object.prototype&&i[s]!==Number.prototype&&i[s]!==String.prototype||(i[s]={}),i[s]===Array.prototype&&(i[s]=[]),i=i[s]}var a=t[t.length-1];mI(i,a)||(i!==Object.prototype&&i!==Number.prototype&&i!==String.prototype||(i={}),i===Array.prototype&&(i=[]),void 0===i[a]||n.bools[a]||"boolean"==typeof i[a]?i[a]=r:Array.isArray(i[a])?i[a].push(r):i[a]=[i[a],r])}function c(e,t,i){if(!i||!n.unknownFn||function(e,t){return n.allBools&&/^--[^=]+$/.test(t)||n.strings[e]||n.bools[e]||r[e]}(e,i)||!1!==n.unknownFn(i)){var o=!n.strings[e]&&gI(t)?Number(t):t;a(s,e.split("."),o),(r[e]||[]).forEach((function(e){a(s,e.split("."),o)}))}}Object.keys(n.bools).forEach((function(e){c(e,void 0!==o[e]&&o[e])}));var l=[];-1!==e.indexOf("--")&&(l=e.slice(e.indexOf("--")+1),e=e.slice(0,e.indexOf("--")));for(var u=0;u<e.length;u++){var d,h,f=e[u];if(/^--.+=/.test(f)){var p=f.match(/^--([^=]+)=([\s\S]*)$/);d=p[1];var g=p[2];n.bools[d]&&(g="false"!==g),c(d,g,f)}else if(/^--no-.+/.test(f))c(d=f.match(/^--no-(.+)/)[1],!1,f);else if(/^--.+/.test(f))d=f.match(/^--(.+)/)[1],void 0===(h=e[u+1])||/^(-|--)[^-]/.test(h)||n.bools[d]||n.allBools||r[d]&&i(d)?/^(true|false)$/.test(h)?(c(d,"true"===h,f),u+=1):c(d,!n.strings[d]||"",f):(c(d,h,f),u+=1);else if(/^-[^-]+/.test(f)){for(var m=f.slice(1,-1).split(""),y=!1,v=0;v<m.length;v++)if("-"!==(h=f.slice(v+2))){if(/[A-Za-z]/.test(m[v])&&"="===h[0]){c(m[v],h.slice(1),f),y=!0;break}if(/[A-Za-z]/.test(m[v])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(h)){c(m[v],h,f),y=!0;break}if(m[v+1]&&m[v+1].match(/\W/)){c(m[v],f.slice(v+2),f),y=!0;break}c(m[v],!n.strings[m[v]]||"",f)}else c(m[v],h,f);d=f.slice(-1)[0],y||"-"===d||(!e[u+1]||/^(-|--)[^-]/.test(e[u+1])||n.bools[d]||r[d]&&i(d)?e[u+1]&&/^(true|false)$/.test(e[u+1])?(c(d,"true"===e[u+1],f),u+=1):c(d,!n.strings[d]||"",f):(c(d,e[u+1],f),u+=1))}else if(n.unknownFn&&!1===n.unknownFn(f)||s._.push(n.strings._||!gI(f)?f:Number(f)),t.stopEarly){s._.push.apply(s._,e.slice(u+1));break}}return Object.keys(o).forEach((function(e){var t,n,i;t=s,n=e.split("."),i=t,n.slice(0,-1).forEach((function(e){i=i[e]||{}})),n[n.length-1]in i||(a(s,e.split("."),o[e]),(r[e]||[]).forEach((function(t){a(s,t.split("."),o[e])})))})),t["--"]?s["--"]=l.slice():l.forEach((function(e){s._.push(e)})),s}));gb("ipcClient"),gb("kemuWidgetService"),yI(process.argv.slice(2));const vI=xd("activeClients");let bI,wI={},SI={};const _I=(e,t)=>`${e}_${t}`,II=e=>wI[e]||null,xI=(e,t)=>{const n=_I(e,t);return SI[n]||[]},kI=()=>{for(const e in wI){const t=wI[e];if(t?.transport===Wu.WS){const e=bb.encodeCommand(Fu.ServicesListChanged);t.send(e)}}},EI=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:o,extraInfo:s,isDevClient:a}=e,c=e=>{console.warn(e),o&&o()};if(r===Wu.WS){if(!s.user?.wsApiKey)return void c(`Attempted to register a WebSocket client without an API key. SessionId: ${n}`);const{valid:e,error:t}=await pI(s.user?.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&(s.user?.wsApiKey&&iv.captureError({error:new Error(t),message:`Error validating api key "${s.user?.wsApiKey}"`,data:s}),vI(`Unable to validate API Key, usage will be limited. SessionId: ${n}`))}wI[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:i,extraInfo:s,terminate:()=>{o&&o()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=_I(e.serviceName,e.version);return SI[r]=SI[r]||[],SI[r].some((e=>e.serviceId===n))||SI[r].push({sendFn:i,serviceId:n}),!0}return!1},removeSubscription:e=>{const r=t.findIndex((t=>t.targetService.serviceName===e.serviceName));if(-1!==r){t.splice(r,1);const i=_I(e.serviceName,e.version),o=SI[i]?.findIndex((e=>e.serviceId===n));if(-1!==o&&(SI[i]?.splice(o,1),!SI[i]?.length)){const t=xv.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=II(t.info.sessionId);e?.extraInfo.ipcSocketId&&Db(e?.extraInfo.ipcSocketId,Fu.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=_I(e.targetService.serviceName,e.targetService.version),r=SI[t]?.findIndex((e=>e.serviceId===n));-1!==r&&SI[t]?.splice(r,1)}t.length=0}},r===Wu.IPC&&(kI(),CI(n))},CI=e=>{const t=xv.getServiceBySessionId(e);if(t?.info.eventEmitter&&xI(t.info.name,t.info.version).length){const t=II(e);t?.extraInfo.ipcSocketId&&Db(t?.extraInfo.ipcSocketId,Fu.BroadcastStart)}},$I=e=>{const t=wI[e];var n;t?.transport===Wu.IPC?kI():(t?.removeAllSubscriptions(),(()=>{const e=Object.values(wI);for(const t of e)if(t.transport===Wu.IPC){const e=t.extraInfo.ipcSocketId,n=xv.getServiceBySessionId(t.serviceSessionId);n?.info.eventEmitter&&(xI(n.info.name,n.info.version).length||e&&Db(e,Fu.BroadcastEnd))}})(),t?.extraInfo.user?.wsApiKey&&(n=t.extraInfo.user.wsApiKey,delete fI[n]),(e=>{const t=wI[e];if(t?.transport===Wu.WS&&t.extraInfo.recipe){const n=[{recipe:t.extraInfo.recipe}];vI(`Notifying IPC clients that a Kemu Compose client [${t.extraInfo.recipe.name} (${t.extraInfo.recipe.poolId})] has disconnected. ServiceSessionId: ${e}`);for(const e in wI){const t=wI[e];t?.transport===Wu.IPC&&bI.execute(Uu.KemuComposerDisconnected,n,t.send,0,t.serviceSessionId,{async:!0}).catch((t=>{vI(`Error notifying IPC client [${e}] that a Kemu Compose client has disconnected: ${t?.message||t}`)}))}}})(e)),delete wI[e]},OI=xd("ipc:handleIpcClientCommand"),NI=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(Fu.AcknowledgeResponse)){const n=e.split(":"),r=parseInt(n[1]),i=parseInt(n[2]);return t&&t(r,isNaN(i)?void 0:i),!0}return!1})(t,((e,t)=>{if(!e)return void OI(`Ignoring ACK response from IPC service ${e} with no service id`);OI(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(jb(e,t),r=t);let i=!1;t&&(i=xv.setServiceStatus(t,"running")),i?EI({serviceSessionId:t||e,transport:Wu.IPC,send:n,extraInfo:{ipcSocketId:t}}):Db(r,Fu.SendManifest)}));!r&&OI(`Received unknown command [${t}] from service ${e}`)};let TI={};Y.platform();const AI=async e=>{const t=e.args[0];if(TI.chooseDirectory)try{const n=await TI.chooseDirectory(t);return e.reply({success:[String(n).trim()]})}catch(t){return console.error(t),e.reply({error:t instanceof Error?t.message:"Unknown error"})}return e.reply({error:"This hub does not support showing file dialogs",errCode:"GUI_NOT_SUPPORTED"})},MI=async e=>{const t=e.args[0];if(TI.chooseFile)try{const n=await TI.chooseFile(t);return e.reply({success:[String(n).trim()]})}catch(t){return console.error(t),e.reply({error:t instanceof Error?t.message:"Unknown error"})}return e.reply({error:"This hub does not support showing file dialogs",errCode:"GUI_NOT_SUPPORTED"})};var PI={},DI={},jI={};function RI(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function LI(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function FI(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function UI(e,...t){if(!FI(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function BI(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");RI(e.outputLen),RI(e.blockLen)}function WI(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function GI(e,t){UI(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(jI,"__esModule",{value:!0}),jI.output=jI.exists=jI.hash=jI.bytes=jI.bool=jI.number=jI.isBytes=void 0,jI.number=RI,jI.bool=LI,jI.isBytes=FI,jI.bytes=UI,jI.hash=BI,jI.exists=WI,jI.output=GI;const VI={number:RI,bool:LI,bytes:UI,hash:BI,exists:WI,output:GI};jI.default=VI;var YI={};Object.defineProperty(YI,"__esModule",{value:!0}),YI.add5L=YI.add5H=YI.add4H=YI.add4L=YI.add3H=YI.add3L=YI.add=YI.rotlBL=YI.rotlBH=YI.rotlSL=YI.rotlSH=YI.rotr32L=YI.rotr32H=YI.rotrBL=YI.rotrBH=YI.rotrSL=YI.rotrSH=YI.shrSL=YI.shrSH=YI.toBig=YI.split=YI.fromBig=void 0;const HI=BigInt(2**32-1),zI=BigInt(32);function qI(e,t=!1){return t?{h:Number(e&HI),l:Number(e>>zI&HI)}:{h:0|Number(e>>zI&HI),l:0|Number(e&HI)}}function KI(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:o,l:s}=qI(e[i],t);[n[i],r[i]]=[o,s]}return[n,r]}YI.fromBig=qI,YI.split=KI;const JI=(e,t)=>BigInt(e>>>0)<<zI|BigInt(t>>>0);YI.toBig=JI;const ZI=(e,t,n)=>e>>>n;YI.shrSH=ZI;const XI=(e,t,n)=>e<<32-n|t>>>n;YI.shrSL=XI;const QI=(e,t,n)=>e>>>n|t<<32-n;YI.rotrSH=QI;const ex=(e,t,n)=>e<<32-n|t>>>n;YI.rotrSL=ex;const tx=(e,t,n)=>e<<64-n|t>>>n-32;YI.rotrBH=tx;const nx=(e,t,n)=>e>>>n-32|t<<64-n;YI.rotrBL=nx;const rx=(e,t)=>t;YI.rotr32H=rx;const ix=e=>e;YI.rotr32L=ix;const ox=(e,t,n)=>e<<n|t>>>32-n;YI.rotlSH=ox;const sx=(e,t,n)=>t<<n|e>>>32-n;YI.rotlSL=sx;const ax=(e,t,n)=>t<<n-32|e>>>64-n;YI.rotlBH=ax;const cx=(e,t,n)=>e<<n-32|t>>>64-n;function lx(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}YI.rotlBL=cx,YI.add=lx;const ux=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);YI.add3L=ux;const dx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;YI.add3H=dx;const hx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);YI.add4L=hx;const fx=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;YI.add4H=fx;const px=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);YI.add5L=px;const gx=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0;YI.add5H=gx;const mx={fromBig:qI,split:KI,toBig:JI,shrSH:ZI,shrSL:XI,rotrSH:QI,rotrSL:ex,rotrBH:tx,rotrBL:nx,rotr32H:rx,rotr32L:ix,rotlSH:ox,rotlSL:sx,rotlBH:ax,rotlBL:cx,add:lx,add3L:ux,add3H:dx,add4L:hx,add4H:fx,add5H:gx,add5L:px};YI.default=mx;var yx={},vx={};Object.defineProperty(vx,"__esModule",{value:!0}),vx.crypto=void 0,vx.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
|
|
11
11
|
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
12
|
-
Object.defineProperty(e,"__esModule",{value:!0}),e.randomBytes=e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.checkOpts=e.Hash=e.concatBytes=e.toBytes=e.utf8ToBytes=e.asyncLoop=e.nextTick=e.hexToBytes=e.bytesToHex=e.byteSwap32=e.byteSwapIfBE=e.byteSwap=e.isLE=e.rotl=e.rotr=e.createView=e.u32=e.u8=e.isBytes=void 0;const t=vx,n=jI;e.isBytes=function(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name},e.u8=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),e.u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),e.createView=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),e.rotr=(e,t)=>e<<32-t|e>>>t,e.rotl=(e,t)=>e<<t|e>>>32-t>>>0,e.isLE=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0],e.byteSwap=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255,e.byteSwapIfBE=e.isLE?e=>e:t=>(0,e.byteSwap)(t),e.byteSwap32=function(t){for(let n=0;n<t.length;n++)t[n]=(0,e.byteSwap)(t[n])};const r=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));e.bytesToHex=function(e){(0,n.bytes)(e);let t="";for(let n=0;n<e.length;n++)t+=r[e[n]];return t};const i=48,o=57,s=65,a=70,c=97,l=102;function u(e){return e>=i&&e<=o?e-i:e>=s&&e<=a?e-(s-10):e>=c&&e<=l?e-(c-10):void 0}function d(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function h(e){return"string"==typeof e&&(e=d(e)),(0,n.bytes)(e),e}e.hexToBytes=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,n=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=u(e.charCodeAt(i)),o=u(e.charCodeAt(i+1));if(void 0===n||void 0===o){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}r[t]=16*n+o}return r},e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let i=Date.now();for(let o=0;o<t;o++){r(o);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=d,e.toBytes=h,e.concatBytes=function(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];(0,n.bytes)(i),t+=i.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const i=e[t];r.set(i,n),n+=i.length}return r},e.Hash=class{clone(){return this._cloneInto()}};const f={}.toString;e.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==f.call(t))throw new Error("Options should be object or undefined");return Object.assign(e,t)},e.wrapConstructor=function(e){const t=t=>e().update(h(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t},e.wrapConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(h(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.wrapXOFConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(h(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.randomBytes=function(e=32){if(t.crypto&&"function"==typeof t.crypto.getRandomValues)return t.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}}(yx),Object.defineProperty(DI,"__esModule",{value:!0}),DI.shake256=DI.shake128=DI.keccak_512=DI.keccak_384=DI.keccak_256=DI.keccak_224=DI.sha3_512=DI.sha3_384=DI.sha3_256=DI.sha3_224=DI.Keccak=DI.keccakP=void 0;const bx=jI,wx=YI,Sx=yx,_x=[],Ix=[],xx=[],kx=BigInt(0),Ex=BigInt(1),Cx=BigInt(2),$x=BigInt(7),Ox=BigInt(256),Nx=BigInt(113);for(let e=0,t=Ex,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],_x.push(2*(5*r+n)),Ix.push((e+1)*(e+2)/2%64);let i=kx;for(let e=0;e<7;e++)t=(t<<Ex^(t>>$x)*Nx)%Ox,t&Cx&&(i^=Ex<<(Ex<<BigInt(e))-Ex);xx.push(i)}const[Tx,Ax]=(0,wx.split)(xx,!0),Mx=(e,t,n)=>n>32?(0,wx.rotlBH)(e,t,n):(0,wx.rotlSH)(e,t,n),Px=(e,t,n)=>n>32?(0,wx.rotlBL)(e,t,n):(0,wx.rotlSL)(e,t,n);function Dx(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const r=(t+8)%10,i=(t+2)%10,o=n[i],s=n[i+1],a=Mx(o,s,1)^n[r],c=Px(o,s,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=a,e[t+n+1]^=c}let t=e[2],i=e[3];for(let n=0;n<24;n++){const r=Ix[n],o=Mx(t,i,r),s=Px(t,i,r),a=_x[n];t=e[a],i=e[a+1],e[a]=o,e[a+1]=s}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=Tx[r],e[1]^=Ax[r]}n.fill(0)}DI.keccakP=Dx;class jx extends Sx.Hash{constructor(e,t,n,r=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,bx.number)(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,Sx.u32)(this.state)}keccak(){Sx.isLE||(0,Sx.byteSwap32)(this.state32),Dx(this.state32,this.rounds),Sx.isLE||(0,Sx.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,bx.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,Sx.toBytes)(e)).length;for(let i=0;i<r;){const o=Math.min(t-this.pos,r-i);for(let t=0;t<o;t++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){(0,bx.exists)(this,!1),(0,bx.bytes)(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,bx.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,bx.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new jx(t,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}DI.Keccak=jx;const Rx=(e,t,n)=>(0,Sx.wrapConstructor)((()=>new jx(t,e,n)));DI.sha3_224=Rx(6,144,28),DI.sha3_256=Rx(6,136,32),DI.sha3_384=Rx(6,104,48),DI.sha3_512=Rx(6,72,64),DI.keccak_224=Rx(1,144,28),DI.keccak_256=Rx(1,136,32),DI.keccak_384=Rx(1,104,48),DI.keccak_512=Rx(1,72,64);const Lx=(e,t,n)=>(0,Sx.wrapXOFConstructorWithOpts)(((r={})=>new jx(t,e,void 0===r.dkLen?n:r.dkLen,!0)));DI.shake128=Lx(31,168,16),DI.shake256=Lx(31,136,32);const{sha3_512:Fx}=DI,Ux=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function Bx(e){let t=0n;for(const n of e.values())t=(t<<8n)+BigInt(n);return t}const Wx=(e="")=>Bx(Fx(e)).toString(36).slice(1),Gx=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),Vx=({globalObj:e=(void 0!==sd?sd:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Ux(32,t):Ux(32,t);return Wx(r).substring(0,32)},Yx=e=>()=>e++,Hx=({random:e=Math.random,counter:t=Yx(Math.floor(476782367*e())),length:n=24,fingerprint:r=Vx({random:e})}={})=>function(){const i=(e=>Gx[Math.floor(e()*Gx.length)])(e),o=Date.now().toString(36),s=t().toString(36),a=Ux(n,e);return`${i+Wx(`${o+a+s+r}`).substring(1,n)}`},zx=Hx();PI.getConstants=()=>({defaultLength:24,bigLength:32}),PI.init=Hx,PI.createId=zx,PI.bufToBigInt=Bx,PI.createCounter=Yx,PI.createFingerprint=Vx,PI.isCuid=(e,{minLength:t=2,maxLength:n=32}={})=>{const r=e.length,i=/^[0-9a-z]+$/;try{if("string"==typeof e&&r>=t&&r<=n&&i.test(e))return!0}finally{}return!1};const{createId:qx,init:Kx,getConstants:Jx,isCuid:Zx}=PI;var Xx=qx;const Qx=xd("getUniqueId"),ek=({reply:e,sourceServiceId:t})=>(Qx(`Generating unique id for service "${t}"`),e({success:[Xx()]})),tk=xd("getActiveServices"),nk=async({transport:e,sourceServiceId:t,reply:n})=>{if(tk(`Received GetServices request from ${e} [${t}]`),e===Wu.WS){let e=xv.getActiveServices();const r=II(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===Wu.WS){if(!r?.extraInfo.user?.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(xv.isInternalKemuService),o=e.filter((e=>e.devMode&&xv.isNotInternalKemuService(e))),s=e.filter((e=>xv.isOfficialKemuService(e)&&xv.isNotInternalKemuService(e)&&xv.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=e.filter((e=>xv.isNotDevService(e)&&xv.isNotInternalKemuService(e)&&!xv.isOfficialKemuService(e))),c=await(async e=>{const{features:t}=await pI(e);return t})(r.extraInfo.user?.wsApiKey),l=c?.hub_services??0,u=s.slice(0,-1!==l?l:s.length);-1!==l&&(i=s.slice(l).map((e=>({name:e.name,version:e.version,svgIcon:e.svgIcon,color:e.color,description:e.description,title:e.title,shortTitle:e.shortTitle})))),e=[...t,...o,...u,...a]}const o=xv.getFailedServices().map((e=>({name:e.name,version:e.version,description:e.description,title:e.title,status:e.status,errorMsg:e.errorMsg,errorCode:e.errorCode,internal:xv.isInternalKemuService(e),svgIcon:e.svgIcon,color:e.color,shortTitle:e.shortTitle})));n({success:[{available:e.map((e=>{const{widgetUIContents:t,...n}=e;return{...n}})),failed:o,installed:i}]})}};let rk="runtime",ik=null;const ok=()=>rk,sk=xd("getSystemInfo"),ak=async({reply:e})=>{sk("Received GetSystemInfo request"),e({success:[await(async()=>({platformArch:Ku(),isDesktopHub:"desktop"===ok(),isRuntimeHub:"runtime"===ok(),hubVersion:Yy,...ik?{updateAvailable:ik}:{}}))()]})},ck=xd("removeService"),lk=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,o=r.version;if(!i)return n({error:"No service name provided"});if(!o)return n({error:"No service version provided"});const s=xv.getAllServiceVersions(i),a=s.find((e=>e.info.version===o));if(!a)return n({error:"Service not found"});ck(`Removing ${s.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await xv.uninstallService(a.info.name,a.info.version),c){const e=II(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.user?.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});ck(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await hI(`${dI()}/v1/organization/validate/uninstall_hub_service`,e,{"Content-Type":"application/json"});if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(ck(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:o}}]})},uk=xd("getDecryptedEdgeApiKey"),dk=({reply:e})=>(uk("Getting decrypted edge API key"),e({success:[lI().globalApiKey]})),hk=({reply:e})=>{uk("Getting hub config");const t=lI();return e({success:[{kemuApiKey:t.globalApiKey,environment:t.environment}]})};let fk,pk,gk,mk,yk;const vk=e=>e.transport===Wu.IPC&&(e.reply({error:"Transport is not allowed to call this function"}),!0);var bk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretNames;if(!r||!n)return e.reply({error:"Invalid request parameters"});if(!fk)return e.reply({error:"Get recipe secrets function not set"});const i=await fk({...t[0]}),o={};for(const e of r)o[e]=e in i?i[e]:null;const s=[{secrets:o}];e.reply({success:s})},wk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretsMap;if(vk(e))return;if(!pk)return e.reply({error:"Add recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await pk({recipeUuid:n,secretsMap:r})}];e.reply({success:i})},Sk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretName;if(vk(e))return;if(!gk)return e.reply({error:"Delete recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await gk({recipeUuid:n,secretName:r})}];e.reply({success:i})},_k=async e=>{const t=e.args[0].recipeUuid;if(!mk)return e.reply({error:"Get recipe secret mappings function not set"});if(!t)return e.reply({error:"Invalid request parameters"});const n=[{secrets:await mk({recipeUuid:t})}];e.reply({success:n})},Ik=async e=>{const t=e.args,n=t[0].hubServiceName,r=t[0].secrets;return yk?n&&r?Array.isArray(r)?(await yk({hubServiceName:n,secrets:r}),void e.reply({success:[]})):e.reply({error:'Expected "secrets" to be an array'}):e.reply({error:"Invalid request parameters"}):e.reply({error:"Add service secret function not set"})};let xk,kk,Ek;const Ck=e=>e.transport===Wu.IPC&&(e.reply({error:"You are not allowed to manage secrets using this transport"}),!0);var $k=async e=>{if(e.args,Ck(e))return;if(!Ek)return e.reply({error:"Get hub secrets function not set"});const t=[{contexts:await Ek()}];e.reply({success:t})},Ok=async e=>{const t=e.args;if(Ck(e))return;if(!xk)return e.reply({error:"Add hub secret function not set"});const n=[{contexts:await xk(t[0])}];e.reply({success:n})},Nk=async e=>{const t=e.args;if(Ck(e))return;if(!kk)return e.reply({error:"Delete hub secret function not set"});const n=[{contexts:await kk(t[0])}];e.reply({success:n})};const Tk=k(V(import.meta.url));let Ak=null;const Mk=xd("hub"),Pk=new function(){const e={};let t,n=console.log;const r={};let i="hub";const o={},s=e=>!o[e],a=(e,t,n,r,i,o)=>{let a=sb?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:o.success?o.success:[o],messageId:t,type:o.success?"response":"error"}};return s(r)&&(a=Fb.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(i,o,s,c)=>{if(!c)return!1;const l=c;if(e[l.messageId]){const t=e[l.messageId];return t&&(clearTimeout(t.timer),t.fulfilled||(t.fulfilled=!0,"response"===l.type?t.resolve(l.args):"error"===l.type&&t.reject(l.args[0])),delete e[l.messageId]),!0}if("execute"!==l.type&&n&&n(`No pending execution found for message id "${l.messageId}"`),"execute"===l.type){const e=r[l.functionName];if(e){const r=e=>{a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,e)};if(t&&!t({args:l.args,functionName:l.functionName,transport:i,messageId:l.messageId,sourceServiceId:s.sourceServiceId,reply:r,send:o}))return n&&n(`Function "${l.functionName}" not allowed to be invoked by client [${s.sourceServiceId}]`),r({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;e({transport:i,args:l.args,reply:r,messageId:l.messageId,sourceServiceId:s.sourceServiceId,send:o})}else{const e=`Function "${l.functionName}" not found.`;n&&n(e),a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(t,r,o,a,c,l)=>{if(!o){const e="No send buffer function provided.";throw n&&n(e),e}Ub+=1;const u=`${i}-${Ub}-exec-${t.substring(0,10)}`,d={messageId:u,functionName:t,send:o,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=sb?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:t,args:r,messageId:u,type:"execute"}};s(c)&&(h=Fb.encode(f,a,c)),e[u]=d,n&&n(`Calling remote function "${t}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete e[u]):0===l?.timeout||p||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=e[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${t} Timed out`)),delete e[u]}),l?.timeout||3e4)),o(h,{sourceServiceId:a,targetServiceId:c,msg:f}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},registerFunctionsMiddleware:e=>{t=e},unregisterAllFunctions:()=>{Object.keys(r).forEach((e=>{delete r[e]}))},getTransportSendFunction:t=>{const n=e[t];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>e,rejectAllPending:t=>{Object.keys(e).forEach((n=>{const r=e[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(t),delete e[n])}))},broadcast:(e,t,r,o)=>{Ub+=1;const a=`${i}-${Ub}-multicast-${e.substring(0,10)}`;let c=sb?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=s(r[0].serviceId);u&&(c=Fb.encode(l,o,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(u=s(i.serviceId),u&&(c=Fb.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:o,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{o[e]=t}}}("hub");bI=Pk,Pk.setLogger(Mk);const Dk={[Uu.RebootToInstallUpdate]:null,[Uu.GetFileContentFromCacheId]:null,[Uu.SaveRecipeToFile]:null},jk=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=II(n.targetServiceId);if(!r)return Mk(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,Wu.IPC;const i=t.json?.messageId;return Mk(`Forwarding message from ${n.sourceServiceId} to ${n.targetServiceId}, msgId: ${i}`),r.send(n.rawMessage,{sourceServiceId:n.sourceServiceId,targetServiceId:n.targetServiceId,msg:{json:t.json}}),!0}return!1},Rk=({sourceServiceId:e,args:t})=>{const n=xv.getServiceBySessionId(e);if(n){const r=xI(n.info.name,n.info.version),i=xI(n.info.name,"*");if(!r.length&&!i.length)return;const o=[...r,...i],s={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};Pk.broadcast(Uu.BroadcastEvent,[s],o,0)}},Lk=async({args:e,reply:t})=>{const n=e[0];if(!n)return Mk("Invalid config for SendToRecipe"),t({error:"Invalid config for SendToRecipe"});const r=(i=n.recipePoolId,Object.values(wI).find((e=>e.extraInfo.recipe?.poolId===i))||null);var i;if(!r)return Mk(`No client found for recipe pool id ${n.recipePoolId}`),t({error:`No client found for recipe pool id "${n.recipePoolId}"`});try{const e=Pk.execute(Uu.SendToRecipe,[n],r.send,0,r.serviceSessionId,{async:!n.waitForResponse,timeout:n.timeout});n.waitForResponse?t({success:await e}):t({success:[]})}catch(e){return Mk(`Error sending to recipe ${n.recipePoolId}: ${e?.message||e}`),t({error:e?.message||"There was an error sending to the recipe"})}},Fk=e=>{const{send:t,transmission:n,json:r}=e;Mk(`Raw message Id received from WS: ${r?.messageId}`),jk(Wu.WS,e)||Pk.processMessage(Wu.WS,t,n,r)},Uk=e=>{const t=(n=e,`${Fu.SocketAcknowledge}${n}`);var n;W_(e,t)},Bk=(e,t)=>{Mk(`Received unknown command [${t}] from service ${e}`)},Wk=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,o=n,s=t[0],a=s?.user?.apiKey||lI().globalApiKey;if(!a)return Mk(`Received ACK from WS service ${n} but no API key was provided`),i({error:"No API key was provided",errCode:"MISSING_API_KEY"});s.user?.id&&iv.setGlobalUserId(s.user?.id),await EI({serviceSessionId:n,transport:Wu.WS,send:r,terminateFn:()=>{V_(n)},extraInfo:{websocketId:o,recipe:s.recipe,user:{wsApiKey:a,userEmail:s.user?.email,userId:s.user?.id}}}),i({success:[]})},Gk=e=>{Mk(`WS Client ${e} disconnected`),$I(e)},Vk=e=>1===e.sourceServiceId?e.functionName===Uu.GetFileContentFromCacheId:e.functionName===Uu.SocketAckResponse||e.functionName===Uu.ServiceManifest||e.functionName===Uu.SubscribeToService||(!!II(e.sourceServiceId)||(e.reply({error:`Session id "${e.sourceServiceId}" not found. Please acknowledge the session first.`}),!1)),Yk=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==Wu.IPC){var i;Mk(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=xv.getMatchingDevService(n.name,n.version,"stopped");if(t){Mk(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const o=II(t.info.sessionId);if(!o)return void Mk(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);o.send=r,wI[i=e]?delete wI[i]:vI(`Could not find source client with session id ${i}`),jb(e,t.info.sessionId);const s=await Jy(n,n.path);t.info={...t.info,...s},Mk(`Updating manifest for dev service ${t.info.sessionId}`),xv.setServiceManifest(t.info.sessionId,s,"running"),Mk(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Db(t.info.sessionId,(e=>`${Fu.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=wI[e];t?t.isDevClient?(t.disconnected=!1,t.transport===Wu.IPC&&(kI(),CI(e))):vI(`Client with session id ${e} is not a dev client`):vI(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{xv.addDevService(e,n,"running");const t=II(e);t?t.isDevClient=!0:EI({serviceSessionId:e,transport:Wu.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}Mk(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var Hk=async e=>{var t;Mk("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",rk=t;const n=e?.ipc?.appSpace||"kemu.",r=e?.ipc?.id||"widgets";if(!e.serviceUrl)throw new Error("Missing service url, please set the `apiUrl` option.");e.errorTracker&&iv.setTracker(e.errorTracker),(e=>{cI={...cI,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey,environment:e.environment}),Pk.registerFunctionsMiddleware(Vk),e.secrets?.serviceSecrets&&(e=>{yk=e})(e.secrets.serviceSecrets.addServiceSecretFn),e.secrets?.recipeSecrets&&((e=>{fk=e})(e.secrets.recipeSecrets.getRecipeDecryptedSecretsFn),(e=>{pk=e})(e.secrets.recipeSecrets.addRecipeSecretFn),(e=>{gk=e})(e.secrets.recipeSecrets.deleteRecipeSecretFn),(e=>{mk=e})(e.secrets.recipeSecrets.getRecipeSecretMappingsFn)),e.secrets?.hubSecrets&&((e=>{Ek=e})(e.secrets.hubSecrets.getHubSecretsFn),(e=>{xk=e})(e.secrets.hubSecrets.addHubSecretsFn),(e=>{kk=e})(e.secrets.hubSecrets.deleteHubSecretFn)),Pk.registerFunction(Uu.GetServiceContents,aI),Pk.registerFunction(Uu.GetServices,nk),Pk.registerFunction(Uu.GetSystemInfo,ak),Pk.registerFunction(Uu.ShowSecretsConfigScreen,(async({args:t,reply:n})=>{const[{name:r,version:i}]=t;e?.onShowSecretsScreen?(await e.onShowSecretsScreen(r,i),n({success:[]})):n({error:"This hub does not support showing secrets configuration screens",errCode:"GUI_NOT_SUPPORTED"})})),Pk.registerFunction(Uu.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Wu.WS){const[e]=n,i=II(r);if(!i)return t({error:`Session id "${r}" not found`});Mk(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),Pk.registerFunction(Uu.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Wu.WS){const[e]=n,i=II(r),o=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(Mk(`Service ${r} subscribing to "${o.serviceName} (${o.version})"`),"hub"===o.serviceName)return i.addSubscription(o),void t({success:[]});if(!i.addSubscription(o))return Mk(`Service ${r} already subscribed to "${o.serviceName} (${o.version})", ignoring request.`),t({success:[]});const s=xv.getMatchingService(o.serviceName,o.version);if(!s)return Mk(`Service ${o.serviceName} ${o.version} not active yet`),t({success:[]});if(!s.info.eventEmitter)return Mk(`Service ${o.serviceName} ${o.version} does not have an event emitter, removing subscription`),i.removeSubscription(o),t({error:`Service "${o.serviceName} (${o.version})" does not produce events`});const a=II(s.info.sessionId);return a?.extraInfo.ipcSocketId&&(Mk(`Sending Broadcast START command to service ${s.info.sessionId}`),Db(a?.extraInfo.ipcSocketId,Fu.BroadcastStart)),t({success:[]})}})),Pk.registerFunction("stopService",H_),Pk.registerFunction("removeService",q_),Pk.registerFunction("launchService",J_),Pk.registerFunction("getMatchingServices",X_),Pk.registerFunction("getSecretsValues",tI),Pk.registerFunction(Uu.GetMappedSecrets,oI),Pk.registerFunction(Uu.BroadcastEvent,Rk),Pk.registerFunction(Uu.ServiceManifest,Yk),Pk.registerFunction(Uu.ChooseDirectoryDialog,AI),Pk.registerFunction(Uu.ChooseFileDialog,MI),Pk.registerFunction(Uu.GetUniqueId,ek),Pk.registerFunction(Uu.SendToRecipe,Lk),Pk.registerFunction(Uu.GetDecryptedEdgeApiKey,dk),Pk.registerFunction(Uu.GetHubConfig,hk),Pk.registerFunction(Uu.SocketAckResponse,Wk),Pk.registerFunction(Uu.UninstallService,lk),Pk.registerFunction(Uu.GetRecipeDecryptedSecretsValues,bk),Pk.registerFunction(Uu.GetRecipeSecretMappings,_k),Pk.registerFunction(Uu.AddRecipeSecretMapping,wk),Pk.registerFunction(Uu.DeleteRecipeSecretMapping,Sk),Pk.registerFunction(Uu.GetHubSecrets,$k),Pk.registerFunction(Uu.AddHubSecrets,Ok),Pk.registerFunction(Uu.DeleteHubSecret,Nk),Pk.registerFunction(Uu.AddServiceSecret,Ik),Object.entries(Dk).forEach((([e,t])=>{t?Pk.registerFunction(e,t):(Mk(`Skipping registration of "${e}" because it's not implemented`),Pk.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),(e=>{Tb=e})((e=>{const{send:t,transmission:n,json:r}=e;Mk(`Raw message Id received from IPC: ${r?.messageId}`),jk(Wu.IPC,e)||Pk.processMessage(Wu.IPC,t,n,r)})),G_(Fk),F_(Uk),B_(Bk),U_(Gk),(e=>{Nb=e})(NI),(e=>{$b=e})((e=>{const t=(e=>`${Fu.IpcAcknowledge}${e}`)(e);Db(e,t)})),(e=>{Ob=e})((e=>{Mk(`IPC socket [${e}] disconnected`);const t=II(e);if(t){Mk(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=xv.getServiceBySessionId(t.serviceSessionId);xv.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,kI()):$I(t.serviceSessionId)}})),await(e=>(e?.ipcId&&(rb.config.id=e.ipcId),e?.ipcAppSpace&&(rb.config.appspace=e.ipcAppSpace),new Promise((e=>{rb.serve((()=>{Cb.info("IPC Server Initiated"),rb.server.on("data",((e,t)=>{const n=Ab[t.id];n?(Cb.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Mb(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Cb.data(`Received command from client [${t.id}]: ${e.command}`),void(Nb&&Nb(t.id,e.command,n));e.klMessage&&Tb&&Tb({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Cb.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),rb.server.on("connect",(e=>{const t=By();Cb.info(`New client connected. Registered as "${t}"`),e.id=t,Ab[t]={socket:e,activeMessage:null,disconnectHandler:()=>Pb(t)},e.on("close",Ab[t].disconnectHandler),$b&&$b(t)})),rb.server.on("disconnect",(e=>{Pb(e.id)})),rb.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),rb.server.start()}))))({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await L_(e?.ws?.port||5368);const i=e?.defaultServicesPath||I.resolve(Tk,"defaultServices");Ak=i;const o=process.env.DEV_SESSION_ID;xv.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),xv.setEnableServiceLogsConfig(!!e?.enableServiceLogs),e?.servicesInstallPath&&(e=>{Xy=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Qy=e})(e.testServicesInstallPath);const s=ev(),a=tv(),c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=s,t.__KEMU_USER_TEST_SERVICES_PATH=a,t.__KEMU_SERVICE_URL=lI().serviceUrl,t.__KEMU_ENVIRONMENT=lI().environment,t};e?.getServiceSecretsFn?(xv.setGetSecretsFunction(e.getServiceSecretsFn),nI(e.getServiceSecretsFn)):(xv.setGetSecretsFunction(c),nI(c)),(e=>{iI=e})(e?.getMappedSecretsFn?e.getMappedSecretsFn:async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{})),xv.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return H("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await xv.loadServices(i,{fixedSession:o?parseInt(o):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0,enableLogs:!0}),null!==e?.servicesInstallPath&&(await Zy(s)||await m(s,{recursive:!0}),await xv.loadServices(s,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,enableLogs:!!e?.enableServiceLogs}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await xv.launchServices({noSpawningList:l||[]}),Mk("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&(e=>{TI=e})({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},zk=e=>{if(e===Wu.WS)return{handleWebsocketConnectionEvent:Uk,handleWebsocketClientDisconnectionEvent:Gk,handleWebsocketMessage:Fk,handleWebsocketClientCommand:Bk,getRemoteInvoke:()=>Pk}},qk=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(xv.getAllServices().every((e=>"running"===e.status))&&e.every((e=>"running"===xv.getMatchingService(e.name,e.version)?.status)))return n();t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let Kk;const Jk=Ml("run"),Zk=Yu(),Xk=1e3,Qk=_(process.argv.slice(2)),eE=e=>"number"==typeof e?{type:me.Number,value:e}:"string"==typeof e?{type:me.String,value:e}:"boolean"==typeof e?{type:me.Boolean,value:e}:Array.isArray(e)?{type:me.Array,value:e}:e;global.ImageData=J;const tE=e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer;ke({createCanvas:(e,t)=>X(e,t),loadImage:async e=>{let t=e;if(tE(e)){const n=e;t=Buffer.from(n.data)}const n=await Z(t),r=X(n.width,n.height).getContext("2d");r.drawImage(n,0,0,n.width,n.height);return r.getImageData(0,0,n.width,n.height)}});const nE=(e,t)=>"*"===e?ao.onAnyGlobalVariableChange(t):ao.onGlobalVariableChange(e,t),rE=(e,t,n)=>ao.setGlobalVariable({name:e,value:t,disableChangeNotifications:n?.disableChangeNotifications||!1,disableDefineNotifications:n?.disableDefineNotifications||!1,doNotOverrideExisting:n?.doNotOverrideExisting||!1}),iE=e=>{ao.deleteGlobalVariable({name:e})},oE=()=>ao.getAllVariables(),sE=e=>ao.getGlobalVariable(e),aE=e=>Wi(e),cE=e=>async()=>{throw new Error(`${e} not implemented`)},lE={createImageDataLike:(e,t,n,r="srgb")=>{let i;return i=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:i,width:t,height:n,colorSpace:r,_kemuType:me.ImageData}},loadImageFile:async e=>{const t=await Z(e),n=X(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)},encodeImageData:async(e,t="jpeg",n)=>{const r=X(e.width,e.height);let i;return r.getContext("2d").putImageData(e,0,0),i="png"===t?await r.encode(t):await r.encode(t,n),i}};var uE={start:async r=>{r=r||{};const i=r?.recipePath||Qk.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!i)throw new Error("`recipePath` not provided. Please specify it in the config object, via a command line argument [--recipePath] or as an environment variable [KEMU_EDGE_RECIPE_PATH].");const{parsed:o}=await e({path:z(q(i),".env")}),s=r.apiKey||process.env.KEMU_API_KEY;if(!s)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");const a=i.endsWith(".json")||i.endsWith(".kemu"),c=a?K(i):i,l=a?i:z(c,"recipe.kemu"),u=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(q(l),"utf-8"));if(!u)throw new Error("Failed to parse recipe file");if(!u.author?.id)throw new Error("Missing required author ID in recipe file.");const{serviceUrl:d,apiKey:h,environment:f}=((e,t)=>{const n=qc(e,t),r=Buffer.from(n,"base64").toString("utf8"),[i,o,s]=r.split("<@>");if(!o||!i||!s)throw new Error("Invalid API key.");return{serviceUrl:o,apiKey:i,environment:s}})(u,s);await oc();const p={id:u.uuid||String(Date.now()),version:1,author:u.author.id};(e=>{fo=e})(console);const g=zk(_e.WS),m=(e,t)=>{if(t)g?.handleWebsocketMessage({send:v,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;g?.handleWebsocketClientCommand(Xk,t)}},y=(bl={instanceServiceId:Xk,sendBuf:m,sendCmd:m,triggerOnCommand:(...e)=>wl(...e),triggerOnConnected:()=>Sl(),triggerOnDisconnected:()=>_l(),triggerOnMessageReceived:(...e)=>Il(...e)},bl);const v=(e,t)=>{if(t)y.triggerOnMessageReceived({send:m,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;y.triggerOnCommand(t)}},b=zu(),w=g.getRemoteInvoke();b.disableServiceEncoding(0,!0),w.disableServiceEncoding(Xk,!0);const S=Object.values(u.blocks[pe].gates).filter((e=>e.type===Ke.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),_=S.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),I=z(c,"services"),x=await n(I).then((()=>!0)).catch((()=>!1));if(_.length>0&&!x)throw new Error("Services directory not found but required services are defined in the recipe. Please make sure there is a `services` directory in the recipe root and add the services you want to use to it.");await Hk({globalApiKey:h,serviceUrl:d,recipeRootPath:c,servicesInstallPath:x?z(c,"services"):null,noDefaultServices:!0,environment:f,ws:{disabled:!0},secrets:{recipeSecrets:{getRecipeDecryptedSecretsFn:async()=>({...o}),getRecipeSecretMappingsFn:cE("getRecipeSecretMappingsFn"),addRecipeSecretFn:cE("addRecipeSecretFn"),deleteRecipeSecretFn:cE("deleteRecipeSecretFn")}},ipc:{appSpace:"kemu-runner.",id:p.id}}),Jk("Waiting for services to run"),await qk(_),Jk("All services are running"),Bc(Zk),Yc(),aa((e=>{Jk("Global processing state changed: ",e)})),u.globalVariables&&(u.globalVariables=await zc(u.globalVariables));const k=await Lc(u,"runner",p.version,p.author,mr.Desktop);return Kk=k,Hu(k),await Gu({apiKey:h,id:u.author.id}),new Promise(((e,t)=>{var n;Vu("acknowledged",(async()=>{await Zk.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Uc(k);if(n.length>0){const e=`Some widgets failed to initialize: ${n.join(", ")}`;return t(e)}await i().catch((e=>{console.error("Error invoking recipe loaded widgets: ",e)})),Jk("Recipe started"),e({sendToInputWidgetAndWaitForOutput:(e,t)=>{const n=eE(t);return r({inputName:e,data:n,waitForOutputChild:!0})},sendToInputWidget:(e,t)=>{const n=eE(t);return r({inputName:e,data:n,waitForOutputChild:!1})},globalVariables:{onChange:nE,setValue:rE,getValue:sE,delete:iE,getAll:oE},status:{onChange:aE},edgeFunctions:{register:Ga.registerFunctionHandler,unregister:Ga.unregisterFunctionHandler,clearAll:Ga.clearAllHandlers}})})),y.triggerOnConnected(),y.triggerOnCommand((n=Xk,`${be.SocketAcknowledge}${n}`))}))},terminate:async()=>{Kk&&await Fc(Kk)}};export{me as DataType,uE as default,tE as isBinaryFile,lE as utils};
|
|
12
|
+
Object.defineProperty(e,"__esModule",{value:!0}),e.randomBytes=e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.checkOpts=e.Hash=e.concatBytes=e.toBytes=e.utf8ToBytes=e.asyncLoop=e.nextTick=e.hexToBytes=e.bytesToHex=e.byteSwap32=e.byteSwapIfBE=e.byteSwap=e.isLE=e.rotl=e.rotr=e.createView=e.u32=e.u8=e.isBytes=void 0;const t=vx,n=jI;e.isBytes=function(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name},e.u8=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),e.u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),e.createView=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),e.rotr=(e,t)=>e<<32-t|e>>>t,e.rotl=(e,t)=>e<<t|e>>>32-t>>>0,e.isLE=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0],e.byteSwap=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255,e.byteSwapIfBE=e.isLE?e=>e:t=>(0,e.byteSwap)(t),e.byteSwap32=function(t){for(let n=0;n<t.length;n++)t[n]=(0,e.byteSwap)(t[n])};const r=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));e.bytesToHex=function(e){(0,n.bytes)(e);let t="";for(let n=0;n<e.length;n++)t+=r[e[n]];return t};const i=48,o=57,s=65,a=70,c=97,l=102;function u(e){return e>=i&&e<=o?e-i:e>=s&&e<=a?e-(s-10):e>=c&&e<=l?e-(c-10):void 0}function d(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function h(e){return"string"==typeof e&&(e=d(e)),(0,n.bytes)(e),e}e.hexToBytes=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,n=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=u(e.charCodeAt(i)),o=u(e.charCodeAt(i+1));if(void 0===n||void 0===o){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}r[t]=16*n+o}return r},e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let i=Date.now();for(let o=0;o<t;o++){r(o);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=d,e.toBytes=h,e.concatBytes=function(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];(0,n.bytes)(i),t+=i.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const i=e[t];r.set(i,n),n+=i.length}return r},e.Hash=class{clone(){return this._cloneInto()}};const f={}.toString;e.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==f.call(t))throw new Error("Options should be object or undefined");return Object.assign(e,t)},e.wrapConstructor=function(e){const t=t=>e().update(h(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t},e.wrapConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(h(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.wrapXOFConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(h(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.randomBytes=function(e=32){if(t.crypto&&"function"==typeof t.crypto.getRandomValues)return t.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}}(yx),Object.defineProperty(DI,"__esModule",{value:!0}),DI.shake256=DI.shake128=DI.keccak_512=DI.keccak_384=DI.keccak_256=DI.keccak_224=DI.sha3_512=DI.sha3_384=DI.sha3_256=DI.sha3_224=DI.Keccak=DI.keccakP=void 0;const bx=jI,wx=YI,Sx=yx,_x=[],Ix=[],xx=[],kx=BigInt(0),Ex=BigInt(1),Cx=BigInt(2),$x=BigInt(7),Ox=BigInt(256),Nx=BigInt(113);for(let e=0,t=Ex,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],_x.push(2*(5*r+n)),Ix.push((e+1)*(e+2)/2%64);let i=kx;for(let e=0;e<7;e++)t=(t<<Ex^(t>>$x)*Nx)%Ox,t&Cx&&(i^=Ex<<(Ex<<BigInt(e))-Ex);xx.push(i)}const[Tx,Ax]=(0,wx.split)(xx,!0),Mx=(e,t,n)=>n>32?(0,wx.rotlBH)(e,t,n):(0,wx.rotlSH)(e,t,n),Px=(e,t,n)=>n>32?(0,wx.rotlBL)(e,t,n):(0,wx.rotlSL)(e,t,n);function Dx(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const r=(t+8)%10,i=(t+2)%10,o=n[i],s=n[i+1],a=Mx(o,s,1)^n[r],c=Px(o,s,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=a,e[t+n+1]^=c}let t=e[2],i=e[3];for(let n=0;n<24;n++){const r=Ix[n],o=Mx(t,i,r),s=Px(t,i,r),a=_x[n];t=e[a],i=e[a+1],e[a]=o,e[a+1]=s}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=Tx[r],e[1]^=Ax[r]}n.fill(0)}DI.keccakP=Dx;class jx extends Sx.Hash{constructor(e,t,n,r=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,bx.number)(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,Sx.u32)(this.state)}keccak(){Sx.isLE||(0,Sx.byteSwap32)(this.state32),Dx(this.state32,this.rounds),Sx.isLE||(0,Sx.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,bx.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,Sx.toBytes)(e)).length;for(let i=0;i<r;){const o=Math.min(t-this.pos,r-i);for(let t=0;t<o;t++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){(0,bx.exists)(this,!1),(0,bx.bytes)(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,bx.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,bx.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new jx(t,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}DI.Keccak=jx;const Rx=(e,t,n)=>(0,Sx.wrapConstructor)((()=>new jx(t,e,n)));DI.sha3_224=Rx(6,144,28),DI.sha3_256=Rx(6,136,32),DI.sha3_384=Rx(6,104,48),DI.sha3_512=Rx(6,72,64),DI.keccak_224=Rx(1,144,28),DI.keccak_256=Rx(1,136,32),DI.keccak_384=Rx(1,104,48),DI.keccak_512=Rx(1,72,64);const Lx=(e,t,n)=>(0,Sx.wrapXOFConstructorWithOpts)(((r={})=>new jx(t,e,void 0===r.dkLen?n:r.dkLen,!0)));DI.shake128=Lx(31,168,16),DI.shake256=Lx(31,136,32);const{sha3_512:Fx}=DI,Ux=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function Bx(e){let t=0n;for(const n of e.values())t=(t<<8n)+BigInt(n);return t}const Wx=(e="")=>Bx(Fx(e)).toString(36).slice(1),Gx=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),Vx=({globalObj:e=(void 0!==sd?sd:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Ux(32,t):Ux(32,t);return Wx(r).substring(0,32)},Yx=e=>()=>e++,Hx=({random:e=Math.random,counter:t=Yx(Math.floor(476782367*e())),length:n=24,fingerprint:r=Vx({random:e})}={})=>function(){const i=(e=>Gx[Math.floor(e()*Gx.length)])(e),o=Date.now().toString(36),s=t().toString(36),a=Ux(n,e);return`${i+Wx(`${o+a+s+r}`).substring(1,n)}`},zx=Hx();PI.getConstants=()=>({defaultLength:24,bigLength:32}),PI.init=Hx,PI.createId=zx,PI.bufToBigInt=Bx,PI.createCounter=Yx,PI.createFingerprint=Vx,PI.isCuid=(e,{minLength:t=2,maxLength:n=32}={})=>{const r=e.length,i=/^[0-9a-z]+$/;try{if("string"==typeof e&&r>=t&&r<=n&&i.test(e))return!0}finally{}return!1};const{createId:qx,init:Kx,getConstants:Jx,isCuid:Zx}=PI;var Xx=qx;const Qx=xd("getUniqueId"),ek=({reply:e,sourceServiceId:t})=>(Qx(`Generating unique id for service "${t}"`),e({success:[Xx()]})),tk=xd("getActiveServices"),nk=async({transport:e,sourceServiceId:t,reply:n})=>{if(tk(`Received GetServices request from ${e} [${t}]`),e===Wu.WS){let e=xv.getActiveServices();const r=II(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===Wu.WS){if(!r?.extraInfo.user?.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(xv.isInternalKemuService),o=e.filter((e=>e.devMode&&xv.isNotInternalKemuService(e))),s=e.filter((e=>xv.isOfficialKemuService(e)&&xv.isNotInternalKemuService(e)&&xv.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=e.filter((e=>xv.isNotDevService(e)&&xv.isNotInternalKemuService(e)&&!xv.isOfficialKemuService(e))),c=await(async e=>{const{features:t}=await pI(e);return t})(r.extraInfo.user?.wsApiKey),l=c?.hub_services??0,u=s.slice(0,-1!==l?l:s.length);-1!==l&&(i=s.slice(l).map((e=>({name:e.name,version:e.version,svgIcon:e.svgIcon,color:e.color,description:e.description,title:e.title,shortTitle:e.shortTitle})))),e=[...t,...o,...u,...a]}const o=xv.getFailedServices().map((e=>({name:e.name,version:e.version,description:e.description,title:e.title,status:e.status,errorMsg:e.errorMsg,errorCode:e.errorCode,internal:xv.isInternalKemuService(e),svgIcon:e.svgIcon,color:e.color,shortTitle:e.shortTitle})));n({success:[{available:e.map((e=>{const{widgetUIContents:t,...n}=e;return{...n}})),failed:o,installed:i}]})}};let rk="runtime",ik=null;const ok=()=>rk,sk=xd("getSystemInfo"),ak=async({reply:e})=>{sk("Received GetSystemInfo request"),e({success:[await(async()=>({platformArch:Ku(),isDesktopHub:"desktop"===ok(),isRuntimeHub:"runtime"===ok(),hubVersion:Yy,...ik?{updateAvailable:ik}:{}}))()]})},ck=xd("removeService"),lk=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,o=r.version;if(!i)return n({error:"No service name provided"});if(!o)return n({error:"No service version provided"});const s=xv.getAllServiceVersions(i),a=s.find((e=>e.info.version===o));if(!a)return n({error:"Service not found"});ck(`Removing ${s.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await xv.uninstallService(a.info.name,a.info.version),c){const e=II(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.user?.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});ck(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await hI(`${dI()}/v1/organization/validate/uninstall_hub_service`,e,{"Content-Type":"application/json"});if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(ck(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:o}}]})},uk=xd("getDecryptedEdgeApiKey"),dk=({reply:e})=>(uk("Getting decrypted edge API key"),e({success:[lI().globalApiKey]})),hk=({reply:e})=>{uk("Getting hub config");const t=lI();return e({success:[{kemuApiKey:t.globalApiKey,environment:t.environment}]})};let fk,pk,gk,mk,yk;const vk=e=>e.transport===Wu.IPC&&(e.reply({error:"Transport is not allowed to call this function"}),!0);var bk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretNames;if(!r||!n)return e.reply({error:"Invalid request parameters"});if(!fk)return e.reply({error:"Get recipe secrets function not set"});const i=await fk({...t[0]}),o={};for(const e of r)o[e]=e in i?i[e]:null;const s=[{secrets:o}];e.reply({success:s})},wk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretsMap;if(vk(e))return;if(!pk)return e.reply({error:"Add recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await pk({recipeUuid:n,secretsMap:r})}];e.reply({success:i})},Sk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretName;if(vk(e))return;if(!gk)return e.reply({error:"Delete recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await gk({recipeUuid:n,secretName:r})}];e.reply({success:i})},_k=async e=>{const t=e.args[0].recipeUuid;if(!mk)return e.reply({error:"Get recipe secret mappings function not set"});if(!t)return e.reply({error:"Invalid request parameters"});const n=[{secrets:await mk({recipeUuid:t})}];e.reply({success:n})},Ik=async e=>{const t=e.args,n=t[0].hubServiceName,r=t[0].secrets;return yk?n&&r?Array.isArray(r)?(await yk({hubServiceName:n,secrets:r}),void e.reply({success:[]})):e.reply({error:'Expected "secrets" to be an array'}):e.reply({error:"Invalid request parameters"}):e.reply({error:"Add service secret function not set"})};let xk,kk,Ek;const Ck=e=>e.transport===Wu.IPC&&(e.reply({error:"You are not allowed to manage secrets using this transport"}),!0);var $k=async e=>{if(e.args,Ck(e))return;if(!Ek)return e.reply({error:"Get hub secrets function not set"});const t=[{contexts:await Ek()}];e.reply({success:t})},Ok=async e=>{const t=e.args;if(Ck(e))return;if(!xk)return e.reply({error:"Add hub secret function not set"});const n=[{contexts:await xk(t[0])}];e.reply({success:n})},Nk=async e=>{const t=e.args;if(Ck(e))return;if(!kk)return e.reply({error:"Delete hub secret function not set"});const n=[{contexts:await kk(t[0])}];e.reply({success:n})};const Tk=k(V(import.meta.url));let Ak=null;const Mk=xd("hub"),Pk=new function(){const e={};let t,n=console.log;const r={};let i="hub";const o={},s=e=>!o[e],a=(e,t,n,r,i,o)=>{let a=sb?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:o.success?o.success:[o],messageId:t,type:o.success?"response":"error"}};return s(r)&&(a=Fb.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(i,o,s,c)=>{if(!c)return!1;const l=c;if(e[l.messageId]){const t=e[l.messageId];return t&&(clearTimeout(t.timer),t.fulfilled||(t.fulfilled=!0,"response"===l.type?t.resolve(l.args):"error"===l.type&&t.reject(l.args[0])),delete e[l.messageId]),!0}if("execute"!==l.type&&n&&n(`No pending execution found for message id "${l.messageId}"`),"execute"===l.type){const e=r[l.functionName];if(e){const r=e=>{a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,e)};if(t&&!t({args:l.args,functionName:l.functionName,transport:i,messageId:l.messageId,sourceServiceId:s.sourceServiceId,reply:r,send:o}))return n&&n(`Function "${l.functionName}" not allowed to be invoked by client [${s.sourceServiceId}]`),r({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;e({transport:i,args:l.args,reply:r,messageId:l.messageId,sourceServiceId:s.sourceServiceId,send:o})}else{const e=`Function "${l.functionName}" not found.`;n&&n(e),a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(t,r,o,a,c,l)=>{if(!o){const e="No send buffer function provided.";throw n&&n(e),e}Ub+=1;const u=`${i}-${Ub}-exec-${t.substring(0,10)}`,d={messageId:u,functionName:t,send:o,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=sb?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:t,args:r,messageId:u,type:"execute"}};s(c)&&(h=Fb.encode(f,a,c)),e[u]=d,n&&n(`Calling remote function "${t}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete e[u]):0===l?.timeout||p||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=e[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${t} Timed out`)),delete e[u]}),l?.timeout||3e4)),o(h,{sourceServiceId:a,targetServiceId:c,msg:f}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},registerFunctionsMiddleware:e=>{t=e},unregisterAllFunctions:()=>{Object.keys(r).forEach((e=>{delete r[e]}))},getTransportSendFunction:t=>{const n=e[t];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>e,rejectAllPending:t=>{Object.keys(e).forEach((n=>{const r=e[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(t),delete e[n])}))},broadcast:(e,t,r,o)=>{Ub+=1;const a=`${i}-${Ub}-multicast-${e.substring(0,10)}`;let c=sb?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=s(r[0].serviceId);u&&(c=Fb.encode(l,o,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(u=s(i.serviceId),u&&(c=Fb.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:o,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{o[e]=t}}}("hub");bI=Pk,Pk.setLogger(Mk);const Dk={[Uu.RebootToInstallUpdate]:null,[Uu.GetFileContentFromCacheId]:null,[Uu.SaveRecipeToFile]:null},jk=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=II(n.targetServiceId);if(!r)return Mk(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,Wu.IPC;const i=t.json?.messageId;return Mk(`Forwarding message from ${n.sourceServiceId} to ${n.targetServiceId}, msgId: ${i}`),r.send(n.rawMessage,{sourceServiceId:n.sourceServiceId,targetServiceId:n.targetServiceId,msg:{json:t.json}}),!0}return!1},Rk=({sourceServiceId:e,args:t})=>{const n=xv.getServiceBySessionId(e);if(n){const r=xI(n.info.name,n.info.version),i=xI(n.info.name,"*");if(!r.length&&!i.length)return;const o=[...r,...i],s={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};Pk.broadcast(Uu.BroadcastEvent,[s],o,0)}},Lk=async({args:e,reply:t})=>{const n=e[0];if(!n)return Mk("Invalid config for SendToRecipe"),t({error:"Invalid config for SendToRecipe"});const r=(i=n.recipePoolId,Object.values(wI).find((e=>e.extraInfo.recipe?.poolId===i))||null);var i;if(!r)return Mk(`No client found for recipe pool id ${n.recipePoolId}`),t({error:`No client found for recipe pool id "${n.recipePoolId}"`});try{const e=Pk.execute(Uu.SendToRecipe,[n],r.send,0,r.serviceSessionId,{async:!n.waitForResponse,timeout:n.timeout});n.waitForResponse?t({success:await e}):t({success:[]})}catch(e){return Mk(`Error sending to recipe ${n.recipePoolId}: ${e?.message||e}`),t({error:e?.message||"There was an error sending to the recipe"})}},Fk=e=>{const{send:t,transmission:n,json:r}=e;Mk(`Raw message Id received from WS: ${r?.messageId}`),jk(Wu.WS,e)||Pk.processMessage(Wu.WS,t,n,r)},Uk=e=>{const t=(n=e,`${Fu.SocketAcknowledge}${n}`);var n;W_(e,t)},Bk=(e,t)=>{Mk(`Received unknown command [${t}] from service ${e}`)},Wk=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,o=n,s=t[0],a=s?.user?.apiKey||lI().globalApiKey;if(!a)return Mk(`Received ACK from WS service ${n} but no API key was provided`),i({error:"No API key was provided",errCode:"MISSING_API_KEY"});s.user?.id&&iv.setGlobalUserId(s.user?.id),await EI({serviceSessionId:n,transport:Wu.WS,send:r,terminateFn:()=>{V_(n)},extraInfo:{websocketId:o,recipe:s.recipe,user:{wsApiKey:a,userEmail:s.user?.email,userId:s.user?.id}}}),i({success:[]})},Gk=e=>{Mk(`WS Client ${e} disconnected`),$I(e)},Vk=e=>1===e.sourceServiceId?e.functionName===Uu.GetFileContentFromCacheId:e.functionName===Uu.SocketAckResponse||e.functionName===Uu.ServiceManifest||e.functionName===Uu.SubscribeToService||(!!II(e.sourceServiceId)||(e.reply({error:`Session id "${e.sourceServiceId}" not found. Please acknowledge the session first.`}),!1)),Yk=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==Wu.IPC){var i;Mk(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=xv.getMatchingDevService(n.name,n.version,"stopped");if(t){Mk(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const o=II(t.info.sessionId);if(!o)return void Mk(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);o.send=r,wI[i=e]?delete wI[i]:vI(`Could not find source client with session id ${i}`),jb(e,t.info.sessionId);const s=await Jy(n,n.path);t.info={...t.info,...s},Mk(`Updating manifest for dev service ${t.info.sessionId}`),xv.setServiceManifest(t.info.sessionId,s,"running"),Mk(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Db(t.info.sessionId,(e=>`${Fu.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=wI[e];t?t.isDevClient?(t.disconnected=!1,t.transport===Wu.IPC&&(kI(),CI(e))):vI(`Client with session id ${e} is not a dev client`):vI(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{xv.addDevService(e,n,"running");const t=II(e);t?t.isDevClient=!0:EI({serviceSessionId:e,transport:Wu.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}Mk(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var Hk=async e=>{var t;Mk("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",rk=t;const n=e?.ipc?.appSpace||"kemu.",r=e?.ipc?.id||"widgets";if(!e.serviceUrl)throw new Error("Missing service url, please set the `apiUrl` option.");e.errorTracker&&iv.setTracker(e.errorTracker),(e=>{cI={...cI,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey,environment:e.environment}),Pk.registerFunctionsMiddleware(Vk),e.secrets?.serviceSecrets&&(e=>{yk=e})(e.secrets.serviceSecrets.addServiceSecretFn),e.secrets?.recipeSecrets&&((e=>{fk=e})(e.secrets.recipeSecrets.getRecipeDecryptedSecretsFn),(e=>{pk=e})(e.secrets.recipeSecrets.addRecipeSecretFn),(e=>{gk=e})(e.secrets.recipeSecrets.deleteRecipeSecretFn),(e=>{mk=e})(e.secrets.recipeSecrets.getRecipeSecretMappingsFn)),e.secrets?.hubSecrets&&((e=>{Ek=e})(e.secrets.hubSecrets.getHubSecretsFn),(e=>{xk=e})(e.secrets.hubSecrets.addHubSecretsFn),(e=>{kk=e})(e.secrets.hubSecrets.deleteHubSecretFn)),Pk.registerFunction(Uu.GetServiceContents,aI),Pk.registerFunction(Uu.GetServices,nk),Pk.registerFunction(Uu.GetSystemInfo,ak),Pk.registerFunction(Uu.ShowSecretsConfigScreen,(async({args:t,reply:n})=>{const[{name:r,version:i}]=t;e?.onShowSecretsScreen?(await e.onShowSecretsScreen(r,i),n({success:[]})):n({error:"This hub does not support showing secrets configuration screens",errCode:"GUI_NOT_SUPPORTED"})})),Pk.registerFunction(Uu.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Wu.WS){const[e]=n,i=II(r);if(!i)return t({error:`Session id "${r}" not found`});Mk(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),Pk.registerFunction(Uu.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Wu.WS){const[e]=n,i=II(r),o=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(Mk(`Service ${r} subscribing to "${o.serviceName} (${o.version})"`),"hub"===o.serviceName)return i.addSubscription(o),void t({success:[]});if(!i.addSubscription(o))return Mk(`Service ${r} already subscribed to "${o.serviceName} (${o.version})", ignoring request.`),t({success:[]});const s=xv.getMatchingService(o.serviceName,o.version);if(!s)return Mk(`Service ${o.serviceName} ${o.version} not active yet`),t({success:[]});if(!s.info.eventEmitter)return Mk(`Service ${o.serviceName} ${o.version} does not have an event emitter, removing subscription`),i.removeSubscription(o),t({error:`Service "${o.serviceName} (${o.version})" does not produce events`});const a=II(s.info.sessionId);return a?.extraInfo.ipcSocketId&&(Mk(`Sending Broadcast START command to service ${s.info.sessionId}`),Db(a?.extraInfo.ipcSocketId,Fu.BroadcastStart)),t({success:[]})}})),Pk.registerFunction("stopService",H_),Pk.registerFunction("removeService",q_),Pk.registerFunction("launchService",J_),Pk.registerFunction("getMatchingServices",X_),Pk.registerFunction("getSecretsValues",tI),Pk.registerFunction(Uu.GetMappedSecrets,oI),Pk.registerFunction(Uu.BroadcastEvent,Rk),Pk.registerFunction(Uu.ServiceManifest,Yk),Pk.registerFunction(Uu.ChooseDirectoryDialog,AI),Pk.registerFunction(Uu.ChooseFileDialog,MI),Pk.registerFunction(Uu.GetUniqueId,ek),Pk.registerFunction(Uu.SendToRecipe,Lk),Pk.registerFunction(Uu.GetDecryptedEdgeApiKey,dk),Pk.registerFunction(Uu.GetHubConfig,hk),Pk.registerFunction(Uu.SocketAckResponse,Wk),Pk.registerFunction(Uu.UninstallService,lk),Pk.registerFunction(Uu.GetRecipeDecryptedSecretsValues,bk),Pk.registerFunction(Uu.GetRecipeSecretMappings,_k),Pk.registerFunction(Uu.AddRecipeSecretMapping,wk),Pk.registerFunction(Uu.DeleteRecipeSecretMapping,Sk),Pk.registerFunction(Uu.GetHubSecrets,$k),Pk.registerFunction(Uu.AddHubSecrets,Ok),Pk.registerFunction(Uu.DeleteHubSecret,Nk),Pk.registerFunction(Uu.AddServiceSecret,Ik),Object.entries(Dk).forEach((([e,t])=>{t?Pk.registerFunction(e,t):(Mk(`Skipping registration of "${e}" because it's not implemented`),Pk.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),(e=>{Tb=e})((e=>{const{send:t,transmission:n,json:r}=e;Mk(`Raw message Id received from IPC: ${r?.messageId}`),jk(Wu.IPC,e)||Pk.processMessage(Wu.IPC,t,n,r)})),G_(Fk),F_(Uk),B_(Bk),U_(Gk),(e=>{Nb=e})(NI),(e=>{$b=e})((e=>{const t=(e=>`${Fu.IpcAcknowledge}${e}`)(e);Db(e,t)})),(e=>{Ob=e})((e=>{Mk(`IPC socket [${e}] disconnected`);const t=II(e);if(t){Mk(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=xv.getServiceBySessionId(t.serviceSessionId);xv.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,kI()):$I(t.serviceSessionId)}})),await(e=>(e?.ipcId&&(rb.config.id=e.ipcId),e?.ipcAppSpace&&(rb.config.appspace=e.ipcAppSpace),new Promise((e=>{rb.serve((()=>{Cb.info("IPC Server Initiated"),rb.server.on("data",((e,t)=>{const n=Ab[t.id];n?(Cb.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Mb(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Cb.data(`Received command from client [${t.id}]: ${e.command}`),void(Nb&&Nb(t.id,e.command,n));e.klMessage&&Tb&&Tb({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Cb.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),rb.server.on("connect",(e=>{const t=By();Cb.info(`New client connected. Registered as "${t}"`),e.id=t,Ab[t]={socket:e,activeMessage:null,disconnectHandler:()=>Pb(t)},e.on("close",Ab[t].disconnectHandler),$b&&$b(t)})),rb.server.on("disconnect",(e=>{Pb(e.id)})),rb.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),rb.server.start()}))))({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await L_(e?.ws?.port||5368);const i=e?.defaultServicesPath||I.resolve(Tk,"defaultServices");Ak=i;const o=process.env.DEV_SESSION_ID;xv.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),xv.setEnableServiceLogsConfig(!!e?.enableServiceLogs),e?.servicesInstallPath&&(e=>{Xy=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Qy=e})(e.testServicesInstallPath);const s=ev(),a=tv(),c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=s,t.__KEMU_USER_TEST_SERVICES_PATH=a,t.__KEMU_SERVICE_URL=lI().serviceUrl,t.__KEMU_ENVIRONMENT=lI().environment,t};e?.getServiceSecretsFn?(xv.setGetSecretsFunction(e.getServiceSecretsFn),nI(e.getServiceSecretsFn)):(xv.setGetSecretsFunction(c),nI(c)),(e=>{iI=e})(e?.getMappedSecretsFn?e.getMappedSecretsFn:async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{})),xv.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return H("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await xv.loadServices(i,{fixedSession:o?parseInt(o):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0,enableLogs:!0}),null!==e?.servicesInstallPath&&(await Zy(s)||await m(s,{recursive:!0}),await xv.loadServices(s,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,enableLogs:!!e?.enableServiceLogs}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await xv.launchServices({noSpawningList:l||[]}),Mk("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&(e=>{TI=e})({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},zk=e=>{if(e===Wu.WS)return{handleWebsocketConnectionEvent:Uk,handleWebsocketClientDisconnectionEvent:Gk,handleWebsocketMessage:Fk,handleWebsocketClientCommand:Bk,getRemoteInvoke:()=>Pk}},qk=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(xv.getAllServices().every((e=>"running"===e.status))&&e.every((e=>"running"===xv.getMatchingService(e.name,e.version)?.status)))return n();t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let Kk;const Jk=Ml("run"),Zk=Yu(),Xk=1e3,Qk=_(process.argv.slice(2)),eE=e=>"number"==typeof e?{type:me.Number,value:e}:"string"==typeof e?{type:me.String,value:e}:"boolean"==typeof e?{type:me.Boolean,value:e}:Array.isArray(e)?{type:me.Array,value:e}:e;global.ImageData=J;const tE=e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer;ke({createCanvas:(e,t)=>X(e,t),loadImage:async e=>{let t=e;if(tE(e)){const n=e;t=Buffer.from(n.data)}const n=await Z(t),r=X(n.width,n.height).getContext("2d");r.drawImage(n,0,0,n.width,n.height);return r.getImageData(0,0,n.width,n.height)}});const nE=(e,t)=>"*"===e?ao.onAnyGlobalVariableChange(t):ao.onGlobalVariableChange(e,t),rE=(e,t,n)=>ao.setGlobalVariable({name:e,value:t,disableChangeNotifications:n?.disableChangeNotifications||!1,disableDefineNotifications:n?.disableDefineNotifications||!1,doNotOverrideExisting:n?.doNotOverrideExisting||!1}),iE=e=>{ao.deleteGlobalVariable({name:e})},oE=()=>ao.getAllVariables(),sE=e=>ao.getGlobalVariable(e),aE=e=>Wi(e),cE=e=>async()=>{throw new Error(`${e} not implemented`)},lE={createImageDataLike:(e,t,n,r="srgb")=>{let i;return i=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:i,width:t,height:n,colorSpace:r,_kemuType:me.ImageData}},loadImageFile:async e=>{const t=await Z(e),n=X(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)},encodeImageData:async(e,t="jpeg",n)=>{const r=X(e.width,e.height);let i;return r.getContext("2d").putImageData(e,0,0),i="png"===t?await r.encode(t):await r.encode(t,n),i}};var uE={start:async r=>{r=r||{};const i=r?.recipePath||Qk.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!i)throw new Error("`recipePath` not provided. Please specify it in the config object, via a command line argument [--recipePath] or as an environment variable [KEMU_EDGE_RECIPE_PATH].");const{parsed:o,error:s}=await e({path:z(q(i),".env")});s&&console.warn(`Failed to load .env file: ${s.message}. This is not an error, it just means that the .env file is not present or is not readable.`);const a=r.apiKey||process.env.KEMU_API_KEY;if(!a)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");const c=i.endsWith(".json")||i.endsWith(".kemu"),l=c?K(i):i,u=c?i:z(l,"recipe.kemu"),d=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(q(u),"utf-8"));if(!d)throw new Error("Failed to parse recipe file");if(!d.author?.id)throw new Error("Missing required author ID in recipe file.");const{serviceUrl:h,apiKey:f,environment:p}=((e,t)=>{const n=qc(e,t),r=Buffer.from(n,"base64").toString("utf8"),[i,o,s]=r.split("<@>");if(!o||!i||!s)throw new Error("Invalid API key.");return{serviceUrl:o,apiKey:i,environment:s}})(d,a);await oc();const g={id:d.uuid||String(Date.now()),version:1,author:d.author.id};(e=>{fo=e})(console);const m=zk(_e.WS),y=(e,t)=>{if(t)m?.handleWebsocketMessage({send:b,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;m?.handleWebsocketClientCommand(Xk,t)}},v=(bl={instanceServiceId:Xk,sendBuf:y,sendCmd:y,triggerOnCommand:(...e)=>wl(...e),triggerOnConnected:()=>Sl(),triggerOnDisconnected:()=>_l(),triggerOnMessageReceived:(...e)=>Il(...e)},bl);const b=(e,t)=>{if(t)v.triggerOnMessageReceived({send:y,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;v.triggerOnCommand(t)}},w=zu(),S=m.getRemoteInvoke();w.disableServiceEncoding(0,!0),S.disableServiceEncoding(Xk,!0);const _=Object.values(d.blocks[pe].gates).filter((e=>e.type===Ke.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),I=_.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),x=z(l,"services"),k=await n(x).then((()=>!0)).catch((()=>!1));if(I.length>0&&!k)throw new Error("Services directory not found but required services are defined in the recipe. Please make sure there is a `services` directory in the recipe root and add the services you want to use to it.");await Hk({globalApiKey:f,serviceUrl:h,recipeRootPath:l,servicesInstallPath:k?z(l,"services"):null,noDefaultServices:!0,environment:p,ws:{disabled:!0},secrets:{recipeSecrets:{getRecipeDecryptedSecretsFn:async()=>({...o}),getRecipeSecretMappingsFn:cE("getRecipeSecretMappingsFn"),addRecipeSecretFn:cE("addRecipeSecretFn"),deleteRecipeSecretFn:cE("deleteRecipeSecretFn")}},ipc:{appSpace:"kemu-runner.",id:g.id}}),Jk("Waiting for services to run"),await qk(I),Jk("All services are running"),Bc(Zk),Yc(),aa((e=>{Jk("Global processing state changed: ",e)})),d.globalVariables&&(d.globalVariables=await zc(d.globalVariables));const E=await Lc(d,"runner",g.version,g.author,mr.Desktop);return Kk=E,Hu(E),await Gu({apiKey:f,id:d.author.id}),new Promise(((e,t)=>{var n;Vu("acknowledged",(async()=>{await Zk.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Uc(E);if(n.length>0){const e=`Some widgets failed to initialize: ${n.join(", ")}`;return t(e)}await i().catch((e=>{console.error("Error invoking recipe loaded widgets: ",e)})),Jk("Recipe started"),e({sendToInputWidgetAndWaitForOutput:(e,t)=>{const n=eE(t);return r({inputName:e,data:n,waitForOutputChild:!0})},sendToInputWidget:(e,t)=>{const n=eE(t);return r({inputName:e,data:n,waitForOutputChild:!1})},globalVariables:{onChange:nE,setValue:rE,getValue:sE,delete:iE,getAll:oE},status:{onChange:aE},edgeFunctions:{register:Ga.registerFunctionHandler,unregister:Ga.unregisterFunctionHandler,clearAll:Ga.clearAllHandlers}})})),v.triggerOnConnected(),v.triggerOnCommand((n=Xk,`${be.SocketAcknowledge}${n}`))}))},terminate:async()=>{Kk&&await Fc(Kk)}};export{me as DataType,uE as default,tE as isBinaryFile,lE as utils};
|