@kemu-io/edge-runtime 0.1.21 → 0.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/runner.js +1 -1
package/package.json
CHANGED
package/runner.js
CHANGED
|
@@ -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"util";import a from"emittery";import"axios";import c from"jszip";import l,{scryptSync as u,createDecipheriv as d,createHash as p}from"crypto";import{satisfies as h}from"compare-versions";import f from"debug";import g,{join as m,dirname as v,resolve as y}from"path";import"node-ipc";import{mkdir as b,readFile as S,access as w,constants as I,readdir as _,rm as $}from"fs/promises";import C from"minimist";import k from"tty";import E,{homedir as x}from"os";import A from"net";import N from"tls";import O,{promises as P}from"fs";import L from"dgram";import T from"stream";import B from"zlib";import j from"buffer";import D from"events";import U from"https";import M from"http";import F,{fileURLToPath as R}from"url";import W from"node:os";import{spawn as G}from"child_process";import{join as V,resolve as H,dirname as z}from"node:path";import{ImageData as q,loadImage as K,createCanvas as J}from"@napi-rs/canvas";var Y;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(Y=Y||(Y={}));const X={};let Z=0,Q="";const ee=e=>X[e]?X[e]:null,te=(e,t)=>{const n=ee(e);if(!n)return n;return n.blocks[t]||null},ne=(e,t,n)=>{const r=te(e,t);if(!r)return r;return r.gates[n]},re=(e,t)=>{let n=r(4);for(;X[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!==Z){const t=new Date;Z=e,Q=t.toJSON()}return Q})()}:: ${e}\n`},i.dbInfo={...t},X[n]=i,n},ie="interrupt_port",se="main.js",oe="state.json",ae="{#}",ce="$var_",le="default";var ue,de,pe,he,fe,ge,me,ve;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(ue||(ue={})),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"}(de||(de={})),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"}(pe||(pe={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(he||(he={})),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:"}(fe||(fe={})),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.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId"}(ge||(ge={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(me||(me={})),function(e){e.IPC="ipc",e.WS="ws"}(ve||(ve={}));const ye="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,be="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,Se="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,we="-",Ie=`inner${we}`,_e=`outer${we}`,$e=`${_e}input${we}`,Ce=`${_e}output${we}`,ke=`${Ie}input${we}`,Ee=`${Ie}output${we}`,xe=e=>(new TextEncoder).encode(e),Ae=e=>e===ie,Ne=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Oe=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,Pe=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Le=e=>"number"==typeof e?de.Number:"string"==typeof e?de.String:"boolean"==typeof e?de.Boolean:Array.isArray(e)?de.Array:Ne(e)?de.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?de.AudioBuffer:e&&void 0!==e.byteLength?de.ArrayBuffer:Oe(e)?de.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?de.Point:de.JsonObj,Te=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Le(n[e]);t[e]=r}return t},Be=(e,t,n)=>"inner"===e?"input"===t?`${ke}${n}`:`${Ee}${n}`:"input"===t?`${$e}${n}`:`${Ce}${n}`,je=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]}},De=e=>new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace});var Ue,Me;!function(e){e.Action="action",e.CustomInput="customInput"}(Ue=Ue||(Ue={})),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"}(Me=Me||(Me={}));const Fe={};let Re;const We=async e=>{const t=Fe[e],n={name:ie,type:de.Boolean};if(t){const r={name:t.portName},i=t.data||{type:de.Boolean,value:!0};Re?(await Re(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...i,timestamp:Date.now()},[n]),"timeout"===t.type&&Ge(e)):console.warn("Interrupt service has not been initialized")}},Ge=e=>{const t=Fe[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete Fe[e],!0)};var Ve={interruptHandler:We,createInterrupt:(e,t,n,i,s,o,a,c)=>{if(c&&Fe[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(Fe[l]={data:a,portName:s,recipePoolId:t,targetWidgetId:i,thingId:n,type:e},"interval"===e)Fe[l].timerRef=setInterval((async()=>await We(l)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);Fe[l].timerRef=setTimeout((async()=>await We(l)),o.timeout)}return l},destroyInterrupt:Ge,destroyAllInterrupts:()=>{Object.keys(Fe).forEach(Ge)},setInvokeChildGateCb:e=>{Re=e}};const He=(e,t,n,r,i)=>{const s=ne(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)=>Ve.createInterrupt(t,e,n,r,i,s,o),a=()=>Object.freeze({...s.state,...s.type===Me.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===Me.input&&!e.customInputs&&{customInputs:[]}};s.state=t};if(i){return{getState:a,setState:c,registerInterrupt:o,getStorageData:async t=>{const r=((e,t,n)=>{const r=ee(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=te(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},recipePoolId:e,recipeType:t,thingRecipeId:n,widgetThingId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r}},ze=[10001,"Invalid `sourcePort` parameter"],qe=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],Ke=[10110,"No storage medium has been loaded, call `loadMedium()` first"],Je=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?o.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),Ye=()=>({inputName:"",dataType:de.Anything}),Xe="output",Ze={processEvent:async(e,t)=>{const n=t.getState(),r={...Ye(),...n};if(e.type===r.dataType||r.dataType===de.Anything)return t.nextWidget(Xe,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...Ye(),...e};return[{name:Xe,type:t.dataType}]},getInputNames:()=>[]},Qe=Object.freeze({in:"in",reset:"reset",increment:"increment"}),et="output";var tt={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(Je(ze));const i={currentValue:0,increment:1,...r.getState()};let s=i.increment,o=i.currentValue;const a=await r.getParentAtPort(Qe.increment);if(t.name===Qe.increment)return void(n.data.type===de.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(s=e)}if(t.name===Qe.reset)return r.setState({...i,currentValue:0});o+=s,r.setState({currentValue:o,increment:s});const c={type:de.Number,value:o};return r.nextGate(et,c)},getInputNames:()=>[{name:Qe.in,type:de.Anything},{name:Qe.reset,type:de.Anything},{name:Qe.increment,type:de.Number}],getOutputNames:()=>[{name:et,type:de.Number}]};const nt=Object.freeze({in:"in",reset:"reset"}),rt="output";var it={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===nt.reset?r.setState({...i,updatedAt:s,elapsed:0}):(r.setState({updatedAt:s,elapsed:o}),r.nextGate(rt,{type:de.Number,value:o}))},getInputNames:()=>[{name:nt.in,type:de.Anything},{name:nt.reset,type:de.Anything}],getOutputNames:()=>[{name:rt,type:de.Number}]};const st=Object.freeze({data:"data",evaluation:"evaluation"}),ot="then",at="else";var ct={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===de.Number||n.data.type===de.String||n.data.type===de.Anything&&o||n.data.type===de.Anything&&a)){let e=!1;return("Equal"===i.condition&&n.data.value==i.value||"Not Equal"===i.condition&&n.data.value!==i.value||"Greater"===i.condition&&n.data.value>Number(i.value)||"Less"===i.condition&&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(ot,n.data):r.nextGate(at,n.data)}if((t.name===st.evaluation&&n.data.type===de.Number||n.data.type===de.String||n.data.type===de.Anything&&(o||a))&&(i.$lastValue=n.data.value,r.setState({...i})),t.name===st.data){let e=!1;return("Equal"===i.condition&&i.$lastValue==i.value||"Not Equal"===i.condition&&i.$lastValue!==i.value||"Greater"===i.condition&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&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,$lastDataType:n.data.type}),e?r.nextGate(ot,n.data):r.nextGate(at,n.data)}},getInputNames:e=>e.useDataPort?[{name:st.data,type:de.Anything},{name:st.evaluation,type:[de.Number,de.String]}]:[{name:"in",type:[de.Number,de.String]}],getOutputNames:e=>e.$lastDataType?[{name:ot,type:e.$lastDataType},{name:at,type:e.$lastDataType}]:[{name:ot,type:[de.Number,de.String]},{name:at,type:[de.Number,de.String]}]};const lt=Object.freeze({in:"in",reset:"reset"}),ut="out";var dt={onParentEvent:async(e,t,n,r)=>{const i={totalCalls:0,callsLimit:1,...r.getState()};return t.name===lt.reset?r.setState({...i,totalCalls:0}):(i.totalCalls=i.totalCalls+1,i.totalCalls>i.callsLimit?(i.totalCalls=0,r.setState(i),r.nextGate(ut,n.data)):void r.setState(i))},getInputNames:()=>[{name:lt.in,type:de.Anything},{name:lt.reset,type:de.Anything}],getOutputNames:()=>[{name:ut,type:de.Anything}]};const pt=Object.freeze({in:"in"}),ht="then",ft="else";var gt={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:10,...r.getState()};if(n.data.type===de.Number)return n.data.value>=i.min&&n.data.value<=i.max?r.nextGate(ht,n.data):r.nextGate(ft,n.data)},getInputNames:()=>[{name:pt.in,type:de.Number}],getOutputNames:()=>[{name:ht,type:de.Number},{name:ft,type:de.Number}]};const mt=Object.freeze({in:"in"}),vt="out";var yt={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===de.Number||n.data.type===de.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(vt,{type:de.Number,value:Number(e)})}},getInputNames:()=>[{name:mt.in,type:de.Number}],getOutputNames:()=>[{name:vt,type:de.Number}]};const bt=Object.freeze({in:"in"}),St="out";var wt={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let s=n.data.value;if(n.data.type===de.Number||n.data.type===de.Anything||n.data.type===de.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(St,{type:"String"===i.convertTo?de.String:de.Number,value:s})}},getInputNames:()=>[{name:bt.in,type:de.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?de.String:de.Number;return[{name:St,type:t}]}};const It=Object.freeze({in:"in"}),_t="out";var $t={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.nextGate(_t,{type:de.Number,value:i.currentValue})},getInputNames:()=>[{name:It.in,type:de.Anything}],getOutputNames:()=>[{name:_t,type:de.Number}]};const Ct=Object.freeze({in:"in",reset:"reset"}),kt="out";var Et={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},s={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Ct.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(kt,n.data)):void 0},getInputNames:()=>[{name:Ct.in,type:de.Anything},{name:Ct.reset,type:de.Anything}],getOutputNames:()=>[{name:kt,type:de.Anything}]};const xt="in";var At={onParentEvent:async()=>{},getInputNames:()=>[{name:xt,type:[de.ImageData,de.Number]}],getOutputNames:()=>[]};const Nt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),Ot=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var Pt={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===de.JsonObj||n.data.type===de.Rect||n.data.type===de.Anything||o){let e=!1;for(const t in s){const n=Le(s[t]),r=!!i.detectedProperties[t],o=i.detectedProperties[t]?.type!==n;if(!r||o){const r=n===de.JsonObj||n===de.Rect||n===de.Array;i.detectedProperties[t]={type:n,...r?{shape:Te(s[t])}:void 0},e=!0}}if(o&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:de.Number}),e&&r.setState(i),s){const e=[];for(const t of i.properties||[]){const n=Ot(s,t.label),o=t.label.includes(".");if(void 0!==n){const s=o?Le(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:de.Anything;e.push(r.nextGate(t.name,{type:s,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:de.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:de.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:Nt};const Lt="output",Tt="noItem";var Bt={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===de.Anything&&(c||a)||n.data.type===de.String&&a||n.data.type===de.Array&&c){s<0&&(s=o.length+s);const e=a?de.String:Le(o[s]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==o[s]?r.nextGate(Lt,{value:o[s],type:e}):r.nextGate(Tt,{value:!0,type:de.Boolean})}},getInputNames:()=>[{name:"in",type:[de.Array,de.String]}],getOutputNames:e=>[{name:Lt,type:e.$$lastDetectedType??de.Anything},{name:Tt,type:de.Boolean}]};let jt;const Dt=e=>{jt=e},Ut=(e,t)=>(()=>{if(!jt)throw new Error("CanvasManager not set");return jt})().createCanvas(e,t),Mt=e=>ye?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Ft=Object.freeze({image:"image",rect:"rect"}),Rt="image";var Wt={onParentEvent:async(e,t,n,r)=>{const i={offset:{height:0,left:0,top:0,width:0},...r.getState()},s=await r.getParentAtPort(Ft.rect),o=[de.Anything,de.Rect,de.JsonObj];if(t.name!==Ft.rect){if(s){const e=s.getValue();null!==e&&(i.rect={...e},r.setState(i))}if(!ye)return n.data.type===de.ImageData?r.nextGate(Rt,n.data):void 0;if(i.$$canvasFrom&&i.$$canvasFrom.getContext||(i.$$canvasFrom=Ut(320,240)),i.$$canvasTo&&i.$$canvasTo.getContext||(i.$$canvasTo=Ut(320,240)),(n.data.type===de.ImageData||n.data.type===de.Anything&&Ne(n.data.value))&&!i.$$processing&&i.$$canvasFrom&&i.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})(n.data.value,i.rect,i.$$canvasFrom,i.$$canvasTo,i.offset);return r.nextGate(Rt,{type:de.ImageData,value:e})}}else Oe(n.data.value)&&o.includes(n.data.type)&&r.setState({...i,rect:n.data.value})},getInputNames:()=>[{name:Ft.image,type:de.ImageData},{name:Ft.rect,type:[de.Rect,de.JsonObj]}],getOutputNames:()=>[{name:Rt,type:de.ImageData}]};const Gt=(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(ye)return new ImageData(t,n);return console.warn("Node environment detected. Aborting new ImageData creation"),e})(e,a,c),u=l.data;for(let e=0;e<c;e++)for(let c=0;c<a;c++){const l=e,d=c,p=4*(e*a+c);let h=0,f=0,g=0,m=0;for(let e=0;e<n;e++)for(let a=0;a<n;a++){const c=l+e-r,u=d+a-r;if(c>=0&&c<o&&u>=0&&u<s){const r=4*(c*s+u),o=t[e*n+a];h+=i[r]*o,f+=i[r+1]*o,g+=i[r+2]*o,m+=i[r+3]*o}}u[p]=h,u[p+1]=f,u[p+2]=g,u[p+3]=m+1*(255-m)}return l},Vt=[-1,0,1,-2,0,2,1,0,1],Ht=Object.freeze({image:"image"}),zt="image";var qt={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={matrix:[...Vt],...i};if(n.data.type===de.ImageData||n.data.type===de.Anything&&Ne(n.data.value)){const e=Gt(n.data.value,s.matrix);return r.nextGate(zt,{type:de.ImageData,value:e})}},getInputNames:()=>[{name:Ht.image,type:de.ImageData}],getOutputNames:()=>[{name:zt,type:de.ImageData}]};const Kt=Object.freeze({output:"output",aborted:"aborted"}),Jt=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),Yt=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:de.Anything})));return n.push({name:"reset",type:de.Anything}),n};var Xt={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(Kt.aborted,n.data);{i.triggeredAt=s;const e=Yt(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(Kt.output,n.data),r.setState(i)}},getInputNames:Yt,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:de.Anything})));return e.push({name:Kt.aborted,type:de.Anything}),e}return[{name:Kt.output,type:de.Anything},{name:Kt.aborted,type:de.Anything}]},getDefaultState:Jt};const Zt=(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)}},Qt=(e,t,n,r,i,s,o)=>{e.fillStyle=i,e.fillRect(t,n,r,r),Zt(e,t,n,i,s,o)},en=(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;Zt(e,t.left-o,t.top-o,r,i,s)},tn=Object.freeze({image:"image",pixels:"pixels"}),nn="image";var rn={onParentEvent:async(e,t,n,r)=>{const i={fontSize:12,color:"#00ff00",size:2,...r.getState()},s=n.data.type===de.ImageData||n.data.type===de.Anything&&Ne(n.data.value);if(t.name===tn.pixels){const e=((e,t)=>t===de.Anything&&(Ne(e)||Pe(e)||Oe(e)||Array.isArray(e))||t===de.Array||t===de.Rect||t===de.Point)(n.data.value,n.data.type);if(!e)return;i.$$pixels=n.data.value}if(t.name===tn.image&&s){const e=n.data.value;i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ut(e.width||1,e.height||1)),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=Mt(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]:"";Oe(n)?en(e,n,i,s,r,a):Pe(n)&&Qt(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:i.size,color:i.color,labelProp:i.labelProp,fontSize:i.fontSize});return r.setState({...i,$$lastFrame:void 0,$$pixels:void 0}),r.nextWidget(nn,{type:de.ImageData,value:e})}r.setState(i)},getInputNames:()=>[{name:tn.image,type:de.ImageData},{name:tn.pixels,type:[de.Rect,de.Point,de.Array]}],getOutputNames:()=>[{name:nn,type:de.ImageData}]};const sn=Object.freeze({in:"in"}),on="output",an=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var cn={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,u=i.max,Math.random()*(u-l)+l);var l,u;if(a){let e=0;if(s&&(e=an(i.min)),o){const t=an(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(on,{type:de.Number,value:c})},getInputNames:()=>[{name:sn.in,type:de.Anything}],getOutputNames:()=>[{name:on,type:de.Number}]};const ln=Object.freeze({output:"output",totalItems:"totalItems"}),un=Object.freeze({trigger:"trigger",clear:"clear"}),dn=()=>({totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),pn=async(e,t)=>t.nextGate(ln.totalItems,{type:de.Number,value:e});var hn={onParentEvent:async(e,t,n,r)=>{const i={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===un.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),pn(i.$$list.length,r);const s=t.name===un.trigger;if(!s)if(Array.isArray(n.data.value))n.data.type!==de.Array&&n.data.type!==de.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await pn(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===de.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 pn(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 pn(e,r),r.nextGate(ln.output,{type:de.Array,value:t})}},getInputNames:e=>{const t={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`array${t+1}`,type:de.Array})));return n.push({name:un.clear,type:de.Anything},{name:un.trigger,type:de.Anything}),n},getOutputNames:e=>[{name:ln.output,type:de.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:ln.totalItems,label:"Total Items",type:de.Number}],getDefaultState:dn};const fn=Object.freeze({start:"start",stop:"stop"}),gn="output",mn="clock_interrupt";var vn={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(Ae(e?.name||"")&&t.name===mn)return r.nextGate(gn,{type:de.Boolean,value:!0});if(t.name===fn.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!==fn.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt("interval",mn,{interval:i.interval}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:fn.start,type:de.Anything},{name:fn.stop,type:de.Anything}],getOutputNames:()=>[{name:gn,type:de.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",mn,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const yn=Object.freeze({in:"in"}),bn="output",Sn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var wn={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===de.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>Sn(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]=Sn(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===de.Number&&(o=Sn(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(bn,{type:s,value:o})},getInputNames:()=>[{name:yn.in,type:[de.Array,de.Number]}],getOutputNames:e=>[{name:bn,type:e.detectedInputType||de.Number,jsonShape:e.detectedInputJson}]};const In=Object.freeze({output:"output"}),_n=Object.freeze({trigger:"trigger"}),$n=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:de.Number,value:10},{name:"y",label:"y",type:de.Number,value:20}]}),Cn=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},kn=e=>{const t={};for(let n=0;n<e.properties.length;n++){let r=e.properties[n].value;const i=e.properties[n].type;i===de.Number?r=Number(r):i===de.String&&(r=String(r)),t[e.properties[n].label]=r}return t};var En={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s=structuredClone(i),o={...$n(),...s};if(t.name===_n.trigger){const e=kn(o);return r.nextGate(In.output,{type:de.JsonObj,value:e})}const a=o.properties.findIndex((e=>e.name===t.name));if(-1!==a){let e=n.data.type===o.properties[a].type;if(!e&&n.data.type===de.Anything){e=Le(n.data.type)===o.properties[a].type}if(e?(o.properties[a].value=n.data.value,o.properties[a].$$invalidInputType=!1):o.properties[a].$$invalidInputType=!0,r.setState(o),!o.useTriggerPort){const e=kn(o);return r.nextGate(In.output,{type:de.JsonObj,value:e})}}},getInputNames:e=>{const t={...$n(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:_n.trigger,label:_n.trigger,type:de.Anything}),n},getOutputNames:e=>[{name:In.output,label:In.output,type:de.JsonObj,jsonShape:Cn(e)}],getDefaultState:$n};const xn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith($e)){const n=t(e,$e);return Be("inner","input",n)}if(e.startsWith(Ee)){const n=t(e,Ee);return Be("outer","output",n)}return null},An=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[de.Anything],index:0}],outputs:[{name:"output",type:[de.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Nn=e=>{const t={...An(),...e},n=t.inputs.map(((e,t)=>({name:Be("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:Be("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 On={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...An(),...i},o=Nn(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(de.Anything)||i.type.includes(n.data.type))){const e=await xn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Nn,getOutputNames:e=>{const t={...An(),...e},n=t.outputs.map(((e,t)=>({name:Be("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:Be("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:An};const Pn=(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 Ln,Tn,Bn,jn,Dn,Un,Mn,Fn,Rn,Wn,Gn={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,u=n,d=o,p=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,h]=n;o<0||h<0||o>=r||h>=i||s.has(`${o},${h}`)||!Pn(o,h,e,t,a||0)||(s.add(`${o},${h}`),l=Math.min(l,o),u=Math.max(u,o),d=Math.min(d,h),p=Math.max(p,h),c.push([o+1,h],[o-1,h],[o,h+1],[o,h-1]))}return{minX:l,maxX:u,minY:d,maxY:p}},l=[];for(let o=0;o<i;o+=4)for(let i=0;i<r;i+=4)if(!s.has(`${i},${o}`)&&Pn(i,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:s}=c(i,o),a=t-e,u=s-r;if(a>=(n.minWidth||1)&&u>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:u}),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}};!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Ln||(Ln={})),function(e){e.Bundle="bundle",e.Group="group"}(Tn||(Tn={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Bn||(Bn={})),function(e){e.Cloud="cloud",e.Web="web"}(jn||(jn={})),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"}(Dn||(Dn={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Un||(Un={})),(Mn||(Mn={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Fn||(Fn={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Rn||(Rn={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Wn||(Wn={}));let Vn=null;var Hn=()=>{if(!Vn)throw new Error("Required function is not set");return Vn};class zn extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const qn=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===Ln.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\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===Ln.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`,Kn=(e,t,n,r)=>{const o=qn(e,n),a={...t,document:{},__errorTracer:e=>{throw new zn(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:Gn,...n===Ln.Cloud?{require:Hn(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:i,CryptoJS:s,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(ye)return"browser";if(Se)return"node";if(be)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}}}},Jn="main",Yn=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},pages:{[Jn]:{code:"\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",language:"javascript",name:"My First Script"}},consoleVisible:!1,$$consoleLines:[]}),Xn=(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 qn(t,e).split(t)[0].split("\n").length+2})(t),n.column=i.column)}return e.message&&(n.message=e.message),n},Zn=(e,t)=>{const n={...Yn(),...t.getState()},r={...n,...e?{$$error:e}:void 0,...n.autoPauseOnError&&e?{pauseExecution:!0}:void 0};e&&(r.$$consoleLines=[...r.$$consoleLines,{type:"error",text:e.message,timestamp:Date.now(),fileName:Jn}]),t.setState(r)};var Qn,er;!function(e){e.ServiceCreationLog="service-creation-log"}(Qn=Qn||(Qn={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(er=er||(er={}));const tr=new a,nr=(e,t,n)=>{const r=te(e,t);if(!r)throw new Error(`Thing ${t} not found in recipe ${e}`);const i=r.gates[n];if(!i)throw new Error(`Widget ${n} not found in thing ${t}`);return i},rr=(e,t,n)=>`${t}:${n}:${e}`,ir=e=>`${e}:new-var`,sr=e=>`value-change:${e}`,or=async(e,t,n,r,i,s,o)=>{const a={...o},c={thingId:n,recipeId:t,variableName:e,changes:s,ownerId:r,callerWidgetId:i,varDefinition:Object.freeze(a)};if(s.includes("added")){const e=ir(n);return tr.emit(e,c)}{const t=rr(e,n,r);return s.includes("value")&&(await tr.emit(sr(e),c),await tr.emit(sr("*"),c)),tr.emit(t,c)}},ar=(e,t,n,r)=>{const i=nr(e,t,r);i.variablesListener={...i.variablesListener,[n]:0},lr(e,t)},cr=(e,t,n,r)=>{const i=nr(e,t,r),s={...i.variablesListener};void 0!==i.variablesListener?.[n]&&(delete s[n],i.variablesListener=s)},lr=async(e,t)=>{const n=te(e,t);if(!n)throw new Error(`Thing "${t}" not found in recipe "${e}"`);const r={...n.variables},i=Object.keys(r);for(const s of i){const i=r[s],o=Object.keys(i);for(const i of o){!n.gates[i]&&(delete r[s][i],await or(s,e,t,i,void 0,["removed"],null))}0===Object.keys(r[s]).length&&delete r[s]}n.variables=r},ur=(e,t,n)=>{for(const r in t){const i=t[r];if(i.createdByWidgetId===e.id)return i;if(e.type===Me.variable&&i.ownerType===Me.variable)return i;if(e.type===Me.script){const t=i.createdByWidgetId===e.groupId,r=n[i.createdByWidgetId];if(!r)continue;const s=r.groupId===e.groupId;if(t||r.type===Me.variable&&s)return i}}return null};var dr=async(e,t,n,r,i,s)=>{const o=te(e,t);if(!o)throw new Error(`Thing ${t} not found in recipe ${e}`);const a={...o.variables};a[r]=a[r]||{};const c=a[r],l=o.gates[n];if(!l)throw new Error(`Widget ${n} not found in thing ${t}`);const u=Object.values(c);let d=!1,p=!1;const h=async i=>or(r,e,t,i.createdByWidgetId,n,["value"],i);if(l.type===Me.variable){d=!0;for(const e of u)e.ownerType===Me.variable&&e.type===i.type&&(e.value=i.value,p=!0,await h(e))}if(l.type===Me.script){d=!0;for(const e of u){const t=e.createdByWidgetId===l.groupId,n=o.gates[e.createdByWidgetId],r=n?.type===Me.variable,s=n?.groupId===l.groupId;(t||r&&s)&&e.type===i.type&&(e.value=i.value,p=!0,await h(e))}}if(!d){d=!0;for(const e of u){e.createdByWidgetId===n&&e.type===i.type&&(e.value=i.value,p=!0,await h(e))}}if(!s?.skipNotifications&&p){const a=Object.values(o.gates);for(const o of a){if(o.id===n&&s?.skipCallerNotification)continue;const a=o.variablesListener?.[r];void 0!==a&&await is(o.id,t,e,`${ce}${r}`,i)}}},pr=(e,t,n,r)=>{const i=te(e,t);if(!i)throw new Error(`Thing ${t} not found in recipe ${e}`);if(!r.readerWidgetId&&!r.ownerWidgetId)throw new Error("readerWidgetId or ownerWidgetId must be provided");const s={...i.variables}[n];if(!s)return;if(r.ownerWidgetId){const e=s[r.ownerWidgetId];return e?.value}const o=i.gates[r.readerWidgetId];if(!o)throw new Error(`Widget ${r.readerWidgetId} not found in thing ${t}`);const a=ur(o,s,i.gates);return a?a.value:null},hr=ar,fr=cr,gr=(e,t)=>tr.on(sr(e),(e=>{if(e.varDefinition)return t({type:e.varDefinition.type,value:e.varDefinition.value,varName:e.variableName})}));const mr="setTimeout",vr="variableChanged",yr=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e;if(!ne(t,n,r))throw new Error(`Widget "${r}" not found in recipe "${t}"`);return{get:(e,i)=>{const s=pr(t,n,e,{readerWidgetId:r});if(null===s){if(void 0===i)throw new Error(`Variable "${e}" is not defined`);return i}return s},set:async(e,i)=>{await dr(t,n,r,e,{type:Le(i),value:i})},onValueChange:(i,s)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");hr(t,n,i,r);const o={...Yn(),...e.getState()};o.$$eventListeners[i]={handler:s,abort:async()=>{fr(t,n,i,r)},name:vr},e.setState(o)}}},br="__command-compile__";let Sr;const wr=()=>{console.log("Method not implemented")},Ir=(e,t,n)=>{const i=(e,...n)=>{const r={...Yn(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},s={};return Object.keys(de).forEach((e=>{s[e]=de[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?yr({recipePoolId:n.recipePoolId,scriptWidgetId:n.widgetId,thingId:n.thingId,getState:t.getState,setState:t.setState}):{get:wr,set:async()=>wr(),onValueChange:wr},setTimeout:(n,i,s)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=r(),o={...Yn(),...t.getState()};o.$$eventListeners[e]={handler:n,rejectHandler:s,name:mr},t.setState(o),t.registerInterrupt("timeout",e,{timeout:i},void 0,e)}},addEventListener:(e,n)=>{if(t.setState){const s=r(),o={...Yn(),...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={...Yn(),...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.`)}}},_r=(e,t,n,r)=>{const i={...Yn(),...n.getState()},s=i.pages[Jn].$$compiledCode;if(s)return{compiledModule:s};{const s=Ir(e,n,t);return Kn(i.pages[Jn].code,s,n.recipeType,r)}},$r=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),Cr=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===mr){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},kr=async(e,t,n)=>{let r={...Yn(),...e.getState()};if(void 0!==n){r.pages[Jn]?.$$compiledCode?.onTerminate&&await(r.pages[Jn].$$compiledCode?.onTerminate());let t=await Cr(r.$$eventListeners,e);t=await(async e=>{const t={...e};for(const n in e)if(e[n].name===vr){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})(t),r.$$eventListeners=t,r.$$error=void 0,r.pages[Jn].$$compiledCode=void 0,r.pages[Jn].code=n,e.setState({...r})}const i=!r.pages[Jn].$$compiledCode,{compiledModule:s,error:o}=_r({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=Xn(o,e.recipeType);return Zn(t,e),null}if(s){const n=(e=>{const t=(t,n)=>{if(Sr)try{return Sr[t](n)}catch(e){return void console.log("Error in custom logger: ",e)}const r={...Yn(),...e.getState()},i=[...r.$$consoleLines||[]];i.push({fileName:Jn,text:n,type:t,timestamp:Date.now()}),i.length>100&&i.splice(0,30),e.setState({...r,$$consoleLines:i})},n={log:e=>{t("log",e)},error:e=>{t("error",e)},warn:e=>{t("warn",e)},info:e=>{t("info",e)}};return n})(e);let o;if(r={...e.getState()},r.pages[Jn].$$compiledCode=s,e.nextGate&&s.setSendToPortFun(e.nextGate),t)try{await s.recipeInit({setState:e.setState,getState:e.getState},n)}catch(t){o=Xn(t,e.recipeType)}if(e.nextGate&&i)try{await s.main(e.nextGate,n)}catch(t){o=Xn(t,e.recipeType)}r.$$lastInputs=s.getWidgetInputs?s.getWidgetInputs():[],r.$$lastOutputs=s.getWidgetOutputs?s.getWidgetOutputs():[],e.setState(r),Zn(o,e)}};var Er={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Yn(),...i};if(!s.pages[Jn])return console.warn("Missing default page");if(s.pauseExecution){if(Object.keys(s.$$eventListeners).length){const e=await Cr(s.$$eventListeners,r);r.setState({...s,$$eventListeners:e})}return}if(Ae(e?.name||""))return s.$$eventListeners[t.name]?(await s.$$eventListeners[t.name].handler(),s.$$eventListeners[t.name].name===mr&&delete s.$$eventListeners[t.name],void r.setState({...s})):void console.log(`Unknown interrupt id [${t.name}] `);if(t.name.startsWith(ce)){const e=t.name.replace(ce,""),r=n.data.value,i=s.$$eventListeners[e];return void(i?.handler&&await i.handler(r))}const o=t.name===br;await kr(r,!1,o?n.data.value:void 0);const a=s.pages[Jn].$$compiledCode;if(e&&e.name!==br&&a){let i;try{await a.asyncProcessEvent(t,e,n)}catch(e){"UserCodeError"===e.name&&(i=Xn(e,r.recipeType))}Zn(i,r)}},getInputNames:(e,t)=>{const n={...Yn(),...e},{compiledModule:r}=_r({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return $r(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...Yn(),...e},{compiledModule:r}=_r({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return $r(e)}return e.$$lastOutputs||[]},getDefaultState:Yn,initialize:async e=>{const t=e.getState(),n={...Yn(),...t};n.pages[Jn].code&&await kr({getState:e.getState,id:e.widgetThingId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[Jn].code)}};const xr=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const i=await Ar(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)},Ar=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),Nr=Object.freeze({image:"image"}),Or=Object.freeze({base64:"base64"}),Pr=()=>({});var Lr={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===Or.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==de.String&&n.data.type!==de.Anything)return;const e=n.data.value;ye&&(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ut(320,240)));try{const t=await xr(e,i.$$memCanvas,i.resize?.width,i.resize?.height);return r.setState(i),r.nextGate(Nr.image,{type:de.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:Or.base64,type:de.String}],getOutputNames:()=>[{name:Nr.image,type:de.ImageData}],getDefaultState:Pr};const Tr=Object.freeze({object:"object",error:"error"}),Br=Object.freeze({string:"string"}),jr=()=>({outputIsArray:!1});var Dr={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===de.String||n.data.type===de.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?de.Array:de.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:de.Boolean,value:!0})}},getInputNames:()=>[{name:Br.string,type:de.String}],getOutputNames:e=>[{name:Tr.object,type:[de.JsonObj,de.Array],label:e.outputIsArray?"array":Tr.object},{name:Tr.error,type:de.Boolean}],getDefaultState:jr};const Ur=Object.freeze({string:"string",length:"length"}),Mr=Object.freeze({trigger:"trigger",setText:"setText"}),Fr=()=>({text:"",dispatchOnSet:!1});var Rr={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===Mr.setText){if(!((n.data.type===de.String||n.data.type===de.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(Ur.length,{type:de.Number,value:i.text.length}),o=r.nextGate(Ur.string,{type:de.String,value:i.text});await Promise.all([s,o])},getInputNames:e=>{const t=[{name:Mr.setText,type:de.String}];return e.dispatchOnSet||t.push({name:Mr.trigger,type:de.Anything}),t},getOutputNames:()=>[{name:Ur.string,type:de.String},{name:Ur.length,type:de.Number}],getDefaultState:Fr};const Wr=Object.freeze({image:"image"}),Gr=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),Vr=()=>({showInputPorts:!1});var Hr={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Gr.x&&(i.cropX=n.data.value),t.name===Gr.y&&(i.cropY=n.data.value),t.name===Gr.width&&(i.cropWidth=n.data.value),t.name===Gr.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===Gr.image){if(n.data.type!==de.ImageData&&n.data.type!==de.Anything)return;if(!Ne(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ut(320,240),i.$$memCanvasContext=Mt(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(Wr.image,{type:de.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Gr.image,type:[de.ImageData]}];return e.showInputPorts&&(t.push({name:Gr.x,type:de.Number}),t.push({name:Gr.y,type:de.Number}),t.push({name:Gr.width,type:de.Number}),t.push({name:Gr.height,type:de.Number})),t},getOutputNames:()=>[{name:Wr.image,type:de.ImageData}],getDefaultState:Vr};const zr=Object.freeze({image:"image"}),qr=Object.freeze({image:"image",width:"width",height:"height"}),Kr=()=>({showInputPorts:!1});var Jr={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===qr.width&&(i.width=n.data.value),t.name===qr.height&&(i.height=n.data.value),void r.setState(i);if(t.name===qr.image){if(n.data.type!==de.ImageData&&n.data.type!==de.Anything)return;if(!Ne(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ut(320,240),i.$$tempCanvas=Ut(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=Mt(t),c=Mt(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(zr.image,{type:de.ImageData,value:t})}},getInputNames:e=>{const t=[{name:qr.image,type:de.ImageData}];return e.showInputPorts&&(t.push({name:qr.width,type:de.Number}),t.push({name:qr.height,type:de.Number})),t},getOutputNames:()=>[{name:zr.image,type:de.ImageData}],getDefaultState:Kr};const Yr=Object.freeze({value:"value"}),Xr=Object.freeze({trigger:"trigger",setValue:"setValue"}),Zr=()=>({value:0,dispatchOnSet:!1});var Qr={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===Xr.setValue){const e=n.data.type===de.Number||n.data.type===de.Anything||n.data.type===de.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(Yr.value,{type:de.Number,value:i.value})},getInputNames:e=>{const t=[{name:Xr.setValue,type:de.Number}];return e.dispatchOnSet||t.push({name:Xr.trigger,type:de.Anything}),t},getOutputNames:()=>[{name:Yr.value,type:de.Number}],getDefaultState:Zr};const ei=Object.freeze({image:"image"}),ti=Object.freeze({image:"image"}),ni=()=>({anchors:[],vertices:[],matrix:[]}),ri={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},s=window,o=n.data.type===de.ImageData;if(s.Speedy&&o){const e=s.Speedy,t=n.data.value;let o,u,d,p=i.$$private?.canvas,h=i.$$private?.context,f={...i};const g=4===i.anchors.length;if(i.$$private?.pipeline)o=i.$$private?.pipeline,u=i.$$private?.source;else{o=e.Pipeline(),u=e.Image.Source();const n=e.Image.Sink();d=e.Transform.PerspectiveWarp(),p?p.width===t.width&&p.height===t.height||(p.width=t.width,p.height=t.height,h=p.getContext("2d")):(c=t.width,l=t.height,p=Ut(c,l),h=p.getContext("2d")),u.output().connectTo(d.input()),d.output().connectTo(n.input()),o.init(u,n,d);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)}d.transform=r,f={...f,$$private:{...f.$$private,canvas:p,context:h,perspective:d,pipeline:o,source:u}}}let m=t;if(g){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})(f,m);e&&(p&&h&&(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,h)),f.$$private&&r.setState({...f,$$private:{...f.$$private,lastInputImage:t}}))}else f.$$private&&r.setState({...f,$$private:{...f.$$private,lastInputImage:t}});return r.nextGate(ei.image,{type:de.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:ti.image,type:de.ImageData}],getOutputNames:()=>[{name:ei.image,type:de.ImageData}],getDefaultState:ni,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},ii=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[de.Anything],name:"input"}],outputs:[{dataType:[de.Anything],name:"output"}]});let si;const oi=()=>{if(!si)throw new Error(Je(Ke));return si};const ai=async e=>{const t=new c,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},ci={};var li=e=>ci[e]||null;const ui=async(e,t,n)=>{try{const r=oi(),i=n?r.loadBlobAsString:r.loadBlob;return await i(e,t)}catch(e){return null}},di=async e=>{const t=se;try{const n=await ui(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},pi=async e=>{const t=oe;try{const n=await ui(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}},hi=(e,t)=>`${e.replace(ae,"")}_${t}`,fi=(e,t)=>`widget/${e.replace(ae,"")}/v/${t}`,gi=async(e,t)=>{const n=oi(),[r]=await Promise.all([ai(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},mi=(e,t)=>{const n=hi(e,t),r=li(n);return r?{...r}:null},vi=(e,t,n)=>{const r=`${`widget/${e.replace(ae,"")}/tmp`}/${t}`;if(n){return oi().getCacheLocation(r)}return r};var yi=mi,bi=async(e,t,n)=>{const r=vi(t,n);await gi(e,r);const i=di(r),s=pi(r),o=oi(),a=o.getCacheLocation(r),[c,l]=await Promise.all([i,s]);if(!c)return null;let u=l;if(!l){const e=ii(),t=JSON.stringify(e);await o.saveBlob(r,oe,xe(t)),u=e}return{cachePath:a,processor:c,storedState:Object.freeze(u)}},Si=(e,t,n)=>{if(n.isTempStorage)return vi(e,t,n.fullStorageRoot);const r=oi(),i=fi(e,t);return n.fullStorageRoot?r.getCacheLocation(i):i};const wi=()=>ii();var Ii={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={...wi(),...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={...wi(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:wi,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetThingId;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=yi(r,i);let o=!s;if(!n.$$processor)if(n.storageUnitId&&!s){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetThingId;const s=await bi(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=Si(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 _i=Object.freeze({event:"event"}),$i="1",Ci="2",ki="3";var Ei={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate($i,n.data),await r.nextGate(Ci,n.data),await r.nextGate(ki,n.data)},getInputNames:()=>[{name:_i.event,type:de.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??de.Anything};return[{name:$i,...t},{name:Ci,...t},{name:ki,...t}]}};const xi=Object.freeze({set:"set",trigger:"trigger"}),Ai="value";var Ni={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={name:"myVar",type:de.String,reactive:!0,defaultValue:"",...i};if(t.name.startsWith(ce)){if(!s.reactive)return;if(n.data.type!==s.type)return;return r.nextWidget(Ai,n.data)}if(t.name!==xi.set){if(t.name===xi.trigger){const e=pr(r.recipePoolId,r.thingRecipeId,s.name,{ownerWidgetId:r.id}),t=e||s.defaultValue;await r.nextWidget(Ai,{type:s.type,value:t})}}else await dr(r.recipePoolId,r.thingRecipeId,r.id,s.name,n.data,{skipCallerNotification:!s.reactive})},getInputNames:e=>{const t={...e};return[{name:xi.set,type:t.type||de.Anything},{name:xi.trigger,type:de.Anything}]},getOutputNames:e=>{const t={...e};return[{name:Ai,type:t.type||de.Anything}]}};let Oi;var Pi=e=>{Oi=e},Li=()=>{if(!Oi)throw new Error("Hub Connector not set");return Oi};const Ti=async(e,t=!1)=>{const n=Li();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 Bi={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const s=Li();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;return s.onParentEvent({recipeId: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}})},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=Li(),r=await Ti(t);if(r)try{return await n.initializeServiceInstance({recipeId:e.recipePoolId,sessionId:r,widgetId:e.widgetThingId,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.widgetThingId}] 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=Li(),r=await Ti(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const ji=Object.freeze({Image:"image"}),Di=Object.freeze({Image:"image"}),Ui=()=>({filters:[{name:"grayscale",value:.5,id:"d-1"}]});const Mi="loaded";const Fi={input:Ze,counter:tt,elapsed:it,ifGate:ct,skipEvent:dt,between:gt,map:yt,parser:wt,slider:$t,suspend:Et,display:At,json:Pt,arrayItem:Bt,extractImage:Wt,imageConvolution:qt,firstEvent:Xt,pixelDraw:rn,randomBetween:cn,arrayCombine:hn,clock:vn,multiplication:wn,object:En,widgetGroup:On,script:Er,base64ToImageData:Lr,jsonParse:Dr,text:Rr,imageCrop:Hr,imageResize:Jr,value:Qr,imageWarp:ri,widgetBundle:Ii,sequence:Ei,variable:Ni,hubService:Bi,imageFilter:{onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:.5,id:"d-1"}],...r.getState()};if(t.name===ji.Image&&n.data.type===de.ImageData){if(!Ne(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas||(i.$$memCanvas=Ut(e.width,e.height)),i.$$context||(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=>`${e.name}(${e.value}${"blur"===e.name?"px":""})`)).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(Di.Image,{type:de.ImageData,value:t})}},getInputNames:()=>[{name:ji.Image,type:de.ImageData}],getOutputNames:()=>[{name:Di.Image,type:de.ImageData}],getDefaultState:Ui},recipeLoad:{onParentEvent:async(e,t,n,r)=>r.nextWidget(Mi,{value:!0,type:de.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:Mi,type:de.Boolean,description:"Triggered when the recipe is fully loaded"}]},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:de.Boolean}]}},Ri={},Wi=async()=>{if(!Object.keys(Ri).length)for(const e in Fi){const t=Fi[e];Ri[e]=Object.freeze({...t})}};var Gi=e=>{if(Ri[e])return Ri[e];throw new Error(Je(qe,e))},Vi=Wi;const Hi=new a,zi="invoked";let qi={},Ki={},Ji={},Yi={};const Xi=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var Zi=(e,t,n,r,i)=>{const s=Xi(e,t,n),o=Xi(e,t),a=Xi(e,t,"produced"),c=Ji[o],l=Date.now();Yi[o]=l,qi[s]={data:r,sourcePortName:n,...i?{target:{widgetId:i.widgetId,portName:i.portName}}:{}},Hi.emit(a,{currentTime:l,prevTime:c,...i?{targetPort:i?.portName}:{}})},Qi=(e,t,n,r,i)=>{const s=Xi(e,t,n),o=Xi(e,t),a=Xi(e,t,zi),c=Ji[o],l=Date.now();Ji[o]=l,Ki[s]={data:r,sourcePortName:n,...i?{source:{widgetId:i.widgetId,portName:i.portName}}:{}},Hi.emit(a,{prevTime:c,currentTime:l,targetPort:n,sourceInfo:i})},es=()=>{qi={},Ki={},Ji={},Yi={},Hi.clearListeners()};let ts,ns,rs;const is=async(e,t,n,r,i)=>{const s=te(n,t);if(!s)return;const o=s.gates[e];if(!o||o.disabled)return;const a={...i,timestamp:Date.now()},c=Gi(o.type),l=cs(e,a,s.recipeId,s.id,s.version,n);if(l&&c.onParentEvent){const t={name:r};return ts&&await ts({recipeId:n,blockId:s.recipeId,gateId:e,targetPort:t.name,data:i}),c.onParentEvent(null,t,{originalEvent:a,data:{...a}},l)}},ss=async(e,t,n,r,i,s,o,a,c,l)=>{if(!e&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!e&&!l)throw new Error("Missing parameter ['originalEvent']");e&&(l={timestamp:Date.now(),type:de.Boolean,value:!0});const u=l;if("string"==typeof n){const e=te(r,n);if(!e)return;n=e}const d=n.gates[t];if(!d||d.disabled)return;const p=a.findIndex((e=>e.name===i)),h=Gi(d.type),f=cs(t,u,n.recipeId,n.id,n.version,r);if(f&&h.onParentEvent&&-1!==p){ts&&await ts({recipeId:r,blockId:n.recipeId,gateId:t,targetPort:s.name,data:o,sourceGate:e?"interrupt_widget":c,sourcePort:e?ie:i});const l={name:a[p].name,type:a[p].type,...a[p].jsonShape?{jsonShape:a[p].jsonShape}:void 0};return Qi(n.recipeId,t,s.name,o,c?{widgetId:c,portName:i}:void 0),h.onParentEvent(l,s,{originalEvent:u,data:o},f)}},os=async(e,t,n,r,i,s,o,a)=>{const c=ee(a);if(!c)throw new Error(`Failed to find recipe "${a}" in cache`);const l=c.dbInfo.recipeType,u=ne(a,i,r);if(!u)return;const d={...n,timestamp:t.timestamp},p=Gi(u.type);let h;h=u.type===Me.input?p.getOutputNames(u.state,{thingRecipeId:i,thingDbId:s,thingVersion:o,id:r,recipeId:a,recipeType:l,recipePoolId:a}):await p.getOutputNames(u.state,{recipePoolId:a,recipeType:l,thingRecipeId:i,widgetId:r});const f=h.findIndex((t=>t.name===e));if(-1!==f){const n=te(a,i);if(!n)return;Zi(i,r,e,d);const s=u.children.length;for(let o=0;o<s;o++){if(je(u.children[o]?.sourcePort).portName===e){const s=n.gates[u.children[o].childId];if(s&&!s.disabled){const c=Gi(s.type);let p;const f={recipePoolId:a,recipeType:l,thingRecipeId:i,widgetId:r};p=s.type===Me.hubService?await c.getInputNames(s.state,f):c.getInputNames(s.state,f);const g=je(u.children[o].targetPort),m=p.find((e=>e.name===g.portName));m&&await ss(!1,s.id,n,a,e,{name:m.name},u.returnOriginalEvent?t:d,h,u.id,t)}}}}},as=async(e,t,n,r)=>{const i=ee(r);if(!i)return null;const s=te(r,n);if(!s)return s;const o=s.gates,a=s.gates[t],c=Gi(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),u=l.findIndex((t=>t.name===e));if(-1!==u){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=je(r.targetPort);if(r.childId===e&&s.portName===t)return i}}return null})(t,l[u].name,o);if(e){const t=Gi(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},cs=(e,t,n,r,i,s)=>{const o=ee(s);if(!o)throw new Error(`Failed to find recipe "${s}" in cache`);const a=ne(s,n,e);if(!a)return console.warn(`Gate ${e} not found in block ${n} for recipe ${s}`),null;const c=async(o,a)=>os(o,t,a,e,n,r,i,s),l={id:e,type:a.type,recipePoolId:s,thingRecipeId:n,recipeType:o.dbInfo.recipeType,returnOriginalEvent:!!a.returnOriginalEvent,registerInterrupt:(t,r,i,o,a)=>Ve.createInterrupt(t,s,n,e,r,i,o,a),cancelInterrupt:e=>Ve.destroyInterrupt(e),nextWidget:c,nextGate:c,getParentAtPort:t=>as(t,e,n,s),getState:()=>Object.freeze({...a.state,...a.type===Me.input&&{customInputs:[]}}),setState:t=>{if("object"!=typeof t)return void console.warn(`Invalid state type [${typeof t}]. Expected an 'object'`);const r={...t,...a.type===Me.input&&!t.customInputs&&{customInputs:[]}},i={...a.state};a.state=r,ns&&ns({blockId:n,gateId:e,prevState:i,newState:{...r},recipeId:s})}};return l};Ve.setInvokeChildGateCb(ss);const ls=new a,us="invoked",ds="state",ps=()=>{Ve.destroyAllInterrupts()},hs=async(e,t,n)=>{const r=ee(e),i=ne(e,t,n);if(i&&r){const s=Gi(i.type);if(s&&"function"==typeof s.terminate){const i=((e,t,n,r)=>He(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)}}}},fs=async(e,t,n,r)=>{const i=ee(e),s=ne(e,t,n);if(s&&i){const o=Gi(s.type);if(o&&"function"==typeof o.initialize){const s=((e,t,n,r)=>He(e,t,n,r,!0))(e,i.dbInfo.recipeType,t,n);if(s){const e=o.initialize;try{await e(s,r||{})}catch(e){throw console.warn(`Error initializing widget "${n}" in thing "${t}": `,e),e}}}}},gs=(e,t)=>{const n=ee(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},ms=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,vs=e=>{ls.emit(ms(ds),e),ls.emit(ms(ds,e.blockId,e.gateId),e)};ts=async e=>{await ls.emit(ms(us),e),await ls.emit(ms(us,e.blockId,e.gateId),e)},(e=>{ns=e})(vs);var ys,bs,Ss,ws,Is,_s,$s,Cs,ks,Es,xs,As,Ns,Os=async(e,t,n,r,i)=>{const s=re(e,{id:t,authorId:r,version:n,recipeType:i});es();const o=ee(s);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=Y.STARTING,o.addLog("recipe registered")),s},Ps=async e=>{const t=ee(e);var n;if(!t)return null;t.addLog("terminating recipe"),ps();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await hs(e,n,t)}X[n=e]&&delete X[n]},Ls=async(e,t)=>{const n=ee(e),r=[],i=[];if(n)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===Ln.Desktop){const e=o.gates[t];if(e.type===Me.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===Me.recipeLoad&&i.push(e)}await fs(e,s,t,{keepCurrentState:!0})}catch(e){r.push({widgetId:t,error:e.message})}}return{failed:r,sendToInputWidget:(t,n,r=le)=>(async(e,t,n,r)=>{const i=ee(n),s=te(n,r),o=Date.now();if(s&&i)for(const i in s.gates){const a=s.gates[i];if(a.type===Me.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=Gi(a.type),l={...t,timestamp:o},u=cs(i,l,r,s.id,s.version,n);if(u&&e.processEvent){const s={...u,getState:u.getState};ts&&await ts({recipeId:n,blockId:r,gateId:i,targetPort:Xe,data:t}),rs?await rs(r,n,c,t):await e.processEvent(l,s)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of i)await is(t.id,le,e,Mi,{type:de.Boolean,value:!0})}}},Ts=e=>{Pi(e)},Bs=(e,t,n,r=!1)=>{const i=gs(t,e);if(i){const{widget:s,thing:o}=i,a={...s.state};s.state=n,r&&vs({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},js=(e,t)=>{const n=gs(t,e);return n?n.widget.state:null},Ds=async(e,t,n,r,i)=>{const s=gs(t,e);if(s)return os(n,r,i,t,s.thing.recipeId,s.thing.id,s.thing.version,e)};!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(ys||(ys={})),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"}(bs||(bs={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Ss||(Ss={})),function(e){e.Bundle="bundle",e.Group="group"}(ws||(ws={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Is||(Is={})),function(e){e.Cloud="cloud",e.Web="web"}(_s||(_s={})),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"}($s||($s={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Cs||(Cs={})),function(e){e.InstallInProgress="installation-in-progress"}(ks||(ks={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Es||(Es={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(xs||(xs={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(As||(As={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.ExportRecipe="export_recipe"}(Ns||(Ns={}));const Us=(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=d("aes-256-cbc",o,i);let c=a.update(s,"base64","utf8");return c+=a.final("utf8"),c})(e.id||"recipe.json","kemu",t),Ms=e=>{try{return JSON.parse(e)}catch(e){return null}},Fs="undefined"!=typeof window,Rs={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Ws={protocolPrefix:4,txtLength:4},Gs=Object.values(Rs).reduce(((e,t)=>e+t),0),Vs=Object.values(Ws).reduce(((e,t)=>e+t),0),Hs=["width","height","colorSpace"],zs=(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)||Hs.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},qs=(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},Ks=(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&&qs(e,s,l)}return e},Js=e=>f(e),Ys="KMSG",Xs="KCMD",Zs=Js("klProtocol");var Qs={encode:(e,t,n)=>{const r={json:e.json},i=zs(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,u=Rs.protocolPrefix+Rs.protocolVersion+Rs.jsonLength+Rs.binaryLength+Rs.fromServiceId+Rs.toServiceId+Rs.sentAt+l+o,d=Buffer.alloc(u),p=Date.now();let h=0;return d.write(Ys,h),h+=Rs.protocolPrefix,d.writeUInt8(1,h),h+=Rs.protocolVersion,d.writeUInt32LE(l,h),h+=Rs.jsonLength,d.writeUInt32LE(o,h),h+=Rs.binaryLength,d.writeUInt32LE(t,h),h+=Rs.fromServiceId,d.writeUInt32LE(n,h),h+=Rs.toServiceId,d.writeBigInt64LE(BigInt(p),h),h+=Rs.sentAt,c.copy(d,h),h+=l,s&&o&&s.copy(d,h),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Rs.protocolPrefix);if(t+=Rs.protocolPrefix,n!==Ys)return null;if(e.byteLength<Gs)return Zs(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Rs.protocolVersion;const i=e.readUInt32LE(t);t+=Rs.jsonLength;const s=e.readUInt32LE(t);t+=Rs.binaryLength;const o=e.readUInt32LE(t);t+=Rs.fromServiceId;const a=e.readUInt32LE(t);t+=Rs.toServiceId;const c=e.readBigInt64LE(t);t+=Rs.sentAt;const l=i+s,u=e.subarray(t,t+l),d=e.subarray(0,Gs);let p=null;return e.byteLength-Gs-i-s>0&&(p=e.subarray(Gs+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},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=Ms(n);if(!i?.json)return Zs("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Ks(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=Gs+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<Gs)return Zs("Invalid Header Size"),e;let n=0;return n+=Rs.protocolPrefix,n+=Rs.protocolVersion,n+=Rs.jsonLength,n+=Rs.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Rs.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=Vs+r,s=Buffer.alloc(i);return s.write(Xs,t),t+=Ws.protocolPrefix,s.writeUint32LE(r,t),t+=Ws.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<Vs)return{command:null};const n=e.toString("utf-8",t,Ws.protocolPrefix);if(t+=Ws.protocolPrefix,n!==Xs)return{command:null};const r=e.readUInt32LE(t);t+=Ws.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-Vs-r;let o=null;s>0&&(o=e.subarray(Vs+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const eo="KMSG",to="KCMD",no=Js("klProtocol"),ro=new TextEncoder;var io={encode:(e,t,n)=>{const r={json:e.json},i=zs(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=ro.encode(a),l=c.byteLength,u=new ArrayBuffer(Rs.protocolPrefix+Rs.protocolVersion+Rs.jsonLength+Rs.binaryLength+Rs.fromServiceId+Rs.toServiceId+Rs.sentAt+l+o),d=new DataView(u),p=new Uint8Array(u),h=Date.now();let f=0;for(let e=0;e<4;++e)p[f++]=eo.charCodeAt(e);return d.setUint8(f,1),f+=Rs.protocolVersion,d.setUint32(f,l,!0),f+=Rs.jsonLength,d.setUint32(f,o,!0),f+=Rs.binaryLength,d.setUint32(f,t,!0),f+=Rs.fromServiceId,d.setUint32(f,n,!0),f+=Rs.toServiceId,d.setBigInt64(f,BigInt(h),!0),f+=Rs.sentAt,p.set(c,f),f+=l,s&&o&&p.set(new Uint8Array(s),f),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Rs.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==eo)return null;if(e.byteLength<Gs)return no.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Rs.protocolVersion;const s=t.getUint32(n,!0);n+=Rs.jsonLength;const o=t.getUint32(n,!0);n+=Rs.binaryLength;const a=t.getUint32(n,!0);n+=Rs.fromServiceId;const c=t.getUint32(n,!0);n+=Rs.toServiceId;const l=t.getBigInt64(n,!0);n+=Rs.sentAt;const u=s+o,d=e.slice(n,n+u),p=new Uint8Array(e,0,Gs);let h=null;if(e.byteLength-Gs-s-o>0){h=new Uint8Array(e,Gs+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:p.slice().buffer},remaining:h}},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=Ms(s);if(!a?.json)return no.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Ks(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,u=null;const d=Gs+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Gs)return no("Invalid Header Size"),e;let n=0;n+=Rs.protocolPrefix,n+=Rs.protocolVersion,n+=Rs.jsonLength,n+=Rs.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Rs.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=ro.encode(e),r=n.byteLength,i=new ArrayBuffer(Vs+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=to.charCodeAt(e);return s.setUint32(t,r,!0),t+=Ws.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Vs)return{command:null};let r="";for(let e=0;e<Ws.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==to)return{command:null};const i=t.getUint32(n,!0);n+=Ws.txtLength;const s=e.byteLength-Vs-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-Vs)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(Vs+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};let so=Qs;Fs&&(so=io);var oo,ao=so;(oo||(oo={})).FunctionNotFound="FNC_NOT_FOUND";let co=Math.ceil(Date.now()/1e3);let lo,uo,po,ho,fo,go=!1;var mo=()=>{go=!0},vo=(e,t)=>{if(!lo)throw new Error("Memory connection not set.");lo.sendBuf(e,t)},yo=e=>uo=e,bo=e=>fo=e,So=e=>po=e,wo=e=>ho=e;const Io=(e,t=2)=>{const n=(e,r)=>{if("object"==typeof e){const i=Object.keys(e);for(const s of i){const i=e[s];if(i&&"object"==typeof i){const o=i._kemuType;if(void 0!==o){if(o===de.ImageData){const t=e[s];e[s]=De(t)}}else r<t&&n(i,++r)}}}};return n(e,1),e};Js("klTransmissionManager"),Js("ipcClient");Js("kemuWidgetService"),C(process.argv.slice(2));const _o=e=>f(`runner:${e}`),$o=_o("connectionManager"),Co=_o("remoteInvoke"),ko=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=Fs?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=ao.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}co+=1;const u=`${i}-${co}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let p=Fs?new ArrayBuffer(0):Buffer.alloc(0);const h={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(p=ao.encode(h,a,c)),t[u]=d,n&&n(`Calling remote function "${e}" with message id "${u}"`);const f="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||f||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=t[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:h}),d.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)=>{co+=1;const a=`${i}-${co}-multicast-${e.substring(0,10)}`;let c=Fs?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=o(r[0].serviceId);u&&(c=ao.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&&(u=o(i.serviceId),u&&(c=ao.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");ko.setLogger(Co);const Eo=new a,xo=new a;let Ao,No=null,Oo=null,Po=null;const Lo={},To=()=>{if(!Po)throw new Error("API key is required to interact with the hub");return Po},Bo=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return Lo[r]=i,i},jo=(e,t)=>Lo[`${e}_${t}`]||null,Do=async(e,t)=>{if(!No)return $o("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await ko.execute(ge.GetServiceContents,n,Mo,No,0))[0]},Uo=async(e,t,n=!1)=>{if(!e||!t)return null;const r=jo(e,t);if(!r||n){const n=r||Bo(e,t);try{const r=await Do(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){$o(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},Mo=vo,Fo=()=>{$o("Disconnected from the server"),No=null,ko.rejectAllPending("Disconnected from the server"),Eo.emit("disconnected")},Ro=()=>{$o("Connected to the server"),Eo.emit("connected")},Wo=()=>Oo,Go=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,Vo=async()=>{const e=Wo();if(e){const t=ee(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===Me.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{$o(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await sa({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){$o(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},Ho=async e=>{if(!e)return void $o("Hub sent ACK request without service id");const t={apiKey:To(),ackSessionId:e};await ko.execute(ge.SocketAckResponse,[t],Mo,e,0),$o("Hub Link acknowledged"),No=e,Eo.emit("acknowledged"),Vo()},zo=async e=>{const t=e.args[0],n=Go("broadcast",`hub_${t.type}`,(0).toString(),"");await xo.emit(n,t)},qo=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===de.ImageData&&Ne(e.value)&&(e.value=De(e.value));const n=Wo();if(n){const r=ee(n);if(r){const i=async e=>{const n=Go("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await xo.emit(n,t)}catch(t){$o(`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===Me.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await i(r);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()};$o(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await Ds(n,r,i.name,t,t)}}}}}}},Ko=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,s=js(r,i);let o=s;if(n&&o&&s&&(o={...s,customState:n},Bs(r,i,o,!0)),o?.service)try{const e=Go("setOutputs",o.service.name,o.service.version,i);await xo.emit(e,t.outputs)}catch(e){$o(`Failed to emit setOutputs event for widget ${i}`,e)}for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===de.ImageData){if(!Ne(n.value)){$o(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=De(n.value)}else n.type===de.JsonObj&&Io(n.value);const t={type:n.type,value:n.value,timestamp:Date.now()};$o(`Sending data to output ${n.name} requested by messageId ${e.messageId}`),await Ds(r,i,n.name,t,t)}e.reply({success:[]})},Jo=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,s=js(r,i);if(s){const t={...s,customState:{...s.customState,...n}};return Bs(r,i,t,!0),e.reply({success:[]})}},Yo=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:s,key:o}=n;$o(`Received request to set a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const a=js(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:s},Bs(r,i,e,!0)}return t({success:[]})},Xo=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:s}=n;$o(`Received request to get a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const o=js(r,i);if(o){const e=o.dependencies?.[s]?.path;return $o(`Returning dependency path for "${s}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},Zo=async()=>{if($o(`Requesting services on ${(new Date).toISOString()}`),!No)return $o("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await ko.execute(ge.GetServices,[],Mo,No,0);Ao=e;for(const t of e.available){if(t.internal)continue;const e=jo(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||Bo(t.name,t.version);$o(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await Do(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){$o(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},Qo=()=>Ao||{available:[],installed:[],failed:[]},ea=()=>!!Ao,ta=async e=>{const{targetServiceSessionId:t}=e;if(!No)return void $o("No target service session id provided");$o(`Forwarding "onParentEvent" to service ${t}`);return await ko.execute(ge.OnParentEvent,[e],Mo,No,t,e.config)},na=async e=>{if(!No)return $o("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await ko.execute(ge.GetDefaultState,[],Mo,No,e);return t},ra=async(e,t,n,r)=>{if(!No)return $o("Hub Link has not been acknowledged. Cannot get services."),null;const[i]=await ko.execute(ge.UIEvent,[t,n],Mo,No,e,r);return i},ia=(e,t)=>{const n=()=>{t()};return Eo.on(e,n),()=>Eo.off(e,n)},sa=async e=>{if(No)return ko.execute(ge.SubscribeToService,[e],Mo,No,0);$o("Hub Link has not been acknowledged. Cannot subscribe to services.")},oa=async e=>{if(No)return ko.execute(ge.UnsubscribeFromService,[e],Mo,No,0);$o("Hub Link has not been acknowledged. Cannot subscribe to services.")},aa=(e,t,n,r)=>{const i=Go("broadcast",t,n,e);return xo.on(i,r)},ca=(e,t,n,r)=>{const i=Go("setOutputs",t,n,e);return xo.on(i,r)},la=async(e,t,n)=>No?ko.execute(e,t,Mo,No,0,n):($o("Hub Link has not been acknowledged. Cannot execute function."),null),ua=async e=>{if(!No)return void $o("Hub Link has not been acknowledged. Cannot execute function.");const t=js(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,currentDependencies:n}],[i]=await ko.execute(ge.InitializeInstance,r,Mo,No,e.sessionId);if(i){const t=js(e.recipeId,e.widgetId);if(t){const n={...t,customState:i};Bs(e.recipeId,e.widgetId,n,!0)}}},da=async(e,t,n,r)=>{if(!No)return void $o("Hub Link has not been acknowledged. Cannot execute function.");const i=js(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 ko.execute(ge.TerminateInstance,s,Mo,No,e)},pa=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=ea(),o=r||!s?await Zo():Qo();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};var ha,fa,ga,ma,va,ya,ba,Sa,wa=async e=>{So(Ro),wo(Fo),Po=e,bo((({json:e,transmission:t})=>{ko.processMessage("websocket",Mo,t,e)})),ko.registerFunction(ge.SetState,Jo),ko.registerFunction(ge.SetOutputs,Ko),ko.registerFunction(ge.BroadcastEvent,qo),ko.registerFunction(ge.HubBroadcastEvent,zo),ko.registerFunction(me.SetDependencyPath,Yo),ko.registerFunction(me.GetDependencyPath,Xo),yo((e=>{((e,t)=>{const n=fe.SocketAcknowledge,r=fe.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,Ho),((e,t)=>{e===fe.ServicesListChanged&&(t&&t())})(e,(()=>{$o("Services list changed"),Eo.emit("services-changed")}))})),await mo()},Ia=(e,t)=>{Eo.on(e,t)},_a=()=>({getServices:Zo,getServiceContents:Uo,onParentEvent:ta,onCommand:ia,getDefaultState:na,getCachedServices:Qo,areServicesCached:ea,subscribeToServiceEvents:sa,unsubscribeFromServiceEvents:oa,callProcessorHandler:ra,onBroadcastEvent:aa,onSetOutputsEvent:ca,executeHubFunction:la,initializeServiceInstance:ua,terminateServiceInstance:da,getCompatibleService:pa}),$a=e=>{Oo=e},Ca=()=>ko;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(ha||(ha={})),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"}(fa||(fa={})),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"}(ga||(ga={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ma||(ma={})),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:"}(va||(va={})),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.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId"}(ya||(ya={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(ba||(ba={})),function(e){e.IPC="ipc",e.WS="ws"}(Sa||(Sa={}));const ka=e=>{try{return JSON.parse(e)}catch(e){return null}},Ea=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,xa=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(Ea);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},Aa=e=>"*"===e||"x"===e||"X"===e,Na=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},Oa=(e,t)=>{if(Aa(e)||Aa(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(Na(e),Na(t));return n>r?1:n<r?-1:0},Pa=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=Oa(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},La=(e,t,n)=>{ja(n);const r=((e,t)=>{const n=xa(e),r=xa(t),i=n.pop(),s=r.pop(),o=Pa(n,r);return 0!==o?o:i&&s?Pa(i.split("."),s.split(".")):i||s?i?-1:1:0})(e,t);return Ta[n].includes(r)},Ta={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},Ba=Object.keys(Ta),ja=e=>{if(-1===Ba.indexOf(e))throw new Error(`Invalid operator, expected one of ${Ba.join("|")}`)};var Da="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ua(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ma,Fa,Ra,Wa,Ga,Va={exports:{}},Ha={exports:{}};function za(){if(Fa)return Ma;Fa=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 Ma=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 qa(){if(Wa)return Ra;return Wa=1,Ra=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=za(),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},Ra}var Ka,Ja,Ya,Xa,Za,Qa={exports:{}};function ec(){return Ja||(Ja=1,Ka=(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)}),Ka}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?Va.exports=(Ga||(Ga=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=qa()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Ha,Ha.exports)),Ha.exports):Va.exports=(Za||(Za=1,function(e,t){const n=k,r=o;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(Xa)return Ya;Xa=1;const e=E,t=k,n=ec(),{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)),Ya={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=qa()(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)}}(Qa,Qa.exports)),Qa.exports);var tc=Ua(Va.exports);const nc=e=>tc(e),rc=Date.now();let ic=Math.ceil(rc/1e3);var sc=()=>ic+=1;const oc=m(x(),"kemu-user-services"),ac=m(x(),"kemu-test-services"),cc="KMU-CB-v1";var lc;!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"}(lc||(lc={}));const uc=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>fa[e])):fa[e.type]}),dc=async e=>{try{return await S(e,"utf-8")}catch(e){return null}},pc=e=>{if(e&&e.startsWith(cc)){const t=e.slice(9),n=decodeURI(t);return ka(n)}return null},hc=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(uc)}:{},...e.outputs?{outputs:e.outputs.map(uc)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(uc)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(uc)}:{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 dc(m(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const s=t.startsWith(cc)?t:`${cc}${t}`,o=pc(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===lc.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${i}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${i}" does not contain a top level widgetGroup`);continue}const l=c.state,u={name:l.name,color:l.color,description:l.description,contents:s,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}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 S(m(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},fc=async e=>{try{return await w(e,I.F_OK),!0}catch{return!1}};let gc=null,mc=null;const vc=()=>gc||oc,yc=nc("servicesManager"),bc={};let Sc=null,wc=null,Ic=null;class _c extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const $c=async e=>{try{return await w(e),!0}catch{return!1}},Cc=async e=>{if(!Sc)throw new Error('IPC config not set, call "setHubIpcConfig" first.');try{if(e.processor===ma.Javascript){yc(`Spawning service ${e.name} with sessionId ${e.sessionId}`);const t=g.join(e.path,"processor.js"),n=g.join(e.path,"processor.mjs"),r=await $c(t)?t:n,i=[`--sessionId=${e.sessionId.toString()}`,`--ipcSpace=${Sc.appSpace}`,`--ipcId=${Sc?.id}`,`--recipePath=${Sc.recipePath||""}`];if(e.internal&&i.push("--internal=true"),!Ic)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const s=await Ic({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 _c(`Missing required environment variables: ${o.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,n)=>{if(!wc)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const o=wc({args:[r,...i],options:{env:s}});o.stdout.on("data",(t=>{yc(`[${e.name}] - stdout: ${t}`)})),o.stderr.on("data",(t=>{yc(`[${e.name}] - stderr: ${t}`)})),o.on("exit",(t=>{yc(`[${e.name}] exited with code ${t}`)})),o.on("spawn",(()=>{yc(`[${e.name}] spawned with PID ${o.pid}`),t(o)})),o.on("error",(t=>{yc(`[${e.name}] error: ${t}`),n(new _c(`Error spawning service ${e.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.processor}`}catch(t){if(t instanceof _c)throw t;throw`Error spawning service ${e.name}: ${t}`}},kc=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[ma.Javascript,ma.Executable,ma.Python].includes(e?.processor)?null:"Invalid processor"},Ec=async(e,t)=>{const n=g.join(e,"manifest.json");if(!await $c(n)){const t=`Missing manifest for service ${e}. Aborting.`;return yc(t),{error:t}}const r=await S(n,"utf-8"),i=ka(r),s=kc(i);if(!i||s){const t=`Invalid service manifest [${e}]: ${s}. Aborting.`;return yc(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 S(g.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return yc(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await dc(g.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=g.join(e,t),{error:r,service:s}=await Ec(n);r?yc(`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 S(g.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){yc(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=sc(),c=t?.fixedSession||a;yc(`Loaded service ${i.name} with sessionId ${c}`);const l=await hc(i,e,{widgetUIContents:o});return xc(l),bc[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null},{service:bc[c]}},xc=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=p("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},Ac=async e=>{try{return e.childProcess=await Cc(e.info),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return yc(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof _c?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},Nc=e=>{const{path:t,...n}=e.info;return{...n}},Oc=()=>Object.values(bc).filter((e=>"running"===e.status)).map(Nc),Pc=e=>{const{serviceName:t,version:n,force:r}=e,i=Object.values(bc).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){yc(`Stopping service "${t} (v${n})"`);i.childProcess.kill("SIGINT")||yc(`Failed to stop service ${t}`)}return i.status="stopped",yc(`Service ${t} stopped`),i},Lc=e=>e.info.internal?e.info.path:g.join(e.info.path,".."),Tc=e=>!!e.internal;var Bc={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await fc(e))return void yc(`Failed to load services from "${e}". Directory does not exist.`);const n=(await _(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));yc(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],s=g.join(e,i),{error:o,service:a}=await Ec(`${s}${t?.internalServices?"":"/dist"}`,t);o&&yc(`Failed to load service ${s}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(yc("Initializing services"),!Sc)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in bc){const n=bc[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?yc(`Service ${n.info.name} is in the noSpawningList. Skipping.`):Ac(n)}yc("Services initialized")},setServiceStatus:(e,t)=>{const n=bc[e];return n?(n.status=t,!0):(yc(`Service with serviceId ${e} not found`),!1)},getActiveServices:Oc,getMatchingService:(e,t)=>{const n=Object.values(bc).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(La(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>bc[e]||null,killAllServices:()=>{for(const e in bc){const t=bc[e];if(t.childProcess)try{yc(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){yc(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await hc(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};bc[e]=r,xc(bc[e].info)},setServiceManifest:(e,t,n)=>{const r=bc[e];if(!r)return yc(`Service with sessionId ${e} not found`),!1;const i=kc(t);if(i)return yc(`Invalid manifest for service ${r.info.name}: ${i}`),!1;xc(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(bc).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:()=>Oc().filter((e=>e.internal)),getAllServices:()=>Object.values(bc),stopService:Pc,uninstallService:async(e,t)=>{yc(`Uninstalling service ${e} v${t}`);const n=Pc({serviceName:e,version:t});if(!n)return!1;yc(`Service ${e} stopped. Removing from disk...`);const r=Lc(n),i=vc();return r.startsWith(i)?(await $(r,{recursive:!0,force:!0}),yc(`Service ${e} successfully removed from disk`),(e=>{const t=bc[e];delete bc[e]})(n.info.sessionId),!0):(yc(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(bc).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{Sc={...e}},loadAndLaunch:async(e,t,n)=>{const r=y(e,t),{error:i,service:s}=await Ec(r);if(i||!s)return{errorMsg:i};try{s.info.internal=!!n,s.childProcess=await Cc(s.info),s.status="started"}catch(e){s.status="error",e instanceof _c?(yc(`Service spawning error: ${e.message} (${e.code})`),s.errorMsg=e.message,s.errorCode=e.code):(yc(`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:Lc,setSpawnNodeFunction:e=>{wc=e},setGetSecretsFunction:e=>{Ic=e},restartService:async(e,t)=>{yc(`Restarting service ${e} v${t}`);const n=Pc({serviceName:e,version:t,force:!0});return!!n&&Ac(n)},getFailedServices:()=>Object.values(bc).filter((e=>"error"===e.status)).map((e=>({...Nc(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Tc,isNotInternalKemuService:e=>!Tc(e),isNotDevService:e=>!e.devMode};class jc{constructor(){}appspace="app.";socketRoot="/tmp/";id=E.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=E.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 Dc{constructor(e){e||(e=new jc),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 Uc=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={}},Mc=Ua(Uc);var Fc=Ua((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 Rc{}class Wc{}const Gc=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 Rc,t=Wc){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 Rc}}())}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 Vc{constructor(){}on(e,t,n=!1){return Gc.string(e),Gc.function(t),Gc.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(Gc.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Gc.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){Gc.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)=>{Gc.string(e),Gc.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 Hc=new Dc;class zc extends Vc{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Hc=new Dc(this.config)}Client=zc;queue=new Fc;socket=!1;connect=Jc;emit=qc;retriesRemaining=0;explicitlyDisconnected=!1}function qc(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Mc;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Hc.format(n),this.config.sync?this.queue.add(Kc.bind(this,n)):this.socket.write(n)}function Kc(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Jc(){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=N.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=A.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=A.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)!=Hc.delimiter||-1==t.indexOf(Hc.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Hc.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Mc;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 Yc=new Dc;class Xc extends Vc{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Yc=new Dc(this.config),this.on("close",el.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Zc;broadcast=Qc;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?O.unlink(this.path,il.bind(this)):il.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Zc(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Mc;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Yc.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 Qc(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Mc;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Yc.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 el(){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 tl(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)==Yc.delimiter&&-1!=t.indexOf(Yc.delimiter))for(r.ipcBuffer="",t=Yc.parse(t);t.length>0;){let e=new Mc;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 nl(e){this.publish("close",e)}function rl(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",nl.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",tl.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 il(){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=ol.bind(this),this.server.on("listening",function(){rl.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?sl.bind(this)():this.server=A.createServer(rl.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 sl(){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=N.createServer(this.config.tls,rl.bind(this))}function ol(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 al{constructor(){}config=new jc;of={};server=!1;get connectTo(){return hl}get connectToNet(){return fl}get disconnect(){return ll}get serve(){return ul}get serveNet(){return pl}get log(){return cl}set connectTo(e){return hl}set connectToNet(e){return fl}set disconnect(e){return ll}set serve(e){return ul}set serveNet(e){return pl}set log(e){return cl}}function cl(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=o.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function ll(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 ul(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=dl),this.server=new Xc(e,this.config,cl),this.server.on("start",t)}function dl(){}function pl(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=dl),this.server=new Xc(e,this.config,cl,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function hl(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=dl),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 zc(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 fl(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=dl),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 zc(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 gl=new class extends al{constructor(){super()}IPC=al};var ml={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const vl=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),yl=e=>{try{return JSON.parse(e)}catch(e){return null}},bl="undefined"!=typeof window,Sl={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},wl={protocolPrefix:4,txtLength:4},Il=Object.values(Sl).reduce(((e,t)=>e+t),0),_l=Object.values(wl).reduce(((e,t)=>e+t),0),$l=["width","height","colorSpace"],Cl=(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)||$l.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},kl=(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},El=(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&&kl(e,s,l)}return e},xl=e=>tc(e),Al="KMSG",Nl="KCMD",Ol=xl("klProtocol");var Pl={encode:(e,t,n)=>{const r={json:e.json},i=Cl(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,u=Sl.protocolPrefix+Sl.protocolVersion+Sl.jsonLength+Sl.binaryLength+Sl.fromServiceId+Sl.toServiceId+Sl.sentAt+l+o,d=Buffer.alloc(u),p=Date.now();let h=0;return d.write(Al,h),h+=Sl.protocolPrefix,d.writeUInt8(1,h),h+=Sl.protocolVersion,d.writeUInt32LE(l,h),h+=Sl.jsonLength,d.writeUInt32LE(o,h),h+=Sl.binaryLength,d.writeUInt32LE(t,h),h+=Sl.fromServiceId,d.writeUInt32LE(n,h),h+=Sl.toServiceId,d.writeBigInt64LE(BigInt(p),h),h+=Sl.sentAt,c.copy(d,h),h+=l,s&&o&&s.copy(d,h),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Sl.protocolPrefix);if(t+=Sl.protocolPrefix,n!==Al)return null;if(e.byteLength<Il)return Ol(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Sl.protocolVersion;const i=e.readUInt32LE(t);t+=Sl.jsonLength;const s=e.readUInt32LE(t);t+=Sl.binaryLength;const o=e.readUInt32LE(t);t+=Sl.fromServiceId;const a=e.readUInt32LE(t);t+=Sl.toServiceId;const c=e.readBigInt64LE(t);t+=Sl.sentAt;const l=i+s,u=e.subarray(t,t+l),d=e.subarray(0,Il);let p=null;return e.byteLength-Il-i-s>0&&(p=e.subarray(Il+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},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=yl(n);if(!i?.json)return Ol("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&El(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=Il+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<Il)return Ol("Invalid Header Size"),e;let n=0;return n+=Sl.protocolPrefix,n+=Sl.protocolVersion,n+=Sl.jsonLength,n+=Sl.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Sl.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=_l+r,s=Buffer.alloc(i);return s.write(Nl,t),t+=wl.protocolPrefix,s.writeUint32LE(r,t),t+=wl.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<_l)return{command:null};const n=e.toString("utf-8",t,wl.protocolPrefix);if(t+=wl.protocolPrefix,n!==Nl)return{command:null};const r=e.readUInt32LE(t);t+=wl.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-_l-r;let o=null;s>0&&(o=e.subarray(_l+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Ll="KMSG",Tl="KCMD",Bl=xl("klProtocol"),jl=new TextEncoder;var Dl={encode:(e,t,n)=>{const r={json:e.json},i=Cl(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=jl.encode(a),l=c.byteLength,u=new ArrayBuffer(Sl.protocolPrefix+Sl.protocolVersion+Sl.jsonLength+Sl.binaryLength+Sl.fromServiceId+Sl.toServiceId+Sl.sentAt+l+o),d=new DataView(u),p=new Uint8Array(u),h=Date.now();let f=0;for(let e=0;e<4;++e)p[f++]=Ll.charCodeAt(e);return d.setUint8(f,1),f+=Sl.protocolVersion,d.setUint32(f,l,!0),f+=Sl.jsonLength,d.setUint32(f,o,!0),f+=Sl.binaryLength,d.setUint32(f,t,!0),f+=Sl.fromServiceId,d.setUint32(f,n,!0),f+=Sl.toServiceId,d.setBigInt64(f,BigInt(h),!0),f+=Sl.sentAt,p.set(c,f),f+=l,s&&o&&p.set(new Uint8Array(s),f),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Sl.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ll)return null;if(e.byteLength<Il)return Bl.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Sl.protocolVersion;const s=t.getUint32(n,!0);n+=Sl.jsonLength;const o=t.getUint32(n,!0);n+=Sl.binaryLength;const a=t.getUint32(n,!0);n+=Sl.fromServiceId;const c=t.getUint32(n,!0);n+=Sl.toServiceId;const l=t.getBigInt64(n,!0);n+=Sl.sentAt;const u=s+o,d=e.slice(n,n+u),p=new Uint8Array(e,0,Il);let h=null;if(e.byteLength-Il-s-o>0){h=new Uint8Array(e,Il+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:p.slice().buffer},remaining:h}},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=yl(s);if(!a?.json)return Bl.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&El(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,u=null;const d=Il+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Il)return Bl("Invalid Header Size"),e;let n=0;n+=Sl.protocolPrefix,n+=Sl.protocolVersion,n+=Sl.jsonLength,n+=Sl.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Sl.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=jl.encode(e),r=n.byteLength,i=new ArrayBuffer(_l+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=Tl.charCodeAt(e);return s.setUint32(t,r,!0),t+=wl.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<_l)return{command:null};let r="";for(let e=0;e<wl.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Tl)return{command:null};const i=t.getUint32(n,!0);n+=wl.txtLength;const s=e.byteLength-_l-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-_l)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(_l+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};const Ul=xl("klTransmissionManager"),Ml=()=>{const e=(t,n,r,i)=>{let s=n,o=null;const a=t instanceof ArrayBuffer;if(Ul(`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=Dl.decodeHeader(c)):(c=s?.partialHeaderData?Buffer.concat([s.partialHeaderData,t]):t,o=Pl.decodeHeader(c)),!o){const{command:t,missing:s,remainingData:o}=a?Dl.decodeCommand(c):Pl.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):Ul(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?(Ul(`${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 Ul(`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;Ul(`Received ${s.header.totalBytesReceived} of ${s.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?Dl.decodeFullKlMessage(s.header):Pl.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 u=l;if(o?.remaining&&(u=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),u)return Ul(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,i)}};return e};gl.config={...gl.config,...ml};const Fl={info:nc("ipcServer:info"),data:nc("ipcServer:data")};let Rl,Wl,Gl,Vl,Hl={};const zl=Ml(),ql=e=>{Hl[e]&&(Fl.info(`Client disconnected [${e}]`),delete Hl[e],Wl&&Wl(e))};var Kl=e=>(e?.ipcId&&(gl.config.id=e.ipcId),e?.ipcAppSpace&&(gl.config.appspace=e.ipcAppSpace),new Promise((e=>{gl.serve((()=>{Fl.info("IPC Server Initiated"),gl.server.on("data",((e,t)=>{const n=Hl[t.id];n?(Fl.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),zl(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Fl.data(`Received command from client [${t.id}]: ${e.command}`),void(Gl&&Gl(t.id,e.command,n));e.klMessage&&Vl&&Vl({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Fl.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),gl.server.on("connect",(e=>{const t=sc();Fl.info(`New client connected. Registered as "${t}"`),e.id=t,Hl[t]={socket:e,activeMessage:null,disconnectHandler:()=>ql(t)},e.on("close",Hl[t].disconnectHandler),Rl&&Rl(t)})),gl.server.on("disconnect",(e=>{ql(e.id)})),gl.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),gl.server.start()}))),Jl=e=>{Rl=e},Yl=e=>{Wl=e},Xl=e=>Vl=e,Zl=(e,t)=>{const n=Hl[e];if(!n)return Fl.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=vl)return Fl.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=Pl.encodeCommand(t);return n.socket.write(r),!0},Ql=(e,t)=>{const n=Hl[e];return!!n&&(Fl.info(`Renaming socket id [${e}] to [${t}]`),delete Hl[e],n.socket.id=t,Hl[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>ql(t),n.socket.on("close",n.disconnectHandler),!0)},eu=e=>{Gl=e};let tu=Pl;bl&&(tu=Dl);var nu,ru=tu;!function(e){e.FunctionNotFound="FNC_NOT_FOUND"}(nu||(nu={}));let iu=Math.ceil(Date.now()/1e3);var su={exports:{}};const ou=["nodebuffer","arraybuffer","fragments"],au="undefined"!=typeof Blob;au&&ou.push("blob");var cu={BINARY_TYPES:ou,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:au,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:lu}=cu,uu=Buffer[Symbol.species];function du(e,t,n,r,i){for(let s=0;s<i;s++)n[r+s]=e[s]^t[3&s]}function pu(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(su.exports={concat:function(e,t){if(0===e.length)return lu;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 uu(n.buffer,n.byteOffset,r):n},mask:du,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 uu(t):ArrayBuffer.isView(t)?n=new uu(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:pu},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");su.exports.mask=function(t,n,r,i,s){s<48?du(t,n,r,i,s):e.mask(t,n,r,i,s)},su.exports.unmask=function(t,n){t.length<32?pu(t,n):e.unmask(t,n)}}catch(e){}var hu=su.exports;const fu=Symbol("kDone"),gu=Symbol("kRun");const mu=B,vu=hu,yu=class{constructor(e){this[fu]=()=>{this.pending--,this[gu]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[gu]()}[gu](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[fu])}}},{kStatusCode:bu}=cu,Su=Buffer[Symbol.species],wu=Buffer.from([0,0,255,255]),Iu=Symbol("permessage-deflate"),_u=Symbol("total-length"),$u=Symbol("callback"),Cu=Symbol("buffers"),ku=Symbol("error");let Eu;var xu=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,!Eu){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Eu=new yu(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[$u];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){Eu.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){Eu.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]?mu.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=mu.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Iu]=this,this._inflate[_u]=0,this._inflate[Cu]=[],this._inflate.on("error",Ou),this._inflate.on("data",Nu)}this._inflate[$u]=n,this._inflate.write(e),t&&this._inflate.write(wu),this._inflate.flush((()=>{const e=this._inflate[ku];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=vu.concat(this._inflate[Cu],this._inflate[_u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[_u]=0,this._inflate[Cu]=[],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]?mu.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=mu.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[_u]=0,this._deflate[Cu]=[],this._deflate.on("data",Au)}this._deflate[$u]=n,this._deflate.write(e),this._deflate.flush(mu.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=vu.concat(this._deflate[Cu],this._deflate[_u]);t&&(e=new Su(e.buffer,e.byteOffset,e.length-4)),this._deflate[$u]=null,this._deflate[_u]=0,this._deflate[Cu]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function Au(e){this[Cu].push(e),this[_u]+=e.length}function Nu(e){this[_u]+=e.length,this[Iu]._maxPayload<1||this[_u]<=this[Iu]._maxPayload?this[Cu].push(e):(this[ku]=new RangeError("Max payload size exceeded"),this[ku].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ku][bu]=1009,this.removeListener("data",Nu),this.reset())}function Ou(e){this[Iu]._inflate=null,e[bu]=1007,this[$u](e)}var Pu={exports:{}};const{isUtf8:Lu}=j,{hasBlob:Tu}=cu;function Bu(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(Pu.exports={isBlob:function(e){return Tu&&"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:Bu,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]},Lu)Pu.exports.isValidUTF8=function(e){return e.length<24?Bu(e):Lu(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Pu.exports.isValidUTF8=function(t){return t.length<32?Bu(t):e(t)}}catch(e){}var ju=Pu.exports;const{Writable:Du}=T,Uu=xu,{BINARY_TYPES:Mu,EMPTY_BUFFER:Fu,kStatusCode:Ru,kWebSocket:Wu}=cu,{concat:Gu,toArrayBuffer:Vu,unmask:Hu}=hu,{isValidStatusCode:zu,isValidUTF8:qu}=ju,Ku=Buffer[Symbol.species];var Ju=class extends Du{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Mu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Wu]=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 Ku(t.buffer,t.byteOffset+e,t.length-e),new Ku(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 Ku(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[Uu.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=Fu;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]&&Hu(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[Uu.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?Gu(n,t):"arraybuffer"===this._binaryType?Vu(Gu(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=Gu(n,t);if(!this._skipUTF8Validation&&!qu(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,Fu),this.end();else{const n=e.readUInt16BE(0);if(!zu(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Ku(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!qu(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[Ru]=r,s}};const{randomFillSync:Yu}=l,Xu=xu,{EMPTY_BUFFER:Zu,kWebSocket:Qu,NOOP:ed}=cu,{isBlob:td,isValidStatusCode:nd}=ju,{mask:rd,toBuffer:id}=hu,sd=Symbol("kByteLength"),od=Buffer.alloc(4),ad=8192;let cd,ld=ad;var ud=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=ed,this[Qu]=void 0}static frame(e,t){let n,r,i=!1,s=2,o=!1;t.mask&&(n=t.maskBuffer||od,t.generateMask?t.generateMask(n):(ld===ad&&(void 0===cd&&(cd=Buffer.alloc(ad)),Yu(cd,0,ad),ld=0),n[0]=cd[ld++],n[1]=cd[ld++],n[2]=cd[ld++],n[3]=cd[ld++]),o=!(n[0]|n[1]|n[2]|n[3]),s=6),"string"==typeof e?r=t.mask&&!o||void 0===t[sd]?(e=Buffer.from(e)).length:t[sd]:(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?(rd(e,n,c,s,r),[c]):(rd(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let s;if(void 0===t)s=Zu;else{if("number"!=typeof t||!nd(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={[sd]: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):td(t)?(i=t.size,s=!1):(i=(t=id(t)).length,s=id.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[sd]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};td(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):td(t)?(i=t.size,s=!1):(i=(t=id(t)).length,s=id.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[sd]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};td(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[Xu.extensionName];let i,s,o=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):td(e)?(i=e.size,s=!1):(i=(e=id(e)).length,s=id.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={[sd]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:s,rsv1:a};td(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[sd],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(dd,this,e,i)}this._bufferedBytes-=r[sd];const s=id(t);n?this.dispatch(s,n,r,i):(this._state=0,this.sendFrame(e.frame(s,r),i),this.dequeue())})).catch((e=>{process.nextTick(pd,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const s=this._extensions[Xu.extensionName];this._bufferedBytes+=r[sd],this._state=1,s.compress(t,r.fin,((t,n)=>{if(this._socket.destroyed){dd(this,new Error("The socket was closed while data was being compressed"),i)}else this._bufferedBytes-=r[sd],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][sd],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][sd],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 dd(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 pd(e,t,n){dd(e,t,n),e.onerror(t)}const{kForOnEventAttribute:hd,kListener:fd}=cu,gd=Symbol("kCode"),md=Symbol("kData"),vd=Symbol("kError"),yd=Symbol("kMessage"),bd=Symbol("kReason"),Sd=Symbol("kTarget"),wd=Symbol("kType"),Id=Symbol("kWasClean");class _d{constructor(e){this[Sd]=null,this[wd]=e}get target(){return this[Sd]}get type(){return this[wd]}}Object.defineProperty(_d.prototype,"target",{enumerable:!0}),Object.defineProperty(_d.prototype,"type",{enumerable:!0});class $d extends _d{constructor(e,t={}){super(e),this[gd]=void 0===t.code?0:t.code,this[bd]=void 0===t.reason?"":t.reason,this[Id]=void 0!==t.wasClean&&t.wasClean}get code(){return this[gd]}get reason(){return this[bd]}get wasClean(){return this[Id]}}Object.defineProperty($d.prototype,"code",{enumerable:!0}),Object.defineProperty($d.prototype,"reason",{enumerable:!0}),Object.defineProperty($d.prototype,"wasClean",{enumerable:!0});class Cd extends _d{constructor(e,t={}){super(e),this[vd]=void 0===t.error?null:t.error,this[yd]=void 0===t.message?"":t.message}get error(){return this[vd]}get message(){return this[yd]}}Object.defineProperty(Cd.prototype,"error",{enumerable:!0}),Object.defineProperty(Cd.prototype,"message",{enumerable:!0});class kd extends _d{constructor(e,t={}){super(e),this[md]=void 0===t.data?null:t.data}get data(){return this[md]}}Object.defineProperty(kd.prototype,"data",{enumerable:!0});const Ed={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[hd]&&r[fd]===t&&!r[hd])return;let r;if("message"===e)r=function(e,n){const r=new kd("message",{data:n?e:e.toString()});r[Sd]=this,Ad(t,this,r)};else if("close"===e)r=function(e,n){const r=new $d("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[Sd]=this,Ad(t,this,r)};else if("error"===e)r=function(e){const n=new Cd("error",{error:e,message:e.message});n[Sd]=this,Ad(t,this,n)};else{if("open"!==e)return;r=function(){const e=new _d("open");e[Sd]=this,Ad(t,this,e)}}r[hd]=!!n[hd],r[fd]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[fd]===t&&!n[hd]){this.removeListener(e,n);break}}};var xd={CloseEvent:$d,ErrorEvent:Cd,Event:_d,EventTarget:Ed,MessageEvent:kd};function Ad(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:Nd}=ju;function Od(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var Pd={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,u=-1,d=0;for(;d<e.length;d++)if(l=e.charCodeAt(d),void 0===n)if(-1===u&&1===Nd[l])-1===c&&(c=d);else if(0===d||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);const r=e.slice(c,u);44===l?(Od(t,r,i),i=Object.create(null)):n=r,c=u=-1}}else-1===u&&-1!==c&&(u=d);else if(void 0===r)if(-1===u&&1===Nd[l])-1===c&&(c=d);else if(32===l||9===l)-1===u&&-1!==c&&(u=d);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d),Od(i,e.slice(c,u),!0),44===l&&(Od(t,n,i),i=Object.create(null),n=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${d}`);r=e.slice(c,d),c=u=-1}else if(o){if(1!==Nd[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:s||(s=!0),o=!1}else if(a)if(1===Nd[l])-1===c&&(c=d);else if(34===l&&-1!==c)a=!1,u=d;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${d}`);o=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===Nd[l])-1===c&&(c=d);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);let o=e.slice(c,u);s&&(o=o.replace(/\\/g,""),s=!1),Od(i,r,o),44===l&&(Od(t,n,i),i=Object.create(null),n=void 0),r=void 0,c=u=-1}}else-1===u&&(u=d);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===u&&(u=d);const p=e.slice(c,u);return void 0===n?Od(t,p,i):(void 0===r?Od(i,p,!0):Od(i,r,s?p.replace(/\\/g,""):p),Od(t,n,i)),t}};const Ld=D,Td=U,Bd=M,jd=A,Dd=N,{randomBytes:Ud,createHash:Md}=l,{URL:Fd}=F,Rd=xu,Wd=Ju,Gd=ud,{isBlob:Vd}=ju,{BINARY_TYPES:Hd,EMPTY_BUFFER:zd,GUID:qd,kForOnEventAttribute:Kd,kListener:Jd,kStatusCode:Yd,kWebSocket:Xd,NOOP:Zd}=cu,{EventTarget:{addEventListener:Qd,removeEventListener:ep}}=xd,{format:tp,parse:np}=Pd,{toBuffer:rp}=hu,ip=3e4,sp=Symbol("kAborted"),op=[8,13],ap=["CONNECTING","OPEN","CLOSING","CLOSED"],cp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let lp=class e extends Ld{constructor(t,n,r){super(),this._binaryType=Hd[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=zd,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]),dp(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Hd.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 Wd({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Gd(t,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=t,i[Xd]=this,s[Xd]=this,t[Xd]=this,i.on("conclude",vp),i.on("drain",yp),i.on("error",bp),i.on("message",wp),i.on("ping",Ip),i.on("pong",_p),s.onerror=Cp,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",Ep),t.on("data",xp),t.on("end",Ap),t.on("error",Np),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[Rd.extensionName]&&this._extensions[Rd.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())})),kp(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";gp(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||zd,n,r)):mp(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||zd,n,r)):mp(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 mp(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Rd.extensionName]||(i.compress=!1),this._sender.send(t||zd,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";gp(this,this._req,e)}}};Object.defineProperty(lp,"CONNECTING",{enumerable:!0,value:ap.indexOf("CONNECTING")}),Object.defineProperty(lp.prototype,"CONNECTING",{enumerable:!0,value:ap.indexOf("CONNECTING")}),Object.defineProperty(lp,"OPEN",{enumerable:!0,value:ap.indexOf("OPEN")}),Object.defineProperty(lp.prototype,"OPEN",{enumerable:!0,value:ap.indexOf("OPEN")}),Object.defineProperty(lp,"CLOSING",{enumerable:!0,value:ap.indexOf("CLOSING")}),Object.defineProperty(lp.prototype,"CLOSING",{enumerable:!0,value:ap.indexOf("CLOSING")}),Object.defineProperty(lp,"CLOSED",{enumerable:!0,value:ap.indexOf("CLOSED")}),Object.defineProperty(lp.prototype,"CLOSED",{enumerable:!0,value:ap.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(lp.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(lp.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[Kd])return t[Jd];return null},set(t){for(const t of this.listeners(e))if(t[Kd]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[Kd]:!0})}})})),lp.prototype.addEventListener=Qd,lp.prototype.removeEventListener=ep;var up=lp;function dp(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:op[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,!op.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${op.join(", ")})`);let s;if(t instanceof Fd)s=t;else try{s=new Fd(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 pp(e,t)}const l=o?443:80,u=Ud(16).toString("base64"),d=o?Td.request:Bd.request,p=new Set;let h,f;if(i.createConnection=i.createConnection||(o?fp:hp),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":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new Rd(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=tp({[Rd.extensionName]:h.offer()})),n.length){for(const e of n){if("string"!=typeof e||!cp.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")),f=e._req=d(i),e._redirects&&e.emit("redirect",e.url,f)}else f=e._req=d(i);i.timeout&&f.on("timeout",(()=>{gp(e,f,"Opening handshake has timed out")})),f.on("error",(t=>{null===f||f[sp]||(f=e._req=null,pp(e,t))})),f.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 gp(e,f,"Maximum redirects exceeded");let s;f.abort();try{s=new Fd(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void pp(e,n)}dp(e,s,n,r)}else e.emit("unexpected-response",f,s)||gp(e,f,`Unexpected server response: ${s.statusCode}`)})),f.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==lp.CONNECTING)return;f=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void gp(e,n,"Invalid Upgrade header");const o=Md("sha1").update(u+qd).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void gp(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 gp(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!h){return void gp(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=np(l)}catch(t){return void gp(e,n,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==Rd.extensionName){return void gp(e,n,"Server indicated an extension that was not requested")}try{h.accept(t[Rd.extensionName])}catch(t){return void gp(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Rd.extensionName]=h}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(f,e):f.end()}function pp(e,t){e._readyState=lp.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function hp(e){return e.path=e.socketPath,jd.connect(e)}function fp(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=jd.isIP(e.host)?"":e.host),Dd.connect(e)}function gp(e,t,n){e._readyState=lp.CLOSING;const r=new Error(n);Error.captureStackTrace(r,gp),t.setHeader?(t[sp]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(pp,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function mp(e,t,n){if(t){const n=Vd(t)?t.size:rp(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${ap[e.readyState]})`);process.nextTick(n,t)}}function vp(e,t){const n=this[Xd];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[Xd]&&(n._socket.removeListener("data",xp),process.nextTick($p,n._socket),1005===e?n.close():n.close(e,t))}function yp(){const e=this[Xd];e.isPaused||e._socket.resume()}function bp(e){const t=this[Xd];void 0!==t._socket[Xd]&&(t._socket.removeListener("data",xp),process.nextTick($p,t._socket),t.close(e[Yd])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Sp(){this[Xd].emitClose()}function wp(e,t){this[Xd].emit("message",e,t)}function Ip(e){const t=this[Xd];t._autoPong&&t.pong(e,!this._isServer,Zd),t.emit("ping",e)}function _p(e){this[Xd].emit("pong",e)}function $p(e){e.resume()}function Cp(e){const t=this[Xd];t.readyState!==lp.CLOSED&&(t.readyState===lp.OPEN&&(t._readyState=lp.CLOSING,kp(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function kp(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),ip)}function Ep(){const e=this[Xd];let t;this.removeListener("close",Ep),this.removeListener("data",xp),this.removeListener("end",Ap),e._readyState=lp.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Xd]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Sp),e._receiver.on("finish",Sp))}function xp(e){this[Xd]._receiver.write(e)||this.pause()}function Ap(){const e=this[Xd];e._readyState=lp.CLOSING,e._receiver.end(),this.end()}function Np(){const e=this[Xd];this.removeListener("error",Np),this.on("error",Zd),e&&(e._readyState=lp.CLOSING,this.destroy())}const{tokenChars:Op}=ju;var Pp={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===Op[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 Lp=D,Tp=M,{createHash:Bp}=l,jp=Pd,Dp=xu,Up=Pp,Mp=up,{GUID:Fp,kWebSocket:Rp}=cu,Wp=/^[+/0-9A-Za-z]{22}==$/;var Gp=class extends Lp{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:Mp,...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=Tp.createServer(((e,t)=>{const n=Tp.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(Vp,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(Vp,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Vp(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",Hp);const i=e.headers["sec-websocket-key"],s=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void qp(this,e,t,405,"Invalid HTTP method")}if(void 0===s||"websocket"!==s.toLowerCase()){return void qp(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!Wp.test(i)){return void qp(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void qp(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void zp(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=Up.parse(a)}catch(n){return void qp(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&void 0!==l){const n=new Dp(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=jp.parse(l);e[Dp.extensionName]&&(n.accept(e[Dp.extensionName]),u[Dp.extensionName]=n)}catch(n){return void qp(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 zp(t,o||401,a,l);this.completeUpgrade(u,i,c,e,t,n,r)}));if(!this.options.verifyClient(s))return zp(t,401)}this.completeUpgrade(u,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,s,o){if(!i.readable||!i.writable)return i.destroy();if(i[Rp])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return zp(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Bp("sha1").update(t+Fp).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[Dp.extensionName]){const t=e[Dp.extensionName].params,n=jp.format({[Dp.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",Hp),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(Vp,this)}))),o(c,r)}};function Vp(e){e._state=2,e.emit("close")}function Hp(){this.destroy()}function zp(e,t,n,r){n=n||Tp.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} ${Tp.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function qp(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,qp),e.emit("wsClientError",r,n,t)}else zp(n,r,i)}var Kp=Ua(Gp);const Jp=nc("websocketServer"),Yp={},Xp=Ml();let Zp,Qp,eh,th,nh;const rh=e=>{const t=Yp[e];t&&t.socket.close()};var ih={startServer:e=>{nh=new Kp({port:e,maxPayload:104857600}),nh.on("connection",(e=>{const t=sc();Jp(`New client connected. Registered as "${t}"`),e.id=t,Yp[t]={socket:e,activeMessage:null},Zp&&Zp(t),e.on("message",(t=>{if(t instanceof Buffer){const n=Yp[e.id];Xp(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),Jp(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{rh(n.socket.id)};if(t.command)return Jp(`Received command from client [${n.socket.id}]: ${t.command}`),void(eh&&eh(n.socket.id,t.command,r,i));t.klMessage&&th&&th({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",(()=>{Jp(`Client disconnected: ${e.id}`),Qp&&Qp(e.id),delete Yp[e.id]})),e.on("error",(()=>{Jp(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},stopServer:()=>{nh.close((()=>{console.log("WebSocket server stopped")}))},onClientConnected:e=>{Zp=e},onClientDisconnected:e=>{Qp=e},onClientCommand:e=>{eh=e},sendCommand:(e,t)=>{const n=Yp[e];if(!n)return Jp(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=vl)return Jp("Message is too long to be a command. Use sendMessage instead."),!1;const r=Pl.encodeCommand(t);return n.socket.send(r),!0},onMessageReceived:e=>th=e,terminateConnection:rh};const sh=nc("stopService"),oh=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Bc.getAllServiceVersions(t);sh(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Bc.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},ah=nc("removeService"),ch=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Bc.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),ah(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Bc.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},lh=nc("launchService"),uh=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=vc();lh(`Loading service ${t}@${n} from ${i}`);const{errorMsg:s,service:o,errorCode:a}=await Bc.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,u=async()=>{const r=o.status;return"running"===r?(lh(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(lh(`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"}):(lh("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return lh(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},dh=nc("getMatchingServices"),ph=async e=>{const t=e.args[0],n=[],r=[];dh(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=Bc.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:Bc.getServiceRootDirectory(t)}):r.push({name:e,version:i})}dh(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},hh=nc("getSecretsValues");let fh;var gh=async e=>{const t=e.args[0].services;if(!fh)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");hh(`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 fh({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})},mh=e=>{fh=e};const vh=nc("getMappedSecrets");let yh;var bh=async e=>{const t=e.args[0].services;vh(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await yh(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})},Sh=e=>{yh=e};const wh=nc("getServiceContents"),Ih=({reply:e,args:t})=>{const[n]=t;wh(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Bc.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}]})}wh(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let _h=null;const $h=async e=>{const{data:t,error:n}=await(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}}})(`${(()=>{if(!_h)throw new Error("Unknown server URL. Please call `setServerUrl` before using the APIs.");return _h})()}/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"}},Ch={},kh=async e=>{const t=(e=>{const t=Ch[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 $h(e);return n&&(Ch[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}},Eh=nc("activeClients");let xh={},Ah={};const Nh=(e,t)=>`${e}_${t}`,Oh=e=>xh[e]||null,Ph=(e,t)=>{const n=Nh(e,t);return Ah[n]||[]},Lh=()=>{for(const e in xh){const t=xh[e];if(t?.transport===Sa.WS){const e=Pl.encodeCommand(va.ServicesListChanged);t.send(e)}}},Th=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===Sa.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 kh(o.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&Eh(`Unable to validate API Key, usage will be limited. SessionId: ${n}`)}xh[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=Nh(e.serviceName,e.version);Ah[r]=Ah[r]||[];return Ah[r].some((e=>e.serviceId===n))||Ah[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=Nh(e.serviceName,e.version),s=Ah[i]?.findIndex((e=>e.serviceId===n));if(-1!==s&&(Ah[i].splice(s,1),!Ah[i].length)){const t=Bc.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=Oh(t.info.sessionId);e?.extraInfo.ipcSocketId&&Zl(e?.extraInfo.ipcSocketId,va.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=Nh(e.targetService.serviceName,e.targetService.version),r=Ah[t].findIndex((e=>e.serviceId===n));-1!==r&&Ah[t].splice(r,1)}t.length=0}},r===Sa.IPC&&(Lh(),jh(n))},Bh=()=>{const e=Object.values(xh);for(const t of e)if(t.transport===Sa.IPC){const e=t.extraInfo.ipcSocketId,n=Bc.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){Ph(n.info.name,n.info.version).length||e&&Zl(e,va.BroadcastEnd)}}},jh=e=>{const t=Bc.getServiceBySessionId(e);if(t?.info.eventEmitter){if(Ph(t.info.name,t.info.version).length){const t=Oh(e);t?.extraInfo.ipcSocketId&&Zl(t?.extraInfo.ipcSocketId,va.BroadcastStart)}}},Dh=e=>{const t=xh[e];delete xh[e],t?.transport===Sa.IPC?Lh():(t?.removeAllSubscriptions(),Bh())},Uh=nc("ipc:handleIpcClientCommand"),Mh=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(va.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 Uh(`Ignoring ACK response from IPC service ${e} with no service id`);Uh(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(Ql(e,t),r=t);let i=!1;t&&(i=Bc.setServiceStatus(t,"running")),i?Th({serviceSessionId:t||e,transport:Sa.IPC,send:n,extraInfo:{ipcSocketId:t}}):Zl(r,va.SendManifest)}));!r&&Uh(`Received unknown command [${t}] from service ${e}`)};let Fh={};W.platform();const Rh=async e=>{const t=e.args[0];if(Fh.chooseDirectory)try{const n=await Fh.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"})},Wh=async e=>{const t=e.args[0];if(Fh.chooseFile)try{const n=await Fh.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"})},Gh=e=>{Fh=e};var Vh={},Hh={},zh={};function qh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Kh(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Jh(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Yh(e,...t){if(!Jh(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 Xh(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");qh(e.outputLen),qh(e.blockLen)}function Zh(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 Qh(e,t){Yh(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(zh,"__esModule",{value:!0}),zh.output=zh.exists=zh.hash=zh.bytes=zh.bool=zh.number=zh.isBytes=void 0,zh.number=qh,zh.bool=Kh,zh.isBytes=Jh,zh.bytes=Yh,zh.hash=Xh,zh.exists=Zh,zh.output=Qh;const ef={number:qh,bool:Kh,bytes:Yh,hash:Xh,exists:Zh,output:Qh};zh.default=ef;var tf={};Object.defineProperty(tf,"__esModule",{value:!0}),tf.add5L=tf.add5H=tf.add4H=tf.add4L=tf.add3H=tf.add3L=tf.add=tf.rotlBL=tf.rotlBH=tf.rotlSL=tf.rotlSH=tf.rotr32L=tf.rotr32H=tf.rotrBL=tf.rotrBH=tf.rotrSL=tf.rotrSH=tf.shrSL=tf.shrSH=tf.toBig=tf.split=tf.fromBig=void 0;const nf=BigInt(2**32-1),rf=BigInt(32);function sf(e,t=!1){return t?{h:Number(e&nf),l:Number(e>>rf&nf)}:{h:0|Number(e>>rf&nf),l:0|Number(e&nf)}}function of(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}=sf(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}tf.fromBig=sf,tf.split=of;const af=(e,t)=>BigInt(e>>>0)<<rf|BigInt(t>>>0);tf.toBig=af;const cf=(e,t,n)=>e>>>n;tf.shrSH=cf;const lf=(e,t,n)=>e<<32-n|t>>>n;tf.shrSL=lf;const uf=(e,t,n)=>e>>>n|t<<32-n;tf.rotrSH=uf;const df=(e,t,n)=>e<<32-n|t>>>n;tf.rotrSL=df;const pf=(e,t,n)=>e<<64-n|t>>>n-32;tf.rotrBH=pf;const hf=(e,t,n)=>e>>>n-32|t<<64-n;tf.rotrBL=hf;const ff=(e,t)=>t;tf.rotr32H=ff;const gf=e=>e;tf.rotr32L=gf;const mf=(e,t,n)=>e<<n|t>>>32-n;tf.rotlSH=mf;const vf=(e,t,n)=>t<<n|e>>>32-n;tf.rotlSL=vf;const yf=(e,t,n)=>t<<n-32|e>>>64-n;tf.rotlBH=yf;const bf=(e,t,n)=>e<<n-32|t>>>64-n;function Sf(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}tf.rotlBL=bf,tf.add=Sf;const wf=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);tf.add3L=wf;const If=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;tf.add3H=If;const _f=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);tf.add4L=_f;const $f=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;tf.add4H=$f;const Cf=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);tf.add5L=Cf;const kf=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0;tf.add5H=kf;const Ef={fromBig:sf,split:of,toBig:af,shrSH:cf,shrSL:lf,rotrSH:uf,rotrSL:df,rotrBH:pf,rotrBL:hf,rotr32H:ff,rotr32L:gf,rotlSH:mf,rotlSL:vf,rotlBH:yf,rotlBL:bf,add:Sf,add3L:wf,add3H:If,add4L:_f,add4H:$f,add5H:kf,add5L:Cf};tf.default=Ef;var xf={},Af={};Object.defineProperty(Af,"__esModule",{value:!0}),Af.crypto=void 0,Af.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"util";import a from"emittery";import"axios";import c from"jszip";import l,{scryptSync as u,createDecipheriv as d,createHash as p}from"crypto";import{satisfies as h}from"compare-versions";import f from"debug";import g,{join as m,dirname as v,resolve as y}from"path";import"node-ipc";import{mkdir as b,readFile as S,access as w,constants as I,readdir as _,rm as $}from"fs/promises";import C from"minimist";import k from"tty";import E,{homedir as x}from"os";import A from"net";import N from"tls";import O,{promises as P}from"fs";import L from"dgram";import T from"stream";import B from"zlib";import j from"buffer";import D from"events";import U from"https";import M from"http";import F,{fileURLToPath as R}from"url";import W from"node:os";import{spawn as G}from"child_process";import{join as V,resolve as H,dirname as z}from"node:path";import{ImageData as q,loadImage as K,createCanvas as J}from"@napi-rs/canvas";var Y;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(Y=Y||(Y={}));const X={};let Z=0,Q="";const ee=e=>X[e]?X[e]:null,te=(e,t)=>{const n=ee(e);if(!n)return n;return n.blocks[t]||null},ne=(e,t,n)=>{const r=te(e,t);if(!r)return r;return r.gates[n]},re=(e,t)=>{let n=r(4);for(;X[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!==Z){const t=new Date;Z=e,Q=t.toJSON()}return Q})()}:: ${e}\n`},i.dbInfo={...t},X[n]=i,n},ie="interrupt_port",se="main.js",oe="state.json",ae="{#}",ce="$var_",le="default";var ue,de,pe,he,fe,ge,me,ve;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(ue||(ue={})),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"}(de||(de={})),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"}(pe||(pe={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(he||(he={})),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:"}(fe||(fe={})),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.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId"}(ge||(ge={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(me||(me={})),function(e){e.IPC="ipc",e.WS="ws"}(ve||(ve={}));const ye="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,be="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,Se="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,we="-",Ie=`inner${we}`,_e=`outer${we}`,$e=`${_e}input${we}`,Ce=`${_e}output${we}`,ke=`${Ie}input${we}`,Ee=`${Ie}output${we}`,xe=e=>(new TextEncoder).encode(e),Ae=e=>e===ie,Ne=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Oe=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,Pe=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Le=e=>"number"==typeof e?de.Number:"string"==typeof e?de.String:"boolean"==typeof e?de.Boolean:Array.isArray(e)?de.Array:Ne(e)?de.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?de.AudioBuffer:e&&void 0!==e.byteLength?de.ArrayBuffer:Oe(e)?de.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?de.Point:de.JsonObj,Te=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Le(n[e]);t[e]=r}return t},Be=(e,t,n)=>"inner"===e?"input"===t?`${ke}${n}`:`${Ee}${n}`:"input"===t?`${$e}${n}`:`${Ce}${n}`,je=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]}},De=e=>new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace});var Ue,Me;!function(e){e.Action="action",e.CustomInput="customInput"}(Ue=Ue||(Ue={})),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"}(Me=Me||(Me={}));const Fe={};let Re;const We=async e=>{const t=Fe[e],n={name:ie,type:de.Boolean};if(t){const r={name:t.portName},i=t.data||{type:de.Boolean,value:!0};Re?(await Re(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...i,timestamp:Date.now()},[n]),"timeout"===t.type&&Ge(e)):console.warn("Interrupt service has not been initialized")}},Ge=e=>{const t=Fe[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete Fe[e],!0)};var Ve={interruptHandler:We,createInterrupt:(e,t,n,i,s,o,a,c)=>{if(c&&Fe[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(Fe[l]={data:a,portName:s,recipePoolId:t,targetWidgetId:i,thingId:n,type:e},"interval"===e)Fe[l].timerRef=setInterval((async()=>await We(l)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);Fe[l].timerRef=setTimeout((async()=>await We(l)),o.timeout)}return l},destroyInterrupt:Ge,destroyAllInterrupts:()=>{Object.keys(Fe).forEach(Ge)},setInvokeChildGateCb:e=>{Re=e}};const He=(e,t,n,r,i)=>{const s=ne(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)=>Ve.createInterrupt(t,e,n,r,i,s,o),a=()=>Object.freeze({...s.state,...s.type===Me.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===Me.input&&!e.customInputs&&{customInputs:[]}};s.state=t};if(i){return{getState:a,setState:c,registerInterrupt:o,getStorageData:async t=>{const r=((e,t,n)=>{const r=ee(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=te(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},recipePoolId:e,recipeType:t,thingRecipeId:n,widgetThingId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r}},ze=[10001,"Invalid `sourcePort` parameter"],qe=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],Ke=[10110,"No storage medium has been loaded, call `loadMedium()` first"],Je=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?o.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),Ye=()=>({inputName:"",dataType:de.Anything}),Xe="output",Ze={processEvent:async(e,t)=>{const n=t.getState(),r={...Ye(),...n};if(e.type===r.dataType||r.dataType===de.Anything)return t.nextWidget(Xe,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...Ye(),...e};return[{name:Xe,type:t.dataType}]},getInputNames:()=>[]},Qe=Object.freeze({in:"in",reset:"reset",increment:"increment"}),et="output";var tt={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(Je(ze));const i={currentValue:0,increment:1,...r.getState()};let s=i.increment,o=i.currentValue;const a=await r.getParentAtPort(Qe.increment);if(t.name===Qe.increment)return void(n.data.type===de.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(s=e)}if(t.name===Qe.reset)return r.setState({...i,currentValue:0});o+=s,r.setState({currentValue:o,increment:s});const c={type:de.Number,value:o};return r.nextGate(et,c)},getInputNames:()=>[{name:Qe.in,type:de.Anything},{name:Qe.reset,type:de.Anything},{name:Qe.increment,type:de.Number}],getOutputNames:()=>[{name:et,type:de.Number}]};const nt=Object.freeze({in:"in",reset:"reset"}),rt="output";var it={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===nt.reset?r.setState({...i,updatedAt:s,elapsed:0}):(r.setState({updatedAt:s,elapsed:o}),r.nextGate(rt,{type:de.Number,value:o}))},getInputNames:()=>[{name:nt.in,type:de.Anything},{name:nt.reset,type:de.Anything}],getOutputNames:()=>[{name:rt,type:de.Number}]};const st=Object.freeze({data:"data",evaluation:"evaluation"}),ot="then",at="else";var ct={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===de.Number||n.data.type===de.String||n.data.type===de.Anything&&o||n.data.type===de.Anything&&a)){let e=!1;return("Equal"===i.condition&&n.data.value==i.value||"Not Equal"===i.condition&&n.data.value!==i.value||"Greater"===i.condition&&n.data.value>Number(i.value)||"Less"===i.condition&&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(ot,n.data):r.nextGate(at,n.data)}if((t.name===st.evaluation&&n.data.type===de.Number||n.data.type===de.String||n.data.type===de.Anything&&(o||a))&&(i.$lastValue=n.data.value,r.setState({...i})),t.name===st.data){let e=!1;return("Equal"===i.condition&&i.$lastValue==i.value||"Not Equal"===i.condition&&i.$lastValue!==i.value||"Greater"===i.condition&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&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,$lastDataType:n.data.type}),e?r.nextGate(ot,n.data):r.nextGate(at,n.data)}},getInputNames:e=>e.useDataPort?[{name:st.data,type:de.Anything},{name:st.evaluation,type:[de.Number,de.String]}]:[{name:"in",type:[de.Number,de.String]}],getOutputNames:e=>e.$lastDataType?[{name:ot,type:e.$lastDataType},{name:at,type:e.$lastDataType}]:[{name:ot,type:[de.Number,de.String]},{name:at,type:[de.Number,de.String]}]};const lt=Object.freeze({in:"in",reset:"reset"}),ut="out";var dt={onParentEvent:async(e,t,n,r)=>{const i={totalCalls:0,callsLimit:1,...r.getState()};return t.name===lt.reset?r.setState({...i,totalCalls:0}):(i.totalCalls=i.totalCalls+1,i.totalCalls>i.callsLimit?(i.totalCalls=0,r.setState(i),r.nextGate(ut,n.data)):void r.setState(i))},getInputNames:()=>[{name:lt.in,type:de.Anything},{name:lt.reset,type:de.Anything}],getOutputNames:()=>[{name:ut,type:de.Anything}]};const pt=Object.freeze({in:"in"}),ht="then",ft="else";var gt={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:10,...r.getState()};if(n.data.type===de.Number)return n.data.value>=i.min&&n.data.value<=i.max?r.nextGate(ht,n.data):r.nextGate(ft,n.data)},getInputNames:()=>[{name:pt.in,type:de.Number}],getOutputNames:()=>[{name:ht,type:de.Number},{name:ft,type:de.Number}]};const mt=Object.freeze({in:"in"}),vt="out";var yt={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===de.Number||n.data.type===de.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(vt,{type:de.Number,value:Number(e)})}},getInputNames:()=>[{name:mt.in,type:de.Number}],getOutputNames:()=>[{name:vt,type:de.Number}]};const bt=Object.freeze({in:"in"}),St="out";var wt={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let s=n.data.value;if(n.data.type===de.Number||n.data.type===de.Anything||n.data.type===de.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(St,{type:"String"===i.convertTo?de.String:de.Number,value:s})}},getInputNames:()=>[{name:bt.in,type:de.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?de.String:de.Number;return[{name:St,type:t}]}};const It=Object.freeze({in:"in"}),_t="out";var $t={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.nextGate(_t,{type:de.Number,value:i.currentValue})},getInputNames:()=>[{name:It.in,type:de.Anything}],getOutputNames:()=>[{name:_t,type:de.Number}]};const Ct=Object.freeze({in:"in",reset:"reset"}),kt="out";var Et={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},s={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Ct.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(kt,n.data)):void 0},getInputNames:()=>[{name:Ct.in,type:de.Anything},{name:Ct.reset,type:de.Anything}],getOutputNames:()=>[{name:kt,type:de.Anything}]};const xt="in";var At={onParentEvent:async()=>{},getInputNames:()=>[{name:xt,type:[de.ImageData,de.Number]}],getOutputNames:()=>[]};const Nt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),Ot=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var Pt={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===de.JsonObj||n.data.type===de.Rect||n.data.type===de.Anything||o){let e=!1;for(const t in s){const n=Le(s[t]),r=!!i.detectedProperties[t],o=i.detectedProperties[t]?.type!==n;if(!r||o){const r=n===de.JsonObj||n===de.Rect||n===de.Array;i.detectedProperties[t]={type:n,...r?{shape:Te(s[t])}:void 0},e=!0}}if(o&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:de.Number}),e&&r.setState(i),s){const e=[];for(const t of i.properties||[]){const n=Ot(s,t.label),o=t.label.includes(".");if(void 0!==n){const s=o?Le(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:de.Anything;e.push(r.nextGate(t.name,{type:s,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:de.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:de.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:Nt};const Lt="output",Tt="noItem";var Bt={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===de.Anything&&(c||a)||n.data.type===de.String&&a||n.data.type===de.Array&&c){s<0&&(s=o.length+s);const e=a?de.String:Le(o[s]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==o[s]?r.nextGate(Lt,{value:o[s],type:e}):r.nextGate(Tt,{value:!0,type:de.Boolean})}},getInputNames:()=>[{name:"in",type:[de.Array,de.String]}],getOutputNames:e=>[{name:Lt,type:e.$$lastDetectedType??de.Anything},{name:Tt,type:de.Boolean}]};let jt;const Dt=e=>{jt=e},Ut=(e,t)=>(()=>{if(!jt)throw new Error("CanvasManager not set");return jt})().createCanvas(e,t),Mt=e=>ye?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Ft=Object.freeze({image:"image",rect:"rect"}),Rt="image";var Wt={onParentEvent:async(e,t,n,r)=>{const i={offset:{height:0,left:0,top:0,width:0},...r.getState()},s=await r.getParentAtPort(Ft.rect),o=[de.Anything,de.Rect,de.JsonObj];if(t.name!==Ft.rect){if(s){const e=s.getValue();null!==e&&(i.rect={...e},r.setState(i))}if(!ye)return n.data.type===de.ImageData?r.nextGate(Rt,n.data):void 0;if(i.$$canvasFrom&&i.$$canvasFrom.getContext||(i.$$canvasFrom=Ut(320,240)),i.$$canvasTo&&i.$$canvasTo.getContext||(i.$$canvasTo=Ut(320,240)),(n.data.type===de.ImageData||n.data.type===de.Anything&&Ne(n.data.value))&&!i.$$processing&&i.$$canvasFrom&&i.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})(n.data.value,i.rect,i.$$canvasFrom,i.$$canvasTo,i.offset);return r.nextGate(Rt,{type:de.ImageData,value:e})}}else Oe(n.data.value)&&o.includes(n.data.type)&&r.setState({...i,rect:n.data.value})},getInputNames:()=>[{name:Ft.image,type:de.ImageData},{name:Ft.rect,type:[de.Rect,de.JsonObj]}],getOutputNames:()=>[{name:Rt,type:de.ImageData}]};const Gt=(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(ye)return new ImageData(t,n);return console.warn("Node environment detected. Aborting new ImageData creation"),e})(e,a,c),u=l.data;for(let e=0;e<c;e++)for(let c=0;c<a;c++){const l=e,d=c,p=4*(e*a+c);let h=0,f=0,g=0,m=0;for(let e=0;e<n;e++)for(let a=0;a<n;a++){const c=l+e-r,u=d+a-r;if(c>=0&&c<o&&u>=0&&u<s){const r=4*(c*s+u),o=t[e*n+a];h+=i[r]*o,f+=i[r+1]*o,g+=i[r+2]*o,m+=i[r+3]*o}}u[p]=h,u[p+1]=f,u[p+2]=g,u[p+3]=m+1*(255-m)}return l},Vt=[-1,0,1,-2,0,2,1,0,1],Ht=Object.freeze({image:"image"}),zt="image";var qt={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={matrix:[...Vt],...i};if(n.data.type===de.ImageData||n.data.type===de.Anything&&Ne(n.data.value)){const e=Gt(n.data.value,s.matrix);return r.nextGate(zt,{type:de.ImageData,value:e})}},getInputNames:()=>[{name:Ht.image,type:de.ImageData}],getOutputNames:()=>[{name:zt,type:de.ImageData}]};const Kt=Object.freeze({output:"output",aborted:"aborted"}),Jt=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),Yt=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:de.Anything})));return n.push({name:"reset",type:de.Anything}),n};var Xt={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(Kt.aborted,n.data);{i.triggeredAt=s;const e=Yt(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(Kt.output,n.data),r.setState(i)}},getInputNames:Yt,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:de.Anything})));return e.push({name:Kt.aborted,type:de.Anything}),e}return[{name:Kt.output,type:de.Anything},{name:Kt.aborted,type:de.Anything}]},getDefaultState:Jt};const Zt=(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)}},Qt=(e,t,n,r,i,s,o)=>{e.fillStyle=i,e.fillRect(t,n,r,r),Zt(e,t,n,i,s,o)},en=(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;Zt(e,t.left-o,t.top-o,r,i,s)},tn=Object.freeze({image:"image",pixels:"pixels"}),nn="image";var rn={onParentEvent:async(e,t,n,r)=>{const i={fontSize:12,color:"#00ff00",size:2,...r.getState()},s=n.data.type===de.ImageData||n.data.type===de.Anything&&Ne(n.data.value);if(t.name===tn.pixels){const e=((e,t)=>t===de.Anything&&(Ne(e)||Pe(e)||Oe(e)||Array.isArray(e))||t===de.Array||t===de.Rect||t===de.Point)(n.data.value,n.data.type);if(!e)return;i.$$pixels=n.data.value}if(t.name===tn.image&&s){const e=n.data.value;i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ut(e.width||1,e.height||1)),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=Mt(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]:"";Oe(n)?en(e,n,i,s,r,a):Pe(n)&&Qt(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:i.size,color:i.color,labelProp:i.labelProp,fontSize:i.fontSize});return r.setState({...i,$$lastFrame:void 0,$$pixels:void 0}),r.nextWidget(nn,{type:de.ImageData,value:e})}r.setState(i)},getInputNames:()=>[{name:tn.image,type:de.ImageData},{name:tn.pixels,type:[de.Rect,de.Point,de.Array]}],getOutputNames:()=>[{name:nn,type:de.ImageData}]};const sn=Object.freeze({in:"in"}),on="output",an=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var cn={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,u=i.max,Math.random()*(u-l)+l);var l,u;if(a){let e=0;if(s&&(e=an(i.min)),o){const t=an(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(on,{type:de.Number,value:c})},getInputNames:()=>[{name:sn.in,type:de.Anything}],getOutputNames:()=>[{name:on,type:de.Number}]};const ln=Object.freeze({output:"output",totalItems:"totalItems"}),un=Object.freeze({trigger:"trigger",clear:"clear"}),dn=()=>({totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),pn=async(e,t)=>t.nextGate(ln.totalItems,{type:de.Number,value:e});var hn={onParentEvent:async(e,t,n,r)=>{const i={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===un.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),pn(i.$$list.length,r);const s=t.name===un.trigger;if(!s)if(Array.isArray(n.data.value))n.data.type!==de.Array&&n.data.type!==de.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await pn(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===de.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 pn(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 pn(e,r),r.nextGate(ln.output,{type:de.Array,value:t})}},getInputNames:e=>{const t={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`array${t+1}`,type:de.Array})));return n.push({name:un.clear,type:de.Anything},{name:un.trigger,type:de.Anything}),n},getOutputNames:e=>[{name:ln.output,type:de.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:ln.totalItems,label:"Total Items",type:de.Number}],getDefaultState:dn};const fn=Object.freeze({start:"start",stop:"stop"}),gn="output",mn="clock_interrupt";var vn={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(Ae(e?.name||"")&&t.name===mn)return r.nextGate(gn,{type:de.Boolean,value:!0});if(t.name===fn.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!==fn.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt("interval",mn,{interval:i.interval}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:fn.start,type:de.Anything},{name:fn.stop,type:de.Anything}],getOutputNames:()=>[{name:gn,type:de.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",mn,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const yn=Object.freeze({in:"in"}),bn="output",Sn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var wn={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===de.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>Sn(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]=Sn(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===de.Number&&(o=Sn(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(bn,{type:s,value:o})},getInputNames:()=>[{name:yn.in,type:[de.Array,de.Number]}],getOutputNames:e=>[{name:bn,type:e.detectedInputType||de.Number,jsonShape:e.detectedInputJson}]};const In=Object.freeze({output:"output"}),_n=Object.freeze({trigger:"trigger"}),$n=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:de.Number,value:10},{name:"y",label:"y",type:de.Number,value:20}]}),Cn=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},kn=e=>{const t={};for(let n=0;n<e.properties.length;n++){let r=e.properties[n].value;const i=e.properties[n].type;i===de.Number?r=Number(r):i===de.String&&(r=String(r)),t[e.properties[n].label]=r}return t};var En={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s=structuredClone(i),o={...$n(),...s};if(t.name===_n.trigger){const e=kn(o);return r.nextGate(In.output,{type:de.JsonObj,value:e})}const a=o.properties.findIndex((e=>e.name===t.name));if(-1!==a){let e=n.data.type===o.properties[a].type;if(!e&&n.data.type===de.Anything){e=Le(n.data.type)===o.properties[a].type}if(e?(o.properties[a].value=n.data.value,o.properties[a].$$invalidInputType=!1):o.properties[a].$$invalidInputType=!0,r.setState(o),!o.useTriggerPort){const e=kn(o);return r.nextGate(In.output,{type:de.JsonObj,value:e})}}},getInputNames:e=>{const t={...$n(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:_n.trigger,label:_n.trigger,type:de.Anything}),n},getOutputNames:e=>[{name:In.output,label:In.output,type:de.JsonObj,jsonShape:Cn(e)}],getDefaultState:$n};const xn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith($e)){const n=t(e,$e);return Be("inner","input",n)}if(e.startsWith(Ee)){const n=t(e,Ee);return Be("outer","output",n)}return null},An=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[de.Anything],index:0}],outputs:[{name:"output",type:[de.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Nn=e=>{const t={...An(),...e},n=t.inputs.map(((e,t)=>({name:Be("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:Be("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 On={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...An(),...i},o=Nn(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(de.Anything)||i.type.includes(n.data.type))){const e=await xn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Nn,getOutputNames:e=>{const t={...An(),...e},n=t.outputs.map(((e,t)=>({name:Be("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:Be("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:An};const Pn=(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 Ln,Tn,Bn,jn,Dn,Un,Mn,Fn,Rn,Wn,Gn={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,u=n,d=o,p=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,h]=n;o<0||h<0||o>=r||h>=i||s.has(`${o},${h}`)||!Pn(o,h,e,t,a||0)||(s.add(`${o},${h}`),l=Math.min(l,o),u=Math.max(u,o),d=Math.min(d,h),p=Math.max(p,h),c.push([o+1,h],[o-1,h],[o,h+1],[o,h-1]))}return{minX:l,maxX:u,minY:d,maxY:p}},l=[];for(let o=0;o<i;o+=4)for(let i=0;i<r;i+=4)if(!s.has(`${i},${o}`)&&Pn(i,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:s}=c(i,o),a=t-e,u=s-r;if(a>=(n.minWidth||1)&&u>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:u}),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}};!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Ln||(Ln={})),function(e){e.Bundle="bundle",e.Group="group"}(Tn||(Tn={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Bn||(Bn={})),function(e){e.Cloud="cloud",e.Web="web"}(jn||(jn={})),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"}(Dn||(Dn={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Un||(Un={})),(Mn||(Mn={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Fn||(Fn={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Rn||(Rn={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Wn||(Wn={}));let Vn=null;var Hn=()=>{if(!Vn)throw new Error("Required function is not set");return Vn};class zn extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const qn=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===Ln.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\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===Ln.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`,Kn=(e,t,n,r)=>{const o=qn(e,n),a={...t,document:{},__errorTracer:e=>{throw new zn(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:Gn,...n===Ln.Cloud?{require:Hn(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:i,CryptoJS:s,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(ye)return"browser";if(Se)return"node";if(be)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}}}},Jn="main",Yn=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},pages:{[Jn]:{code:"\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",language:"javascript",name:"My First Script"}},consoleVisible:!1,$$consoleLines:[]}),Xn=(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 qn(t,e).split(t)[0].split("\n").length+2})(t),n.column=i.column)}return e.message&&(n.message=e.message),n},Zn=(e,t)=>{const n={...Yn(),...t.getState()},r={...n,...e?{$$error:e}:void 0,...n.autoPauseOnError&&e?{pauseExecution:!0}:void 0};e&&(r.$$consoleLines=[...r.$$consoleLines,{type:"error",text:e.message,timestamp:Date.now(),fileName:Jn}]),t.setState(r)};var Qn,er;!function(e){e.ServiceCreationLog="service-creation-log"}(Qn=Qn||(Qn={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(er=er||(er={}));const tr=new a,nr=(e,t,n)=>{const r=te(e,t);if(!r)throw new Error(`Thing ${t} not found in recipe ${e}`);const i=r.gates[n];if(!i)throw new Error(`Widget ${n} not found in thing ${t}`);return i},rr=(e,t,n)=>`${t}:${n}:${e}`,ir=e=>`${e}:new-var`,sr=e=>`value-change:${e}`,or=async(e,t,n,r,i,s,o)=>{const a={...o},c={thingId:n,recipeId:t,variableName:e,changes:s,ownerId:r,callerWidgetId:i,varDefinition:Object.freeze(a)};if(s.includes("added")){const e=ir(n);return tr.emit(e,c)}{const t=rr(e,n,r);return s.includes("value")&&(await tr.emit(sr(e),c),await tr.emit(sr("*"),c)),tr.emit(t,c)}},ar=(e,t,n,r)=>{const i=nr(e,t,r);i.variablesListener={...i.variablesListener,[n]:0},lr(e,t)},cr=(e,t,n,r)=>{const i=nr(e,t,r),s={...i.variablesListener};void 0!==i.variablesListener?.[n]&&(delete s[n],i.variablesListener=s)},lr=async(e,t)=>{const n=te(e,t);if(!n)throw new Error(`Thing "${t}" not found in recipe "${e}"`);const r={...n.variables},i=Object.keys(r);for(const s of i){const i=r[s],o=Object.keys(i);for(const i of o){!n.gates[i]&&(delete r[s][i],await or(s,e,t,i,void 0,["removed"],null))}0===Object.keys(r[s]).length&&delete r[s]}n.variables=r},ur=(e,t,n)=>{for(const r in t){const i=t[r];if(i.createdByWidgetId===e.id)return i;if(e.type===Me.variable&&i.ownerType===Me.variable)return i;if(e.type===Me.script){const t=i.createdByWidgetId===e.groupId,r=n[i.createdByWidgetId];if(!r)continue;const s=r.groupId===e.groupId;if(t||r.type===Me.variable&&s)return i}}return null};var dr=async(e,t,n,r,i,s)=>{const o=te(e,t);if(!o)throw new Error(`Thing ${t} not found in recipe ${e}`);const a={...o.variables};a[r]=a[r]||{};const c=a[r],l=o.gates[n];if(!l)throw new Error(`Widget ${n} not found in thing ${t}`);const u=Object.values(c);let d=!1,p=!1;const h=async i=>or(r,e,t,i.createdByWidgetId,n,["value"],i);if(l.type===Me.variable){d=!0;for(const e of u)e.ownerType===Me.variable&&e.type===i.type&&(e.value=i.value,p=!0,await h(e))}if(l.type===Me.script){d=!0;for(const e of u){const t=e.createdByWidgetId===l.groupId,n=o.gates[e.createdByWidgetId],r=n?.type===Me.variable,s=n?.groupId===l.groupId;(t||r&&s)&&e.type===i.type&&(e.value=i.value,p=!0,await h(e))}}if(!d){d=!0;for(const e of u){e.createdByWidgetId===n&&e.type===i.type&&(e.value=i.value,p=!0,await h(e))}}if(!s?.skipNotifications&&p){const a=Object.values(o.gates);for(const o of a){if(o.id===n&&s?.skipCallerNotification)continue;const a=o.variablesListener?.[r];void 0!==a&&await is(o.id,t,e,`${ce}${r}`,i)}}},pr=(e,t,n,r)=>{const i=te(e,t);if(!i)throw new Error(`Thing ${t} not found in recipe ${e}`);if(!r.readerWidgetId&&!r.ownerWidgetId)throw new Error("readerWidgetId or ownerWidgetId must be provided");const s={...i.variables}[n];if(!s)return;if(r.ownerWidgetId){const e=s[r.ownerWidgetId];return e?.value}const o=i.gates[r.readerWidgetId];if(!o)throw new Error(`Widget ${r.readerWidgetId} not found in thing ${t}`);const a=ur(o,s,i.gates);return a?a.value:null},hr=ar,fr=cr,gr=(e,t)=>tr.on(sr(e),(e=>{if(e.varDefinition)return t({type:e.varDefinition.type,value:e.varDefinition.value,varName:e.variableName})}));const mr="setTimeout",vr="variableChanged",yr=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e;if(!ne(t,n,r))throw new Error(`Widget "${r}" not found in recipe "${t}"`);return{get:(e,i)=>{const s=pr(t,n,e,{readerWidgetId:r});if(null===s){if(void 0===i)throw new Error(`Variable "${e}" is not defined`);return i}return s},set:async(e,i)=>{await dr(t,n,r,e,{type:Le(i),value:i})},onValueChange:(i,s)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");hr(t,n,i,r);const o={...Yn(),...e.getState()};o.$$eventListeners[i]={handler:s,abort:async()=>{fr(t,n,i,r)},name:vr},e.setState(o)}}},br="__command-compile__";let Sr;const wr=()=>{console.log("Method not implemented")},Ir=(e,t,n)=>{const i=(e,...n)=>{const r={...Yn(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},s={};return Object.keys(de).forEach((e=>{s[e]=de[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?yr({recipePoolId:n.recipePoolId,scriptWidgetId:n.widgetId,thingId:n.thingId,getState:t.getState,setState:t.setState}):{get:wr,set:async()=>wr(),onValueChange:wr},setTimeout:(n,i,s)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=r(),o={...Yn(),...t.getState()};o.$$eventListeners[e]={handler:n,rejectHandler:s,name:mr},t.setState(o),t.registerInterrupt("timeout",e,{timeout:i},void 0,e)}},addEventListener:(e,n)=>{if(t.setState){const s=r(),o={...Yn(),...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={...Yn(),...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.`)}}},_r=(e,t,n,r)=>{const i={...Yn(),...n.getState()},s=i.pages[Jn].$$compiledCode;if(s)return{compiledModule:s};{const s=Ir(e,n,t);return Kn(i.pages[Jn].code,s,n.recipeType,r)}},$r=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),Cr=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===mr){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},kr=async(e,t,n)=>{let r={...Yn(),...e.getState()};if(void 0!==n){r.pages[Jn]?.$$compiledCode?.onTerminate&&await(r.pages[Jn].$$compiledCode?.onTerminate());let t=await Cr(r.$$eventListeners,e);t=await(async e=>{const t={...e};for(const n in e)if(e[n].name===vr){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})(t),r.$$eventListeners=t,r.$$error=void 0,r.pages[Jn].$$compiledCode=void 0,r.pages[Jn].code=n,e.setState({...r})}const i=!r.pages[Jn].$$compiledCode,{compiledModule:s,error:o}=_r({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=Xn(o,e.recipeType);return Zn(t,e),null}if(s){const n=(e=>{const t=(t,n)=>{if(Sr)try{return Sr[t](n)}catch(e){return void console.log("Error in custom logger: ",e)}const r={...Yn(),...e.getState()},i=[...r.$$consoleLines||[]];i.push({fileName:Jn,text:n,type:t,timestamp:Date.now()}),i.length>100&&i.splice(0,30),e.setState({...r,$$consoleLines:i})},n={log:e=>{t("log",e)},error:e=>{t("error",e)},warn:e=>{t("warn",e)},info:e=>{t("info",e)}};return n})(e);let o;if(r={...e.getState()},r.pages[Jn].$$compiledCode=s,e.nextGate&&s.setSendToPortFun(e.nextGate),t)try{await s.recipeInit({setState:e.setState,getState:e.getState},n)}catch(t){o=Xn(t,e.recipeType)}if(e.nextGate&&i)try{await s.main(e.nextGate,n)}catch(t){o=Xn(t,e.recipeType)}r.$$lastInputs=s.getWidgetInputs?s.getWidgetInputs():[],r.$$lastOutputs=s.getWidgetOutputs?s.getWidgetOutputs():[],e.setState(r),Zn(o,e)}};var Er={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Yn(),...i};if(!s.pages[Jn])return console.warn("Missing default page");if(s.pauseExecution){if(Object.keys(s.$$eventListeners).length){const e=await Cr(s.$$eventListeners,r);r.setState({...s,$$eventListeners:e})}return}if(Ae(e?.name||""))return s.$$eventListeners[t.name]?(await s.$$eventListeners[t.name].handler(),s.$$eventListeners[t.name].name===mr&&delete s.$$eventListeners[t.name],void r.setState({...s})):void console.log(`Unknown interrupt id [${t.name}] `);if(t.name.startsWith(ce)){const e=t.name.replace(ce,""),r=n.data.value,i=s.$$eventListeners[e];return void(i?.handler&&await i.handler(r))}const o=t.name===br;await kr(r,!1,o?n.data.value:void 0);const a=s.pages[Jn].$$compiledCode;if(e&&e.name!==br&&a){let i;try{await a.asyncProcessEvent(t,e,n)}catch(e){"UserCodeError"===e.name&&(i=Xn(e,r.recipeType))}Zn(i,r)}},getInputNames:(e,t)=>{const n={...Yn(),...e},{compiledModule:r}=_r({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return $r(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...Yn(),...e},{compiledModule:r}=_r({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return $r(e)}return e.$$lastOutputs||[]},getDefaultState:Yn,initialize:async e=>{const t=e.getState(),n={...Yn(),...t};n.pages[Jn].code&&await kr({getState:e.getState,id:e.widgetThingId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[Jn].code)}};const xr=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const i=await Ar(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)},Ar=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),Nr=Object.freeze({image:"image"}),Or=Object.freeze({base64:"base64"}),Pr=()=>({});var Lr={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===Or.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==de.String&&n.data.type!==de.Anything)return;const e=n.data.value;ye&&(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ut(320,240)));try{const t=await xr(e,i.$$memCanvas,i.resize?.width,i.resize?.height);return r.setState(i),r.nextGate(Nr.image,{type:de.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:Or.base64,type:de.String}],getOutputNames:()=>[{name:Nr.image,type:de.ImageData}],getDefaultState:Pr};const Tr=Object.freeze({object:"object",error:"error"}),Br=Object.freeze({string:"string"}),jr=()=>({outputIsArray:!1});var Dr={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===de.String||n.data.type===de.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?de.Array:de.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:de.Boolean,value:!0})}},getInputNames:()=>[{name:Br.string,type:de.String}],getOutputNames:e=>[{name:Tr.object,type:[de.JsonObj,de.Array],label:e.outputIsArray?"array":Tr.object},{name:Tr.error,type:de.Boolean}],getDefaultState:jr};const Ur=Object.freeze({string:"string",length:"length"}),Mr=Object.freeze({trigger:"trigger",setText:"setText"}),Fr=()=>({text:"",dispatchOnSet:!1});var Rr={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===Mr.setText){if(!((n.data.type===de.String||n.data.type===de.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(Ur.length,{type:de.Number,value:i.text.length}),o=r.nextGate(Ur.string,{type:de.String,value:i.text});await Promise.all([s,o])},getInputNames:e=>{const t=[{name:Mr.setText,type:de.String}];return e.dispatchOnSet||t.push({name:Mr.trigger,type:de.Anything}),t},getOutputNames:()=>[{name:Ur.string,type:de.String},{name:Ur.length,type:de.Number}],getDefaultState:Fr};const Wr=Object.freeze({image:"image"}),Gr=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),Vr=()=>({showInputPorts:!1});var Hr={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Gr.x&&(i.cropX=n.data.value),t.name===Gr.y&&(i.cropY=n.data.value),t.name===Gr.width&&(i.cropWidth=n.data.value),t.name===Gr.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===Gr.image){if(n.data.type!==de.ImageData&&n.data.type!==de.Anything)return;if(!Ne(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ut(320,240),i.$$memCanvasContext=Mt(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(Wr.image,{type:de.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Gr.image,type:[de.ImageData]}];return e.showInputPorts&&(t.push({name:Gr.x,type:de.Number}),t.push({name:Gr.y,type:de.Number}),t.push({name:Gr.width,type:de.Number}),t.push({name:Gr.height,type:de.Number})),t},getOutputNames:()=>[{name:Wr.image,type:de.ImageData}],getDefaultState:Vr};const zr=Object.freeze({image:"image"}),qr=Object.freeze({image:"image",width:"width",height:"height"}),Kr=()=>({showInputPorts:!1});var Jr={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===qr.width&&(i.width=n.data.value),t.name===qr.height&&(i.height=n.data.value),void r.setState(i);if(t.name===qr.image){if(n.data.type!==de.ImageData&&n.data.type!==de.Anything)return;if(!Ne(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ut(320,240),i.$$tempCanvas=Ut(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=Mt(t),c=Mt(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(zr.image,{type:de.ImageData,value:t})}},getInputNames:e=>{const t=[{name:qr.image,type:de.ImageData}];return e.showInputPorts&&(t.push({name:qr.width,type:de.Number}),t.push({name:qr.height,type:de.Number})),t},getOutputNames:()=>[{name:zr.image,type:de.ImageData}],getDefaultState:Kr};const Yr=Object.freeze({value:"value"}),Xr=Object.freeze({trigger:"trigger",setValue:"setValue"}),Zr=()=>({value:0,dispatchOnSet:!1});var Qr={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===Xr.setValue){const e=n.data.type===de.Number||n.data.type===de.Anything||n.data.type===de.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(Yr.value,{type:de.Number,value:i.value})},getInputNames:e=>{const t=[{name:Xr.setValue,type:de.Number}];return e.dispatchOnSet||t.push({name:Xr.trigger,type:de.Anything}),t},getOutputNames:()=>[{name:Yr.value,type:de.Number}],getDefaultState:Zr};const ei=Object.freeze({image:"image"}),ti=Object.freeze({image:"image"}),ni=()=>({anchors:[],vertices:[],matrix:[]}),ri={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},s=window,o=n.data.type===de.ImageData;if(s.Speedy&&o){const e=s.Speedy,t=n.data.value;let o,u,d,p=i.$$private?.canvas,h=i.$$private?.context,f={...i};const g=4===i.anchors.length;if(i.$$private?.pipeline)o=i.$$private?.pipeline,u=i.$$private?.source;else{o=e.Pipeline(),u=e.Image.Source();const n=e.Image.Sink();d=e.Transform.PerspectiveWarp(),p?p.width===t.width&&p.height===t.height||(p.width=t.width,p.height=t.height,h=p.getContext("2d")):(c=t.width,l=t.height,p=Ut(c,l),h=p.getContext("2d")),u.output().connectTo(d.input()),d.output().connectTo(n.input()),o.init(u,n,d);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)}d.transform=r,f={...f,$$private:{...f.$$private,canvas:p,context:h,perspective:d,pipeline:o,source:u}}}let m=t;if(g){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})(f,m);e&&(p&&h&&(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,h)),f.$$private&&r.setState({...f,$$private:{...f.$$private,lastInputImage:t}}))}else f.$$private&&r.setState({...f,$$private:{...f.$$private,lastInputImage:t}});return r.nextGate(ei.image,{type:de.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:ti.image,type:de.ImageData}],getOutputNames:()=>[{name:ei.image,type:de.ImageData}],getDefaultState:ni,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},ii=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[de.Anything],name:"input"}],outputs:[{dataType:[de.Anything],name:"output"}]});let si;const oi=()=>{if(!si)throw new Error(Je(Ke));return si};const ai=async e=>{const t=new c,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},ci={};var li=e=>ci[e]||null;const ui=async(e,t,n)=>{try{const r=oi(),i=n?r.loadBlobAsString:r.loadBlob;return await i(e,t)}catch(e){return null}},di=async e=>{const t=se;try{const n=await ui(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},pi=async e=>{const t=oe;try{const n=await ui(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}},hi=(e,t)=>`${e.replace(ae,"")}_${t}`,fi=(e,t)=>`widget/${e.replace(ae,"")}/v/${t}`,gi=async(e,t)=>{const n=oi(),[r]=await Promise.all([ai(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},mi=(e,t)=>{const n=hi(e,t),r=li(n);return r?{...r}:null},vi=(e,t,n)=>{const r=`${`widget/${e.replace(ae,"")}/tmp`}/${t}`;if(n){return oi().getCacheLocation(r)}return r};var yi=mi,bi=async(e,t,n)=>{const r=vi(t,n);await gi(e,r);const i=di(r),s=pi(r),o=oi(),a=o.getCacheLocation(r),[c,l]=await Promise.all([i,s]);if(!c)return null;let u=l;if(!l){const e=ii(),t=JSON.stringify(e);await o.saveBlob(r,oe,xe(t)),u=e}return{cachePath:a,processor:c,storedState:Object.freeze(u)}},Si=(e,t,n)=>{if(n.isTempStorage)return vi(e,t,n.fullStorageRoot);const r=oi(),i=fi(e,t);return n.fullStorageRoot?r.getCacheLocation(i):i};const wi=()=>ii();var Ii={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={...wi(),...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={...wi(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:wi,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetThingId;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=yi(r,i);let o=!s;if(!n.$$processor)if(n.storageUnitId&&!s){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetThingId;const s=await bi(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=Si(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 _i=Object.freeze({event:"event"}),$i="1",Ci="2",ki="3";var Ei={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate($i,n.data),await r.nextGate(Ci,n.data),await r.nextGate(ki,n.data)},getInputNames:()=>[{name:_i.event,type:de.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??de.Anything};return[{name:$i,...t},{name:Ci,...t},{name:ki,...t}]}};const xi=Object.freeze({set:"set",trigger:"trigger"}),Ai="value";var Ni={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={name:"myVar",type:de.String,reactive:!0,defaultValue:"",...i};if(t.name.startsWith(ce)){if(!s.reactive)return;if(n.data.type!==s.type)return;return r.nextWidget(Ai,n.data)}if(t.name!==xi.set){if(t.name===xi.trigger){const e=pr(r.recipePoolId,r.thingRecipeId,s.name,{ownerWidgetId:r.id}),t=e||s.defaultValue;await r.nextWidget(Ai,{type:s.type,value:t})}}else await dr(r.recipePoolId,r.thingRecipeId,r.id,s.name,n.data,{skipCallerNotification:!s.reactive})},getInputNames:e=>{const t={...e};return[{name:xi.set,type:t.type||de.Anything},{name:xi.trigger,type:de.Anything}]},getOutputNames:e=>{const t={...e};return[{name:Ai,type:t.type||de.Anything}]}};let Oi;var Pi=e=>{Oi=e},Li=()=>{if(!Oi)throw new Error("Hub Connector not set");return Oi};const Ti=async(e,t=!1)=>{const n=Li();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 Bi={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const s=Li();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;return s.onParentEvent({recipeId: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}})},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=Li(),r=await Ti(t);if(r)try{return await n.initializeServiceInstance({recipeId:e.recipePoolId,sessionId:r,widgetId:e.widgetThingId,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.widgetThingId}] 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=Li(),r=await Ti(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const ji=Object.freeze({Image:"image"}),Di=Object.freeze({Image:"image"}),Ui=()=>({filters:[{name:"grayscale",value:.5,id:"d-1"}]});const Mi="loaded";const Fi={input:Ze,counter:tt,elapsed:it,ifGate:ct,skipEvent:dt,between:gt,map:yt,parser:wt,slider:$t,suspend:Et,display:At,json:Pt,arrayItem:Bt,extractImage:Wt,imageConvolution:qt,firstEvent:Xt,pixelDraw:rn,randomBetween:cn,arrayCombine:hn,clock:vn,multiplication:wn,object:En,widgetGroup:On,script:Er,base64ToImageData:Lr,jsonParse:Dr,text:Rr,imageCrop:Hr,imageResize:Jr,value:Qr,imageWarp:ri,widgetBundle:Ii,sequence:Ei,variable:Ni,hubService:Bi,imageFilter:{onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:.5,id:"d-1"}],...r.getState()};if(t.name===ji.Image&&n.data.type===de.ImageData){if(!Ne(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas||(i.$$memCanvas=Ut(e.width,e.height)),i.$$context||(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=>`${e.name}(${e.value}${"blur"===e.name?"px":""})`)).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(Di.Image,{type:de.ImageData,value:t})}},getInputNames:()=>[{name:ji.Image,type:de.ImageData}],getOutputNames:()=>[{name:Di.Image,type:de.ImageData}],getDefaultState:Ui},recipeLoad:{onParentEvent:async(e,t,n,r)=>r.nextWidget(Mi,{value:!0,type:de.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:Mi,type:de.Boolean,description:"Triggered when the recipe is fully loaded"}]},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:de.Boolean}]}},Ri={},Wi=async()=>{if(!Object.keys(Ri).length)for(const e in Fi){const t=Fi[e];Ri[e]=Object.freeze({...t})}};var Gi=e=>{if(Ri[e])return Ri[e];throw new Error(Je(qe,e))},Vi=Wi;const Hi=new a,zi="invoked";let qi={},Ki={},Ji={},Yi={};const Xi=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var Zi=(e,t,n,r,i)=>{const s=Xi(e,t,n),o=Xi(e,t),a=Xi(e,t,"produced"),c=Ji[o],l=Date.now();Yi[o]=l,qi[s]={data:r,sourcePortName:n,...i?{target:{widgetId:i.widgetId,portName:i.portName}}:{}},Hi.emit(a,{currentTime:l,prevTime:c,...i?{targetPort:i?.portName}:{}})},Qi=(e,t,n,r,i)=>{const s=Xi(e,t,n),o=Xi(e,t),a=Xi(e,t,zi),c=Ji[o],l=Date.now();Ji[o]=l,Ki[s]={data:r,sourcePortName:n,...i?{source:{widgetId:i.widgetId,portName:i.portName}}:{}},Hi.emit(a,{prevTime:c,currentTime:l,targetPort:n,sourceInfo:i})},es=()=>{qi={},Ki={},Ji={},Yi={},Hi.clearListeners()};let ts,ns,rs;const is=async(e,t,n,r,i)=>{const s=te(n,t);if(!s)return;const o=s.gates[e];if(!o||o.disabled)return;const a={...i,timestamp:Date.now()},c=Gi(o.type),l=cs(e,a,s.recipeId,s.id,s.version,n);if(l&&c.onParentEvent){const t={name:r};return ts&&await ts({recipeId:n,blockId:s.recipeId,gateId:e,targetPort:t.name,data:i}),c.onParentEvent(null,t,{originalEvent:a,data:{...a}},l)}},ss=async(e,t,n,r,i,s,o,a,c,l)=>{if(!e&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!e&&!l)throw new Error("Missing parameter ['originalEvent']");e&&(l={timestamp:Date.now(),type:de.Boolean,value:!0});const u=l;if("string"==typeof n){const e=te(r,n);if(!e)return;n=e}const d=n.gates[t];if(!d||d.disabled)return;const p=a.findIndex((e=>e.name===i)),h=Gi(d.type),f=cs(t,u,n.recipeId,n.id,n.version,r);if(f&&h.onParentEvent&&-1!==p){ts&&await ts({recipeId:r,blockId:n.recipeId,gateId:t,targetPort:s.name,data:o,sourceGate:e?"interrupt_widget":c,sourcePort:e?ie:i});const l={name:a[p].name,type:a[p].type,...a[p].jsonShape?{jsonShape:a[p].jsonShape}:void 0};return Qi(n.recipeId,t,s.name,o,c?{widgetId:c,portName:i}:void 0),h.onParentEvent(l,s,{originalEvent:u,data:o},f)}},os=async(e,t,n,r,i,s,o,a)=>{const c=ee(a);if(!c)throw new Error(`Failed to find recipe "${a}" in cache`);const l=c.dbInfo.recipeType,u=ne(a,i,r);if(!u)return;const d={...n,timestamp:t.timestamp},p=Gi(u.type);let h;h=u.type===Me.input?p.getOutputNames(u.state,{thingRecipeId:i,thingDbId:s,thingVersion:o,id:r,recipeId:a,recipeType:l,recipePoolId:a}):await p.getOutputNames(u.state,{recipePoolId:a,recipeType:l,thingRecipeId:i,widgetId:r});const f=h.findIndex((t=>t.name===e));if(-1!==f){const n=te(a,i);if(!n)return;Zi(i,r,e,d);const s=u.children.length;for(let o=0;o<s;o++){if(je(u.children[o]?.sourcePort).portName===e){const s=n.gates[u.children[o].childId];if(s&&!s.disabled){const c=Gi(s.type);let p;const f={recipePoolId:a,recipeType:l,thingRecipeId:i,widgetId:r};p=s.type===Me.hubService?await c.getInputNames(s.state,f):c.getInputNames(s.state,f);const g=je(u.children[o].targetPort),m=p.find((e=>e.name===g.portName));m&&await ss(!1,s.id,n,a,e,{name:m.name},u.returnOriginalEvent?t:d,h,u.id,t)}}}}},as=async(e,t,n,r)=>{const i=ee(r);if(!i)return null;const s=te(r,n);if(!s)return s;const o=s.gates,a=s.gates[t],c=Gi(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),u=l.findIndex((t=>t.name===e));if(-1!==u){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=je(r.targetPort);if(r.childId===e&&s.portName===t)return i}}return null})(t,l[u].name,o);if(e){const t=Gi(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},cs=(e,t,n,r,i,s)=>{const o=ee(s);if(!o)throw new Error(`Failed to find recipe "${s}" in cache`);const a=ne(s,n,e);if(!a)return console.warn(`Gate ${e} not found in block ${n} for recipe ${s}`),null;const c=async(o,a)=>os(o,t,a,e,n,r,i,s),l={id:e,type:a.type,recipePoolId:s,thingRecipeId:n,recipeType:o.dbInfo.recipeType,returnOriginalEvent:!!a.returnOriginalEvent,registerInterrupt:(t,r,i,o,a)=>Ve.createInterrupt(t,s,n,e,r,i,o,a),cancelInterrupt:e=>Ve.destroyInterrupt(e),nextWidget:c,nextGate:c,getParentAtPort:t=>as(t,e,n,s),getState:()=>Object.freeze({...a.state,...a.type===Me.input&&{customInputs:[]}}),setState:t=>{if("object"!=typeof t)return void console.warn(`Invalid state type [${typeof t}]. Expected an 'object'`);const r={...t,...a.type===Me.input&&!t.customInputs&&{customInputs:[]}},i={...a.state};a.state=r,ns&&ns({blockId:n,gateId:e,prevState:i,newState:{...r},recipeId:s})}};return l};Ve.setInvokeChildGateCb(ss);const ls=new a,us="invoked",ds="state",ps=()=>{Ve.destroyAllInterrupts()},hs=async(e,t,n)=>{const r=ee(e),i=ne(e,t,n);if(i&&r){const s=Gi(i.type);if(s&&"function"==typeof s.terminate){const i=((e,t,n,r)=>He(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)}}}},fs=async(e,t,n,r)=>{const i=ee(e),s=ne(e,t,n);if(s&&i){const o=Gi(s.type);if(o&&"function"==typeof o.initialize){const s=((e,t,n,r)=>He(e,t,n,r,!0))(e,i.dbInfo.recipeType,t,n);if(s){const e=o.initialize;try{await e(s,r||{})}catch(e){throw console.warn(`Error initializing widget "${n}" in thing "${t}": `,e),e}}}}},gs=(e,t)=>{const n=ee(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},ms=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,vs=e=>{ls.emit(ms(ds),e),ls.emit(ms(ds,e.blockId,e.gateId),e)};ts=async e=>{await ls.emit(ms(us),e),await ls.emit(ms(us,e.blockId,e.gateId),e)},(e=>{ns=e})(vs);var ys,bs,Ss,ws,Is,_s,$s,Cs,ks,Es,xs,As,Ns,Os=async(e,t,n,r,i)=>{const s=re(e,{id:t,authorId:r,version:n,recipeType:i});es();const o=ee(s);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=Y.STARTING,o.addLog("recipe registered")),s},Ps=async e=>{const t=ee(e);var n;if(!t)return null;t.addLog("terminating recipe"),ps();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await hs(e,n,t)}X[n=e]&&delete X[n]},Ls=async(e,t)=>{const n=ee(e),r=[],i=[];if(n)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===Ln.Desktop){const e=o.gates[t];if(e.type===Me.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===Me.recipeLoad&&i.push(e)}await fs(e,s,t,{keepCurrentState:!0})}catch(e){r.push({widgetId:t,error:e.message})}}return{failed:r,sendToInputWidget:(t,n,r=le)=>(async(e,t,n,r)=>{const i=ee(n),s=te(n,r),o=Date.now();if(s&&i)for(const i in s.gates){const a=s.gates[i];if(a.type===Me.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=Gi(a.type),l={...t,timestamp:o},u=cs(i,l,r,s.id,s.version,n);if(u&&e.processEvent){const s={...u,getState:u.getState};ts&&await ts({recipeId:n,blockId:r,gateId:i,targetPort:Xe,data:t}),rs?await rs(r,n,c,t):await e.processEvent(l,s)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of i)await is(t.id,le,e,Mi,{type:de.Boolean,value:!0})}}},Ts=e=>{Pi(e)},Bs=(e,t,n,r=!1)=>{const i=gs(t,e);if(i){const{widget:s,thing:o}=i,a={...s.state};s.state=n,r&&vs({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},js=(e,t)=>{const n=gs(t,e);return n?n.widget.state:null},Ds=async(e,t,n,r,i)=>{const s=gs(t,e);if(s)return os(n,r,i,t,s.thing.recipeId,s.thing.id,s.thing.version,e)};!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(ys||(ys={})),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"}(bs||(bs={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Ss||(Ss={})),function(e){e.Bundle="bundle",e.Group="group"}(ws||(ws={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Is||(Is={})),function(e){e.Cloud="cloud",e.Web="web"}(_s||(_s={})),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"}($s||($s={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Cs||(Cs={})),function(e){e.InstallInProgress="installation-in-progress"}(ks||(ks={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Es||(Es={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(xs||(xs={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(As||(As={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.ExportRecipe="export_recipe"}(Ns||(Ns={}));const Us=(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=d("aes-256-cbc",o,i);let c=a.update(s,"base64","utf8");return c+=a.final("utf8"),c})(e.id||"recipe.json","kemu",t),Ms=e=>{try{return JSON.parse(e)}catch(e){return null}},Fs="undefined"!=typeof window,Rs={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Ws={protocolPrefix:4,txtLength:4},Gs=Object.values(Rs).reduce(((e,t)=>e+t),0),Vs=Object.values(Ws).reduce(((e,t)=>e+t),0),Hs=["width","height","colorSpace"],zs=(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)||Hs.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},qs=(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},Ks=(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&&qs(e,s,l)}return e},Js=e=>f(e),Ys="KMSG",Xs="KCMD",Zs=Js("klProtocol");var Qs={encode:(e,t,n)=>{const r={json:e.json},i=zs(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,u=Rs.protocolPrefix+Rs.protocolVersion+Rs.jsonLength+Rs.binaryLength+Rs.fromServiceId+Rs.toServiceId+Rs.sentAt+l+o,d=Buffer.alloc(u),p=Date.now();let h=0;return d.write(Ys,h),h+=Rs.protocolPrefix,d.writeUInt8(1,h),h+=Rs.protocolVersion,d.writeUInt32LE(l,h),h+=Rs.jsonLength,d.writeUInt32LE(o,h),h+=Rs.binaryLength,d.writeUInt32LE(t,h),h+=Rs.fromServiceId,d.writeUInt32LE(n,h),h+=Rs.toServiceId,d.writeBigInt64LE(BigInt(p),h),h+=Rs.sentAt,c.copy(d,h),h+=l,s&&o&&s.copy(d,h),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Rs.protocolPrefix);if(t+=Rs.protocolPrefix,n!==Ys)return null;if(e.byteLength<Gs)return Zs(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Rs.protocolVersion;const i=e.readUInt32LE(t);t+=Rs.jsonLength;const s=e.readUInt32LE(t);t+=Rs.binaryLength;const o=e.readUInt32LE(t);t+=Rs.fromServiceId;const a=e.readUInt32LE(t);t+=Rs.toServiceId;const c=e.readBigInt64LE(t);t+=Rs.sentAt;const l=i+s,u=e.subarray(t,t+l),d=e.subarray(0,Gs);let p=null;return e.byteLength-Gs-i-s>0&&(p=e.subarray(Gs+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},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=Ms(n);if(!i?.json)return Zs("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Ks(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=Gs+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<Gs)return Zs("Invalid Header Size"),e;let n=0;return n+=Rs.protocolPrefix,n+=Rs.protocolVersion,n+=Rs.jsonLength,n+=Rs.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Rs.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=Vs+r,s=Buffer.alloc(i);return s.write(Xs,t),t+=Ws.protocolPrefix,s.writeUint32LE(r,t),t+=Ws.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<Vs)return{command:null};const n=e.toString("utf-8",t,Ws.protocolPrefix);if(t+=Ws.protocolPrefix,n!==Xs)return{command:null};const r=e.readUInt32LE(t);t+=Ws.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-Vs-r;let o=null;s>0&&(o=e.subarray(Vs+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const eo="KMSG",to="KCMD",no=Js("klProtocol"),ro=new TextEncoder;var io={encode:(e,t,n)=>{const r={json:e.json},i=zs(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=ro.encode(a),l=c.byteLength,u=new ArrayBuffer(Rs.protocolPrefix+Rs.protocolVersion+Rs.jsonLength+Rs.binaryLength+Rs.fromServiceId+Rs.toServiceId+Rs.sentAt+l+o),d=new DataView(u),p=new Uint8Array(u),h=Date.now();let f=0;for(let e=0;e<4;++e)p[f++]=eo.charCodeAt(e);return d.setUint8(f,1),f+=Rs.protocolVersion,d.setUint32(f,l,!0),f+=Rs.jsonLength,d.setUint32(f,o,!0),f+=Rs.binaryLength,d.setUint32(f,t,!0),f+=Rs.fromServiceId,d.setUint32(f,n,!0),f+=Rs.toServiceId,d.setBigInt64(f,BigInt(h),!0),f+=Rs.sentAt,p.set(c,f),f+=l,s&&o&&p.set(new Uint8Array(s),f),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Rs.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==eo)return null;if(e.byteLength<Gs)return no.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Rs.protocolVersion;const s=t.getUint32(n,!0);n+=Rs.jsonLength;const o=t.getUint32(n,!0);n+=Rs.binaryLength;const a=t.getUint32(n,!0);n+=Rs.fromServiceId;const c=t.getUint32(n,!0);n+=Rs.toServiceId;const l=t.getBigInt64(n,!0);n+=Rs.sentAt;const u=s+o,d=e.slice(n,n+u),p=new Uint8Array(e,0,Gs);let h=null;if(e.byteLength-Gs-s-o>0){h=new Uint8Array(e,Gs+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:p.slice().buffer},remaining:h}},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=Ms(s);if(!a?.json)return no.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Ks(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,u=null;const d=Gs+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Gs)return no("Invalid Header Size"),e;let n=0;n+=Rs.protocolPrefix,n+=Rs.protocolVersion,n+=Rs.jsonLength,n+=Rs.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Rs.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=ro.encode(e),r=n.byteLength,i=new ArrayBuffer(Vs+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=to.charCodeAt(e);return s.setUint32(t,r,!0),t+=Ws.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Vs)return{command:null};let r="";for(let e=0;e<Ws.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==to)return{command:null};const i=t.getUint32(n,!0);n+=Ws.txtLength;const s=e.byteLength-Vs-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-Vs)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(Vs+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};let so=Qs;Fs&&(so=io);var oo,ao=so;(oo||(oo={})).FunctionNotFound="FNC_NOT_FOUND";let co=Math.ceil(Date.now()/1e3);let lo,uo,po,ho,fo,go=!1;var mo=()=>{go=!0},vo=(e,t)=>{if(!lo)throw new Error("Memory connection not set.");lo.sendBuf(e,t)},yo=e=>uo=e,bo=e=>fo=e,So=e=>po=e,wo=e=>ho=e;const Io=(e,t=2)=>{const n=(e,r)=>{if("object"==typeof e){const i=Object.keys(e);for(const s of i){const i=e[s];if(i&&"object"==typeof i){const o=i._kemuType;if(void 0!==o){if(o===de.ImageData){const t=e[s];e[s]=De(t)}}else r<t&&n(i,++r)}}}};return n(e,1),e};Js("klTransmissionManager"),Js("ipcClient");Js("kemuWidgetService"),C(process.argv.slice(2));const _o=e=>f(`runner:${e}`),$o=_o("connectionManager"),Co=_o("remoteInvoke"),ko=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=Fs?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=ao.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}co+=1;const u=`${i}-${co}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let p=Fs?new ArrayBuffer(0):Buffer.alloc(0);const h={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(p=ao.encode(h,a,c)),t[u]=d,n&&n(`Calling remote function "${e}" with message id "${u}"`);const f="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||f||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=t[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:h}),d.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)=>{co+=1;const a=`${i}-${co}-multicast-${e.substring(0,10)}`;let c=Fs?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=o(r[0].serviceId);u&&(c=ao.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&&(u=o(i.serviceId),u&&(c=ao.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");ko.setLogger(Co);const Eo=new a,xo=new a;let Ao,No=null,Oo=null,Po=null;const Lo={},To=()=>{if(!Po)throw new Error("API key is required to interact with the hub");return Po},Bo=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return Lo[r]=i,i},jo=(e,t)=>Lo[`${e}_${t}`]||null,Do=async(e,t)=>{if(!No)return $o("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await ko.execute(ge.GetServiceContents,n,Mo,No,0))[0]},Uo=async(e,t,n=!1)=>{if(!e||!t)return null;const r=jo(e,t);if(!r||n){const n=r||Bo(e,t);try{const r=await Do(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){$o(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},Mo=vo,Fo=()=>{$o("Disconnected from the server"),No=null,ko.rejectAllPending("Disconnected from the server"),Eo.emit("disconnected")},Ro=()=>{$o("Connected to the server"),Eo.emit("connected")},Wo=()=>Oo,Go=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,Vo=async()=>{const e=Wo();if(e){const t=ee(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===Me.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{$o(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await sa({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){$o(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},Ho=async e=>{if(!e)return void $o("Hub sent ACK request without service id");const t={apiKey:To(),ackSessionId:e};await ko.execute(ge.SocketAckResponse,[t],Mo,e,0),$o("Hub Link acknowledged"),No=e,Eo.emit("acknowledged"),Vo()},zo=async e=>{const t=e.args[0],n=Go("broadcast",`hub_${t.type}`,(0).toString(),"");await xo.emit(n,t)},qo=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===de.ImageData&&Ne(e.value)&&(e.value=De(e.value));const n=Wo();if(n){const r=ee(n);if(r){const i=async e=>{const n=Go("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await xo.emit(n,t)}catch(t){$o(`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===Me.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await i(r);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()};$o(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await Ds(n,r,i.name,t,t)}}}}}}},Ko=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,s=js(r,i);let o=s;if(n&&o&&s&&(o={...s,customState:n},Bs(r,i,o,!0)),o?.service)try{const e=Go("setOutputs",o.service.name,o.service.version,i);await xo.emit(e,t.outputs)}catch(e){$o(`Failed to emit setOutputs event for widget ${i}`,e)}for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===de.ImageData){if(!Ne(n.value)){$o(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=De(n.value)}else n.type===de.JsonObj&&Io(n.value);const t={type:n.type,value:n.value,timestamp:Date.now()};$o(`Sending data to output ${n.name} requested by messageId ${e.messageId}`),await Ds(r,i,n.name,t,t)}e.reply({success:[]})},Jo=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,s=js(r,i);if(s){const t={...s,customState:{...s.customState,...n}};return Bs(r,i,t,!0),e.reply({success:[]})}},Yo=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:s,key:o}=n;$o(`Received request to set a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const a=js(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:s},Bs(r,i,e,!0)}return t({success:[]})},Xo=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:s}=n;$o(`Received request to get a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const o=js(r,i);if(o){const e=o.dependencies?.[s]?.path;return $o(`Returning dependency path for "${s}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},Zo=async()=>{if($o(`Requesting services on ${(new Date).toISOString()}`),!No)return $o("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await ko.execute(ge.GetServices,[],Mo,No,0);Ao=e;for(const t of e.available){if(t.internal)continue;const e=jo(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||Bo(t.name,t.version);$o(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await Do(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){$o(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},Qo=()=>Ao||{available:[],installed:[],failed:[]},ea=()=>!!Ao,ta=async e=>{const{targetServiceSessionId:t}=e;if(!No)return void $o("No target service session id provided");$o(`Forwarding "onParentEvent" to service ${t}`);return await ko.execute(ge.OnParentEvent,[e],Mo,No,t,e.config)},na=async e=>{if(!No)return $o("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await ko.execute(ge.GetDefaultState,[],Mo,No,e);return t},ra=async(e,t,n,r)=>{if(!No)return $o("Hub Link has not been acknowledged. Cannot get services."),null;const[i]=await ko.execute(ge.UIEvent,[t,n],Mo,No,e,r);return i},ia=(e,t)=>{const n=()=>{t()};return Eo.on(e,n),()=>Eo.off(e,n)},sa=async e=>{if(No)return ko.execute(ge.SubscribeToService,[e],Mo,No,0);$o("Hub Link has not been acknowledged. Cannot subscribe to services.")},oa=async e=>{if(No)return ko.execute(ge.UnsubscribeFromService,[e],Mo,No,0);$o("Hub Link has not been acknowledged. Cannot subscribe to services.")},aa=(e,t,n,r)=>{const i=Go("broadcast",t,n,e);return xo.on(i,r)},ca=(e,t,n,r)=>{const i=Go("setOutputs",t,n,e);return xo.on(i,r)},la=async(e,t,n)=>No?ko.execute(e,t,Mo,No,0,n):($o("Hub Link has not been acknowledged. Cannot execute function."),null),ua=async e=>{if(!No)return void $o("Hub Link has not been acknowledged. Cannot execute function.");const t=js(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,currentDependencies:n}],[i]=await ko.execute(ge.InitializeInstance,r,Mo,No,e.sessionId);if(i){const t=js(e.recipeId,e.widgetId);if(t){const n={...t,customState:i};Bs(e.recipeId,e.widgetId,n,!0)}}},da=async(e,t,n,r)=>{if(!No)return void $o("Hub Link has not been acknowledged. Cannot execute function.");const i=js(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 ko.execute(ge.TerminateInstance,s,Mo,No,e)},pa=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=ea(),o=r||!s?await Zo():Qo();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};var ha,fa,ga,ma,va,ya,ba,Sa,wa=async e=>{So(Ro),wo(Fo),Po=e,bo((({json:e,transmission:t})=>{ko.processMessage("websocket",Mo,t,e)})),ko.registerFunction(ge.SetState,Jo),ko.registerFunction(ge.SetOutputs,Ko),ko.registerFunction(ge.BroadcastEvent,qo),ko.registerFunction(ge.HubBroadcastEvent,zo),ko.registerFunction(me.SetDependencyPath,Yo),ko.registerFunction(me.GetDependencyPath,Xo),yo((e=>{((e,t)=>{const n=fe.SocketAcknowledge,r=fe.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,Ho),((e,t)=>{e===fe.ServicesListChanged&&(t&&t())})(e,(()=>{$o("Services list changed"),Eo.emit("services-changed")}))})),await mo()},Ia=(e,t)=>{Eo.on(e,t)},_a=()=>({getServices:Zo,getServiceContents:Uo,onParentEvent:ta,onCommand:ia,getDefaultState:na,getCachedServices:Qo,areServicesCached:ea,subscribeToServiceEvents:sa,unsubscribeFromServiceEvents:oa,callProcessorHandler:ra,onBroadcastEvent:aa,onSetOutputsEvent:ca,executeHubFunction:la,initializeServiceInstance:ua,terminateServiceInstance:da,getCompatibleService:pa}),$a=e=>{Oo=e},Ca=()=>ko;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(ha||(ha={})),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"}(fa||(fa={})),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"}(ga||(ga={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ma||(ma={})),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:"}(va||(va={})),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.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId"}(ya||(ya={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(ba||(ba={})),function(e){e.IPC="ipc",e.WS="ws"}(Sa||(Sa={}));const ka=e=>{try{return JSON.parse(e)}catch(e){return null}},Ea=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,xa=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(Ea);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},Aa=e=>"*"===e||"x"===e||"X"===e,Na=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},Oa=(e,t)=>{if(Aa(e)||Aa(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(Na(e),Na(t));return n>r?1:n<r?-1:0},Pa=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=Oa(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},La=(e,t,n)=>{ja(n);const r=((e,t)=>{const n=xa(e),r=xa(t),i=n.pop(),s=r.pop(),o=Pa(n,r);return 0!==o?o:i&&s?Pa(i.split("."),s.split(".")):i||s?i?-1:1:0})(e,t);return Ta[n].includes(r)},Ta={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},Ba=Object.keys(Ta),ja=e=>{if(-1===Ba.indexOf(e))throw new Error(`Invalid operator, expected one of ${Ba.join("|")}`)};var Da="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ua(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ma,Fa,Ra,Wa,Ga,Va={exports:{}},Ha={exports:{}};function za(){if(Fa)return Ma;Fa=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 Ma=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 qa(){if(Wa)return Ra;return Wa=1,Ra=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=za(),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},Ra}var Ka,Ja,Ya,Xa,Za,Qa={exports:{}};function ec(){return Ja||(Ja=1,Ka=(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)}),Ka}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?Va.exports=(Ga||(Ga=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=qa()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Ha,Ha.exports)),Ha.exports):Va.exports=(Za||(Za=1,function(e,t){const n=k,r=o;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(Xa)return Ya;Xa=1;const e=E,t=k,n=ec(),{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)),Ya={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=qa()(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)}}(Qa,Qa.exports)),Qa.exports);var tc=Ua(Va.exports);const nc=e=>tc(e),rc=Date.now();let ic=Math.ceil(rc/1e3);var sc=()=>ic+=1;const oc=m(x(),"kemu-user-services"),ac=m(x(),"kemu-test-services"),cc="KMU-CB-v1";var lc;!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"}(lc||(lc={}));const uc=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>fa[e])):fa[e.type]}),dc=async e=>{try{return await S(e,"utf-8")}catch(e){return null}},pc=e=>{if(e&&e.startsWith(cc)){const t=e.slice(9),n=decodeURI(t);return ka(n)}return null},hc=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(uc)}:{},...e.outputs?{outputs:e.outputs.map(uc)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(uc)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(uc)}:{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 dc(m(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const s=t.startsWith(cc)?t:`${cc}${t}`,o=pc(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===lc.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${i}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${i}" does not contain a top level widgetGroup`);continue}const l=c.state,u={name:l.name,color:l.color,description:l.description,contents:s,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}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 S(m(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},fc=async e=>{try{return await w(e,I.F_OK),!0}catch{return!1}};let gc=null,mc=null;const vc=()=>gc||oc,yc=nc("servicesManager"),bc={};let Sc=null,wc=null,Ic=null;class _c extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const $c=async e=>{try{return await w(e),!0}catch{return!1}},Cc=async e=>{if(!Sc)throw new Error('IPC config not set, call "setHubIpcConfig" first.');try{if(e.processor===ma.Javascript){yc(`Spawning service ${e.name} with sessionId ${e.sessionId}`);const t=g.join(e.path,"processor.js"),n=g.join(e.path,"processor.mjs"),r=await $c(t)?t:n,i=[`--sessionId=${e.sessionId.toString()}`,`--ipcSpace=${Sc.appSpace}`,`--ipcId=${Sc?.id}`,`--recipePath=${Sc.recipePath||""}`];if(e.internal&&i.push("--internal=true"),!Ic)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const s=await Ic({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 _c(`Missing required environment variables: ${o.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,n)=>{if(!wc)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const o=wc({args:[r,...i],serviceInfo:{name:e.name,version:e.version},options:{env:s}});o.stdout.on("data",(t=>{yc(`[${e.name}] - stdout: ${t}`)})),o.stderr.on("data",(t=>{yc(`[${e.name}] - stderr: ${t}`)})),o.on("exit",(t=>{yc(`[${e.name}] exited with code ${t}`)})),o.on("spawn",(()=>{yc(`[${e.name}] spawned with PID ${o.pid}`),t(o)})),o.on("error",(t=>{yc(`[${e.name}] error: ${t}`),n(new _c(`Error spawning service ${e.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.processor}`}catch(t){if(t instanceof _c)throw t;throw`Error spawning service ${e.name}: ${t}`}},kc=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[ma.Javascript,ma.Executable,ma.Python].includes(e?.processor)?null:"Invalid processor"},Ec=async(e,t)=>{const n=g.join(e,"manifest.json");if(!await $c(n)){const t=`Missing manifest for service ${e}. Aborting.`;return yc(t),{error:t}}const r=await S(n,"utf-8"),i=ka(r),s=kc(i);if(!i||s){const t=`Invalid service manifest [${e}]: ${s}. Aborting.`;return yc(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 S(g.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return yc(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await dc(g.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=g.join(e,t),{error:r,service:s}=await Ec(n);r?yc(`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 S(g.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){yc(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=sc(),c=t?.fixedSession||a;yc(`Loaded service ${i.name} with sessionId ${c}`);const l=await hc(i,e,{widgetUIContents:o});return xc(l),bc[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null},{service:bc[c]}},xc=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=p("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},Ac=async e=>{try{return e.childProcess=await Cc(e.info),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return yc(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof _c?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},Nc=e=>{const{path:t,...n}=e.info;return{...n}},Oc=()=>Object.values(bc).filter((e=>"running"===e.status)).map(Nc),Pc=e=>{const{serviceName:t,version:n,force:r}=e,i=Object.values(bc).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){yc(`Stopping service "${t} (v${n})"`);i.childProcess.kill("SIGINT")||yc(`Failed to stop service ${t}`)}return i.status="stopped",yc(`Service ${t} stopped`),i},Lc=e=>e.info.internal?e.info.path:g.join(e.info.path,".."),Tc=e=>!!e.internal;var Bc={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await fc(e))return void yc(`Failed to load services from "${e}". Directory does not exist.`);const n=(await _(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));yc(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],s=g.join(e,i),{error:o,service:a}=await Ec(`${s}${t?.internalServices?"":"/dist"}`,t);o&&yc(`Failed to load service ${s}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(yc("Initializing services"),!Sc)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in bc){const n=bc[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?yc(`Service ${n.info.name} is in the noSpawningList. Skipping.`):Ac(n)}yc("Services initialized")},setServiceStatus:(e,t)=>{const n=bc[e];return n?(n.status=t,!0):(yc(`Service with serviceId ${e} not found`),!1)},getActiveServices:Oc,getMatchingService:(e,t)=>{const n=Object.values(bc).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(La(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>bc[e]||null,killAllServices:()=>{for(const e in bc){const t=bc[e];if(t.childProcess)try{yc(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){yc(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await hc(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};bc[e]=r,xc(bc[e].info)},setServiceManifest:(e,t,n)=>{const r=bc[e];if(!r)return yc(`Service with sessionId ${e} not found`),!1;const i=kc(t);if(i)return yc(`Invalid manifest for service ${r.info.name}: ${i}`),!1;xc(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(bc).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:()=>Oc().filter((e=>e.internal)),getAllServices:()=>Object.values(bc),stopService:Pc,uninstallService:async(e,t)=>{yc(`Uninstalling service ${e} v${t}`);const n=Pc({serviceName:e,version:t});if(!n)return!1;yc(`Service ${e} stopped. Removing from disk...`);const r=Lc(n),i=vc();return r.startsWith(i)?(await $(r,{recursive:!0,force:!0}),yc(`Service ${e} successfully removed from disk`),(e=>{const t=bc[e];delete bc[e]})(n.info.sessionId),!0):(yc(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(bc).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{Sc={...e}},loadAndLaunch:async(e,t,n)=>{const r=y(e,t),{error:i,service:s}=await Ec(r);if(i||!s)return{errorMsg:i};try{s.info.internal=!!n,s.childProcess=await Cc(s.info),s.status="started"}catch(e){s.status="error",e instanceof _c?(yc(`Service spawning error: ${e.message} (${e.code})`),s.errorMsg=e.message,s.errorCode=e.code):(yc(`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:Lc,setSpawnNodeFunction:e=>{wc=e},setGetSecretsFunction:e=>{Ic=e},restartService:async(e,t)=>{yc(`Restarting service ${e} v${t}`);const n=Pc({serviceName:e,version:t,force:!0});return!!n&&Ac(n)},getFailedServices:()=>Object.values(bc).filter((e=>"error"===e.status)).map((e=>({...Nc(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Tc,isNotInternalKemuService:e=>!Tc(e),isNotDevService:e=>!e.devMode};class jc{constructor(){}appspace="app.";socketRoot="/tmp/";id=E.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=E.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 Dc{constructor(e){e||(e=new jc),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 Uc=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={}},Mc=Ua(Uc);var Fc=Ua((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 Rc{}class Wc{}const Gc=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 Rc,t=Wc){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 Rc}}())}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 Vc{constructor(){}on(e,t,n=!1){return Gc.string(e),Gc.function(t),Gc.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(Gc.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Gc.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){Gc.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)=>{Gc.string(e),Gc.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 Hc=new Dc;class zc extends Vc{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Hc=new Dc(this.config)}Client=zc;queue=new Fc;socket=!1;connect=Jc;emit=qc;retriesRemaining=0;explicitlyDisconnected=!1}function qc(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Mc;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Hc.format(n),this.config.sync?this.queue.add(Kc.bind(this,n)):this.socket.write(n)}function Kc(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Jc(){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=N.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=A.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=A.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)!=Hc.delimiter||-1==t.indexOf(Hc.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Hc.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Mc;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 Yc=new Dc;class Xc extends Vc{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Yc=new Dc(this.config),this.on("close",el.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Zc;broadcast=Qc;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?O.unlink(this.path,il.bind(this)):il.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Zc(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Mc;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Yc.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 Qc(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Mc;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Yc.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 el(){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 tl(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)==Yc.delimiter&&-1!=t.indexOf(Yc.delimiter))for(r.ipcBuffer="",t=Yc.parse(t);t.length>0;){let e=new Mc;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 nl(e){this.publish("close",e)}function rl(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",nl.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",tl.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 il(){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=ol.bind(this),this.server.on("listening",function(){rl.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?sl.bind(this)():this.server=A.createServer(rl.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 sl(){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=N.createServer(this.config.tls,rl.bind(this))}function ol(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 al{constructor(){}config=new jc;of={};server=!1;get connectTo(){return hl}get connectToNet(){return fl}get disconnect(){return ll}get serve(){return ul}get serveNet(){return pl}get log(){return cl}set connectTo(e){return hl}set connectToNet(e){return fl}set disconnect(e){return ll}set serve(e){return ul}set serveNet(e){return pl}set log(e){return cl}}function cl(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=o.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function ll(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 ul(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=dl),this.server=new Xc(e,this.config,cl),this.server.on("start",t)}function dl(){}function pl(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=dl),this.server=new Xc(e,this.config,cl,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function hl(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=dl),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 zc(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 fl(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=dl),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 zc(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 gl=new class extends al{constructor(){super()}IPC=al};var ml={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const vl=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),yl=e=>{try{return JSON.parse(e)}catch(e){return null}},bl="undefined"!=typeof window,Sl={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},wl={protocolPrefix:4,txtLength:4},Il=Object.values(Sl).reduce(((e,t)=>e+t),0),_l=Object.values(wl).reduce(((e,t)=>e+t),0),$l=["width","height","colorSpace"],Cl=(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)||$l.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},kl=(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},El=(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&&kl(e,s,l)}return e},xl=e=>tc(e),Al="KMSG",Nl="KCMD",Ol=xl("klProtocol");var Pl={encode:(e,t,n)=>{const r={json:e.json},i=Cl(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,u=Sl.protocolPrefix+Sl.protocolVersion+Sl.jsonLength+Sl.binaryLength+Sl.fromServiceId+Sl.toServiceId+Sl.sentAt+l+o,d=Buffer.alloc(u),p=Date.now();let h=0;return d.write(Al,h),h+=Sl.protocolPrefix,d.writeUInt8(1,h),h+=Sl.protocolVersion,d.writeUInt32LE(l,h),h+=Sl.jsonLength,d.writeUInt32LE(o,h),h+=Sl.binaryLength,d.writeUInt32LE(t,h),h+=Sl.fromServiceId,d.writeUInt32LE(n,h),h+=Sl.toServiceId,d.writeBigInt64LE(BigInt(p),h),h+=Sl.sentAt,c.copy(d,h),h+=l,s&&o&&s.copy(d,h),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Sl.protocolPrefix);if(t+=Sl.protocolPrefix,n!==Al)return null;if(e.byteLength<Il)return Ol(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Sl.protocolVersion;const i=e.readUInt32LE(t);t+=Sl.jsonLength;const s=e.readUInt32LE(t);t+=Sl.binaryLength;const o=e.readUInt32LE(t);t+=Sl.fromServiceId;const a=e.readUInt32LE(t);t+=Sl.toServiceId;const c=e.readBigInt64LE(t);t+=Sl.sentAt;const l=i+s,u=e.subarray(t,t+l),d=e.subarray(0,Il);let p=null;return e.byteLength-Il-i-s>0&&(p=e.subarray(Il+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},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=yl(n);if(!i?.json)return Ol("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&El(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=Il+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<Il)return Ol("Invalid Header Size"),e;let n=0;return n+=Sl.protocolPrefix,n+=Sl.protocolVersion,n+=Sl.jsonLength,n+=Sl.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Sl.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=_l+r,s=Buffer.alloc(i);return s.write(Nl,t),t+=wl.protocolPrefix,s.writeUint32LE(r,t),t+=wl.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<_l)return{command:null};const n=e.toString("utf-8",t,wl.protocolPrefix);if(t+=wl.protocolPrefix,n!==Nl)return{command:null};const r=e.readUInt32LE(t);t+=wl.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-_l-r;let o=null;s>0&&(o=e.subarray(_l+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Ll="KMSG",Tl="KCMD",Bl=xl("klProtocol"),jl=new TextEncoder;var Dl={encode:(e,t,n)=>{const r={json:e.json},i=Cl(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=jl.encode(a),l=c.byteLength,u=new ArrayBuffer(Sl.protocolPrefix+Sl.protocolVersion+Sl.jsonLength+Sl.binaryLength+Sl.fromServiceId+Sl.toServiceId+Sl.sentAt+l+o),d=new DataView(u),p=new Uint8Array(u),h=Date.now();let f=0;for(let e=0;e<4;++e)p[f++]=Ll.charCodeAt(e);return d.setUint8(f,1),f+=Sl.protocolVersion,d.setUint32(f,l,!0),f+=Sl.jsonLength,d.setUint32(f,o,!0),f+=Sl.binaryLength,d.setUint32(f,t,!0),f+=Sl.fromServiceId,d.setUint32(f,n,!0),f+=Sl.toServiceId,d.setBigInt64(f,BigInt(h),!0),f+=Sl.sentAt,p.set(c,f),f+=l,s&&o&&p.set(new Uint8Array(s),f),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Sl.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ll)return null;if(e.byteLength<Il)return Bl.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Sl.protocolVersion;const s=t.getUint32(n,!0);n+=Sl.jsonLength;const o=t.getUint32(n,!0);n+=Sl.binaryLength;const a=t.getUint32(n,!0);n+=Sl.fromServiceId;const c=t.getUint32(n,!0);n+=Sl.toServiceId;const l=t.getBigInt64(n,!0);n+=Sl.sentAt;const u=s+o,d=e.slice(n,n+u),p=new Uint8Array(e,0,Il);let h=null;if(e.byteLength-Il-s-o>0){h=new Uint8Array(e,Il+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:p.slice().buffer},remaining:h}},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=yl(s);if(!a?.json)return Bl.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&El(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,u=null;const d=Il+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Il)return Bl("Invalid Header Size"),e;let n=0;n+=Sl.protocolPrefix,n+=Sl.protocolVersion,n+=Sl.jsonLength,n+=Sl.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Sl.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=jl.encode(e),r=n.byteLength,i=new ArrayBuffer(_l+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=Tl.charCodeAt(e);return s.setUint32(t,r,!0),t+=wl.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<_l)return{command:null};let r="";for(let e=0;e<wl.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Tl)return{command:null};const i=t.getUint32(n,!0);n+=wl.txtLength;const s=e.byteLength-_l-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-_l)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(_l+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};const Ul=xl("klTransmissionManager"),Ml=()=>{const e=(t,n,r,i)=>{let s=n,o=null;const a=t instanceof ArrayBuffer;if(Ul(`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=Dl.decodeHeader(c)):(c=s?.partialHeaderData?Buffer.concat([s.partialHeaderData,t]):t,o=Pl.decodeHeader(c)),!o){const{command:t,missing:s,remainingData:o}=a?Dl.decodeCommand(c):Pl.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):Ul(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?(Ul(`${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 Ul(`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;Ul(`Received ${s.header.totalBytesReceived} of ${s.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?Dl.decodeFullKlMessage(s.header):Pl.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 u=l;if(o?.remaining&&(u=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),u)return Ul(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,i)}};return e};gl.config={...gl.config,...ml};const Fl={info:nc("ipcServer:info"),data:nc("ipcServer:data")};let Rl,Wl,Gl,Vl,Hl={};const zl=Ml(),ql=e=>{Hl[e]&&(Fl.info(`Client disconnected [${e}]`),delete Hl[e],Wl&&Wl(e))};var Kl=e=>(e?.ipcId&&(gl.config.id=e.ipcId),e?.ipcAppSpace&&(gl.config.appspace=e.ipcAppSpace),new Promise((e=>{gl.serve((()=>{Fl.info("IPC Server Initiated"),gl.server.on("data",((e,t)=>{const n=Hl[t.id];n?(Fl.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),zl(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Fl.data(`Received command from client [${t.id}]: ${e.command}`),void(Gl&&Gl(t.id,e.command,n));e.klMessage&&Vl&&Vl({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Fl.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),gl.server.on("connect",(e=>{const t=sc();Fl.info(`New client connected. Registered as "${t}"`),e.id=t,Hl[t]={socket:e,activeMessage:null,disconnectHandler:()=>ql(t)},e.on("close",Hl[t].disconnectHandler),Rl&&Rl(t)})),gl.server.on("disconnect",(e=>{ql(e.id)})),gl.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),gl.server.start()}))),Jl=e=>{Rl=e},Yl=e=>{Wl=e},Xl=e=>Vl=e,Zl=(e,t)=>{const n=Hl[e];if(!n)return Fl.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=vl)return Fl.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=Pl.encodeCommand(t);return n.socket.write(r),!0},Ql=(e,t)=>{const n=Hl[e];return!!n&&(Fl.info(`Renaming socket id [${e}] to [${t}]`),delete Hl[e],n.socket.id=t,Hl[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>ql(t),n.socket.on("close",n.disconnectHandler),!0)},eu=e=>{Gl=e};let tu=Pl;bl&&(tu=Dl);var nu,ru=tu;!function(e){e.FunctionNotFound="FNC_NOT_FOUND"}(nu||(nu={}));let iu=Math.ceil(Date.now()/1e3);var su={exports:{}};const ou=["nodebuffer","arraybuffer","fragments"],au="undefined"!=typeof Blob;au&&ou.push("blob");var cu={BINARY_TYPES:ou,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:au,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:lu}=cu,uu=Buffer[Symbol.species];function du(e,t,n,r,i){for(let s=0;s<i;s++)n[r+s]=e[s]^t[3&s]}function pu(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(su.exports={concat:function(e,t){if(0===e.length)return lu;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 uu(n.buffer,n.byteOffset,r):n},mask:du,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 uu(t):ArrayBuffer.isView(t)?n=new uu(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:pu},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");su.exports.mask=function(t,n,r,i,s){s<48?du(t,n,r,i,s):e.mask(t,n,r,i,s)},su.exports.unmask=function(t,n){t.length<32?pu(t,n):e.unmask(t,n)}}catch(e){}var hu=su.exports;const fu=Symbol("kDone"),gu=Symbol("kRun");const mu=B,vu=hu,yu=class{constructor(e){this[fu]=()=>{this.pending--,this[gu]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[gu]()}[gu](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[fu])}}},{kStatusCode:bu}=cu,Su=Buffer[Symbol.species],wu=Buffer.from([0,0,255,255]),Iu=Symbol("permessage-deflate"),_u=Symbol("total-length"),$u=Symbol("callback"),Cu=Symbol("buffers"),ku=Symbol("error");let Eu;var xu=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,!Eu){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Eu=new yu(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[$u];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){Eu.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){Eu.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]?mu.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=mu.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Iu]=this,this._inflate[_u]=0,this._inflate[Cu]=[],this._inflate.on("error",Ou),this._inflate.on("data",Nu)}this._inflate[$u]=n,this._inflate.write(e),t&&this._inflate.write(wu),this._inflate.flush((()=>{const e=this._inflate[ku];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=vu.concat(this._inflate[Cu],this._inflate[_u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[_u]=0,this._inflate[Cu]=[],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]?mu.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=mu.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[_u]=0,this._deflate[Cu]=[],this._deflate.on("data",Au)}this._deflate[$u]=n,this._deflate.write(e),this._deflate.flush(mu.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=vu.concat(this._deflate[Cu],this._deflate[_u]);t&&(e=new Su(e.buffer,e.byteOffset,e.length-4)),this._deflate[$u]=null,this._deflate[_u]=0,this._deflate[Cu]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function Au(e){this[Cu].push(e),this[_u]+=e.length}function Nu(e){this[_u]+=e.length,this[Iu]._maxPayload<1||this[_u]<=this[Iu]._maxPayload?this[Cu].push(e):(this[ku]=new RangeError("Max payload size exceeded"),this[ku].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ku][bu]=1009,this.removeListener("data",Nu),this.reset())}function Ou(e){this[Iu]._inflate=null,e[bu]=1007,this[$u](e)}var Pu={exports:{}};const{isUtf8:Lu}=j,{hasBlob:Tu}=cu;function Bu(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(Pu.exports={isBlob:function(e){return Tu&&"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:Bu,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]},Lu)Pu.exports.isValidUTF8=function(e){return e.length<24?Bu(e):Lu(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Pu.exports.isValidUTF8=function(t){return t.length<32?Bu(t):e(t)}}catch(e){}var ju=Pu.exports;const{Writable:Du}=T,Uu=xu,{BINARY_TYPES:Mu,EMPTY_BUFFER:Fu,kStatusCode:Ru,kWebSocket:Wu}=cu,{concat:Gu,toArrayBuffer:Vu,unmask:Hu}=hu,{isValidStatusCode:zu,isValidUTF8:qu}=ju,Ku=Buffer[Symbol.species];var Ju=class extends Du{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Mu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Wu]=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 Ku(t.buffer,t.byteOffset+e,t.length-e),new Ku(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 Ku(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[Uu.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=Fu;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]&&Hu(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[Uu.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?Gu(n,t):"arraybuffer"===this._binaryType?Vu(Gu(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=Gu(n,t);if(!this._skipUTF8Validation&&!qu(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,Fu),this.end();else{const n=e.readUInt16BE(0);if(!zu(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Ku(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!qu(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[Ru]=r,s}};const{randomFillSync:Yu}=l,Xu=xu,{EMPTY_BUFFER:Zu,kWebSocket:Qu,NOOP:ed}=cu,{isBlob:td,isValidStatusCode:nd}=ju,{mask:rd,toBuffer:id}=hu,sd=Symbol("kByteLength"),od=Buffer.alloc(4),ad=8192;let cd,ld=ad;var ud=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=ed,this[Qu]=void 0}static frame(e,t){let n,r,i=!1,s=2,o=!1;t.mask&&(n=t.maskBuffer||od,t.generateMask?t.generateMask(n):(ld===ad&&(void 0===cd&&(cd=Buffer.alloc(ad)),Yu(cd,0,ad),ld=0),n[0]=cd[ld++],n[1]=cd[ld++],n[2]=cd[ld++],n[3]=cd[ld++]),o=!(n[0]|n[1]|n[2]|n[3]),s=6),"string"==typeof e?r=t.mask&&!o||void 0===t[sd]?(e=Buffer.from(e)).length:t[sd]:(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?(rd(e,n,c,s,r),[c]):(rd(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let s;if(void 0===t)s=Zu;else{if("number"!=typeof t||!nd(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={[sd]: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):td(t)?(i=t.size,s=!1):(i=(t=id(t)).length,s=id.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[sd]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};td(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):td(t)?(i=t.size,s=!1):(i=(t=id(t)).length,s=id.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[sd]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};td(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[Xu.extensionName];let i,s,o=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):td(e)?(i=e.size,s=!1):(i=(e=id(e)).length,s=id.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={[sd]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:s,rsv1:a};td(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[sd],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(dd,this,e,i)}this._bufferedBytes-=r[sd];const s=id(t);n?this.dispatch(s,n,r,i):(this._state=0,this.sendFrame(e.frame(s,r),i),this.dequeue())})).catch((e=>{process.nextTick(pd,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const s=this._extensions[Xu.extensionName];this._bufferedBytes+=r[sd],this._state=1,s.compress(t,r.fin,((t,n)=>{if(this._socket.destroyed){dd(this,new Error("The socket was closed while data was being compressed"),i)}else this._bufferedBytes-=r[sd],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][sd],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][sd],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 dd(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 pd(e,t,n){dd(e,t,n),e.onerror(t)}const{kForOnEventAttribute:hd,kListener:fd}=cu,gd=Symbol("kCode"),md=Symbol("kData"),vd=Symbol("kError"),yd=Symbol("kMessage"),bd=Symbol("kReason"),Sd=Symbol("kTarget"),wd=Symbol("kType"),Id=Symbol("kWasClean");class _d{constructor(e){this[Sd]=null,this[wd]=e}get target(){return this[Sd]}get type(){return this[wd]}}Object.defineProperty(_d.prototype,"target",{enumerable:!0}),Object.defineProperty(_d.prototype,"type",{enumerable:!0});class $d extends _d{constructor(e,t={}){super(e),this[gd]=void 0===t.code?0:t.code,this[bd]=void 0===t.reason?"":t.reason,this[Id]=void 0!==t.wasClean&&t.wasClean}get code(){return this[gd]}get reason(){return this[bd]}get wasClean(){return this[Id]}}Object.defineProperty($d.prototype,"code",{enumerable:!0}),Object.defineProperty($d.prototype,"reason",{enumerable:!0}),Object.defineProperty($d.prototype,"wasClean",{enumerable:!0});class Cd extends _d{constructor(e,t={}){super(e),this[vd]=void 0===t.error?null:t.error,this[yd]=void 0===t.message?"":t.message}get error(){return this[vd]}get message(){return this[yd]}}Object.defineProperty(Cd.prototype,"error",{enumerable:!0}),Object.defineProperty(Cd.prototype,"message",{enumerable:!0});class kd extends _d{constructor(e,t={}){super(e),this[md]=void 0===t.data?null:t.data}get data(){return this[md]}}Object.defineProperty(kd.prototype,"data",{enumerable:!0});const Ed={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[hd]&&r[fd]===t&&!r[hd])return;let r;if("message"===e)r=function(e,n){const r=new kd("message",{data:n?e:e.toString()});r[Sd]=this,Ad(t,this,r)};else if("close"===e)r=function(e,n){const r=new $d("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[Sd]=this,Ad(t,this,r)};else if("error"===e)r=function(e){const n=new Cd("error",{error:e,message:e.message});n[Sd]=this,Ad(t,this,n)};else{if("open"!==e)return;r=function(){const e=new _d("open");e[Sd]=this,Ad(t,this,e)}}r[hd]=!!n[hd],r[fd]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[fd]===t&&!n[hd]){this.removeListener(e,n);break}}};var xd={CloseEvent:$d,ErrorEvent:Cd,Event:_d,EventTarget:Ed,MessageEvent:kd};function Ad(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:Nd}=ju;function Od(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var Pd={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,u=-1,d=0;for(;d<e.length;d++)if(l=e.charCodeAt(d),void 0===n)if(-1===u&&1===Nd[l])-1===c&&(c=d);else if(0===d||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);const r=e.slice(c,u);44===l?(Od(t,r,i),i=Object.create(null)):n=r,c=u=-1}}else-1===u&&-1!==c&&(u=d);else if(void 0===r)if(-1===u&&1===Nd[l])-1===c&&(c=d);else if(32===l||9===l)-1===u&&-1!==c&&(u=d);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d),Od(i,e.slice(c,u),!0),44===l&&(Od(t,n,i),i=Object.create(null),n=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${d}`);r=e.slice(c,d),c=u=-1}else if(o){if(1!==Nd[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:s||(s=!0),o=!1}else if(a)if(1===Nd[l])-1===c&&(c=d);else if(34===l&&-1!==c)a=!1,u=d;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${d}`);o=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===Nd[l])-1===c&&(c=d);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);let o=e.slice(c,u);s&&(o=o.replace(/\\/g,""),s=!1),Od(i,r,o),44===l&&(Od(t,n,i),i=Object.create(null),n=void 0),r=void 0,c=u=-1}}else-1===u&&(u=d);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===u&&(u=d);const p=e.slice(c,u);return void 0===n?Od(t,p,i):(void 0===r?Od(i,p,!0):Od(i,r,s?p.replace(/\\/g,""):p),Od(t,n,i)),t}};const Ld=D,Td=U,Bd=M,jd=A,Dd=N,{randomBytes:Ud,createHash:Md}=l,{URL:Fd}=F,Rd=xu,Wd=Ju,Gd=ud,{isBlob:Vd}=ju,{BINARY_TYPES:Hd,EMPTY_BUFFER:zd,GUID:qd,kForOnEventAttribute:Kd,kListener:Jd,kStatusCode:Yd,kWebSocket:Xd,NOOP:Zd}=cu,{EventTarget:{addEventListener:Qd,removeEventListener:ep}}=xd,{format:tp,parse:np}=Pd,{toBuffer:rp}=hu,ip=3e4,sp=Symbol("kAborted"),op=[8,13],ap=["CONNECTING","OPEN","CLOSING","CLOSED"],cp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let lp=class e extends Ld{constructor(t,n,r){super(),this._binaryType=Hd[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=zd,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]),dp(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Hd.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 Wd({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Gd(t,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=t,i[Xd]=this,s[Xd]=this,t[Xd]=this,i.on("conclude",vp),i.on("drain",yp),i.on("error",bp),i.on("message",wp),i.on("ping",Ip),i.on("pong",_p),s.onerror=Cp,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",Ep),t.on("data",xp),t.on("end",Ap),t.on("error",Np),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[Rd.extensionName]&&this._extensions[Rd.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())})),kp(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";gp(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||zd,n,r)):mp(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||zd,n,r)):mp(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 mp(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Rd.extensionName]||(i.compress=!1),this._sender.send(t||zd,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";gp(this,this._req,e)}}};Object.defineProperty(lp,"CONNECTING",{enumerable:!0,value:ap.indexOf("CONNECTING")}),Object.defineProperty(lp.prototype,"CONNECTING",{enumerable:!0,value:ap.indexOf("CONNECTING")}),Object.defineProperty(lp,"OPEN",{enumerable:!0,value:ap.indexOf("OPEN")}),Object.defineProperty(lp.prototype,"OPEN",{enumerable:!0,value:ap.indexOf("OPEN")}),Object.defineProperty(lp,"CLOSING",{enumerable:!0,value:ap.indexOf("CLOSING")}),Object.defineProperty(lp.prototype,"CLOSING",{enumerable:!0,value:ap.indexOf("CLOSING")}),Object.defineProperty(lp,"CLOSED",{enumerable:!0,value:ap.indexOf("CLOSED")}),Object.defineProperty(lp.prototype,"CLOSED",{enumerable:!0,value:ap.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(lp.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(lp.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[Kd])return t[Jd];return null},set(t){for(const t of this.listeners(e))if(t[Kd]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[Kd]:!0})}})})),lp.prototype.addEventListener=Qd,lp.prototype.removeEventListener=ep;var up=lp;function dp(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:op[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,!op.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${op.join(", ")})`);let s;if(t instanceof Fd)s=t;else try{s=new Fd(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 pp(e,t)}const l=o?443:80,u=Ud(16).toString("base64"),d=o?Td.request:Bd.request,p=new Set;let h,f;if(i.createConnection=i.createConnection||(o?fp:hp),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":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new Rd(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=tp({[Rd.extensionName]:h.offer()})),n.length){for(const e of n){if("string"!=typeof e||!cp.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")),f=e._req=d(i),e._redirects&&e.emit("redirect",e.url,f)}else f=e._req=d(i);i.timeout&&f.on("timeout",(()=>{gp(e,f,"Opening handshake has timed out")})),f.on("error",(t=>{null===f||f[sp]||(f=e._req=null,pp(e,t))})),f.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 gp(e,f,"Maximum redirects exceeded");let s;f.abort();try{s=new Fd(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void pp(e,n)}dp(e,s,n,r)}else e.emit("unexpected-response",f,s)||gp(e,f,`Unexpected server response: ${s.statusCode}`)})),f.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==lp.CONNECTING)return;f=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void gp(e,n,"Invalid Upgrade header");const o=Md("sha1").update(u+qd).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void gp(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 gp(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!h){return void gp(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=np(l)}catch(t){return void gp(e,n,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==Rd.extensionName){return void gp(e,n,"Server indicated an extension that was not requested")}try{h.accept(t[Rd.extensionName])}catch(t){return void gp(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Rd.extensionName]=h}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(f,e):f.end()}function pp(e,t){e._readyState=lp.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function hp(e){return e.path=e.socketPath,jd.connect(e)}function fp(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=jd.isIP(e.host)?"":e.host),Dd.connect(e)}function gp(e,t,n){e._readyState=lp.CLOSING;const r=new Error(n);Error.captureStackTrace(r,gp),t.setHeader?(t[sp]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(pp,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function mp(e,t,n){if(t){const n=Vd(t)?t.size:rp(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${ap[e.readyState]})`);process.nextTick(n,t)}}function vp(e,t){const n=this[Xd];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[Xd]&&(n._socket.removeListener("data",xp),process.nextTick($p,n._socket),1005===e?n.close():n.close(e,t))}function yp(){const e=this[Xd];e.isPaused||e._socket.resume()}function bp(e){const t=this[Xd];void 0!==t._socket[Xd]&&(t._socket.removeListener("data",xp),process.nextTick($p,t._socket),t.close(e[Yd])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Sp(){this[Xd].emitClose()}function wp(e,t){this[Xd].emit("message",e,t)}function Ip(e){const t=this[Xd];t._autoPong&&t.pong(e,!this._isServer,Zd),t.emit("ping",e)}function _p(e){this[Xd].emit("pong",e)}function $p(e){e.resume()}function Cp(e){const t=this[Xd];t.readyState!==lp.CLOSED&&(t.readyState===lp.OPEN&&(t._readyState=lp.CLOSING,kp(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function kp(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),ip)}function Ep(){const e=this[Xd];let t;this.removeListener("close",Ep),this.removeListener("data",xp),this.removeListener("end",Ap),e._readyState=lp.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Xd]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Sp),e._receiver.on("finish",Sp))}function xp(e){this[Xd]._receiver.write(e)||this.pause()}function Ap(){const e=this[Xd];e._readyState=lp.CLOSING,e._receiver.end(),this.end()}function Np(){const e=this[Xd];this.removeListener("error",Np),this.on("error",Zd),e&&(e._readyState=lp.CLOSING,this.destroy())}const{tokenChars:Op}=ju;var Pp={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===Op[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 Lp=D,Tp=M,{createHash:Bp}=l,jp=Pd,Dp=xu,Up=Pp,Mp=up,{GUID:Fp,kWebSocket:Rp}=cu,Wp=/^[+/0-9A-Za-z]{22}==$/;var Gp=class extends Lp{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:Mp,...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=Tp.createServer(((e,t)=>{const n=Tp.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(Vp,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(Vp,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Vp(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",Hp);const i=e.headers["sec-websocket-key"],s=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void qp(this,e,t,405,"Invalid HTTP method")}if(void 0===s||"websocket"!==s.toLowerCase()){return void qp(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!Wp.test(i)){return void qp(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void qp(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void zp(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=Up.parse(a)}catch(n){return void qp(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&void 0!==l){const n=new Dp(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=jp.parse(l);e[Dp.extensionName]&&(n.accept(e[Dp.extensionName]),u[Dp.extensionName]=n)}catch(n){return void qp(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 zp(t,o||401,a,l);this.completeUpgrade(u,i,c,e,t,n,r)}));if(!this.options.verifyClient(s))return zp(t,401)}this.completeUpgrade(u,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,s,o){if(!i.readable||!i.writable)return i.destroy();if(i[Rp])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return zp(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Bp("sha1").update(t+Fp).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[Dp.extensionName]){const t=e[Dp.extensionName].params,n=jp.format({[Dp.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",Hp),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(Vp,this)}))),o(c,r)}};function Vp(e){e._state=2,e.emit("close")}function Hp(){this.destroy()}function zp(e,t,n,r){n=n||Tp.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} ${Tp.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function qp(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,qp),e.emit("wsClientError",r,n,t)}else zp(n,r,i)}var Kp=Ua(Gp);const Jp=nc("websocketServer"),Yp={},Xp=Ml();let Zp,Qp,eh,th,nh;const rh=e=>{const t=Yp[e];t&&t.socket.close()};var ih={startServer:e=>{nh=new Kp({port:e,maxPayload:104857600}),nh.on("connection",(e=>{const t=sc();Jp(`New client connected. Registered as "${t}"`),e.id=t,Yp[t]={socket:e,activeMessage:null},Zp&&Zp(t),e.on("message",(t=>{if(t instanceof Buffer){const n=Yp[e.id];Xp(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),Jp(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{rh(n.socket.id)};if(t.command)return Jp(`Received command from client [${n.socket.id}]: ${t.command}`),void(eh&&eh(n.socket.id,t.command,r,i));t.klMessage&&th&&th({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",(()=>{Jp(`Client disconnected: ${e.id}`),Qp&&Qp(e.id),delete Yp[e.id]})),e.on("error",(()=>{Jp(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},stopServer:()=>{nh.close((()=>{console.log("WebSocket server stopped")}))},onClientConnected:e=>{Zp=e},onClientDisconnected:e=>{Qp=e},onClientCommand:e=>{eh=e},sendCommand:(e,t)=>{const n=Yp[e];if(!n)return Jp(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=vl)return Jp("Message is too long to be a command. Use sendMessage instead."),!1;const r=Pl.encodeCommand(t);return n.socket.send(r),!0},onMessageReceived:e=>th=e,terminateConnection:rh};const sh=nc("stopService"),oh=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Bc.getAllServiceVersions(t);sh(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Bc.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},ah=nc("removeService"),ch=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Bc.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),ah(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Bc.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},lh=nc("launchService"),uh=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=vc();lh(`Loading service ${t}@${n} from ${i}`);const{errorMsg:s,service:o,errorCode:a}=await Bc.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,u=async()=>{const r=o.status;return"running"===r?(lh(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(lh(`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"}):(lh("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return lh(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},dh=nc("getMatchingServices"),ph=async e=>{const t=e.args[0],n=[],r=[];dh(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=Bc.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:Bc.getServiceRootDirectory(t)}):r.push({name:e,version:i})}dh(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},hh=nc("getSecretsValues");let fh;var gh=async e=>{const t=e.args[0].services;if(!fh)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");hh(`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 fh({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})},mh=e=>{fh=e};const vh=nc("getMappedSecrets");let yh;var bh=async e=>{const t=e.args[0].services;vh(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await yh(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})},Sh=e=>{yh=e};const wh=nc("getServiceContents"),Ih=({reply:e,args:t})=>{const[n]=t;wh(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Bc.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}]})}wh(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let _h=null;const $h=async e=>{const{data:t,error:n}=await(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}}})(`${(()=>{if(!_h)throw new Error("Unknown server URL. Please call `setServerUrl` before using the APIs.");return _h})()}/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"}},Ch={},kh=async e=>{const t=(e=>{const t=Ch[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 $h(e);return n&&(Ch[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}},Eh=nc("activeClients");let xh={},Ah={};const Nh=(e,t)=>`${e}_${t}`,Oh=e=>xh[e]||null,Ph=(e,t)=>{const n=Nh(e,t);return Ah[n]||[]},Lh=()=>{for(const e in xh){const t=xh[e];if(t?.transport===Sa.WS){const e=Pl.encodeCommand(va.ServicesListChanged);t.send(e)}}},Th=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===Sa.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 kh(o.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&Eh(`Unable to validate API Key, usage will be limited. SessionId: ${n}`)}xh[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=Nh(e.serviceName,e.version);Ah[r]=Ah[r]||[];return Ah[r].some((e=>e.serviceId===n))||Ah[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=Nh(e.serviceName,e.version),s=Ah[i]?.findIndex((e=>e.serviceId===n));if(-1!==s&&(Ah[i].splice(s,1),!Ah[i].length)){const t=Bc.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=Oh(t.info.sessionId);e?.extraInfo.ipcSocketId&&Zl(e?.extraInfo.ipcSocketId,va.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=Nh(e.targetService.serviceName,e.targetService.version),r=Ah[t].findIndex((e=>e.serviceId===n));-1!==r&&Ah[t].splice(r,1)}t.length=0}},r===Sa.IPC&&(Lh(),jh(n))},Bh=()=>{const e=Object.values(xh);for(const t of e)if(t.transport===Sa.IPC){const e=t.extraInfo.ipcSocketId,n=Bc.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){Ph(n.info.name,n.info.version).length||e&&Zl(e,va.BroadcastEnd)}}},jh=e=>{const t=Bc.getServiceBySessionId(e);if(t?.info.eventEmitter){if(Ph(t.info.name,t.info.version).length){const t=Oh(e);t?.extraInfo.ipcSocketId&&Zl(t?.extraInfo.ipcSocketId,va.BroadcastStart)}}},Dh=e=>{const t=xh[e];delete xh[e],t?.transport===Sa.IPC?Lh():(t?.removeAllSubscriptions(),Bh())},Uh=nc("ipc:handleIpcClientCommand"),Mh=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(va.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 Uh(`Ignoring ACK response from IPC service ${e} with no service id`);Uh(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(Ql(e,t),r=t);let i=!1;t&&(i=Bc.setServiceStatus(t,"running")),i?Th({serviceSessionId:t||e,transport:Sa.IPC,send:n,extraInfo:{ipcSocketId:t}}):Zl(r,va.SendManifest)}));!r&&Uh(`Received unknown command [${t}] from service ${e}`)};let Fh={};W.platform();const Rh=async e=>{const t=e.args[0];if(Fh.chooseDirectory)try{const n=await Fh.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"})},Wh=async e=>{const t=e.args[0];if(Fh.chooseFile)try{const n=await Fh.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"})},Gh=e=>{Fh=e};var Vh={},Hh={},zh={};function qh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Kh(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Jh(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Yh(e,...t){if(!Jh(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 Xh(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");qh(e.outputLen),qh(e.blockLen)}function Zh(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 Qh(e,t){Yh(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(zh,"__esModule",{value:!0}),zh.output=zh.exists=zh.hash=zh.bytes=zh.bool=zh.number=zh.isBytes=void 0,zh.number=qh,zh.bool=Kh,zh.isBytes=Jh,zh.bytes=Yh,zh.hash=Xh,zh.exists=Zh,zh.output=Qh;const ef={number:qh,bool:Kh,bytes:Yh,hash:Xh,exists:Zh,output:Qh};zh.default=ef;var tf={};Object.defineProperty(tf,"__esModule",{value:!0}),tf.add5L=tf.add5H=tf.add4H=tf.add4L=tf.add3H=tf.add3L=tf.add=tf.rotlBL=tf.rotlBH=tf.rotlSL=tf.rotlSH=tf.rotr32L=tf.rotr32H=tf.rotrBL=tf.rotrBH=tf.rotrSL=tf.rotrSH=tf.shrSL=tf.shrSH=tf.toBig=tf.split=tf.fromBig=void 0;const nf=BigInt(2**32-1),rf=BigInt(32);function sf(e,t=!1){return t?{h:Number(e&nf),l:Number(e>>rf&nf)}:{h:0|Number(e>>rf&nf),l:0|Number(e&nf)}}function of(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}=sf(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}tf.fromBig=sf,tf.split=of;const af=(e,t)=>BigInt(e>>>0)<<rf|BigInt(t>>>0);tf.toBig=af;const cf=(e,t,n)=>e>>>n;tf.shrSH=cf;const lf=(e,t,n)=>e<<32-n|t>>>n;tf.shrSL=lf;const uf=(e,t,n)=>e>>>n|t<<32-n;tf.rotrSH=uf;const df=(e,t,n)=>e<<32-n|t>>>n;tf.rotrSL=df;const pf=(e,t,n)=>e<<64-n|t>>>n-32;tf.rotrBH=pf;const hf=(e,t,n)=>e>>>n-32|t<<64-n;tf.rotrBL=hf;const ff=(e,t)=>t;tf.rotr32H=ff;const gf=e=>e;tf.rotr32L=gf;const mf=(e,t,n)=>e<<n|t>>>32-n;tf.rotlSH=mf;const vf=(e,t,n)=>t<<n|e>>>32-n;tf.rotlSL=vf;const yf=(e,t,n)=>t<<n-32|e>>>64-n;tf.rotlBH=yf;const bf=(e,t,n)=>e<<n-32|t>>>64-n;function Sf(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}tf.rotlBL=bf,tf.add=Sf;const wf=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);tf.add3L=wf;const If=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;tf.add3H=If;const _f=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);tf.add4L=_f;const $f=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;tf.add4H=$f;const Cf=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);tf.add5L=Cf;const kf=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0;tf.add5H=kf;const Ef={fromBig:sf,split:of,toBig:af,shrSH:cf,shrSL:lf,rotrSH:uf,rotrSL:df,rotrBH:pf,rotrBL:hf,rotr32H:ff,rotr32L:gf,rotlSH:mf,rotlSL:vf,rotlBH:yf,rotlBL:bf,add:Sf,add3L:wf,add3H:If,add4L:_f,add4H:$f,add5H:kf,add5L:Cf};tf.default=Ef;var xf={},Af={};Object.defineProperty(Af,"__esModule",{value:!0}),Af.crypto=void 0,Af.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
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=Af,n=zh;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")}}(xf),Object.defineProperty(Hh,"__esModule",{value:!0}),Hh.shake256=Hh.shake128=Hh.keccak_512=Hh.keccak_384=Hh.keccak_256=Hh.keccak_224=Hh.sha3_512=Hh.sha3_384=Hh.sha3_256=Hh.sha3_224=Hh.Keccak=Hh.keccakP=void 0;const Nf=zh,Of=tf,Pf=xf,Lf=[],Tf=[],Bf=[],jf=BigInt(0),Df=BigInt(1),Uf=BigInt(2),Mf=BigInt(7),Ff=BigInt(256),Rf=BigInt(113);for(let e=0,t=Df,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Lf.push(2*(5*r+n)),Tf.push((e+1)*(e+2)/2%64);let i=jf;for(let e=0;e<7;e++)t=(t<<Df^(t>>Mf)*Rf)%Ff,t&Uf&&(i^=Df<<(Df<<BigInt(e))-Df);Bf.push(i)}const[Wf,Gf]=(0,Of.split)(Bf,!0),Vf=(e,t,n)=>n>32?(0,Of.rotlBH)(e,t,n):(0,Of.rotlSH)(e,t,n),Hf=(e,t,n)=>n>32?(0,Of.rotlBL)(e,t,n):(0,Of.rotlSL)(e,t,n);function zf(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=Vf(s,o,1)^n[r],c=Hf(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=Tf[n],s=Vf(t,i,r),o=Hf(t,i,r),a=Lf[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]^=Wf[r],e[1]^=Gf[r]}n.fill(0)}Hh.keccakP=zf;class qf extends Pf.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,Nf.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,Pf.u32)(this.state)}keccak(){Pf.isLE||(0,Pf.byteSwap32)(this.state32),zf(this.state32,this.rounds),Pf.isLE||(0,Pf.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,Nf.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,Pf.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,Nf.exists)(this,!1),(0,Nf.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,Nf.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,Nf.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 qf(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}}Hh.Keccak=qf;const Kf=(e,t,n)=>(0,Pf.wrapConstructor)((()=>new qf(t,e,n)));Hh.sha3_224=Kf(6,144,28),Hh.sha3_256=Kf(6,136,32),Hh.sha3_384=Kf(6,104,48),Hh.sha3_512=Kf(6,72,64),Hh.keccak_224=Kf(1,144,28),Hh.keccak_256=Kf(1,136,32),Hh.keccak_384=Kf(1,104,48),Hh.keccak_512=Kf(1,72,64);const Jf=(e,t,n)=>(0,Pf.wrapXOFConstructorWithOpts)(((r={})=>new qf(t,e,void 0===r.dkLen?n:r.dkLen,!0)));Hh.shake128=Jf(31,168,16),Hh.shake256=Jf(31,136,32);const{sha3_512:Yf}=Hh,Xf=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function Zf(e){let t=0n;for(const n of e.values()){t=(t<<8n)+BigInt(n)}return t}const Qf=(e="")=>Zf(Yf(e)).toString(36).slice(1),eg=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),tg=({globalObj:e=(void 0!==Da?Da:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Xf(32,t):Xf(32,t);return Qf(r).substring(0,32)},ng=e=>()=>e++,rg=({random:e=Math.random,counter:t=ng(Math.floor(476782367*e())),length:n=24,fingerprint:r=tg({random:e})}={})=>function(){const i=(e=>eg[Math.floor(e()*eg.length)])(e),s=Date.now().toString(36),o=t().toString(36),a=Xf(n,e);return`${i+Qf(`${s+a+o+r}`).substring(1,n)}`},ig=rg();Vh.getConstants=()=>({defaultLength:24,bigLength:32}),Vh.init=rg,Vh.createId=ig,Vh.bufToBigInt=Zf,Vh.createCounter=ng,Vh.createFingerprint=tg,Vh.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:sg,init:og,getConstants:ag,isCuid:cg}=Vh;var lg=sg;const ug=nc("getUniqueId"),dg=({reply:e,sourceServiceId:t})=>{ug(`Generating unique id for service "${t}"`);return e({success:[lg()]})},pg=nc("getActiveServices"),hg=async({transport:e,sourceServiceId:t,reply:n})=>{if(pg(`Received GetServices request from ${e} [${t}]`),e===Sa.WS){let e=Bc.getActiveServices();const r=Oh(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===Sa.WS){if(!r?.extraInfo.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(Bc.isInternalKemuService),s=e.filter((e=>e.devMode&&Bc.isNotInternalKemuService(e))),o=e.filter((e=>Bc.isOfficialKemuService(e)&&Bc.isNotInternalKemuService(e)&&Bc.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=await(async e=>{const{features:t}=await kh(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=Bc.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:Bc.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}]})}},fg=v(R(import.meta.url)),gg=nc("hub"),mg=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=bl?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=ru.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}iu+=1;const u=`${i}-${iu}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let p=bl?new ArrayBuffer(0):Buffer.alloc(0);const h={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(p=ru.encode(h,a,c)),t[u]=d,n&&n(`Calling remote function "${e}" with message id "${u}"`);const f="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||f||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=t[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:h}),d.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)=>{iu+=1;const a=`${i}-${iu}-multicast-${e.substring(0,10)}`;let c=bl?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=o(r[0].serviceId);u&&(c=ru.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&&(u=o(i.serviceId),u&&(c=ru.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");mg.setLogger(gg);const vg=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=Oh(n.targetServiceId);if(!r)return gg(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,Sa.IPC;const i=t.json?.messageId;return gg(`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},yg=({sourceServiceId:e,args:t})=>{const n=Bc.getServiceBySessionId(e);if(n){const r=Ph(n.info.name,n.info.version),i=Ph(n.info.name,"*");if(!r.length&&!i.length)return;const s=[...r,...i],o=t[0],a={outputs:o.outputs,variantId:o.variantId,source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};mg.broadcast(ya.BroadcastEvent,[a],s,0)}},bg=e=>{const{send:t,transmission:n,json:r}=e;gg(`Raw message Id received from WS: ${r?.messageId}`);vg(Sa.WS,e)||mg.processMessage(Sa.WS,t,n,r)},Sg=e=>{const t=(n=e,`${va.SocketAcknowledge}${n}`);var n;ih.sendCommand(e,t)},wg=(e,t)=>{gg(`Received unknown command [${t}] from service ${e}`)},Ig=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,{apiKey:s}=t[0],o=n;await Th({serviceSessionId:n,transport:Sa.WS,send:r,terminateFn:()=>{ih.terminateConnection(n)},extraInfo:{websocketId:o,wsApiKey:s}}),i({success:[]})},_g=e=>{gg(`WS Client ${e} disconnected`),Dh(e)},$g=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==Sa.IPC){var i;gg(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Bc.getMatchingDevService(n.name,n.version,"stopped");if(t){gg(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const s=Oh(t.info.sessionId);if(!s)return void gg(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);s.send=r,xh[i=e]?delete xh[i]:Eh(`Could not find source client with session id ${i}`),Ql(e,t.info.sessionId);const o=await hc(n,n.path);t.info={...t.info,...o},gg(`Updating manifest for dev service ${t.info.sessionId}`),Bc.setServiceManifest(t.info.sessionId,o,"running"),gg(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Zl(t.info.sessionId,(e=>`${va.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=xh[e];t?t.isDevClient?(t.disconnected=!1,t.transport===Sa.IPC&&(Lh(),jh(e))):Eh(`Client with session id ${e} is not a dev client`):Eh(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{Bc.addDevService(e,n,"running");const t=Oh(e);t?t.isDevClient=!0:Th({serviceSessionId:e,transport:Sa.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}gg(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var Cg=async e=>{gg("Starting Kemu Hub...");const t=e?.ipc?.appSpace||"kemu.",n=e?.ipc?.id||"widgets";if(!e.serviceUrl)throw new Error("Missing service url, please set the `apiUrl` option.");const r=e.serviceUrl;_h=r,mg.registerFunction(ya.GetServiceContents,Ih),mg.registerFunction(ya.GetServices,hg),mg.registerFunction(ya.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"})})),mg.registerFunction(ya.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Sa.WS){const[e]=n,i=Oh(r);if(!i)return t({error:`Session id "${r}" not found`});gg(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),mg.registerFunction(ya.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Sa.WS){const[e]=n,i=Oh(r),s=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(gg(`Service ${r} subscribing to "${s.serviceName} (${s.version})"`),"hub"===s.serviceName)return i.addSubscription(s),void t({success:[]});if(!i.addSubscription(s))return gg(`Service ${r} already subscribed to "${s.serviceName} (${s.version})", ignoring request.`),t({success:[]});const o=Bc.getMatchingService(s.serviceName,s.version);if(!o)return gg(`Service ${s.serviceName} ${s.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return gg(`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=Oh(o.info.sessionId);return a?.extraInfo.ipcSocketId&&(gg(`Sending Broadcast START command to service ${o.info.sessionId}`),Zl(a?.extraInfo.ipcSocketId,va.BroadcastStart)),t({success:[]})}})),mg.registerFunction("stopService",oh),mg.registerFunction("removeService",ch),mg.registerFunction("launchService",uh),mg.registerFunction("getMatchingServices",ph),mg.registerFunction("getSecretsValues",gh),mg.registerFunction(ya.GetMappedSecrets,bh),mg.registerFunction(ya.BroadcastEvent,yg),mg.registerFunction(ya.ServiceManifest,$g),mg.registerFunction(ya.ChooseDirectoryDialog,Rh),mg.registerFunction(ya.ChooseFileDialog,Wh),mg.registerFunction(ya.GetUniqueId,dg),mg.registerFunction(ya.SocketAckResponse,Ig),Xl((e=>{const{send:t,transmission:n,json:r}=e;gg(`Raw message Id received from IPC: ${r?.messageId}`);vg(Sa.IPC,e)||mg.processMessage(Sa.IPC,t,n,r)})),ih.onMessageReceived(bg),ih.onClientConnected(Sg),ih.onClientCommand(wg),ih.onClientDisconnected(_g),eu(Mh),Jl((e=>{const t=(e=>`${va.IpcAcknowledge}${e}`)(e);Zl(e,t)})),Yl((e=>{gg(`IPC socket [${e}] disconnected`);const t=Oh(e);if(t){gg(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Bc.getServiceBySessionId(t.serviceSessionId);Bc.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,Lh()):Dh(t.serviceSessionId)}})),await Kl({ipcAppSpace:t,ipcId:n}),e?.ws?.disabled||await ih.startServer(e?.ws?.port||5368);const i=e?.defaultServicesPath||g.resolve(fg,"defaultServices"),s=process.env.DEV_SESSION_ID;Bc.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:t,id:n}),e?.servicesInstallPath&&(e=>{gc=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{mc=e})(e.testServicesInstallPath);const o=vc(),a=mc||ac,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=r,t},l=async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{});e?.getServiceSecretsFn?(Bc.setGetSecretsFunction(e.getServiceSecretsFn),mh(e.getServiceSecretsFn)):(Bc.setGetSecretsFunction(c),mh(c)),Sh(e?.getMappedSecretsFn?e.getMappedSecretsFn:l),Bc.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return G("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await Bc.loadServices(i,{fixedSession:s?parseInt(s):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0}),null!==e?.servicesInstallPath&&(await fc(o)||await b(o,{recursive:!0}),await Bc.loadServices(o,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME}));const u=process.env.DEV_NO_SPAWN_LIST?.split(",");await Bc.launchServices({noSpawningList:u||[]}),gg("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&Gh({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},kg=e=>{if(e===Sa.WS)return{handleWebsocketConnectionEvent:Sg,handleWebsocketClientDisconnectionEvent:_g,handleWebsocketMessage:bg,handleWebsocketClientCommand:wg,getRemoteInvoke:()=>mg}},Eg=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Bc.getAllServices().every((e=>"running"===e.status))){if(e.every((e=>"running"===Bc.getMatchingService(e.name,e.version)?.status)))return n()}t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let xg;const Ag=_o("run"),Ng=_a(),Og=1e3,Pg=C(process.argv.slice(2));global.ImageData=q,Dt({createCanvas:(e,t)=>J(e,t)});const Lg={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:de.ImageData}},loadImageFile:async e=>{const t=await K(e),n=J(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=J(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 Tg={start:async r=>{r=r||{};const i=r?.recipePath||Pg.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:V(H(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"),a=o?z(i):i,c=o?i:V(a,"recipe.json"),l=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(H(c),"utf-8"));if(!l)throw new Error("Failed to parse recipe file");const{serviceUrl:u,apiKey:d}=((e,t)=>{const n=Us(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 Vi();const p={id:l.id||String(Date.now()),version:1,author:""};(e=>{Sr=e})(console);const h=kg(ve.WS),f=(e,t)=>{if(t)h?.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;h?.handleWebsocketClientCommand(Og,t)}},g=(lo={instanceServiceId:Og,sendBuf:f,sendCmd:f,triggerOnCommand:(...e)=>uo(...e),triggerOnConnected:()=>po(),triggerOnDisconnected:()=>ho(),triggerOnMessageReceived:(...e)=>fo(...e)},lo);const m=(e,t)=>{if(t)g.triggerOnMessageReceived({send:f,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;g.triggerOnCommand(t)}},v=Ca(),y=h.getRemoteInvoke();v.disableServiceEncoding(0,!0),y.disableServiceEncoding(Og,!0);const b=Object.values(l.blocks[le].gates).filter((e=>e.type===Me.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=V(a,"services"),I=await n(w).then((()=>!0)).catch((()=>!1));await Cg({recipeRootPath:a,servicesInstallPath:I?V(a,"services"):null,noDefaultServices:!0,ws:{disabled:!0},serviceUrl:u,ipc:{appSpace:"kemu-runner.",id:p.id}}),Ag("Waiting for services to run"),await Eg(S),Ag("All services are running"),Ts(Ng);const _=await Os(l,"runner",p.version,p.author,Ss.Desktop);return xg=_,$a(_),await wa(d),new Promise(((e,t)=>{var n;Ia("acknowledged",(async()=>{await Ng.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Ls(_);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)})),Ag("Recipe started"),e({sendToInputWidget:r})})),g.triggerOnConnected(),g.triggerOnCommand((n=Og,`${fe.SocketAcknowledge}${n}`))}))},terminate:async()=>{xg&&await Ps(xg)},onVariableChange:(e,t)=>gr(e,t)};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{de as DataType,Tg as default,Lg as utils};
|