@kemu-io/edge-runtime 1.2.5 → 1.2.6
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 +2 -2
package/runner.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{config as e}from"dotenv";import{readFile as t,access as n}from"node:fs/promises";import{nanoid as r}from"nanoid";import i from"jsonp";import s from"crypto-js";import o from"emittery";import"axios";import a from"jszip";import c from"util";import l from"mustache";import d,{scryptSync as u,createDecipheriv as p,createHash as g}from"crypto";import{satisfies as h}from"compare-versions";import f from"debug";import m,{join as y,dirname as v,resolve as b}from"path";import"node-ipc";import{mkdir as S,readFile as w,access as I,constants as _,readdir as $,rm as C}from"fs/promises";import k from"minimist";import E from"tty";import x,{homedir as A}from"os";import N from"net";import P from"tls";import O,{promises as T}from"fs";import L from"dgram";import B from"stream";import D from"zlib";import j from"buffer";import U from"events";import R from"https";import F from"http";import M,{fileURLToPath as W}from"url";import G from"node:os";import{spawn as V}from"child_process";import{join as H,resolve as z,dirname as q}from"node:path";import{ImageData as K,loadImage as J,createCanvas as Y}from"@napi-rs/canvas";var X;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(X=X||(X={}));const Z="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,Q="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,ee="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,te={};let ne=0,re="";const ie=e=>te[e]?te[e]:null,se=(e,t)=>{const n=ie(e);if(!n)return n;return n.blocks[t]||null},oe=(e,t,n)=>{const r=se(e,t);if(!r)return r;return r.gates[n]},ae=(e,t)=>{let n=r(4);for(;te[n];)n=r(4);const i=(s=e,JSON.parse(JSON.stringify(s)));var s;return i.logs="",i.addLog=e=>{i.logs+=`${(()=>{const e=Date.now();if(e!==ne){const t=new Date;ne=e,re=t.toJSON()}return re})()}:: ${e}\n`},i.dbInfo={...t},te[n]=i,n},ce="interrupt_port",le="main.js",de="state.json",ue="{#}",pe="UI:",ge="default";var he,fe,me,ye,ve,be,Se,we;let Ie;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(he||(he={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(fe||(fe={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(me||(me={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ye||(ye={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(ve||(ve={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(be||(be={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(Se||(Se={})),function(e){e.IPC="ipc",e.WS="ws"}(we||(we={}));const _e=()=>{if(!Ie)throw new Error("CanvasManager not set");return Ie},$e=e=>{Ie=e},Ce=(e,t)=>_e().createCanvas(e,t),ke=e=>Z?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Ee=e=>_e().loadImage(e),xe="-",Ae=`inner${xe}`,Ne=`outer${xe}`,Pe=`${Ne}input${xe}`,Oe=`${Ne}output${xe}`,Te=`${Ae}input${xe}`,Le=`${Ae}output${xe}`,Be=e=>(new TextEncoder).encode(e),De=e=>e===ce,je=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Ue=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.top&&void 0!==e.left&&"number"==typeof e.width&&"number"==typeof e.height&&"number"==typeof e.top&&"number"==typeof e.left,Re=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Fe=e=>"number"==typeof e?fe.Number:"string"==typeof e?fe.String:"boolean"==typeof e?fe.Boolean:Array.isArray(e)?fe.Array:je(e)?fe.ImageData:e&&void 0!==e.duration&&void 0!==e.length&&void 0!==e.numberOfChannels&&void 0!==e.sampleRate&&"function"==typeof e.getChannelData&&"AudioBuffer"===e.constructor.name?fe.AudioBuffer:e&&void 0!==e.byteLength?fe.ArrayBuffer:Ue(e)?fe.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?fe.Point:(e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer)(e)?fe.BinaryFile:fe.JsonObj,Me=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Fe(n[e]);t[e]=r}return t},We=(e,t,n)=>"inner"===e?"input"===t?`${Te}${n}`:`${Le}${n}`:"input"===t?`${Pe}${n}`:`${Oe}${n}`,Ge=e=>{const t=(e||"")?.split("_");if(t.length<3)throw new Error(`Unknown child identifier format [${e}]`);const n=t[0];return{portType:t[1],widgetId:n,portName:t[2]}},Ve=async e=>{try{return new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace})}catch(t){console.warn("Failed to create ImageData from info, assuming raw image data",t);return await Ee(e.data)}};var He,ze;!function(e){e.Action="action",e.CustomInput="customInput"}(He=He||(He={})),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.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",e.imageFilter="imageFilter",e.recipeLoad="recipeLoad",e.note="note",e.stringify="stringify",e.templateString="templateString",e.expressionEval="expressionEval",e.rescue="rescue",e.objectCombine="objectCombine",e.loop="loop"}(ze=ze||(ze={}));const qe={};let Ke;const Je=async e=>{const t=qe[e],n={name:ce,type:fe.Boolean};if(t){const r={name:t.portName},i=t.data||{type:fe.Boolean,value:!0};Ke?(await Ke(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...i,timestamp:Date.now()},[n]),"timeout"===t.type&&Ye(e)):console.warn("Interrupt service has not been initialized")}},Ye=e=>{const t=qe[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete qe[e],!0)};var Xe={interruptHandler:Je,createInterrupt:(e,t,n,i,s,o,a,c)=>{if(c&&qe[c])throw new Error("The given interrupt id already exists");const l=c||r().replace(/_/g,"-");if("interval"===e&&!o.interval)throw new Error(`Invalid interval. Expected a number greater than 0, but got '${o.interval}'`);if("timeout"===e&&!o.timeout)throw new Error(`Invalid timeout. Expected a number greater than 0, but got '${o.timeout}'`);if(qe[l]={data:a,portName:s,recipePoolId:t,targetWidgetId:i,thingId:n,type:e},"interval"===e)qe[l].timerRef=setInterval((async()=>await Je(l)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);qe[l].timerRef=setTimeout((async()=>await Je(l)),o.timeout)}return l},destroyInterrupt:Ye,destroyAllInterrupts:()=>{Object.keys(qe).forEach(Ye)},setInvokeChildGateCb:e=>{Ke=e}};const Ze=[10001,"Invalid `sourcePort` parameter"],Qe=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],et=[10110,"No storage medium has been loaded, call `loadMedium()` first"],tt=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?c.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),nt=()=>({inputName:"",dataType:fe.Anything}),rt="output",it={processEvent:async(e,t)=>{const n=t.getState(),r={...nt(),...n};if(e.type===r.dataType||r.dataType===fe.Anything)return t.nextWidget(rt,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...nt(),...e};return[{name:rt,type:t.dataType}]},getInputNames:()=>[]},st=Object.freeze({in:"in",reset:"reset",increment:"increment"}),ot="output";var at={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(tt(Ze));const i={currentValue:0,increment:1,...r.getState()};let s=i.increment,o=i.currentValue;const a=await r.getParentAtPort(st.increment);if(t.name===st.increment)return void(n.data.type===fe.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(s=e)}if(t.name===st.reset)return r.setState({...i,currentValue:0});o+=s,r.setState({currentValue:o,increment:s});const c={type:fe.Number,value:o};return r.nextGate(ot,c)},getInputNames:()=>[{name:st.in,type:fe.Anything},{name:st.reset,type:fe.Anything},{name:st.increment,type:fe.Number}],getOutputNames:()=>[{name:ot,type:fe.Number}]};const ct=Object.freeze({in:"in",reset:"reset"}),lt="output";var dt={onParentEvent:async(e,t,n,r)=>{const i={updatedAt:0,elapsed:0,...r.getState()},s=Date.now(),o=s-(i.updatedAt||s);return t.name===ct.reset?r.setState({...i,updatedAt:s,elapsed:0}):(r.setState({updatedAt:s,elapsed:o}),r.nextGate(lt,{type:fe.Number,value:o}))},getInputNames:()=>[{name:ct.in,type:fe.Anything},{name:ct.reset,type:fe.Anything}],getOutputNames:()=>[{name:lt,type:fe.Number}]};const ut=Object.freeze({data:"data",evaluation:"evaluation"}),pt="then",gt="else";var ht={onParentEvent:async(e,t,n,r)=>{const i={value:5,condition:"Equal",useDataPort:!1,...r.getState()},s=n.data.value,o=!isNaN(Number(s)),a="string"==typeof s;if(!i.useDataPort&&(n.data.type===fe.Number||n.data.type===fe.String||n.data.type===fe.Boolean||n.data.type===fe.Anything&&o||n.data.type===fe.Anything&&a)){let e=!1;return("Equal"===i.condition&&(n.data.value==i.value||n.data.type===fe.Boolean&&n.data.value.toString()===i.value.toString())||"Not Equal"===i.condition&&(n.data.value!==i.value||n.data.type===fe.Boolean&&n.data.value!==i.value.toString())||"Greater"===i.condition&&n.data.type===fe.Number&&n.data.value>Number(i.value)||"Less"===i.condition&&n.data.type===fe.Number&&n.data.value<Number(i.value)||"Starts With"===i.condition&&String(n.data.value).startsWith(String(i.value))||"Ends With"===i.condition&&String(n.data.value).endsWith(String(i.value))||"Includes"===i.condition&&String(n.data.value).includes(String(i.value))||"Matches"===i.condition&&String(n.data.value).match(String(i.value)))&&(e=!0),e?r.nextGate(pt,n.data):r.nextGate(gt,n.data)}if(t.name===ut.evaluation&&(n.data.type===fe.Number||n.data.type===fe.String||n.data.type===fe.Boolean||n.data.type===fe.Anything&&(o||a))&&(i.$lastValue=n.data.value,i.$lastInputDataType=n.data.type,r.setState({...i})),t.name===ut.data){let e=!1;return("Equal"===i.condition&&(i.$lastValue==i.value||i.$lastInputDataType===fe.Boolean&&i.$lastValue?.toString()===i.value.toString())||"Not Equal"===i.condition&&(i.$lastValue!==i.value||i.$lastInputDataType===fe.Boolean&&i.$lastValue!==i.value.toString())||"Greater"===i.condition&&i.$lastInputDataType===fe.Number&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&i.$lastInputDataType===fe.Number&&Number(i.$lastValue)<Number(i.value)||"Starts With"===i.condition&&String(i.$lastValue).startsWith(String(i.value))||"Ends With"===i.condition&&String(i.$lastValue).endsWith(String(i.value))||"Includes"===i.condition&&String(i.$lastValue).includes(String(i.value))||"Matches"===i.condition&&String(i.$lastValue).match(String(i.value)))&&(e=!0),r.setState({...i,$lastValue:void 0,$lastInputDataType:void 0}),e?r.nextGate(pt,n.data):r.nextGate(gt,n.data)}},getInputNames:e=>e.useDataPort?[{name:ut.data,type:fe.Anything,triggerPort:!0},{name:ut.evaluation,type:[fe.Number,fe.String,fe.Boolean]}]:[{name:"in",type:[fe.Number,fe.String,fe.Boolean]}],getOutputNames:e=>e.$lastOutputDataType?[{name:pt,type:e.$lastOutputDataType},{name:gt,type:e.$lastOutputDataType}]:[{name:pt,type:[fe.Number,fe.String]},{name:gt,type:[fe.Number,fe.String]}]};const ft=Object.freeze({in:"in",reset:"reset"}),mt="out";var yt={onParentEvent:async(e,t,n,r)=>{const i={totalCalls:0,callsLimit:1,...r.getState()};return t.name===ft.reset?r.setState({...i,totalCalls:0}):(i.totalCalls=i.totalCalls+1,i.totalCalls>i.callsLimit?(i.totalCalls=0,r.setState(i),r.nextGate(mt,n.data)):void r.setState(i))},getInputNames:()=>[{name:ft.in,type:fe.Anything},{name:ft.reset,type:fe.Anything}],getOutputNames:()=>[{name:mt,type:fe.Anything}]};const vt=Object.freeze({in:"in"}),bt="then",St="else";var wt={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:10,...r.getState()};if(n.data.type===fe.Number)return n.data.value>=i.min&&n.data.value<=i.max?r.nextGate(bt,n.data):r.nextGate(St,n.data)},getInputNames:()=>[{name:vt.in,type:fe.Number}],getOutputNames:()=>[{name:bt,type:fe.Number},{name:St,type:fe.Number}]};const It=Object.freeze({in:"in"}),_t="out";var $t={onParentEvent:async(e,t,n,r)=>{const i={clamp:!0,...r.getState()},s=Number(n.data.value);if(void 0!==i.fromMax&&void 0!==i.fromMin&&void 0!==i.toMax&&void 0!==i.toMin&&""!==i.fromMax&&""!==i.fromMin&&""!==i.toMax&&""!==i.toMin&&(n.data.type===fe.Number||n.data.type===fe.Anything&&!isNaN(Number(s)))){let e=((e,t,n,r,i)=>(e-t)*(i-r)/(n-t)+r)(s,Number(i.fromMin),Number(i.fromMax),Number(i.toMin),Number(i.toMax));if(isNaN(e))return;return i.clamp&&(e<Number(i.toMin)&&(e=Number(i.toMin)),e>Number(i.toMax)&&(e=Number(i.toMax))),r.nextGate(_t,{type:fe.Number,value:Number(e)})}},getInputNames:()=>[{name:It.in,type:fe.Number}],getOutputNames:()=>[{name:_t,type:fe.Number}]};const Ct=Object.freeze({in:"in"}),kt="out";var Et={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let s=n.data.value;if(n.data.type===fe.Number||n.data.type===fe.Anything||n.data.type===fe.String){if((!isNaN(Number(s))||"string"==typeof s)&&!Array.isArray(s))return"Integer"===i.convertTo?s=parseInt(s):"Decimal"===i.convertTo?s=parseFloat(Number(s).toFixed(i.floatPlaces)):"String"===i.convertTo?s=String(s):"Abs"===i.convertTo?s=Math.abs(Number(s)):"Round"===i.convertTo&&(s=Math.round(Number(s))),r.nextGate(kt,{type:"String"===i.convertTo?fe.String:fe.Number,value:s})}},getInputNames:()=>[{name:Ct.in,type:fe.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?fe.String:fe.Number;return[{name:kt,type:t}]}};const xt=Object.freeze({in:"in"}),At="out";var Nt={onParentEvent:async(e,t,n,r)=>{const i={currentValue:50,min:0,max:100,...r.getState()};let s=!1;return i.currentValue<i.min&&(i.currentValue=i.min,s=!0),i.currentValue>i.max&&(i.currentValue=i.max,s=!0),s&&r.setState(i),r.nextWidget(At,{type:fe.Number,value:i.currentValue})},getInputNames:()=>[{name:xt.in,type:fe.Anything}],getOutputNames:()=>[{name:At,type:fe.Number}]};const Pt=Object.freeze({in:"in",reset:"reset"}),Ot="out";var Tt={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},s={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Pt.reset)return r.setState({...s,lastCalledAt:0});const o=Date.now(),a=o-s.lastCalledAt;return s.lastCalledAt===i.lastCalledAt||a>=s.delayMs&&s.delayMs>0?(s.lastCalledAt=o,r.setState(s),r.nextGate(Ot,n.data)):void 0},getInputNames:()=>[{name:Pt.in,type:fe.Anything},{name:Pt.reset,type:fe.Anything}],getOutputNames:()=>[{name:Ot,type:fe.Anything}]};const Lt="in";var Bt={onParentEvent:async()=>{},getInputNames:()=>[{name:Lt,type:[fe.ImageData,fe.Number]}],getOutputNames:()=>[]};const Dt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),jt=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var Ut={onParentEvent:async(e,t,n,r)=>{const i={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},s=n?.data?.value,o=Array.isArray(s);if(n.data.type===fe.JsonObj||n.data.type===fe.Rect||n.data.type===fe.Point||n.data.type===fe.BinaryFile||n.data.type===fe.Anything||o){let e=!1;for(const t in s){const n=Fe(s[t]),r=!!i.detectedProperties[t],o=i.detectedProperties[t]?.type!==n;if(!r||o){const r=n===fe.JsonObj||n===fe.Rect||n===fe.Point||n===fe.Array;i.detectedProperties[t]={type:n,...r?{shape:Me(s[t])}:void 0},e=!0}}if(o&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:fe.Number}),e&&r.setState(i),s){const e=[];for(const t of i.properties||[]){const n=jt(s,t.label),o=t.label.includes(".");if(void 0!==n){const s=o?Fe(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:fe.Anything;e.push(r.nextGate(t.name,{type:s,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:fe.JsonObj}],getOutputNames:e=>{const t={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...e};return t.properties.map((e=>{const n=void 0!==t.detectedProperties[e.label]?t.detectedProperties[e.label]?.type:fe.Anything,r=t.detectedProperties[e.label]?.shape||void 0,i="string"==typeof e;return{name:i?e:e.name,label:i?e:e.label,type:n,jsonShape:r}}))},getDefaultState:Dt};const Rt="output",Ft="noItem";var Mt={onParentEvent:async(e,t,n,r)=>{const i={index:0,...r.getState()};let s=i.index;const o=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===fe.Anything&&(c||a)||n.data.type===fe.String&&a||n.data.type===fe.Array&&c){s<0&&(s=o.length+s);const e=a?fe.String:Fe(o[s]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==o[s]?r.nextGate(Rt,{value:o[s],type:e}):r.nextGate(Ft,{value:!0,type:fe.Boolean})}},getInputNames:()=>[{name:"in",type:[fe.Array,fe.String]}],getOutputNames:e=>[{name:Rt,type:e.$$lastDetectedType??fe.Anything},{name:Ft,type:fe.Boolean}]};const Wt={},Gt=e=>(Wt[e]||(Wt[e]={canvasFrom:Ce(320,240),canvasTo:Ce(320,240)}),Wt[e]),Vt=Object.freeze({image:"image",rect:"rect"}),Ht="image";var zt={onParentEvent:async(e,t,n,r)=>{const i=Gt(r.id),s={offset:{height:0,left:0,top:0,width:0},...r.getState()},o=[fe.Anything,fe.Rect,fe.JsonObj];if(t.name===Vt.rect&&Ue(n.data.value)&&o.includes(n.data.type)&&(s.rect=n.data.value,r.setState({...s})),t.name===Vt.image){if(!((n.data.type===fe.ImageData||n.data.type===fe.Anything)&&je(n.data.value)))throw new Error("Invalid image data. Expected a valid ImageData type");i.lastImage=n.data.value}if(i.lastImage&&s.rect){const e=((e,t,n,r,i)=>{if(r&&r.getContext){const s=r.getContext("2d"),o=n.getContext("2d");if(s&&o){n.width=e.width,n.height=e.height,o.putImageData(e,0,0);const a={...i};i&&(a.height=Number(i.height),a.width=Number(i.width),a.left=Number(i.left),a.top=Number(i.top));const c={top:0,width:0,left:0,height:0,...a};return i&&(Number.isInteger(c.width)||(c.width=t.width*c.width),Number.isInteger(c.height)||(c.height=t.height*c.height),Number.isInteger(c.left)||(c.left=t.left+t.width*c.left),Number.isInteger(c.top)||(c.top=t.top+t.height*c.top)),r.width=t.width+c.width,r.height=t.height+c.height,s.drawImage(n,t.left+c.left,t.top+c.top,t.width+c.width,t.height+c.height,0,0,r.width+c.width,r.height+c.height),s.getImageData(0,0,r.width||1,r.height||1)}}return e})(i.lastImage,s.rect,i.canvasFrom,i.canvasTo,s.offset);r.setState({...s,rect:null}),i.lastImage=void 0,await r.nextWidget(Ht,{type:fe.ImageData,value:e})}},getInputNames:()=>[{name:Vt.image,type:fe.ImageData},{name:Vt.rect,type:[fe.Rect,fe.JsonObj]}],getOutputNames:()=>[{name:Ht,type:fe.ImageData}],initialize:async e=>{Gt(e.widgetId)},terminate:async e=>{delete Wt[e.widgetId]}};const qt=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),i=e.data,s=e.width,o=e.height,a=s,c=o,l=((e,t,n)=>{if(Z)return new ImageData(t,n);return console.warn("Node environment detected. Aborting new ImageData creation"),e})(e,a,c),d=l.data;for(let e=0;e<c;e++)for(let c=0;c<a;c++){const l=e,u=c,p=4*(e*a+c);let g=0,h=0,f=0,m=0;for(let e=0;e<n;e++)for(let a=0;a<n;a++){const c=l+e-r,d=u+a-r;if(c>=0&&c<o&&d>=0&&d<s){const r=4*(c*s+d),o=t[e*n+a];g+=i[r]*o,h+=i[r+1]*o,f+=i[r+2]*o,m+=i[r+3]*o}}d[p]=g,d[p+1]=h,d[p+2]=f,d[p+3]=m+1*(255-m)}return l},Kt=[-1,0,1,-2,0,2,1,0,1],Jt=Object.freeze({image:"image"}),Yt="image";var Xt={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={matrix:[...Kt],...i};if(n.data.type===fe.ImageData||n.data.type===fe.Anything&&je(n.data.value)){const e=qt(n.data.value,s.matrix);return r.nextGate(Yt,{type:fe.ImageData,value:e})}},getInputNames:()=>[{name:Jt.image,type:fe.ImageData}],getOutputNames:()=>[{name:Yt,type:fe.ImageData}]};const Zt=Object.freeze({output:"output",aborted:"aborted"}),Qt=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),en=e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e},n=Array(t.inputs).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:"reset",type:fe.Anything}),n};var tn={onParentEvent:async(e,t,n,r)=>{const i={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...i,triggeredAt:0});const s=Date.now(),o=s-i.triggeredAt;if(i.triggeredAt&&!(o>=i.delayMs&&i.delayMs>0)&&i.delayMs)return r.nextGate(Zt.aborted,n.data);{i.triggeredAt=s;const e=en(i,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id)).findIndex((e=>e.name===t.name));-1!==e&&(i.lastInputIndex=e),i.matchingOutputs?-1!==e&&await r.nextGate(`output${e+1}`,n.data):await r.nextGate(Zt.output,n.data),r.setState(i)}},getInputNames:en,getOutputNames:e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e};if(e.matchingOutputs){const e=Array(t.inputs).fill(0).map(((e,t)=>({name:`output${t+1}`,type:fe.Anything})));return e.push({name:Zt.aborted,type:fe.Anything}),e}return[{name:Zt.output,type:fe.Anything},{name:Zt.aborted,type:fe.Anything}]},getDefaultState:Qt};const nn=(e,t,n,r,i,s)=>{if(i){const o=e.measureText(i),a=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-s,1.1*o.width,a),e.font=`${s}px Arial`,e.fillStyle="black",e.fillText(i,t,n)}},rn=(e,t,n,r,i,s,o)=>{e.fillStyle=i,e.fillRect(t,n,r,r),nn(e,t,n,i,s,o)},sn=(e,t,n,r,i,s)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const o=n/2;nn(e,t.left-o,t.top-o,r,i,s)},on={},an=e=>(on[e]||(on[e]={memCanvas:Ce(320,240),lastFrame:void 0,pixels:void 0}),on[e]),cn=Object.freeze({image:"image",pixels:"pixels"}),ln="image";var dn={onParentEvent:async(e,t,n,r)=>{const i=an(r.id),s={fontSize:12,color:"#00ff00",size:2,...r.getState()},o=(n.data.type===fe.ImageData||n.data.type===fe.Anything)&&je(n.data.value);if(t.name===cn.pixels){const e=(e=>Re(e)||Ue(e)||Array.isArray(e)&&e[0]&&(Re(e[0])||Ue(e[0])))(n.data.value);if(!e)return;i.pixels=n.data.value}if(t.name===cn.image&&o){const e=n.data.value;i.lastFrame=e}if(i.lastFrame&&i.pixels&&i.memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:i,color:s,labelProp:o,fontSize:a}=e;if(r){const e=ke(r);if(e){r.width!==t.width&&(r.width=t.width),r.height!==t.height&&(r.height=t.height),e.putImageData(t,0,0);const c=Array.isArray(n)?n:[n];for(let t=0;t<c.length;t++){const n=c[t],r=o?n[o]:"";Ue(n)?sn(e,n,i,s,r,a):Re(n)&&rn(e,n.x,n.y,i,s,r,a)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:i.lastFrame,pixels:i.pixels||[],memCanvas:i.memCanvas,size:s.size,color:s.color,labelProp:s.labelProp,fontSize:s.fontSize});return i.lastFrame=void 0,i.pixels=void 0,r.setState({...s}),r.nextWidget(ln,{type:fe.ImageData,value:e})}r.setState(s)},getInputNames:()=>[{name:cn.image,type:fe.ImageData},{name:cn.pixels,type:[fe.Rect,fe.Point,fe.Array,fe.JsonObj]}],getOutputNames:()=>[{name:ln,type:fe.ImageData}],initialize:async e=>{an(e.widgetId)},terminate:async e=>{delete on[e.widgetId]}};const un=Object.freeze({in:"in"}),pn="output",gn=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var hn={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:100,...r.getState()},s=!Number.isInteger(i.min),o=!Number.isInteger(i.max),a=s||o;let c=(l=i.min,d=i.max,Math.random()*(d-l)+l);var l,d;if(a){let e=0;if(s&&(e=gn(i.min)),o){const t=gn(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(pn,{type:fe.Number,value:c})},getInputNames:()=>[{name:un.in,type:fe.Anything}],getOutputNames:()=>[{name:pn,type:fe.Number}]};const fn=Object.freeze({output:"output",totalItems:"totalItems"}),mn=Object.freeze({trigger:"trigger",clear:"clear"}),yn=()=>({$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),vn=async(e,t)=>t.nextGate(fn.totalItems,{type:fe.Number,value:e});var bn={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===mn.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),vn(i.$$list.length,r);const s=t.name===mn.trigger;if(!s)if(Array.isArray(n.data.value))n.data.type!==fe.Array&&n.data.type!==fe.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await vn(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===fe.JsonObj?i.$$outputShape={...i.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:i.$$outputShape={...i.$$outputShape,[t]:n.data.type},i.$$list.push(n.data.value),r.setState({...i}),await vn(i.$$list.length,r)}if(s){Object.keys(i.$$outputShape).length&&(i.properties={autoFilled:!0,jsonShape:{...i.$$outputShape}});const e=i.$$list.length,t=[...i.$$list];return i.$$list=[],r.setState({...i}),await vn(e,r),r.nextGate(fn.output,{type:fe.Array,value:t})}},getInputNames:e=>{const t={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:mn.clear,type:fe.Anything},{name:mn.trigger,type:fe.Anything}),n},getOutputNames:e=>[{name:fn.output,type:fe.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:fn.totalItems,label:"Total Items",type:fe.Number}],getDefaultState:yn};const Sn=Object.freeze({start:"start",stop:"stop"}),wn="output",In="clock_interrupt";var _n={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(De(e?.name||"")&&t.name===In)return r.nextGate(wn,{type:fe.Boolean,value:!0});if(t.name===Sn.stop&&i.enabled&&i.$$interruptId){r.cancelInterrupt(i.$$interruptId)?(i.enabled=!1,i.$$interruptId=void 0,r.setState(i)):console.warn(`Failed to cancel interrupt [${i.$$interruptId}]`)}else t.name!==Sn.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt("interval",In,{interval:i.interval}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:Sn.start,type:fe.Anything},{name:Sn.stop,type:fe.Anything}],getOutputNames:()=>[{name:wn,type:fe.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",In,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const $n=Object.freeze({in:"in"}),Cn="output",kn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var En={onParentEvent:async(e,t,n,r)=>{const i={userProperties:[],factor:2,decimalPoints:2,...r.getState()},s=n.data.type;let o=n.data.value,a=!1;return e?.jsonShape&&(i.detectedInputJson={...i.detectedInputJson,...e?.jsonShape},a=!0),i.detectedInputType||(i.detectedInputType=s,a=!0),n.data.type===fe.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>kn(e,t,n)));return r})(n.data.value,i.factor,i.decimalPoints):"object"==typeof n.data.value?.[0]&&(o=((e,t,n,r)=>{const i=(e||[]).map((e=>{const i={...e};return Object.keys(i).forEach((e=>{r?.length&&!r?.includes(e)||(i[e]=kn(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===fe.Number&&(o=kn(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(Cn,{type:s,value:o})},getInputNames:()=>[{name:$n.in,type:[fe.Array,fe.Number]}],getOutputNames:e=>[{name:Cn,type:e.detectedInputType||fe.Number,jsonShape:e.detectedInputJson}]};const xn={},An=Object.freeze({output:"output"}),Nn=Object.freeze({trigger:"trigger"}),Pn=e=>e===fe.ArrayBuffer||e===fe.AudioBuffer||e===fe.BinaryFile||e===fe.ImageData||e===fe.ImageBitmap||e===fe.Array||e===fe.JsonObj,On=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:fe.Number,value:10},{name:"y",label:"y",type:fe.Number,value:20}]}),Tn=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},Ln=(e,t)=>{const n={};for(let r=0;r<e.properties.length;r++){let i=e.properties[r].value;const s=e.properties[r].type;Pn(s)&&(i=xn[t][e.properties[r].name]),s===fe.Number?i=Number(i):s===fe.String&&(i=String(i)),n[e.properties[r].label]=i}return n};var Bn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s=structuredClone(i),o={...On(),...s};if(t.name===Nn.trigger){const e=Ln(o,r.id);return r.nextWidget(An.output,{type:fe.JsonObj,value:e})}const a=o.properties.findIndex((e=>e.name===t.name));if(-1!==a){const e=o.properties[a];let t=n.data.type===e.type;if(!t&&n.data.type===fe.Anything){t=Fe(n.data.type)===e.type}if(t){const t=Pn(n.data.type);xn[r.id]=xn[r.id]||{},t?(xn[r.id][e.name]=n.data.value,o.properties[a].value=void 0):o.properties[a].value=n.data.value,o.properties[a].$$invalidInputType=!1}else o.properties[a].$$invalidInputType=!0;if(r.setState(o),!o.useTriggerPort){const e=Ln(o,r.id);return r.nextWidget(An.output,{type:fe.JsonObj,value:e})}}},getInputNames:e=>{const t={...On(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:Nn.trigger,label:Nn.trigger,type:fe.Anything}),n},getOutputNames:e=>[{name:An.output,label:An.output,type:fe.JsonObj,jsonShape:Tn(e)}],getDefaultState:On,initialize:async e=>{xn[e.widgetId]={}},terminate:async e=>{delete xn[e.widgetId]}};const Dn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(Pe)){const n=t(e,Pe);return We("inner","input",n)}if(e.startsWith(Le)){const n=t(e,Le);return We("outer","output",n)}return null},jn=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[fe.Anything],index:0}],outputs:[{name:"output",type:[fe.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Un=e=>{const t={...jn(),...e},n=t.inputs.map(((e,t)=>({name:We("outer","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t}))),r=t.outputs.map(((e,t)=>({name:We("inner","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:n.length+t})));return[...n,...r]};var Rn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...jn(),...i},o=Un(s,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const i=o[e];if(t.name===i.name&&(i.type.includes(fe.Anything)||i.type.includes(n.data.type))){const e=await Dn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Un,getOutputNames:e=>{const t={...jn(),...e},n=t.outputs.map(((e,t)=>({name:We("outer","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t})));return[...t.inputs.map(((e,t)=>({name:We("inner","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:t+n.length}))),...n]},getDefaultState:jn};const Fn=(e,t,n,r,i)=>{const s=4*(t*n.width+e),o=n.data[s],a=n.data[s+1],c=n.data[s+2];return Math.abs(o-r.r)<=i&&Math.abs(a-r.g)<=i&&Math.abs(c-r.b)<=i};var Mn={getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,i=n[t+1]||0,s=n[t+2]||0;return{avr:(r+i+s)/3,r:r,g:i,b:s}},getBoundingBox:(e,t,n)=>{const r=e.width,i=e.height,s=new Set,o=Number(n.threshold||0),a=isNaN(o)?10:o,c=(n,o)=>{const c=[[n,o]];let l=n,d=n,u=o,p=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,g]=n;o<0||g<0||o>=r||g>=i||s.has(`${o},${g}`)||!Fn(o,g,e,t,a||0)||(s.add(`${o},${g}`),l=Math.min(l,o),d=Math.max(d,o),u=Math.min(u,g),p=Math.max(p,g),c.push([o+1,g],[o-1,g],[o,g+1],[o,g-1]))}return{minX:l,maxX:d,minY:u,maxY:p}},l=[];for(let o=0;o<i;o+=4)for(let i=0;i<r;i+=4)if(!s.has(`${i},${o}`)&&Fn(i,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:s}=c(i,o),a=t-e,d=s-r;if(a>=(n.minWidth||1)&&d>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:d}),n.maxBoxes&&l.length>=n.maxBoxes)return l}return l},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,i="object"==typeof n,s=i?n.r:n,o=i?n.g:n,a=i?n.b:n;r[t]=s,r[t+1]=o,r[t+2]=a,r[t+3]=255}};const Wn=e=>Fe(e);var Gn,Vn,Hn,zn,qn,Kn,Jn,Yn,Xn,Zn;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Gn||(Gn={})),function(e){e.Bundle="bundle",e.Group="group"}(Vn||(Vn={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Hn||(Hn={})),function(e){e.Cloud="cloud",e.Web="web"}(zn||(zn={})),function(e){e.Cpu_128M="kmu-cpu-128m",e.Cpu_256M="kmu-cpu-256m",e.Cpu_512M="kmu-cpu-512m",e.Cpu_1024M="kmu-cpu-1024m",e.Cpu_2048M="kmu-cpu-2048m",e.Cpu_4096M="kmu-cpu-4096m"}(qn||(qn={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Kn||(Kn={})),(Jn||(Jn={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Yn||(Yn={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Xn||(Xn={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Zn||(Zn={}));let Qn=null;var er=()=>{if(!Qn)throw new Error("Required function is not set");return Qn};class tr extends Error{targetWidgetId;targetPortName;sourcePortName;sourceWidgetId;targetWidgetType;sourceWidgetType;constructor(e,t){super(e),this.name="ChildWidgetError",t.stack&&(this.stack=t.stack),this.targetWidgetId=t.targetWidgetId,this.targetPortName=t.targetPortName,this.sourcePortName=t.sourcePortName,this.sourceWidgetId=t.sourceWidgetId,this.targetWidgetType=t.targetWidgetType,this.sourceWidgetType=t.sourceWidgetType}}class nr extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const rr=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===Gn.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar console = this.console;\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\n\t\t\tvar Kemu = {\n\t\t\t\tservices: {\n\t\t\t\t\thttp: { ...this.httpWebService },\n\t\t\t\t\tdynamoDb: { ...this.dynamoService },\n\t\t\t\t\tgoogleSheets: {\n\t\t\t\t\t\t...this.googleSheetsService,\n\t\t\t\t\t}\n\t\t\t\t},\n\n\t\t\t\timage: this.imageHelpers,\n\t\t\t\tvariable: this.variablesManager,\n\n\t\t\t\thelpers: {\n\t\t\t\t\tdecodeDataType: this.decodeDataType,\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\tjsonp: this.jsonp,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tvar sendToPort;\n\n\t\t\t// --- User Methods Start ---\n\t\t\t${e||""};\n\t\t\t// --- User Methods End ---\n\t\t\t\n\t\t\t// Processes the user code asynchronously.\n\t\t\tconst asyncProcessEvent = async (targetPort, sourcePort, event) => {\n\t\t\t\tconst userProcessEvent = typeof processEvent === 'undefined' ? undefined : processEvent;\n\t\t\t\tif(userProcessEvent) {\n\t\t\t\t\ttry{\n\t\t\t\t\t\treturn await userProcessEvent(targetPort, sourcePort, event, sendToPort);\n\t\t\t\t\t}catch(e){\n\t\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked the very first time the recipe is initialized */\n\t\t\tconst asyncRecipeInit = async (context, logger) => {\n\t\t\t\ttry {\n\t\t\t\t\t${t===Gn.Browser?"if(logger) { console = logger; }":""}\n\t\t\t\t\tif(typeof recipeInit === 'function') {\n\t\t\t\t\t\treturn recipeInit(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked every time the code is about to be replaced */\n\t\t\tconst asyncOnTerminate = async (context) => {\n\t\t\t\ttry {\n\t\t\t\t\tif(typeof onTerminate === 'function') {\n\t\t\t\t\t\treturn onTerminate(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** updates the function that allows widget contexts to send data to the next widget */\n\t\t\tconst setSendToPort = (sendNextFun) => {\n\t\t\t\tsendToPort = sendNextFun;\n\t\t\t}\n\n\t\t\t/** invoked the every time the user code is compiled. */\n\t\t\tconst asyncMainEvent = async (sendNextFun, logger) => {\n\t\t\t\ttry{\n\t\t\t\t\tsetSendToPort(sendNextFun);\n\t\t\t\t\tif(logger) { console = logger; }\n\t\t\t\t\tif(typeof main === 'function'){\n\t\t\t\t\t\treturn main();\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tasyncProcessEvent: asyncProcessEvent,\n\t\t\t\tmain: asyncMainEvent,\n\t\t\t\trecipeInit: asyncRecipeInit,\n\t\t\t\tsetSendToPortFun: setSendToPort,\n\t\t\t\tonTerminate: asyncOnTerminate,\n\t\t\t\tgetLocalContext: () => global,\n\t\t\t\tgetWidgetInputs: typeof getWidgetInputs === 'undefined' ? undefined : getWidgetInputs,\n\t\t\t\tgetWidgetOutputs: typeof getWidgetOutputs === 'undefined' ? undefined : getWidgetOutputs,\n\t\t\t};\n\t\t}\n\t\t\n\t\treturn function compiler(context){\n\t\t\treturn _user_code_.call(context)\n\t\t}\n\n\t\treturn compiler;\n\t`,ir=(e,t,n,r)=>{const o=rr(e,n),a={...t,document:{},__errorTracer:e=>{if(e instanceof tr)throw e;throw new nr(e.message,e.stack)},__jest:void 0===globalThis.__jest?void 0:globalThis.__jest,___notSupportedMethod:()=>r?.error("This method is not supported."),console:console,setInterval:()=>r?.error("'setInterval' is not supported. Please use a \"Timer\" widget instead."),setTimeout:t?.setTimeout,imageHelpers:Mn,...n===Gn.Cloud?{require:er(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:i,CryptoJS:s,decodeDataType:Wn,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(Z)return"browser";if(ee)return"node";if(Q)return"worker";throw new Error("Unsupported environment")})()?(e=>e.replace(/[//]{2}[ ]*@kemu-cloud[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-cloud[ \t]*\}/gim,""))(o):(e=>e.replace(/[//]{2}[ ]*@kemu-browser[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-browser[ \t]*\}/gim,""))(o),t=new Function(e);return{compiledModule:t()(a)}}catch(e){return{error:{name:"CompileError",message:e.message,stack:e.stack}}}},sr="main",or="My Script",ar="This is a test script.",cr=`\n/**\n * Name: ${or}\n * Description: ${ar}\n */\n\nconst getWidgetInputs = () => [\n\t{ name: 'Input 1', type: DataType.Number }\n];\n\nconst getWidgetOutputs = () => [\n\t{ name: 'Output 1', type: DataType.Number }\n]\n\nlet counter = 0;\n\nconst processEvent = async (targetPort, sourceWidget, event) => {\n\tif(targetPort.name === 'Input 1'){\n\t\treturn sendToPort('Output 1', {\n\t\t\ttype: DataType.Number,\n\t\t\tvalue: counter++,\n\t\t});\n\t}\n}\n`.trim(),lr=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},version:2,metadata:{name:or,description:ar},pages:{[sr]:{code:cr,language:"javascript",name:"My First Script"}}}),dr=(e,t)=>{const n={message:"Unknown Error"};if(e?.stack){const r=e?.stack?.split(":")[0].trim();n.type=r;const i=(e=>{const t=/,[ ]?<anonymous>:([0-9]+:[0-9]+)\)/gm;let n;for(;null!==(n=t.exec(e));){n.index===t.lastIndex&&t.lastIndex++;const e=n[1].split(":");if(2===e.length)return{line:Number(e[0])||0,column:Number(e[1])||0}}return null})(e.stack);i&&(n.line=i.line-(e=>{const t="___user_code_section___";return rr(t,e).split(t)[0].split("\n").length+2})(t),n.column=i.column)}return e.message&&(n.message=e.message),n},ur=(e,t)=>{const n={...{...lr(),...t.getState()},$$error:e||void 0};e&&console.error(e.message),t.setState(n)},pr=new o;let gr,hr,fr={},mr={};const yr=e=>{const t=oe(gr,hr,e);if(!t)throw new Error(`Widget ${e} not found in thing ${hr}`);return t},vr=(e,t)=>`${e}:${t}`,br=e=>`${yr(e.createdByWidgetId).id}::${e.variableName}`,Sr=e=>`${pe}${e}`;var wr=e=>{const t=yr(e.createdByWidgetId),n=br({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});mr[n]={type:e.type,subscriberWidgetId:t.id,subscriberWidgetType:t.type}},Ir=e=>{const t=br({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});delete mr[t]},_r=async e=>{const t=yr(e.setByWidgetId);if(!t)throw new Error(`Widget ${e.setByWidgetId} not found in thing ${hr} in recipe ${gr}`);const n=e.variableName.startsWith(pe)?br({variableName:e.variableName,createdByWidgetId:e.setByWidgetId}):e.variableName;fr[n]={value:e.value,type:e.type};const r={value:e.value,type:e.type,varName:e.variableName,isUIElement:e.variableName.startsWith(pe),setByWidgetType:t.type,setByWidgetId:e.setByWidgetId};await pr.emit(vr(e.variableName,e.type),r),e.type!==fe.Anything&&await pr.emit(vr(e.variableName,fe.Anything),r)},$r=e=>{const{readerWidgetId:t,variableName:n}=e;if(!yr(t))throw new Error(`Widget ${t} not found in thing ${hr} in recipe ${gr}`);const r=n.startsWith(pe)?br({variableName:e.variableName,createdByWidgetId:e.readerWidgetId}):n,i=fr[r];if(i)return{type:i.type,value:i.value}},Cr=e=>{const{widgetId:t,variableName:n,type:r}=e;if(!yr(t))throw new Error(`Widget ${t} not found in thing ${hr} in recipe ${gr}`);const i=vr(n,r);let s;return s=pr.on(i,(async r=>{oe(gr,hr,t)?await e.onValueChange(r):(console.warn(`Zombie widget ${t} detected, unsubscribing from variable events "${n}"`),s?.())})),s},kr=(e,t)=>{const n=vr(e,fe.Anything);return pr.on(n,(async e=>{const{isUIElement:n,...r}=e;await t(r)}))},Er=e=>{mr={},fr={},gr=e.recipePoolId,hr=e.thingId};const xr="setTimeout",Ar="variableChanged",Nr=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=oe(t,n,r);if(!i)throw new Error(`Widget "${r}" not found in recipe "${t}"`);const s=(e,t)=>{const n=$r({readerWidgetId:r,variableName:e});if(n||t)return void 0===n?{value:t?.value??t,type:t?.type??Fe(t)}:{value:n.value,type:n.type}},o=(t,n,s)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");const o={...lr(),...e.getState()},a=Cr({variableName:t,type:fe.Anything,widgetId:r,onValueChange:async e=>{n?e.setByWidgetType===ze.widgetGroup&&e.setByWidgetId===i.groupId&&await s(e):s(e)}});delete o.$$eventListeners[t],o.$$eventListeners[t]={handler:s,abort:async()=>{a()},name:Ar},e.setState(o)};return{get:s,set:async(e,t,n)=>{await _r({variableName:e,type:n||Fe(t),setByWidgetId:r,value:t})},onValueChange:(e,t)=>{o(e,!1,t)},onUIValueChange:(e,t)=>{const n=Sr(e);o(n,!0,t)},getUIValue:e=>{const r=Sr(e),o=s(r);if(o)return{value:o.value,type:o.type};const a=i.groupId;if(!a)throw new Error("You can only read UI variables from inside a widgetGroup");const c=oe(t,n,a);if(!c)throw new Error(`Widget "${a}" not found in recipe "${t}"`);const l=c.state,d=(l.settings||[]).find((t=>t.variableName===e));if(!d)throw new Error(`Field "${e}" not found in widgetGroup "${l.name}"`);const u=d.config.defaultValue;if(!u)throw new Error(`Field "${e}" in widgetGroup "${l.name}" has no default value`);return{value:u,type:Fe(u)}}}},Pr="__command-compile__";let Or;const Tr=()=>{throw new Error("Method not implemented")},Lr=(e,t,n)=>{const i=(e,...n)=>{const r={...lr(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},s={};return Object.keys(fe).forEach((e=>{s[e]=fe[e]})),{dataTypesEnum:s,notify:{success:e=>{t.getState()?.$$managedUI?.notify?.success(e)},error:e=>{t.getState()?.$$managedUI?.notify?.error(e)},info:e=>{t.getState()?.$$managedUI?.notify?.info(e)}},variablesManager:e.variablesManager?Nr({recipePoolId:n.recipePoolId,scriptWidgetId:n.widgetId,thingId:n.thingId,getState:t.getState,setState:t.setState}):{get:Tr,set:async()=>Tr(),onValueChange:Tr,onUIValueChange:Tr,getUIValue:Tr},setTimeout:(n,i,s)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=r(),o={...lr(),...t.getState()};o.$$eventListeners[e]={handler:n,rejectHandler:s,name:xr},t.setState(o),t.registerInterrupt("timeout",e,{timeout:i},void 0,e)}},addEventListener:(e,n)=>{if(t.setState){const s=r(),o={...lr(),...t.getState()};o.$$eventListeners[s]={handler:n,name:e},t.setState(o),window.addEventListener(e,i.bind(s))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,n)=>{if(t.setState){const r={...lr(),...t.getState()},i=Object.keys(r.$$eventListeners).find((t=>r.$$eventListeners[t].name===e&&r.$$eventListeners[t].handler===n));t.setState(r),i&&removeEventListener(r.$$eventListeners[i].name,r.$$eventListeners[i].handler)}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)}}},Br=(e,t,n,r)=>{const i={...lr(),...n.getState()},s=i.pages[sr].$$compiledCode;if(s)return{compiledModule:s};{const s=Lr(e,n,t);return ir(i.pages[sr].code,s,n.recipeType,r)}},Dr=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),jr=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===xr){const e=n[r]?.rejectHandler;if("function"==typeof e)try{await e("TIMER_ABORTED")}catch(e){console.log("Error in reject interrupt handler: ",e)}t.cancelInterrupt(r),delete n[r]}}return n},Ur=async e=>{const t={...e};for(const n in e){if(e[n].name===Ar){const r=e[n]?.abort;if("function"==typeof r)try{await r()}catch(e){console.log("Error in abort interrupt handler: ",e)}delete t[n]}}return t},Rr=async(e,t,n)=>{let r={...lr(),...e.getState()};if(void 0!==n){r.pages[sr]?.$$compiledCode?.onTerminate&&await(r.pages[sr].$$compiledCode?.onTerminate());let t=await jr(r.$$eventListeners,e);t=await Ur(t),r.$$eventListeners=t,r.pages[sr].$$compiledCode=void 0,r.pages[sr].code=n,e.setState({...r})}const i=!r.pages[sr].$$compiledCode,{compiledModule:s,error:o}=Br({variablesManager:!0,withTimers:!0},{recipePoolId:e.recipePoolId,thingId:e.thingRecipeId,widgetId:e.id},{getState:e.getState,setState:e.setState,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt});if(o){console.log("Failed to compile user code");const t=dr(o,e.recipeType);return ur(t,e),null}if(s){const n=(()=>{const e=(e,...t)=>{if(Or)try{return Or[e](...t)}catch(e){return void console.log("Error in custom logger: ",e)}console[e](...t)};return{log:(...t)=>{e("log",...t)},error:(...t)=>{e("error",...t)},warn:(...t)=>{e("warn",...t)},info:(...t)=>{e("info",...t)}}})();let o;r={...e.getState()},r.pages[sr].$$compiledCode=s;const a=Mr(r.pages[sr].code);a?.name===r.metadata?.name&&a?.description===r.metadata?.description||(r.metadata=a||void 0);const c=e.nextWidget||e.nextGate;if(c&&s.setSendToPortFun(c),t)try{await s.recipeInit({setState:e.setState,getState:e.getState},n)}catch(t){o=dr(t,e.recipeType)}if(c&&i)try{await s.main(c,n)}catch(t){o=dr(t,e.recipeType)}r.$$lastInputs=s.getWidgetInputs?s.getWidgetInputs():[],r.$$lastOutputs=s.getWidgetOutputs?s.getWidgetOutputs():[],e.setState(r),ur(o,e)}};var Fr={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...lr(),...i};if(!s.pages[sr])return console.warn("Missing default page");if(De(e?.name||""))return s.$$eventListeners[t.name]?(await s.$$eventListeners[t.name].handler(),s.$$eventListeners[t.name].name===xr&&delete s.$$eventListeners[t.name],void r.setState({...s})):void console.log(`Unknown interrupt id [${t.name}] `);const o=t.name===Pr;await Rr(r,!1,o?n.data.value:void 0);const a=s.pages[sr].$$compiledCode;if(e&&e.name!==Pr&&a)try{await a.asyncProcessEvent(t,e,n)}catch(e){if("UserCodeError"===e.name){const t=dr(e,r.recipeType);throw ur(t,r),t}throw e}},getInputNames:(e,t)=>{const n={...lr(),...e},{compiledModule:r}=Br({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return Dr(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...lr(),...e},{compiledModule:r}=Br({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return Dr(e)}return e.$$lastOutputs||[]},getDefaultState:lr,initialize:async e=>{const t=e.getState(),n={...lr(),...t};n.pages[sr].code&&await Rr({getState:e.getState,id:e.widgetId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,nextWidget:e.nextWidget,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[sr].code)},terminate:async e=>{try{const t=e.getState();t.pages[sr].$$compiledCode?.onTerminate&&await t.pages[sr].$$compiledCode.onTerminate();const n=e=>Xe.destroyInterrupt(e),r=await jr(t.$$eventListeners,{cancelInterrupt:n});await Ur(r)}catch(t){console.warn(`Error terminating script widget ${e.widgetId}: `,t)}}};const Mr=e=>{const t=e.trimStart().match(/^(?:\/\*\*(?:[^*]|\*(?!\/))*\*\/|\/\*(?:[^*]|\*(?!\/))*\*\/)/);if(!t)return null;const n=t[0].replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map((e=>e.replace(/^\s*\*?\s?/,"").trim())).join("\n"),r=n.match(/Name\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),i=n.match(/Description\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),s={};return r&&r[1]&&(s.name=r[1].trim()),i&&i[1]&&(s.description=i[1].trim()),Object.keys(s).length>0?s:null},Wr=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const i=await Gr(e);return((e,t,n,r)=>{const i=r.getContext("2d");if(!i)throw new Error("Failed to get canvas context");const s=e.width,o=e.height;return r.width=t,r.height=n,i.drawImage(e,0,0,s,o,0,0,t,n),i.getImageData(0,0,t,n)})(i,n||i.naturalWidth,r||i.naturalHeight,t)},Gr=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),Vr=Object.freeze({image:"image"}),Hr=Object.freeze({base64:"base64"}),zr=()=>({});var qr={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===Hr.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==fe.String&&n.data.type!==fe.Anything)return;const e=n.data.value;Z&&(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240)));try{const t=await Wr(e,i.$$memCanvas,i.resize?.width,i.resize?.height);return r.setState(i),r.nextGate(Vr.image,{type:fe.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:Hr.base64,type:fe.String}],getOutputNames:()=>[{name:Vr.image,type:fe.ImageData}],getDefaultState:zr};const Kr=Object.freeze({object:"object",error:"error"}),Jr=Object.freeze({string:"string"}),Yr=()=>({outputIsArray:!1});var Xr={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===fe.String||n.data.type===fe.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!i.outputIsArray?r.setState({...i,outputIsArray:!0}):!t&&i.outputIsArray&&r.setState({...i,outputIsArray:!1}),r.nextGate("object",{type:t?fe.Array:fe.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:fe.Boolean,value:!0})}},getInputNames:()=>[{name:Jr.string,type:fe.String}],getOutputNames:e=>[{name:Kr.object,type:[fe.JsonObj,fe.Array],label:e.outputIsArray?"array":Kr.object},{name:Kr.error,type:fe.Boolean}],getDefaultState:Yr};const Zr=Object.freeze({string:"string",length:"length"}),Qr=Object.freeze({trigger:"trigger",setText:"setText"}),ei=()=>({text:"",dispatchOnSet:!1});var ti={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===Qr.setText){if(!((n.data.type===fe.String||n.data.type===fe.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(i.text=n.data.value,r.setState(i)),!i.dispatchOnSet)return}const s=r.nextGate(Zr.length,{type:fe.Number,value:i.text.length}),o=r.nextGate(Zr.string,{type:fe.String,value:i.text});await Promise.all([s,o])},getInputNames:e=>{const t=[{name:Qr.setText,type:fe.String}];return e.dispatchOnSet||t.push({name:Qr.trigger,type:fe.Anything}),t},getOutputNames:()=>[{name:Zr.string,type:fe.String},{name:Zr.length,type:fe.Number}],getDefaultState:ei};const ni=Object.freeze({image:"image"}),ri=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),ii=()=>({showInputPorts:!1});var si={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===ri.x&&(i.cropX=n.data.value),t.name===ri.y&&(i.cropY=n.data.value),t.name===ri.width&&(i.cropWidth=n.data.value),t.name===ri.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===ri.image){if(n.data.type!==fe.ImageData&&n.data.type!==fe.Anything)return;if(!je(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$memCanvasContext=ke(i.$$memCanvas),r.setState(i)),!i.$$memCanvas||!i.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return i.$$memCanvas.width=e.width,i.$$memCanvas.height=e.height,(i.cropX||i.cropY||i.cropWidth||i.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const i=Math.max(r.x||0,0),s=Math.max(r.y||0,0),o=e.width,a=e.height,c=Math.min(Math.ceil(r.width||o),o),l=Math.min(Math.ceil(r.height||a),a);return t.width=e.width,t.height=e.height,n.putImageData(e,0,0),n.drawImage(t,i,s,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,i.$$memCanvas,i.$$memCanvasContext,{x:i.cropX,y:i.cropY,width:i.cropWidth,height:i.cropHeight})),r.nextGate(ni.image,{type:fe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:ri.image,type:[fe.ImageData]}];return e.showInputPorts&&(t.push({name:ri.x,type:fe.Number}),t.push({name:ri.y,type:fe.Number}),t.push({name:ri.width,type:fe.Number}),t.push({name:ri.height,type:fe.Number})),t},getOutputNames:()=>[{name:ni.image,type:fe.ImageData}],getDefaultState:ii};const oi=Object.freeze({image:"image"}),ai=Object.freeze({image:"image",width:"width",height:"height"}),ci=()=>({showInputPorts:!1});var li={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===ai.width&&(i.width=n.data.value),t.name===ai.height&&(i.height=n.data.value),void r.setState(i);if(t.name===ai.image){if(n.data.type!==fe.ImageData&&n.data.type!==fe.Anything)return;if(!je(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$tempCanvas=Ce(320,240),r.setState(i)),!i.$$memCanvas||!i.$$tempCanvas)return;let t=e;return(i.width||i.height)&&(t=((e,t,n,r,i)=>{if(!r&&!i)return e;r&&!i?i=r*(e.height/e.width):!r&&i&&(r=i*(e.width/e.height));const s=Math.max(1,r||e.width),o=Math.max(1,i||e.height);n.width===e.width&&n.height===e.height||(n.width=e.width,n.height=e.height),t.width=s,t.height=o;const a=ke(t),c=ke(n);if(!a||!c)throw new Error("Failed to get canvas context");return c.putImageData(e,0,0),a.drawImage(n,0,0,e.width,e.height,0,0,s,o),a.getImageData(0,0,s,o)})(e,i.$$memCanvas,i.$$tempCanvas,i.width,i.height)),r.nextGate(oi.image,{type:fe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:ai.image,type:fe.ImageData}];return e.showInputPorts&&(t.push({name:ai.width,type:fe.Number}),t.push({name:ai.height,type:fe.Number})),t},getOutputNames:()=>[{name:oi.image,type:fe.ImageData}],getDefaultState:ci};const di=Object.freeze({value:"value"}),ui=Object.freeze({trigger:"trigger",setValue:"setValue"}),pi=()=>({value:0,dispatchOnSet:!1});var gi={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===ui.setValue){const e=n.data.type===fe.Number||n.data.type===fe.Anything||n.data.type===fe.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(i.value=Number(n.data.value),r.setState(i),!i.dispatchOnSet)return}return r.nextGate(di.value,{type:fe.Number,value:i.value})},getInputNames:e=>{const t=[{name:ui.setValue,type:fe.Number}];return e.dispatchOnSet||t.push({name:ui.trigger,type:fe.Anything}),t},getOutputNames:()=>[{name:di.value,type:fe.Number}],getDefaultState:pi};const hi=Object.freeze({image:"image"}),fi=Object.freeze({image:"image"}),mi=()=>({anchors:[],vertices:[],matrix:[]}),yi={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},s=window,o=n.data.type===fe.ImageData;if(s.Speedy&&o){const e=s.Speedy,t=n.data.value;let o,d,u,p=i.$$private?.canvas,g=i.$$private?.context,h={...i};const f=4===i.anchors.length;if(i.$$private?.pipeline)o=i.$$private?.pipeline,d=i.$$private?.source;else{o=e.Pipeline(),d=e.Image.Source();const n=e.Image.Sink();u=e.Transform.PerspectiveWarp(),p?p.width===t.width&&p.height===t.height||(p.width=t.width,p.height=t.height,g=p.getContext("2d")):(c=t.width,l=t.height,p=Ce(c,l),g=p.getContext("2d")),d.output().connectTo(u.input()),u.output().connectTo(n.input()),o.init(d,n,u);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===i.anchors.length){const t=e.Matrix(2,4,[(a=i.anchors)[0].x,a[0].y,a[1].x,a[1].y,a[2].x,a[2].y,a[3].x,a[3].y]),n=e.Matrix(2,4,i.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),s=e.Matrix.Zeros(3,3);await e.Matrix.perspective(s,t,n);const o=s.read();r=e.Matrix(3,3,o)}u.transform=r,h={...h,$$private:{...h.$$private,canvas:p,context:g,perspective:u,pipeline:o,source:d}}}let m=t;if(f){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,i=e.$$private?.pipeline;if(n.Speedy&&r&&i){const e=n.Speedy,s=await createImageBitmap(t),o=await e.load(s);return r.media=o,(await i.run()).image.source}return null})(h,m);e&&(p&&g&&(m=((e,t,n)=>(t.width=e.width,t.height=e.height,n.drawImage(e,0,0),n.getImageData(0,0,e.width,e.height)))(e,p,g)),h.$$private&&r.setState({...h,$$private:{...h.$$private,lastInputImage:t}}))}else h.$$private&&r.setState({...h,$$private:{...h.$$private,lastInputImage:t}});return r.nextGate(hi.image,{type:fe.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:fi.image,type:fe.ImageData}],getOutputNames:()=>[{name:hi.image,type:fe.ImageData}],getDefaultState:mi,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},vi=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[fe.Anything],name:"input"}],outputs:[{dataType:[fe.Anything],name:"output"}]});let bi;const Si=()=>{if(!bi)throw new Error(tt(et));return bi};const wi=async e=>{const t=new a,n=await t.loadAsync(e),r={};for(const e in n.files)if(!n.files[e].dir){const t=await n.file(e);t&&(r[e]=await t.async("uint8array"))}return r},Ii={};var _i=e=>Ii[e]||null;const $i=async(e,t,n)=>{try{const r=Si(),i=n?r.loadBlobAsString:r.loadBlob;return await i(e,t)}catch(e){return null}},Ci=async e=>{const t=le;try{const n=await $i(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},ki=async e=>{const t=de;try{const n=await $i(e,t,!0);if(!n)return null;return JSON.parse(n)}catch(n){return console.log(`Failed to parse the bundle's state [${e}/${t}] %j`,n),null}},Ei=(e,t)=>`${e.replace(ue,"")}_${t}`,xi=(e,t)=>`widget/${e.replace(ue,"")}/v/${t}`,Ai=async(e,t)=>{const n=Si(),[r]=await Promise.all([wi(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},Ni=(e,t)=>{const n=Ei(e,t),r=_i(n);return r?{...r}:null},Pi=(e,t,n)=>{const r=`${`widget/${e.replace(ue,"")}/tmp`}/${t}`;if(n){return Si().getCacheLocation(r)}return r};var Oi=Ni,Ti=async(e,t,n)=>{const r=Pi(t,n);await Ai(e,r);const i=Ci(r),s=ki(r),o=Si(),a=o.getCacheLocation(r),[c,l]=await Promise.all([i,s]);if(!c)return null;let d=l;if(!l){const e=vi(),t=JSON.stringify(e);await o.saveBlob(r,de,Be(t)),d=e}return{cachePath:a,processor:c,storedState:Object.freeze(d)}},Li=(e,t,n)=>{if(n.isTempStorage)return Pi(e,t,n.fullStorageRoot);const r=Si(),i=xi(e,t);return n.fullStorageRoot?r.getCacheLocation(i):i};const Bi=()=>vi();var Di={onParentEvent:async(e,t,n,r)=>{const i=r.getState();return i.$$processor?.onParentEvent({sourcePort:e?.name||"",targetPort:t?.name||"",data:n.data},{getState:r.getState,recipeId:r.recipePoolId,recipeType:r.recipeType,setState:r.setState,nextWidget:r.nextGate})},getInputNames:(e,t)=>{const n={...Bi(),...e};return n.$$processor?.getInputNames?n.$$processor.getInputNames(e,t):n.inputs.map((e=>({name:e.name,type:e.dataType})))},getOutputNames:(e,t)=>{const n={...Bi(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:Bi,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetId;const i=n.$$cacheInfo?.version.toString()||n.collectionInfo?.version.toString()||1;if(n.$$cacheInfo={...n.$$cacheInfo,version:Number(i),widgetThingId:r},!r||!i)throw new Error("Widget bundle state is missing cache id or version");console.log("Loading state from cache");const s=Oi(r,i);let o=!s;if(!n.$$processor)if(n.storageUnitId&&!s){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetId;const s=await Ti(t,r,i);o=!0,s&&(n={...n,$$processor:s.processor,$$cacheInfo:{...n.$$cacheInfo,widgetThingId:r,version:Number(i)}},e.setState(n))}}else if(s){o=!1;const r=n.collectionInfo?{...n.collectionInfo}:void 0;n={...n,...!t.keepCurrentState&&s.storedState?{...s.storedState,...r?{collectionInfo:r}:{}}:{},$$processor:s.processor},e.setState(n)}const a=Li(r,i,{fullStorageRoot:!0,isTempStorage:o});console.log("Invoking bundle initialize with cache: ",a);try{await(n.$$processor?.initialize({cacheLocation:a,getState:e.getState,setState:e.setState}));const t=e.getState();e.setState({...t,$$initializationError:void 0})}catch(t){const n=e.getState();throw e.setState({...n,$$initializationError:t.message||"An error occurred initializing the widget"}),t}},terminate:async e=>{const t={...e.getState()};console.log(`Terminating widget bundle ${t.name} [${t.$$cacheInfo?.widgetThingId||""}]`);const n=t.$$processor;n&&"function"==typeof n.terminate&&await n.terminate({getState:e.getState,setState:e.setState,recipePoolId:e.recipePoolId,widgetId:e.widgetId})}};const ji=Object.freeze({event:"event"}),Ui="1",Ri="2",Fi="3";var Mi={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate(Ui,n.data),await r.nextGate(Ri,n.data),await r.nextGate(Fi,n.data)},getInputNames:()=>[{name:ji.event,type:fe.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??fe.Anything};return[{name:Ui,...t},{name:Ri,...t},{name:Fi,...t}]}};const Wi=()=>({name:"myVar",type:fe.Anything,reactive:!0,defaultValue:""}),Gi=Object.freeze({set:"set",read:"read"}),Vi="value";var Hi={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Wi(),...i};if(t.name!==Gi.set){if(t.name===Gi.read){const e=$r({variableName:s.name,readerWidgetId:r.id}),t=e?e.value:s.defaultValue;await r.nextWidget(Vi,{type:s.type,value:t})}}else{if(n.data.type!==s.type&&s.type!==fe.Anything)return;await _r({variableName:s.name,value:n.data.value,setByWidgetId:r.id,type:s.type})}},getInputNames:e=>{const t={...e};return[{name:Gi.set,type:t.type||fe.Anything},{name:Gi.read,type:fe.Anything}]},getOutputNames:e=>{const t={...e};return[{name:Vi,type:t.type||fe.Anything}]},initialize:async e=>{const t=e.getState(),n={...Wi(),...t};if(n.$$abortListener)try{n.$$abortListener()}catch(t){console.warn(`Error aborting variable listener for widget ${e.widgetId}: `,t)}wr({variableName:n.name,type:n.type,createdByWidgetId:e.widgetId});const r=Cr({variableName:n.name,type:n.type,widgetId:e.widgetId,onValueChange:async t=>{const n=e.getState();void 0!==t.value&&(n.type!==fe.Anything&&t.type!==n.type||n.reactive&&await e.nextWidget(Vi,{type:t.type,value:t.value}))}});e.setState({...n,$$abortListener:r})},terminate:async e=>{const t=e.getState(),n={...Wi(),...t};n.$$abortListener&&n.$$abortListener(),Ir({variableName:n.name,createdByWidgetId:e.widgetId})}};let zi;var qi=e=>{zi=e},Ki=()=>{if(!zi)throw new Error("Hub Connector not set");return zi};const Ji=e=>{const t=ie(e);return t?.name||""},Yi=async(e,t=!1)=>{const n=Ki();let r=e.$$$serviceId;if(!e.service)return console.log("Aborting service initialization, missing property `service` in state."),null;if(!r||t){const t=await n.getCompatibleService(e.service.name,e.service.version,"^");if(!t)return null;r=t.sessionId}return r};var Xi={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const s=Ki();let o=i.$$$serviceId;if(!o){const e=s.getCachedServices().available.find((e=>e.name===i.service?.name&&e.version===i.service?.version));if(!e)return;o=e.sessionId,i.$$$serviceId=o,r.setState(i)}const a=i.service?.variants?.find((e=>e.id===i.variantId)),c=a?i.dynamicInputs[a.id]||a?.inputs||[]:i.service?.inputs||[];if(!c?.length)return;if(!a&&i.service?.ignoreParentEvents)return;const l=i.service?.processingTimeoutSec,d=i.service?.name&&r.eventContext?.[i.service?.name];return s.onParentEvent({recipeId:r.recipePoolId,recipeName:Ji(r.recipePoolId),data:n.data,targetServiceSessionId:o,currentState:i.customState,targetVariantId:i.variantId,target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:l?1e3*l:0,async:i.service?.asyncParentEvents},eventContext:d})},getInputNames:async e=>{const t=e.variantId;if(t&&e.dynamicInputs?.[t])return[...e.dynamicInputs[t]||[]];if(!t)return e.service?.inputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.inputs||[]}return[]},getOutputNames:async e=>{const t=e.variantId;if(t&&e.dynamicOutputs?.[t])return[...e.dynamicOutputs[t]||[]];if(!t)return e.service?.outputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.outputs||[]}return[]},initialize:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=ie(e.recipePoolId),r=n?.name||"",i=Ki(),s=await Yi(t);if(s)try{return await i.initializeServiceInstance({recipeId:e.recipePoolId,sessionId:s,recipeName:r,widgetId:e.widgetId,recipeType:e.recipeType,variantId:t.variantId})}catch(t){if("FNC_NOT_FOUND"!==t?.errCode){if(!!("string"!=typeof t||!t.match('^Function ".*" not found.$')))throw t;console.warn(`Widget [${e.widgetId}] does not have an init function.`)}}else console.log(`Aborting service initialization, "${t.service?.name}" was not found in the current Hub.`)},terminate:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=Ki(),r=await Yi(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const Zi=Object.freeze({Image:"image"}),Qi=Object.freeze({Image:"image"}),es=()=>({filters:[{name:"grayscale",value:"0.5",id:"d-1"}]});var ts={onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:"0.5",id:"d-1"}],...r.getState()};if(t.name===Zi.Image&&n.data.type===fe.ImageData){if(!je(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas?.getContext||(i.$$memCanvas=Ce(e.width,e.height)),i.$$context?.drawImage||(i.$$context=i.$$memCanvas.getContext("2d")),i.$$memCanvas.width!==e.width&&(i.$$memCanvas.width=e.width),i.$$memCanvas.height!==e.height&&(i.$$memCanvas.height=e.height),r.setState(i),i.$$context.putImageData(e,0,0),i.filters.length?i.$$context.filter=i.filters.map((e=>{let t="";return"blur"===e.name?t="px":"hue-rotate"===e.name&&(t="deg"),`${e.name}(${parseFloat(e.value)}${t})`})).join(" "):i.$$context.filter="none",i.$$context.drawImage(i.$$memCanvas,0,0);const t=i.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(Qi.Image,{type:fe.ImageData,value:t})}},getInputNames:()=>[{name:Zi.Image,type:fe.ImageData}],getOutputNames:()=>[{name:Qi.Image,type:fe.ImageData}],getDefaultState:es};const ns="loaded";var rs={onParentEvent:async(e,t,n,r)=>r.nextWidget(ns,{value:!0,type:fe.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:ns,type:fe.Boolean,description:"Triggered when the recipe is fully loaded"}]};var is={onParentEvent:async()=>{},getInputNames:()=>[],getOutputNames:()=>[],getDefaultState:()=>({text:"",color:"#eac43e",size:{width:300,height:200}})};var ss={onParentEvent:async(e,t,n,r)=>{try{const e=((e,t)=>{switch(t){case fe.Number:case fe.Boolean:case fe.String:return String(e);case fe.Array:case fe.JsonObj:case fe.Rect:case fe.Point:return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));case fe.ArrayBuffer:if(e instanceof ArrayBuffer){if(ee)return Buffer.from(e).toString("base64");{const t=new Uint8Array(e),n=t.length,r=new Array(n);for(let e=0;e<n;e++)r[e]=String.fromCharCode(t[e]);return btoa(r.join(""))}}throw new Error("Type is ArrayBuffer but value is not an ArrayBuffer");case fe.ImageData:{if(!je(e))throw new Error("Expected ImageData");const t=e,n=Ce(t.width,t.height),r=ke(n);if(!r)throw new Error("Failed to get canvas context");r.putImageData(t,0,0);const i=n.toDataURL("image/png");if(!i)throw new Error("Failed to convert canvas to data URL");return i.split(",")[1]}default:return String(e)}})(n.data.value,n.data.type);return r.nextWidget("text",{type:fe.String,value:e})}catch(e){return r.nextWidget("error",{type:fe.String,value:e instanceof Error?e.message:"Failed to stringify object"})}},getInputNames:()=>[{name:"object",type:[fe.Number,fe.String,fe.ArrayBuffer,fe.Array,fe.Boolean,fe.JsonObj,fe.Rect,fe.Point,fe.ImageData]}],getOutputNames:()=>[{name:"text",type:fe.String},{name:"error",type:fe.String}],getDefaultState:()=>({})};const os=e=>{if(Array.isArray(e))return e.map(((e,t,n)=>null===e||"object"!=typeof e?{value:e,"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}:{...os(e),"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}));if("object"==typeof e&&null!==e){const t={};for(const n in e){const r=e[n];t[n]=os(r)}return t}return e},as=(e,t)=>{const n=(e=>{const t=new Date;return{input:"object"==typeof e&&null!==e?os(e):{value:e},date:{year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hours:t.getHours(),minutes:t.getMinutes(),seconds:t.getSeconds(),milliseconds:t.getMilliseconds(),time:t.getTime(),dayOfWeek:t.getDay(),dayName:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()],shortDayName:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getDay()],date:t.getDate(),fullYear:t.getFullYear(),timezoneOffset:t.getTimezoneOffset(),UTCDate:t.getUTCDate(),UTCDay:t.getUTCDay(),UTCFullYear:t.getUTCFullYear(),UTCHours:t.getUTCHours(),UTCMilliseconds:t.getUTCMilliseconds(),UTCMonth:t.getUTCMonth()+1,UTCMinutes:t.getUTCMinutes(),UTCSeconds:t.getUTCSeconds(),isoString:t.toISOString(),localeString:t.toLocaleString()}}})(t);return l.render(e,n)},cs=()=>({text:"",format:"Text"});var ls={onParentEvent:async(e,t,n,r)=>{const i={text:"",format:"Text",...r.getState()},s=as(i.text,n.data.value);return r.nextWidget("text",{type:fe.String,value:s})},getInputNames:()=>[{name:"input",type:fe.Anything}],getOutputNames:()=>[{name:"text",type:fe.String}],getDefaultState:cs};const ds=()=>({expression:""});var us={onParentEvent:async(e,t,n,r)=>{const i={expression:"",...r.getState()},s=((e,t)=>{const n=Symbol("error"),r=`\n // 'data' is an argument to this function, passed by new Function call.\n // 'SError' is also an argument, providing the error symbol.\n // 'this' inside this function (created by new Function) is the global object.\n\n\t\t// Shadow eval and Function in this non-strict scope.\n\t\tvar eval = undefined;\n\t\tvar Function = undefined;\n\n // Define the sandbox environment\n const sandboxEnvironment = {\n // Make input 'data' accessible\n data: data,\n \n // Safe console (bind methods to the original console)\n console: undefined,\n\n // Mocked/disabled globals\n process: undefined,\n document: undefined,\n navigator: undefined,\n \n require: undefined,\n // eval and Function are shadowed by var declarations above\n \n // Allowed safe globals (pointing to the real ones, accessed via 'this')\n Math: this.Math,\n Date: this.Date,\n JSON: this.JSON,\n Array: this.Array,\n Object: this.Object,\n String: this.String,\n Number: this.Number,\n Boolean: this.Boolean,\n RegExp: this.RegExp,\n // Error: this.Error, // Not Allow Error constructor\n Symbol: this.Symbol, // Allow Symbol constructor\n Map: this.Map,\n Set: this.Set,\n Promise: this.Promise, // Allow Promise if async expressions are intended\n // setTimeout, setInterval, fetch, etc., are deliberately omitted\n };\n\n // Assign the sandboxEnvironment to act as the 'global' context variables\n const global = sandboxEnvironment;\n const window = sandboxEnvironment;\n const globalThis = sandboxEnvironment;\n\n // Shadow top-level variables that might be accessed directly,\n // ensuring they use the sandboxed versions.\n const process = sandboxEnvironment.process;\n const document = sandboxEnvironment.document;\n const navigator = sandboxEnvironment.navigator;\n const console = sandboxEnvironment.console; // Use the sandboxed console for the expression\n const require = sandboxEnvironment.require;\n // 'eval' and 'Function' are already shadowed by var declarations\n\n // The expression will be evaluated in this scope.\n // 'data' is available as it's an argument to the outer function.\n // 'global.xxx' will resolve to 'sandboxEnvironment.xxx'.\n // 'process.yyy' will resolve to 'sandboxEnvironment.process.yyy'.\n \n return () => {\n "use strict"; // Apply strict mode only to the expression evaluation scope\n const abort = Symbol('abort'); // Local symbol for the expression's optional special return value\n\n let result;\n try {\n // Strict mode can add a layer of security and prevent some common errors.\n // It also changes 'this' binding within the expression if it uses 'this'.\n // If the expression uses 'this', under strict mode it would be undefined unless explicitly set.\n // For expressions not using 'this', strict mode is generally safer.\n result = (() => { return ${t}; })();\n } catch(e) {\n // Log the error using the sandboxed console\n // Use 'instanceof Error' to ensure 'e' has a message property.\n const errorMessage = e instanceof Error ? e.message : String(e);\n return {\n\t\t\t\t\terror: 'Error during expression execution: ' + errorMessage, \n\t\t\t\t\tvalue: null\n\t\t\t\t}; // Return the SError symbol passed into this function's scope\n }\n \n\t\t\t// allows ternary expressions that return 'abort' to cancel the evaluation\n if (result !== abort) {\n // Original logic: if result is strictly true, and expression wasn't literally "true", return original data.\n if (result === true && String(expression).trim() !== 'true') {\n return {value: data, error: null}; \n } else {\n return {value: result, error: null};\n }\n }\n \n // If the expression explicitly returned the 'abort' symbol\n return {value: abort, error: null}; \n }\n // End of functionBody template literal\n `;try{return new Function("data","SError",r)(e,n).call({})}catch(e){return{error:e.message,value:null}}})(n.data.value,i.expression);if("symbol"==typeof s.value)return;if(s.error)throw new Error(s.error);if(Number.isNaN(s.value))throw new Error("Expression resulted in NaN");if(void 0===s.value||null===s.value)return;const o=Fe(s.value);return o!==i.$$lastResultType&&r.setState({...i,$$lastResultType:o}),r.nextWidget("result",{type:o,value:s.value})},getInputNames:()=>[{name:"data",type:fe.Anything}],getOutputNames:e=>[{name:"result",type:e.$$lastResultType||fe.Anything}],getDefaultState:ds};var ps={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type});try{await r.nextWidget("event",n.data)}catch(e){const t=e;await r.nextWidget("error",{type:fe.JsonObj,value:{error:{message:e.message,targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType,stack:e.stack},inputEvent:{type:n.data.type,data:n.data.value}}})}},getInputNames:()=>[{name:"event",type:fe.Anything}],getOutputNames:e=>[{name:"event",type:{...e}.$$lastEventType??fe.Anything},{name:"error",type:fe.JsonObj,jsonShape:{error:fe.JsonObj,inputEvent:fe.JsonObj}}]};const gs={},hs=Object.freeze({output:"output"}),fs=Object.freeze({read:"read",clear:"clear"}),ms=()=>({$$$time:0,totalInputs:1});var ys={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalInputs:1,...r.getState()};if(gs[r.id]||(gs[r.id]={}),t.name===fs.clear)return gs[r.id]={},void r.setState(i);const s=t.name===fs.read;if(!(s||n.data.type!==fe.JsonObj&&n.data.type!==fe.Anything&&n.data.type!==fe.Rect||"object"!=typeof n.data.value||null===n.data.value||Array.isArray(n.data.value))){const e=gs[r.id]||{};gs[r.id]={...e,...n.data.value}}if(s){const e={...gs[r.id]};return gs[r.id]={},r.setState({...i}),r.nextWidget(hs.output,{type:fe.JsonObj,value:e})}},getInputNames:e=>{const t={$$$time:0,totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:fs.clear,type:fe.Anything},{name:fs.read,type:fe.Anything,triggerPort:!0}),n},getOutputNames:()=>[{name:hs.output,type:fe.JsonObj}],getDefaultState:ms,initialize:async e=>{gs[e.widgetId]={}},terminate:async e=>{delete gs[e.widgetId]}};const vs={},bs=Object.freeze({output:"output",index:"index",finish:"finish"}),Ss=Object.freeze({array:"array",next:"next",clear:"clear"}),ws=()=>({autoLoop:!1,autoClear:!1,$$outputType:fe.Anything,totalItems:0,currentIndex:0});const Is={input:it,counter:at,elapsed:dt,ifGate:ht,skipEvent:yt,between:wt,map:$t,parser:Et,slider:Nt,suspend:Tt,display:Bt,json:Ut,arrayItem:Mt,extractImage:zt,imageConvolution:Xt,firstEvent:tn,pixelDraw:dn,randomBetween:hn,arrayCombine:bn,clock:_n,multiplication:En,object:Bn,widgetGroup:Rn,script:Fr,base64ToImageData:qr,jsonParse:Xr,text:ti,imageCrop:si,imageResize:li,value:gi,imageWarp:yi,widgetBundle:Di,sequence:Mi,variable:Hi,hubService:Xi,imageFilter:ts,recipeLoad:rs,note:is,stringify:ss,templateString:ls,expressionEval:us,rescue:ps,objectCombine:ys,loop:{onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...ws(),...i};if(t.name===Ss.clear)return delete vs[r.id],void r.setState({...ws(),autoLoop:s.autoLoop,autoClear:s.autoClear});if(t.name!==Ss.array)t.name===Ss.next&&await(async e=>{const t=e.id,n=vs[t],r={...ws(),...e.getState()};if(n&&n.index<n.list.length){const i=n.index,s=n.list[i];await e.nextWidget(bs.index,{type:fe.Number,value:i}),await e.nextWidget(bs.output,{type:r.$$outputType,value:s}),n.index++,e.setState({...r,currentIndex:n.index}),n.index===n.list.length&&(await e.nextWidget(bs.finish,{type:fe.Boolean,value:!0}),r.autoClear?(delete vs[t],e.setState({...ws()})):(n.index=0,e.setState({...r,currentIndex:0})))}})(r);else if((n.data.type===fe.Array||n.data.type===fe.Anything)&&Array.isArray(n.data.value)){const e=n.data.value,t=e[0],i=void 0!==t?Fe(t):fe.Anything,o={list:e,index:0};vs[r.id]=o;const a={...s,$$outputType:i,totalItems:e.length,currentIndex:0};if(r.setState(a),a.autoLoop&&e.length>0){for(const t of e){const e=o.index;r.setState({...a,currentIndex:e}),await r.nextWidget(bs.index,{type:fe.Number,value:e}),await r.nextWidget(bs.output,{type:a.$$outputType,value:t}),o.index++}await r.nextWidget(bs.finish,{type:fe.Boolean,value:!0}),a.autoClear?(delete vs[r.id],r.setState({...a,$$outputType:fe.Anything,totalItems:0,currentIndex:0})):(o.index=0,r.setState({...a,currentIndex:0}))}}},getInputNames:()=>[{name:Ss.array,type:fe.Array},{name:Ss.next,type:fe.Anything},{name:Ss.clear,type:fe.Anything}],getOutputNames:e=>{const t={...ws(),...e};return[{name:bs.index,type:fe.Number},{name:bs.output,type:t.$$outputType},{name:bs.finish,type:fe.Anything}]},getDefaultState:ws,initialize:async e=>{const t={...ws(),...e.getState()};vs[e.widgetId]={list:[],index:0},e.setState({...t,currentIndex:0,totalItems:0})},terminate:async e=>{delete vs[e.widgetId]}},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:fe.Boolean}]}},_s={},$s=async()=>{if(!Object.keys(_s).length)for(const e in Is){const t=Is[e];_s[e]=Object.freeze({...t})}};var Cs=e=>{if(_s[e])return _s[e];throw new Error(tt(Qe,e))},ks=$s;const Es=new o,xs="invoked";let As={},Ns={},Ps={},Os={};const Ts=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var Ls=(e,t,n,r,i)=>{const s=Ts(e,t,n),o=Ts(e,t),a=Ts(e,t,"produced"),c=Ps[o],l=Date.now();Os[o]=l,As[s]={data:r,sourcePortName:n,...i?{target:{widgetId:i.widgetId,portName:i.portName}}:{}},Es.emit(a,{currentTime:l,prevTime:c,...i?{targetPort:i?.portName}:{}})},Bs=(e,t,n,r,i)=>{const s=Ts(e,t,n),o=Ts(e,t),a=Ts(e,t,xs),c=Ps[o],l=Date.now();Ps[o]=l,Ns[s]={data:r,sourcePortName:n,...i?{source:{widgetId:i.widgetId,portName:i.portName}}:{}},Es.emit(a,{prevTime:c,currentTime:l,targetPort:n,sourceInfo:i})},Ds=()=>{As={},Ns={},Ps={},Os={},Es.clearListeners()};const js={};let Us={};const Rs=new o;let Fs=!1,Ms=!1,Ws=!1,Gs=null,Vs=null;const Hs="processing-state-change",zs="error-event",qs={abortRequested:!1,isPaused:!1,pausePromise:null,pausePromiseResolve:null,lastPausedWidgetId:null},Ks=e=>(Vs=e,Rs.emit(Hs,e)),Js=(e,t)=>`${e}-${t}`,Ys=(e,t)=>`state-change:${Js(e,t)}`,Xs=e=>{const{thingId:t,widgetId:n}=e,r=Js(t,n);return js[r]||{isProcessing:!1}},Zs=()=>{qs.abortRequested=!1,qs.isPaused=!1},Qs=e=>(qs.pausePromise||(qs.isPaused=!0,qs.pausePromise=new Promise((e=>{qs.pausePromiseResolve=e})),e&&(qs.lastPausedWidgetId=e),Ks({isProcessing:!0,isPaused:!0,...e?{pauseTrapWidgetId:e}:{}})),qs.pausePromise);var eo,to,no=async e=>{const{thingId:t,widgetId:n}=e,r=Js(t,n),i=Ys(t,n),s=Xs({thingId:t,widgetId:n});if(s.isProcessing)return;const o={isProcessing:!0,isPaused:!1,startTime:Date.now()};js[r]=o,Fs||(Fs=!0,Gs=null,await Ks({isProcessing:!0,isPaused:!1})),await Rs.emit(i,{thingId:t,widgetId:n,prevState:s,newState:o})},ro=async e=>{const{thingId:t,widgetId:n,error:r}=e,i=Js(t,n),s=Ys(t,n),o=Xs({thingId:t,widgetId:n}),a={isProcessing:!1,isPaused:!1,startTime:o.startTime,endTime:Date.now(),error:r};js[i]=a,await Rs.emit(s,{thingId:t,widgetId:n,prevState:o,newState:a}),r&&(Gs=r,await Rs.emit(zs,r)),Fs&&0===Object.values(js).filter((e=>e.isProcessing)).length&&(Fs=!1,Ms=!1,Zs(),await Ks({isProcessing:!1,isPaused:!1}))},io=()=>{Fs=!1;for(const e in js)delete js[e];qs.abortRequested=!1,qs.isPaused=!1,qs.pausePromise=null,qs.pausePromiseResolve=null,qs.lastPausedWidgetId=null,Rs.clearListeners()},so=()=>qs.abortRequested,oo=e=>{qs.lastPausedWidgetId=e,qs.isPaused=!0,Ks({isProcessing:!0,isPaused:!0,pauseTrapWidgetId:e})},ao=()=>Ms||Ws?null:qs.pausePromise,co=e=>Ws?null:Us[e]??null,lo=()=>Ms,uo=e=>Qs(e);!function(e){e.ServiceCreationLog="service-creation-log"}(eo=eo||(eo={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(to=to||(to={}));let po={},go={},ho=null;const fo=(e,t)=>{const n=(()=>{if(null===ho)throw new Error("Recipe execution type not set, please set the execution type using `setRecipeExecutionType`");return ho===Gn.Desktop})();let r=n?go[e]:void 0;return r||(r=(e=>{const{widgets:t,targetId:n,allowedTypes:r}=e;if(!t[n])return[];const i=new Set;Object.values(t).forEach((e=>{e.children?.forEach((e=>i.add(e.childId)))}));const s=Object.keys(t).filter((e=>!i.has(e))),o=s.length>0?s:Object.keys(t),a=[],c=(e,i,s)=>{if(s.has(e))return;s.add(e);const o=t[e],l=!r||r.includes(o.type),d=[...i];l&&d.push(e),e===n?a.push(d.join("/")):o.children?.forEach((e=>c(e.childId,d,s))),s.delete(e)};return o.forEach((e=>c(e,[],new Set))),[...new Set(a)]})({widgets:t,targetId:e,allowedTypes:[ze.hubService]}),n&&(go[e]=r)),r},mo=(e,t,n)=>{fo(t,n).forEach((n=>{po[n]={eventContext:e,widgetId:t}}))},yo=(e,t)=>{const n=t[e].state,r=n.service?.name;if(!r)return[];const i=fo(e,t),s=new Map;for(const e of i){const n=e.split("/");let i="";for(let e=0;e<n.length-1;e++){i=0===e?n[e]:`${i}/${n[e]}`;const o=po[i];if(o&&!s.has(o.widgetId)){const e=t[o.widgetId].state;e.service?.name===r&&s.set(o.widgetId,{path:i,data:o,pathSegments:i.split("/").length})}}}return Array.from(s.values())},vo=()=>{po={}},bo=e=>{ho=e},So=()=>{po={},go={}};let wo,Io,_o,$o=!1,Co=0;const ko=async e=>{const{widgetId:t,thingId:n,recipeId:r,targetPortName:i,data:s}=e,o=se(r,n);if(!o)return;const a=o.gates[t];if(!a||a.disabled)return;const c={...s,timestamp:Date.now()},l=Cs(a.type),d=Po({gateId:t,originalEvent:c,blockRecipeId:o.recipeId,blockDbId:o.id,blockVersion:o.version,recipeId:r});if(d&&l.onParentEvent){const e={name:i};return wo&&await wo({recipeId:r,blockId:o.recipeId,gateId:t,targetPort:e.name,data:s}),l.onParentEvent(null,e,{originalEvent:c,data:{...c}},d)}},Eo=async e=>{const{interruptDriven:t,childGateId:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c}=e;let{originalEvent:l,block:d}=e;if(!t&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!t&&!l)throw new Error("Missing parameter ['originalEvent']");t&&(l={timestamp:Date.now(),type:fe.Boolean,value:!0});const u=l;if("string"==typeof d){const e=se(r,d);if(!e)return;d=e}const p=d.gates[n];if(!p||p.disabled)return;const g=a.findIndex((e=>e.name===i)),h=Cs(p.type),f=Po({gateId:n,originalEvent:u,blockRecipeId:d.recipeId,blockDbId:d.id,blockVersion:d.version,recipeId:r});if(f&&h.onParentEvent&&-1!==g){wo&&await wo({recipeId:r,blockId:d.recipeId,gateId:n,targetPort:s.name,data:o,sourceGate:t?"interrupt_widget":c,sourcePort:t?ce:i});const e={name:a[g].name,type:a[g].type,...a[g].jsonShape?{jsonShape:a[g].jsonShape}:void 0};return Bs(d.recipeId,n,s.name,o,c?{widgetId:c,portName:i}:void 0),h.onParentEvent(e,s,{originalEvent:u,data:o},f)}},xo=async e=>{const{portName:t,originalEvent:n,data:r,currentGateId:i,blockRecipeId:s,thingDbId:o,thingVersion:a,recipeId:c,eventContext:l}=e,d=ie(c);if(!d)throw new Error(`Failed to find recipe "${c}" in cache`);const u=d.dbInfo.recipeType,p=oe(c,s,i);if(!p)return;const g={...r,timestamp:n.timestamp},h=Cs(p.type);let f;f=p.type===ze.input?h.getOutputNames(p.state,{thingRecipeId:s,thingDbId:o,thingVersion:a,id:i,recipeId:c,recipeType:u,recipePoolId:c}):await h.getOutputNames(p.state,{recipePoolId:c,recipeType:u,thingRecipeId:s,widgetId:i});const m=f.findIndex((e=>e.name===t));if(-1!==m){const e=se(c,s);if(!e)return;Ls(s,i,t,g);let r=null;const o=p.children.length;if(p.type===ze.hubService&&l){const t=p.state,n=t.service?.name;n&&mo(l,p.id,e.gates)}try{for(let a=0;a<o;a++){const o=e.gates[p.children[a].childId];if(o?.disabled)continue;const l=Ge(p.children[a]?.sourcePort),d=Ge(p.children[a]?.targetPort);if(l.portName===t&&o&&!o.disabled){if($o&&ao()&&(oo(o.id),await ao()),co(o.id)&&!lo()&&"innerInput"!==d?.portType){const e=uo(o.id);await e}if($o&&so())break;const a=Cs(o.type);let l;const h={recipePoolId:c,recipeType:u,thingRecipeId:s,widgetId:i};l=o.type===ze.hubService?await a.getInputNames(o.state,h):a.getInputNames(o.state,h);const m=l.find((e=>e.name===d.portName));if(m){$o&&await no({thingId:s,widgetId:o.id}),Co++;if(!await Eo({interruptDriven:!1,childGateId:o.id,block:e,recipeId:c,sourcePortName:t,targetPort:{name:m.name},data:p.returnOriginalEvent?n:g,sourceOutputNames:f,sourceGateId:p.id,originalEvent:n}).then((()=>!0)).catch((e=>{const n=o.type===ze.hubService&&"CHILD_WIDGET_ERROR"===e.errCode;if(e instanceof tr)throw e;if(n&&e.errData){const t=e.errData;throw new tr(e.error||e.message||("string"==typeof e?e:JSON.stringify(e)),{targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType})}if(!r){const n="string"==typeof e?e:e.message||JSON.stringify(e);r={targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,error:n}}throw new tr(e.message||("string"==typeof e?e:JSON.stringify(e)),{stack:e.stack,targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,sourceWidgetId:p.id,targetWidgetType:o.type,sourceWidgetType:p.type})})).finally((()=>{if(Co--,$o)return ro({thingId:s,widgetId:o.id,error:r})})))break}}}}catch(e){if(e instanceof tr)throw e;console.error(`Error processing next widget [${i}]: ${e}`)}finally{Co<0&&(console.warn("Active execution counter is negative, this should never happen"),Co=0),0===Co&&vo()}}},Ao=async(e,t,n,r)=>{const i=ie(r);if(!i)return null;const s=se(r,n);if(!s)return s;const o=s.gates,a=s.gates[t],c=Cs(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),d=l.findIndex((t=>t.name===e));if(-1!==d){const e=((e,t,n)=>{for(const r in n){const i=n[r],s=i.children.length;for(let n=0;n<s;n++){const r=i.children[n],s=Ge(r.targetPort);if(r.childId===e&&s.portName===t)return i}}return null})(t,l[d].name,o);if(e){const t=Cs(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},No=e=>{const{gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}=e;if(!ie(o))throw new Error(`Failed to find recipe "${o}" in cache`);if(!oe(o,r,t))throw console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),new Error(`Gate ${t} not found in block ${r} for recipe ${o}`);return async(e,a)=>xo({portName:e,originalEvent:n||{timestamp:Date.now(),type:a.type,value:a.value},data:a,currentGateId:t,blockRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o})},Po=e=>{const{gateId:t,originalEvent:n,blockRecipeId:r,blockDbId:i,blockVersion:s,recipeId:o}=e,a=ie(o);if(!a)throw new Error(`Failed to find recipe "${o}" in cache`);const c=oe(o,r,t);if(!c)return console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),null;const l=No({gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}),d=c.type===ze.hubService,u=d?yo(t,a.blocks[r].gates):[],p=u.reduce(((e,t)=>e.pathSegments>t.pathSegments?e:t),u[0]),g={id:t,type:c.type,recipePoolId:o,thingRecipeId:r,recipeType:a.dbInfo.recipeType,returnOriginalEvent:!!c.returnOriginalEvent,registerInterrupt:(e,n,i,s,a)=>Xe.createInterrupt(e,o,r,t,n,i,s,a),cancelInterrupt:e=>Xe.destroyInterrupt(e),nextWidget:l,nextGate:l,getParentAtPort:e=>Ao(e,t,r,o),getState:()=>Object.freeze({...c.state,...c.type===ze.input&&{customInputs:[]}}),setState:e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const n={...e,...c.type===ze.input&&!e.customInputs&&{customInputs:[]}},i={...c.state};c.state=n,Io&&Io({blockId:r,gateId:t,prevState:i,newState:{...n},recipeId:o})},...d&&p&&{eventContext:p.data.eventContext}};return g};Xe.setInvokeChildGateCb((async(e,t,n,r,i,s,o,a,c,l)=>Eo({interruptDriven:e,childGateId:t,block:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c,originalEvent:l})));const Oo=(e,t,n,r,i)=>{const s=oe(e,n,r);if(!s)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=(t,i,s,o)=>Xe.createInterrupt(t,e,n,r,i,s,o),a=()=>Object.freeze({...s.state,...s.type===ze.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...s.type===ze.input&&!e.customInputs&&{customInputs:[]}};s.state=t},l=async t=>{const r=((e,t,n)=>{const r=ie(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=se(e,t);if(!i)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(i.storageUnits||[]).includes(n))throw new Error(`The Thing "${t}" has no access to storage unit "${n}"`);return r.storage[n]||null})(e,n,t);return r};if(i){return{getState:a,setState:c,registerInterrupt:o,getStorageData:l,nextWidget:No({gateId:r,thingRecipeId:n,thingDbId:s.id,thingVersion:"default",recipeId:e}),recipePoolId:e,recipeType:t,thingRecipeId:n,widgetId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r}},To=new o,Lo="invoked",Bo="state",Do=()=>{Xe.destroyAllInterrupts()},jo=async(e,t,n)=>{const r=ie(e),i=oe(e,t,n);if(i&&r){const s=Cs(i.type);if(s&&"function"==typeof s.terminate){const i=((e,t,n,r)=>Oo(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(i)try{await s.terminate(i)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},Uo=async e=>{const{recipePoolId:t,thingRecipeId:n,widgetRecipeId:r,options:i}=e,s=ie(t),o=oe(t,n,r);if(o&&s){const e=Cs(o.type);if(e&&"function"==typeof e.initialize){const a=((e,t,n,r)=>Oo(e,t,n,r,!0))(t,s.dbInfo.recipeType,n,r);if(a){const t=e.initialize;try{(e=>{if(e.type===ze.script){const t=e.state;if((t.version||0)<2){const n=Object.keys(e.variablesListener||{});for(const t of n)if(e.variablesListener){const n=Sr(t);e.variablesListener[n]=e.variablesListener[t],delete e.variablesListener[t],delete e.variables}t.version=2}}})(o),await t(a,i||{})}catch(e){throw console.warn(`Error initializing widget "${r}" in thing "${n}": `,e),e}}}}},Ro=(e,t)=>{const n=ie(t);if(n)for(const t in n.blocks){const r=n.blocks[t];for(const t in r.gates)if(t===e)return{widget:r.gates[t],thing:r}}return null},Fo=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,Mo=e=>{To.emit(Fo(Bo),e),To.emit(Fo(Bo,e.blockId,e.gateId),e)};wo=async e=>{await To.emit(Fo(Lo),e),await To.emit(Fo(Lo,e.blockId,e.gateId),e)},(e=>{Io=e})(Mo);var Wo,Go,Vo,Ho,zo,qo,Ko,Jo,Yo,Xo,Zo,Qo,ea,ta=async(e,t,n,r,i)=>{const s=ae(e,{id:t,authorId:r,version:n,recipeType:i});Ds(),So(),bo(i);const o=ie(s);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=X.STARTING,o.addLog("recipe registered")),s},na=async e=>{const t=ie(e);var n;if(!t)return null;t.addLog("terminating recipe"),Do(),io();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await jo(e,n,t)}te[n=e]&&delete te[n]},ra=async(e,t)=>{const n=ie(e),r=[],i=[];if(n){Er({recipePoolId:e,thingId:ge});for(const s in n.blocks){const o=n.blocks[s];if(!t||!Array.isArray(t)||t.includes(s))for(const t in o.gates)try{if(n.dbInfo?.recipeType===Gn.Desktop){const e=o.gates[t];if(e.type===ze.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===ze.recipeLoad&&i.push(e)}await Uo({recipePoolId:e,thingRecipeId:s,widgetRecipeId:t,options:{keepCurrentState:!0}})}catch(e){r.push({widgetId:t,error:e.message})}}}return{failed:r,sendToInputWidget:(t,n,r=ge)=>(async(e,t,n,r)=>{const i=ie(n),s=se(n,r),o=Date.now();if(s&&i)for(const i in s.gates){const a=s.gates[i];if(a.type===ze.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=Cs(a.type),l={...t,timestamp:o},d=Po({gateId:i,originalEvent:l,blockRecipeId:r,blockDbId:s.id,blockVersion:s.version,recipeId:n});if(d&&e.processEvent){const s={...d,getState:d.getState};wo&&await wo({recipeId:n,blockId:r,gateId:i,targetPort:rt,data:t}),_o?await _o(r,n,c,t):await e.processEvent(l,s)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of i)await ko({widgetId:t.id,thingId:ge,recipeId:e,targetPortName:ns,data:{type:fe.Boolean,value:!0}})}}},ia=e=>{qi(e)},sa=(e,t,n,r=!1)=>{const i=Ro(t,e);if(i){const{widget:s,thing:o}=i,a={...s.state};s.state=n,r&&Mo({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},oa=(e,t)=>{const n=Ro(t,e);return n?n.widget.state:null},aa=async e=>{const{recipePoolId:t,currentGateId:n,sourcePortName:r,originalEvent:i,data:s,eventContext:o}=e,a=Ro(n,t);if(a)return xo({portName:r,originalEvent:i,data:s,currentGateId:n,blockRecipeId:a.thing.recipeId,thingDbId:a.thing.id,thingVersion:a.thing.version,recipeId:t,eventContext:o})};!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(Wo||(Wo={})),function(e){e.UserFriendlyName="user_friendly_name",e.UserFriendlyDescription="user_friendly_description",e.InternalDescription="internal_description",e.TierLevel="tier_level",e.ProductFeatures="product_features",e.UserSubscribeCode="subscription_code"}(Go||(Go={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Vo||(Vo={})),function(e){e.Bundle="bundle",e.Group="group"}(Ho||(Ho={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(zo||(zo={})),function(e){e.Cloud="cloud",e.Web="web"}(qo||(qo={})),function(e){e.Cpu_128M="kmu-cpu-128m",e.Cpu_256M="kmu-cpu-256m",e.Cpu_512M="kmu-cpu-512m",e.Cpu_1024M="kmu-cpu-1024m",e.Cpu_2048M="kmu-cpu-2048m",e.Cpu_4096M="kmu-cpu-4096m"}(Ko||(Ko={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Jo||(Jo={})),function(e){e.InstallInProgress="installation-in-progress"}(Yo||(Yo={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Xo||(Xo={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Zo||(Zo={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Qo||(Qo={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.UninstallHubService="uninstall_hub_service",e.ExportRecipe="export_recipe"}(ea||(ea={}));const ca=(e,t)=>((e,t,n)=>{const r=Buffer.from(n,"base64"),i=r.subarray(0,16),s=r.subarray(16).toString("base64"),o=u(e,t,32),a=p("aes-256-cbc",o,i);let c=a.update(s,"base64","utf8");return c+=a.final("utf8"),c})(e.id||"recipe.kemu","kemu",t);var la,da,ua,pa,ga,ha,fa,ma;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(la||(la={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(da||(da={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(ua||(ua={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(pa||(pa={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(ga||(ga={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(ha||(ha={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(fa||(fa={})),function(e){e.IPC="ipc",e.WS="ws"}(ma||(ma={}));const ya=e=>{try{return JSON.parse(e)}catch(e){return null}},va="undefined"!=typeof window,ba={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Sa={protocolPrefix:4,txtLength:4},wa=Object.values(ba).reduce(((e,t)=>e+t),0),Ia=Object.values(Sa).reduce(((e,t)=>e+t),0),_a=["width","height","colorSpace"],$a=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${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,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)Object.hasOwn(e,n)||_a.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={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};s=o(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:s}:null},Ca=(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 s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},ka=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(Object.hasOwn(n,s)){const{index:o,length:a,binaryType:c}=n[s];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&Ca(e,s,l)}return e},Ea=e=>f(e),xa="KMSG",Aa="KCMD",Na=Ea("klProtocol");var Pa={encode:(e,t,n)=>{const r={json:e.json},i=$a(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,d=ba.protocolPrefix+ba.protocolVersion+ba.jsonLength+ba.binaryLength+ba.fromServiceId+ba.toServiceId+ba.sentAt+l+o,u=Buffer.alloc(d),p=Date.now();let g=0;return u.write(xa,g),g+=ba.protocolPrefix,u.writeUInt8(1,g),g+=ba.protocolVersion,u.writeUInt32LE(l,g),g+=ba.jsonLength,u.writeUInt32LE(o,g),g+=ba.binaryLength,u.writeUInt32LE(t,g),g+=ba.fromServiceId,u.writeUInt32LE(n,g),g+=ba.toServiceId,u.writeBigInt64LE(BigInt(p),g),g+=ba.sentAt,c.copy(u,g),g+=l,s&&o&&s.copy(u,g),u},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,ba.protocolPrefix);if(t+=ba.protocolPrefix,n!==xa)return null;if(e.byteLength<wa)return Na(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=ba.protocolVersion;const i=e.readUInt32LE(t);t+=ba.jsonLength;const s=e.readUInt32LE(t);t+=ba.binaryLength;const o=e.readUInt32LE(t);t+=ba.fromServiceId;const a=e.readUInt32LE(t);t+=ba.toServiceId;const c=e.readBigInt64LE(t);t+=ba.sentAt;const l=i+s,d=e.subarray(t,t+l),u=e.subarray(0,wa);let p=null;return e.byteLength-wa-i-s>0&&(p=e.subarray(wa+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[d],headerPackage:u},remaining:p}},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=ya(n);if(!i?.json)return Na("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&ka(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=wa+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<wa)return Na("Invalid Header Size"),e;let n=0;return n+=ba.protocolPrefix,n+=ba.protocolVersion,n+=ba.jsonLength,n+=ba.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=ba.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=Ia+r,s=Buffer.alloc(i);return s.write(Aa,t),t+=Sa.protocolPrefix,s.writeUint32LE(r,t),t+=Sa.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<Ia)return{command:null};const n=e.toString("utf-8",t,Sa.protocolPrefix);if(t+=Sa.protocolPrefix,n!==Aa)return{command:null};const r=e.readUInt32LE(t);t+=Sa.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-Ia-r;let o=null;s>0&&(o=e.subarray(Ia+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Oa="KMSG",Ta="KCMD",La=Ea("klProtocol"),Ba=new TextEncoder;var Da={encode:(e,t,n)=>{const r={json:e.json},i=$a(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Ba.encode(a),l=c.byteLength,d=new ArrayBuffer(ba.protocolPrefix+ba.protocolVersion+ba.jsonLength+ba.binaryLength+ba.fromServiceId+ba.toServiceId+ba.sentAt+l+o),u=new DataView(d),p=new Uint8Array(d),g=Date.now();let h=0;for(let e=0;e<4;++e)p[h++]=Oa.charCodeAt(e);return u.setUint8(h,1),h+=ba.protocolVersion,u.setUint32(h,l,!0),h+=ba.jsonLength,u.setUint32(h,o,!0),h+=ba.binaryLength,u.setUint32(h,t,!0),h+=ba.fromServiceId,u.setUint32(h,n,!0),h+=ba.toServiceId,u.setBigInt64(h,BigInt(g),!0),h+=ba.sentAt,p.set(c,h),h+=l,s&&o&&p.set(new Uint8Array(s),h),d},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<ba.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Oa)return null;if(e.byteLength<wa)return La.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=ba.protocolVersion;const s=t.getUint32(n,!0);n+=ba.jsonLength;const o=t.getUint32(n,!0);n+=ba.binaryLength;const a=t.getUint32(n,!0);n+=ba.fromServiceId;const c=t.getUint32(n,!0);n+=ba.toServiceId;const l=t.getBigInt64(n,!0);n+=ba.sentAt;const d=s+o,u=e.slice(n,n+d),p=new Uint8Array(e,0,wa);let g=null;if(e.byteLength-wa-s-o>0){g=new Uint8Array(e,wa+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[u],headerPackage:p.slice().buffer},remaining:g}},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 s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=ya(s);if(!a?.json)return La.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&ka(a.json,o,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,d=null;const u=wa+e.jsonLength+e.binaryLength;return c.byteLength>u&&(d=c.subarray(u),l=c.subarray(0,u)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:d?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<wa)return La("Invalid Header Size"),e;let n=0;n+=ba.protocolPrefix,n+=ba.protocolVersion,n+=ba.jsonLength,n+=ba.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=ba.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Ba.encode(e),r=n.byteLength,i=new ArrayBuffer(Ia+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=Ta.charCodeAt(e);return s.setUint32(t,r,!0),t+=Sa.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Ia)return{command:null};let r="";for(let e=0;e<Sa.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ta)return{command:null};const i=t.getUint32(n,!0);n+=Sa.txtLength;const s=e.byteLength-Ia-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-Ia)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(Ia+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};let ja=Pa;va&&(ja=Da);var Ua,Ra=ja;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Ua||(Ua={}));let Fa=Math.ceil(Date.now()/1e3);let Ma,Wa,Ga,Va,Ha,za=!1;var qa=()=>{za=!0},Ka=(e,t)=>{if(!Ma)throw new Error("Memory connection not set.");Ma.sendBuf(e,t)},Ja=e=>Wa=e,Ya=e=>Ha=e,Xa=e=>Ga=e,Za=e=>Va=e;const Qa=async(e,t=2)=>{const n=async(e,r)=>{if(Array.isArray(e))for(let i=0;i<e.length;i++){const s=e[i];if(s&&"object"==typeof s)if(Array.isArray(s))await n(s,r+1);else{const o=s._kemuType;void 0!==o?o===fe.ImageData&&(e[i]=await Ve(s)):r<t&&await n(s,r+1)}}else if("object"==typeof e&&null!==e){const i=Object.keys(e);for(const s of i){const i=e[s];if(i&&"object"==typeof i){const o=i._kemuType;void 0!==o?o===fe.ImageData&&(e[s]=await Ve(i)):r<t&&await n(i,r+1)}}}};return await n(e,1),e};Ea("klTransmissionManager"),Ea("ipcClient");Ea("kemuWidgetService"),k(process.argv.slice(2));const ec=e=>f(`runner:${e}`),tc=ec("connectionManager"),nc=ec("remoteInvoke"),rc=new function(e){const t={};let n=console.log;const r={};let i=e||String(Date.now());const s={},o=e=>!s[e],a=(e,t,n,r,i,s)=>{let a=va?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return o(r)&&(a=Ra.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,i,s,o)=>{if(!o)return!1;const c=o;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=r[c.functionName];if(t){const n=e=>{a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:s.sourceServiceId,send:i})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,s,a,c,l)=>{if(!s){const e="No send buffer function provided.";throw n&&n(e),e}Fa+=1;const d=`${i}-${Fa}-exec-${e.substring(0,10)}`,u={messageId:d,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};u.promise=new Promise(((e,t)=>{u.resolve=e,u.reject=t}));let p=va?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:r,messageId:d,type:"execute"}};o(c)&&(p=Ra.encode(g,a,c)),t[d]=u,n&&n(`Calling remote function "${e}" with message id "${d}"`);const h="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(u.fulfilled=!0,u.resolve([void 0]),delete t[d]):0===l?.timeout||h||(u.timer=setTimeout((()=>{n&&n(`Remote function ${d} timed out`);const r=t[d];r&&!r.fulfilled&&(r.fulfilled=!0,u.reject(`Function ${e} Timed out`)),delete t[d]}),l?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:g}),u.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,s)=>{Fa+=1;const a=`${i}-${Fa}-multicast-${e.substring(0,10)}`;let c=va?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let d=o(r[0].serviceId);d&&(c=Ra.encode(l,s,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&&(d=o(i.serviceId),d&&(c=Ra.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:s,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("kweb");rc.setLogger(nc);const ic=new o,sc=new o;let oc,ac=null,cc=null,lc=null,dc=null;const uc={},pc=()=>{if(!lc)throw new Error("API key is required to interact with the hub");return lc},gc=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return uc[r]=i,i},hc=(e,t)=>uc[`${e}_${t}`]||null,fc=async(e,t)=>{if(!ac)return tc("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await rc.execute(be.GetServiceContents,n,yc,ac,0))[0]},mc=async(e,t,n=!1)=>{if(!e||!t)return null;const r=hc(e,t);if(!r||n){const n=r||gc(e,t);try{const r=await fc(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){tc(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},yc=Ka,vc=()=>{tc("Disconnected from the server"),ac=null,dc=null,rc.rejectAllPending("Disconnected from the server"),ic.emit("disconnected")},bc=()=>{tc("Connected to the server"),ic.emit("connected")},Sc=()=>cc,wc=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,Ic=async()=>{const e=Sc();if(e){const t=ie(e)?.blocks;if(t){const n={};for(const r in t){const i=t[r];for(const t in i.gates){const r=i.gates[t];if(r.type===ze.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{tc(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await jc({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){tc(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},_c=async e=>{if(!e)return void tc("Hub sent ACK request without service id");const t={apiKey:pc(),ackSessionId:e};await rc.execute(be.SocketAckResponse,[t],yc,e,0),tc("Hub Link acknowledged"),ac=e,ic.emit("acknowledged"),Ic()},$c=async e=>{const t=e.args[0],n=wc("broadcast",`hub_${t.type}`,(0).toString(),"");await sc.emit(n,t)},Cc=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===fe.ImageData&&je(e.value)&&(e.value=await Ve(e.value));const n=Sc();if(n){const r=ie(n);if(r){const i=async e=>{const n=wc("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await sc.emit(n,t)}catch(t){tc(`Failed to emit broadcast event for target ${e}`,t)}};await i("app");for(const s in r.blocks){const o=r.blocks[s];for(const r in o.gates){const s=o.gates[r];if(s.disabled)continue;const a=s.state;if(s.type===ze.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await i(r);const s=a?.service?.name&&t.eventContext?{[a.service.name]:t.eventContext}:void 0;for(const i of t.outputs||[])if(null!==i.value&&void 0!==i.value){const t={type:i.type,value:i.value,timestamp:Date.now()};tc(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await aa({recipePoolId:n,currentGateId:r,sourcePortName:i.name,originalEvent:t,data:t,eventContext:s})}}}}}}},kc=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,s=oa(r,i);let o=s;if(n&&o&&s&&(o={...s,customState:n},sa(r,i,o,!0)),o?.service)try{const e=wc("setOutputs",o.service.name,o.service.version,i);await sc.emit(e,t.outputs)}catch(e){tc(`Failed to emit setOutputs event for widget ${i}`,e)}let a=null;for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===fe.ImageData){if(!je(n.value)){tc(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=await Ve(n.value)}else n.type!==fe.JsonObj&&n.type!==fe.Array||await Qa(n.value);const s={type:n.type,value:n.value,timestamp:Date.now()};tc(`Sending data to output ${n.name} requested by messageId ${e.messageId}`);const c=o?.service?.name&&t.eventContext?{[o.service.name]:t.eventContext}:void 0;try{await aa({recipePoolId:r,currentGateId:i,sourcePortName:n.name,originalEvent:s,data:s,eventContext:c})}catch(e){tc(`Failed to trigger next global widget for output ${n.name}`,e),a=e;break}}if(a){const t=a instanceof tr,n=a;e.reply({error:a.message,errCode:t?"CHILD_WIDGET_ERROR":"INVOKING_ERROR",errData:{targetWidgetId:n.targetWidgetId,targetPortName:n.targetPortName,sourcePortName:n.sourcePortName,sourceWidgetId:n.sourceWidgetId,targetWidgetType:n.targetWidgetType,sourceWidgetType:n.sourceWidgetType}})}else e.reply({success:[]})},Ec=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,s=oa(r,i);if(s){const t={...s,customState:{...s.customState,...n}};return sa(r,i,t,!0),e.reply({success:[]})}},xc=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:s,key:o}=n;tc(`Received request to set a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const a=oa(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:s},sa(r,i,e,!0)}return t({success:[]})},Ac=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:s}=n;tc(`Received request to get a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const o=oa(r,i);if(o){const e=o.dependencies?.[s]?.path;return tc(`Returning dependency path for "${s}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},Nc=async()=>{if(tc(`Requesting services on ${(new Date).toISOString()}`),!ac)return tc("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await rc.execute(be.GetServices,[],yc,ac,0);oc=e;for(const t of e.available){if(t.internal)continue;const e=hc(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||gc(t.name,t.version);tc(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await fc(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){tc(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},Pc=()=>oc||{available:[],installed:[],failed:[]},Oc=()=>!!oc,Tc=async e=>{const{targetServiceSessionId:t}=e;if(!ac)return void tc("No target service session id provided");tc(`Forwarding "onParentEvent" to service ${t}`);return await rc.execute(be.OnParentEvent,[e],yc,ac,t,e.config).catch((e=>{throw tc(`Error invoking onParentEvent callback: ${e}`),e.errCode===Ua.ParentEventCallbackError?e.error:e}))},Lc=async e=>{if(!ac)return tc("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await rc.execute(be.GetDefaultState,[],yc,ac,e);return t},Bc=async(e,t,n,r)=>{if(!ac)return tc("Hub Link has not been acknowledged. Cannot get services."),null;const[i]=await rc.execute(be.UIEvent,[t,n],yc,ac,e,r);return i},Dc=(e,t)=>{const n=()=>{t()};return ic.on(e,n),()=>ic.off(e,n)},jc=async e=>{if(ac)return rc.execute(be.SubscribeToService,[e],yc,ac,0);tc("Hub Link has not been acknowledged. Cannot subscribe to services.")},Uc=async e=>{if(ac)return rc.execute(be.UnsubscribeFromService,[e],yc,ac,0);tc("Hub Link has not been acknowledged. Cannot subscribe to services.")},Rc=(e,t,n,r)=>{const i=wc("broadcast",t,n,e);return sc.on(i,r)},Fc=(e,t,n,r)=>{const i=wc("setOutputs",t,n,e);return sc.on(i,r)},Mc=async(e,t,n)=>ac?rc.execute(e,t,yc,ac,0,n):(tc("Hub Link has not been acknowledged. Cannot execute function."),null),Wc=async e=>{if(!ac)return void tc("Hub Link has not been acknowledged. Cannot execute function.");const t=oa(e.recipeId,e.widgetId);if(!t)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const n=Object.keys(t.dependencies||{}).reduce(((e,n)=>(e[n]=t.dependencies?.[n]?.path||null,e)),{}),r=[{currentState:t.customState,recipeId:e.recipeId,widgetId:e.widgetId,variantId:e.variantId,recipeType:e.recipeType,recipeName:e.recipeName,currentDependencies:n}],[i]=await rc.execute(be.InitializeInstance,r,yc,ac,e.sessionId);if(i){const t=oa(e.recipeId,e.widgetId);if(t){const n={...t,customState:i};sa(e.recipeId,e.widgetId,n,!0)}}},Gc=async(e,t,n,r)=>{if(!ac)return void tc("Hub Link has not been acknowledged. Cannot execute function.");const i=oa(n,t);if(!i)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const s=[{currentState:i.customState,recipeId:n,widgetId:t,variantId:r}];await rc.execute(be.TerminateInstance,s,yc,ac,e)},Vc=async(e,t,n="^",r)=>{const i=["^","~",">=",">","<=","<","="];if(!i.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${i.join(", ")}`);const s=Oc(),o=r||!s?await Nc():Pc();for(const r of o.available)if(r.name===e){if(r.version===t)return r;if(h(r.version,`${n}${t}`))return r}return null},Hc=async()=>{if(!ac)return tc("Hub Link has not been acknowledged. Cannot get services."),null;if(dc)return dc;const[e]=await rc.execute(be.GetSystemInfo,[],yc,ac,0).catch((e=>(tc("Failed to get system info",e),[null])));return dc=e,e};var zc,qc,Kc,Jc,Yc,Xc,Zc,Qc,el=async e=>{Xa(bc),Za(vc),lc=e,Ya((({json:e,transmission:t})=>{rc.processMessage("websocket",yc,t,e)})),rc.registerFunction(be.SetState,Ec),rc.registerFunction(be.SetOutputs,kc),rc.registerFunction(be.BroadcastEvent,Cc),rc.registerFunction(be.HubBroadcastEvent,$c),rc.registerFunction(Se.SetDependencyPath,xc),rc.registerFunction(Se.GetDependencyPath,Ac),Ja((e=>{((e,t)=>{const n=ve.SocketAcknowledge,r=ve.IpcAcknowledge,i=e.startsWith(n);if(e===r)return t&&t(),0;if(i){const s=e.split(i?n:r),o=parseInt(s[1]);return t&&t(o),o}})(e,_c),((e,t)=>{e===ve.ServicesListChanged&&(t&&t())})(e,(()=>{tc("Services list changed"),ic.emit("services-changed")}))})),await qa()},tl=(e,t)=>{ic.on(e,t)},nl=()=>({getServices:Nc,getServiceContents:mc,onParentEvent:Tc,onCommand:Dc,getDefaultState:Lc,getCachedServices:Pc,areServicesCached:Oc,subscribeToServiceEvents:jc,unsubscribeFromServiceEvents:Uc,callProcessorHandler:Bc,onBroadcastEvent:Rc,onSetOutputsEvent:Fc,executeHubFunction:Mc,initializeServiceInstance:Wc,terminateServiceInstance:Gc,getCompatibleService:Vc,getHubSystemInfo:Hc}),rl=e=>{cc=e},il=()=>rc;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(zc||(zc={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(qc||(qc={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(Kc||(Kc={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(Jc||(Jc={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(Yc||(Yc={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(Xc||(Xc={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(Zc||(Zc={})),function(e){e.IPC="ipc",e.WS="ws"}(Qc||(Qc={}));const sl=e=>{try{return JSON.parse(e)}catch(e){return null}},ol=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,al=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(ol);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},cl=e=>"*"===e||"x"===e||"X"===e,ll=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},dl=(e,t)=>{if(cl(e)||cl(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(ll(e),ll(t));return n>r?1:n<r?-1:0},ul=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=dl(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},pl=(e,t,n)=>{fl(n);const r=((e,t)=>{const n=al(e),r=al(t),i=n.pop(),s=r.pop(),o=ul(n,r);return 0!==o?o:i&&s?ul(i.split("."),s.split(".")):i||s?i?-1:1:0})(e,t);return gl[n].includes(r)},gl={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},hl=Object.keys(gl),fl=e=>{if(-1===hl.indexOf(e))throw new Error(`Invalid operator, expected one of ${hl.join("|")}`)};var ml="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function yl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var vl,bl,Sl,wl,Il,_l={exports:{}},$l={exports:{}};function Cl(){if(bl)return vl;bl=1;var e=1e3,t=60*e,n=60*t,r=24*n,i=7*r,s=365.25*r;function o(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}return vl=function(a,c){c=c||{};var l=typeof a;if("string"===l&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*i;case"days":case"day":case"d":return c*r;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===l&&isFinite(a))return c.long?function(i){var s=Math.abs(i);if(s>=r)return o(i,s,r,"day");if(s>=n)return o(i,s,n,"hour");if(s>=t)return o(i,s,t,"minute");if(s>=e)return o(i,s,e,"second");return i+" ms"}(a):function(i){var s=Math.abs(i);if(s>=r)return Math.round(i/r)+"d";if(s>=n)return Math.round(i/n)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}function kl(){if(wl)return Sl;return wl=1,Sl=function(e){function t(e){let r,i,s,o=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),s=i-(r||i);n.diff=s,n.prev=r,n.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,i)=>{if("%%"===r)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];r=s.call(n,t),e.splice(o,1),o--}return r})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),i=r.length;for(n=0;n<i;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=Cl(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t},Sl}var El,xl,Al,Nl,Pl,Ol={exports:{}};function Tl(){return xl||(xl=1,El=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return-1!==r&&(-1===i||r<i)}),El}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?_l.exports=(Il||(Il=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))})),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=kl()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}($l,$l.exports)),$l.exports):_l.exports=(Pl||(Pl=1,function(e,t){const n=E,r=c;t.init=function(e){e.inspectOpts={};const n=Object.keys(t.inspectOpts);for(let r=0;r<n.length;r++)e.inspectOpts[n[r]]=t.inspectOpts[n[r]]},t.log=function(...e){return process.stderr.write(r.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(n){const{namespace:r,useColors:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),s=` ${i};1m${r} [0m`;n[0]=s+n[0].split("\n").join("\n"+s),n.push(i+"m+"+e.exports.humanize(this.diff)+"[0m")}else n[0]=(t.inspectOpts.hideDate?"":(new Date).toISOString()+" ")+r+" "+n[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)},t.destroy=r.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if(Nl)return Al;Nl=1;const e=x,t=E,n=Tl(),{env:r}=process;let i;function s(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function o(t,s){if(0===i)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!s&&void 0===i)return 0;const o=i||0;if("dumb"===r.TERM)return o;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in r))||"codeship"===r.CI_NAME?1:o;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if("truecolor"===r.COLORTERM)return 3;if("TERM_PROGRAM"in r){const e=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:o}return n("no-color")||n("no-colors")||n("color=false")||n("color=never")?i=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(i=1),"FORCE_COLOR"in r&&(i="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),Al={supportsColor:function(e){return s(o(e,e&&e.isTTY))},stdout:s(o(!0,t.isatty(1))),stderr:s(o(!0,t.isatty(2)))}}();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let r=process.env[t];return r=!!/^(yes|on|true|enabled)$/i.test(r)||!/^(no|off|false|disabled)$/i.test(r)&&("null"===r?null:Number(r)),e[n]=r,e}),{}),e.exports=kl()(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},i.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(Ol,Ol.exports)),Ol.exports);var Ll=yl(_l.exports);const Bl=e=>Ll(e),Dl=Date.now();let jl=Math.ceil(Dl/1e3);var Ul=()=>jl+=1;const Rl=y(A(),"kemu-user-services"),Fl=y(A(),"kemu-test-services"),Ml="KMU-CB-v1",Wl=process.env.HUB_PKG_VERSION||'"1.3.5"';var Gl;!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"}(Gl||(Gl={}));const Vl=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>qc[e])):qc[e.type]}),Hl=async e=>{try{return await w(e,"utf-8")}catch(e){return null}},zl=e=>{if(e&&e.startsWith(Ml)){const t=e.slice(9),n=decodeURI(t);return sl(n)}return null},ql=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(Vl)}:{},...e.outputs?{outputs:e.outputs.map(Vl)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(Vl)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(Vl)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},s=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const i of t.customWidgets){const t=await Hl(y(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const s=t.startsWith(Ml)?t:`${Ml}${t}`,o=zl(s);if(!o){n(`Custom widget file "${i}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(o).filter((e=>e.type===Gl.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,d={name:l.name,color:l.color,description:l.description,contents:s,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(d)}return r})(t,e,n?.log);if(s.length?i.customWidgets=s:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await w(y(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},Kl=async e=>{try{return await I(e,_.F_OK),!0}catch{return!1}};let Jl=null,Yl=null;const Xl=()=>Jl||Rl,Zl=Bl("servicesManager"),Ql={};let ed=null,td=null,nd=null;class rd extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const id=async e=>{try{return await I(e),!0}catch{return!1}},sd=async e=>{if(!ed)throw new Error('IPC config not set, call "setHubIpcConfig" first.');try{if(e.processor===Jc.Javascript){Zl(`Spawning service ${e.name} with sessionId ${e.sessionId}`);const t=m.join(e.path,"processor.js"),n=m.join(e.path,"processor.mjs"),r=await id(t)?t:n,i=[`--sessionId=${e.sessionId.toString()}`,`--ipcSpace=${ed.appSpace}`,`--ipcId=${ed?.id}`,`--recipePath=${ed.recipePath||""}`];if(e.internal&&i.push("--internal=true"),!nd)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const s=await nd({name:e.name,version:e.version,requiredSecrets:e.requiredSecrets||{}}),o=Object.entries(e.requiredSecrets||{}).filter((([e,t])=>{const n=s[e];return null==n&&!t.optional})).map((([e])=>e));if(o?.length)throw new rd(`Missing required environment variables: ${o.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,n)=>{if(!td)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const o=td({args:[r,...i],serviceInfo:{name:e.name,version:e.version},options:{env:s}});o.stdout.on("data",(t=>{Zl(`[${e.name}] - stdout: ${t}`)})),o.stderr.on("data",(t=>{Zl(`[${e.name}] - stderr: ${t}`)})),o.on("exit",(t=>{Zl(`[${e.name}] exited with code ${t}`)})),o.on("spawn",(()=>{Zl(`[${e.name}] spawned with PID ${o.pid}`),t(o)})),o.on("error",(t=>{Zl(`[${e.name}] error: ${t}`),n(new rd(`Error spawning service ${e.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.processor}`}catch(t){if(t instanceof rd)throw t;throw`Error spawning service ${e.name}: ${t}`}},od=e=>{if(!e?.name)return"Missing name";if(!e?.version)return"Missing version";if(!e?.description)return"Missing description";if(!e?.processor)return"Missing processor";return[Jc.Javascript,Jc.Executable,Jc.Python].includes(e?.processor)?null:"Invalid processor"},ad=async(e,t)=>{const n=m.join(e,"manifest.json");if(!await id(n)){const t=`Missing manifest for service ${e}. Aborting.`;return Zl(t),{error:t}}const r=await w(n,"utf-8"),i=sl(r),s=od(i);if(!i||s){const t=`Invalid service manifest [${e}]: ${s}. Aborting.`;return Zl(t),{error:t}}let o;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{o=await w(m.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return Zl(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await Hl(m.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=m.join(e,t),{error:r,service:s}=await ad(n);r?Zl(`Error loading sub-service ${t}: ${r}`):s&&(s.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 w(m.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){Zl(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=Ul(),c=t?.fixedSession||a;Zl(`Loaded service ${i.name} with sessionId ${c}`);const l=await ql(i,e,{widgetUIContents:o});return cd(l),Ql[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null},{service:Ql[c]}},cd=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=g("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},ld=async e=>{try{return e.childProcess=await sd(e.info),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return Zl(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof rd?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},dd=e=>{const{path:t,...n}=e.info;return{...n}},ud=()=>Object.values(Ql).filter((e=>"running"===e.status)).map(dd),pd=e=>{const{serviceName:t,version:n,force:r}=e,i=Object.values(Ql).find((t=>t.info.name===e.serviceName&&t.info.version===e.version));if(!i)return null;if(i.info.internal&&!r)throw`Cannot stop internal service ${t}`;if(i.childProcess){Zl(`Stopping service "${t} (v${n})"`);i.childProcess.kill("SIGINT")||Zl(`Failed to stop service ${t}`)}return i.status="stopped",Zl(`Service ${t} stopped`),i},gd=e=>e.info.internal?e.info.path:m.join(e.info.path,".."),hd=e=>!!e.internal;var fd={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await Kl(e))return void Zl(`Failed to load services from "${e}". Directory does not exist.`);const n=(await $(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));Zl(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],s=m.join(e,i),{error:o,service:a}=await ad(`${s}${t?.internalServices?"":"/dist"}`,t);o&&Zl(`Failed to load service ${s}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(Zl("Initializing services"),!ed)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in Ql){const n=Ql[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?Zl(`Service ${n.info.name} is in the noSpawningList. Skipping.`):ld(n)}Zl("Services initialized")},setServiceStatus:(e,t)=>{const n=Ql[e];return n?(n.status=t,!0):(Zl(`Service with serviceId ${e} not found`),!1)},getActiveServices:ud,getMatchingService:(e,t)=>{const n=Object.values(Ql).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(pl(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>Ql[e]||null,killAllServices:()=>{for(const e in Ql){const t=Ql[e];if(t.childProcess)try{Zl(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){Zl(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await ql(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};Ql[e]=r,cd(Ql[e].info)},setServiceManifest:(e,t,n)=>{const r=Ql[e];if(!r)return Zl(`Service with sessionId ${e} not found`),!1;const i=od(t);if(i)return Zl(`Invalid manifest for service ${r.info.name}: ${i}`),!1;cd(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(Ql).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:()=>ud().filter((e=>e.internal)),getAllServices:()=>Object.values(Ql),stopService:pd,uninstallService:async(e,t)=>{Zl(`Uninstalling service ${e} v${t}`);const n=pd({serviceName:e,version:t});if(!n)return!1;Zl(`Service ${e} stopped. Removing from disk...`);const r=gd(n),i=Xl();return r.startsWith(i)?(await C(r,{recursive:!0,force:!0}),Zl(`Service ${e} successfully removed from disk`),(e=>{const t=Ql[e];delete Ql[e]})(n.info.sessionId),!0):(Zl(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(Ql).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{ed={...e}},loadAndLaunch:async(e,t,n)=>{const r=b(e,t),{error:i,service:s}=await ad(r);if(i||!s)return{errorMsg:i};try{s.info.internal=!!n,s.childProcess=await sd(s.info),s.status="started"}catch(e){s.status="error",e instanceof rd?(Zl(`Service spawning error: ${e.message} (${e.code})`),s.errorMsg=e.message,s.errorCode=e.code):(Zl(`Error launching service ${s.info.name}: ${e}`),s.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:s,errorCode:s.errorCode,errorMsg:s.errorMsg}},getServiceRootDirectory:gd,setSpawnNodeFunction:e=>{td=e},setGetSecretsFunction:e=>{nd=e},restartService:async(e,t)=>{Zl(`Restarting service ${e} v${t}`);const n=pd({serviceName:e,version:t,force:!0});return!!n&&ld(n)},getFailedServices:()=>Object.values(Ql).filter((e=>"error"===e.status)).map((e=>({...dd(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:hd,isNotInternalKemuService:e=>!hd(e),isNotDevService:e=>!e.devMode};class md{constructor(){}appspace="app.";socketRoot="/tmp/";id=x.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=x.networkInterfaces();let t="";e&&Array.isArray(e)&&e.length>0&&(t=e[Object.keys(e)[0]][0].family);return 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 yd{constructor(e){e||(e=new md),this.delimiter=e.delimiter}format(e){return e.data||!1===e.data||0===e.data||(e.data={}),e.data._maxListeners&&(e.data={}),e=e.JSON+this.delimiter}parse(e){let t=e.split(this.delimiter);return t.pop(),t}}var vd=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={}},bd=yl(vd);var Sd=yl((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(){if(t=!0,e.length<1||this.stop)return void(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 wd{}class Id{}const _d=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 wd,t=Id){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 wd}}())}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 $d{constructor(){}on(e,t,n=!1){return _d.string(e),_d.function(t),_d.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(_d.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;_d.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){_d.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)=>{_d.string(e),_d.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 Cd=new yd;class kd extends $d{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Cd=new yd(this.config)}Client=kd;queue=new Sd;socket=!1;connect=Ad;emit=Ed;retriesRemaining=0;explicitlyDisconnected=!1}function Ed(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new bd;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Cd.format(n),this.config.sync?this.queue.add(xd.bind(this,n)):this.socket.write(n)}function xd(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Ad(){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=O.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=O.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(O.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=P.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=N.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=N.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)!=Cd.delimiter||-1==t.indexOf(Cd.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Cd.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new bd;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 Nd=new yd;class Pd extends $d{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Nd=new yd(this.config),this.on("close",Ld.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Od;broadcast=Td;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?O.unlink(this.path,Ud.bind(this)):Ud.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Od(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new bd;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Nd.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 Td(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new bd;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Nd.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 Ld(){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 Bd(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)==Nd.delimiter&&-1!=t.indexOf(Nd.delimiter))for(r.ipcBuffer="",t=Nd.parse(t);t.length>0;){let e=new bd;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 Dd(e){this.publish("close",e)}function jd(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",Dd.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",Bd.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 Ud(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=L.createSocket(this.udp4?"udp4":"udp6"),this.server.write=Fd.bind(this),this.server.on("listening",function(){jd.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?Rd.bind(this)():this.server=N.createServer(jd.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 Rd(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=O.readFileSync(this.config.tls.private):this.config.tls.key=O.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=O.readFileSync(this.config.tls.public):this.config.tls.cert=O.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=O.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(O.readFileSync(this.config.tls.trustedConnections[e]))}this.server=P.createServer(this.config.tls,jd.bind(this))}function Fd(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 Md{constructor(){}config=new md;of={};server=!1;get connectTo(){return qd}get connectToNet(){return Kd}get disconnect(){return Gd}get serve(){return Vd}get serveNet(){return zd}get log(){return Wd}set connectTo(e){return qd}set connectToNet(e){return Kd}set disconnect(e){return Gd}set serve(e){return Vd}set serveNet(e){return zd}set log(e){return Wd}}function Wd(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=c.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function Gd(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 Vd(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=Hd),this.server=new Pd(e,this.config,Wd),this.server.on("start",t)}function Hd(){}function zd(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=Hd),this.server=new Pd(e,this.config,Wd,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function qd(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=Hd),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 kd(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 Kd(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=Hd),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 kd(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 Jd=new class extends Md{constructor(){super()}IPC=Md};var Yd={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const Xd=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),Zd=e=>{try{return JSON.parse(e)}catch(e){return null}},Qd="undefined"!=typeof window,eu={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},tu={protocolPrefix:4,txtLength:4},nu=Object.values(eu).reduce(((e,t)=>e+t),0),ru=Object.values(tu).reduce(((e,t)=>e+t),0),iu=["width","height","colorSpace"],su=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${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,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)e.hasOwnProperty(n)||iu.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={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};s=o(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:s}:null},ou=(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 s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},au=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(n.hasOwnProperty(s)){const{index:o,length:a,binaryType:c}=n[s];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&ou(e,s,l)}return e},cu=e=>Ll(e),lu="KMSG",du="KCMD",uu=cu("klProtocol");var pu={encode:(e,t,n)=>{const r={json:e.json},i=su(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,d=eu.protocolPrefix+eu.protocolVersion+eu.jsonLength+eu.binaryLength+eu.fromServiceId+eu.toServiceId+eu.sentAt+l+o,u=Buffer.alloc(d),p=Date.now();let g=0;return u.write(lu,g),g+=eu.protocolPrefix,u.writeUInt8(1,g),g+=eu.protocolVersion,u.writeUInt32LE(l,g),g+=eu.jsonLength,u.writeUInt32LE(o,g),g+=eu.binaryLength,u.writeUInt32LE(t,g),g+=eu.fromServiceId,u.writeUInt32LE(n,g),g+=eu.toServiceId,u.writeBigInt64LE(BigInt(p),g),g+=eu.sentAt,c.copy(u,g),g+=l,s&&o&&s.copy(u,g),u},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,eu.protocolPrefix);if(t+=eu.protocolPrefix,n!==lu)return null;if(e.byteLength<nu)return uu(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=eu.protocolVersion;const i=e.readUInt32LE(t);t+=eu.jsonLength;const s=e.readUInt32LE(t);t+=eu.binaryLength;const o=e.readUInt32LE(t);t+=eu.fromServiceId;const a=e.readUInt32LE(t);t+=eu.toServiceId;const c=e.readBigInt64LE(t);t+=eu.sentAt;const l=i+s,d=e.subarray(t,t+l),u=e.subarray(0,nu);let p=null;return e.byteLength-nu-i-s>0&&(p=e.subarray(nu+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[d],headerPackage:u},remaining:p}},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=Zd(n);if(!i?.json)return uu("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&au(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=nu+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<nu)return uu("Invalid Header Size"),e;let n=0;return n+=eu.protocolPrefix,n+=eu.protocolVersion,n+=eu.jsonLength,n+=eu.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=eu.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=ru+r,s=Buffer.alloc(i);return s.write(du,t),t+=tu.protocolPrefix,s.writeUint32LE(r,t),t+=tu.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<ru)return{command:null};const n=e.toString("utf-8",t,tu.protocolPrefix);if(t+=tu.protocolPrefix,n!==du)return{command:null};const r=e.readUInt32LE(t);t+=tu.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-ru-r;let o=null;s>0&&(o=e.subarray(ru+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const gu="KMSG",hu="KCMD",fu=cu("klProtocol"),mu=new TextEncoder;var yu={encode:(e,t,n)=>{const r={json:e.json},i=su(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=mu.encode(a),l=c.byteLength,d=new ArrayBuffer(eu.protocolPrefix+eu.protocolVersion+eu.jsonLength+eu.binaryLength+eu.fromServiceId+eu.toServiceId+eu.sentAt+l+o),u=new DataView(d),p=new Uint8Array(d),g=Date.now();let h=0;for(let e=0;e<4;++e)p[h++]=gu.charCodeAt(e);return u.setUint8(h,1),h+=eu.protocolVersion,u.setUint32(h,l,!0),h+=eu.jsonLength,u.setUint32(h,o,!0),h+=eu.binaryLength,u.setUint32(h,t,!0),h+=eu.fromServiceId,u.setUint32(h,n,!0),h+=eu.toServiceId,u.setBigInt64(h,BigInt(g),!0),h+=eu.sentAt,p.set(c,h),h+=l,s&&o&&p.set(new Uint8Array(s),h),d},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<eu.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==gu)return null;if(e.byteLength<nu)return fu.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=eu.protocolVersion;const s=t.getUint32(n,!0);n+=eu.jsonLength;const o=t.getUint32(n,!0);n+=eu.binaryLength;const a=t.getUint32(n,!0);n+=eu.fromServiceId;const c=t.getUint32(n,!0);n+=eu.toServiceId;const l=t.getBigInt64(n,!0);n+=eu.sentAt;const d=s+o,u=e.slice(n,n+d),p=new Uint8Array(e,0,nu);let g=null;if(e.byteLength-nu-s-o>0){g=new Uint8Array(e,nu+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[u],headerPackage:p.slice().buffer},remaining:g}},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 s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Zd(s);if(!a?.json)return fu.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&au(a.json,o,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,d=null;const u=nu+e.jsonLength+e.binaryLength;return c.byteLength>u&&(d=c.subarray(u),l=c.subarray(0,u)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:d?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<nu)return fu("Invalid Header Size"),e;let n=0;n+=eu.protocolPrefix,n+=eu.protocolVersion,n+=eu.jsonLength,n+=eu.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=eu.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=mu.encode(e),r=n.byteLength,i=new ArrayBuffer(ru+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=hu.charCodeAt(e);return s.setUint32(t,r,!0),t+=tu.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<ru)return{command:null};let r="";for(let e=0;e<tu.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==hu)return{command:null};const i=t.getUint32(n,!0);n+=tu.txtLength;const s=e.byteLength-ru-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-ru)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(ru+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};const vu=cu("klTransmissionManager"),bu=()=>{const e=(t,n,r,i)=>{let s=n,o=null;const a=t instanceof ArrayBuffer;if(vu(`RAW: ${t.toString()}`),!s||s.partialHeaderData){let c;if(a?(c=s?.partialHeaderData?new Uint8Array([...new Uint8Array(s.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=yu.decodeHeader(c)):(c=s?.partialHeaderData?Buffer.concat([s.partialHeaderData,t]):t,o=pu.decodeHeader(c)),!o){const{command:t,missing:s,remainingData:o}=a?yu.decodeCommand(c):pu.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):vu(s?`ERROR: Missing ${s} 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`),o?(vu(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,n,r,i)):void 0}if(o.partialHeader)return s={firstPackageAt:Date.now(),partialHeaderData:c},r(s);if(!o.header)return vu(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=o.header;s={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:o.remaining}},r(s)}else s.header&&s.header.totalBytesReceived<s.header.totalBytesExpected&&(s.header.packages.push(t),s.header.totalBytesReceived+=t.byteLength,r(s));if(s.header&&s.header.totalBytesReceived>=s.header.totalBytesExpected){const t=Date.now()-s.header.sentAt.getTime(),n=Date.now()-s.firstPackageAt;vu(`Received ${s.header.totalBytesReceived} of ${s.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?yu.decodeFullKlMessage(s.header):pu.decodeFullKlMessage(s.header),c=s.header.totalBytesReceived,l=s.header.remaining;r(null),o&&i({klMessage:o.message,complete:!0,sourceServiceId:s.header.fromServiceId,targetServiceId:s.header.toServiceId,rawMessage:o.message.rawMessage});let d=l;if(o?.remaining&&(d=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),s=new Uint8Array(t),o=new Uint8Array(r);return o.set(i),o.set(s,i.length),r})(l,o.remaining):o.remaining:l?Buffer.concat([l,o.remaining]):o.remaining),d)return vu(`${d.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(d,null,r,i)}};return e};Jd.config={...Jd.config,...Yd};const Su={info:Bl("ipcServer:info"),data:Bl("ipcServer:data")};let wu,Iu,_u,$u,Cu={};const ku=bu(),Eu=e=>{Cu[e]&&(Su.info(`Client disconnected [${e}]`),delete Cu[e],Iu&&Iu(e))};var xu=e=>(e?.ipcId&&(Jd.config.id=e.ipcId),e?.ipcAppSpace&&(Jd.config.appspace=e.ipcAppSpace),new Promise((e=>{Jd.serve((()=>{Su.info("IPC Server Initiated"),Jd.server.on("data",((e,t)=>{const n=Cu[t.id];n?(Su.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),ku(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Su.data(`Received command from client [${t.id}]: ${e.command}`),void(_u&&_u(t.id,e.command,n));e.klMessage&&$u&&$u({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Su.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),Jd.server.on("connect",(e=>{const t=Ul();Su.info(`New client connected. Registered as "${t}"`),e.id=t,Cu[t]={socket:e,activeMessage:null,disconnectHandler:()=>Eu(t)},e.on("close",Cu[t].disconnectHandler),wu&&wu(t)})),Jd.server.on("disconnect",(e=>{Eu(e.id)})),Jd.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),Jd.server.start()}))),Au=e=>{wu=e},Nu=e=>{Iu=e},Pu=e=>$u=e,Ou=(e,t)=>{const n=Cu[e];if(!n)return Su.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=Xd)return Su.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=pu.encodeCommand(t);return n.socket.write(r),!0},Tu=(e,t)=>{const n=Cu[e];return!!n&&(Su.info(`Renaming socket id [${e}] to [${t}]`),delete Cu[e],n.socket.id=t,Cu[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Eu(t),n.socket.on("close",n.disconnectHandler),!0)},Lu=e=>{_u=e};let Bu=pu;Qd&&(Bu=yu);var Du,ju=Bu;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Du||(Du={}));let Uu=Math.ceil(Date.now()/1e3);var Ru={exports:{}};const Fu=["nodebuffer","arraybuffer","fragments"],Mu="undefined"!=typeof Blob;Mu&&Fu.push("blob");var Wu={BINARY_TYPES:Fu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Mu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:Gu}=Wu,Vu=Buffer[Symbol.species];function Hu(e,t,n,r,i){for(let s=0;s<i;s++)n[r+s]=e[s]^t[3&s]}function zu(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(Ru.exports={concat:function(e,t){if(0===e.length)return Gu;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 Vu(n.buffer,n.byteOffset,r):n},mask:Hu,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 Vu(t):ArrayBuffer.isView(t)?n=new Vu(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:zu},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Ru.exports.mask=function(t,n,r,i,s){s<48?Hu(t,n,r,i,s):e.mask(t,n,r,i,s)},Ru.exports.unmask=function(t,n){t.length<32?zu(t,n):e.unmask(t,n)}}catch(e){}var qu=Ru.exports;const Ku=Symbol("kDone"),Ju=Symbol("kRun");const Yu=D,Xu=qu,Zu=class{constructor(e){this[Ku]=()=>{this.pending--,this[Ju]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ju]()}[Ju](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Ku])}}},{kStatusCode:Qu}=Wu,ep=Buffer[Symbol.species],tp=Buffer.from([0,0,255,255]),np=Symbol("permessage-deflate"),rp=Symbol("total-length"),ip=Symbol("callback"),sp=Symbol("buffers"),op=Symbol("error");let ap;var cp=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,!ap){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;ap=new Zu(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[ip];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){ap.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){ap.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]?Yu.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Yu.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[np]=this,this._inflate[rp]=0,this._inflate[sp]=[],this._inflate.on("error",up),this._inflate.on("data",dp)}this._inflate[ip]=n,this._inflate.write(e),t&&this._inflate.write(tp),this._inflate.flush((()=>{const e=this._inflate[op];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=Xu.concat(this._inflate[sp],this._inflate[rp]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[rp]=0,this._inflate[sp]=[],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]?Yu.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Yu.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[rp]=0,this._deflate[sp]=[],this._deflate.on("data",lp)}this._deflate[ip]=n,this._deflate.write(e),this._deflate.flush(Yu.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Xu.concat(this._deflate[sp],this._deflate[rp]);t&&(e=new ep(e.buffer,e.byteOffset,e.length-4)),this._deflate[ip]=null,this._deflate[rp]=0,this._deflate[sp]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function lp(e){this[sp].push(e),this[rp]+=e.length}function dp(e){this[rp]+=e.length,this[np]._maxPayload<1||this[rp]<=this[np]._maxPayload?this[sp].push(e):(this[op]=new RangeError("Max payload size exceeded"),this[op].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[op][Qu]=1009,this.removeListener("data",dp),this.reset())}function up(e){this[np]._inflate=null,e[Qu]=1007,this[ip](e)}var pp={exports:{}};const{isUtf8:gp}=j,{hasBlob:hp}=Wu;function fp(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(pp.exports={isBlob:function(e){return hp&&"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:fp,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]},gp)pp.exports.isValidUTF8=function(e){return e.length<24?fp(e):gp(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");pp.exports.isValidUTF8=function(t){return t.length<32?fp(t):e(t)}}catch(e){}var mp=pp.exports;const{Writable:yp}=B,vp=cp,{BINARY_TYPES:bp,EMPTY_BUFFER:Sp,kStatusCode:wp,kWebSocket:Ip}=Wu,{concat:_p,toArrayBuffer:$p,unmask:Cp}=qu,{isValidStatusCode:kp,isValidUTF8:Ep}=mp,xp=Buffer[Symbol.species];var Ap=class extends yp{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||bp[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Ip]=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 xp(t.buffer,t.byteOffset+e,t.length-e),new xp(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 xp(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[vp.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);if(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"))}else this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(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"))}else 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=Sp;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]&&Cp(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[vp.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?_p(n,t):"arraybuffer"===this._binaryType?$p(_p(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=_p(n,t);if(!this._skipUTF8Validation&&!Ep(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,Sp),this.end();else{const n=e.readUInt16BE(0);if(!kp(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new xp(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ep(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 s=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,this.createError),s.code=i,s[wp]=r,s}};const{randomFillSync:Np}=d,Pp=cp,{EMPTY_BUFFER:Op,kWebSocket:Tp,NOOP:Lp}=Wu,{isBlob:Bp,isValidStatusCode:Dp}=mp,{mask:jp,toBuffer:Up}=qu,Rp=Symbol("kByteLength"),Fp=Buffer.alloc(4),Mp=8192;let Wp,Gp=Mp;var Vp=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=Lp,this[Tp]=void 0}static frame(e,t){let n,r,i=!1,s=2,o=!1;t.mask&&(n=t.maskBuffer||Fp,t.generateMask?t.generateMask(n):(Gp===Mp&&(void 0===Wp&&(Wp=Buffer.alloc(Mp)),Np(Wp,0,Mp),Gp=0),n[0]=Wp[Gp++],n[1]=Wp[Gp++],n[2]=Wp[Gp++],n[3]=Wp[Gp++]),o=!(n[0]|n[1]|n[2]|n[3]),s=6),"string"==typeof e?r=t.mask&&!o||void 0===t[Rp]?(e=Buffer.from(e)).length:t[Rp]:(r=e.length,i=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(s+=8,a=127):r>125&&(s+=2,a=126);const c=Buffer.allocUnsafe(i?r+s:s);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[s-4]=n[0],c[s-3]=n[1],c[s-2]=n[2],c[s-1]=n[3],o?[c,e]:i?(jp(e,n,c,s,r),[c]):(jp(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let s;if(void 0===t)s=Op;else{if("number"!=typeof t||!Dp(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");s=Buffer.allocUnsafe(2+e),s.writeUInt16BE(t,0),"string"==typeof n?s.write(n,2):s.set(n,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0)}const o={[Rp]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(e.frame(s,o),i)}ping(t,n,r){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):Bp(t)?(i=t.size,s=!1):(i=(t=Up(t)).length,s=Up.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Rp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};Bp(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}pong(t,n,r){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):Bp(t)?(i=t.size,s=!1):(i=(t=Up(t)).length,s=Up.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Rp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};Bp(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}send(e,t,n){const r=this._extensions[Pp.extensionName];let i,s,o=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):Bp(e)?(i=e.size,s=!1):(i=(e=Up(e)).length,s=Up.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,o=0),t.fin&&(this._firstFragment=!0);const c={[Rp]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:s,rsv1:a};Bp(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[Rp],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(Hp,this,e,i)}this._bufferedBytes-=r[Rp];const s=Up(t);n?this.dispatch(s,n,r,i):(this._state=0,this.sendFrame(e.frame(s,r),i),this.dequeue())})).catch((e=>{process.nextTick(zp,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const s=this._extensions[Pp.extensionName];this._bufferedBytes+=r[Rp],this._state=1,s.compress(t,r.fin,((t,n)=>{if(this._socket.destroyed){Hp(this,new Error("The socket was closed while data was being compressed"),i)}else this._bufferedBytes-=r[Rp],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][Rp],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Rp],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)}};function Hp(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 zp(e,t,n){Hp(e,t,n),e.onerror(t)}const{kForOnEventAttribute:qp,kListener:Kp}=Wu,Jp=Symbol("kCode"),Yp=Symbol("kData"),Xp=Symbol("kError"),Zp=Symbol("kMessage"),Qp=Symbol("kReason"),eg=Symbol("kTarget"),tg=Symbol("kType"),ng=Symbol("kWasClean");class rg{constructor(e){this[eg]=null,this[tg]=e}get target(){return this[eg]}get type(){return this[tg]}}Object.defineProperty(rg.prototype,"target",{enumerable:!0}),Object.defineProperty(rg.prototype,"type",{enumerable:!0});class ig extends rg{constructor(e,t={}){super(e),this[Jp]=void 0===t.code?0:t.code,this[Qp]=void 0===t.reason?"":t.reason,this[ng]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Jp]}get reason(){return this[Qp]}get wasClean(){return this[ng]}}Object.defineProperty(ig.prototype,"code",{enumerable:!0}),Object.defineProperty(ig.prototype,"reason",{enumerable:!0}),Object.defineProperty(ig.prototype,"wasClean",{enumerable:!0});class sg extends rg{constructor(e,t={}){super(e),this[Xp]=void 0===t.error?null:t.error,this[Zp]=void 0===t.message?"":t.message}get error(){return this[Xp]}get message(){return this[Zp]}}Object.defineProperty(sg.prototype,"error",{enumerable:!0}),Object.defineProperty(sg.prototype,"message",{enumerable:!0});class og extends rg{constructor(e,t={}){super(e),this[Yp]=void 0===t.data?null:t.data}get data(){return this[Yp]}}Object.defineProperty(og.prototype,"data",{enumerable:!0});const ag={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[qp]&&r[Kp]===t&&!r[qp])return;let r;if("message"===e)r=function(e,n){const r=new og("message",{data:n?e:e.toString()});r[eg]=this,lg(t,this,r)};else if("close"===e)r=function(e,n){const r=new ig("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[eg]=this,lg(t,this,r)};else if("error"===e)r=function(e){const n=new sg("error",{error:e,message:e.message});n[eg]=this,lg(t,this,n)};else{if("open"!==e)return;r=function(){const e=new rg("open");e[eg]=this,lg(t,this,e)}}r[qp]=!!n[qp],r[Kp]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[Kp]===t&&!n[qp]){this.removeListener(e,n);break}}};var cg={CloseEvent:ig,ErrorEvent:sg,Event:rg,EventTarget:ag,MessageEvent:og};function lg(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:dg}=mp;function ug(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var pg={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),s=!1,o=!1,a=!1,c=-1,l=-1,d=-1,u=0;for(;u<e.length;u++)if(l=e.charCodeAt(u),void 0===n)if(-1===d&&1===dg[l])-1===c&&(c=u);else if(0===u||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u);const r=e.slice(c,d);44===l?(ug(t,r,i),i=Object.create(null)):n=r,c=d=-1}}else-1===d&&-1!==c&&(d=u);else if(void 0===r)if(-1===d&&1===dg[l])-1===c&&(c=u);else if(32===l||9===l)-1===d&&-1!==c&&(d=u);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u),ug(i,e.slice(c,d),!0),44===l&&(ug(t,n,i),i=Object.create(null),n=void 0),c=d=-1}else{if(61!==l||-1===c||-1!==d)throw new SyntaxError(`Unexpected character at index ${u}`);r=e.slice(c,u),c=d=-1}else if(o){if(1!==dg[l])throw new SyntaxError(`Unexpected character at index ${u}`);-1===c?c=u:s||(s=!0),o=!1}else if(a)if(1===dg[l])-1===c&&(c=u);else if(34===l&&-1!==c)a=!1,d=u;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${u}`);o=!0}else if(34===l&&61===e.charCodeAt(u-1))a=!0;else if(-1===d&&1===dg[l])-1===c&&(c=u);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u);let o=e.slice(c,d);s&&(o=o.replace(/\\/g,""),s=!1),ug(i,r,o),44===l&&(ug(t,n,i),i=Object.create(null),n=void 0),r=void 0,c=d=-1}}else-1===d&&(d=u);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===d&&(d=u);const p=e.slice(c,d);return void 0===n?ug(t,p,i):(void 0===r?ug(i,p,!0):ug(i,r,s?p.replace(/\\/g,""):p),ug(t,n,i)),t}};const gg=U,hg=R,fg=F,mg=N,yg=P,{randomBytes:vg,createHash:bg}=d,{URL:Sg}=M,wg=cp,Ig=Ap,_g=Vp,{isBlob:$g}=mp,{BINARY_TYPES:Cg,EMPTY_BUFFER:kg,GUID:Eg,kForOnEventAttribute:xg,kListener:Ag,kStatusCode:Ng,kWebSocket:Pg,NOOP:Og}=Wu,{EventTarget:{addEventListener:Tg,removeEventListener:Lg}}=cg,{format:Bg,parse:Dg}=pg,{toBuffer:jg}=qu,Ug=3e4,Rg=Symbol("kAborted"),Fg=[8,13],Mg=["CONNECTING","OPEN","CLOSING","CLOSED"],Wg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let Gg=class e extends gg{constructor(t,n,r){super(),this._binaryType=Cg[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=kg,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]),Hg(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Cg.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 Ig({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new _g(t,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=t,i[Pg]=this,s[Pg]=this,t[Pg]=this,i.on("conclude",Xg),i.on("drain",Zg),i.on("error",Qg),i.on("message",th),i.on("ping",nh),i.on("pong",rh),s.onerror=sh,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",ah),t.on("data",ch),t.on("end",lh),t.on("error",dh),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[wg.extensionName]&&this._extensions[wg.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())})),oh(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";Jg(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||kg,n,r)):Yg(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||kg,n,r)):Yg(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 Yg(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[wg.extensionName]||(i.compress=!1),this._sender.send(t||kg,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";Jg(this,this._req,e)}}};Object.defineProperty(Gg,"CONNECTING",{enumerable:!0,value:Mg.indexOf("CONNECTING")}),Object.defineProperty(Gg.prototype,"CONNECTING",{enumerable:!0,value:Mg.indexOf("CONNECTING")}),Object.defineProperty(Gg,"OPEN",{enumerable:!0,value:Mg.indexOf("OPEN")}),Object.defineProperty(Gg.prototype,"OPEN",{enumerable:!0,value:Mg.indexOf("OPEN")}),Object.defineProperty(Gg,"CLOSING",{enumerable:!0,value:Mg.indexOf("CLOSING")}),Object.defineProperty(Gg.prototype,"CLOSING",{enumerable:!0,value:Mg.indexOf("CLOSING")}),Object.defineProperty(Gg,"CLOSED",{enumerable:!0,value:Mg.indexOf("CLOSED")}),Object.defineProperty(Gg.prototype,"CLOSED",{enumerable:!0,value:Mg.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Gg.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Gg.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[xg])return t[Ag];return null},set(t){for(const t of this.listeners(e))if(t[xg]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[xg]:!0})}})})),Gg.prototype.addEventListener=Tg,Gg.prototype.removeEventListener=Lg;var Vg=Gg;function Hg(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Fg[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,!Fg.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Fg.join(", ")})`);let s;if(t instanceof Sg)s=t;else try{s=new Sg(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===s.protocol?s.protocol="ws:":"https:"===s.protocol&&(s.protocol="wss:"),e._url=s.href;const o="wss:"===s.protocol,a="ws+unix:"===s.protocol;let c;if("ws:"===s.protocol||o||a?a&&!s.pathname?c="The URL's pathname is empty":s.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 zg(e,t)}const l=o?443:80,d=vg(16).toString("base64"),u=o?hg.request:fg.request,p=new Set;let g,h;if(i.createConnection=i.createConnection||(o?Kg:qg),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(g=new wg(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Bg({[wg.extensionName]:g.offer()})),n.length){for(const e of n){if("string"!=typeof e||!Wg.test(e)||p.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.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),(s.username||s.password)&&(i.auth=`${s.username}:${s.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=o,e._originalHostOrSocketPath=a?i.socketPath:s.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&&s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(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")),h=e._req=u(i),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=u(i);i.timeout&&h.on("timeout",(()=>{Jg(e,h,"Opening handshake has timed out")})),h.on("error",(t=>{null===h||h[Rg]||(h=e._req=null,zg(e,t))})),h.on("response",(s=>{const o=s.headers.location,a=s.statusCode;if(o&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void Jg(e,h,"Maximum redirects exceeded");let s;h.abort();try{s=new Sg(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void zg(e,n)}Hg(e,s,n,r)}else e.emit("unexpected-response",h,s)||Jg(e,h,`Unexpected server response: ${s.statusCode}`)})),h.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==Gg.CONNECTING)return;h=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void Jg(e,n,"Invalid Upgrade header");const o=bg("sha1").update(d+Eg).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void Jg(e,n,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?p.size?p.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":p.size&&(c="Server sent no subprotocol"),c)return void Jg(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!g){return void Jg(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Dg(l)}catch(t){return void Jg(e,n,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==wg.extensionName){return void Jg(e,n,"Server indicated an extension that was not requested")}try{g.accept(t[wg.extensionName])}catch(t){return void Jg(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[wg.extensionName]=g}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(h,e):h.end()}function zg(e,t){e._readyState=Gg.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function qg(e){return e.path=e.socketPath,mg.connect(e)}function Kg(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=mg.isIP(e.host)?"":e.host),yg.connect(e)}function Jg(e,t,n){e._readyState=Gg.CLOSING;const r=new Error(n);Error.captureStackTrace(r,Jg),t.setHeader?(t[Rg]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(zg,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Yg(e,t,n){if(t){const n=$g(t)?t.size:jg(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Mg[e.readyState]})`);process.nextTick(n,t)}}function Xg(e,t){const n=this[Pg];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[Pg]&&(n._socket.removeListener("data",ch),process.nextTick(ih,n._socket),1005===e?n.close():n.close(e,t))}function Zg(){const e=this[Pg];e.isPaused||e._socket.resume()}function Qg(e){const t=this[Pg];void 0!==t._socket[Pg]&&(t._socket.removeListener("data",ch),process.nextTick(ih,t._socket),t.close(e[Ng])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function eh(){this[Pg].emitClose()}function th(e,t){this[Pg].emit("message",e,t)}function nh(e){const t=this[Pg];t._autoPong&&t.pong(e,!this._isServer,Og),t.emit("ping",e)}function rh(e){this[Pg].emit("pong",e)}function ih(e){e.resume()}function sh(e){const t=this[Pg];t.readyState!==Gg.CLOSED&&(t.readyState===Gg.OPEN&&(t._readyState=Gg.CLOSING,oh(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function oh(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),Ug)}function ah(){const e=this[Pg];let t;this.removeListener("close",ah),this.removeListener("data",ch),this.removeListener("end",lh),e._readyState=Gg.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Pg]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",eh),e._receiver.on("finish",eh))}function ch(e){this[Pg]._receiver.write(e)||this.pause()}function lh(){const e=this[Pg];e._readyState=Gg.CLOSING,e._receiver.end(),this.end()}function dh(){const e=this[Pg];this.removeListener("error",dh),this.on("error",Og),e&&(e._readyState=Gg.CLOSING,this.destroy())}const{tokenChars:uh}=mp;var ph={parse:function(e){const t=new Set;let n=-1,r=-1,i=0;for(;i<e.length;i++){const s=e.charCodeAt(i);if(-1===r&&1===uh[s])-1===n&&(n=i);else if(0===i||32!==s&&9!==s){if(44!==s)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${i}`);-1===r&&(r=i);const s=e.slice(n,r);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),n=r=-1}}else-1===r&&-1!==n&&(r=i)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const s=e.slice(n,i);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}};const gh=U,hh=F,{createHash:fh}=d,mh=pg,yh=cp,vh=ph,bh=Vg,{GUID:Sh,kWebSocket:wh}=Wu,Ih=/^[+/0-9A-Za-z]{22}==$/;var _h=class extends gh{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:bh,...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=hh.createServer(((e,t)=>{const n=hh.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($h,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($h,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{$h(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",Ch);const i=e.headers["sec-websocket-key"],s=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Eh(this,e,t,405,"Invalid HTTP method")}if(void 0===s||"websocket"!==s.toLowerCase()){return void Eh(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!Ih.test(i)){return void Eh(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void Eh(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void kh(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=vh.parse(a)}catch(n){return void Eh(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&void 0!==l){const n=new yh(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=mh.parse(l);e[yh.extensionName]&&(n.accept(e[yh.extensionName]),d[yh.extensionName]=n)}catch(n){return void Eh(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const s={origin:e.headers[""+(8===o?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(s,((s,o,a,l)=>{if(!s)return kh(t,o||401,a,l);this.completeUpgrade(d,i,c,e,t,n,r)}));if(!this.options.verifyClient(s))return kh(t,401)}this.completeUpgrade(d,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,s,o){if(!i.readable||!i.writable)return i.destroy();if(i[wh])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return kh(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${fh("sha1").update(t+Sh).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[yh.extensionName]){const t=e[yh.extensionName].params,n=mh.format({[yh.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",Ch),c.setSocket(i,s,{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($h,this)}))),o(c,r)}};function $h(e){e._state=2,e.emit("close")}function Ch(){this.destroy()}function kh(e,t,n,r){n=n||hh.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} ${hh.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function Eh(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,Eh),e.emit("wsClientError",r,n,t)}else kh(n,r,i)}var xh=yl(_h);const Ah=Bl("websocketServer"),Nh={},Ph=bu();let Oh,Th,Lh,Bh,Dh;const jh=e=>{const t=Nh[e];t&&t.socket.close()};var Uh={startServer:e=>{Dh=new xh({port:e,maxPayload:1048576e3}),Dh.on("connection",(e=>{const t=Ul();Ah(`New client connected. Registered as "${t}"`),e.id=t,Nh[t]={socket:e,activeMessage:null},Oh&&Oh(t),e.on("message",(t=>{if(t instanceof Buffer){const n=Nh[e.id];Ph(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),Ah(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{jh(n.socket.id)};if(t.command)return Ah(`Received command from client [${n.socket.id}]: ${t.command}`),void(Lh&&Lh(n.socket.id,t.command,r,i));t.klMessage&&Bh&&Bh({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",(()=>{Ah(`Client disconnected: ${e.id}`),Th&&Th(e.id),delete Nh[e.id]})),e.on("error",(()=>{Ah(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},stopServer:()=>{Dh.close((()=>{console.log("WebSocket server stopped")}))},onClientConnected:e=>{Oh=e},onClientDisconnected:e=>{Th=e},onClientCommand:e=>{Lh=e},sendCommand:(e,t)=>{const n=Nh[e];if(!n)return Ah(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=Xd)return Ah("Message is too long to be a command. Use sendMessage instead."),!1;const r=pu.encodeCommand(t);return n.socket.send(r),!0},onMessageReceived:e=>Bh=e,terminateConnection:jh};const Rh=Bl("stopService"),Fh=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=fd.getAllServiceVersions(t);Rh(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await fd.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},Mh=Bl("removeService"),Wh=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=fd.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),Mh(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await fd.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},Gh=Bl("launchService"),Vh=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=Xl();Gh(`Loading service ${t}@${n} from ${i}`);const{errorMsg:s,service:o,errorCode:a}=await fd.loadAndLaunch(i,r,!1);if(s||"started"!==o?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${s||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,d=async()=>{const r=o.status;return"running"===r?(Gh(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(Gh(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${o.errorMsg||"failed to initiate"}"`}):Date.now()-c>l?e.reply({error:"Timeout waiting for service to start"}):(Gh("Retrying in 1 second..."),void setTimeout(d,1e3)))};d()}catch(r){return Gh(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},Hh=Bl("getMatchingServices"),zh=async e=>{const t=e.args[0],n=[],r=[];Hh(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=fd.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:fd.getServiceRootDirectory(t)}):r.push({name:e,version:i})}Hh(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},qh=Bl("getSecretsValues");let Kh;var Jh=async e=>{const t=e.args[0].services;if(!Kh)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");qh(`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 Kh({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})},Yh=e=>{Kh=e};const Xh=Bl("getMappedSecrets");let Zh;var Qh=async e=>{const t=e.args[0].services;Xh(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await Zh(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})},ef=e=>{Zh=e};const tf=Bl("getServiceContents"),nf=({reply:e,args:t})=>{const[n]=t;tf(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=fd.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}]})}tf(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let rf={globalApiKey:void 0};const sf=()=>({...rf}),of=()=>{const e=sf();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},af=async(e,t)=>{try{const n=await fetch(e,{method:"POST",body:JSON.stringify(t)});return n.ok?{data:await n.json(),statusCode:n.status,success:!0}:{statusCode:n.status,error:await n.text(),success:!1}}catch(e){return{statusCode:500,error:e instanceof Error?e.message:"Internal server error",success:!1}}},cf={},lf=async e=>{const t=(e=>{const t=cf[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 af(`${of()}/v1/validate/validate_key`,{apiKey:e});return n?(console.warn(`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&&(cf[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}},df=Bl("activeClients");let uf={},pf={};const gf=(e,t)=>`${e}_${t}`,hf=e=>uf[e]||null,ff=(e,t)=>{const n=gf(e,t);return pf[n]||[]},mf=()=>{for(const e in uf){const t=uf[e];if(t?.transport===Qc.WS){const e=pu.encodeCommand(Yc.ServicesListChanged);t.send(e)}}},yf=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:s,extraInfo:o,isDevClient:a}=e,c=e=>{console.warn(e),s&&s()};if(r===Qc.WS){if(!o.wsApiKey)return void c(`Attempted to register a WebSocket client without an API key. SessionId: ${n}`);const{valid:e,error:t}=await lf(o.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&df(`Unable to validate API Key, usage will be limited. SessionId: ${n}`)}uf[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:i,extraInfo:o,terminate:()=>{s&&s()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=gf(e.serviceName,e.version);pf[r]=pf[r]||[];return pf[r].some((e=>e.serviceId===n))||pf[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=gf(e.serviceName,e.version),s=pf[i]?.findIndex((e=>e.serviceId===n));if(-1!==s&&(pf[i]?.splice(s,1),!pf[i]?.length)){const t=fd.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=hf(t.info.sessionId);e?.extraInfo.ipcSocketId&&Ou(e?.extraInfo.ipcSocketId,Yc.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=gf(e.targetService.serviceName,e.targetService.version),r=pf[t]?.findIndex((e=>e.serviceId===n));-1!==r&&pf[t]?.splice(r,1)}t.length=0}},r===Qc.IPC&&(mf(),bf(n))},vf=()=>{const e=Object.values(uf);for(const t of e)if(t.transport===Qc.IPC){const e=t.extraInfo.ipcSocketId,n=fd.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){ff(n.info.name,n.info.version).length||e&&Ou(e,Yc.BroadcastEnd)}}},bf=e=>{const t=fd.getServiceBySessionId(e);if(t?.info.eventEmitter){if(ff(t.info.name,t.info.version).length){const t=hf(e);t?.extraInfo.ipcSocketId&&Ou(t?.extraInfo.ipcSocketId,Yc.BroadcastStart)}}},Sf=e=>{const t=uf[e];delete uf[e],t?.transport===Qc.IPC?mf():(t?.removeAllSubscriptions(),vf())},wf=Bl("ipc:handleIpcClientCommand"),If=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(Yc.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 wf(`Ignoring ACK response from IPC service ${e} with no service id`);wf(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(Tu(e,t),r=t);let i=!1;t&&(i=fd.setServiceStatus(t,"running")),i?yf({serviceSessionId:t||e,transport:Qc.IPC,send:n,extraInfo:{ipcSocketId:t}}):Ou(r,Yc.SendManifest)}));!r&&wf(`Received unknown command [${t}] from service ${e}`)};let _f={};G.platform();const $f=async e=>{const t=e.args[0];if(_f.chooseDirectory)try{const n=await _f.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"})},Cf=async e=>{const t=e.args[0];if(_f.chooseFile)try{const n=await _f.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"})},kf=e=>{_f=e};var Ef={},xf={},Af={};function Nf(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Pf(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Of(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Tf(e,...t){if(!Of(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 Lf(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Nf(e.outputLen),Nf(e.blockLen)}function Bf(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 Df(e,t){Tf(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(Af,"__esModule",{value:!0}),Af.output=Af.exists=Af.hash=Af.bytes=Af.bool=Af.number=Af.isBytes=void 0,Af.number=Nf,Af.bool=Pf,Af.isBytes=Of,Af.bytes=Tf,Af.hash=Lf,Af.exists=Bf,Af.output=Df;const jf={number:Nf,bool:Pf,bytes:Tf,hash:Lf,exists:Bf,output:Df};Af.default=jf;var Uf={};Object.defineProperty(Uf,"__esModule",{value:!0}),Uf.add5L=Uf.add5H=Uf.add4H=Uf.add4L=Uf.add3H=Uf.add3L=Uf.add=Uf.rotlBL=Uf.rotlBH=Uf.rotlSL=Uf.rotlSH=Uf.rotr32L=Uf.rotr32H=Uf.rotrBL=Uf.rotrBH=Uf.rotrSL=Uf.rotrSH=Uf.shrSL=Uf.shrSH=Uf.toBig=Uf.split=Uf.fromBig=void 0;const Rf=BigInt(2**32-1),Ff=BigInt(32);function Mf(e,t=!1){return t?{h:Number(e&Rf),l:Number(e>>Ff&Rf)}:{h:0|Number(e>>Ff&Rf),l:0|Number(e&Rf)}}function Wf(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=Mf(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}Uf.fromBig=Mf,Uf.split=Wf;const Gf=(e,t)=>BigInt(e>>>0)<<Ff|BigInt(t>>>0);Uf.toBig=Gf;const Vf=(e,t,n)=>e>>>n;Uf.shrSH=Vf;const Hf=(e,t,n)=>e<<32-n|t>>>n;Uf.shrSL=Hf;const zf=(e,t,n)=>e>>>n|t<<32-n;Uf.rotrSH=zf;const qf=(e,t,n)=>e<<32-n|t>>>n;Uf.rotrSL=qf;const Kf=(e,t,n)=>e<<64-n|t>>>n-32;Uf.rotrBH=Kf;const Jf=(e,t,n)=>e>>>n-32|t<<64-n;Uf.rotrBL=Jf;const Yf=(e,t)=>t;Uf.rotr32H=Yf;const Xf=e=>e;Uf.rotr32L=Xf;const Zf=(e,t,n)=>e<<n|t>>>32-n;Uf.rotlSH=Zf;const Qf=(e,t,n)=>t<<n|e>>>32-n;Uf.rotlSL=Qf;const em=(e,t,n)=>t<<n-32|e>>>64-n;Uf.rotlBH=em;const tm=(e,t,n)=>e<<n-32|t>>>64-n;function nm(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}Uf.rotlBL=tm,Uf.add=nm;const rm=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);Uf.add3L=rm;const im=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;Uf.add3H=im;const sm=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);Uf.add4L=sm;const om=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;Uf.add4H=om;const am=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);Uf.add5L=am;const cm=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0;Uf.add5H=cm;const lm={fromBig:Mf,split:Wf,toBig:Gf,shrSH:Vf,shrSL:Hf,rotrSH:zf,rotrSL:qf,rotrBH:Kf,rotrBL:Jf,rotr32H:Yf,rotr32L:Xf,rotlSH:Zf,rotlSL:Qf,rotlBH:em,rotlBL:tm,add:nm,add3L:rm,add3H:im,add4L:sm,add4H:om,add5H:cm,add5L:am};Uf.default=lm;var dm={},um={};Object.defineProperty(um,"__esModule",{value:!0}),um.crypto=void 0,um.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
|
|
1
|
+
import{config as e}from"dotenv";import{readFile as t,access as n}from"node:fs/promises";import{nanoid as r}from"nanoid";import i from"jsonp";import s from"crypto-js";import o from"emittery";import"axios";import a from"jszip";import c from"util";import d from"mustache";import l,{scryptSync as u,createDecipheriv as p,createHash as g}from"crypto";import{satisfies as h}from"compare-versions";import f from"debug";import m,{join as y,dirname as v,resolve as b}from"path";import"node-ipc";import{mkdir as S,readFile as w,access as I,constants as _,readdir as $,rm as C}from"fs/promises";import k from"minimist";import E from"tty";import x,{homedir as A}from"os";import N from"net";import P from"tls";import O,{promises as T}from"fs";import L from"dgram";import B from"stream";import D from"zlib";import j from"buffer";import U from"events";import R from"https";import F from"http";import M,{fileURLToPath as W}from"url";import G from"node:os";import{spawn as V}from"child_process";import{join as H,resolve as z,dirname as q}from"node:path";import{ImageData as K,loadImage as J,createCanvas as Y}from"@napi-rs/canvas";var X;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(X=X||(X={}));const Z="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,Q="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,ee="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,te={};let ne=0,re="";const ie=e=>te[e]?te[e]:null,se=(e,t)=>{const n=ie(e);if(!n)return n;return n.blocks[t]||null},oe=(e,t,n)=>{const r=se(e,t);if(!r)return r;return r.gates[n]},ae=(e,t)=>{let n=r(4);for(;te[n];)n=r(4);const i=(s=e,JSON.parse(JSON.stringify(s)));var s;return i.logs="",i.addLog=e=>{i.logs+=`${(()=>{const e=Date.now();if(e!==ne){const t=new Date;ne=e,re=t.toJSON()}return re})()}:: ${e}\n`},i.dbInfo={...t},te[n]=i,n},ce="interrupt_port",de="main.js",le="state.json",ue="{#}",pe="UI:",ge="default";var he,fe,me,ye,ve,be,Se,we;let Ie;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(he||(he={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(fe||(fe={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(me||(me={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ye||(ye={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(ve||(ve={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(be||(be={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(Se||(Se={})),function(e){e.IPC="ipc",e.WS="ws"}(we||(we={}));const _e=()=>{if(!Ie)throw new Error("CanvasManager not set");return Ie},$e=e=>{Ie=e},Ce=(e,t)=>_e().createCanvas(e,t),ke=e=>Z?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Ee=e=>_e().loadImage(e),xe="-",Ae=`inner${xe}`,Ne=`outer${xe}`,Pe=`${Ne}input${xe}`,Oe=`${Ne}output${xe}`,Te=`${Ae}input${xe}`,Le=`${Ae}output${xe}`,Be=e=>(new TextEncoder).encode(e),De=e=>e===ce,je=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Ue=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.top&&void 0!==e.left&&"number"==typeof e.width&&"number"==typeof e.height&&"number"==typeof e.top&&"number"==typeof e.left,Re=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Fe=e=>"number"==typeof e?fe.Number:"string"==typeof e?fe.String:"boolean"==typeof e?fe.Boolean:Array.isArray(e)?fe.Array:je(e)?fe.ImageData:e&&void 0!==e.duration&&void 0!==e.length&&void 0!==e.numberOfChannels&&void 0!==e.sampleRate&&"function"==typeof e.getChannelData&&"AudioBuffer"===e.constructor.name?fe.AudioBuffer:e&&void 0!==e.byteLength?fe.ArrayBuffer:Ue(e)?fe.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?fe.Point:(e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer)(e)?fe.BinaryFile:fe.JsonObj,Me=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Fe(n[e]);t[e]=r}return t},We=(e,t,n)=>"inner"===e?"input"===t?`${Te}${n}`:`${Le}${n}`:"input"===t?`${Pe}${n}`:`${Oe}${n}`,Ge=e=>{const t=(e||"")?.split("_");if(t.length<3)throw new Error(`Unknown child identifier format [${e}]`);const n=t[0];return{portType:t[1],widgetId:n,portName:t[2]}},Ve=async e=>{try{return new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace})}catch(t){console.warn("Failed to create ImageData from info, assuming raw image data",t);return await Ee(e.data)}};var He,ze;!function(e){e.Action="action",e.CustomInput="customInput"}(He=He||(He={})),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.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",e.imageFilter="imageFilter",e.recipeLoad="recipeLoad",e.note="note",e.stringify="stringify",e.templateString="templateString",e.expressionEval="expressionEval",e.rescue="rescue",e.objectCombine="objectCombine",e.loop="loop"}(ze=ze||(ze={}));const qe={};let Ke;const Je=async e=>{const t=qe[e],n={name:ce,type:fe.Boolean};if(t){const r={name:t.portName},i=t.data||{type:fe.Boolean,value:!0};Ke?(await Ke(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...i,timestamp:Date.now()},[n]),"timeout"===t.type&&Ye(e)):console.warn("Interrupt service has not been initialized")}},Ye=e=>{const t=qe[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete qe[e],!0)};var Xe={interruptHandler:Je,createInterrupt:(e,t,n,i,s,o,a,c)=>{if(c&&qe[c])throw new Error("The given interrupt id already exists");const d=c||r().replace(/_/g,"-");if("interval"===e&&!o.interval)throw new Error(`Invalid interval. Expected a number greater than 0, but got '${o.interval}'`);if("timeout"===e&&!o.timeout)throw new Error(`Invalid timeout. Expected a number greater than 0, but got '${o.timeout}'`);if(qe[d]={data:a,portName:s,recipePoolId:t,targetWidgetId:i,thingId:n,type:e},"interval"===e)qe[d].timerRef=setInterval((async()=>await Je(d)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);qe[d].timerRef=setTimeout((async()=>await Je(d)),o.timeout)}return d},destroyInterrupt:Ye,destroyAllInterrupts:()=>{Object.keys(qe).forEach(Ye)},setInvokeChildGateCb:e=>{Ke=e}};const Ze=[10001,"Invalid `sourcePort` parameter"],Qe=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],et=[10110,"No storage medium has been loaded, call `loadMedium()` first"],tt=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?c.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),nt=()=>({inputName:"",dataType:fe.Anything}),rt="output",it={processEvent:async(e,t)=>{const n=t.getState(),r={...nt(),...n};if(e.type===r.dataType||r.dataType===fe.Anything)return t.nextWidget(rt,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...nt(),...e};return[{name:rt,type:t.dataType}]},getInputNames:()=>[]},st=Object.freeze({in:"in",reset:"reset",increment:"increment"}),ot="output";var at={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(tt(Ze));const i={currentValue:0,increment:1,...r.getState()};let s=i.increment,o=i.currentValue;const a=await r.getParentAtPort(st.increment);if(t.name===st.increment)return void(n.data.type===fe.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(s=e)}if(t.name===st.reset)return r.setState({...i,currentValue:0});o+=s,r.setState({currentValue:o,increment:s});const c={type:fe.Number,value:o};return r.nextGate(ot,c)},getInputNames:()=>[{name:st.in,type:fe.Anything},{name:st.reset,type:fe.Anything},{name:st.increment,type:fe.Number}],getOutputNames:()=>[{name:ot,type:fe.Number}]};const ct=Object.freeze({in:"in",reset:"reset"}),dt="output";var lt={onParentEvent:async(e,t,n,r)=>{const i={updatedAt:0,elapsed:0,...r.getState()},s=Date.now(),o=s-(i.updatedAt||s);return t.name===ct.reset?r.setState({...i,updatedAt:s,elapsed:0}):(r.setState({updatedAt:s,elapsed:o}),r.nextGate(dt,{type:fe.Number,value:o}))},getInputNames:()=>[{name:ct.in,type:fe.Anything},{name:ct.reset,type:fe.Anything}],getOutputNames:()=>[{name:dt,type:fe.Number}]};const ut=Object.freeze({data:"data",evaluation:"evaluation"}),pt="then",gt="else";var ht={onParentEvent:async(e,t,n,r)=>{const i={value:5,condition:"Equal",useDataPort:!1,...r.getState()},s=n.data.value,o=!isNaN(Number(s)),a="string"==typeof s;if(!i.useDataPort&&(n.data.type===fe.Number||n.data.type===fe.String||n.data.type===fe.Boolean||n.data.type===fe.Anything&&o||n.data.type===fe.Anything&&a)){let e=!1;return("Equal"===i.condition&&(n.data.value==i.value||n.data.type===fe.Boolean&&n.data.value.toString()===i.value.toString())||"Not Equal"===i.condition&&(n.data.value!==i.value||n.data.type===fe.Boolean&&n.data.value!==i.value.toString())||"Greater"===i.condition&&n.data.type===fe.Number&&n.data.value>Number(i.value)||"Less"===i.condition&&n.data.type===fe.Number&&n.data.value<Number(i.value)||"Starts With"===i.condition&&String(n.data.value).startsWith(String(i.value))||"Ends With"===i.condition&&String(n.data.value).endsWith(String(i.value))||"Includes"===i.condition&&String(n.data.value).includes(String(i.value))||"Matches"===i.condition&&String(n.data.value).match(String(i.value)))&&(e=!0),e?r.nextGate(pt,n.data):r.nextGate(gt,n.data)}if(t.name===ut.evaluation&&(n.data.type===fe.Number||n.data.type===fe.String||n.data.type===fe.Boolean||n.data.type===fe.Anything&&(o||a))&&(i.$lastValue=n.data.value,i.$lastInputDataType=n.data.type,r.setState({...i})),t.name===ut.data){let e=!1;return("Equal"===i.condition&&(i.$lastValue==i.value||i.$lastInputDataType===fe.Boolean&&i.$lastValue?.toString()===i.value.toString())||"Not Equal"===i.condition&&(i.$lastValue!==i.value||i.$lastInputDataType===fe.Boolean&&i.$lastValue!==i.value.toString())||"Greater"===i.condition&&i.$lastInputDataType===fe.Number&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&i.$lastInputDataType===fe.Number&&Number(i.$lastValue)<Number(i.value)||"Starts With"===i.condition&&String(i.$lastValue).startsWith(String(i.value))||"Ends With"===i.condition&&String(i.$lastValue).endsWith(String(i.value))||"Includes"===i.condition&&String(i.$lastValue).includes(String(i.value))||"Matches"===i.condition&&String(i.$lastValue).match(String(i.value)))&&(e=!0),r.setState({...i,$lastValue:void 0,$lastInputDataType:void 0}),e?r.nextGate(pt,n.data):r.nextGate(gt,n.data)}},getInputNames:e=>e.useDataPort?[{name:ut.data,type:fe.Anything,triggerPort:!0},{name:ut.evaluation,type:[fe.Number,fe.String,fe.Boolean]}]:[{name:"in",type:[fe.Number,fe.String,fe.Boolean]}],getOutputNames:e=>e.$lastOutputDataType?[{name:pt,type:e.$lastOutputDataType},{name:gt,type:e.$lastOutputDataType}]:[{name:pt,type:[fe.Number,fe.String]},{name:gt,type:[fe.Number,fe.String]}]};const ft=Object.freeze({in:"in",reset:"reset"}),mt="out";var yt={onParentEvent:async(e,t,n,r)=>{const i={totalCalls:0,callsLimit:1,...r.getState()};return t.name===ft.reset?r.setState({...i,totalCalls:0}):(i.totalCalls=i.totalCalls+1,i.totalCalls>i.callsLimit?(i.totalCalls=0,r.setState(i),r.nextGate(mt,n.data)):void r.setState(i))},getInputNames:()=>[{name:ft.in,type:fe.Anything},{name:ft.reset,type:fe.Anything}],getOutputNames:()=>[{name:mt,type:fe.Anything}]};const vt=Object.freeze({in:"in"}),bt="then",St="else";var wt={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:10,...r.getState()};if(n.data.type===fe.Number)return n.data.value>=i.min&&n.data.value<=i.max?r.nextGate(bt,n.data):r.nextGate(St,n.data)},getInputNames:()=>[{name:vt.in,type:fe.Number}],getOutputNames:()=>[{name:bt,type:fe.Number},{name:St,type:fe.Number}]};const It=Object.freeze({in:"in"}),_t="out";var $t={onParentEvent:async(e,t,n,r)=>{const i={clamp:!0,...r.getState()},s=Number(n.data.value);if(void 0!==i.fromMax&&void 0!==i.fromMin&&void 0!==i.toMax&&void 0!==i.toMin&&""!==i.fromMax&&""!==i.fromMin&&""!==i.toMax&&""!==i.toMin&&(n.data.type===fe.Number||n.data.type===fe.Anything&&!isNaN(Number(s)))){let e=((e,t,n,r,i)=>(e-t)*(i-r)/(n-t)+r)(s,Number(i.fromMin),Number(i.fromMax),Number(i.toMin),Number(i.toMax));if(isNaN(e))return;return i.clamp&&(e<Number(i.toMin)&&(e=Number(i.toMin)),e>Number(i.toMax)&&(e=Number(i.toMax))),r.nextGate(_t,{type:fe.Number,value:Number(e)})}},getInputNames:()=>[{name:It.in,type:fe.Number}],getOutputNames:()=>[{name:_t,type:fe.Number}]};const Ct=Object.freeze({in:"in"}),kt="out";var Et={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let s=n.data.value;if(n.data.type===fe.Number||n.data.type===fe.Anything||n.data.type===fe.String){if((!isNaN(Number(s))||"string"==typeof s)&&!Array.isArray(s))return"Integer"===i.convertTo?s=parseInt(s):"Decimal"===i.convertTo?s=parseFloat(Number(s).toFixed(i.floatPlaces)):"String"===i.convertTo?s=String(s):"Abs"===i.convertTo?s=Math.abs(Number(s)):"Round"===i.convertTo&&(s=Math.round(Number(s))),r.nextGate(kt,{type:"String"===i.convertTo?fe.String:fe.Number,value:s})}},getInputNames:()=>[{name:Ct.in,type:fe.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?fe.String:fe.Number;return[{name:kt,type:t}]}};const xt=Object.freeze({in:"in"}),At="out";var Nt={onParentEvent:async(e,t,n,r)=>{const i={currentValue:50,min:0,max:100,...r.getState()};let s=!1;return i.currentValue<i.min&&(i.currentValue=i.min,s=!0),i.currentValue>i.max&&(i.currentValue=i.max,s=!0),s&&r.setState(i),r.nextWidget(At,{type:fe.Number,value:i.currentValue})},getInputNames:()=>[{name:xt.in,type:fe.Anything}],getOutputNames:()=>[{name:At,type:fe.Number}]};const Pt=Object.freeze({in:"in",reset:"reset"}),Ot="out";var Tt={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},s={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Pt.reset)return r.setState({...s,lastCalledAt:0});const o=Date.now(),a=o-s.lastCalledAt;return s.lastCalledAt===i.lastCalledAt||a>=s.delayMs&&s.delayMs>0?(s.lastCalledAt=o,r.setState(s),r.nextGate(Ot,n.data)):void 0},getInputNames:()=>[{name:Pt.in,type:fe.Anything},{name:Pt.reset,type:fe.Anything}],getOutputNames:()=>[{name:Ot,type:fe.Anything}]};const Lt="in";var Bt={onParentEvent:async()=>{},getInputNames:()=>[{name:Lt,type:[fe.ImageData,fe.Number]}],getOutputNames:()=>[]};const Dt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),jt=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var Ut={onParentEvent:async(e,t,n,r)=>{const i={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},s=n?.data?.value,o=Array.isArray(s);if(n.data.type===fe.JsonObj||n.data.type===fe.Rect||n.data.type===fe.Point||n.data.type===fe.BinaryFile||n.data.type===fe.Anything||o){let e=!1;for(const t in s){const n=Fe(s[t]),r=!!i.detectedProperties[t],o=i.detectedProperties[t]?.type!==n;if(!r||o){const r=n===fe.JsonObj||n===fe.Rect||n===fe.Point||n===fe.Array;i.detectedProperties[t]={type:n,...r?{shape:Me(s[t])}:void 0},e=!0}}if(o&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:fe.Number}),e&&r.setState(i),s){const e=[];for(const t of i.properties||[]){const n=jt(s,t.label),o=t.label.includes(".");if(void 0!==n){const s=o?Fe(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:fe.Anything;e.push(r.nextGate(t.name,{type:s,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:fe.JsonObj}],getOutputNames:e=>{const t={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...e};return t.properties.map((e=>{const n=void 0!==t.detectedProperties[e.label]?t.detectedProperties[e.label]?.type:fe.Anything,r=t.detectedProperties[e.label]?.shape||void 0,i="string"==typeof e;return{name:i?e:e.name,label:i?e:e.label,type:n,jsonShape:r}}))},getDefaultState:Dt};const Rt="output",Ft="noItem";var Mt={onParentEvent:async(e,t,n,r)=>{const i={index:0,...r.getState()};let s=i.index;const o=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===fe.Anything&&(c||a)||n.data.type===fe.String&&a||n.data.type===fe.Array&&c){s<0&&(s=o.length+s);const e=a?fe.String:Fe(o[s]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==o[s]?r.nextGate(Rt,{value:o[s],type:e}):r.nextGate(Ft,{value:!0,type:fe.Boolean})}},getInputNames:()=>[{name:"in",type:[fe.Array,fe.String]}],getOutputNames:e=>[{name:Rt,type:e.$$lastDetectedType??fe.Anything},{name:Ft,type:fe.Boolean}]};const Wt={},Gt=e=>(Wt[e]||(Wt[e]={canvasFrom:Ce(320,240),canvasTo:Ce(320,240)}),Wt[e]),Vt=Object.freeze({image:"image",rect:"rect"}),Ht="image";var zt={onParentEvent:async(e,t,n,r)=>{const i=Gt(r.id),s={offset:{height:0,left:0,top:0,width:0},...r.getState()},o=[fe.Anything,fe.Rect,fe.JsonObj];if(t.name===Vt.rect&&Ue(n.data.value)&&o.includes(n.data.type)&&(s.rect=n.data.value,r.setState({...s})),t.name===Vt.image){if(!((n.data.type===fe.ImageData||n.data.type===fe.Anything)&&je(n.data.value)))throw new Error("Invalid image data. Expected a valid ImageData type");i.lastImage=n.data.value}if(i.lastImage&&s.rect){const e=((e,t,n,r,i)=>{if(r&&r.getContext){const s=r.getContext("2d"),o=n.getContext("2d");if(s&&o){n.width=e.width,n.height=e.height,o.putImageData(e,0,0);const a={...i};i&&(a.height=Number(i.height),a.width=Number(i.width),a.left=Number(i.left),a.top=Number(i.top));const c={top:0,width:0,left:0,height:0,...a};return i&&(Number.isInteger(c.width)||(c.width=t.width*c.width),Number.isInteger(c.height)||(c.height=t.height*c.height),Number.isInteger(c.left)||(c.left=t.left+t.width*c.left),Number.isInteger(c.top)||(c.top=t.top+t.height*c.top)),r.width=t.width+c.width,r.height=t.height+c.height,s.drawImage(n,t.left+c.left,t.top+c.top,t.width+c.width,t.height+c.height,0,0,r.width+c.width,r.height+c.height),s.getImageData(0,0,r.width||1,r.height||1)}}return e})(i.lastImage,s.rect,i.canvasFrom,i.canvasTo,s.offset);r.setState({...s,rect:null}),i.lastImage=void 0,await r.nextWidget(Ht,{type:fe.ImageData,value:e})}},getInputNames:()=>[{name:Vt.image,type:fe.ImageData},{name:Vt.rect,type:[fe.Rect,fe.JsonObj]}],getOutputNames:()=>[{name:Ht,type:fe.ImageData}],initialize:async e=>{Gt(e.widgetId)},terminate:async e=>{delete Wt[e.widgetId]}};const qt=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),i=e.data,s=e.width,o=e.height,a=s,c=o,d=((e,t,n)=>{if(Z)return new ImageData(t,n);return console.warn("Node environment detected. Aborting new ImageData creation"),e})(e,a,c),l=d.data;for(let e=0;e<c;e++)for(let c=0;c<a;c++){const d=e,u=c,p=4*(e*a+c);let g=0,h=0,f=0,m=0;for(let e=0;e<n;e++)for(let a=0;a<n;a++){const c=d+e-r,l=u+a-r;if(c>=0&&c<o&&l>=0&&l<s){const r=4*(c*s+l),o=t[e*n+a];g+=i[r]*o,h+=i[r+1]*o,f+=i[r+2]*o,m+=i[r+3]*o}}l[p]=g,l[p+1]=h,l[p+2]=f,l[p+3]=m+1*(255-m)}return d},Kt=[-1,0,1,-2,0,2,1,0,1],Jt=Object.freeze({image:"image"}),Yt="image";var Xt={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={matrix:[...Kt],...i};if(n.data.type===fe.ImageData||n.data.type===fe.Anything&&je(n.data.value)){const e=qt(n.data.value,s.matrix);return r.nextGate(Yt,{type:fe.ImageData,value:e})}},getInputNames:()=>[{name:Jt.image,type:fe.ImageData}],getOutputNames:()=>[{name:Yt,type:fe.ImageData}]};const Zt=Object.freeze({output:"output",aborted:"aborted"}),Qt=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),en=e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e},n=Array(t.inputs).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:"reset",type:fe.Anything}),n};var tn={onParentEvent:async(e,t,n,r)=>{const i={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...i,triggeredAt:0});const s=Date.now(),o=s-i.triggeredAt;if(i.triggeredAt&&!(o>=i.delayMs&&i.delayMs>0)&&i.delayMs)return r.nextGate(Zt.aborted,n.data);{i.triggeredAt=s;const e=en(i,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id)).findIndex((e=>e.name===t.name));-1!==e&&(i.lastInputIndex=e),i.matchingOutputs?-1!==e&&await r.nextGate(`output${e+1}`,n.data):await r.nextGate(Zt.output,n.data),r.setState(i)}},getInputNames:en,getOutputNames:e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e};if(e.matchingOutputs){const e=Array(t.inputs).fill(0).map(((e,t)=>({name:`output${t+1}`,type:fe.Anything})));return e.push({name:Zt.aborted,type:fe.Anything}),e}return[{name:Zt.output,type:fe.Anything},{name:Zt.aborted,type:fe.Anything}]},getDefaultState:Qt};const nn=(e,t,n,r,i,s)=>{if(i){const o=e.measureText(i),a=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-s,1.1*o.width,a),e.font=`${s}px Arial`,e.fillStyle="black",e.fillText(i,t,n)}},rn=(e,t,n,r,i,s,o)=>{e.fillStyle=i,e.fillRect(t,n,r,r),nn(e,t,n,i,s,o)},sn=(e,t,n,r,i,s)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const o=n/2;nn(e,t.left-o,t.top-o,r,i,s)},on={},an=e=>(on[e]||(on[e]={memCanvas:Ce(320,240),lastFrame:void 0,pixels:void 0}),on[e]),cn=Object.freeze({image:"image",pixels:"pixels"}),dn="image";var ln={onParentEvent:async(e,t,n,r)=>{const i=an(r.id),s={fontSize:12,color:"#00ff00",size:2,...r.getState()},o=(n.data.type===fe.ImageData||n.data.type===fe.Anything)&&je(n.data.value);if(t.name===cn.pixels){const e=(e=>Re(e)||Ue(e)||Array.isArray(e)&&e[0]&&(Re(e[0])||Ue(e[0])))(n.data.value);if(!e)return;i.pixels=n.data.value}if(t.name===cn.image&&o){const e=n.data.value;i.lastFrame=e}if(i.lastFrame&&i.pixels&&i.memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:i,color:s,labelProp:o,fontSize:a}=e;if(r){const e=ke(r);if(e){r.width!==t.width&&(r.width=t.width),r.height!==t.height&&(r.height=t.height),e.putImageData(t,0,0);const c=Array.isArray(n)?n:[n];for(let t=0;t<c.length;t++){const n=c[t],r=o?n[o]:"";Ue(n)?sn(e,n,i,s,r,a):Re(n)&&rn(e,n.x,n.y,i,s,r,a)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:i.lastFrame,pixels:i.pixels||[],memCanvas:i.memCanvas,size:s.size,color:s.color,labelProp:s.labelProp,fontSize:s.fontSize});return i.lastFrame=void 0,i.pixels=void 0,r.setState({...s}),r.nextWidget(dn,{type:fe.ImageData,value:e})}r.setState(s)},getInputNames:()=>[{name:cn.image,type:fe.ImageData},{name:cn.pixels,type:[fe.Rect,fe.Point,fe.Array,fe.JsonObj]}],getOutputNames:()=>[{name:dn,type:fe.ImageData}],initialize:async e=>{an(e.widgetId)},terminate:async e=>{delete on[e.widgetId]}};const un=Object.freeze({in:"in"}),pn="output",gn=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var hn={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:100,...r.getState()},s=!Number.isInteger(i.min),o=!Number.isInteger(i.max),a=s||o;let c=(d=i.min,l=i.max,Math.random()*(l-d)+d);var d,l;if(a){let e=0;if(s&&(e=gn(i.min)),o){const t=gn(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(pn,{type:fe.Number,value:c})},getInputNames:()=>[{name:un.in,type:fe.Anything}],getOutputNames:()=>[{name:pn,type:fe.Number}]};const fn=Object.freeze({output:"output",totalItems:"totalItems"}),mn=Object.freeze({trigger:"trigger",clear:"clear"}),yn=()=>({$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),vn=async(e,t)=>t.nextGate(fn.totalItems,{type:fe.Number,value:e});var bn={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===mn.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),vn(i.$$list.length,r);const s=t.name===mn.trigger;if(!s)if(Array.isArray(n.data.value))n.data.type!==fe.Array&&n.data.type!==fe.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await vn(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===fe.JsonObj?i.$$outputShape={...i.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:i.$$outputShape={...i.$$outputShape,[t]:n.data.type},i.$$list.push(n.data.value),r.setState({...i}),await vn(i.$$list.length,r)}if(s){Object.keys(i.$$outputShape).length&&(i.properties={autoFilled:!0,jsonShape:{...i.$$outputShape}});const e=i.$$list.length,t=[...i.$$list];return i.$$list=[],r.setState({...i}),await vn(e,r),r.nextGate(fn.output,{type:fe.Array,value:t})}},getInputNames:e=>{const t={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:mn.clear,type:fe.Anything},{name:mn.trigger,type:fe.Anything}),n},getOutputNames:e=>[{name:fn.output,type:fe.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:fn.totalItems,label:"Total Items",type:fe.Number}],getDefaultState:yn};const Sn=Object.freeze({start:"start",stop:"stop"}),wn="output",In="clock_interrupt";var _n={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(De(e?.name||"")&&t.name===In)return r.nextGate(wn,{type:fe.Boolean,value:!0});if(t.name===Sn.stop&&i.enabled&&i.$$interruptId){r.cancelInterrupt(i.$$interruptId)?(i.enabled=!1,i.$$interruptId=void 0,r.setState(i)):console.warn(`Failed to cancel interrupt [${i.$$interruptId}]`)}else t.name!==Sn.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt("interval",In,{interval:i.interval}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:Sn.start,type:fe.Anything},{name:Sn.stop,type:fe.Anything}],getOutputNames:()=>[{name:wn,type:fe.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",In,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const $n=Object.freeze({in:"in"}),Cn="output",kn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var En={onParentEvent:async(e,t,n,r)=>{const i={userProperties:[],factor:2,decimalPoints:2,...r.getState()},s=n.data.type;let o=n.data.value,a=!1;return e?.jsonShape&&(i.detectedInputJson={...i.detectedInputJson,...e?.jsonShape},a=!0),i.detectedInputType||(i.detectedInputType=s,a=!0),n.data.type===fe.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>kn(e,t,n)));return r})(n.data.value,i.factor,i.decimalPoints):"object"==typeof n.data.value?.[0]&&(o=((e,t,n,r)=>{const i=(e||[]).map((e=>{const i={...e};return Object.keys(i).forEach((e=>{r?.length&&!r?.includes(e)||(i[e]=kn(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===fe.Number&&(o=kn(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(Cn,{type:s,value:o})},getInputNames:()=>[{name:$n.in,type:[fe.Array,fe.Number]}],getOutputNames:e=>[{name:Cn,type:e.detectedInputType||fe.Number,jsonShape:e.detectedInputJson}]};const xn={},An=Object.freeze({output:"output"}),Nn=Object.freeze({trigger:"trigger"}),Pn=e=>e===fe.ArrayBuffer||e===fe.AudioBuffer||e===fe.BinaryFile||e===fe.ImageData||e===fe.ImageBitmap||e===fe.Array||e===fe.JsonObj,On=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:fe.Number,value:10},{name:"y",label:"y",type:fe.Number,value:20}]}),Tn=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},Ln=(e,t)=>{const n={};for(let r=0;r<e.properties.length;r++){let i=e.properties[r].value;const s=e.properties[r].type;Pn(s)&&(i=xn[t][e.properties[r].name]),s===fe.Number?i=Number(i):s===fe.String&&(i=String(i)),n[e.properties[r].label]=i}return n};var Bn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s=structuredClone(i),o={...On(),...s};if(t.name===Nn.trigger){const e=Ln(o,r.id);return r.nextWidget(An.output,{type:fe.JsonObj,value:e})}const a=o.properties.findIndex((e=>e.name===t.name));if(-1!==a){const e=o.properties[a];let t=n.data.type===e.type;if(!t&&n.data.type===fe.Anything){t=Fe(n.data.type)===e.type}if(t){const t=Pn(n.data.type);xn[r.id]=xn[r.id]||{},t?(xn[r.id][e.name]=n.data.value,o.properties[a].value=void 0):o.properties[a].value=n.data.value,o.properties[a].$$invalidInputType=!1}else o.properties[a].$$invalidInputType=!0;if(r.setState(o),!o.useTriggerPort){const e=Ln(o,r.id);return r.nextWidget(An.output,{type:fe.JsonObj,value:e})}}},getInputNames:e=>{const t={...On(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:Nn.trigger,label:Nn.trigger,type:fe.Anything}),n},getOutputNames:e=>[{name:An.output,label:An.output,type:fe.JsonObj,jsonShape:Tn(e)}],getDefaultState:On,initialize:async e=>{xn[e.widgetId]={}},terminate:async e=>{delete xn[e.widgetId]}};const Dn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(Pe)){const n=t(e,Pe);return We("inner","input",n)}if(e.startsWith(Le)){const n=t(e,Le);return We("outer","output",n)}return null},jn=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[fe.Anything],index:0}],outputs:[{name:"output",type:[fe.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Un=e=>{const t={...jn(),...e},n=t.inputs.map(((e,t)=>({name:We("outer","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t}))),r=t.outputs.map(((e,t)=>({name:We("inner","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:n.length+t})));return[...n,...r]};var Rn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...jn(),...i},o=Un(s,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const i=o[e];if(t.name===i.name&&(i.type.includes(fe.Anything)||i.type.includes(n.data.type))){const e=await Dn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Un,getOutputNames:e=>{const t={...jn(),...e},n=t.outputs.map(((e,t)=>({name:We("outer","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t})));return[...t.inputs.map(((e,t)=>({name:We("inner","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:t+n.length}))),...n]},getDefaultState:jn};const Fn=(e,t,n,r,i)=>{const s=4*(t*n.width+e),o=n.data[s],a=n.data[s+1],c=n.data[s+2];return Math.abs(o-r.r)<=i&&Math.abs(a-r.g)<=i&&Math.abs(c-r.b)<=i};var Mn={getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,i=n[t+1]||0,s=n[t+2]||0;return{avr:(r+i+s)/3,r:r,g:i,b:s}},getBoundingBox:(e,t,n)=>{const r=e.width,i=e.height,s=new Set,o=Number(n.threshold||0),a=isNaN(o)?10:o,c=(n,o)=>{const c=[[n,o]];let d=n,l=n,u=o,p=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,g]=n;o<0||g<0||o>=r||g>=i||s.has(`${o},${g}`)||!Fn(o,g,e,t,a||0)||(s.add(`${o},${g}`),d=Math.min(d,o),l=Math.max(l,o),u=Math.min(u,g),p=Math.max(p,g),c.push([o+1,g],[o-1,g],[o,g+1],[o,g-1]))}return{minX:d,maxX:l,minY:u,maxY:p}},d=[];for(let o=0;o<i;o+=4)for(let i=0;i<r;i+=4)if(!s.has(`${i},${o}`)&&Fn(i,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:s}=c(i,o),a=t-e,l=s-r;if(a>=(n.minWidth||1)&&l>=(n.minHeight||1)&&d.push({left:e,top:r,width:a,height:l}),n.maxBoxes&&d.length>=n.maxBoxes)return d}return d},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,i="object"==typeof n,s=i?n.r:n,o=i?n.g:n,a=i?n.b:n;r[t]=s,r[t+1]=o,r[t+2]=a,r[t+3]=255}};const Wn=e=>Fe(e);var Gn,Vn,Hn,zn,qn,Kn,Jn,Yn,Xn,Zn;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Gn||(Gn={})),function(e){e.Bundle="bundle",e.Group="group"}(Vn||(Vn={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Hn||(Hn={})),function(e){e.Cloud="cloud",e.Web="web"}(zn||(zn={})),function(e){e.Cpu_128M="kmu-cpu-128m",e.Cpu_256M="kmu-cpu-256m",e.Cpu_512M="kmu-cpu-512m",e.Cpu_1024M="kmu-cpu-1024m",e.Cpu_2048M="kmu-cpu-2048m",e.Cpu_4096M="kmu-cpu-4096m"}(qn||(qn={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Kn||(Kn={})),(Jn||(Jn={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Yn||(Yn={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Xn||(Xn={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Zn||(Zn={}));let Qn=null;var er=()=>{if(!Qn)throw new Error("Required function is not set");return Qn};class tr extends Error{targetWidgetId;targetPortName;sourcePortName;sourceWidgetId;targetWidgetType;sourceWidgetType;constructor(e,t){super(e),this.name="ChildWidgetError",t.stack&&(this.stack=t.stack),this.targetWidgetId=t.targetWidgetId,this.targetPortName=t.targetPortName,this.sourcePortName=t.sourcePortName,this.sourceWidgetId=t.sourceWidgetId,this.targetWidgetType=t.targetWidgetType,this.sourceWidgetType=t.sourceWidgetType}}class nr extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const rr=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===Gn.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\t\t\t\n\t\t\tvar console = this.console;\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\n\t\t\tvar Kemu = {\n\t\t\t\tservices: {\n\t\t\t\t\thttp: { ...this.httpWebService },\n\t\t\t\t\tdynamoDb: { ...this.dynamoService },\n\t\t\t\t\tgoogleSheets: {\n\t\t\t\t\t\t...this.googleSheetsService,\n\t\t\t\t\t}\n\t\t\t\t},\n\n\t\t\t\timage: this.imageHelpers,\n\t\t\t\tvariable: this.variablesManager,\n\n\t\t\t\thelpers: {\n\t\t\t\t\tdecodeDataType: this.decodeDataType,\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\tjsonp: this.jsonp,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tvar sendToPort;\n\n\t\t\t// --- User Methods Start ---\n\t\t\t${e||""};\n\t\t\t// --- User Methods End ---\n\t\t\t\n\t\t\t// Processes the user code asynchronously.\n\t\t\tconst asyncProcessEvent = async (targetPort, sourcePort, event) => {\n\t\t\t\tconst userProcessEvent = typeof processEvent === 'undefined' ? undefined : processEvent;\n\t\t\t\tif(userProcessEvent) {\n\t\t\t\t\ttry{\n\t\t\t\t\t\treturn await userProcessEvent(targetPort, sourcePort, event, sendToPort);\n\t\t\t\t\t}catch(e){\n\t\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked the very first time the recipe is initialized */\n\t\t\tconst asyncRecipeInit = async (context) => {\n\t\t\t\ttry {\n\t\t\t\t\tif(typeof recipeInit === 'function') {\n\t\t\t\t\t\treturn recipeInit(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked every time the code is about to be replaced */\n\t\t\tconst asyncOnTerminate = async (context) => {\n\t\t\t\ttry {\n\t\t\t\t\tif(typeof onTerminate === 'function') {\n\t\t\t\t\t\treturn onTerminate(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** updates the function that allows widget contexts to send data to the next widget */\n\t\t\tconst setSendToPort = (sendNextFun) => {\n\t\t\t\tsendToPort = sendNextFun;\n\t\t\t}\n\n\t\t\t/** invoked the every time the user code is compiled. */\n\t\t\tconst asyncMainEvent = async (sendNextFun) => {\n\t\t\t\ttry{\n\t\t\t\t\tsetSendToPort(sendNextFun);\n\t\t\t\t\tif(typeof main === 'function'){\n\t\t\t\t\t\treturn main();\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tasyncProcessEvent: asyncProcessEvent,\n\t\t\t\tmain: asyncMainEvent,\n\t\t\t\trecipeInit: asyncRecipeInit,\n\t\t\t\tsetSendToPortFun: setSendToPort,\n\t\t\t\tonTerminate: asyncOnTerminate,\n\t\t\t\tgetLocalContext: () => global,\n\t\t\t\tgetWidgetInputs: typeof getWidgetInputs === 'undefined' ? undefined : getWidgetInputs,\n\t\t\t\tgetWidgetOutputs: typeof getWidgetOutputs === 'undefined' ? undefined : getWidgetOutputs,\n\t\t\t};\n\t\t}\n\t\t\n\t\treturn function compiler(context){\n\t\t\treturn _user_code_.call(context)\n\t\t}\n\n\t\treturn compiler;\n\t`,ir=(e,t,n,r)=>{const o=rr(e,n),a={...t,document:{},__errorTracer:e=>{if(e instanceof tr)throw e;throw new nr(e.message,e.stack)},__jest:void 0===globalThis.__jest?void 0:globalThis.__jest,___notSupportedMethod:()=>r?.error("This method is not supported."),console:{...t.logger},setInterval:()=>r?.error("'setInterval' is not supported. Please use a \"Timer\" widget instead."),setTimeout:t?.setTimeout,imageHelpers:Mn,...n===Gn.Cloud?{require:er(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:i,CryptoJS:s,decodeDataType:Wn,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(Z)return"browser";if(ee)return"node";if(Q)return"worker";throw new Error("Unsupported environment")})()?(e=>e.replace(/[//]{2}[ ]*@kemu-cloud[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-cloud[ \t]*\}/gim,""))(o):(e=>e.replace(/[//]{2}[ ]*@kemu-browser[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-browser[ \t]*\}/gim,""))(o),t=new Function(e);return{compiledModule:t()(a)}}catch(e){return{error:{name:"CompileError",message:e.message,stack:e.stack}}}},sr="main",or="My Script",ar="This is a test script.",cr=`\n/**\n * Name: ${or}\n * Description: ${ar}\n */\n\nconst getWidgetInputs = () => [\n\t{ name: 'Input 1', type: DataType.Number }\n];\n\nconst getWidgetOutputs = () => [\n\t{ name: 'Output 1', type: DataType.Number }\n]\n\nlet counter = 0;\n\nconst processEvent = async (targetPort, sourceWidget, event) => {\n\tif(targetPort.name === 'Input 1'){\n\t\treturn sendToPort('Output 1', {\n\t\t\ttype: DataType.Number,\n\t\t\tvalue: counter++,\n\t\t});\n\t}\n}\n`.trim(),dr=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},version:2,metadata:{name:or,description:ar},pages:{[sr]:{code:cr,language:"javascript",name:"My First Script"}}}),lr=(e,t)=>{const n={message:"Unknown Error"};if(e?.stack){const r=e?.stack?.split(":")[0].trim();n.type=r;const i=(e=>{const t=/,[ ]?<anonymous>:([0-9]+:[0-9]+)\)/gm;let n;for(;null!==(n=t.exec(e));){n.index===t.lastIndex&&t.lastIndex++;const e=n[1].split(":");if(2===e.length)return{line:Number(e[0])||0,column:Number(e[1])||0}}return null})(e.stack);i&&(n.line=i.line-(e=>{const t="___user_code_section___";return rr(t,e).split(t)[0].split("\n").length+2})(t),n.column=i.column)}return e.message&&(n.message=e.message),n},ur=(e,t)=>{const n={...{...dr(),...t.getState()},$$error:e||void 0};e&&console.error(e.message),t.setState(n)},pr=new o;let gr,hr,fr={},mr={};const yr=e=>{const t=oe(gr,hr,e);if(!t)throw new Error(`Widget ${e} not found in thing ${hr}`);return t},vr=(e,t)=>`${e}:${t}`,br=e=>`${yr(e.createdByWidgetId).id}::${e.variableName}`,Sr=e=>`${pe}${e}`;var wr=e=>{const t=yr(e.createdByWidgetId),n=br({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});mr[n]={type:e.type,subscriberWidgetId:t.id,subscriberWidgetType:t.type}},Ir=e=>{const t=br({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});delete mr[t]},_r=async e=>{const t=yr(e.setByWidgetId);if(!t)throw new Error(`Widget ${e.setByWidgetId} not found in thing ${hr} in recipe ${gr}`);const n=e.variableName.startsWith(pe)?br({variableName:e.variableName,createdByWidgetId:e.setByWidgetId}):e.variableName;fr[n]={value:e.value,type:e.type};const r={value:e.value,type:e.type,varName:e.variableName,isUIElement:e.variableName.startsWith(pe),setByWidgetType:t.type,setByWidgetId:e.setByWidgetId};await pr.emit(vr(e.variableName,e.type),r),e.type!==fe.Anything&&await pr.emit(vr(e.variableName,fe.Anything),r)},$r=e=>{const{readerWidgetId:t,variableName:n}=e;if(!yr(t))throw new Error(`Widget ${t} not found in thing ${hr} in recipe ${gr}`);const r=n.startsWith(pe)?br({variableName:e.variableName,createdByWidgetId:e.readerWidgetId}):n,i=fr[r];if(i)return{type:i.type,value:i.value}},Cr=e=>{const{widgetId:t,variableName:n,type:r}=e;if(!yr(t))throw new Error(`Widget ${t} not found in thing ${hr} in recipe ${gr}`);const i=vr(n,r);let s;return s=pr.on(i,(async r=>{oe(gr,hr,t)?await e.onValueChange(r):(console.warn(`Zombie widget ${t} detected, unsubscribing from variable events "${n}"`),s?.())})),s},kr=(e,t)=>{const n=vr(e,fe.Anything);return pr.on(n,(async e=>{const{isUIElement:n,...r}=e;await t(r)}))},Er=e=>{mr={},fr={},gr=e.recipePoolId,hr=e.thingId};const xr="setTimeout",Ar="variableChanged",Nr=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=oe(t,n,r);if(!i)throw new Error(`Widget "${r}" not found in recipe "${t}"`);const s=(e,t)=>{const n=$r({readerWidgetId:r,variableName:e});if(n||t)return void 0===n?{value:t?.value??t,type:t?.type??Fe(t)}:{value:n.value,type:n.type}},o=(t,n,s)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");const o={...dr(),...e.getState()},a=Cr({variableName:t,type:fe.Anything,widgetId:r,onValueChange:async e=>{n?e.setByWidgetType===ze.widgetGroup&&e.setByWidgetId===i.groupId&&await s(e):s(e)}});delete o.$$eventListeners[t],o.$$eventListeners[t]={handler:s,abort:async()=>{a()},name:Ar},e.setState(o)};return{get:s,set:async(e,t,n)=>{await _r({variableName:e,type:n||Fe(t),setByWidgetId:r,value:t})},onValueChange:(e,t)=>{o(e,!1,t)},onUIValueChange:(e,t)=>{const n=Sr(e);o(n,!0,t)},getUIValue:e=>{const r=Sr(e),o=s(r);if(o)return{value:o.value,type:o.type};const a=i.groupId;if(!a)throw new Error("You can only read UI variables from inside a widgetGroup");const c=oe(t,n,a);if(!c)throw new Error(`Widget "${a}" not found in recipe "${t}"`);const d=c.state,l=(d.settings||[]).find((t=>t.variableName===e));if(!l)throw new Error(`Field "${e}" not found in widgetGroup "${d.name}"`);const u=l.config.defaultValue;if(!u)throw new Error(`Field "${e}" in widgetGroup "${d.name}" has no default value`);return{value:u,type:Fe(u)}}}},Pr="__command-compile__";let Or;const Tr=()=>{throw new Error("Method not implemented")},Lr=(e,t,n)=>{const i=(e,...n)=>{const r={...dr(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},s={};return Object.keys(fe).forEach((e=>{s[e]=fe[e]})),{logger:jr(),dataTypesEnum:s,notify:{success:e=>{t.getState()?.$$managedUI?.notify?.success(e)},error:e=>{t.getState()?.$$managedUI?.notify?.error(e)},info:e=>{t.getState()?.$$managedUI?.notify?.info(e)}},variablesManager:e.variablesManager?Nr({recipePoolId:n.recipePoolId,scriptWidgetId:n.widgetId,thingId:n.thingId,getState:t.getState,setState:t.setState}):{get:Tr,set:async()=>Tr(),onValueChange:Tr,onUIValueChange:Tr,getUIValue:Tr},setTimeout:(n,i,s)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=r(),o={...dr(),...t.getState()};o.$$eventListeners[e]={handler:n,rejectHandler:s,name:xr},t.setState(o),t.registerInterrupt("timeout",e,{timeout:i},void 0,e)}},addEventListener:(e,n)=>{if(t.setState){const s=r(),o={...dr(),...t.getState()};o.$$eventListeners[s]={handler:n,name:e},t.setState(o),window.addEventListener(e,i.bind(s))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,n)=>{if(t.setState){const r={...dr(),...t.getState()},i=Object.keys(r.$$eventListeners).find((t=>r.$$eventListeners[t].name===e&&r.$$eventListeners[t].handler===n));t.setState(r),i&&removeEventListener(r.$$eventListeners[i].name,r.$$eventListeners[i].handler)}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)}}},Br=(e,t,n)=>{const r={...dr(),...n.getState()},i=r.pages[sr].$$compiledCode;if(i)return{compiledModule:i};{const i=Lr(e,n,t);return ir(r.pages[sr].code,i,n.recipeType)}},Dr=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),jr=()=>{const e=(e,...t)=>{if(Or)try{return Or[e](...t)}catch(e){return void console.log("Error in custom logger: ",e)}console[e](...t)};return{log:(...t)=>{e("log",...t)},error:(...t)=>{e("error",...t)},warn:(...t)=>{e("warn",...t)},info:(...t)=>{e("info",...t)}}},Ur=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===xr){const e=n[r]?.rejectHandler;if("function"==typeof e)try{await e("TIMER_ABORTED")}catch(e){console.log("Error in reject interrupt handler: ",e)}t.cancelInterrupt(r),delete n[r]}}return n},Rr=async e=>{const t={...e};for(const n in e){if(e[n].name===Ar){const r=e[n]?.abort;if("function"==typeof r)try{await r()}catch(e){console.log("Error in abort interrupt handler: ",e)}delete t[n]}}return t},Fr=async(e,t,n)=>{let r={...dr(),...e.getState()};if(void 0!==n){r.pages[sr]?.$$compiledCode?.onTerminate&&await(r.pages[sr].$$compiledCode?.onTerminate());let t=await Ur(r.$$eventListeners,e);t=await Rr(t),r.$$eventListeners=t,r.pages[sr].$$compiledCode=void 0,r.pages[sr].code=n,e.setState({...r})}const i=!r.pages[sr].$$compiledCode,{compiledModule:s,error:o}=Br({variablesManager:!0,withTimers:!0},{recipePoolId:e.recipePoolId,thingId:e.thingRecipeId,widgetId:e.id},{getState:e.getState,setState:e.setState,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt});if(o){console.log("Failed to compile user code");const t=lr(o,e.recipeType);return ur(t,e),null}if(s){let n;r={...e.getState()},r.pages[sr].$$compiledCode=s;const o=Wr(r.pages[sr].code);o?.name===r.metadata?.name&&o?.description===r.metadata?.description||(r.metadata=o||void 0);const a=e.nextWidget||e.nextGate;if(a&&s.setSendToPortFun(a),t)try{await s.recipeInit({setState:e.setState,getState:e.getState})}catch(t){n=lr(t,e.recipeType)}if(a&&i)try{await s.main(a)}catch(t){n=lr(t,e.recipeType)}r.$$lastInputs=s.getWidgetInputs?s.getWidgetInputs():[],r.$$lastOutputs=s.getWidgetOutputs?s.getWidgetOutputs():[],e.setState(r),ur(n,e)}};var Mr={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...dr(),...i};if(!s.pages[sr])return console.warn("Missing default page");if(De(e?.name||""))return s.$$eventListeners[t.name]?(await s.$$eventListeners[t.name].handler(),s.$$eventListeners[t.name].name===xr&&delete s.$$eventListeners[t.name],void r.setState({...s})):void console.log(`Unknown interrupt id [${t.name}] `);const o=t.name===Pr;await Fr(r,!1,o?n.data.value:void 0);const a=s.pages[sr].$$compiledCode;if(e&&e.name!==Pr&&a)try{await a.asyncProcessEvent(t,e,n)}catch(e){if("UserCodeError"===e.name){const t=lr(e,r.recipeType);throw ur(t,r),t}throw e}},getInputNames:(e,t)=>{const n={...dr(),...e},{compiledModule:r}=Br({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return Dr(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...dr(),...e},{compiledModule:r}=Br({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return Dr(e)}return e.$$lastOutputs||[]},getDefaultState:dr,initialize:async e=>{const t=e.getState(),n={...dr(),...t};n.pages[sr].code&&await Fr({getState:e.getState,id:e.widgetId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,nextWidget:e.nextWidget,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[sr].code)},terminate:async e=>{try{const t=e.getState();t.pages[sr].$$compiledCode?.onTerminate&&await t.pages[sr].$$compiledCode.onTerminate();const n=e=>Xe.destroyInterrupt(e),r=await Ur(t.$$eventListeners,{cancelInterrupt:n});await Rr(r)}catch(t){console.warn(`Error terminating script widget ${e.widgetId}: `,t)}}};const Wr=e=>{const t=e.trimStart().match(/^(?:\/\*\*(?:[^*]|\*(?!\/))*\*\/|\/\*(?:[^*]|\*(?!\/))*\*\/)/);if(!t)return null;const n=t[0].replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map((e=>e.replace(/^\s*\*?\s?/,"").trim())).join("\n"),r=n.match(/Name\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),i=n.match(/Description\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),s={};return r&&r[1]&&(s.name=r[1].trim()),i&&i[1]&&(s.description=i[1].trim()),Object.keys(s).length>0?s:null},Gr=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const i=await Vr(e);return((e,t,n,r)=>{const i=r.getContext("2d");if(!i)throw new Error("Failed to get canvas context");const s=e.width,o=e.height;return r.width=t,r.height=n,i.drawImage(e,0,0,s,o,0,0,t,n),i.getImageData(0,0,t,n)})(i,n||i.naturalWidth,r||i.naturalHeight,t)},Vr=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),Hr=Object.freeze({image:"image"}),zr=Object.freeze({base64:"base64"}),qr=()=>({});var Kr={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===zr.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==fe.String&&n.data.type!==fe.Anything)return;const e=n.data.value;Z&&(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240)));try{const t=await Gr(e,i.$$memCanvas,i.resize?.width,i.resize?.height);return r.setState(i),r.nextGate(Hr.image,{type:fe.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:zr.base64,type:fe.String}],getOutputNames:()=>[{name:Hr.image,type:fe.ImageData}],getDefaultState:qr};const Jr=Object.freeze({object:"object",error:"error"}),Yr=Object.freeze({string:"string"}),Xr=()=>({outputIsArray:!1});var Zr={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===fe.String||n.data.type===fe.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!i.outputIsArray?r.setState({...i,outputIsArray:!0}):!t&&i.outputIsArray&&r.setState({...i,outputIsArray:!1}),r.nextGate("object",{type:t?fe.Array:fe.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:fe.Boolean,value:!0})}},getInputNames:()=>[{name:Yr.string,type:fe.String}],getOutputNames:e=>[{name:Jr.object,type:[fe.JsonObj,fe.Array],label:e.outputIsArray?"array":Jr.object},{name:Jr.error,type:fe.Boolean}],getDefaultState:Xr};const Qr=Object.freeze({string:"string",length:"length"}),ei=Object.freeze({trigger:"trigger",setText:"setText"}),ti=()=>({text:"",dispatchOnSet:!1});var ni={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===ei.setText){if(!((n.data.type===fe.String||n.data.type===fe.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(i.text=n.data.value,r.setState(i)),!i.dispatchOnSet)return}const s=r.nextGate(Qr.length,{type:fe.Number,value:i.text.length}),o=r.nextGate(Qr.string,{type:fe.String,value:i.text});await Promise.all([s,o])},getInputNames:e=>{const t=[{name:ei.setText,type:fe.String}];return e.dispatchOnSet||t.push({name:ei.trigger,type:fe.Anything}),t},getOutputNames:()=>[{name:Qr.string,type:fe.String},{name:Qr.length,type:fe.Number}],getDefaultState:ti};const ri=Object.freeze({image:"image"}),ii=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),si=()=>({showInputPorts:!1});var oi={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===ii.x&&(i.cropX=n.data.value),t.name===ii.y&&(i.cropY=n.data.value),t.name===ii.width&&(i.cropWidth=n.data.value),t.name===ii.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===ii.image){if(n.data.type!==fe.ImageData&&n.data.type!==fe.Anything)return;if(!je(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$memCanvasContext=ke(i.$$memCanvas),r.setState(i)),!i.$$memCanvas||!i.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return i.$$memCanvas.width=e.width,i.$$memCanvas.height=e.height,(i.cropX||i.cropY||i.cropWidth||i.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const i=Math.max(r.x||0,0),s=Math.max(r.y||0,0),o=e.width,a=e.height,c=Math.min(Math.ceil(r.width||o),o),d=Math.min(Math.ceil(r.height||a),a);return t.width=e.width,t.height=e.height,n.putImageData(e,0,0),n.drawImage(t,i,s,c,d,0,0,c,d),n.getImageData(0,0,c,d)})(e,i.$$memCanvas,i.$$memCanvasContext,{x:i.cropX,y:i.cropY,width:i.cropWidth,height:i.cropHeight})),r.nextGate(ri.image,{type:fe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:ii.image,type:[fe.ImageData]}];return e.showInputPorts&&(t.push({name:ii.x,type:fe.Number}),t.push({name:ii.y,type:fe.Number}),t.push({name:ii.width,type:fe.Number}),t.push({name:ii.height,type:fe.Number})),t},getOutputNames:()=>[{name:ri.image,type:fe.ImageData}],getDefaultState:si};const ai=Object.freeze({image:"image"}),ci=Object.freeze({image:"image",width:"width",height:"height"}),di=()=>({showInputPorts:!1});var li={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===ci.width&&(i.width=n.data.value),t.name===ci.height&&(i.height=n.data.value),void r.setState(i);if(t.name===ci.image){if(n.data.type!==fe.ImageData&&n.data.type!==fe.Anything)return;if(!je(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$tempCanvas=Ce(320,240),r.setState(i)),!i.$$memCanvas||!i.$$tempCanvas)return;let t=e;return(i.width||i.height)&&(t=((e,t,n,r,i)=>{if(!r&&!i)return e;r&&!i?i=r*(e.height/e.width):!r&&i&&(r=i*(e.width/e.height));const s=Math.max(1,r||e.width),o=Math.max(1,i||e.height);n.width===e.width&&n.height===e.height||(n.width=e.width,n.height=e.height),t.width=s,t.height=o;const a=ke(t),c=ke(n);if(!a||!c)throw new Error("Failed to get canvas context");return c.putImageData(e,0,0),a.drawImage(n,0,0,e.width,e.height,0,0,s,o),a.getImageData(0,0,s,o)})(e,i.$$memCanvas,i.$$tempCanvas,i.width,i.height)),r.nextGate(ai.image,{type:fe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:ci.image,type:fe.ImageData}];return e.showInputPorts&&(t.push({name:ci.width,type:fe.Number}),t.push({name:ci.height,type:fe.Number})),t},getOutputNames:()=>[{name:ai.image,type:fe.ImageData}],getDefaultState:di};const ui=Object.freeze({value:"value"}),pi=Object.freeze({trigger:"trigger",setValue:"setValue"}),gi=()=>({value:0,dispatchOnSet:!1});var hi={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===pi.setValue){const e=n.data.type===fe.Number||n.data.type===fe.Anything||n.data.type===fe.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(i.value=Number(n.data.value),r.setState(i),!i.dispatchOnSet)return}return r.nextGate(ui.value,{type:fe.Number,value:i.value})},getInputNames:e=>{const t=[{name:pi.setValue,type:fe.Number}];return e.dispatchOnSet||t.push({name:pi.trigger,type:fe.Anything}),t},getOutputNames:()=>[{name:ui.value,type:fe.Number}],getDefaultState:gi};const fi=Object.freeze({image:"image"}),mi=Object.freeze({image:"image"}),yi=()=>({anchors:[],vertices:[],matrix:[]}),vi={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},s=window,o=n.data.type===fe.ImageData;if(s.Speedy&&o){const e=s.Speedy,t=n.data.value;let o,l,u,p=i.$$private?.canvas,g=i.$$private?.context,h={...i};const f=4===i.anchors.length;if(i.$$private?.pipeline)o=i.$$private?.pipeline,l=i.$$private?.source;else{o=e.Pipeline(),l=e.Image.Source();const n=e.Image.Sink();u=e.Transform.PerspectiveWarp(),p?p.width===t.width&&p.height===t.height||(p.width=t.width,p.height=t.height,g=p.getContext("2d")):(c=t.width,d=t.height,p=Ce(c,d),g=p.getContext("2d")),l.output().connectTo(u.input()),u.output().connectTo(n.input()),o.init(l,n,u);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===i.anchors.length){const t=e.Matrix(2,4,[(a=i.anchors)[0].x,a[0].y,a[1].x,a[1].y,a[2].x,a[2].y,a[3].x,a[3].y]),n=e.Matrix(2,4,i.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),s=e.Matrix.Zeros(3,3);await e.Matrix.perspective(s,t,n);const o=s.read();r=e.Matrix(3,3,o)}u.transform=r,h={...h,$$private:{...h.$$private,canvas:p,context:g,perspective:u,pipeline:o,source:l}}}let m=t;if(f){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,i=e.$$private?.pipeline;if(n.Speedy&&r&&i){const e=n.Speedy,s=await createImageBitmap(t),o=await e.load(s);return r.media=o,(await i.run()).image.source}return null})(h,m);e&&(p&&g&&(m=((e,t,n)=>(t.width=e.width,t.height=e.height,n.drawImage(e,0,0),n.getImageData(0,0,e.width,e.height)))(e,p,g)),h.$$private&&r.setState({...h,$$private:{...h.$$private,lastInputImage:t}}))}else h.$$private&&r.setState({...h,$$private:{...h.$$private,lastInputImage:t}});return r.nextGate(fi.image,{type:fe.ImageData,value:m})}var a,c,d;console.log("Environment not supported")},getInputNames:()=>[{name:mi.image,type:fe.ImageData}],getOutputNames:()=>[{name:fi.image,type:fe.ImageData}],getDefaultState:yi,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},bi=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[fe.Anything],name:"input"}],outputs:[{dataType:[fe.Anything],name:"output"}]});let Si;const wi=()=>{if(!Si)throw new Error(tt(et));return Si};const Ii=async e=>{const t=new a,n=await t.loadAsync(e),r={};for(const e in n.files)if(!n.files[e].dir){const t=await n.file(e);t&&(r[e]=await t.async("uint8array"))}return r},_i={};var $i=e=>_i[e]||null;const Ci=async(e,t,n)=>{try{const r=wi(),i=n?r.loadBlobAsString:r.loadBlob;return await i(e,t)}catch(e){return null}},ki=async e=>{const t=de;try{const n=await Ci(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},Ei=async e=>{const t=le;try{const n=await Ci(e,t,!0);if(!n)return null;return JSON.parse(n)}catch(n){return console.log(`Failed to parse the bundle's state [${e}/${t}] %j`,n),null}},xi=(e,t)=>`${e.replace(ue,"")}_${t}`,Ai=(e,t)=>`widget/${e.replace(ue,"")}/v/${t}`,Ni=async(e,t)=>{const n=wi(),[r]=await Promise.all([Ii(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},Pi=(e,t)=>{const n=xi(e,t),r=$i(n);return r?{...r}:null},Oi=(e,t,n)=>{const r=`${`widget/${e.replace(ue,"")}/tmp`}/${t}`;if(n){return wi().getCacheLocation(r)}return r};var Ti=Pi,Li=async(e,t,n)=>{const r=Oi(t,n);await Ni(e,r);const i=ki(r),s=Ei(r),o=wi(),a=o.getCacheLocation(r),[c,d]=await Promise.all([i,s]);if(!c)return null;let l=d;if(!d){const e=bi(),t=JSON.stringify(e);await o.saveBlob(r,le,Be(t)),l=e}return{cachePath:a,processor:c,storedState:Object.freeze(l)}},Bi=(e,t,n)=>{if(n.isTempStorage)return Oi(e,t,n.fullStorageRoot);const r=wi(),i=Ai(e,t);return n.fullStorageRoot?r.getCacheLocation(i):i};const Di=()=>bi();var ji={onParentEvent:async(e,t,n,r)=>{const i=r.getState();return i.$$processor?.onParentEvent({sourcePort:e?.name||"",targetPort:t?.name||"",data:n.data},{getState:r.getState,recipeId:r.recipePoolId,recipeType:r.recipeType,setState:r.setState,nextWidget:r.nextGate})},getInputNames:(e,t)=>{const n={...Di(),...e};return n.$$processor?.getInputNames?n.$$processor.getInputNames(e,t):n.inputs.map((e=>({name:e.name,type:e.dataType})))},getOutputNames:(e,t)=>{const n={...Di(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:Di,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetId;const i=n.$$cacheInfo?.version.toString()||n.collectionInfo?.version.toString()||1;if(n.$$cacheInfo={...n.$$cacheInfo,version:Number(i),widgetThingId:r},!r||!i)throw new Error("Widget bundle state is missing cache id or version");console.log("Loading state from cache");const s=Ti(r,i);let o=!s;if(!n.$$processor)if(n.storageUnitId&&!s){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetId;const s=await Li(t,r,i);o=!0,s&&(n={...n,$$processor:s.processor,$$cacheInfo:{...n.$$cacheInfo,widgetThingId:r,version:Number(i)}},e.setState(n))}}else if(s){o=!1;const r=n.collectionInfo?{...n.collectionInfo}:void 0;n={...n,...!t.keepCurrentState&&s.storedState?{...s.storedState,...r?{collectionInfo:r}:{}}:{},$$processor:s.processor},e.setState(n)}const a=Bi(r,i,{fullStorageRoot:!0,isTempStorage:o});console.log("Invoking bundle initialize with cache: ",a);try{await(n.$$processor?.initialize({cacheLocation:a,getState:e.getState,setState:e.setState}));const t=e.getState();e.setState({...t,$$initializationError:void 0})}catch(t){const n=e.getState();throw e.setState({...n,$$initializationError:t.message||"An error occurred initializing the widget"}),t}},terminate:async e=>{const t={...e.getState()};console.log(`Terminating widget bundle ${t.name} [${t.$$cacheInfo?.widgetThingId||""}]`);const n=t.$$processor;n&&"function"==typeof n.terminate&&await n.terminate({getState:e.getState,setState:e.setState,recipePoolId:e.recipePoolId,widgetId:e.widgetId})}};const Ui=Object.freeze({event:"event"}),Ri="1",Fi="2",Mi="3";var Wi={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate(Ri,n.data),await r.nextGate(Fi,n.data),await r.nextGate(Mi,n.data)},getInputNames:()=>[{name:Ui.event,type:fe.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??fe.Anything};return[{name:Ri,...t},{name:Fi,...t},{name:Mi,...t}]}};const Gi=()=>({name:"myVar",type:fe.Anything,reactive:!0,defaultValue:""}),Vi=Object.freeze({set:"set",read:"read"}),Hi="value";var zi={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Gi(),...i};if(t.name!==Vi.set){if(t.name===Vi.read){const e=$r({variableName:s.name,readerWidgetId:r.id}),t=e?e.value:s.defaultValue;await r.nextWidget(Hi,{type:s.type,value:t})}}else{if(n.data.type!==s.type&&s.type!==fe.Anything)return;await _r({variableName:s.name,value:n.data.value,setByWidgetId:r.id,type:s.type})}},getInputNames:e=>{const t={...e};return[{name:Vi.set,type:t.type||fe.Anything},{name:Vi.read,type:fe.Anything}]},getOutputNames:e=>{const t={...e};return[{name:Hi,type:t.type||fe.Anything}]},initialize:async e=>{const t=e.getState(),n={...Gi(),...t};if(n.$$abortListener)try{n.$$abortListener()}catch(t){console.warn(`Error aborting variable listener for widget ${e.widgetId}: `,t)}wr({variableName:n.name,type:n.type,createdByWidgetId:e.widgetId});const r=Cr({variableName:n.name,type:n.type,widgetId:e.widgetId,onValueChange:async t=>{const n=e.getState();void 0!==t.value&&(n.type!==fe.Anything&&t.type!==n.type||n.reactive&&await e.nextWidget(Hi,{type:t.type,value:t.value}))}});e.setState({...n,$$abortListener:r})},terminate:async e=>{const t=e.getState(),n={...Gi(),...t};n.$$abortListener&&n.$$abortListener(),Ir({variableName:n.name,createdByWidgetId:e.widgetId})}};let qi;var Ki=e=>{qi=e},Ji=()=>{if(!qi)throw new Error("Hub Connector not set");return qi};const Yi=e=>{const t=ie(e);return t?.name||""},Xi=async(e,t=!1)=>{const n=Ji();let r=e.$$$serviceId;if(!e.service)return console.log("Aborting service initialization, missing property `service` in state."),null;if(!r||t){const t=await n.getCompatibleService(e.service.name,e.service.version,"^");if(!t)return null;r=t.sessionId}return r};var Zi={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const s=Ji();let o=i.$$$serviceId;if(!o){const e=s.getCachedServices().available.find((e=>e.name===i.service?.name&&e.version===i.service?.version));if(!e)return;o=e.sessionId,i.$$$serviceId=o,r.setState(i)}const a=i.service?.variants?.find((e=>e.id===i.variantId)),c=a?i.dynamicInputs[a.id]||a?.inputs||[]:i.service?.inputs||[];if(!c?.length)return;if(!a&&i.service?.ignoreParentEvents)return;const d=i.service?.processingTimeoutSec,l=i.service?.name&&r.eventContext?.[i.service?.name];return s.onParentEvent({recipeId:r.recipePoolId,recipeName:Yi(r.recipePoolId),data:n.data,targetServiceSessionId:o,currentState:i.customState,targetVariantId:i.variantId,target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:d?1e3*d:0,async:i.service?.asyncParentEvents},eventContext:l})},getInputNames:async e=>{const t=e.variantId;if(t&&e.dynamicInputs?.[t])return[...e.dynamicInputs[t]||[]];if(!t)return e.service?.inputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.inputs||[]}return[]},getOutputNames:async e=>{const t=e.variantId;if(t&&e.dynamicOutputs?.[t])return[...e.dynamicOutputs[t]||[]];if(!t)return e.service?.outputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.outputs||[]}return[]},initialize:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=ie(e.recipePoolId),r=n?.name||"",i=Ji(),s=await Xi(t);if(s)try{return await i.initializeServiceInstance({recipeId:e.recipePoolId,sessionId:s,recipeName:r,widgetId:e.widgetId,recipeType:e.recipeType,variantId:t.variantId})}catch(t){if("FNC_NOT_FOUND"!==t?.errCode){if(!!("string"!=typeof t||!t.match('^Function ".*" not found.$')))throw t;console.warn(`Widget [${e.widgetId}] does not have an init function.`)}}else console.log(`Aborting service initialization, "${t.service?.name}" was not found in the current Hub.`)},terminate:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=Ji(),r=await Xi(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const Qi=Object.freeze({Image:"image"}),es=Object.freeze({Image:"image"}),ts=()=>({filters:[{name:"grayscale",value:"0.5",id:"d-1"}]});var ns={onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:"0.5",id:"d-1"}],...r.getState()};if(t.name===Qi.Image&&n.data.type===fe.ImageData){if(!je(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas?.getContext||(i.$$memCanvas=Ce(e.width,e.height)),i.$$context?.drawImage||(i.$$context=i.$$memCanvas.getContext("2d")),i.$$memCanvas.width!==e.width&&(i.$$memCanvas.width=e.width),i.$$memCanvas.height!==e.height&&(i.$$memCanvas.height=e.height),r.setState(i),i.$$context.putImageData(e,0,0),i.filters.length?i.$$context.filter=i.filters.map((e=>{let t="";return"blur"===e.name?t="px":"hue-rotate"===e.name&&(t="deg"),`${e.name}(${parseFloat(e.value)}${t})`})).join(" "):i.$$context.filter="none",i.$$context.drawImage(i.$$memCanvas,0,0);const t=i.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(es.Image,{type:fe.ImageData,value:t})}},getInputNames:()=>[{name:Qi.Image,type:fe.ImageData}],getOutputNames:()=>[{name:es.Image,type:fe.ImageData}],getDefaultState:ts};const rs="loaded";var is={onParentEvent:async(e,t,n,r)=>r.nextWidget(rs,{value:!0,type:fe.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:rs,type:fe.Boolean,description:"Triggered when the recipe is fully loaded"}]};var ss={onParentEvent:async()=>{},getInputNames:()=>[],getOutputNames:()=>[],getDefaultState:()=>({text:"",color:"#eac43e",size:{width:300,height:200}})};var os={onParentEvent:async(e,t,n,r)=>{try{const e=((e,t)=>{switch(t){case fe.Number:case fe.Boolean:case fe.String:return String(e);case fe.Array:case fe.JsonObj:case fe.Rect:case fe.Point:return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));case fe.ArrayBuffer:if(e instanceof ArrayBuffer){if(ee)return Buffer.from(e).toString("base64");{const t=new Uint8Array(e),n=t.length,r=new Array(n);for(let e=0;e<n;e++)r[e]=String.fromCharCode(t[e]);return btoa(r.join(""))}}throw new Error("Type is ArrayBuffer but value is not an ArrayBuffer");case fe.ImageData:{if(!je(e))throw new Error("Expected ImageData");const t=e,n=Ce(t.width,t.height),r=ke(n);if(!r)throw new Error("Failed to get canvas context");r.putImageData(t,0,0);const i=n.toDataURL("image/png");if(!i)throw new Error("Failed to convert canvas to data URL");return i.split(",")[1]}default:return String(e)}})(n.data.value,n.data.type);return r.nextWidget("text",{type:fe.String,value:e})}catch(e){return r.nextWidget("error",{type:fe.String,value:e instanceof Error?e.message:"Failed to stringify object"})}},getInputNames:()=>[{name:"object",type:[fe.Number,fe.String,fe.ArrayBuffer,fe.Array,fe.Boolean,fe.JsonObj,fe.Rect,fe.Point,fe.ImageData]}],getOutputNames:()=>[{name:"text",type:fe.String},{name:"error",type:fe.String}],getDefaultState:()=>({})};const as=e=>{if(Array.isArray(e))return e.map(((e,t,n)=>null===e||"object"!=typeof e?{value:e,"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}:{...as(e),"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}));if("object"==typeof e&&null!==e){const t={};for(const n in e){const r=e[n];t[n]=as(r)}return t}return e},cs=(e,t)=>{const n=(e=>{const t=new Date;return{input:"object"==typeof e&&null!==e?as(e):{value:e},date:{year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hours:t.getHours(),minutes:t.getMinutes(),seconds:t.getSeconds(),milliseconds:t.getMilliseconds(),time:t.getTime(),dayOfWeek:t.getDay(),dayName:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()],shortDayName:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getDay()],date:t.getDate(),fullYear:t.getFullYear(),timezoneOffset:t.getTimezoneOffset(),UTCDate:t.getUTCDate(),UTCDay:t.getUTCDay(),UTCFullYear:t.getUTCFullYear(),UTCHours:t.getUTCHours(),UTCMilliseconds:t.getUTCMilliseconds(),UTCMonth:t.getUTCMonth()+1,UTCMinutes:t.getUTCMinutes(),UTCSeconds:t.getUTCSeconds(),isoString:t.toISOString(),localeString:t.toLocaleString()}}})(t);return d.render(e,n)},ds=()=>({text:"",format:"Text"});var ls={onParentEvent:async(e,t,n,r)=>{const i={text:"",format:"Text",...r.getState()},s=cs(i.text,n.data.value);return r.nextWidget("text",{type:fe.String,value:s})},getInputNames:()=>[{name:"input",type:fe.Anything}],getOutputNames:()=>[{name:"text",type:fe.String}],getDefaultState:ds};const us=()=>({expression:""});var ps={onParentEvent:async(e,t,n,r)=>{const i={expression:"",...r.getState()},s=((e,t)=>{const n=Symbol("error"),r=`\n // 'data' is an argument to this function, passed by new Function call.\n // 'SError' is also an argument, providing the error symbol.\n // 'this' inside this function (created by new Function) is the global object.\n\n\t\t// Shadow eval and Function in this non-strict scope.\n\t\tvar eval = undefined;\n\t\tvar Function = undefined;\n\n // Define the sandbox environment\n const sandboxEnvironment = {\n // Make input 'data' accessible\n data: data,\n \n // Safe console (bind methods to the original console)\n console: undefined,\n\n // Mocked/disabled globals\n process: undefined,\n document: undefined,\n navigator: undefined,\n \n require: undefined,\n // eval and Function are shadowed by var declarations above\n \n // Allowed safe globals (pointing to the real ones, accessed via 'this')\n Math: this.Math,\n Date: this.Date,\n JSON: this.JSON,\n Array: this.Array,\n Object: this.Object,\n String: this.String,\n Number: this.Number,\n Boolean: this.Boolean,\n RegExp: this.RegExp,\n // Error: this.Error, // Not Allow Error constructor\n Symbol: this.Symbol, // Allow Symbol constructor\n Map: this.Map,\n Set: this.Set,\n Promise: this.Promise, // Allow Promise if async expressions are intended\n // setTimeout, setInterval, fetch, etc., are deliberately omitted\n };\n\n // Assign the sandboxEnvironment to act as the 'global' context variables\n const global = sandboxEnvironment;\n const window = sandboxEnvironment;\n const globalThis = sandboxEnvironment;\n\n // Shadow top-level variables that might be accessed directly,\n // ensuring they use the sandboxed versions.\n const process = sandboxEnvironment.process;\n const document = sandboxEnvironment.document;\n const navigator = sandboxEnvironment.navigator;\n const console = sandboxEnvironment.console; // Use the sandboxed console for the expression\n const require = sandboxEnvironment.require;\n // 'eval' and 'Function' are already shadowed by var declarations\n\n // The expression will be evaluated in this scope.\n // 'data' is available as it's an argument to the outer function.\n // 'global.xxx' will resolve to 'sandboxEnvironment.xxx'.\n // 'process.yyy' will resolve to 'sandboxEnvironment.process.yyy'.\n \n return () => {\n "use strict"; // Apply strict mode only to the expression evaluation scope\n const abort = Symbol('abort'); // Local symbol for the expression's optional special return value\n\n let result;\n try {\n // Strict mode can add a layer of security and prevent some common errors.\n // It also changes 'this' binding within the expression if it uses 'this'.\n // If the expression uses 'this', under strict mode it would be undefined unless explicitly set.\n // For expressions not using 'this', strict mode is generally safer.\n result = (() => { return ${t}; })();\n } catch(e) {\n // Log the error using the sandboxed console\n // Use 'instanceof Error' to ensure 'e' has a message property.\n const errorMessage = e instanceof Error ? e.message : String(e);\n return {\n\t\t\t\t\terror: 'Error during expression execution: ' + errorMessage, \n\t\t\t\t\tvalue: null\n\t\t\t\t}; // Return the SError symbol passed into this function's scope\n }\n \n\t\t\t// allows ternary expressions that return 'abort' to cancel the evaluation\n if (result !== abort) {\n // Original logic: if result is strictly true, and expression wasn't literally "true", return original data.\n if (result === true && String(expression).trim() !== 'true') {\n return {value: data, error: null}; \n } else {\n return {value: result, error: null};\n }\n }\n \n // If the expression explicitly returned the 'abort' symbol\n return {value: abort, error: null}; \n }\n // End of functionBody template literal\n `;try{return new Function("data","SError",r)(e,n).call({})}catch(e){return{error:e.message,value:null}}})(n.data.value,i.expression);if("symbol"==typeof s.value)return;if(s.error)throw new Error(s.error);if(Number.isNaN(s.value))throw new Error("Expression resulted in NaN");if(void 0===s.value||null===s.value)return;const o=Fe(s.value);return o!==i.$$lastResultType&&r.setState({...i,$$lastResultType:o}),r.nextWidget("result",{type:o,value:s.value})},getInputNames:()=>[{name:"data",type:fe.Anything}],getOutputNames:e=>[{name:"result",type:e.$$lastResultType||fe.Anything}],getDefaultState:us};var gs={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type});try{await r.nextWidget("event",n.data)}catch(e){const t=e;await r.nextWidget("error",{type:fe.JsonObj,value:{error:{message:e.message,targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType,stack:e.stack},inputEvent:{type:n.data.type,data:n.data.value}}})}},getInputNames:()=>[{name:"event",type:fe.Anything}],getOutputNames:e=>[{name:"event",type:{...e}.$$lastEventType??fe.Anything},{name:"error",type:fe.JsonObj,jsonShape:{error:fe.JsonObj,inputEvent:fe.JsonObj}}]};const hs={},fs=Object.freeze({output:"output"}),ms=Object.freeze({read:"read",clear:"clear"}),ys=()=>({$$$time:0,totalInputs:1});var vs={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalInputs:1,...r.getState()};if(hs[r.id]||(hs[r.id]={}),t.name===ms.clear)return hs[r.id]={},void r.setState(i);const s=t.name===ms.read;if(!(s||n.data.type!==fe.JsonObj&&n.data.type!==fe.Anything&&n.data.type!==fe.Rect||"object"!=typeof n.data.value||null===n.data.value||Array.isArray(n.data.value))){const e=hs[r.id]||{};hs[r.id]={...e,...n.data.value}}if(s){const e={...hs[r.id]};return hs[r.id]={},r.setState({...i}),r.nextWidget(fs.output,{type:fe.JsonObj,value:e})}},getInputNames:e=>{const t={$$$time:0,totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:ms.clear,type:fe.Anything},{name:ms.read,type:fe.Anything,triggerPort:!0}),n},getOutputNames:()=>[{name:fs.output,type:fe.JsonObj}],getDefaultState:ys,initialize:async e=>{hs[e.widgetId]={}},terminate:async e=>{delete hs[e.widgetId]}};const bs={},Ss=Object.freeze({output:"output",index:"index",finish:"finish"}),ws=Object.freeze({array:"array",next:"next",clear:"clear"}),Is=()=>({autoLoop:!1,autoClear:!1,$$outputType:fe.Anything,totalItems:0,currentIndex:0});const _s={input:it,counter:at,elapsed:lt,ifGate:ht,skipEvent:yt,between:wt,map:$t,parser:Et,slider:Nt,suspend:Tt,display:Bt,json:Ut,arrayItem:Mt,extractImage:zt,imageConvolution:Xt,firstEvent:tn,pixelDraw:ln,randomBetween:hn,arrayCombine:bn,clock:_n,multiplication:En,object:Bn,widgetGroup:Rn,script:Mr,base64ToImageData:Kr,jsonParse:Zr,text:ni,imageCrop:oi,imageResize:li,value:hi,imageWarp:vi,widgetBundle:ji,sequence:Wi,variable:zi,hubService:Zi,imageFilter:ns,recipeLoad:is,note:ss,stringify:os,templateString:ls,expressionEval:ps,rescue:gs,objectCombine:vs,loop:{onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Is(),...i};if(t.name===ws.clear)return delete bs[r.id],void r.setState({...Is(),autoLoop:s.autoLoop,autoClear:s.autoClear});if(t.name!==ws.array)t.name===ws.next&&await(async e=>{const t=e.id,n=bs[t],r={...Is(),...e.getState()};if(n&&n.index<n.list.length){const i=n.index,s=n.list[i];await e.nextWidget(Ss.index,{type:fe.Number,value:i}),await e.nextWidget(Ss.output,{type:r.$$outputType,value:s}),n.index++,e.setState({...r,currentIndex:n.index}),n.index===n.list.length&&(await e.nextWidget(Ss.finish,{type:fe.Boolean,value:!0}),r.autoClear?(delete bs[t],e.setState({...Is()})):(n.index=0,e.setState({...r,currentIndex:0})))}})(r);else if((n.data.type===fe.Array||n.data.type===fe.Anything)&&Array.isArray(n.data.value)){const e=n.data.value,t=e[0],i=void 0!==t?Fe(t):fe.Anything,o={list:e,index:0};bs[r.id]=o;const a={...s,$$outputType:i,totalItems:e.length,currentIndex:0};if(r.setState(a),a.autoLoop&&e.length>0){for(const t of e){const e=o.index;r.setState({...a,currentIndex:e}),await r.nextWidget(Ss.index,{type:fe.Number,value:e}),await r.nextWidget(Ss.output,{type:a.$$outputType,value:t}),o.index++}await r.nextWidget(Ss.finish,{type:fe.Boolean,value:!0}),a.autoClear?(delete bs[r.id],r.setState({...a,$$outputType:fe.Anything,totalItems:0,currentIndex:0})):(o.index=0,r.setState({...a,currentIndex:0}))}}},getInputNames:()=>[{name:ws.array,type:fe.Array},{name:ws.next,type:fe.Anything},{name:ws.clear,type:fe.Anything}],getOutputNames:e=>{const t={...Is(),...e};return[{name:Ss.index,type:fe.Number},{name:Ss.output,type:t.$$outputType},{name:Ss.finish,type:fe.Anything}]},getDefaultState:Is,initialize:async e=>{const t={...Is(),...e.getState()};bs[e.widgetId]={list:[],index:0},e.setState({...t,currentIndex:0,totalItems:0})},terminate:async e=>{delete bs[e.widgetId]}},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:fe.Boolean}]}},$s={},Cs=async()=>{if(!Object.keys($s).length)for(const e in _s){const t=_s[e];$s[e]=Object.freeze({...t})}};var ks=e=>{if($s[e])return $s[e];throw new Error(tt(Qe,e))},Es=Cs;const xs=new o,As="invoked";let Ns={},Ps={},Os={},Ts={};const Ls=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var Bs=(e,t,n,r,i)=>{const s=Ls(e,t,n),o=Ls(e,t),a=Ls(e,t,"produced"),c=Os[o],d=Date.now();Ts[o]=d,Ns[s]={data:r,sourcePortName:n,...i?{target:{widgetId:i.widgetId,portName:i.portName}}:{}},xs.emit(a,{currentTime:d,prevTime:c,...i?{targetPort:i?.portName}:{}})},Ds=(e,t,n,r,i)=>{const s=Ls(e,t,n),o=Ls(e,t),a=Ls(e,t,As),c=Os[o],d=Date.now();Os[o]=d,Ps[s]={data:r,sourcePortName:n,...i?{source:{widgetId:i.widgetId,portName:i.portName}}:{}},xs.emit(a,{prevTime:c,currentTime:d,targetPort:n,sourceInfo:i})},js=()=>{Ns={},Ps={},Os={},Ts={},xs.clearListeners()};const Us={};let Rs={};const Fs=new o;let Ms=!1,Ws=!1,Gs=!1,Vs=null,Hs=null;const zs="processing-state-change",qs="error-event",Ks={abortRequested:!1,isPaused:!1,pausePromise:null,pausePromiseResolve:null,lastPausedWidgetId:null},Js=e=>(Hs=e,Fs.emit(zs,e)),Ys=(e,t)=>`${e}-${t}`,Xs=(e,t)=>`state-change:${Ys(e,t)}`,Zs=e=>{const{thingId:t,widgetId:n}=e,r=Ys(t,n);return Us[r]||{isProcessing:!1}},Qs=()=>{Ks.abortRequested=!1,Ks.isPaused=!1},eo=e=>(Ks.pausePromise||(Ks.isPaused=!0,Ks.pausePromise=new Promise((e=>{Ks.pausePromiseResolve=e})),e&&(Ks.lastPausedWidgetId=e),Js({isProcessing:!0,isPaused:!0,...e?{pauseTrapWidgetId:e}:{}})),Ks.pausePromise);var to,no,ro=async e=>{const{thingId:t,widgetId:n}=e,r=Ys(t,n),i=Xs(t,n),s=Zs({thingId:t,widgetId:n});if(s.isProcessing)return;const o={isProcessing:!0,isPaused:!1,startTime:Date.now()};Us[r]=o,Ms||(Ms=!0,Vs=null,await Js({isProcessing:!0,isPaused:!1})),await Fs.emit(i,{thingId:t,widgetId:n,prevState:s,newState:o})},io=async e=>{const{thingId:t,widgetId:n,error:r}=e,i=Ys(t,n),s=Xs(t,n),o=Zs({thingId:t,widgetId:n}),a={isProcessing:!1,isPaused:!1,startTime:o.startTime,endTime:Date.now(),error:r};Us[i]=a,await Fs.emit(s,{thingId:t,widgetId:n,prevState:o,newState:a}),r&&(Vs=r,await Fs.emit(qs,r)),Ms&&0===Object.values(Us).filter((e=>e.isProcessing)).length&&(Ms=!1,Ws=!1,Qs(),await Js({isProcessing:!1,isPaused:!1}))},so=()=>{Ms=!1;for(const e in Us)delete Us[e];Ks.abortRequested=!1,Ks.isPaused=!1,Ks.pausePromise=null,Ks.pausePromiseResolve=null,Ks.lastPausedWidgetId=null,Fs.clearListeners()},oo=()=>Ks.abortRequested,ao=e=>{Ks.lastPausedWidgetId=e,Ks.isPaused=!0,Js({isProcessing:!0,isPaused:!0,pauseTrapWidgetId:e})},co=()=>Ws||Gs?null:Ks.pausePromise,lo=e=>Gs?null:Rs[e]??null,uo=()=>Ws,po=e=>eo(e);!function(e){e.ServiceCreationLog="service-creation-log"}(to=to||(to={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(no=no||(no={}));let go={},ho={},fo=null;const mo=(e,t)=>{const n=(()=>{if(null===fo)throw new Error("Recipe execution type not set, please set the execution type using `setRecipeExecutionType`");return fo===Gn.Desktop})();let r=n?ho[e]:void 0;return r||(r=(e=>{const{widgets:t,targetId:n,allowedTypes:r}=e;if(!t[n])return[];const i=new Set;Object.values(t).forEach((e=>{e.children?.forEach((e=>i.add(e.childId)))}));const s=Object.keys(t).filter((e=>!i.has(e))),o=s.length>0?s:Object.keys(t),a=[],c=(e,i,s)=>{if(s.has(e))return;s.add(e);const o=t[e],d=!r||r.includes(o.type),l=[...i];d&&l.push(e),e===n?a.push(l.join("/")):o.children?.forEach((e=>c(e.childId,l,s))),s.delete(e)};return o.forEach((e=>c(e,[],new Set))),[...new Set(a)]})({widgets:t,targetId:e,allowedTypes:[ze.hubService]}),n&&(ho[e]=r)),r},yo=(e,t,n)=>{mo(t,n).forEach((n=>{go[n]={eventContext:e,widgetId:t}}))},vo=(e,t)=>{const n=t[e].state,r=n.service?.name;if(!r)return[];const i=mo(e,t),s=new Map;for(const e of i){const n=e.split("/");let i="";for(let e=0;e<n.length-1;e++){i=0===e?n[e]:`${i}/${n[e]}`;const o=go[i];if(o&&!s.has(o.widgetId)){const e=t[o.widgetId].state;e.service?.name===r&&s.set(o.widgetId,{path:i,data:o,pathSegments:i.split("/").length})}}}return Array.from(s.values())},bo=()=>{go={}},So=e=>{fo=e},wo=()=>{go={},ho={}};let Io,_o,$o,Co=!1,ko=0;const Eo=async e=>{const{widgetId:t,thingId:n,recipeId:r,targetPortName:i,data:s}=e,o=se(r,n);if(!o)return;const a=o.gates[t];if(!a||a.disabled)return;const c={...s,timestamp:Date.now()},d=ks(a.type),l=Oo({gateId:t,originalEvent:c,blockRecipeId:o.recipeId,blockDbId:o.id,blockVersion:o.version,recipeId:r});if(l&&d.onParentEvent){const e={name:i};return Io&&await Io({recipeId:r,blockId:o.recipeId,gateId:t,targetPort:e.name,data:s}),d.onParentEvent(null,e,{originalEvent:c,data:{...c}},l)}},xo=async e=>{const{interruptDriven:t,childGateId:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c}=e;let{originalEvent:d,block:l}=e;if(!t&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!t&&!d)throw new Error("Missing parameter ['originalEvent']");t&&(d={timestamp:Date.now(),type:fe.Boolean,value:!0});const u=d;if("string"==typeof l){const e=se(r,l);if(!e)return;l=e}const p=l.gates[n];if(!p||p.disabled)return;const g=a.findIndex((e=>e.name===i)),h=ks(p.type),f=Oo({gateId:n,originalEvent:u,blockRecipeId:l.recipeId,blockDbId:l.id,blockVersion:l.version,recipeId:r});if(f&&h.onParentEvent&&-1!==g){Io&&await Io({recipeId:r,blockId:l.recipeId,gateId:n,targetPort:s.name,data:o,sourceGate:t?"interrupt_widget":c,sourcePort:t?ce:i});const e={name:a[g].name,type:a[g].type,...a[g].jsonShape?{jsonShape:a[g].jsonShape}:void 0};return Ds(l.recipeId,n,s.name,o,c?{widgetId:c,portName:i}:void 0),h.onParentEvent(e,s,{originalEvent:u,data:o},f)}},Ao=async e=>{const{portName:t,originalEvent:n,data:r,currentGateId:i,blockRecipeId:s,thingDbId:o,thingVersion:a,recipeId:c,eventContext:d}=e,l=ie(c);if(!l)throw new Error(`Failed to find recipe "${c}" in cache`);const u=l.dbInfo.recipeType,p=oe(c,s,i);if(!p)return;const g={...r,timestamp:n.timestamp},h=ks(p.type);let f;f=p.type===ze.input?h.getOutputNames(p.state,{thingRecipeId:s,thingDbId:o,thingVersion:a,id:i,recipeId:c,recipeType:u,recipePoolId:c}):await h.getOutputNames(p.state,{recipePoolId:c,recipeType:u,thingRecipeId:s,widgetId:i});const m=f.findIndex((e=>e.name===t));if(-1!==m){const e=se(c,s);if(!e)return;Bs(s,i,t,g);let r=null;const o=p.children.length;if(p.type===ze.hubService&&d){const t=p.state,n=t.service?.name;n&&yo(d,p.id,e.gates)}try{for(let a=0;a<o;a++){const o=e.gates[p.children[a].childId];if(o?.disabled)continue;const d=Ge(p.children[a]?.sourcePort),l=Ge(p.children[a]?.targetPort);if(d.portName===t&&o&&!o.disabled){if(Co&&co()&&(ao(o.id),await co()),lo(o.id)&&!uo()&&"innerInput"!==l?.portType){const e=po(o.id);await e}if(Co&&oo())break;const a=ks(o.type);let d;const h={recipePoolId:c,recipeType:u,thingRecipeId:s,widgetId:i};d=o.type===ze.hubService?await a.getInputNames(o.state,h):a.getInputNames(o.state,h);const m=d.find((e=>e.name===l.portName));if(m){Co&&await ro({thingId:s,widgetId:o.id}),ko++;if(!await xo({interruptDriven:!1,childGateId:o.id,block:e,recipeId:c,sourcePortName:t,targetPort:{name:m.name},data:p.returnOriginalEvent?n:g,sourceOutputNames:f,sourceGateId:p.id,originalEvent:n}).then((()=>!0)).catch((e=>{const n=o.type===ze.hubService&&"CHILD_WIDGET_ERROR"===e.errCode;if(e instanceof tr)throw e;if(n&&e.errData){const t=e.errData;throw new tr(e.error||e.message||("string"==typeof e?e:JSON.stringify(e)),{targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType})}if(!r){const n="string"==typeof e?e:e.message||JSON.stringify(e);r={targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,error:n}}throw new tr(e.message||("string"==typeof e?e:JSON.stringify(e)),{stack:e.stack,targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,sourceWidgetId:p.id,targetWidgetType:o.type,sourceWidgetType:p.type})})).finally((()=>{if(ko--,Co)return io({thingId:s,widgetId:o.id,error:r})})))break}}}}catch(e){if(e instanceof tr)throw e;console.error(`Error processing next widget [${i}]: ${e}`)}finally{ko<0&&(console.warn("Active execution counter is negative, this should never happen"),ko=0),0===ko&&bo()}}},No=async(e,t,n,r)=>{const i=ie(r);if(!i)return null;const s=se(r,n);if(!s)return s;const o=s.gates,a=s.gates[t],c=ks(a.type),d=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),l=d.findIndex((t=>t.name===e));if(-1!==l){const e=((e,t,n)=>{for(const r in n){const i=n[r],s=i.children.length;for(let n=0;n<s;n++){const r=i.children[n],s=Ge(r.targetPort);if(r.childId===e&&s.portName===t)return i}}return null})(t,d[l].name,o);if(e){const t=ks(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},Po=e=>{const{gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}=e;if(!ie(o))throw new Error(`Failed to find recipe "${o}" in cache`);if(!oe(o,r,t))throw console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),new Error(`Gate ${t} not found in block ${r} for recipe ${o}`);return async(e,a)=>Ao({portName:e,originalEvent:n||{timestamp:Date.now(),type:a.type,value:a.value},data:a,currentGateId:t,blockRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o})},Oo=e=>{const{gateId:t,originalEvent:n,blockRecipeId:r,blockDbId:i,blockVersion:s,recipeId:o}=e,a=ie(o);if(!a)throw new Error(`Failed to find recipe "${o}" in cache`);const c=oe(o,r,t);if(!c)return console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),null;const d=Po({gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}),l=c.type===ze.hubService,u=l?vo(t,a.blocks[r].gates):[],p=u.reduce(((e,t)=>e.pathSegments>t.pathSegments?e:t),u[0]),g={id:t,type:c.type,recipePoolId:o,thingRecipeId:r,recipeType:a.dbInfo.recipeType,returnOriginalEvent:!!c.returnOriginalEvent,registerInterrupt:(e,n,i,s,a)=>Xe.createInterrupt(e,o,r,t,n,i,s,a),cancelInterrupt:e=>Xe.destroyInterrupt(e),nextWidget:d,nextGate:d,getParentAtPort:e=>No(e,t,r,o),getState:()=>Object.freeze({...c.state,...c.type===ze.input&&{customInputs:[]}}),setState:e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const n={...e,...c.type===ze.input&&!e.customInputs&&{customInputs:[]}},i={...c.state};c.state=n,_o&&_o({blockId:r,gateId:t,prevState:i,newState:{...n},recipeId:o})},...l&&p&&{eventContext:p.data.eventContext}};return g};Xe.setInvokeChildGateCb((async(e,t,n,r,i,s,o,a,c,d)=>xo({interruptDriven:e,childGateId:t,block:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c,originalEvent:d})));const To=(e,t,n,r,i)=>{const s=oe(e,n,r);if(!s)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=(t,i,s,o)=>Xe.createInterrupt(t,e,n,r,i,s,o),a=()=>Object.freeze({...s.state,...s.type===ze.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...s.type===ze.input&&!e.customInputs&&{customInputs:[]}};s.state=t},d=async t=>{const r=((e,t,n)=>{const r=ie(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=se(e,t);if(!i)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(i.storageUnits||[]).includes(n))throw new Error(`The Thing "${t}" has no access to storage unit "${n}"`);return r.storage[n]||null})(e,n,t);return r};if(i){return{getState:a,setState:c,registerInterrupt:o,getStorageData:d,nextWidget:Po({gateId:r,thingRecipeId:n,thingDbId:s.id,thingVersion:"default",recipeId:e}),recipePoolId:e,recipeType:t,thingRecipeId:n,widgetId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r}},Lo=new o,Bo="invoked",Do="state",jo=()=>{Xe.destroyAllInterrupts()},Uo=async(e,t,n)=>{const r=ie(e),i=oe(e,t,n);if(i&&r){const s=ks(i.type);if(s&&"function"==typeof s.terminate){const i=((e,t,n,r)=>To(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(i)try{await s.terminate(i)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},Ro=async e=>{const{recipePoolId:t,thingRecipeId:n,widgetRecipeId:r,options:i}=e,s=ie(t),o=oe(t,n,r);if(o&&s){const e=ks(o.type);if(e&&"function"==typeof e.initialize){const a=((e,t,n,r)=>To(e,t,n,r,!0))(t,s.dbInfo.recipeType,n,r);if(a){const t=e.initialize;try{(e=>{if(e.type===ze.script){const t=e.state;if((t.version||0)<2){const n=Object.keys(e.variablesListener||{});for(const t of n)if(e.variablesListener){const n=Sr(t);e.variablesListener[n]=e.variablesListener[t],delete e.variablesListener[t],delete e.variables}t.version=2}}})(o),await t(a,i||{})}catch(e){throw console.warn(`Error initializing widget "${r}" in thing "${n}": `,e),e}}}}},Fo=(e,t)=>{const n=ie(t);if(n)for(const t in n.blocks){const r=n.blocks[t];for(const t in r.gates)if(t===e)return{widget:r.gates[t],thing:r}}return null},Mo=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,Wo=e=>{Lo.emit(Mo(Do),e),Lo.emit(Mo(Do,e.blockId,e.gateId),e)};Io=async e=>{await Lo.emit(Mo(Bo),e),await Lo.emit(Mo(Bo,e.blockId,e.gateId),e)},(e=>{_o=e})(Wo);var Go,Vo,Ho,zo,qo,Ko,Jo,Yo,Xo,Zo,Qo,ea,ta,na=async(e,t,n,r,i)=>{const s=ae(e,{id:t,authorId:r,version:n,recipeType:i});js(),wo(),So(i);const o=ie(s);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=X.STARTING,o.addLog("recipe registered")),s},ra=async e=>{const t=ie(e);var n;if(!t)return null;t.addLog("terminating recipe"),jo(),so();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await Uo(e,n,t)}te[n=e]&&delete te[n]},ia=async(e,t)=>{const n=ie(e),r=[],i=[];if(n){Er({recipePoolId:e,thingId:ge});for(const s in n.blocks){const o=n.blocks[s];if(!t||!Array.isArray(t)||t.includes(s))for(const t in o.gates)try{if(n.dbInfo?.recipeType===Gn.Desktop){const e=o.gates[t];if(e.type===ze.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===ze.recipeLoad&&i.push(e)}await Ro({recipePoolId:e,thingRecipeId:s,widgetRecipeId:t,options:{keepCurrentState:!0}})}catch(e){r.push({widgetId:t,error:e.message})}}}return{failed:r,sendToInputWidget:(t,n,r=ge)=>(async(e,t,n,r)=>{const i=ie(n),s=se(n,r),o=Date.now();if(s&&i)for(const i in s.gates){const a=s.gates[i];if(a.type===ze.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=ks(a.type),d={...t,timestamp:o},l=Oo({gateId:i,originalEvent:d,blockRecipeId:r,blockDbId:s.id,blockVersion:s.version,recipeId:n});if(l&&e.processEvent){const s={...l,getState:l.getState};Io&&await Io({recipeId:n,blockId:r,gateId:i,targetPort:rt,data:t}),$o?await $o(r,n,c,t):await e.processEvent(d,s)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of i)await Eo({widgetId:t.id,thingId:ge,recipeId:e,targetPortName:rs,data:{type:fe.Boolean,value:!0}})}}},sa=e=>{Ki(e)},oa=(e,t,n,r=!1)=>{const i=Fo(t,e);if(i){const{widget:s,thing:o}=i,a={...s.state};s.state=n,r&&Wo({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},aa=(e,t)=>{const n=Fo(t,e);return n?n.widget.state:null},ca=async e=>{const{recipePoolId:t,currentGateId:n,sourcePortName:r,originalEvent:i,data:s,eventContext:o}=e,a=Fo(n,t);if(a)return Ao({portName:r,originalEvent:i,data:s,currentGateId:n,blockRecipeId:a.thing.recipeId,thingDbId:a.thing.id,thingVersion:a.thing.version,recipeId:t,eventContext:o})};!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(Go||(Go={})),function(e){e.UserFriendlyName="user_friendly_name",e.UserFriendlyDescription="user_friendly_description",e.InternalDescription="internal_description",e.TierLevel="tier_level",e.ProductFeatures="product_features",e.UserSubscribeCode="subscription_code"}(Vo||(Vo={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Ho||(Ho={})),function(e){e.Bundle="bundle",e.Group="group"}(zo||(zo={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(qo||(qo={})),function(e){e.Cloud="cloud",e.Web="web"}(Ko||(Ko={})),function(e){e.Cpu_128M="kmu-cpu-128m",e.Cpu_256M="kmu-cpu-256m",e.Cpu_512M="kmu-cpu-512m",e.Cpu_1024M="kmu-cpu-1024m",e.Cpu_2048M="kmu-cpu-2048m",e.Cpu_4096M="kmu-cpu-4096m"}(Jo||(Jo={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Yo||(Yo={})),function(e){e.InstallInProgress="installation-in-progress"}(Xo||(Xo={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Zo||(Zo={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Qo||(Qo={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(ea||(ea={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.UninstallHubService="uninstall_hub_service",e.ExportRecipe="export_recipe"}(ta||(ta={}));const da=(e,t)=>((e,t,n)=>{const r=Buffer.from(n,"base64"),i=r.subarray(0,16),s=r.subarray(16).toString("base64"),o=u(e,t,32),a=p("aes-256-cbc",o,i);let c=a.update(s,"base64","utf8");return c+=a.final("utf8"),c})(e.id||"recipe.kemu","kemu",t);var la,ua,pa,ga,ha,fa,ma,ya;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(la||(la={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(ua||(ua={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(pa||(pa={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ga||(ga={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(ha||(ha={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(fa||(fa={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(ma||(ma={})),function(e){e.IPC="ipc",e.WS="ws"}(ya||(ya={}));const va=e=>{try{return JSON.parse(e)}catch(e){return null}},ba="undefined"!=typeof window,Sa={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},wa={protocolPrefix:4,txtLength:4},Ia=Object.values(Sa).reduce(((e,t)=>e+t),0),_a=Object.values(wa).reduce(((e,t)=>e+t),0),$a=["width","height","colorSpace"],Ca=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${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,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)Object.hasOwn(e,n)||$a.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={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};s=o(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:s}:null},ka=(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 s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},Ea=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(Object.hasOwn(n,s)){const{index:o,length:a,binaryType:c}=n[s];let d=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":d=t.subarray(o,o+a);break;case"ArrayBuffer":d=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":d=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":d=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":d=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){d=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":d=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":d=i?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":d=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":d=new Int8Array(t.slice(o,o+a))}d&&ka(e,s,d)}return e},xa=e=>f(e),Aa="KMSG",Na="KCMD",Pa=xa("klProtocol");var Oa={encode:(e,t,n)=>{const r={json:e.json},i=Ca(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),d=c.byteLength,l=Sa.protocolPrefix+Sa.protocolVersion+Sa.jsonLength+Sa.binaryLength+Sa.fromServiceId+Sa.toServiceId+Sa.sentAt+d+o,u=Buffer.alloc(l),p=Date.now();let g=0;return u.write(Aa,g),g+=Sa.protocolPrefix,u.writeUInt8(1,g),g+=Sa.protocolVersion,u.writeUInt32LE(d,g),g+=Sa.jsonLength,u.writeUInt32LE(o,g),g+=Sa.binaryLength,u.writeUInt32LE(t,g),g+=Sa.fromServiceId,u.writeUInt32LE(n,g),g+=Sa.toServiceId,u.writeBigInt64LE(BigInt(p),g),g+=Sa.sentAt,c.copy(u,g),g+=d,s&&o&&s.copy(u,g),u},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Sa.protocolPrefix);if(t+=Sa.protocolPrefix,n!==Aa)return null;if(e.byteLength<Ia)return Pa(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Sa.protocolVersion;const i=e.readUInt32LE(t);t+=Sa.jsonLength;const s=e.readUInt32LE(t);t+=Sa.binaryLength;const o=e.readUInt32LE(t);t+=Sa.fromServiceId;const a=e.readUInt32LE(t);t+=Sa.toServiceId;const c=e.readBigInt64LE(t);t+=Sa.sentAt;const d=i+s,l=e.subarray(t,t+d),u=e.subarray(0,Ia);let p=null;return e.byteLength-Ia-i-s>0&&(p=e.subarray(Ia+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[l],headerPackage:u},remaining:p}},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=va(n);if(!i?.json)return Pa("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Ea(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=Ia+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Ia)return Pa("Invalid Header Size"),e;let n=0;return n+=Sa.protocolPrefix,n+=Sa.protocolVersion,n+=Sa.jsonLength,n+=Sa.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Sa.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=_a+r,s=Buffer.alloc(i);return s.write(Na,t),t+=wa.protocolPrefix,s.writeUint32LE(r,t),t+=wa.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<_a)return{command:null};const n=e.toString("utf-8",t,wa.protocolPrefix);if(t+=wa.protocolPrefix,n!==Na)return{command:null};const r=e.readUInt32LE(t);t+=wa.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-_a-r;let o=null;s>0&&(o=e.subarray(_a+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Ta="KMSG",La="KCMD",Ba=xa("klProtocol"),Da=new TextEncoder;var ja={encode:(e,t,n)=>{const r={json:e.json},i=Ca(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Da.encode(a),d=c.byteLength,l=new ArrayBuffer(Sa.protocolPrefix+Sa.protocolVersion+Sa.jsonLength+Sa.binaryLength+Sa.fromServiceId+Sa.toServiceId+Sa.sentAt+d+o),u=new DataView(l),p=new Uint8Array(l),g=Date.now();let h=0;for(let e=0;e<4;++e)p[h++]=Ta.charCodeAt(e);return u.setUint8(h,1),h+=Sa.protocolVersion,u.setUint32(h,d,!0),h+=Sa.jsonLength,u.setUint32(h,o,!0),h+=Sa.binaryLength,u.setUint32(h,t,!0),h+=Sa.fromServiceId,u.setUint32(h,n,!0),h+=Sa.toServiceId,u.setBigInt64(h,BigInt(g),!0),h+=Sa.sentAt,p.set(c,h),h+=d,s&&o&&p.set(new Uint8Array(s),h),l},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Sa.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ta)return null;if(e.byteLength<Ia)return Ba.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Sa.protocolVersion;const s=t.getUint32(n,!0);n+=Sa.jsonLength;const o=t.getUint32(n,!0);n+=Sa.binaryLength;const a=t.getUint32(n,!0);n+=Sa.fromServiceId;const c=t.getUint32(n,!0);n+=Sa.toServiceId;const d=t.getBigInt64(n,!0);n+=Sa.sentAt;const l=s+o,u=e.slice(n,n+l),p=new Uint8Array(e,0,Ia);let g=null;if(e.byteLength-Ia-s-o>0){g=new Uint8Array(e,Ia+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(d)),packages:[u],headerPackage:p.slice().buffer},remaining:g}},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 s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=va(s);if(!a?.json)return Ba.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Ea(a.json,o,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 d=c,l=null;const u=Ia+e.jsonLength+e.binaryLength;return c.byteLength>u&&(l=c.subarray(u),d=c.subarray(0,u)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:d.buffer},remaining:l?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Ia)return Ba("Invalid Header Size"),e;let n=0;n+=Sa.protocolPrefix,n+=Sa.protocolVersion,n+=Sa.jsonLength,n+=Sa.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Sa.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Da.encode(e),r=n.byteLength,i=new ArrayBuffer(_a+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=La.charCodeAt(e);return s.setUint32(t,r,!0),t+=wa.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<_a)return{command:null};let r="";for(let e=0;e<wa.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==La)return{command:null};const i=t.getUint32(n,!0);n+=wa.txtLength;const s=e.byteLength-_a-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-_a)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(_a+i));let d=0;return s<0&&(d=Math.abs(s)),{command:a,remainingData:c,missing:d}}};let Ua=Oa;ba&&(Ua=ja);var Ra,Fa=Ua;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Ra||(Ra={}));let Ma=Math.ceil(Date.now()/1e3);let Wa,Ga,Va,Ha,za,qa=!1;var Ka=()=>{qa=!0},Ja=(e,t)=>{if(!Wa)throw new Error("Memory connection not set.");Wa.sendBuf(e,t)},Ya=e=>Ga=e,Xa=e=>za=e,Za=e=>Va=e,Qa=e=>Ha=e;const ec=async(e,t=2)=>{const n=async(e,r)=>{if(Array.isArray(e))for(let i=0;i<e.length;i++){const s=e[i];if(s&&"object"==typeof s)if(Array.isArray(s))await n(s,r+1);else{const o=s._kemuType;void 0!==o?o===fe.ImageData&&(e[i]=await Ve(s)):r<t&&await n(s,r+1)}}else if("object"==typeof e&&null!==e){const i=Object.keys(e);for(const s of i){const i=e[s];if(i&&"object"==typeof i){const o=i._kemuType;void 0!==o?o===fe.ImageData&&(e[s]=await Ve(i)):r<t&&await n(i,r+1)}}}};return await n(e,1),e};xa("klTransmissionManager"),xa("ipcClient");xa("kemuWidgetService"),k(process.argv.slice(2));const tc=e=>f(`runner:${e}`),nc=tc("connectionManager"),rc=tc("remoteInvoke"),ic=new function(e){const t={};let n=console.log;const r={};let i=e||String(Date.now());const s={},o=e=>!s[e],a=(e,t,n,r,i,s)=>{let a=ba?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return o(r)&&(a=Fa.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,i,s,o)=>{if(!o)return!1;const c=o;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=r[c.functionName];if(t){const n=e=>{a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:s.sourceServiceId,send:i})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,s,a,c,d)=>{if(!s){const e="No send buffer function provided.";throw n&&n(e),e}Ma+=1;const l=`${i}-${Ma}-exec-${e.substring(0,10)}`,u={messageId:l,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};u.promise=new Promise(((e,t)=>{u.resolve=e,u.reject=t}));let p=ba?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:r,messageId:l,type:"execute"}};o(c)&&(p=Fa.encode(g,a,c)),t[l]=u,n&&n(`Calling remote function "${e}" with message id "${l}"`);const h="true"===process.env.NO_INVOKE_TIMEOUT;return d?.async?(u.fulfilled=!0,u.resolve([void 0]),delete t[l]):0===d?.timeout||h||(u.timer=setTimeout((()=>{n&&n(`Remote function ${l} timed out`);const r=t[l];r&&!r.fulfilled&&(r.fulfilled=!0,u.reject(`Function ${e} Timed out`)),delete t[l]}),d?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:g}),u.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,s)=>{Ma+=1;const a=`${i}-${Ma}-multicast-${e.substring(0,10)}`;let c=ba?new ArrayBuffer(0):Buffer.alloc(0);const d={json:{functionName:e,args:t,messageId:a,type:"execute"}};let l=o(r[0].serviceId);l&&(c=Fa.encode(d,s,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&&(l=o(i.serviceId),l&&(c=Fa.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:d,sourceServiceId:s,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("kweb");ic.setLogger(rc);const sc=new o,oc=new o;let ac,cc=null,dc=null,lc=null,uc=null;const pc={},gc=()=>{if(!lc)throw new Error("API key is required to interact with the hub");return lc},hc=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return pc[r]=i,i},fc=(e,t)=>pc[`${e}_${t}`]||null,mc=async(e,t)=>{if(!cc)return nc("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await ic.execute(be.GetServiceContents,n,vc,cc,0))[0]},yc=async(e,t,n=!1)=>{if(!e||!t)return null;const r=fc(e,t);if(!r||n){const n=r||hc(e,t);try{const r=await mc(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){nc(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},vc=Ja,bc=()=>{nc("Disconnected from the server"),cc=null,uc=null,ic.rejectAllPending("Disconnected from the server"),sc.emit("disconnected")},Sc=()=>{nc("Connected to the server"),sc.emit("connected")},wc=()=>dc,Ic=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,_c=async()=>{const e=wc();if(e){const t=ie(e)?.blocks;if(t){const n={};for(const r in t){const i=t[r];for(const t in i.gates){const r=i.gates[t];if(r.type===ze.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{nc(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await Uc({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){nc(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},$c=async e=>{if(!e)return void nc("Hub sent ACK request without service id");const t={apiKey:gc(),ackSessionId:e};await ic.execute(be.SocketAckResponse,[t],vc,e,0),nc("Hub Link acknowledged"),cc=e,sc.emit("acknowledged"),_c()},Cc=async e=>{const t=e.args[0],n=Ic("broadcast",`hub_${t.type}`,(0).toString(),"");await oc.emit(n,t)},kc=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===fe.ImageData&&je(e.value)&&(e.value=await Ve(e.value));const n=wc();if(n){const r=ie(n);if(r){const i=async e=>{const n=Ic("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await oc.emit(n,t)}catch(t){nc(`Failed to emit broadcast event for target ${e}`,t)}};await i("app");for(const s in r.blocks){const o=r.blocks[s];for(const r in o.gates){const s=o.gates[r];if(s.disabled)continue;const a=s.state;if(s.type===ze.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await i(r);const s=a?.service?.name&&t.eventContext?{[a.service.name]:t.eventContext}:void 0;for(const i of t.outputs||[])if(null!==i.value&&void 0!==i.value){const t={type:i.type,value:i.value,timestamp:Date.now()};nc(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await ca({recipePoolId:n,currentGateId:r,sourcePortName:i.name,originalEvent:t,data:t,eventContext:s})}}}}}}},Ec=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,s=aa(r,i);let o=s;if(n&&o&&s&&(o={...s,customState:n},oa(r,i,o,!0)),o?.service)try{const e=Ic("setOutputs",o.service.name,o.service.version,i);await oc.emit(e,t.outputs)}catch(e){nc(`Failed to emit setOutputs event for widget ${i}`,e)}let a=null;for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===fe.ImageData){if(!je(n.value)){nc(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=await Ve(n.value)}else n.type!==fe.JsonObj&&n.type!==fe.Array||await ec(n.value);const s={type:n.type,value:n.value,timestamp:Date.now()};nc(`Sending data to output ${n.name} requested by messageId ${e.messageId}`);const c=o?.service?.name&&t.eventContext?{[o.service.name]:t.eventContext}:void 0;try{await ca({recipePoolId:r,currentGateId:i,sourcePortName:n.name,originalEvent:s,data:s,eventContext:c})}catch(e){nc(`Failed to trigger next global widget for output ${n.name}`,e),a=e;break}}if(a){const t=a instanceof tr,n=a;e.reply({error:a.message,errCode:t?"CHILD_WIDGET_ERROR":"INVOKING_ERROR",errData:{targetWidgetId:n.targetWidgetId,targetPortName:n.targetPortName,sourcePortName:n.sourcePortName,sourceWidgetId:n.sourceWidgetId,targetWidgetType:n.targetWidgetType,sourceWidgetType:n.sourceWidgetType}})}else e.reply({success:[]})},xc=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,s=aa(r,i);if(s){const t={...s,customState:{...s.customState,...n}};return oa(r,i,t,!0),e.reply({success:[]})}},Ac=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:s,key:o}=n;nc(`Received request to set a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const a=aa(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:s},oa(r,i,e,!0)}return t({success:[]})},Nc=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:s}=n;nc(`Received request to get a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const o=aa(r,i);if(o){const e=o.dependencies?.[s]?.path;return nc(`Returning dependency path for "${s}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},Pc=async()=>{if(nc(`Requesting services on ${(new Date).toISOString()}`),!cc)return nc("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await ic.execute(be.GetServices,[],vc,cc,0);ac=e;for(const t of e.available){if(t.internal)continue;const e=fc(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||hc(t.name,t.version);nc(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await mc(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){nc(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},Oc=()=>ac||{available:[],installed:[],failed:[]},Tc=()=>!!ac,Lc=async e=>{const{targetServiceSessionId:t}=e;if(!cc)return void nc("No target service session id provided");nc(`Forwarding "onParentEvent" to service ${t}`);return await ic.execute(be.OnParentEvent,[e],vc,cc,t,e.config).catch((e=>{throw nc(`Error invoking onParentEvent callback: ${e}`),e.errCode===Ra.ParentEventCallbackError?e.error:e}))},Bc=async e=>{if(!cc)return nc("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await ic.execute(be.GetDefaultState,[],vc,cc,e);return t},Dc=async(e,t,n,r)=>{if(!cc)return nc("Hub Link has not been acknowledged. Cannot get services."),null;const[i]=await ic.execute(be.UIEvent,[t,n],vc,cc,e,r);return i},jc=(e,t)=>{const n=()=>{t()};return sc.on(e,n),()=>sc.off(e,n)},Uc=async e=>{if(cc)return ic.execute(be.SubscribeToService,[e],vc,cc,0);nc("Hub Link has not been acknowledged. Cannot subscribe to services.")},Rc=async e=>{if(cc)return ic.execute(be.UnsubscribeFromService,[e],vc,cc,0);nc("Hub Link has not been acknowledged. Cannot subscribe to services.")},Fc=(e,t,n,r)=>{const i=Ic("broadcast",t,n,e);return oc.on(i,r)},Mc=(e,t,n,r)=>{const i=Ic("setOutputs",t,n,e);return oc.on(i,r)},Wc=async(e,t,n)=>cc?ic.execute(e,t,vc,cc,0,n):(nc("Hub Link has not been acknowledged. Cannot execute function."),null),Gc=async e=>{if(!cc)return void nc("Hub Link has not been acknowledged. Cannot execute function.");const t=aa(e.recipeId,e.widgetId);if(!t)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const n=Object.keys(t.dependencies||{}).reduce(((e,n)=>(e[n]=t.dependencies?.[n]?.path||null,e)),{}),r=[{currentState:t.customState,recipeId:e.recipeId,widgetId:e.widgetId,variantId:e.variantId,recipeType:e.recipeType,recipeName:e.recipeName,currentDependencies:n}],[i]=await ic.execute(be.InitializeInstance,r,vc,cc,e.sessionId);if(i){const t=aa(e.recipeId,e.widgetId);if(t){const n={...t,customState:i};oa(e.recipeId,e.widgetId,n,!0)}}},Vc=async(e,t,n,r)=>{if(!cc)return void nc("Hub Link has not been acknowledged. Cannot execute function.");const i=aa(n,t);if(!i)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const s=[{currentState:i.customState,recipeId:n,widgetId:t,variantId:r}];await ic.execute(be.TerminateInstance,s,vc,cc,e)},Hc=async(e,t,n="^",r)=>{const i=["^","~",">=",">","<=","<","="];if(!i.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${i.join(", ")}`);const s=Tc(),o=r||!s?await Pc():Oc();for(const r of o.available)if(r.name===e){if(r.version===t)return r;if(h(r.version,`${n}${t}`))return r}return null},zc=async()=>{if(!cc)return nc("Hub Link has not been acknowledged. Cannot get services."),null;if(uc)return uc;const[e]=await ic.execute(be.GetSystemInfo,[],vc,cc,0).catch((e=>(nc("Failed to get system info",e),[null])));return uc=e,e};var qc,Kc,Jc,Yc,Xc,Zc,Qc,ed,td=async e=>{Za(Sc),Qa(bc),lc=e,Xa((({json:e,transmission:t})=>{ic.processMessage("websocket",vc,t,e)})),ic.registerFunction(be.SetState,xc),ic.registerFunction(be.SetOutputs,Ec),ic.registerFunction(be.BroadcastEvent,kc),ic.registerFunction(be.HubBroadcastEvent,Cc),ic.registerFunction(Se.SetDependencyPath,Ac),ic.registerFunction(Se.GetDependencyPath,Nc),Ya((e=>{((e,t)=>{const n=ve.SocketAcknowledge,r=ve.IpcAcknowledge,i=e.startsWith(n);if(e===r)return t&&t(),0;if(i){const s=e.split(i?n:r),o=parseInt(s[1]);return t&&t(o),o}})(e,$c),((e,t)=>{e===ve.ServicesListChanged&&(t&&t())})(e,(()=>{nc("Services list changed"),sc.emit("services-changed")}))})),await Ka()},nd=(e,t)=>{sc.on(e,t)},rd=()=>({getServices:Pc,getServiceContents:yc,onParentEvent:Lc,onCommand:jc,getDefaultState:Bc,getCachedServices:Oc,areServicesCached:Tc,subscribeToServiceEvents:Uc,unsubscribeFromServiceEvents:Rc,callProcessorHandler:Dc,onBroadcastEvent:Fc,onSetOutputsEvent:Mc,executeHubFunction:Wc,initializeServiceInstance:Gc,terminateServiceInstance:Vc,getCompatibleService:Hc,getHubSystemInfo:zc}),id=e=>{dc=e},sd=()=>ic;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(qc||(qc={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(Kc||(Kc={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(Jc||(Jc={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(Yc||(Yc={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(Xc||(Xc={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(Zc||(Zc={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(Qc||(Qc={})),function(e){e.IPC="ipc",e.WS="ws"}(ed||(ed={}));const od=e=>{try{return JSON.parse(e)}catch(e){return null}},ad=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,cd=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(ad);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},dd=e=>"*"===e||"x"===e||"X"===e,ld=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},ud=(e,t)=>{if(dd(e)||dd(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(ld(e),ld(t));return n>r?1:n<r?-1:0},pd=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=ud(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},gd=(e,t,n)=>{md(n);const r=((e,t)=>{const n=cd(e),r=cd(t),i=n.pop(),s=r.pop(),o=pd(n,r);return 0!==o?o:i&&s?pd(i.split("."),s.split(".")):i||s?i?-1:1:0})(e,t);return hd[n].includes(r)},hd={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},fd=Object.keys(hd),md=e=>{if(-1===fd.indexOf(e))throw new Error(`Invalid operator, expected one of ${fd.join("|")}`)};var yd="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function vd(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var bd,Sd,wd,Id,_d,$d={exports:{}},Cd={exports:{}};function kd(){if(Sd)return bd;Sd=1;var e=1e3,t=60*e,n=60*t,r=24*n,i=7*r,s=365.25*r;function o(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}return bd=function(a,c){c=c||{};var d=typeof a;if("string"===d&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*i;case"days":case"day":case"d":return c*r;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===d&&isFinite(a))return c.long?function(i){var s=Math.abs(i);if(s>=r)return o(i,s,r,"day");if(s>=n)return o(i,s,n,"hour");if(s>=t)return o(i,s,t,"minute");if(s>=e)return o(i,s,e,"second");return i+" ms"}(a):function(i){var s=Math.abs(i);if(s>=r)return Math.round(i/r)+"d";if(s>=n)return Math.round(i/n)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}function Ed(){if(Id)return wd;return Id=1,wd=function(e){function t(e){let r,i,s,o=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),s=i-(r||i);n.diff=s,n.prev=r,n.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,i)=>{if("%%"===r)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];r=s.call(n,t),e.splice(o,1),o--}return r})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),i=r.length;for(n=0;n<i;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=kd(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t},wd}var xd,Ad,Nd,Pd,Od,Td={exports:{}};function Ld(){return Ad||(Ad=1,xd=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return-1!==r&&(-1===i||r<i)}),xd}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?$d.exports=(_d||(_d=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))})),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=Ed()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Cd,Cd.exports)),Cd.exports):$d.exports=(Od||(Od=1,function(e,t){const n=E,r=c;t.init=function(e){e.inspectOpts={};const n=Object.keys(t.inspectOpts);for(let r=0;r<n.length;r++)e.inspectOpts[n[r]]=t.inspectOpts[n[r]]},t.log=function(...e){return process.stderr.write(r.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(n){const{namespace:r,useColors:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),s=` ${i};1m${r} [0m`;n[0]=s+n[0].split("\n").join("\n"+s),n.push(i+"m+"+e.exports.humanize(this.diff)+"[0m")}else n[0]=(t.inspectOpts.hideDate?"":(new Date).toISOString()+" ")+r+" "+n[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)},t.destroy=r.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if(Pd)return Nd;Pd=1;const e=x,t=E,n=Ld(),{env:r}=process;let i;function s(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function o(t,s){if(0===i)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!s&&void 0===i)return 0;const o=i||0;if("dumb"===r.TERM)return o;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in r))||"codeship"===r.CI_NAME?1:o;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if("truecolor"===r.COLORTERM)return 3;if("TERM_PROGRAM"in r){const e=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:o}return n("no-color")||n("no-colors")||n("color=false")||n("color=never")?i=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(i=1),"FORCE_COLOR"in r&&(i="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),Nd={supportsColor:function(e){return s(o(e,e&&e.isTTY))},stdout:s(o(!0,t.isatty(1))),stderr:s(o(!0,t.isatty(2)))}}();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let r=process.env[t];return r=!!/^(yes|on|true|enabled)$/i.test(r)||!/^(no|off|false|disabled)$/i.test(r)&&("null"===r?null:Number(r)),e[n]=r,e}),{}),e.exports=Ed()(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},i.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(Td,Td.exports)),Td.exports);var Bd=vd($d.exports);const Dd=e=>Bd(e),jd=Date.now();let Ud=Math.ceil(jd/1e3);var Rd=()=>Ud+=1;const Fd=y(A(),"kemu-user-services"),Md=y(A(),"kemu-test-services"),Wd="KMU-CB-v1",Gd=process.env.HUB_PKG_VERSION||'"1.3.5"';var Vd;!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"}(Vd||(Vd={}));const Hd=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>Kc[e])):Kc[e.type]}),zd=async e=>{try{return await w(e,"utf-8")}catch(e){return null}},qd=e=>{if(e&&e.startsWith(Wd)){const t=e.slice(9),n=decodeURI(t);return od(n)}return null},Kd=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(Hd)}:{},...e.outputs?{outputs:e.outputs.map(Hd)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(Hd)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(Hd)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},s=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const i of t.customWidgets){const t=await zd(y(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const s=t.startsWith(Wd)?t:`${Wd}${t}`,o=qd(s);if(!o){n(`Custom widget file "${i}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(o).filter((e=>e.type===Vd.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 d=c.state,l={name:d.name,color:d.color,description:d.description,contents:s,rootGroupId:c.id,icon:d.icon,protocolVersion:d.protocolVersion||"2"};r.push(l)}return r})(t,e,n?.log);if(s.length?i.customWidgets=s:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await w(y(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},Jd=async e=>{try{return await I(e,_.F_OK),!0}catch{return!1}};let Yd=null,Xd=null;const Zd=()=>Yd||Fd,Qd=Dd("servicesManager"),el={};let tl=null,nl=null,rl=null;class il extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const sl=async e=>{try{return await I(e),!0}catch{return!1}},ol=async e=>{if(!tl)throw new Error('IPC config not set, call "setHubIpcConfig" first.');try{if(e.processor===Yc.Javascript){Qd(`Spawning service ${e.name} with sessionId ${e.sessionId}`);const t=m.join(e.path,"processor.js"),n=m.join(e.path,"processor.mjs"),r=await sl(t)?t:n,i=[`--sessionId=${e.sessionId.toString()}`,`--ipcSpace=${tl.appSpace}`,`--ipcId=${tl?.id}`,`--recipePath=${tl.recipePath||""}`];if(e.internal&&i.push("--internal=true"),!rl)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const s=await rl({name:e.name,version:e.version,requiredSecrets:e.requiredSecrets||{}}),o=Object.entries(e.requiredSecrets||{}).filter((([e,t])=>{const n=s[e];return null==n&&!t.optional})).map((([e])=>e));if(o?.length)throw new il(`Missing required environment variables: ${o.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,n)=>{if(!nl)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const o=nl({args:[r,...i],serviceInfo:{name:e.name,version:e.version},options:{env:s}});o.stdout.on("data",(t=>{Qd(`[${e.name}] - stdout: ${t}`)})),o.stderr.on("data",(t=>{Qd(`[${e.name}] - stderr: ${t}`)})),o.on("exit",(t=>{Qd(`[${e.name}] exited with code ${t}`)})),o.on("spawn",(()=>{Qd(`[${e.name}] spawned with PID ${o.pid}`),t(o)})),o.on("error",(t=>{Qd(`[${e.name}] error: ${t}`),n(new il(`Error spawning service ${e.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.processor}`}catch(t){if(t instanceof il)throw t;throw`Error spawning service ${e.name}: ${t}`}},al=e=>{if(!e?.name)return"Missing name";if(!e?.version)return"Missing version";if(!e?.description)return"Missing description";if(!e?.processor)return"Missing processor";return[Yc.Javascript,Yc.Executable,Yc.Python].includes(e?.processor)?null:"Invalid processor"},cl=async(e,t)=>{const n=m.join(e,"manifest.json");if(!await sl(n)){const t=`Missing manifest for service ${e}. Aborting.`;return Qd(t),{error:t}}const r=await w(n,"utf-8"),i=od(r),s=al(i);if(!i||s){const t=`Invalid service manifest [${e}]: ${s}. Aborting.`;return Qd(t),{error:t}}let o;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{o=await w(m.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return Qd(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await zd(m.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=m.join(e,t),{error:r,service:s}=await cl(n);r?Qd(`Error loading sub-service ${t}: ${r}`):s&&(s.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 w(m.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){Qd(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=Rd(),c=t?.fixedSession||a;Qd(`Loaded service ${i.name} with sessionId ${c}`);const d=await Kd(i,e,{widgetUIContents:o});return dl(d),el[c]={info:{...d,path:e,sessionId:c},status:"loaded",childProcess:null},{service:el[c]}},dl=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=g("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},ll=async e=>{try{return e.childProcess=await ol(e.info),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return Qd(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof il?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},ul=e=>{const{path:t,...n}=e.info;return{...n}},pl=()=>Object.values(el).filter((e=>"running"===e.status)).map(ul),gl=e=>{const{serviceName:t,version:n,force:r}=e,i=Object.values(el).find((t=>t.info.name===e.serviceName&&t.info.version===e.version));if(!i)return null;if(i.info.internal&&!r)throw`Cannot stop internal service ${t}`;if(i.childProcess){Qd(`Stopping service "${t} (v${n})"`);i.childProcess.kill("SIGINT")||Qd(`Failed to stop service ${t}`)}return i.status="stopped",Qd(`Service ${t} stopped`),i},hl=e=>e.info.internal?e.info.path:m.join(e.info.path,".."),fl=e=>!!e.internal;var ml={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await Jd(e))return void Qd(`Failed to load services from "${e}". Directory does not exist.`);const n=(await $(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));Qd(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],s=m.join(e,i),{error:o,service:a}=await cl(`${s}${t?.internalServices?"":"/dist"}`,t);o&&Qd(`Failed to load service ${s}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(Qd("Initializing services"),!tl)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in el){const n=el[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?Qd(`Service ${n.info.name} is in the noSpawningList. Skipping.`):ll(n)}Qd("Services initialized")},setServiceStatus:(e,t)=>{const n=el[e];return n?(n.status=t,!0):(Qd(`Service with serviceId ${e} not found`),!1)},getActiveServices:pl,getMatchingService:(e,t)=>{const n=Object.values(el).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(gd(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>el[e]||null,killAllServices:()=>{for(const e in el){const t=el[e];if(t.childProcess)try{Qd(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){Qd(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await Kd(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};el[e]=r,dl(el[e].info)},setServiceManifest:(e,t,n)=>{const r=el[e];if(!r)return Qd(`Service with sessionId ${e} not found`),!1;const i=al(t);if(i)return Qd(`Invalid manifest for service ${r.info.name}: ${i}`),!1;dl(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(el).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:()=>pl().filter((e=>e.internal)),getAllServices:()=>Object.values(el),stopService:gl,uninstallService:async(e,t)=>{Qd(`Uninstalling service ${e} v${t}`);const n=gl({serviceName:e,version:t});if(!n)return!1;Qd(`Service ${e} stopped. Removing from disk...`);const r=hl(n),i=Zd();return r.startsWith(i)?(await C(r,{recursive:!0,force:!0}),Qd(`Service ${e} successfully removed from disk`),(e=>{const t=el[e];delete el[e]})(n.info.sessionId),!0):(Qd(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(el).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{tl={...e}},loadAndLaunch:async(e,t,n)=>{const r=b(e,t),{error:i,service:s}=await cl(r);if(i||!s)return{errorMsg:i};try{s.info.internal=!!n,s.childProcess=await ol(s.info),s.status="started"}catch(e){s.status="error",e instanceof il?(Qd(`Service spawning error: ${e.message} (${e.code})`),s.errorMsg=e.message,s.errorCode=e.code):(Qd(`Error launching service ${s.info.name}: ${e}`),s.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:s,errorCode:s.errorCode,errorMsg:s.errorMsg}},getServiceRootDirectory:hl,setSpawnNodeFunction:e=>{nl=e},setGetSecretsFunction:e=>{rl=e},restartService:async(e,t)=>{Qd(`Restarting service ${e} v${t}`);const n=gl({serviceName:e,version:t,force:!0});return!!n&&ll(n)},getFailedServices:()=>Object.values(el).filter((e=>"error"===e.status)).map((e=>({...ul(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:fl,isNotInternalKemuService:e=>!fl(e),isNotDevService:e=>!e.devMode};class yl{constructor(){}appspace="app.";socketRoot="/tmp/";id=x.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=x.networkInterfaces();let t="";e&&Array.isArray(e)&&e.length>0&&(t=e[Object.keys(e)[0]][0].family);return 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 vl{constructor(e){e||(e=new yl),this.delimiter=e.delimiter}format(e){return e.data||!1===e.data||0===e.data||(e.data={}),e.data._maxListeners&&(e.data={}),e=e.JSON+this.delimiter}parse(e){let t=e.split(this.delimiter);return t.pop(),t}}var bl=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={}},Sl=vd(bl);var wl=vd((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(){if(t=!0,e.length<1||this.stop)return void(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 Il{}class _l{}const $l=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 Il,t=_l){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 Il}}())}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 Cl{constructor(){}on(e,t,n=!1){return $l.string(e),$l.function(t),$l.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($l.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;$l.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){$l.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)=>{$l.string(e),$l.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 kl=new vl;class El extends Cl{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),kl=new vl(this.config)}Client=El;queue=new wl;socket=!1;connect=Nl;emit=xl;retriesRemaining=0;explicitlyDisconnected=!1}function xl(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Sl;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):kl.format(n),this.config.sync?this.queue.add(Al.bind(this,n)):this.socket.write(n)}function Al(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Nl(){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=O.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=O.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(O.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=P.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=N.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=N.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)!=kl.delimiter||-1==t.indexOf(kl.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=kl.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Sl;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 Pl=new vl;class Ol extends Cl{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Pl=new vl(this.config),this.on("close",Bl.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Tl;broadcast=Ll;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?O.unlink(this.path,Rl.bind(this)):Rl.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Tl(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Sl;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Pl.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 Ll(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Sl;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Pl.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 Bl(){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 Dl(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)==Pl.delimiter&&-1!=t.indexOf(Pl.delimiter))for(r.ipcBuffer="",t=Pl.parse(t);t.length>0;){let e=new Sl;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 jl(e){this.publish("close",e)}function Ul(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",jl.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",Dl.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 Rl(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=L.createSocket(this.udp4?"udp4":"udp6"),this.server.write=Ml.bind(this),this.server.on("listening",function(){Ul.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?Fl.bind(this)():this.server=N.createServer(Ul.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 Fl(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=O.readFileSync(this.config.tls.private):this.config.tls.key=O.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=O.readFileSync(this.config.tls.public):this.config.tls.cert=O.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=O.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(O.readFileSync(this.config.tls.trustedConnections[e]))}this.server=P.createServer(this.config.tls,Ul.bind(this))}function Ml(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 Wl{constructor(){}config=new yl;of={};server=!1;get connectTo(){return Kl}get connectToNet(){return Jl}get disconnect(){return Vl}get serve(){return Hl}get serveNet(){return ql}get log(){return Gl}set connectTo(e){return Kl}set connectToNet(e){return Jl}set disconnect(e){return Vl}set serve(e){return Hl}set serveNet(e){return ql}set log(e){return Gl}}function Gl(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=c.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function Vl(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 Hl(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=zl),this.server=new Ol(e,this.config,Gl),this.server.on("start",t)}function zl(){}function ql(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=zl),this.server=new Ol(e,this.config,Gl,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function Kl(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=zl),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 El(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 Jl(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=zl),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 El(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 Yl=new class extends Wl{constructor(){super()}IPC=Wl};var Xl={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const Zl=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),Ql=e=>{try{return JSON.parse(e)}catch(e){return null}},eu="undefined"!=typeof window,tu={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},nu={protocolPrefix:4,txtLength:4},ru=Object.values(tu).reduce(((e,t)=>e+t),0),iu=Object.values(nu).reduce(((e,t)=>e+t),0),su=["width","height","colorSpace"],ou=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${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,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)e.hasOwnProperty(n)||su.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={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};s=o(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:s}:null},au=(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 s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},cu=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(n.hasOwnProperty(s)){const{index:o,length:a,binaryType:c}=n[s];let d=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":d=t.subarray(o,o+a);break;case"ArrayBuffer":d=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":d=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":d=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":d=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){d=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":d=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":d=i?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":d=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":d=new Int8Array(t.slice(o,o+a))}d&&au(e,s,d)}return e},du=e=>Bd(e),lu="KMSG",uu="KCMD",pu=du("klProtocol");var gu={encode:(e,t,n)=>{const r={json:e.json},i=ou(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),d=c.byteLength,l=tu.protocolPrefix+tu.protocolVersion+tu.jsonLength+tu.binaryLength+tu.fromServiceId+tu.toServiceId+tu.sentAt+d+o,u=Buffer.alloc(l),p=Date.now();let g=0;return u.write(lu,g),g+=tu.protocolPrefix,u.writeUInt8(1,g),g+=tu.protocolVersion,u.writeUInt32LE(d,g),g+=tu.jsonLength,u.writeUInt32LE(o,g),g+=tu.binaryLength,u.writeUInt32LE(t,g),g+=tu.fromServiceId,u.writeUInt32LE(n,g),g+=tu.toServiceId,u.writeBigInt64LE(BigInt(p),g),g+=tu.sentAt,c.copy(u,g),g+=d,s&&o&&s.copy(u,g),u},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,tu.protocolPrefix);if(t+=tu.protocolPrefix,n!==lu)return null;if(e.byteLength<ru)return pu(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=tu.protocolVersion;const i=e.readUInt32LE(t);t+=tu.jsonLength;const s=e.readUInt32LE(t);t+=tu.binaryLength;const o=e.readUInt32LE(t);t+=tu.fromServiceId;const a=e.readUInt32LE(t);t+=tu.toServiceId;const c=e.readBigInt64LE(t);t+=tu.sentAt;const d=i+s,l=e.subarray(t,t+d),u=e.subarray(0,ru);let p=null;return e.byteLength-ru-i-s>0&&(p=e.subarray(ru+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[l],headerPackage:u},remaining:p}},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=Ql(n);if(!i?.json)return pu("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&cu(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=ru+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<ru)return pu("Invalid Header Size"),e;let n=0;return n+=tu.protocolPrefix,n+=tu.protocolVersion,n+=tu.jsonLength,n+=tu.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=tu.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=iu+r,s=Buffer.alloc(i);return s.write(uu,t),t+=nu.protocolPrefix,s.writeUint32LE(r,t),t+=nu.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<iu)return{command:null};const n=e.toString("utf-8",t,nu.protocolPrefix);if(t+=nu.protocolPrefix,n!==uu)return{command:null};const r=e.readUInt32LE(t);t+=nu.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-iu-r;let o=null;s>0&&(o=e.subarray(iu+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const hu="KMSG",fu="KCMD",mu=du("klProtocol"),yu=new TextEncoder;var vu={encode:(e,t,n)=>{const r={json:e.json},i=ou(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=yu.encode(a),d=c.byteLength,l=new ArrayBuffer(tu.protocolPrefix+tu.protocolVersion+tu.jsonLength+tu.binaryLength+tu.fromServiceId+tu.toServiceId+tu.sentAt+d+o),u=new DataView(l),p=new Uint8Array(l),g=Date.now();let h=0;for(let e=0;e<4;++e)p[h++]=hu.charCodeAt(e);return u.setUint8(h,1),h+=tu.protocolVersion,u.setUint32(h,d,!0),h+=tu.jsonLength,u.setUint32(h,o,!0),h+=tu.binaryLength,u.setUint32(h,t,!0),h+=tu.fromServiceId,u.setUint32(h,n,!0),h+=tu.toServiceId,u.setBigInt64(h,BigInt(g),!0),h+=tu.sentAt,p.set(c,h),h+=d,s&&o&&p.set(new Uint8Array(s),h),l},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<tu.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==hu)return null;if(e.byteLength<ru)return mu.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=tu.protocolVersion;const s=t.getUint32(n,!0);n+=tu.jsonLength;const o=t.getUint32(n,!0);n+=tu.binaryLength;const a=t.getUint32(n,!0);n+=tu.fromServiceId;const c=t.getUint32(n,!0);n+=tu.toServiceId;const d=t.getBigInt64(n,!0);n+=tu.sentAt;const l=s+o,u=e.slice(n,n+l),p=new Uint8Array(e,0,ru);let g=null;if(e.byteLength-ru-s-o>0){g=new Uint8Array(e,ru+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(d)),packages:[u],headerPackage:p.slice().buffer},remaining:g}},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 s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Ql(s);if(!a?.json)return mu.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&cu(a.json,o,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 d=c,l=null;const u=ru+e.jsonLength+e.binaryLength;return c.byteLength>u&&(l=c.subarray(u),d=c.subarray(0,u)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:d.buffer},remaining:l?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<ru)return mu("Invalid Header Size"),e;let n=0;n+=tu.protocolPrefix,n+=tu.protocolVersion,n+=tu.jsonLength,n+=tu.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=tu.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=yu.encode(e),r=n.byteLength,i=new ArrayBuffer(iu+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=fu.charCodeAt(e);return s.setUint32(t,r,!0),t+=nu.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<iu)return{command:null};let r="";for(let e=0;e<nu.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==fu)return{command:null};const i=t.getUint32(n,!0);n+=nu.txtLength;const s=e.byteLength-iu-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-iu)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(iu+i));let d=0;return s<0&&(d=Math.abs(s)),{command:a,remainingData:c,missing:d}}};const bu=du("klTransmissionManager"),Su=()=>{const e=(t,n,r,i)=>{let s=n,o=null;const a=t instanceof ArrayBuffer;if(bu(`RAW: ${t.toString()}`),!s||s.partialHeaderData){let c;if(a?(c=s?.partialHeaderData?new Uint8Array([...new Uint8Array(s.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=vu.decodeHeader(c)):(c=s?.partialHeaderData?Buffer.concat([s.partialHeaderData,t]):t,o=gu.decodeHeader(c)),!o){const{command:t,missing:s,remainingData:o}=a?vu.decodeCommand(c):gu.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):bu(s?`ERROR: Missing ${s} 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`),o?(bu(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,n,r,i)):void 0}if(o.partialHeader)return s={firstPackageAt:Date.now(),partialHeaderData:c},r(s);if(!o.header)return bu(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const d=o.header;s={firstPackageAt:Date.now(),header:{...d,totalBytesReceived:d.packages[0].byteLength,totalBytesExpected:d.binaryLength+d.jsonLength,remaining:o.remaining}},r(s)}else s.header&&s.header.totalBytesReceived<s.header.totalBytesExpected&&(s.header.packages.push(t),s.header.totalBytesReceived+=t.byteLength,r(s));if(s.header&&s.header.totalBytesReceived>=s.header.totalBytesExpected){const t=Date.now()-s.header.sentAt.getTime(),n=Date.now()-s.firstPackageAt;bu(`Received ${s.header.totalBytesReceived} of ${s.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?vu.decodeFullKlMessage(s.header):gu.decodeFullKlMessage(s.header),c=s.header.totalBytesReceived,d=s.header.remaining;r(null),o&&i({klMessage:o.message,complete:!0,sourceServiceId:s.header.fromServiceId,targetServiceId:s.header.toServiceId,rawMessage:o.message.rawMessage});let l=d;if(o?.remaining&&(l=a?d?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),s=new Uint8Array(t),o=new Uint8Array(r);return o.set(i),o.set(s,i.length),r})(d,o.remaining):o.remaining:d?Buffer.concat([d,o.remaining]):o.remaining),l)return bu(`${l.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(l,null,r,i)}};return e};Yl.config={...Yl.config,...Xl};const wu={info:Dd("ipcServer:info"),data:Dd("ipcServer:data")};let Iu,_u,$u,Cu,ku={};const Eu=Su(),xu=e=>{ku[e]&&(wu.info(`Client disconnected [${e}]`),delete ku[e],_u&&_u(e))};var Au=e=>(e?.ipcId&&(Yl.config.id=e.ipcId),e?.ipcAppSpace&&(Yl.config.appspace=e.ipcAppSpace),new Promise((e=>{Yl.serve((()=>{wu.info("IPC Server Initiated"),Yl.server.on("data",((e,t)=>{const n=ku[t.id];n?(wu.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Eu(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return wu.data(`Received command from client [${t.id}]: ${e.command}`),void($u&&$u(t.id,e.command,n));e.klMessage&&Cu&&Cu({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):wu.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),Yl.server.on("connect",(e=>{const t=Rd();wu.info(`New client connected. Registered as "${t}"`),e.id=t,ku[t]={socket:e,activeMessage:null,disconnectHandler:()=>xu(t)},e.on("close",ku[t].disconnectHandler),Iu&&Iu(t)})),Yl.server.on("disconnect",(e=>{xu(e.id)})),Yl.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),Yl.server.start()}))),Nu=e=>{Iu=e},Pu=e=>{_u=e},Ou=e=>Cu=e,Tu=(e,t)=>{const n=ku[e];if(!n)return wu.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=Zl)return wu.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=gu.encodeCommand(t);return n.socket.write(r),!0},Lu=(e,t)=>{const n=ku[e];return!!n&&(wu.info(`Renaming socket id [${e}] to [${t}]`),delete ku[e],n.socket.id=t,ku[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>xu(t),n.socket.on("close",n.disconnectHandler),!0)},Bu=e=>{$u=e};let Du=gu;eu&&(Du=vu);var ju,Uu=Du;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(ju||(ju={}));let Ru=Math.ceil(Date.now()/1e3);var Fu={exports:{}};const Mu=["nodebuffer","arraybuffer","fragments"],Wu="undefined"!=typeof Blob;Wu&&Mu.push("blob");var Gu={BINARY_TYPES:Mu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Wu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:Vu}=Gu,Hu=Buffer[Symbol.species];function zu(e,t,n,r,i){for(let s=0;s<i;s++)n[r+s]=e[s]^t[3&s]}function qu(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(Fu.exports={concat:function(e,t){if(0===e.length)return Vu;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 Hu(n.buffer,n.byteOffset,r):n},mask:zu,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 Hu(t):ArrayBuffer.isView(t)?n=new Hu(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:qu},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Fu.exports.mask=function(t,n,r,i,s){s<48?zu(t,n,r,i,s):e.mask(t,n,r,i,s)},Fu.exports.unmask=function(t,n){t.length<32?qu(t,n):e.unmask(t,n)}}catch(e){}var Ku=Fu.exports;const Ju=Symbol("kDone"),Yu=Symbol("kRun");const Xu=D,Zu=Ku,Qu=class{constructor(e){this[Ju]=()=>{this.pending--,this[Yu]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Yu]()}[Yu](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Ju])}}},{kStatusCode:ep}=Gu,tp=Buffer[Symbol.species],np=Buffer.from([0,0,255,255]),rp=Symbol("permessage-deflate"),ip=Symbol("total-length"),sp=Symbol("callback"),op=Symbol("buffers"),ap=Symbol("error");let cp;var dp=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,!cp){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;cp=new Qu(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[sp];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){cp.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){cp.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]?Xu.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Xu.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[rp]=this,this._inflate[ip]=0,this._inflate[op]=[],this._inflate.on("error",pp),this._inflate.on("data",up)}this._inflate[sp]=n,this._inflate.write(e),t&&this._inflate.write(np),this._inflate.flush((()=>{const e=this._inflate[ap];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=Zu.concat(this._inflate[op],this._inflate[ip]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ip]=0,this._inflate[op]=[],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]?Xu.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Xu.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[ip]=0,this._deflate[op]=[],this._deflate.on("data",lp)}this._deflate[sp]=n,this._deflate.write(e),this._deflate.flush(Xu.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Zu.concat(this._deflate[op],this._deflate[ip]);t&&(e=new tp(e.buffer,e.byteOffset,e.length-4)),this._deflate[sp]=null,this._deflate[ip]=0,this._deflate[op]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function lp(e){this[op].push(e),this[ip]+=e.length}function up(e){this[ip]+=e.length,this[rp]._maxPayload<1||this[ip]<=this[rp]._maxPayload?this[op].push(e):(this[ap]=new RangeError("Max payload size exceeded"),this[ap].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ap][ep]=1009,this.removeListener("data",up),this.reset())}function pp(e){this[rp]._inflate=null,e[ep]=1007,this[sp](e)}var gp={exports:{}};const{isUtf8:hp}=j,{hasBlob:fp}=Gu;function mp(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(gp.exports={isBlob:function(e){return fp&&"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:mp,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]},hp)gp.exports.isValidUTF8=function(e){return e.length<24?mp(e):hp(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");gp.exports.isValidUTF8=function(t){return t.length<32?mp(t):e(t)}}catch(e){}var yp=gp.exports;const{Writable:vp}=B,bp=dp,{BINARY_TYPES:Sp,EMPTY_BUFFER:wp,kStatusCode:Ip,kWebSocket:_p}=Gu,{concat:$p,toArrayBuffer:Cp,unmask:kp}=Ku,{isValidStatusCode:Ep,isValidUTF8:xp}=yp,Ap=Buffer[Symbol.species];var Np=class extends vp{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Sp[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[_p]=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 Ap(t.buffer,t.byteOffset+e,t.length-e),new Ap(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 Ap(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[bp.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);if(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"))}else this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(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"))}else 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=wp;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]&&kp(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[bp.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?$p(n,t):"arraybuffer"===this._binaryType?Cp($p(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=$p(n,t);if(!this._skipUTF8Validation&&!xp(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,wp),this.end();else{const n=e.readUInt16BE(0);if(!Ep(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Ap(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!xp(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 s=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,this.createError),s.code=i,s[Ip]=r,s}};const{randomFillSync:Pp}=l,Op=dp,{EMPTY_BUFFER:Tp,kWebSocket:Lp,NOOP:Bp}=Gu,{isBlob:Dp,isValidStatusCode:jp}=yp,{mask:Up,toBuffer:Rp}=Ku,Fp=Symbol("kByteLength"),Mp=Buffer.alloc(4),Wp=8192;let Gp,Vp=Wp;var Hp=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=Bp,this[Lp]=void 0}static frame(e,t){let n,r,i=!1,s=2,o=!1;t.mask&&(n=t.maskBuffer||Mp,t.generateMask?t.generateMask(n):(Vp===Wp&&(void 0===Gp&&(Gp=Buffer.alloc(Wp)),Pp(Gp,0,Wp),Vp=0),n[0]=Gp[Vp++],n[1]=Gp[Vp++],n[2]=Gp[Vp++],n[3]=Gp[Vp++]),o=!(n[0]|n[1]|n[2]|n[3]),s=6),"string"==typeof e?r=t.mask&&!o||void 0===t[Fp]?(e=Buffer.from(e)).length:t[Fp]:(r=e.length,i=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(s+=8,a=127):r>125&&(s+=2,a=126);const c=Buffer.allocUnsafe(i?r+s:s);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[s-4]=n[0],c[s-3]=n[1],c[s-2]=n[2],c[s-1]=n[3],o?[c,e]:i?(Up(e,n,c,s,r),[c]):(Up(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let s;if(void 0===t)s=Tp;else{if("number"!=typeof t||!jp(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");s=Buffer.allocUnsafe(2+e),s.writeUInt16BE(t,0),"string"==typeof n?s.write(n,2):s.set(n,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0)}const o={[Fp]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(e.frame(s,o),i)}ping(t,n,r){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):Dp(t)?(i=t.size,s=!1):(i=(t=Rp(t)).length,s=Rp.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Fp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};Dp(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}pong(t,n,r){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):Dp(t)?(i=t.size,s=!1):(i=(t=Rp(t)).length,s=Rp.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Fp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};Dp(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}send(e,t,n){const r=this._extensions[Op.extensionName];let i,s,o=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):Dp(e)?(i=e.size,s=!1):(i=(e=Rp(e)).length,s=Rp.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,o=0),t.fin&&(this._firstFragment=!0);const c={[Fp]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:s,rsv1:a};Dp(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[Fp],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(zp,this,e,i)}this._bufferedBytes-=r[Fp];const s=Rp(t);n?this.dispatch(s,n,r,i):(this._state=0,this.sendFrame(e.frame(s,r),i),this.dequeue())})).catch((e=>{process.nextTick(qp,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const s=this._extensions[Op.extensionName];this._bufferedBytes+=r[Fp],this._state=1,s.compress(t,r.fin,((t,n)=>{if(this._socket.destroyed){zp(this,new Error("The socket was closed while data was being compressed"),i)}else this._bufferedBytes-=r[Fp],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][Fp],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Fp],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)}};function zp(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 qp(e,t,n){zp(e,t,n),e.onerror(t)}const{kForOnEventAttribute:Kp,kListener:Jp}=Gu,Yp=Symbol("kCode"),Xp=Symbol("kData"),Zp=Symbol("kError"),Qp=Symbol("kMessage"),eg=Symbol("kReason"),tg=Symbol("kTarget"),ng=Symbol("kType"),rg=Symbol("kWasClean");class ig{constructor(e){this[tg]=null,this[ng]=e}get target(){return this[tg]}get type(){return this[ng]}}Object.defineProperty(ig.prototype,"target",{enumerable:!0}),Object.defineProperty(ig.prototype,"type",{enumerable:!0});class sg extends ig{constructor(e,t={}){super(e),this[Yp]=void 0===t.code?0:t.code,this[eg]=void 0===t.reason?"":t.reason,this[rg]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Yp]}get reason(){return this[eg]}get wasClean(){return this[rg]}}Object.defineProperty(sg.prototype,"code",{enumerable:!0}),Object.defineProperty(sg.prototype,"reason",{enumerable:!0}),Object.defineProperty(sg.prototype,"wasClean",{enumerable:!0});class og extends ig{constructor(e,t={}){super(e),this[Zp]=void 0===t.error?null:t.error,this[Qp]=void 0===t.message?"":t.message}get error(){return this[Zp]}get message(){return this[Qp]}}Object.defineProperty(og.prototype,"error",{enumerable:!0}),Object.defineProperty(og.prototype,"message",{enumerable:!0});class ag extends ig{constructor(e,t={}){super(e),this[Xp]=void 0===t.data?null:t.data}get data(){return this[Xp]}}Object.defineProperty(ag.prototype,"data",{enumerable:!0});const cg={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[Kp]&&r[Jp]===t&&!r[Kp])return;let r;if("message"===e)r=function(e,n){const r=new ag("message",{data:n?e:e.toString()});r[tg]=this,lg(t,this,r)};else if("close"===e)r=function(e,n){const r=new sg("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[tg]=this,lg(t,this,r)};else if("error"===e)r=function(e){const n=new og("error",{error:e,message:e.message});n[tg]=this,lg(t,this,n)};else{if("open"!==e)return;r=function(){const e=new ig("open");e[tg]=this,lg(t,this,e)}}r[Kp]=!!n[Kp],r[Jp]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[Jp]===t&&!n[Kp]){this.removeListener(e,n);break}}};var dg={CloseEvent:sg,ErrorEvent:og,Event:ig,EventTarget:cg,MessageEvent:ag};function lg(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:ug}=yp;function pg(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var gg={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),s=!1,o=!1,a=!1,c=-1,d=-1,l=-1,u=0;for(;u<e.length;u++)if(d=e.charCodeAt(u),void 0===n)if(-1===l&&1===ug[d])-1===c&&(c=u);else if(0===u||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u);const r=e.slice(c,l);44===d?(pg(t,r,i),i=Object.create(null)):n=r,c=l=-1}}else-1===l&&-1!==c&&(l=u);else if(void 0===r)if(-1===l&&1===ug[d])-1===c&&(c=u);else if(32===d||9===d)-1===l&&-1!==c&&(l=u);else if(59===d||44===d){if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u),pg(i,e.slice(c,l),!0),44===d&&(pg(t,n,i),i=Object.create(null),n=void 0),c=l=-1}else{if(61!==d||-1===c||-1!==l)throw new SyntaxError(`Unexpected character at index ${u}`);r=e.slice(c,u),c=l=-1}else if(o){if(1!==ug[d])throw new SyntaxError(`Unexpected character at index ${u}`);-1===c?c=u:s||(s=!0),o=!1}else if(a)if(1===ug[d])-1===c&&(c=u);else if(34===d&&-1!==c)a=!1,l=u;else{if(92!==d)throw new SyntaxError(`Unexpected character at index ${u}`);o=!0}else if(34===d&&61===e.charCodeAt(u-1))a=!0;else if(-1===l&&1===ug[d])-1===c&&(c=u);else if(-1===c||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u);let o=e.slice(c,l);s&&(o=o.replace(/\\/g,""),s=!1),pg(i,r,o),44===d&&(pg(t,n,i),i=Object.create(null),n=void 0),r=void 0,c=l=-1}}else-1===l&&(l=u);if(-1===c||a||32===d||9===d)throw new SyntaxError("Unexpected end of input");-1===l&&(l=u);const p=e.slice(c,l);return void 0===n?pg(t,p,i):(void 0===r?pg(i,p,!0):pg(i,r,s?p.replace(/\\/g,""):p),pg(t,n,i)),t}};const hg=U,fg=R,mg=F,yg=N,vg=P,{randomBytes:bg,createHash:Sg}=l,{URL:wg}=M,Ig=dp,_g=Np,$g=Hp,{isBlob:Cg}=yp,{BINARY_TYPES:kg,EMPTY_BUFFER:Eg,GUID:xg,kForOnEventAttribute:Ag,kListener:Ng,kStatusCode:Pg,kWebSocket:Og,NOOP:Tg}=Gu,{EventTarget:{addEventListener:Lg,removeEventListener:Bg}}=dg,{format:Dg,parse:jg}=gg,{toBuffer:Ug}=Ku,Rg=3e4,Fg=Symbol("kAborted"),Mg=[8,13],Wg=["CONNECTING","OPEN","CLOSING","CLOSED"],Gg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let Vg=class e extends hg{constructor(t,n,r){super(),this._binaryType=kg[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Eg,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]),zg(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){kg.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 _g({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new $g(t,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=t,i[Og]=this,s[Og]=this,t[Og]=this,i.on("conclude",Zg),i.on("drain",Qg),i.on("error",eh),i.on("message",nh),i.on("ping",rh),i.on("pong",ih),s.onerror=oh,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",ch),t.on("data",dh),t.on("end",lh),t.on("error",uh),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[Ig.extensionName]&&this._extensions[Ig.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())})),ah(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";Yg(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||Eg,n,r)):Xg(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||Eg,n,r)):Xg(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 Xg(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ig.extensionName]||(i.compress=!1),this._sender.send(t||Eg,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";Yg(this,this._req,e)}}};Object.defineProperty(Vg,"CONNECTING",{enumerable:!0,value:Wg.indexOf("CONNECTING")}),Object.defineProperty(Vg.prototype,"CONNECTING",{enumerable:!0,value:Wg.indexOf("CONNECTING")}),Object.defineProperty(Vg,"OPEN",{enumerable:!0,value:Wg.indexOf("OPEN")}),Object.defineProperty(Vg.prototype,"OPEN",{enumerable:!0,value:Wg.indexOf("OPEN")}),Object.defineProperty(Vg,"CLOSING",{enumerable:!0,value:Wg.indexOf("CLOSING")}),Object.defineProperty(Vg.prototype,"CLOSING",{enumerable:!0,value:Wg.indexOf("CLOSING")}),Object.defineProperty(Vg,"CLOSED",{enumerable:!0,value:Wg.indexOf("CLOSED")}),Object.defineProperty(Vg.prototype,"CLOSED",{enumerable:!0,value:Wg.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Vg.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Vg.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[Ag])return t[Ng];return null},set(t){for(const t of this.listeners(e))if(t[Ag]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[Ag]:!0})}})})),Vg.prototype.addEventListener=Lg,Vg.prototype.removeEventListener=Bg;var Hg=Vg;function zg(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Mg[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,!Mg.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Mg.join(", ")})`);let s;if(t instanceof wg)s=t;else try{s=new wg(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===s.protocol?s.protocol="ws:":"https:"===s.protocol&&(s.protocol="wss:"),e._url=s.href;const o="wss:"===s.protocol,a="ws+unix:"===s.protocol;let c;if("ws:"===s.protocol||o||a?a&&!s.pathname?c="The URL's pathname is empty":s.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 qg(e,t)}const d=o?443:80,l=bg(16).toString("base64"),u=o?fg.request:mg.request,p=new Set;let g,h;if(i.createConnection=i.createConnection||(o?Jg:Kg),i.defaultPort=i.defaultPort||d,i.port=s.port||d,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(g=new Ig(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Dg({[Ig.extensionName]:g.offer()})),n.length){for(const e of n){if("string"!=typeof e||!Gg.test(e)||p.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.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),(s.username||s.password)&&(i.auth=`${s.username}:${s.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=o,e._originalHostOrSocketPath=a?i.socketPath:s.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&&s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(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")),h=e._req=u(i),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=u(i);i.timeout&&h.on("timeout",(()=>{Yg(e,h,"Opening handshake has timed out")})),h.on("error",(t=>{null===h||h[Fg]||(h=e._req=null,qg(e,t))})),h.on("response",(s=>{const o=s.headers.location,a=s.statusCode;if(o&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void Yg(e,h,"Maximum redirects exceeded");let s;h.abort();try{s=new wg(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void qg(e,n)}zg(e,s,n,r)}else e.emit("unexpected-response",h,s)||Yg(e,h,`Unexpected server response: ${s.statusCode}`)})),h.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==Vg.CONNECTING)return;h=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void Yg(e,n,"Invalid Upgrade header");const o=Sg("sha1").update(l+xg).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void Yg(e,n,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?p.size?p.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":p.size&&(c="Server sent no subprotocol"),c)return void Yg(e,n,c);a&&(e._protocol=a);const d=t.headers["sec-websocket-extensions"];if(void 0!==d){if(!g){return void Yg(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=jg(d)}catch(t){return void Yg(e,n,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==Ig.extensionName){return void Yg(e,n,"Server indicated an extension that was not requested")}try{g.accept(t[Ig.extensionName])}catch(t){return void Yg(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Ig.extensionName]=g}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(h,e):h.end()}function qg(e,t){e._readyState=Vg.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function Kg(e){return e.path=e.socketPath,yg.connect(e)}function Jg(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=yg.isIP(e.host)?"":e.host),vg.connect(e)}function Yg(e,t,n){e._readyState=Vg.CLOSING;const r=new Error(n);Error.captureStackTrace(r,Yg),t.setHeader?(t[Fg]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(qg,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Xg(e,t,n){if(t){const n=Cg(t)?t.size:Ug(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Wg[e.readyState]})`);process.nextTick(n,t)}}function Zg(e,t){const n=this[Og];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[Og]&&(n._socket.removeListener("data",dh),process.nextTick(sh,n._socket),1005===e?n.close():n.close(e,t))}function Qg(){const e=this[Og];e.isPaused||e._socket.resume()}function eh(e){const t=this[Og];void 0!==t._socket[Og]&&(t._socket.removeListener("data",dh),process.nextTick(sh,t._socket),t.close(e[Pg])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function th(){this[Og].emitClose()}function nh(e,t){this[Og].emit("message",e,t)}function rh(e){const t=this[Og];t._autoPong&&t.pong(e,!this._isServer,Tg),t.emit("ping",e)}function ih(e){this[Og].emit("pong",e)}function sh(e){e.resume()}function oh(e){const t=this[Og];t.readyState!==Vg.CLOSED&&(t.readyState===Vg.OPEN&&(t._readyState=Vg.CLOSING,ah(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function ah(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),Rg)}function ch(){const e=this[Og];let t;this.removeListener("close",ch),this.removeListener("data",dh),this.removeListener("end",lh),e._readyState=Vg.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Og]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",th),e._receiver.on("finish",th))}function dh(e){this[Og]._receiver.write(e)||this.pause()}function lh(){const e=this[Og];e._readyState=Vg.CLOSING,e._receiver.end(),this.end()}function uh(){const e=this[Og];this.removeListener("error",uh),this.on("error",Tg),e&&(e._readyState=Vg.CLOSING,this.destroy())}const{tokenChars:ph}=yp;var gh={parse:function(e){const t=new Set;let n=-1,r=-1,i=0;for(;i<e.length;i++){const s=e.charCodeAt(i);if(-1===r&&1===ph[s])-1===n&&(n=i);else if(0===i||32!==s&&9!==s){if(44!==s)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${i}`);-1===r&&(r=i);const s=e.slice(n,r);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),n=r=-1}}else-1===r&&-1!==n&&(r=i)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const s=e.slice(n,i);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}};const hh=U,fh=F,{createHash:mh}=l,yh=gg,vh=dp,bh=gh,Sh=Hg,{GUID:wh,kWebSocket:Ih}=Gu,_h=/^[+/0-9A-Za-z]{22}==$/;var $h=class extends hh{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:Sh,...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=fh.createServer(((e,t)=>{const n=fh.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(Ch,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(Ch,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Ch(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",kh);const i=e.headers["sec-websocket-key"],s=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void xh(this,e,t,405,"Invalid HTTP method")}if(void 0===s||"websocket"!==s.toLowerCase()){return void xh(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!_h.test(i)){return void xh(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void xh(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Eh(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=bh.parse(a)}catch(n){return void xh(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const d=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==d){const n=new vh(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=yh.parse(d);e[vh.extensionName]&&(n.accept(e[vh.extensionName]),l[vh.extensionName]=n)}catch(n){return void xh(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const s={origin:e.headers[""+(8===o?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(s,((s,o,a,d)=>{if(!s)return Eh(t,o||401,a,d);this.completeUpgrade(l,i,c,e,t,n,r)}));if(!this.options.verifyClient(s))return Eh(t,401)}this.completeUpgrade(l,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,s,o){if(!i.readable||!i.writable)return i.destroy();if(i[Ih])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Eh(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${mh("sha1").update(t+wh).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[vh.extensionName]){const t=e[vh.extensionName].params,n=yh.format({[vh.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",kh),c.setSocket(i,s,{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(Ch,this)}))),o(c,r)}};function Ch(e){e._state=2,e.emit("close")}function kh(){this.destroy()}function Eh(e,t,n,r){n=n||fh.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} ${fh.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function xh(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,xh),e.emit("wsClientError",r,n,t)}else Eh(n,r,i)}var Ah=vd($h);const Nh=Dd("websocketServer"),Ph={},Oh=Su();let Th,Lh,Bh,Dh,jh;const Uh=e=>{const t=Ph[e];t&&t.socket.close()};var Rh={startServer:e=>{jh=new Ah({port:e,maxPayload:1048576e3}),jh.on("connection",(e=>{const t=Rd();Nh(`New client connected. Registered as "${t}"`),e.id=t,Ph[t]={socket:e,activeMessage:null},Th&&Th(t),e.on("message",(t=>{if(t instanceof Buffer){const n=Ph[e.id];Oh(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),Nh(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{Uh(n.socket.id)};if(t.command)return Nh(`Received command from client [${n.socket.id}]: ${t.command}`),void(Bh&&Bh(n.socket.id,t.command,r,i));t.klMessage&&Dh&&Dh({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",(()=>{Nh(`Client disconnected: ${e.id}`),Lh&&Lh(e.id),delete Ph[e.id]})),e.on("error",(()=>{Nh(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},stopServer:()=>{jh.close((()=>{console.log("WebSocket server stopped")}))},onClientConnected:e=>{Th=e},onClientDisconnected:e=>{Lh=e},onClientCommand:e=>{Bh=e},sendCommand:(e,t)=>{const n=Ph[e];if(!n)return Nh(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=Zl)return Nh("Message is too long to be a command. Use sendMessage instead."),!1;const r=gu.encodeCommand(t);return n.socket.send(r),!0},onMessageReceived:e=>Dh=e,terminateConnection:Uh};const Fh=Dd("stopService"),Mh=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=ml.getAllServiceVersions(t);Fh(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await ml.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},Wh=Dd("removeService"),Gh=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=ml.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),Wh(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await ml.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},Vh=Dd("launchService"),Hh=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=Zd();Vh(`Loading service ${t}@${n} from ${i}`);const{errorMsg:s,service:o,errorCode:a}=await ml.loadAndLaunch(i,r,!1);if(s||"started"!==o?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${s||"error-not-provided"}`,errCode:a});const c=Date.now(),d=3e4,l=async()=>{const r=o.status;return"running"===r?(Vh(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(Vh(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${o.errorMsg||"failed to initiate"}"`}):Date.now()-c>d?e.reply({error:"Timeout waiting for service to start"}):(Vh("Retrying in 1 second..."),void setTimeout(l,1e3)))};l()}catch(r){return Vh(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},zh=Dd("getMatchingServices"),qh=async e=>{const t=e.args[0],n=[],r=[];zh(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=ml.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:ml.getServiceRootDirectory(t)}):r.push({name:e,version:i})}zh(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},Kh=Dd("getSecretsValues");let Jh;var Yh=async e=>{const t=e.args[0].services;if(!Jh)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");Kh(`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 Jh({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})},Xh=e=>{Jh=e};const Zh=Dd("getMappedSecrets");let Qh;var ef=async e=>{const t=e.args[0].services;Zh(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await Qh(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})},tf=e=>{Qh=e};const nf=Dd("getServiceContents"),rf=({reply:e,args:t})=>{const[n]=t;nf(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=ml.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}]})}nf(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let sf={globalApiKey:void 0};const of=()=>({...sf}),af=()=>{const e=of();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},cf=async(e,t)=>{try{const n=await fetch(e,{method:"POST",body:JSON.stringify(t)});return n.ok?{data:await n.json(),statusCode:n.status,success:!0}:{statusCode:n.status,error:await n.text(),success:!1}}catch(e){return{statusCode:500,error:e instanceof Error?e.message:"Internal server error",success:!1}}},df={},lf=async e=>{const t=(e=>{const t=df[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 cf(`${af()}/v1/validate/validate_key`,{apiKey:e});return n?(console.warn(`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&&(df[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}},uf=Dd("activeClients");let pf={},gf={};const hf=(e,t)=>`${e}_${t}`,ff=e=>pf[e]||null,mf=(e,t)=>{const n=hf(e,t);return gf[n]||[]},yf=()=>{for(const e in pf){const t=pf[e];if(t?.transport===ed.WS){const e=gu.encodeCommand(Xc.ServicesListChanged);t.send(e)}}},vf=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:s,extraInfo:o,isDevClient:a}=e,c=e=>{console.warn(e),s&&s()};if(r===ed.WS){if(!o.wsApiKey)return void c(`Attempted to register a WebSocket client without an API key. SessionId: ${n}`);const{valid:e,error:t}=await lf(o.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&uf(`Unable to validate API Key, usage will be limited. SessionId: ${n}`)}pf[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:i,extraInfo:o,terminate:()=>{s&&s()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=hf(e.serviceName,e.version);gf[r]=gf[r]||[];return gf[r].some((e=>e.serviceId===n))||gf[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=hf(e.serviceName,e.version),s=gf[i]?.findIndex((e=>e.serviceId===n));if(-1!==s&&(gf[i]?.splice(s,1),!gf[i]?.length)){const t=ml.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=ff(t.info.sessionId);e?.extraInfo.ipcSocketId&&Tu(e?.extraInfo.ipcSocketId,Xc.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=hf(e.targetService.serviceName,e.targetService.version),r=gf[t]?.findIndex((e=>e.serviceId===n));-1!==r&&gf[t]?.splice(r,1)}t.length=0}},r===ed.IPC&&(yf(),Sf(n))},bf=()=>{const e=Object.values(pf);for(const t of e)if(t.transport===ed.IPC){const e=t.extraInfo.ipcSocketId,n=ml.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){mf(n.info.name,n.info.version).length||e&&Tu(e,Xc.BroadcastEnd)}}},Sf=e=>{const t=ml.getServiceBySessionId(e);if(t?.info.eventEmitter){if(mf(t.info.name,t.info.version).length){const t=ff(e);t?.extraInfo.ipcSocketId&&Tu(t?.extraInfo.ipcSocketId,Xc.BroadcastStart)}}},wf=e=>{const t=pf[e];delete pf[e],t?.transport===ed.IPC?yf():(t?.removeAllSubscriptions(),bf())},If=Dd("ipc:handleIpcClientCommand"),_f=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(Xc.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 If(`Ignoring ACK response from IPC service ${e} with no service id`);If(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(Lu(e,t),r=t);let i=!1;t&&(i=ml.setServiceStatus(t,"running")),i?vf({serviceSessionId:t||e,transport:ed.IPC,send:n,extraInfo:{ipcSocketId:t}}):Tu(r,Xc.SendManifest)}));!r&&If(`Received unknown command [${t}] from service ${e}`)};let $f={};G.platform();const Cf=async e=>{const t=e.args[0];if($f.chooseDirectory)try{const n=await $f.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"})},kf=async e=>{const t=e.args[0];if($f.chooseFile)try{const n=await $f.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"})},Ef=e=>{$f=e};var xf={},Af={},Nf={};function Pf(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Of(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Tf(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Lf(e,...t){if(!Tf(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 Bf(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Pf(e.outputLen),Pf(e.blockLen)}function Df(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 jf(e,t){Lf(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(Nf,"__esModule",{value:!0}),Nf.output=Nf.exists=Nf.hash=Nf.bytes=Nf.bool=Nf.number=Nf.isBytes=void 0,Nf.number=Pf,Nf.bool=Of,Nf.isBytes=Tf,Nf.bytes=Lf,Nf.hash=Bf,Nf.exists=Df,Nf.output=jf;const Uf={number:Pf,bool:Of,bytes:Lf,hash:Bf,exists:Df,output:jf};Nf.default=Uf;var Rf={};Object.defineProperty(Rf,"__esModule",{value:!0}),Rf.add5L=Rf.add5H=Rf.add4H=Rf.add4L=Rf.add3H=Rf.add3L=Rf.add=Rf.rotlBL=Rf.rotlBH=Rf.rotlSL=Rf.rotlSH=Rf.rotr32L=Rf.rotr32H=Rf.rotrBL=Rf.rotrBH=Rf.rotrSL=Rf.rotrSH=Rf.shrSL=Rf.shrSH=Rf.toBig=Rf.split=Rf.fromBig=void 0;const Ff=BigInt(2**32-1),Mf=BigInt(32);function Wf(e,t=!1){return t?{h:Number(e&Ff),l:Number(e>>Mf&Ff)}:{h:0|Number(e>>Mf&Ff),l:0|Number(e&Ff)}}function Gf(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=Wf(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}Rf.fromBig=Wf,Rf.split=Gf;const Vf=(e,t)=>BigInt(e>>>0)<<Mf|BigInt(t>>>0);Rf.toBig=Vf;const Hf=(e,t,n)=>e>>>n;Rf.shrSH=Hf;const zf=(e,t,n)=>e<<32-n|t>>>n;Rf.shrSL=zf;const qf=(e,t,n)=>e>>>n|t<<32-n;Rf.rotrSH=qf;const Kf=(e,t,n)=>e<<32-n|t>>>n;Rf.rotrSL=Kf;const Jf=(e,t,n)=>e<<64-n|t>>>n-32;Rf.rotrBH=Jf;const Yf=(e,t,n)=>e>>>n-32|t<<64-n;Rf.rotrBL=Yf;const Xf=(e,t)=>t;Rf.rotr32H=Xf;const Zf=e=>e;Rf.rotr32L=Zf;const Qf=(e,t,n)=>e<<n|t>>>32-n;Rf.rotlSH=Qf;const em=(e,t,n)=>t<<n|e>>>32-n;Rf.rotlSL=em;const tm=(e,t,n)=>t<<n-32|e>>>64-n;Rf.rotlBH=tm;const nm=(e,t,n)=>e<<n-32|t>>>64-n;function rm(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}Rf.rotlBL=nm,Rf.add=rm;const im=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);Rf.add3L=im;const sm=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;Rf.add3H=sm;const om=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);Rf.add4L=om;const am=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;Rf.add4H=am;const cm=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);Rf.add5L=cm;const dm=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0;Rf.add5H=dm;const lm={fromBig:Wf,split:Gf,toBig:Vf,shrSH:Hf,shrSL:zf,rotrSH:qf,rotrSL:Kf,rotrBH:Jf,rotrBL:Yf,rotr32H:Xf,rotr32L:Zf,rotlSH:Qf,rotlSL:em,rotlBH:tm,rotlBL:nm,add:rm,add3L:im,add3H:sm,add4L:om,add4H:am,add5H:dm,add5L:cm};Rf.default=lm;var um={},pm={};Object.defineProperty(pm,"__esModule",{value:!0}),pm.crypto=void 0,pm.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
|
|
2
2
|
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3
|
-
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=um,n=Af;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={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function s(e){return e>=i._0&&e<=i._9?e-i._0:e>=i._A&&e<=i._F?e-(i._A-10):e>=i._a&&e<=i._f?e-(i._a-10):void 0}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=s(e.charCodeAt(i)),o=s(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};function o(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function a(e){return"string"==typeof e&&(e=o(e)),(0,n.bytes)(e),e}e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let i=Date.now();for(let s=0;s<t;s++){r(s);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=o,e.toBytes=a,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 c={}.toString;e.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==c.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(a(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(a(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(a(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")}}(dm),Object.defineProperty(xf,"__esModule",{value:!0}),xf.shake256=xf.shake128=xf.keccak_512=xf.keccak_384=xf.keccak_256=xf.keccak_224=xf.sha3_512=xf.sha3_384=xf.sha3_256=xf.sha3_224=xf.Keccak=xf.keccakP=void 0;const pm=Af,gm=Uf,hm=dm,fm=[],mm=[],ym=[],vm=BigInt(0),bm=BigInt(1),Sm=BigInt(2),wm=BigInt(7),Im=BigInt(256),_m=BigInt(113);for(let e=0,t=bm,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],fm.push(2*(5*r+n)),mm.push((e+1)*(e+2)/2%64);let i=vm;for(let e=0;e<7;e++)t=(t<<bm^(t>>wm)*_m)%Im,t&Sm&&(i^=bm<<(bm<<BigInt(e))-bm);ym.push(i)}const[$m,Cm]=(0,gm.split)(ym,!0),km=(e,t,n)=>n>32?(0,gm.rotlBH)(e,t,n):(0,gm.rotlSH)(e,t,n),Em=(e,t,n)=>n>32?(0,gm.rotlBL)(e,t,n):(0,gm.rotlSL)(e,t,n);function xm(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,s=n[i],o=n[i+1],a=km(s,o,1)^n[r],c=Em(s,o,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=mm[n],s=km(t,i,r),o=Em(t,i,r),a=fm[n];t=e[a],i=e[a+1],e[a]=s,e[a+1]=o}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]^=$m[r],e[1]^=Cm[r]}n.fill(0)}xf.keccakP=xm;class Am extends hm.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,pm.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,hm.u32)(this.state)}keccak(){hm.isLE||(0,hm.byteSwap32)(this.state32),xm(this.state32,this.rounds),hm.isLE||(0,hm.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,pm.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,hm.toBytes)(e)).length;for(let i=0;i<r;){const s=Math.min(t-this.pos,r-i);for(let t=0;t<s;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,pm.exists)(this,!1),(0,pm.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 s=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+s),r),this.posOut+=s,r+=s}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,pm.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,pm.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:s}=this;return e||(e=new Am(t,n,r,s,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=s,e.destroyed=this.destroyed,e}}xf.Keccak=Am;const Nm=(e,t,n)=>(0,hm.wrapConstructor)((()=>new Am(t,e,n)));xf.sha3_224=Nm(6,144,28),xf.sha3_256=Nm(6,136,32),xf.sha3_384=Nm(6,104,48),xf.sha3_512=Nm(6,72,64),xf.keccak_224=Nm(1,144,28),xf.keccak_256=Nm(1,136,32),xf.keccak_384=Nm(1,104,48),xf.keccak_512=Nm(1,72,64);const Pm=(e,t,n)=>(0,hm.wrapXOFConstructorWithOpts)(((r={})=>new Am(t,e,void 0===r.dkLen?n:r.dkLen,!0)));xf.shake128=Pm(31,168,16),xf.shake256=Pm(31,136,32);const{sha3_512:Om}=xf,Tm=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function Lm(e){let t=0n;for(const n of e.values()){t=(t<<8n)+BigInt(n)}return t}const Bm=(e="")=>Lm(Om(e)).toString(36).slice(1),Dm=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),jm=({globalObj:e=(void 0!==ml?ml:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Tm(32,t):Tm(32,t);return Bm(r).substring(0,32)},Um=e=>()=>e++,Rm=({random:e=Math.random,counter:t=Um(Math.floor(476782367*e())),length:n=24,fingerprint:r=jm({random:e})}={})=>function(){const i=(e=>Dm[Math.floor(e()*Dm.length)])(e),s=Date.now().toString(36),o=t().toString(36),a=Tm(n,e);return`${i+Bm(`${s+a+o+r}`).substring(1,n)}`},Fm=Rm();Ef.getConstants=()=>({defaultLength:24,bigLength:32}),Ef.init=Rm,Ef.createId=Fm,Ef.bufToBigInt=Lm,Ef.createCounter=Um,Ef.createFingerprint=jm,Ef.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:Mm,init:Wm,getConstants:Gm,isCuid:Vm}=Ef;var Hm=Mm;const zm=Bl("getUniqueId"),qm=({reply:e,sourceServiceId:t})=>{zm(`Generating unique id for service "${t}"`);return e({success:[Hm()]})},Km=Bl("getActiveServices"),Jm=async({transport:e,sourceServiceId:t,reply:n})=>{if(Km(`Received GetServices request from ${e} [${t}]`),e===Qc.WS){let e=fd.getActiveServices();const r=hf(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===Qc.WS){if(!r?.extraInfo.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(fd.isInternalKemuService),s=e.filter((e=>e.devMode&&fd.isNotInternalKemuService(e))),o=e.filter((e=>fd.isOfficialKemuService(e)&&fd.isNotInternalKemuService(e)&&fd.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=await(async e=>{const{features:t}=await lf(e);return t})(r.extraInfo.wsApiKey),c=a?.hub_services??0,l=o.slice(0,-1!==c?c:o.length);i=o.slice(c).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,...s,...l]}const s=fd.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:fd.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:s,installed:i}]})}};let Ym="runtime",Xm=null;const Zm=()=>Ym,Qm=Bl("getSystemInfo"),ey=async({reply:e})=>{Qm("Received GetSystemInfo request");e({success:[await(async()=>({platformArch:`${"win32"===process.platform?"win":"darwin"===process.platform?"osx":""}-${(()=>{switch(process.arch){case"x64":return"x64";case"ia32":return"x86";case"arm":return"arm";case"arm64":return"arm64";default:return""}})()}`,isDesktopHub:"desktop"===Zm(),isRuntimeHub:"runtime"===Zm(),hubVersion:Wl,...Xm?{updateAvailable:Xm}:{}}))()]})},ty=Bl("removeService"),ny=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,s=r.version;if(!i)return n({error:"No service name provided"});if(!s)return n({error:"No service version provided"});const o=fd.getAllServiceVersions(i),a=o.find((e=>e.info.version===s));if(!a)return n({error:"Service not found"});ty(`Removing ${o.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await fd.uninstallService(a.info.name,a.info.version),c){const e=hf(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});ty(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await af(`${of()}/v1/validate/uninstall_hub_service`,e);if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(ty(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:s}}]})},ry=Bl("getDecryptedEdgeApiKey"),iy=({reply:e})=>{ry("Getting decrypted edge API key");return e({success:[sf().globalApiKey]})},sy=v(W(import.meta.url)),oy=Bl("hub"),ay=new function(e){const t={};let n=console.log;const r={};let i=e||String(Date.now());const s={},o=e=>!s[e],a=(e,t,n,r,i,s)=>{let a=Qd?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return o(r)&&(a=ju.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,i,s,o)=>{if(!o)return!1;const c=o;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=r[c.functionName];if(t){const n=e=>{a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:s.sourceServiceId,send:i})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,s,a,c,l)=>{if(!s){const e="No send buffer function provided.";throw n&&n(e),e}Uu+=1;const d=`${i}-${Uu}-exec-${e.substring(0,10)}`,u={messageId:d,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};u.promise=new Promise(((e,t)=>{u.resolve=e,u.reject=t}));let p=Qd?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:r,messageId:d,type:"execute"}};o(c)&&(p=ju.encode(g,a,c)),t[d]=u,n&&n(`Calling remote function "${e}" with message id "${d}"`);const h="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(u.fulfilled=!0,u.resolve([void 0]),delete t[d]):0===l?.timeout||h||(u.timer=setTimeout((()=>{n&&n(`Remote function ${d} timed out`);const r=t[d];r&&!r.fulfilled&&(r.fulfilled=!0,u.reject(`Function ${e} Timed out`)),delete t[d]}),l?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:g}),u.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,s)=>{Uu+=1;const a=`${i}-${Uu}-multicast-${e.substring(0,10)}`;let c=Qd?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let d=o(r[0].serviceId);d&&(c=ju.encode(l,s,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&&(d=o(i.serviceId),d&&(c=ju.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:s,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("hub");ay.setLogger(oy);const cy={[Xc.RebootToInstallUpdate]:null,[Xc.GetFileContentFromCacheId]:null},ly=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=hf(n.targetServiceId);if(!r)return oy(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,Qc.IPC;const i=t.json?.messageId;return oy(`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},dy=({sourceServiceId:e,args:t})=>{const n=fd.getServiceBySessionId(e);if(n){const r=ff(n.info.name,n.info.version),i=ff(n.info.name,"*");if(!r.length&&!i.length)return;const s=[...r,...i],o={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};ay.broadcast(Xc.BroadcastEvent,[o],s,0)}},uy=e=>{const{send:t,transmission:n,json:r}=e;oy(`Raw message Id received from WS: ${r?.messageId}`);ly(Qc.WS,e)||ay.processMessage(Qc.WS,t,n,r)},py=e=>{const t=(n=e,`${Yc.SocketAcknowledge}${n}`);var n;Uh.sendCommand(e,t)},gy=(e,t)=>{oy(`Received unknown command [${t}] from service ${e}`)},hy=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,s=n,o=sf().globalApiKey||t[0]?.apiKey;await yf({serviceSessionId:n,transport:Qc.WS,send:r,terminateFn:()=>{Uh.terminateConnection(n)},extraInfo:{websocketId:s,wsApiKey:o}}),i({success:[]})},fy=e=>{oy(`WS Client ${e} disconnected`),Sf(e)},my=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==Qc.IPC){var i;oy(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=fd.getMatchingDevService(n.name,n.version,"stopped");if(t){oy(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const s=hf(t.info.sessionId);if(!s)return void oy(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);s.send=r,uf[i=e]?delete uf[i]:df(`Could not find source client with session id ${i}`),Tu(e,t.info.sessionId);const o=await ql(n,n.path);t.info={...t.info,...o},oy(`Updating manifest for dev service ${t.info.sessionId}`),fd.setServiceManifest(t.info.sessionId,o,"running"),oy(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Ou(t.info.sessionId,(e=>`${Yc.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=uf[e];t?t.isDevClient?(t.disconnected=!1,t.transport===Qc.IPC&&(mf(),bf(e))):df(`Client with session id ${e} is not a dev client`):df(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{fd.addDevService(e,n,"running");const t=hf(e);t?t.isDevClient=!0:yf({serviceSessionId:e,transport:Qc.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}oy(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var yy=async e=>{var t;oy("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",Ym=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=>{rf={...rf,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey}),ay.registerFunction(Xc.GetServiceContents,nf),ay.registerFunction(Xc.GetServices,Jm),ay.registerFunction(Xc.GetSystemInfo,ey),ay.registerFunction(Xc.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"})})),ay.registerFunction(Xc.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Qc.WS){const[e]=n,i=hf(r);if(!i)return t({error:`Session id "${r}" not found`});oy(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),ay.registerFunction(Xc.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Qc.WS){const[e]=n,i=hf(r),s=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(oy(`Service ${r} subscribing to "${s.serviceName} (${s.version})"`),"hub"===s.serviceName)return i.addSubscription(s),void t({success:[]});if(!i.addSubscription(s))return oy(`Service ${r} already subscribed to "${s.serviceName} (${s.version})", ignoring request.`),t({success:[]});const o=fd.getMatchingService(s.serviceName,s.version);if(!o)return oy(`Service ${s.serviceName} ${s.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return oy(`Service ${s.serviceName} ${s.version} does not have an event emitter, removing subscription`),i.removeSubscription(s),t({error:`Service "${s.serviceName} (${s.version})" does not produce events`});const a=hf(o.info.sessionId);return a?.extraInfo.ipcSocketId&&(oy(`Sending Broadcast START command to service ${o.info.sessionId}`),Ou(a?.extraInfo.ipcSocketId,Yc.BroadcastStart)),t({success:[]})}})),ay.registerFunction("stopService",Fh),ay.registerFunction("removeService",Wh),ay.registerFunction("launchService",Vh),ay.registerFunction("getMatchingServices",zh),ay.registerFunction("getSecretsValues",Jh),ay.registerFunction(Xc.GetMappedSecrets,Qh),ay.registerFunction(Xc.BroadcastEvent,dy),ay.registerFunction(Xc.ServiceManifest,my),ay.registerFunction(Xc.ChooseDirectoryDialog,$f),ay.registerFunction(Xc.ChooseFileDialog,Cf),ay.registerFunction(Xc.GetUniqueId,qm),ay.registerFunction(Xc.GetDecryptedEdgeApiKey,iy),ay.registerFunction(Xc.SocketAckResponse,hy),ay.registerFunction(Xc.UninstallService,ny),Object.entries(cy).forEach((([e,t])=>{t?ay.registerFunction(e,t):(oy(`Skipping registration of "${e}" because it's not implemented`),ay.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),Pu((e=>{const{send:t,transmission:n,json:r}=e;oy(`Raw message Id received from IPC: ${r?.messageId}`);ly(Qc.IPC,e)||ay.processMessage(Qc.IPC,t,n,r)})),Uh.onMessageReceived(uy),Uh.onClientConnected(py),Uh.onClientCommand(gy),Uh.onClientDisconnected(fy),Lu(If),Au((e=>{const t=(e=>`${Yc.IpcAcknowledge}${e}`)(e);Ou(e,t)})),Nu((e=>{oy(`IPC socket [${e}] disconnected`);const t=hf(e);if(t){oy(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=fd.getServiceBySessionId(t.serviceSessionId);fd.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,mf()):Sf(t.serviceSessionId)}})),await xu({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await Uh.startServer(e?.ws?.port||5368);const i=e?.defaultServicesPath||m.resolve(sy,"defaultServices"),s=process.env.DEV_SESSION_ID;fd.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),e?.servicesInstallPath&&(e=>{Jl=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Yl=e})(e.testServicesInstallPath);const o=Xl(),a=Yl||Fl,c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=o,t.__KEMU_USER_TEST_SERVICES_PATH=a,t.__KEMU_SERVICE_URL=sf().serviceUrl,t},l=async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{});e?.getServiceSecretsFn?(fd.setGetSecretsFunction(e.getServiceSecretsFn),Yh(e.getServiceSecretsFn)):(fd.setGetSecretsFunction(c),Yh(c)),ef(e?.getMappedSecretsFn?e.getMappedSecretsFn:l),fd.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return V("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await fd.loadServices(i,{fixedSession:s?parseInt(s):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0}),null!==e?.servicesInstallPath&&(await Kl(o)||await S(o,{recursive:!0}),await fd.loadServices(o,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME}));const d=process.env.DEV_NO_SPAWN_LIST?.split(",");await fd.launchServices({noSpawningList:d||[]}),oy("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&kf({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},vy=e=>{if(e===Qc.WS)return{handleWebsocketConnectionEvent:py,handleWebsocketClientDisconnectionEvent:fy,handleWebsocketMessage:uy,handleWebsocketClientCommand:gy,getRemoteInvoke:()=>ay}},by=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(fd.getAllServices().every((e=>"running"===e.status))){if(e.every((e=>"running"===fd.getMatchingService(e.name,e.version)?.status)))return n()}t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let Sy;const wy=ec("run"),Iy=nl(),_y=1e3,$y=k(process.argv.slice(2));global.ImageData=K,$e({createCanvas:(e,t)=>Y(e,t),loadImage:async e=>{const t=await J(e),n=Y(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}});const Cy={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:da.ImageData}},loadImageFile:async e=>{const t=await J(e),n=Y(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=Y(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 ky={start:async r=>{r=r||{};const i=r?.recipePath||$y.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].");e({path:H(z(i),".env")});const 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 o=i.endsWith(".json")||i.endsWith(".kemu"),a=o?q(i):i,c=o?i:H(a,"recipe.kemu"),l=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(z(c),"utf-8"));if(!l)throw new Error("Failed to parse recipe file");const{serviceUrl:d,apiKey:u}=((e,t)=>{const n=ca(e,t),r=Buffer.from(n,"base64").toString("utf8"),[i,s]=r.split("<@>");if(!s||!i)throw new Error("Invalid API key.");return{serviceUrl:s,apiKey:i}})(l,s);await ks();const p={id:l.id||String(Date.now()),version:1,author:""};(e=>{Or=e})(console);const g=vy(we.WS),h=(e,t)=>{if(t)g?.handleWebsocketMessage({send:m,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;g?.handleWebsocketClientCommand(_y,t)}},f=(Ma={instanceServiceId:_y,sendBuf:h,sendCmd:h,triggerOnCommand:(...e)=>Wa(...e),triggerOnConnected:()=>Ga(),triggerOnDisconnected:()=>Va(),triggerOnMessageReceived:(...e)=>Ha(...e)},Ma);const m=(e,t)=>{if(t)f.triggerOnMessageReceived({send:h,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;f.triggerOnCommand(t)}},y=il(),v=g.getRemoteInvoke();y.disableServiceEncoding(0,!0),v.disableServiceEncoding(_y,!0);const b=Object.values(l.blocks[ge].gates).filter((e=>e.type===ze.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),S=b.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),w=H(a,"services"),I=await n(w).then((()=>!0)).catch((()=>!1));await yy({globalApiKey:u,serviceUrl:d,recipeRootPath:a,servicesInstallPath:I?H(a,"services"):null,noDefaultServices:!0,ws:{disabled:!0},ipc:{appSpace:"kemu-runner.",id:p.id}}),wy("Waiting for services to run"),await by(S),wy("All services are running"),ia(Iy);const _=await ta(l,"runner",p.version,p.author,Vo.Desktop);return Sy=_,rl(_),await el(u),new Promise(((e,t)=>{var n;tl("acknowledged",(async()=>{await Iy.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await ra(_);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)})),wy("Recipe started"),e({sendToInputWidget:(e,t)=>"number"==typeof t?r(e,{type:fe.Number,value:t}):"string"==typeof t?r(e,{type:fe.String,value:t}):"boolean"==typeof t?r(e,{type:fe.Boolean,value:t}):Array.isArray(t)?r(e,{type:fe.Array,value:t}):r(e,t)})})),f.triggerOnConnected(),f.triggerOnCommand((n=_y,`${ve.SocketAcknowledge}${n}`))}))},terminate:async()=>{Sy&&await na(Sy)},onVariableChange:(e,t)=>kr(e,t)};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{fe as DataType,ky as default,Cy as utils};
|
|
3
|
+
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=pm,n=Nf;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={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function s(e){return e>=i._0&&e<=i._9?e-i._0:e>=i._A&&e<=i._F?e-(i._A-10):e>=i._a&&e<=i._f?e-(i._a-10):void 0}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=s(e.charCodeAt(i)),o=s(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};function o(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function a(e){return"string"==typeof e&&(e=o(e)),(0,n.bytes)(e),e}e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let i=Date.now();for(let s=0;s<t;s++){r(s);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=o,e.toBytes=a,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 c={}.toString;e.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==c.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(a(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(a(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(a(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")}}(um),Object.defineProperty(Af,"__esModule",{value:!0}),Af.shake256=Af.shake128=Af.keccak_512=Af.keccak_384=Af.keccak_256=Af.keccak_224=Af.sha3_512=Af.sha3_384=Af.sha3_256=Af.sha3_224=Af.Keccak=Af.keccakP=void 0;const gm=Nf,hm=Rf,fm=um,mm=[],ym=[],vm=[],bm=BigInt(0),Sm=BigInt(1),wm=BigInt(2),Im=BigInt(7),_m=BigInt(256),$m=BigInt(113);for(let e=0,t=Sm,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],mm.push(2*(5*r+n)),ym.push((e+1)*(e+2)/2%64);let i=bm;for(let e=0;e<7;e++)t=(t<<Sm^(t>>Im)*$m)%_m,t&wm&&(i^=Sm<<(Sm<<BigInt(e))-Sm);vm.push(i)}const[Cm,km]=(0,hm.split)(vm,!0),Em=(e,t,n)=>n>32?(0,hm.rotlBH)(e,t,n):(0,hm.rotlSH)(e,t,n),xm=(e,t,n)=>n>32?(0,hm.rotlBL)(e,t,n):(0,hm.rotlSL)(e,t,n);function Am(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,s=n[i],o=n[i+1],a=Em(s,o,1)^n[r],c=xm(s,o,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=ym[n],s=Em(t,i,r),o=xm(t,i,r),a=mm[n];t=e[a],i=e[a+1],e[a]=s,e[a+1]=o}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]^=Cm[r],e[1]^=km[r]}n.fill(0)}Af.keccakP=Am;class Nm extends fm.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,gm.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,fm.u32)(this.state)}keccak(){fm.isLE||(0,fm.byteSwap32)(this.state32),Am(this.state32,this.rounds),fm.isLE||(0,fm.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,gm.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,fm.toBytes)(e)).length;for(let i=0;i<r;){const s=Math.min(t-this.pos,r-i);for(let t=0;t<s;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,gm.exists)(this,!1),(0,gm.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 s=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+s),r),this.posOut+=s,r+=s}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,gm.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,gm.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:s}=this;return e||(e=new Nm(t,n,r,s,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=s,e.destroyed=this.destroyed,e}}Af.Keccak=Nm;const Pm=(e,t,n)=>(0,fm.wrapConstructor)((()=>new Nm(t,e,n)));Af.sha3_224=Pm(6,144,28),Af.sha3_256=Pm(6,136,32),Af.sha3_384=Pm(6,104,48),Af.sha3_512=Pm(6,72,64),Af.keccak_224=Pm(1,144,28),Af.keccak_256=Pm(1,136,32),Af.keccak_384=Pm(1,104,48),Af.keccak_512=Pm(1,72,64);const Om=(e,t,n)=>(0,fm.wrapXOFConstructorWithOpts)(((r={})=>new Nm(t,e,void 0===r.dkLen?n:r.dkLen,!0)));Af.shake128=Om(31,168,16),Af.shake256=Om(31,136,32);const{sha3_512:Tm}=Af,Lm=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function Bm(e){let t=0n;for(const n of e.values()){t=(t<<8n)+BigInt(n)}return t}const Dm=(e="")=>Bm(Tm(e)).toString(36).slice(1),jm=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),Um=({globalObj:e=(void 0!==yd?yd:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Lm(32,t):Lm(32,t);return Dm(r).substring(0,32)},Rm=e=>()=>e++,Fm=({random:e=Math.random,counter:t=Rm(Math.floor(476782367*e())),length:n=24,fingerprint:r=Um({random:e})}={})=>function(){const i=(e=>jm[Math.floor(e()*jm.length)])(e),s=Date.now().toString(36),o=t().toString(36),a=Lm(n,e);return`${i+Dm(`${s+a+o+r}`).substring(1,n)}`},Mm=Fm();xf.getConstants=()=>({defaultLength:24,bigLength:32}),xf.init=Fm,xf.createId=Mm,xf.bufToBigInt=Bm,xf.createCounter=Rm,xf.createFingerprint=Um,xf.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:Wm,init:Gm,getConstants:Vm,isCuid:Hm}=xf;var zm=Wm;const qm=Dd("getUniqueId"),Km=({reply:e,sourceServiceId:t})=>{qm(`Generating unique id for service "${t}"`);return e({success:[zm()]})},Jm=Dd("getActiveServices"),Ym=async({transport:e,sourceServiceId:t,reply:n})=>{if(Jm(`Received GetServices request from ${e} [${t}]`),e===ed.WS){let e=ml.getActiveServices();const r=ff(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===ed.WS){if(!r?.extraInfo.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(ml.isInternalKemuService),s=e.filter((e=>e.devMode&&ml.isNotInternalKemuService(e))),o=e.filter((e=>ml.isOfficialKemuService(e)&&ml.isNotInternalKemuService(e)&&ml.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=await(async e=>{const{features:t}=await lf(e);return t})(r.extraInfo.wsApiKey),c=a?.hub_services??0,d=o.slice(0,-1!==c?c:o.length);i=o.slice(c).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,...s,...d]}const s=ml.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:ml.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:s,installed:i}]})}};let Xm="runtime",Zm=null;const Qm=()=>Xm,ey=Dd("getSystemInfo"),ty=async({reply:e})=>{ey("Received GetSystemInfo request");e({success:[await(async()=>({platformArch:`${"win32"===process.platform?"win":"darwin"===process.platform?"osx":""}-${(()=>{switch(process.arch){case"x64":return"x64";case"ia32":return"x86";case"arm":return"arm";case"arm64":return"arm64";default:return""}})()}`,isDesktopHub:"desktop"===Qm(),isRuntimeHub:"runtime"===Qm(),hubVersion:Gd,...Zm?{updateAvailable:Zm}:{}}))()]})},ny=Dd("removeService"),ry=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,s=r.version;if(!i)return n({error:"No service name provided"});if(!s)return n({error:"No service version provided"});const o=ml.getAllServiceVersions(i),a=o.find((e=>e.info.version===s));if(!a)return n({error:"Service not found"});ny(`Removing ${o.length} service(s) with name: ${i}`);const c=a.info.publicationId;let d;if(await ml.uninstallService(a.info.name,a.info.version),c){const e=ff(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});ny(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await cf(`${af()}/v1/validate/uninstall_hub_service`,e);if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(ny(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));d=i?.remaining}n({success:[{remaining:d,service:{name:i,version:s}}]})},iy=Dd("getDecryptedEdgeApiKey"),sy=({reply:e})=>{iy("Getting decrypted edge API key");return e({success:[of().globalApiKey]})},oy=v(W(import.meta.url)),ay=Dd("hub"),cy=new function(e){const t={};let n=console.log;const r={};let i=e||String(Date.now());const s={},o=e=>!s[e],a=(e,t,n,r,i,s)=>{let a=eu?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return o(r)&&(a=Uu.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,i,s,o)=>{if(!o)return!1;const c=o;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=r[c.functionName];if(t){const n=e=>{a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:s.sourceServiceId,send:i})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,s,a,c,d)=>{if(!s){const e="No send buffer function provided.";throw n&&n(e),e}Ru+=1;const l=`${i}-${Ru}-exec-${e.substring(0,10)}`,u={messageId:l,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};u.promise=new Promise(((e,t)=>{u.resolve=e,u.reject=t}));let p=eu?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:r,messageId:l,type:"execute"}};o(c)&&(p=Uu.encode(g,a,c)),t[l]=u,n&&n(`Calling remote function "${e}" with message id "${l}"`);const h="true"===process.env.NO_INVOKE_TIMEOUT;return d?.async?(u.fulfilled=!0,u.resolve([void 0]),delete t[l]):0===d?.timeout||h||(u.timer=setTimeout((()=>{n&&n(`Remote function ${l} timed out`);const r=t[l];r&&!r.fulfilled&&(r.fulfilled=!0,u.reject(`Function ${e} Timed out`)),delete t[l]}),d?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:g}),u.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,s)=>{Ru+=1;const a=`${i}-${Ru}-multicast-${e.substring(0,10)}`;let c=eu?new ArrayBuffer(0):Buffer.alloc(0);const d={json:{functionName:e,args:t,messageId:a,type:"execute"}};let l=o(r[0].serviceId);l&&(c=Uu.encode(d,s,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&&(l=o(i.serviceId),l&&(c=Uu.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:d,sourceServiceId:s,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("hub");cy.setLogger(ay);const dy={[Zc.RebootToInstallUpdate]:null,[Zc.GetFileContentFromCacheId]:null},ly=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=ff(n.targetServiceId);if(!r)return ay(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,ed.IPC;const i=t.json?.messageId;return ay(`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},uy=({sourceServiceId:e,args:t})=>{const n=ml.getServiceBySessionId(e);if(n){const r=mf(n.info.name,n.info.version),i=mf(n.info.name,"*");if(!r.length&&!i.length)return;const s=[...r,...i],o={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};cy.broadcast(Zc.BroadcastEvent,[o],s,0)}},py=e=>{const{send:t,transmission:n,json:r}=e;ay(`Raw message Id received from WS: ${r?.messageId}`);ly(ed.WS,e)||cy.processMessage(ed.WS,t,n,r)},gy=e=>{const t=(n=e,`${Xc.SocketAcknowledge}${n}`);var n;Rh.sendCommand(e,t)},hy=(e,t)=>{ay(`Received unknown command [${t}] from service ${e}`)},fy=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,s=n,o=of().globalApiKey||t[0]?.apiKey;await vf({serviceSessionId:n,transport:ed.WS,send:r,terminateFn:()=>{Rh.terminateConnection(n)},extraInfo:{websocketId:s,wsApiKey:o}}),i({success:[]})},my=e=>{ay(`WS Client ${e} disconnected`),wf(e)},yy=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==ed.IPC){var i;ay(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=ml.getMatchingDevService(n.name,n.version,"stopped");if(t){ay(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const s=ff(t.info.sessionId);if(!s)return void ay(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);s.send=r,pf[i=e]?delete pf[i]:uf(`Could not find source client with session id ${i}`),Lu(e,t.info.sessionId);const o=await Kd(n,n.path);t.info={...t.info,...o},ay(`Updating manifest for dev service ${t.info.sessionId}`),ml.setServiceManifest(t.info.sessionId,o,"running"),ay(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Tu(t.info.sessionId,(e=>`${Xc.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=pf[e];t?t.isDevClient?(t.disconnected=!1,t.transport===ed.IPC&&(yf(),Sf(e))):uf(`Client with session id ${e} is not a dev client`):uf(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{ml.addDevService(e,n,"running");const t=ff(e);t?t.isDevClient=!0:vf({serviceSessionId:e,transport:ed.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}ay(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var vy=async e=>{var t;ay("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",Xm=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=>{sf={...sf,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey}),cy.registerFunction(Zc.GetServiceContents,rf),cy.registerFunction(Zc.GetServices,Ym),cy.registerFunction(Zc.GetSystemInfo,ty),cy.registerFunction(Zc.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"})})),cy.registerFunction(Zc.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ed.WS){const[e]=n,i=ff(r);if(!i)return t({error:`Session id "${r}" not found`});ay(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),cy.registerFunction(Zc.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ed.WS){const[e]=n,i=ff(r),s=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(ay(`Service ${r} subscribing to "${s.serviceName} (${s.version})"`),"hub"===s.serviceName)return i.addSubscription(s),void t({success:[]});if(!i.addSubscription(s))return ay(`Service ${r} already subscribed to "${s.serviceName} (${s.version})", ignoring request.`),t({success:[]});const o=ml.getMatchingService(s.serviceName,s.version);if(!o)return ay(`Service ${s.serviceName} ${s.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return ay(`Service ${s.serviceName} ${s.version} does not have an event emitter, removing subscription`),i.removeSubscription(s),t({error:`Service "${s.serviceName} (${s.version})" does not produce events`});const a=ff(o.info.sessionId);return a?.extraInfo.ipcSocketId&&(ay(`Sending Broadcast START command to service ${o.info.sessionId}`),Tu(a?.extraInfo.ipcSocketId,Xc.BroadcastStart)),t({success:[]})}})),cy.registerFunction("stopService",Mh),cy.registerFunction("removeService",Gh),cy.registerFunction("launchService",Hh),cy.registerFunction("getMatchingServices",qh),cy.registerFunction("getSecretsValues",Yh),cy.registerFunction(Zc.GetMappedSecrets,ef),cy.registerFunction(Zc.BroadcastEvent,uy),cy.registerFunction(Zc.ServiceManifest,yy),cy.registerFunction(Zc.ChooseDirectoryDialog,Cf),cy.registerFunction(Zc.ChooseFileDialog,kf),cy.registerFunction(Zc.GetUniqueId,Km),cy.registerFunction(Zc.GetDecryptedEdgeApiKey,sy),cy.registerFunction(Zc.SocketAckResponse,fy),cy.registerFunction(Zc.UninstallService,ry),Object.entries(dy).forEach((([e,t])=>{t?cy.registerFunction(e,t):(ay(`Skipping registration of "${e}" because it's not implemented`),cy.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),Ou((e=>{const{send:t,transmission:n,json:r}=e;ay(`Raw message Id received from IPC: ${r?.messageId}`);ly(ed.IPC,e)||cy.processMessage(ed.IPC,t,n,r)})),Rh.onMessageReceived(py),Rh.onClientConnected(gy),Rh.onClientCommand(hy),Rh.onClientDisconnected(my),Bu(_f),Nu((e=>{const t=(e=>`${Xc.IpcAcknowledge}${e}`)(e);Tu(e,t)})),Pu((e=>{ay(`IPC socket [${e}] disconnected`);const t=ff(e);if(t){ay(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=ml.getServiceBySessionId(t.serviceSessionId);ml.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,yf()):wf(t.serviceSessionId)}})),await Au({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await Rh.startServer(e?.ws?.port||5368);const i=e?.defaultServicesPath||m.resolve(oy,"defaultServices"),s=process.env.DEV_SESSION_ID;ml.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),e?.servicesInstallPath&&(e=>{Yd=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Xd=e})(e.testServicesInstallPath);const o=Zd(),a=Xd||Md,c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=o,t.__KEMU_USER_TEST_SERVICES_PATH=a,t.__KEMU_SERVICE_URL=of().serviceUrl,t},d=async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{});e?.getServiceSecretsFn?(ml.setGetSecretsFunction(e.getServiceSecretsFn),Xh(e.getServiceSecretsFn)):(ml.setGetSecretsFunction(c),Xh(c)),tf(e?.getMappedSecretsFn?e.getMappedSecretsFn:d),ml.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return V("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await ml.loadServices(i,{fixedSession:s?parseInt(s):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0}),null!==e?.servicesInstallPath&&(await Jd(o)||await S(o,{recursive:!0}),await ml.loadServices(o,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await ml.launchServices({noSpawningList:l||[]}),ay("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&Ef({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},by=e=>{if(e===ed.WS)return{handleWebsocketConnectionEvent:gy,handleWebsocketClientDisconnectionEvent:my,handleWebsocketMessage:py,handleWebsocketClientCommand:hy,getRemoteInvoke:()=>cy}},Sy=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(ml.getAllServices().every((e=>"running"===e.status))){if(e.every((e=>"running"===ml.getMatchingService(e.name,e.version)?.status)))return n()}t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let wy;const Iy=tc("run"),_y=rd(),$y=1e3,Cy=k(process.argv.slice(2));global.ImageData=K,$e({createCanvas:(e,t)=>Y(e,t),loadImage:async e=>{const t=await J(e),n=Y(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}});const ky={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:ua.ImageData}},loadImageFile:async e=>{const t=await J(e),n=Y(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=Y(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 Ey={start:async r=>{r=r||{};const i=r?.recipePath||Cy.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].");e({path:H(z(i),".env")});const 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 o=i.endsWith(".json")||i.endsWith(".kemu"),a=o?q(i):i,c=o?i:H(a,"recipe.kemu"),d=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(z(c),"utf-8"));if(!d)throw new Error("Failed to parse recipe file");const{serviceUrl:l,apiKey:u}=((e,t)=>{const n=da(e,t),r=Buffer.from(n,"base64").toString("utf8"),[i,s]=r.split("<@>");if(!s||!i)throw new Error("Invalid API key.");return{serviceUrl:s,apiKey:i}})(d,s);await Es();const p={id:d.id||String(Date.now()),version:1,author:""};(e=>{Or=e})(console);const g=by(we.WS),h=(e,t)=>{if(t)g?.handleWebsocketMessage({send:m,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;g?.handleWebsocketClientCommand($y,t)}},f=(Wa={instanceServiceId:$y,sendBuf:h,sendCmd:h,triggerOnCommand:(...e)=>Ga(...e),triggerOnConnected:()=>Va(),triggerOnDisconnected:()=>Ha(),triggerOnMessageReceived:(...e)=>za(...e)},Wa);const m=(e,t)=>{if(t)f.triggerOnMessageReceived({send:h,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;f.triggerOnCommand(t)}},y=sd(),v=g.getRemoteInvoke();y.disableServiceEncoding(0,!0),v.disableServiceEncoding($y,!0);const b=Object.values(d.blocks[ge].gates).filter((e=>e.type===ze.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),S=b.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),w=H(a,"services"),I=await n(w).then((()=>!0)).catch((()=>!1));await vy({globalApiKey:u,serviceUrl:l,recipeRootPath:a,servicesInstallPath:I?H(a,"services"):null,noDefaultServices:!0,ws:{disabled:!0},ipc:{appSpace:"kemu-runner.",id:p.id}}),Iy("Waiting for services to run"),await Sy(S),Iy("All services are running"),sa(_y);const _=await na(d,"runner",p.version,p.author,Ho.Desktop);return wy=_,id(_),await td(u),new Promise(((e,t)=>{var n;nd("acknowledged",(async()=>{await _y.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await ia(_);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)})),Iy("Recipe started"),e({sendToInputWidget:(e,t)=>"number"==typeof t?r(e,{type:fe.Number,value:t}):"string"==typeof t?r(e,{type:fe.String,value:t}):"boolean"==typeof t?r(e,{type:fe.Boolean,value:t}):Array.isArray(t)?r(e,{type:fe.Array,value:t}):r(e,t)})})),f.triggerOnConnected(),f.triggerOnCommand((n=$y,`${ve.SocketAcknowledge}${n}`))}))},terminate:async()=>{wy&&await ra(wy)},onVariableChange:(e,t)=>kr(e,t)};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{fe as DataType,Ey as default,ky as utils};
|