@kemu-io/edge-runtime 1.1.0 → 1.2.0
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.d.ts +6 -4
- package/runner.js +2 -2
package/runner.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{config as e}from"dotenv";import{readFile as t,access as n}from"node:fs/promises";import{nanoid as r}from"nanoid";import i from"jsonp";import s from"crypto-js";import o from"util";import a from"emittery";import"axios";import c from"jszip";import l from"mustache";import d,{scryptSync as u,createDecipheriv as p,createHash as g}from"crypto";import{satisfies as h}from"compare-versions";import f from"debug";import m,{join as v,dirname as y,resolve as b}from"path";import"node-ipc";import{mkdir as w,readFile as S,access as I,constants as _,readdir as $,rm as C}from"fs/promises";import k from"minimist";import E from"tty";import x,{homedir as A}from"os";import N from"net";import P from"tls";import O,{promises as T}from"fs";import L from"dgram";import B from"stream";import D from"zlib";import j from"buffer";import U from"events";import R from"https";import F from"http";import M,{fileURLToPath as W}from"url";import G from"node:os";import{spawn as V}from"child_process";import{join as H,resolve as z,dirname as q}from"node:path";import{ImageData as K,loadImage as J,createCanvas as Y}from"@napi-rs/canvas";var X;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(X=X||(X={}));const Z="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,Q="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,ee="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,te={};let ne=0,re="";const ie=e=>te[e]?te[e]:null,se=(e,t)=>{const n=ie(e);if(!n)return n;return n.blocks[t]||null},oe=(e,t,n)=>{const r=se(e,t);if(!r)return r;return r.gates[n]},ae=(e,t)=>{let n=r(4);for(;te[n];)n=r(4);const i=(s=e,JSON.parse(JSON.stringify(s)));var s;return i.logs="",i.addLog=e=>{i.logs+=`${(()=>{const e=Date.now();if(e!==ne){const t=new Date;ne=e,re=t.toJSON()}return re})()}:: ${e}\n`},i.dbInfo={...t},te[n]=i,n},ce="interrupt_port",le="main.js",de="state.json",ue="{#}",pe="$var_",ge="default";var he,fe,me,ve,ye,be,we,Se;let Ie;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(he||(he={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(fe||(fe={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(me||(me={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ve||(ve={})),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:"}(ye||(ye={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(be||(be={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(we||(we={})),function(e){e.IPC="ipc",e.WS="ws"}(Se||(Se={}));const _e=()=>{if(!Ie)throw new Error("CanvasManager not set");return Ie},$e=e=>{Ie=e},Ce=(e,t)=>_e().createCanvas(e,t),ke=e=>Z?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Ee=e=>_e().loadImage(e),xe="-",Ae=`inner${xe}`,Ne=`outer${xe}`,Pe=`${Ne}input${xe}`,Oe=`${Ne}output${xe}`,Te=`${Ae}input${xe}`,Le=`${Ae}output${xe}`,Be=e=>(new TextEncoder).encode(e),De=e=>e===ce,je=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Ue=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.top&&void 0!==e.left&&"number"==typeof e.width&&"number"==typeof e.height&&"number"==typeof e.top&&"number"==typeof e.left,Re=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Fe=e=>"number"==typeof e?fe.Number:"string"==typeof e?fe.String:"boolean"==typeof e?fe.Boolean:Array.isArray(e)?fe.Array:je(e)?fe.ImageData:e&&void 0!==e.duration&&void 0!==e.length&&void 0!==e.numberOfChannels&&void 0!==e.sampleRate&&"function"==typeof e.getChannelData&&"AudioBuffer"===e.constructor.name?fe.AudioBuffer:e&&void 0!==e.byteLength?fe.ArrayBuffer:Ue(e)?fe.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?fe.Point:(e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer)(e)?fe.BinaryFile:fe.JsonObj,Me=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Fe(n[e]);t[e]=r}return t},We=(e,t,n)=>"inner"===e?"input"===t?`${Te}${n}`:`${Le}${n}`:"input"===t?`${Pe}${n}`:`${Oe}${n}`,Ge=e=>{const t=(e||"")?.split("_");if(t.length<3)throw new Error(`Unknown child identifier format [${e}]`);const n=t[0];return{portType:t[1],widgetId:n,portName:t[2]}},Ve=async e=>{try{return new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace})}catch(t){console.warn("Failed to create ImageData from info, assuming raw image data",t);return await Ee(e.data)}};var He,ze;!function(e){e.Action="action",e.CustomInput="customInput"}(He=He||(He={})),function(e){e.input="input",e.counter="counter",e.play="play",e.elapsed="elapsed",e.ifGate="ifGate",e.skipEvent="skipEvent",e.between="between",e.map="map",e.parser="parser",e.slider="slider",e.suspend="suspend",e.display="display",e.json="json",e.arrayItem="arrayItem",e.extractImage="extractImage",e.imageConvolution="imageConvolution",e.firstEvent="firstEvent",e.pixelDraw="pixelDraw",e.randomBetween="randomBetween",e.arrayCombine="arrayCombine",e.clock="clock",e.multiplication="multiplication",e.object="object",e.widgetGroup="widgetGroup",e.script="script",e.base64ToImageData="base64ToImageData",e.jsonParse="jsonParse",e.text="text",e.imageCrop="imageCrop",e.imageResize="imageResize",e.value="value",e.imageWarp="imageWarp",e.widgetBundle="widgetBundle",e.sequence="sequence",e.variable="variable",e.hubService="hubService",e.imageFilter="imageFilter",e.recipeLoad="recipeLoad",e.note="note",e.stringify="stringify",e.templateString="templateString",e.expressionEval="expressionEval",e.rescue="rescue"}(ze=ze||(ze={}));const qe={};let Ke;const Je=async e=>{const t=qe[e],n={name:ce,type:fe.Boolean};if(t){const r={name:t.portName},i=t.data||{type:fe.Boolean,value:!0};Ke?(await Ke(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...i,timestamp:Date.now()},[n]),"timeout"===t.type&&Ye(e)):console.warn("Interrupt service has not been initialized")}},Ye=e=>{const t=qe[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete qe[e],!0)};var Xe={interruptHandler:Je,createInterrupt:(e,t,n,i,s,o,a,c)=>{if(c&&qe[c])throw new Error("The given interrupt id already exists");const l=c||r().replace(/_/g,"-");if("interval"===e&&!o.interval)throw new Error(`Invalid interval. Expected a number greater than 0, but got '${o.interval}'`);if("timeout"===e&&!o.timeout)throw new Error(`Invalid timeout. Expected a number greater than 0, but got '${o.timeout}'`);if(qe[l]={data:a,portName:s,recipePoolId:t,targetWidgetId:i,thingId:n,type:e},"interval"===e)qe[l].timerRef=setInterval((async()=>await Je(l)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);qe[l].timerRef=setTimeout((async()=>await Je(l)),o.timeout)}return l},destroyInterrupt:Ye,destroyAllInterrupts:()=>{Object.keys(qe).forEach(Ye)},setInvokeChildGateCb:e=>{Ke=e}};const Ze=(e,t,n,r,i)=>{const s=oe(e,n,r);if(!s)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=(t,i,s,o)=>Xe.createInterrupt(t,e,n,r,i,s,o),a=()=>Object.freeze({...s.state,...s.type===ze.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...s.type===ze.input&&!e.customInputs&&{customInputs:[]}};s.state=t};if(i){return{getState:a,setState:c,registerInterrupt:o,getStorageData:async t=>{const r=((e,t,n)=>{const r=ie(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=se(e,t);if(!i)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(i.storageUnits||[]).includes(n))throw new Error(`The Thing "${t}" has no access to storage unit "${n}"`);return r.storage[n]||null})(e,n,t);return r},recipePoolId:e,recipeType:t,thingRecipeId:n,widgetThingId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r}},Qe=[10001,"Invalid `sourcePort` parameter"],et=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],tt=[10110,"No storage medium has been loaded, call `loadMedium()` first"],nt=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?o.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),rt=()=>({inputName:"",dataType:fe.Anything}),it="output",st={processEvent:async(e,t)=>{const n=t.getState(),r={...rt(),...n};if(e.type===r.dataType||r.dataType===fe.Anything)return t.nextWidget(it,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...rt(),...e};return[{name:it,type:t.dataType}]},getInputNames:()=>[]},ot=Object.freeze({in:"in",reset:"reset",increment:"increment"}),at="output";var ct={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(nt(Qe));const i={currentValue:0,increment:1,...r.getState()};let s=i.increment,o=i.currentValue;const a=await r.getParentAtPort(ot.increment);if(t.name===ot.increment)return void(n.data.type===fe.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(s=e)}if(t.name===ot.reset)return r.setState({...i,currentValue:0});o+=s,r.setState({currentValue:o,increment:s});const c={type:fe.Number,value:o};return r.nextGate(at,c)},getInputNames:()=>[{name:ot.in,type:fe.Anything},{name:ot.reset,type:fe.Anything},{name:ot.increment,type:fe.Number}],getOutputNames:()=>[{name:at,type:fe.Number}]};const lt=Object.freeze({in:"in",reset:"reset"}),dt="output";var ut={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===lt.reset?r.setState({...i,updatedAt:s,elapsed:0}):(r.setState({updatedAt:s,elapsed:o}),r.nextGate(dt,{type:fe.Number,value:o}))},getInputNames:()=>[{name:lt.in,type:fe.Anything},{name:lt.reset,type:fe.Anything}],getOutputNames:()=>[{name:dt,type:fe.Number}]};const pt=Object.freeze({data:"data",evaluation:"evaluation"}),gt="then",ht="else";var ft={onParentEvent:async(e,t,n,r)=>{const i={value:5,condition:"Equal",useDataPort:!1,...r.getState()},s=n.data.value,o=!isNaN(Number(s)),a="string"==typeof s;if(!i.useDataPort&&(n.data.type===fe.Number||n.data.type===fe.String||n.data.type===fe.Boolean||n.data.type===fe.Anything&&o||n.data.type===fe.Anything&&a)){let e=!1;return("Equal"===i.condition&&(n.data.value==i.value||n.data.type===fe.Boolean&&n.data.value.toString()===i.value.toString())||"Not Equal"===i.condition&&(n.data.value!==i.value||n.data.type===fe.Boolean&&n.data.value!==i.value.toString())||"Greater"===i.condition&&n.data.type===fe.Number&&n.data.value>Number(i.value)||"Less"===i.condition&&n.data.type===fe.Number&&n.data.value<Number(i.value)||"Starts With"===i.condition&&String(n.data.value).startsWith(String(i.value))||"Ends With"===i.condition&&String(n.data.value).endsWith(String(i.value))||"Includes"===i.condition&&String(n.data.value).includes(String(i.value))||"Matches"===i.condition&&String(n.data.value).match(String(i.value)))&&(e=!0),e?r.nextGate(gt,n.data):r.nextGate(ht,n.data)}if(t.name===pt.evaluation&&(n.data.type===fe.Number||n.data.type===fe.String||n.data.type===fe.Boolean||n.data.type===fe.Anything&&(o||a))&&(i.$lastValue=n.data.value,i.$lastInputDataType=n.data.type,r.setState({...i})),t.name===pt.data){let e=!1;return("Equal"===i.condition&&(i.$lastValue==i.value||i.$lastInputDataType===fe.Boolean&&i.$lastValue?.toString()===i.value.toString())||"Not Equal"===i.condition&&(i.$lastValue!==i.value||i.$lastInputDataType===fe.Boolean&&i.$lastValue!==i.value.toString())||"Greater"===i.condition&&i.$lastInputDataType===fe.Number&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&i.$lastInputDataType===fe.Number&&Number(i.$lastValue)<Number(i.value)||"Starts With"===i.condition&&String(i.$lastValue).startsWith(String(i.value))||"Ends With"===i.condition&&String(i.$lastValue).endsWith(String(i.value))||"Includes"===i.condition&&String(i.$lastValue).includes(String(i.value))||"Matches"===i.condition&&String(i.$lastValue).match(String(i.value)))&&(e=!0),r.setState({...i,$lastValue:void 0,$lastInputDataType:void 0}),e?r.nextGate(gt,n.data):r.nextGate(ht,n.data)}},getInputNames:e=>e.useDataPort?[{name:pt.data,type:fe.Anything,triggerPort:!0},{name:pt.evaluation,type:[fe.Number,fe.String,fe.Boolean]}]:[{name:"in",type:[fe.Number,fe.String,fe.Boolean]}],getOutputNames:e=>e.$lastOutputDataType?[{name:gt,type:e.$lastOutputDataType},{name:ht,type:e.$lastOutputDataType}]:[{name:gt,type:[fe.Number,fe.String]},{name:ht,type:[fe.Number,fe.String]}]};const mt=Object.freeze({in:"in",reset:"reset"}),vt="out";var yt={onParentEvent:async(e,t,n,r)=>{const i={totalCalls:0,callsLimit:1,...r.getState()};return t.name===mt.reset?r.setState({...i,totalCalls:0}):(i.totalCalls=i.totalCalls+1,i.totalCalls>i.callsLimit?(i.totalCalls=0,r.setState(i),r.nextGate(vt,n.data)):void r.setState(i))},getInputNames:()=>[{name:mt.in,type:fe.Anything},{name:mt.reset,type:fe.Anything}],getOutputNames:()=>[{name:vt,type:fe.Anything}]};const bt=Object.freeze({in:"in"}),wt="then",St="else";var It={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:10,...r.getState()};if(n.data.type===fe.Number)return n.data.value>=i.min&&n.data.value<=i.max?r.nextGate(wt,n.data):r.nextGate(St,n.data)},getInputNames:()=>[{name:bt.in,type:fe.Number}],getOutputNames:()=>[{name:wt,type:fe.Number},{name:St,type:fe.Number}]};const _t=Object.freeze({in:"in"}),$t="out";var Ct={onParentEvent:async(e,t,n,r)=>{const i={clamp:!0,...r.getState()},s=Number(n.data.value);if(void 0!==i.fromMax&&void 0!==i.fromMin&&void 0!==i.toMax&&void 0!==i.toMin&&""!==i.fromMax&&""!==i.fromMin&&""!==i.toMax&&""!==i.toMin&&(n.data.type===fe.Number||n.data.type===fe.Anything&&!isNaN(Number(s)))){let e=((e,t,n,r,i)=>(e-t)*(i-r)/(n-t)+r)(s,Number(i.fromMin),Number(i.fromMax),Number(i.toMin),Number(i.toMax));if(isNaN(e))return;return i.clamp&&(e<Number(i.toMin)&&(e=Number(i.toMin)),e>Number(i.toMax)&&(e=Number(i.toMax))),r.nextGate($t,{type:fe.Number,value:Number(e)})}},getInputNames:()=>[{name:_t.in,type:fe.Number}],getOutputNames:()=>[{name:$t,type:fe.Number}]};const kt=Object.freeze({in:"in"}),Et="out";var xt={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let s=n.data.value;if(n.data.type===fe.Number||n.data.type===fe.Anything||n.data.type===fe.String){if((!isNaN(Number(s))||"string"==typeof s)&&!Array.isArray(s))return"Integer"===i.convertTo?s=parseInt(s):"Decimal"===i.convertTo?s=parseFloat(Number(s).toFixed(i.floatPlaces)):"String"===i.convertTo?s=String(s):"Abs"===i.convertTo?s=Math.abs(Number(s)):"Round"===i.convertTo&&(s=Math.round(Number(s))),r.nextGate(Et,{type:"String"===i.convertTo?fe.String:fe.Number,value:s})}},getInputNames:()=>[{name:kt.in,type:fe.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?fe.String:fe.Number;return[{name:Et,type:t}]}};const At=Object.freeze({in:"in"}),Nt="out";var Pt={onParentEvent:async(e,t,n,r)=>{const i={currentValue:50,min:0,max:100,...r.getState()};let s=!1;return i.currentValue<i.min&&(i.currentValue=i.min,s=!0),i.currentValue>i.max&&(i.currentValue=i.max,s=!0),s&&r.setState(i),r.nextWidget(Nt,{type:fe.Number,value:i.currentValue})},getInputNames:()=>[{name:At.in,type:fe.Anything}],getOutputNames:()=>[{name:Nt,type:fe.Number}]};const Ot=Object.freeze({in:"in",reset:"reset"}),Tt="out";var Lt={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},s={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Ot.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(Tt,n.data)):void 0},getInputNames:()=>[{name:Ot.in,type:fe.Anything},{name:Ot.reset,type:fe.Anything}],getOutputNames:()=>[{name:Tt,type:fe.Anything}]};const Bt="in";var Dt={onParentEvent:async()=>{},getInputNames:()=>[{name:Bt,type:[fe.ImageData,fe.Number]}],getOutputNames:()=>[]};const jt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),Ut=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var Rt={onParentEvent:async(e,t,n,r)=>{const i={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},s=n?.data?.value,o=Array.isArray(s);if(n.data.type===fe.JsonObj||n.data.type===fe.Rect||n.data.type===fe.Point||n.data.type===fe.BinaryFile||n.data.type===fe.Anything||o){let e=!1;for(const t in s){const n=Fe(s[t]),r=!!i.detectedProperties[t],o=i.detectedProperties[t]?.type!==n;if(!r||o){const r=n===fe.JsonObj||n===fe.Rect||n===fe.Point||n===fe.Array;i.detectedProperties[t]={type:n,...r?{shape:Me(s[t])}:void 0},e=!0}}if(o&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:fe.Number}),e&&r.setState(i),s){const e=[];for(const t of i.properties||[]){const n=Ut(s,t.label),o=t.label.includes(".");if(void 0!==n){const s=o?Fe(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:fe.Anything;e.push(r.nextGate(t.name,{type:s,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:fe.JsonObj}],getOutputNames:e=>{const t={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...e};return t.properties.map((e=>{const n=void 0!==t.detectedProperties[e.label]?t.detectedProperties[e.label]?.type:fe.Anything,r=t.detectedProperties[e.label]?.shape||void 0,i="string"==typeof e;return{name:i?e:e.name,label:i?e:e.label,type:n,jsonShape:r}}))},getDefaultState:jt};const Ft="output",Mt="noItem";var Wt={onParentEvent:async(e,t,n,r)=>{const i={index:0,...r.getState()};let s=i.index;const o=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===fe.Anything&&(c||a)||n.data.type===fe.String&&a||n.data.type===fe.Array&&c){s<0&&(s=o.length+s);const e=a?fe.String:Fe(o[s]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==o[s]?r.nextGate(Ft,{value:o[s],type:e}):r.nextGate(Mt,{value:!0,type:fe.Boolean})}},getInputNames:()=>[{name:"in",type:[fe.Array,fe.String]}],getOutputNames:e=>[{name:Ft,type:e.$$lastDetectedType??fe.Anything},{name:Mt,type:fe.Boolean}]};const Gt=Object.freeze({image:"image",rect:"rect"}),Vt="image";var Ht={onParentEvent:async(e,t,n,r)=>{const i={offset:{height:0,left:0,top:0,width:0},...r.getState()},s=await r.getParentAtPort(Gt.rect),o=[fe.Anything,fe.Rect,fe.JsonObj];if(t.name!==Gt.rect){if(s){const e=s.getValue();null!==e&&(i.rect={...e},r.setState(i))}if(!Z)return n.data.type===fe.ImageData?r.nextGate(Vt,n.data):void 0;if(i.$$canvasFrom&&i.$$canvasFrom.getContext||(i.$$canvasFrom=Ce(320,240)),i.$$canvasTo&&i.$$canvasTo.getContext||(i.$$canvasTo=Ce(320,240)),(n.data.type===fe.ImageData||n.data.type===fe.Anything&&je(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(Vt,{type:fe.ImageData,value:e})}}else Ue(n.data.value)&&o.includes(n.data.type)&&r.setState({...i,rect:n.data.value})},getInputNames:()=>[{name:Gt.image,type:fe.ImageData},{name:Gt.rect,type:[fe.Rect,fe.JsonObj]}],getOutputNames:()=>[{name:Vt,type:fe.ImageData}]};const zt=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),i=e.data,s=e.width,o=e.height,a=s,c=o,l=((e,t,n)=>{if(Z)return new ImageData(t,n);return console.warn("Node environment detected. Aborting new ImageData creation"),e})(e,a,c),d=l.data;for(let e=0;e<c;e++)for(let c=0;c<a;c++){const l=e,u=c,p=4*(e*a+c);let g=0,h=0,f=0,m=0;for(let e=0;e<n;e++)for(let a=0;a<n;a++){const c=l+e-r,d=u+a-r;if(c>=0&&c<o&&d>=0&&d<s){const r=4*(c*s+d),o=t[e*n+a];g+=i[r]*o,h+=i[r+1]*o,f+=i[r+2]*o,m+=i[r+3]*o}}d[p]=g,d[p+1]=h,d[p+2]=f,d[p+3]=m+1*(255-m)}return l},qt=[-1,0,1,-2,0,2,1,0,1],Kt=Object.freeze({image:"image"}),Jt="image";var Yt={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={matrix:[...qt],...i};if(n.data.type===fe.ImageData||n.data.type===fe.Anything&&je(n.data.value)){const e=zt(n.data.value,s.matrix);return r.nextGate(Jt,{type:fe.ImageData,value:e})}},getInputNames:()=>[{name:Kt.image,type:fe.ImageData}],getOutputNames:()=>[{name:Jt,type:fe.ImageData}]};const Xt=Object.freeze({output:"output",aborted:"aborted"}),Zt=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),Qt=e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e},n=Array(t.inputs).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:"reset",type:fe.Anything}),n};var en={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(Xt.aborted,n.data);{i.triggeredAt=s;const e=Qt(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(Xt.output,n.data),r.setState(i)}},getInputNames:Qt,getOutputNames:e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e};if(e.matchingOutputs){const e=Array(t.inputs).fill(0).map(((e,t)=>({name:`output${t+1}`,type:fe.Anything})));return e.push({name:Xt.aborted,type:fe.Anything}),e}return[{name:Xt.output,type:fe.Anything},{name:Xt.aborted,type:fe.Anything}]},getDefaultState:Zt};const tn=(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)}},nn=(e,t,n,r,i,s,o)=>{e.fillStyle=i,e.fillRect(t,n,r,r),tn(e,t,n,i,s,o)},rn=(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;tn(e,t.left-o,t.top-o,r,i,s)},sn=Object.freeze({image:"image",pixels:"pixels"}),on="image";var an={onParentEvent:async(e,t,n,r)=>{const i={fontSize:12,color:"#00ff00",size:2,...r.getState()},s=n.data.type===fe.ImageData||n.data.type===fe.Anything&&je(n.data.value);if(t.name===sn.pixels){const e=(e=>Re(e)||Ue(e)||Array.isArray(e)&&e[0]&&(Re(e[0])||Ue(e[0])))(n.data.value);if(!e)return;i.$$pixels=n.data.value}if(t.name===sn.image&&s){const e=n.data.value;i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(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=ke(r);if(e){r.width!==t.width&&(r.width=t.width),r.height!==t.height&&(r.height=t.height),e.putImageData(t,0,0);const c=Array.isArray(n)?n:[n];for(let t=0;t<c.length;t++){const n=c[t],r=o?n[o]:"";Ue(n)?rn(e,n,i,s,r,a):Re(n)&&nn(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(on,{type:fe.ImageData,value:e})}r.setState(i)},getInputNames:()=>[{name:sn.image,type:fe.ImageData},{name:sn.pixels,type:[fe.Rect,fe.Point,fe.Array,fe.JsonObj]}],getOutputNames:()=>[{name:on,type:fe.ImageData}]};const cn=Object.freeze({in:"in"}),ln="output",dn=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var un={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:100,...r.getState()},s=!Number.isInteger(i.min),o=!Number.isInteger(i.max),a=s||o;let c=(l=i.min,d=i.max,Math.random()*(d-l)+l);var l,d;if(a){let e=0;if(s&&(e=dn(i.min)),o){const t=dn(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(ln,{type:fe.Number,value:c})},getInputNames:()=>[{name:cn.in,type:fe.Anything}],getOutputNames:()=>[{name:ln,type:fe.Number}]};const pn=Object.freeze({output:"output",totalItems:"totalItems"}),gn=Object.freeze({trigger:"trigger",clear:"clear"}),hn=()=>({$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),fn=async(e,t)=>t.nextGate(pn.totalItems,{type:fe.Number,value:e});var mn={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===gn.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),fn(i.$$list.length,r);const s=t.name===gn.trigger;if(!s)if(Array.isArray(n.data.value))n.data.type!==fe.Array&&n.data.type!==fe.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await fn(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===fe.JsonObj?i.$$outputShape={...i.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:i.$$outputShape={...i.$$outputShape,[t]:n.data.type},i.$$list.push(n.data.value),r.setState({...i}),await fn(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 fn(e,r),r.nextGate(pn.output,{type:fe.Array,value:t})}},getInputNames:e=>{const t={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:gn.clear,type:fe.Anything},{name:gn.trigger,type:fe.Anything}),n},getOutputNames:e=>[{name:pn.output,type:fe.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:pn.totalItems,label:"Total Items",type:fe.Number}],getDefaultState:hn};const vn=Object.freeze({start:"start",stop:"stop"}),yn="output",bn="clock_interrupt";var wn={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(De(e?.name||"")&&t.name===bn)return r.nextGate(yn,{type:fe.Boolean,value:!0});if(t.name===vn.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!==vn.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt("interval",bn,{interval:i.interval}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:vn.start,type:fe.Anything},{name:vn.stop,type:fe.Anything}],getOutputNames:()=>[{name:yn,type:fe.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",bn,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const Sn=Object.freeze({in:"in"}),In="output",_n=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var $n={onParentEvent:async(e,t,n,r)=>{const i={userProperties:[],factor:2,decimalPoints:2,...r.getState()},s=n.data.type;let o=n.data.value,a=!1;return e?.jsonShape&&(i.detectedInputJson={...i.detectedInputJson,...e?.jsonShape},a=!0),i.detectedInputType||(i.detectedInputType=s,a=!0),n.data.type===fe.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>_n(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]=_n(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===fe.Number&&(o=_n(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(In,{type:s,value:o})},getInputNames:()=>[{name:Sn.in,type:[fe.Array,fe.Number]}],getOutputNames:e=>[{name:In,type:e.detectedInputType||fe.Number,jsonShape:e.detectedInputJson}]};const Cn=Object.freeze({output:"output"}),kn=Object.freeze({trigger:"trigger"}),En=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:fe.Number,value:10},{name:"y",label:"y",type:fe.Number,value:20}]}),xn=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},An=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===fe.Number?r=Number(r):i===fe.String&&(r=String(r)),t[e.properties[n].label]=r}return t};var Nn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s=structuredClone(i),o={...En(),...s};if(t.name===kn.trigger){const e=An(o);return r.nextGate(Cn.output,{type:fe.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===fe.Anything){e=Fe(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=An(o);return r.nextGate(Cn.output,{type:fe.JsonObj,value:e})}}},getInputNames:e=>{const t={...En(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:kn.trigger,label:kn.trigger,type:fe.Anything}),n},getOutputNames:e=>[{name:Cn.output,label:Cn.output,type:fe.JsonObj,jsonShape:xn(e)}],getDefaultState:En};const Pn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(Pe)){const n=t(e,Pe);return We("inner","input",n)}if(e.startsWith(Le)){const n=t(e,Le);return We("outer","output",n)}return null},On=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[fe.Anything],index:0}],outputs:[{name:"output",type:[fe.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Tn=e=>{const t={...On(),...e},n=t.inputs.map(((e,t)=>({name:We("outer","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t}))),r=t.outputs.map(((e,t)=>({name:We("inner","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:n.length+t})));return[...n,...r]};var Ln={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...On(),...i},o=Tn(s,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const i=o[e];if(t.name===i.name&&(i.type.includes(fe.Anything)||i.type.includes(n.data.type))){const e=await Pn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Tn,getOutputNames:e=>{const t={...On(),...e},n=t.outputs.map(((e,t)=>({name:We("outer","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t})));return[...t.inputs.map(((e,t)=>({name:We("inner","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:t+n.length}))),...n]},getDefaultState:On};const Bn=(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 Dn={getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,i=n[t+1]||0,s=n[t+2]||0;return{avr:(r+i+s)/3,r:r,g:i,b:s}},getBoundingBox:(e,t,n)=>{const r=e.width,i=e.height,s=new Set,o=Number(n.threshold||0),a=isNaN(o)?10:o,c=(n,o)=>{const c=[[n,o]];let l=n,d=n,u=o,p=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,g]=n;o<0||g<0||o>=r||g>=i||s.has(`${o},${g}`)||!Bn(o,g,e,t,a||0)||(s.add(`${o},${g}`),l=Math.min(l,o),d=Math.max(d,o),u=Math.min(u,g),p=Math.max(p,g),c.push([o+1,g],[o-1,g],[o,g+1],[o,g-1]))}return{minX:l,maxX:d,minY:u,maxY:p}},l=[];for(let o=0;o<i;o+=4)for(let i=0;i<r;i+=4)if(!s.has(`${i},${o}`)&&Bn(i,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:s}=c(i,o),a=t-e,d=s-r;if(a>=(n.minWidth||1)&&d>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:d}),n.maxBoxes&&l.length>=n.maxBoxes)return l}return l},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,i="object"==typeof n,s=i?n.r:n,o=i?n.g:n,a=i?n.b:n;r[t]=s,r[t+1]=o,r[t+2]=a,r[t+3]=255}};const jn=e=>Fe(e);var Un,Rn,Fn,Mn,Wn,Gn,Vn,Hn,zn,qn;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Un||(Un={})),function(e){e.Bundle="bundle",e.Group="group"}(Rn||(Rn={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Fn||(Fn={})),function(e){e.Cloud="cloud",e.Web="web"}(Mn||(Mn={})),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"}(Wn||(Wn={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Gn||(Gn={})),(Vn||(Vn={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Hn||(Hn={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(zn||(zn={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(qn||(qn={}));let Kn=null;var Jn=()=>{if(!Kn)throw new Error("Required function is not set");return Kn};class Yn extends Error{targetWidgetId;targetPortName;sourcePortName;sourceWidgetId;targetWidgetType;sourceWidgetType;constructor(e,t){super(e),this.name="ChildWidgetError",t.stack&&(this.stack=t.stack),this.targetWidgetId=t.targetWidgetId,this.targetPortName=t.targetPortName,this.sourcePortName=t.sourcePortName,this.sourceWidgetId=t.sourceWidgetId,this.targetWidgetType=t.targetWidgetType,this.sourceWidgetType=t.sourceWidgetType}}class Xn extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const Zn=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===Un.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar console = this.console;\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\n\t\t\tvar Kemu = {\n\t\t\t\tservices: {\n\t\t\t\t\thttp: { ...this.httpWebService },\n\t\t\t\t\tdynamoDb: { ...this.dynamoService },\n\t\t\t\t\tgoogleSheets: {\n\t\t\t\t\t\t...this.googleSheetsService,\n\t\t\t\t\t}\n\t\t\t\t},\n\n\t\t\t\timage: this.imageHelpers,\n\t\t\t\tvariable: this.variablesManager,\n\n\t\t\t\thelpers: {\n\t\t\t\t\tdecodeDataType: this.decodeDataType,\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\tjsonp: this.jsonp,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tvar sendToPort;\n\n\t\t\t// --- User Methods Start ---\n\t\t\t${e||""};\n\t\t\t// --- User Methods End ---\n\t\t\t\n\t\t\t// Processes the user code asynchronously.\n\t\t\tconst asyncProcessEvent = async (targetPort, sourcePort, event) => {\n\t\t\t\tconst userProcessEvent = typeof processEvent === 'undefined' ? undefined : processEvent;\n\t\t\t\tif(userProcessEvent) {\n\t\t\t\t\ttry{\n\t\t\t\t\t\treturn await userProcessEvent(targetPort, sourcePort, event, sendToPort);\n\t\t\t\t\t}catch(e){\n\t\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked the very first time the recipe is initialized */\n\t\t\tconst asyncRecipeInit = async (context, logger) => {\n\t\t\t\ttry {\n\t\t\t\t\t${t===Un.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`,Qn=(e,t,n,r)=>{const o=Zn(e,n),a={...t,document:{},__errorTracer:e=>{if(e instanceof Yn)throw e;throw new Xn(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:Dn,...n===Un.Cloud?{require:Jn(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:i,CryptoJS:s,decodeDataType:jn,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(Z)return"browser";if(ee)return"node";if(Q)return"worker";throw new Error("Unsupported environment")})()?(e=>e.replace(/[//]{2}[ ]*@kemu-cloud[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-cloud[ \t]*\}/gim,""))(o):(e=>e.replace(/[//]{2}[ ]*@kemu-browser[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-browser[ \t]*\}/gim,""))(o),t=new Function(e);return{compiledModule:t()(a)}}catch(e){return{error:{name:"CompileError",message:e.message,stack:e.stack}}}},er="main",tr="My Script",nr="This is a test script.",rr=`\n/**\n * Name: ${tr}\n * Description: ${nr}\n */\n\nconst getWidgetInputs = () => [\n\t{ name: 'Input 1', type: DataType.Number }\n];\n\nconst getWidgetOutputs = () => [\n\t{ name: 'Output 1', type: DataType.Number }\n]\n\nlet counter = 0;\n\nconst processEvent = async (targetPort, sourceWidget, event) => {\n\tif(targetPort.name === 'Input 1'){\n\t\treturn sendToPort('Output 1', {\n\t\t\ttype: DataType.Number,\n\t\t\tvalue: counter++,\n\t\t});\n\t}\n}\n`.trim(),ir=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},metadata:{name:tr,description:nr},pages:{[er]:{code:rr,language:"javascript",name:"My First Script"}}}),sr=(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 Zn(t,e).split(t)[0].split("\n").length+2})(t),n.column=i.column)}return e.message&&(n.message=e.message),n},or=(e,t)=>{const n={...{...ir(),...t.getState()},$$error:e||void 0};e&&console.error(e.message),t.setState(n)};var ar,cr;!function(e){e.ServiceCreationLog="service-creation-log"}(ar=ar||(ar={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(cr=cr||(cr={}));const lr=new a,dr=(e,t,n)=>{const r=se(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},ur=(e,t,n)=>`${t}:${n}:${e}`,pr=e=>`${e}:new-var`,gr=e=>`value-change:${e}`,hr=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=pr(n);return lr.emit(e,c)}{const t=ur(e,n,r);return s.includes("value")&&(await lr.emit(gr(e),c),await lr.emit(gr("*"),c)),lr.emit(t,c)}},fr=(e,t,n,r)=>{const i=dr(e,t,r);i.variablesListener={...i.variablesListener,[n]:0},vr(e,t)},mr=(e,t,n,r)=>{const i=dr(e,t,r),s={...i.variablesListener};void 0!==i.variablesListener?.[n]&&(delete s[n],i.variablesListener=s)},vr=async(e,t)=>{const n=se(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 hr(s,e,t,i,void 0,["removed"],null))}0===Object.keys(r[s]).length&&delete r[s]}n.variables=r},yr=(e,t,n)=>{for(const r in t){const i=t[r];if(i.createdByWidgetId===e.id)return i;if(e.type===ze.variable&&i.ownerType===ze.variable)return i;if(e.type===ze.script){const t=i.createdByWidgetId===e.groupId,r=n[i.createdByWidgetId];if(!r)continue;const s=r.groupId===e.groupId;if(t||r.type===ze.variable&&s)return i}}return null};var br=async(e,t,n,r,i,s)=>{const o=se(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 d=Object.values(c);let u=!1,p=!1;const g=async i=>hr(r,e,t,i.createdByWidgetId,n,["value"],i);if(l.type===ze.variable){u=!0;for(const e of d)e.ownerType===ze.variable&&e.type===i.type&&(e.value=i.value,p=!0,await g(e))}if(l.type===ze.script){u=!0;for(const e of d){const t=e.createdByWidgetId===l.groupId,n=o.gates[e.createdByWidgetId],r=n?.type===ze.variable,s=n?.groupId===l.groupId;(t||r&&s)&&e.type===i.type&&(e.value=i.value,p=!0,await g(e))}}if(!u){u=!0;for(const e of d){e.createdByWidgetId===n&&e.type===i.type&&(e.value=i.value,p=!0,await g(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 Qs({widgetId:o.id,thingId:t,recipeId:e,targetPortName:`${pe}${r}`,data:i})}}},wr=(e,t,n,r)=>{const i=se(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=yr(o,s,i.gates);return a?a.value:null},Sr=fr,Ir=mr,_r=(e,t)=>lr.on(gr(e),(e=>{if(e.varDefinition)return t({type:e.varDefinition.type,value:e.varDefinition.value,varName:e.variableName})}));const $r="setTimeout",Cr="variableChanged",kr=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e;if(!oe(t,n,r))throw new Error(`Widget "${r}" not found in recipe "${t}"`);return{get:(e,i)=>{const s=wr(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 br(t,n,r,e,{type:Fe(i),value:i})},onValueChange:(i,s)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");Sr(t,n,i,r);const o={...ir(),...e.getState()};o.$$eventListeners[i]={handler:s,abort:async()=>{Ir(t,n,i,r)},name:Cr},e.setState(o)}}},Er="__command-compile__";let xr;const Ar=()=>{console.log("Method not implemented")},Nr=(e,t,n)=>{const i=(e,...n)=>{const r={...ir(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},s={};return Object.keys(fe).forEach((e=>{s[e]=fe[e]})),{dataTypesEnum:s,notify:{success:e=>{t.getState()?.$$managedUI?.notify?.success(e)},error:e=>{t.getState()?.$$managedUI?.notify?.error(e)},info:e=>{t.getState()?.$$managedUI?.notify?.info(e)}},variablesManager:e.variablesManager?kr({recipePoolId:n.recipePoolId,scriptWidgetId:n.widgetId,thingId:n.thingId,getState:t.getState,setState:t.setState}):{get:Ar,set:async()=>Ar(),onValueChange:Ar},setTimeout:(n,i,s)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=r(),o={...ir(),...t.getState()};o.$$eventListeners[e]={handler:n,rejectHandler:s,name:$r},t.setState(o),t.registerInterrupt("timeout",e,{timeout:i},void 0,e)}},addEventListener:(e,n)=>{if(t.setState){const s=r(),o={...ir(),...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={...ir(),...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.`)}}},Pr=(e,t,n,r)=>{const i={...ir(),...n.getState()},s=i.pages[er].$$compiledCode;if(s)return{compiledModule:s};{const s=Nr(e,n,t);return Qn(i.pages[er].code,s,n.recipeType,r)}},Or=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),Tr=async(e,t,n)=>{let r={...ir(),...e.getState()};if(void 0!==n){r.pages[er]?.$$compiledCode?.onTerminate&&await(r.pages[er].$$compiledCode?.onTerminate());let t=await(async(e,t)=>{const n={...e};for(const r in e)if(e[r].name===$r){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})(r.$$eventListeners,e);t=await(async e=>{const t={...e};for(const n in e)if(e[n].name===Cr){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.pages[er].$$compiledCode=void 0,r.pages[er].code=n,e.setState({...r})}const i=!r.pages[er].$$compiledCode,{compiledModule:s,error:o}=Pr({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=sr(o,e.recipeType);return or(t,e),null}if(s){const n=(()=>{const e=(e,...t)=>{if(xr)try{return xr[e](...t)}catch(e){return void console.log("Error in custom logger: ",e)}console[e](...t)};return{log:(...t)=>{e("log",...t)},error:(...t)=>{e("error",...t)},warn:(...t)=>{e("warn",...t)},info:(...t)=>{e("info",...t)}}})();let o;r={...e.getState()},r.pages[er].$$compiledCode=s;const a=Br(r.pages[er].code);if(a?.name===r.metadata?.name&&a?.description===r.metadata?.description||(r.metadata=a||void 0),e.nextGate&&s.setSendToPortFun(e.nextGate),t)try{await s.recipeInit({setState:e.setState,getState:e.getState},n)}catch(t){o=sr(t,e.recipeType)}if(e.nextGate&&i)try{await s.main(e.nextGate,n)}catch(t){o=sr(t,e.recipeType)}r.$$lastInputs=s.getWidgetInputs?s.getWidgetInputs():[],r.$$lastOutputs=s.getWidgetOutputs?s.getWidgetOutputs():[],e.setState(r),or(o,e)}};var Lr={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...ir(),...i};if(!s.pages[er])return console.warn("Missing default page");if(De(e?.name||""))return s.$$eventListeners[t.name]?(await s.$$eventListeners[t.name].handler(),s.$$eventListeners[t.name].name===$r&&delete s.$$eventListeners[t.name],void r.setState({...s})):void console.log(`Unknown interrupt id [${t.name}] `);if(t.name.startsWith(pe)){const e=t.name.replace(pe,""),r=n.data.value,i=s.$$eventListeners[e];return void(i?.handler&&await i.handler(r))}const o=t.name===Er;await Tr(r,!1,o?n.data.value:void 0);const a=s.pages[er].$$compiledCode;if(e&&e.name!==Er&&a)try{await a.asyncProcessEvent(t,e,n)}catch(e){if("UserCodeError"===e.name){const t=sr(e,r.recipeType);throw or(t,r),t}throw e}},getInputNames:(e,t)=>{const n={...ir(),...e},{compiledModule:r}=Pr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return Or(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...ir(),...e},{compiledModule:r}=Pr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return Or(e)}return e.$$lastOutputs||[]},getDefaultState:ir,initialize:async e=>{const t=e.getState(),n={...ir(),...t};n.pages[er].code&&await Tr({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[er].code)}};const Br=e=>{const t=e.trimStart().match(/^(?:\/\*\*(?:[^*]|\*(?!\/))*\*\/|\/\*(?:[^*]|\*(?!\/))*\*\/)/);if(!t)return null;const n=t[0].replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map((e=>e.replace(/^\s*\*?\s?/,"").trim())).join("\n"),r=n.match(/Name\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),i=n.match(/Description\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),s={};return r&&r[1]&&(s.name=r[1].trim()),i&&i[1]&&(s.description=i[1].trim()),Object.keys(s).length>0?s:null},Dr=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const i=await jr(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)},jr=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),Ur=Object.freeze({image:"image"}),Rr=Object.freeze({base64:"base64"}),Fr=()=>({});var Mr={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===Rr.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==fe.String&&n.data.type!==fe.Anything)return;const e=n.data.value;Z&&(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240)));try{const t=await Dr(e,i.$$memCanvas,i.resize?.width,i.resize?.height);return r.setState(i),r.nextGate(Ur.image,{type:fe.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:Rr.base64,type:fe.String}],getOutputNames:()=>[{name:Ur.image,type:fe.ImageData}],getDefaultState:Fr};const Wr=Object.freeze({object:"object",error:"error"}),Gr=Object.freeze({string:"string"}),Vr=()=>({outputIsArray:!1});var Hr={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===fe.String||n.data.type===fe.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!i.outputIsArray?r.setState({...i,outputIsArray:!0}):!t&&i.outputIsArray&&r.setState({...i,outputIsArray:!1}),r.nextGate("object",{type:t?fe.Array:fe.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:fe.Boolean,value:!0})}},getInputNames:()=>[{name:Gr.string,type:fe.String}],getOutputNames:e=>[{name:Wr.object,type:[fe.JsonObj,fe.Array],label:e.outputIsArray?"array":Wr.object},{name:Wr.error,type:fe.Boolean}],getDefaultState:Vr};const zr=Object.freeze({string:"string",length:"length"}),qr=Object.freeze({trigger:"trigger",setText:"setText"}),Kr=()=>({text:"",dispatchOnSet:!1});var Jr={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===qr.setText){if(!((n.data.type===fe.String||n.data.type===fe.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(i.text=n.data.value,r.setState(i)),!i.dispatchOnSet)return}const s=r.nextGate(zr.length,{type:fe.Number,value:i.text.length}),o=r.nextGate(zr.string,{type:fe.String,value:i.text});await Promise.all([s,o])},getInputNames:e=>{const t=[{name:qr.setText,type:fe.String}];return e.dispatchOnSet||t.push({name:qr.trigger,type:fe.Anything}),t},getOutputNames:()=>[{name:zr.string,type:fe.String},{name:zr.length,type:fe.Number}],getDefaultState:Kr};const Yr=Object.freeze({image:"image"}),Xr=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),Zr=()=>({showInputPorts:!1});var Qr={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Xr.x&&(i.cropX=n.data.value),t.name===Xr.y&&(i.cropY=n.data.value),t.name===Xr.width&&(i.cropWidth=n.data.value),t.name===Xr.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===Xr.image){if(n.data.type!==fe.ImageData&&n.data.type!==fe.Anything)return;if(!je(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$memCanvasContext=ke(i.$$memCanvas),r.setState(i)),!i.$$memCanvas||!i.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return i.$$memCanvas.width=e.width,i.$$memCanvas.height=e.height,(i.cropX||i.cropY||i.cropWidth||i.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const i=Math.max(r.x||0,0),s=Math.max(r.y||0,0),o=e.width,a=e.height,c=Math.min(Math.ceil(r.width||o),o),l=Math.min(Math.ceil(r.height||a),a);return t.width=e.width,t.height=e.height,n.putImageData(e,0,0),n.drawImage(t,i,s,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,i.$$memCanvas,i.$$memCanvasContext,{x:i.cropX,y:i.cropY,width:i.cropWidth,height:i.cropHeight})),r.nextGate(Yr.image,{type:fe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Xr.image,type:[fe.ImageData]}];return e.showInputPorts&&(t.push({name:Xr.x,type:fe.Number}),t.push({name:Xr.y,type:fe.Number}),t.push({name:Xr.width,type:fe.Number}),t.push({name:Xr.height,type:fe.Number})),t},getOutputNames:()=>[{name:Yr.image,type:fe.ImageData}],getDefaultState:Zr};const ei=Object.freeze({image:"image"}),ti=Object.freeze({image:"image",width:"width",height:"height"}),ni=()=>({showInputPorts:!1});var ri={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===ti.width&&(i.width=n.data.value),t.name===ti.height&&(i.height=n.data.value),void r.setState(i);if(t.name===ti.image){if(n.data.type!==fe.ImageData&&n.data.type!==fe.Anything)return;if(!je(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$tempCanvas=Ce(320,240),r.setState(i)),!i.$$memCanvas||!i.$$tempCanvas)return;let t=e;return(i.width||i.height)&&(t=((e,t,n,r,i)=>{if(!r&&!i)return e;r&&!i?i=r*(e.height/e.width):!r&&i&&(r=i*(e.width/e.height));const s=Math.max(1,r||e.width),o=Math.max(1,i||e.height);n.width===e.width&&n.height===e.height||(n.width=e.width,n.height=e.height),t.width=s,t.height=o;const a=ke(t),c=ke(n);if(!a||!c)throw new Error("Failed to get canvas context");return c.putImageData(e,0,0),a.drawImage(n,0,0,e.width,e.height,0,0,s,o),a.getImageData(0,0,s,o)})(e,i.$$memCanvas,i.$$tempCanvas,i.width,i.height)),r.nextGate(ei.image,{type:fe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:ti.image,type:fe.ImageData}];return e.showInputPorts&&(t.push({name:ti.width,type:fe.Number}),t.push({name:ti.height,type:fe.Number})),t},getOutputNames:()=>[{name:ei.image,type:fe.ImageData}],getDefaultState:ni};const ii=Object.freeze({value:"value"}),si=Object.freeze({trigger:"trigger",setValue:"setValue"}),oi=()=>({value:0,dispatchOnSet:!1});var ai={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===si.setValue){const e=n.data.type===fe.Number||n.data.type===fe.Anything||n.data.type===fe.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(i.value=Number(n.data.value),r.setState(i),!i.dispatchOnSet)return}return r.nextGate(ii.value,{type:fe.Number,value:i.value})},getInputNames:e=>{const t=[{name:si.setValue,type:fe.Number}];return e.dispatchOnSet||t.push({name:si.trigger,type:fe.Anything}),t},getOutputNames:()=>[{name:ii.value,type:fe.Number}],getDefaultState:oi};const ci=Object.freeze({image:"image"}),li=Object.freeze({image:"image"}),di=()=>({anchors:[],vertices:[],matrix:[]}),ui={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},s=window,o=n.data.type===fe.ImageData;if(s.Speedy&&o){const e=s.Speedy,t=n.data.value;let o,d,u,p=i.$$private?.canvas,g=i.$$private?.context,h={...i};const f=4===i.anchors.length;if(i.$$private?.pipeline)o=i.$$private?.pipeline,d=i.$$private?.source;else{o=e.Pipeline(),d=e.Image.Source();const n=e.Image.Sink();u=e.Transform.PerspectiveWarp(),p?p.width===t.width&&p.height===t.height||(p.width=t.width,p.height=t.height,g=p.getContext("2d")):(c=t.width,l=t.height,p=Ce(c,l),g=p.getContext("2d")),d.output().connectTo(u.input()),u.output().connectTo(n.input()),o.init(d,n,u);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===i.anchors.length){const t=e.Matrix(2,4,[(a=i.anchors)[0].x,a[0].y,a[1].x,a[1].y,a[2].x,a[2].y,a[3].x,a[3].y]),n=e.Matrix(2,4,i.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),s=e.Matrix.Zeros(3,3);await e.Matrix.perspective(s,t,n);const o=s.read();r=e.Matrix(3,3,o)}u.transform=r,h={...h,$$private:{...h.$$private,canvas:p,context:g,perspective:u,pipeline:o,source:d}}}let m=t;if(f){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,i=e.$$private?.pipeline;if(n.Speedy&&r&&i){const e=n.Speedy,s=await createImageBitmap(t),o=await e.load(s);return r.media=o,(await i.run()).image.source}return null})(h,m);e&&(p&&g&&(m=((e,t,n)=>(t.width=e.width,t.height=e.height,n.drawImage(e,0,0),n.getImageData(0,0,e.width,e.height)))(e,p,g)),h.$$private&&r.setState({...h,$$private:{...h.$$private,lastInputImage:t}}))}else h.$$private&&r.setState({...h,$$private:{...h.$$private,lastInputImage:t}});return r.nextGate(ci.image,{type:fe.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:li.image,type:fe.ImageData}],getOutputNames:()=>[{name:ci.image,type:fe.ImageData}],getDefaultState:di,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},pi=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[fe.Anything],name:"input"}],outputs:[{dataType:[fe.Anything],name:"output"}]});let gi;const hi=()=>{if(!gi)throw new Error(nt(tt));return gi};const fi=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},mi={};var vi=e=>mi[e]||null;const yi=async(e,t,n)=>{try{const r=hi(),i=n?r.loadBlobAsString:r.loadBlob;return await i(e,t)}catch(e){return null}},bi=async e=>{const t=le;try{const n=await yi(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},wi=async e=>{const t=de;try{const n=await yi(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}},Si=(e,t)=>`${e.replace(ue,"")}_${t}`,Ii=(e,t)=>`widget/${e.replace(ue,"")}/v/${t}`,_i=async(e,t)=>{const n=hi(),[r]=await Promise.all([fi(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},$i=(e,t)=>{const n=Si(e,t),r=vi(n);return r?{...r}:null},Ci=(e,t,n)=>{const r=`${`widget/${e.replace(ue,"")}/tmp`}/${t}`;if(n){return hi().getCacheLocation(r)}return r};var ki=$i,Ei=async(e,t,n)=>{const r=Ci(t,n);await _i(e,r);const i=bi(r),s=wi(r),o=hi(),a=o.getCacheLocation(r),[c,l]=await Promise.all([i,s]);if(!c)return null;let d=l;if(!l){const e=pi(),t=JSON.stringify(e);await o.saveBlob(r,de,Be(t)),d=e}return{cachePath:a,processor:c,storedState:Object.freeze(d)}},xi=(e,t,n)=>{if(n.isTempStorage)return Ci(e,t,n.fullStorageRoot);const r=hi(),i=Ii(e,t);return n.fullStorageRoot?r.getCacheLocation(i):i};const Ai=()=>pi();var Ni={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={...Ai(),...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={...Ai(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:Ai,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=ki(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 Ei(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=xi(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 Pi=Object.freeze({event:"event"}),Oi="1",Ti="2",Li="3";var Bi={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate(Oi,n.data),await r.nextGate(Ti,n.data),await r.nextGate(Li,n.data)},getInputNames:()=>[{name:Pi.event,type:fe.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??fe.Anything};return[{name:Oi,...t},{name:Ti,...t},{name:Li,...t}]}};const Di=Object.freeze({set:"set",trigger:"trigger"}),ji="value";var Ui={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={name:"myVar",type:fe.String,reactive:!0,defaultValue:"",...i};if(t.name.startsWith(pe)){if(!s.reactive)return;if(n.data.type!==s.type)return;return r.nextWidget(ji,n.data)}if(t.name!==Di.set){if(t.name===Di.trigger){const e=wr(r.recipePoolId,r.thingRecipeId,s.name,{ownerWidgetId:r.id}),t=e||s.defaultValue;await r.nextWidget(ji,{type:s.type,value:t})}}else await br(r.recipePoolId,r.thingRecipeId,r.id,s.name,n.data,{skipCallerNotification:!s.reactive})},getInputNames:e=>{const t={...e};return[{name:Di.set,type:t.type||fe.Anything},{name:Di.trigger,type:fe.Anything}]},getOutputNames:e=>{const t={...e};return[{name:ji,type:t.type||fe.Anything}]}};let Ri;var Fi=e=>{Ri=e},Mi=()=>{if(!Ri)throw new Error("Hub Connector not set");return Ri};const Wi=async(e,t=!1)=>{const n=Mi();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 Gi={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const s=Mi();let o=i.$$$serviceId;if(!o){const e=s.getCachedServices().available.find((e=>e.name===i.service?.name&&e.version===i.service?.version));if(!e)return;o=e.sessionId,i.$$$serviceId=o,r.setState(i)}const a=i.service?.variants?.find((e=>e.id===i.variantId)),c=a?i.dynamicInputs[a.id]||a?.inputs||[]:i.service?.inputs||[];if(!c?.length)return;if(!a&&i.service?.ignoreParentEvents)return;const l=i.service?.processingTimeoutSec,d=i.service?.name&&r.eventContext?.[i.service?.name];return s.onParentEvent({recipeId:r.recipePoolId,data:n.data,targetServiceSessionId:o,currentState:i.customState,targetVariantId:i.variantId,target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:l?1e3*l:0,async:i.service?.asyncParentEvents},eventContext:d})},getInputNames:async e=>{const t=e.variantId;if(t&&e.dynamicInputs?.[t])return[...e.dynamicInputs[t]||[]];if(!t)return e.service?.inputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.inputs||[]}return[]},getOutputNames:async e=>{const t=e.variantId;if(t&&e.dynamicOutputs?.[t])return[...e.dynamicOutputs[t]||[]];if(!t)return e.service?.outputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.outputs||[]}return[]},initialize:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=Mi(),r=await Wi(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=Mi(),r=await Wi(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const Vi=Object.freeze({Image:"image"}),Hi=Object.freeze({Image:"image"}),zi=()=>({filters:[{name:"grayscale",value:"0.5",id:"d-1"}]});const qi="loaded";var Ki={onParentEvent:async(e,t,n,r)=>{try{const e=((e,t)=>{switch(t){case fe.Number:case fe.Boolean:case fe.String:return String(e);case fe.Array:case fe.JsonObj:case fe.Rect:case fe.Point:return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));case fe.ArrayBuffer:if(e instanceof ArrayBuffer){if(ee)return Buffer.from(e).toString("base64");{const t=new Uint8Array(e),n=t.length,r=new Array(n);for(let e=0;e<n;e++)r[e]=String.fromCharCode(t[e]);return btoa(r.join(""))}}throw new Error("Type is ArrayBuffer but value is not an ArrayBuffer");case fe.ImageData:{if(!je(e))throw new Error("Expected ImageData");const t=e,n=Ce(t.width,t.height),r=ke(n);if(!r)throw new Error("Failed to get canvas context");r.putImageData(t,0,0);const i=n.toDataURL("image/png");if(!i)throw new Error("Failed to convert canvas to data URL");return i.split(",")[1]}default:return String(e)}})(n.data.value,n.data.type);return r.nextWidget("text",{type:fe.String,value:e})}catch(e){return r.nextWidget("error",{type:fe.String,value:e instanceof Error?e.message:"Failed to stringify object"})}},getInputNames:()=>[{name:"object",type:[fe.Number,fe.String,fe.ArrayBuffer,fe.Array,fe.Boolean,fe.JsonObj,fe.Rect,fe.Point,fe.ImageData]}],getOutputNames:()=>[{name:"text",type:fe.String},{name:"error",type:fe.String}],getDefaultState:()=>({})};const Ji=(e,t)=>{const n=(e=>{const t=new Date;return{input:"object"==typeof e&&null!==e?e:{value:e},date:{year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hours:t.getHours(),minutes:t.getMinutes(),seconds:t.getSeconds(),milliseconds:t.getMilliseconds(),time:t.getTime(),dayOfWeek:t.getDay(),dayName:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()],shortDayName:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getDay()],date:t.getDate(),fullYear:t.getFullYear(),timezoneOffset:t.getTimezoneOffset(),UTCDate:t.getUTCDate(),UTCDay:t.getUTCDay(),UTCFullYear:t.getUTCFullYear(),UTCHours:t.getUTCHours(),UTCMilliseconds:t.getUTCMilliseconds(),UTCMonth:t.getUTCMonth()+1,UTCMinutes:t.getUTCMinutes(),UTCSeconds:t.getUTCSeconds(),isoString:t.toISOString(),localeString:t.toLocaleString()}}})(t);return l.render(e,n)},Yi=()=>({text:"",format:"Text"});const Xi=()=>({expression:""});const Zi={input:st,counter:ct,elapsed:ut,ifGate:ft,skipEvent:yt,between:It,map:Ct,parser:xt,slider:Pt,suspend:Lt,display:Dt,json:Rt,arrayItem:Wt,extractImage:Ht,imageConvolution:Yt,firstEvent:en,pixelDraw:an,randomBetween:un,arrayCombine:mn,clock:wn,multiplication:$n,object:Nn,widgetGroup:Ln,script:Lr,base64ToImageData:Mr,jsonParse:Hr,text:Jr,imageCrop:Qr,imageResize:ri,value:ai,imageWarp:ui,widgetBundle:Ni,sequence:Bi,variable:Ui,hubService:Gi,imageFilter:{onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:"0.5",id:"d-1"}],...r.getState()};if(t.name===Vi.Image&&n.data.type===fe.ImageData){if(!je(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas?.getContext||(i.$$memCanvas=Ce(e.width,e.height)),i.$$context?.drawImage||(i.$$context=i.$$memCanvas.getContext("2d")),i.$$memCanvas.width!==e.width&&(i.$$memCanvas.width=e.width),i.$$memCanvas.height!==e.height&&(i.$$memCanvas.height=e.height),r.setState(i),i.$$context.putImageData(e,0,0),i.filters.length?i.$$context.filter=i.filters.map((e=>{let t="";return"blur"===e.name?t="px":"hue-rotate"===e.name&&(t="deg"),`${e.name}(${parseFloat(e.value)}${t})`})).join(" "):i.$$context.filter="none",i.$$context.drawImage(i.$$memCanvas,0,0);const t=i.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(Hi.Image,{type:fe.ImageData,value:t})}},getInputNames:()=>[{name:Vi.Image,type:fe.ImageData}],getOutputNames:()=>[{name:Hi.Image,type:fe.ImageData}],getDefaultState:zi},recipeLoad:{onParentEvent:async(e,t,n,r)=>r.nextWidget(qi,{value:!0,type:fe.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:qi,type:fe.Boolean,description:"Triggered when the recipe is fully loaded"}]},note:{onParentEvent:async()=>{},getInputNames:()=>[],getOutputNames:()=>[],getDefaultState:()=>({text:"",color:"#eac43e",size:{width:300,height:200}})},stringify:Ki,templateString:{onParentEvent:async(e,t,n,r)=>{const i={text:"",format:"Text",...r.getState()},s=Ji(i.text,n.data.value);return r.nextWidget("text",{type:fe.String,value:s})},getInputNames:()=>[{name:"input",type:fe.Anything}],getOutputNames:()=>[{name:"text",type:fe.String}],getDefaultState:Yi},expressionEval:{onParentEvent:async(e,t,n,r)=>{const i={expression:"",...r.getState()},s=((e,t)=>{const n=Symbol("error"),r=`\n // 'data' is an argument to this function, passed by new Function call.\n // 'SError' is also an argument, providing the error symbol.\n // 'this' inside this function (created by new Function) is the global object.\n\n\t\t// Shadow eval and Function in this non-strict scope.\n\t\tvar eval = undefined;\n\t\tvar Function = undefined;\n\n // Define the sandbox environment\n const sandboxEnvironment = {\n // Make input 'data' accessible\n data: data,\n \n // Safe console (bind methods to the original console)\n console: undefined,\n\n // Mocked/disabled globals\n process: undefined,\n document: undefined,\n navigator: undefined,\n \n require: undefined,\n // eval and Function are shadowed by var declarations above\n \n // Allowed safe globals (pointing to the real ones, accessed via 'this')\n Math: this.Math,\n Date: this.Date,\n JSON: this.JSON,\n Array: this.Array,\n Object: this.Object,\n String: this.String,\n Number: this.Number,\n Boolean: this.Boolean,\n RegExp: this.RegExp,\n // Error: this.Error, // Not Allow Error constructor\n Symbol: this.Symbol, // Allow Symbol constructor\n Map: this.Map,\n Set: this.Set,\n Promise: this.Promise, // Allow Promise if async expressions are intended\n // setTimeout, setInterval, fetch, etc., are deliberately omitted\n };\n\n // Assign the sandboxEnvironment to act as the 'global' context variables\n const global = sandboxEnvironment;\n const window = sandboxEnvironment;\n const globalThis = sandboxEnvironment;\n\n // Shadow top-level variables that might be accessed directly,\n // ensuring they use the sandboxed versions.\n const process = sandboxEnvironment.process;\n const document = sandboxEnvironment.document;\n const navigator = sandboxEnvironment.navigator;\n const console = sandboxEnvironment.console; // Use the sandboxed console for the expression\n const require = sandboxEnvironment.require;\n // 'eval' and 'Function' are already shadowed by var declarations\n\n // The expression will be evaluated in this scope.\n // 'data' is available as it's an argument to the outer function.\n // 'global.xxx' will resolve to 'sandboxEnvironment.xxx'.\n // 'process.yyy' will resolve to 'sandboxEnvironment.process.yyy'.\n \n return () => {\n "use strict"; // Apply strict mode only to the expression evaluation scope\n const abort = Symbol('abort'); // Local symbol for the expression's optional special return value\n\n let result;\n try {\n // Strict mode can add a layer of security and prevent some common errors.\n // It also changes 'this' binding within the expression if it uses 'this'.\n // If the expression uses 'this', under strict mode it would be undefined unless explicitly set.\n // For expressions not using 'this', strict mode is generally safer.\n result = (() => { return ${t}; })();\n } catch(e) {\n // Log the error using the sandboxed console\n // Use 'instanceof Error' to ensure 'e' has a message property.\n const errorMessage = e instanceof Error ? e.message : String(e);\n return {\n\t\t\t\t\terror: 'Error during expression execution: ' + errorMessage, \n\t\t\t\t\tvalue: null\n\t\t\t\t}; // Return the SError symbol passed into this function's scope\n }\n \n\t\t\t// allows ternary expressions that return 'abort' to cancel the evaluation\n if (result !== abort) {\n // Original logic: if result is strictly true, and expression wasn't literally "true", return original data.\n if (result === true && String(expression).trim() !== 'true') {\n return {value: data, error: null}; \n } else {\n return {value: result, error: null};\n }\n }\n \n // If the expression explicitly returned the 'abort' symbol\n return {value: abort, error: null}; \n }\n // End of functionBody template literal\n `;try{return new Function("data","SError",r)(e,n).call({})}catch(e){return{error:e.message,value:null}}})(n.data.value,i.expression);if("symbol"==typeof s.value)return;if(s.error)throw new Error(s.error);if(Number.isNaN(s.value))throw new Error("Expression resulted in NaN");if(void 0===s.value||null===s.value)return;const o=Fe(s.value);return o!==i.$$lastResultType&&r.setState({...i,$$lastResultType:o}),r.nextWidget("result",{type:o,value:s.value})},getInputNames:()=>[{name:"data",type:fe.Anything}],getOutputNames:e=>[{name:"result",type:e.$$lastResultType||fe.Anything}],getDefaultState:Xi},rescue:{onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type});try{await r.nextWidget("event",n.data)}catch(e){const t=e;await r.nextWidget("error",{type:fe.JsonObj,value:{error:{message:e.message,targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType,stack:e.stack},inputEvent:{type:n.data.type,data:n.data.value}}})}},getInputNames:()=>[{name:"event",type:fe.Anything}],getOutputNames:e=>[{name:"event",type:{...e}.$$lastEventType??fe.Anything},{name:"error",type:fe.JsonObj,jsonShape:{error:fe.JsonObj,inputEvent:fe.JsonObj}}]},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:fe.Boolean}]}},Qi={},es=async()=>{if(!Object.keys(Qi).length)for(const e in Zi){const t=Zi[e];Qi[e]=Object.freeze({...t})}};var ts=e=>{if(Qi[e])return Qi[e];throw new Error(nt(et,e))},ns=es;const rs=new a,is="invoked";let ss={},os={},as={},cs={};const ls=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var ds=(e,t,n,r,i)=>{const s=ls(e,t,n),o=ls(e,t),a=ls(e,t,"produced"),c=as[o],l=Date.now();cs[o]=l,ss[s]={data:r,sourcePortName:n,...i?{target:{widgetId:i.widgetId,portName:i.portName}}:{}},rs.emit(a,{currentTime:l,prevTime:c,...i?{targetPort:i?.portName}:{}})},us=(e,t,n,r,i)=>{const s=ls(e,t,n),o=ls(e,t),a=ls(e,t,is),c=as[o],l=Date.now();as[o]=l,os[s]={data:r,sourcePortName:n,...i?{source:{widgetId:i.widgetId,portName:i.portName}}:{}},rs.emit(a,{prevTime:c,currentTime:l,targetPort:n,sourceInfo:i})},ps=()=>{ss={},os={},as={},cs={},rs.clearListeners()};const gs={};let hs={};const fs=new a;let ms=!1,vs=!1,ys=!1,bs=null,ws=null;const Ss="processing-state-change",Is="error-event",_s={abortRequested:!1,isPaused:!1,pausePromise:null,pausePromiseResolve:null,lastPausedWidgetId:null},$s=e=>(ws=e,fs.emit(Ss,e)),Cs=(e,t)=>`${e}-${t}`,ks=(e,t)=>`state-change:${Cs(e,t)}`,Es=e=>{const{thingId:t,widgetId:n}=e,r=Cs(t,n);return gs[r]||{isProcessing:!1}},xs=()=>{_s.abortRequested=!1,_s.isPaused=!1},As=e=>(_s.pausePromise||(_s.isPaused=!0,_s.pausePromise=new Promise((e=>{_s.pausePromiseResolve=e})),e&&(_s.lastPausedWidgetId=e),$s({isProcessing:!0,isPaused:!0,...e?{pauseTrapWidgetId:e}:{}})),_s.pausePromise);var Ns=async e=>{const{thingId:t,widgetId:n}=e,r=Cs(t,n),i=ks(t,n),s=Es({thingId:t,widgetId:n});if(s.isProcessing)return;const o={isProcessing:!0,isPaused:!1,startTime:Date.now()};gs[r]=o,ms||(ms=!0,bs=null,await $s({isProcessing:!0,isPaused:!1})),await fs.emit(i,{thingId:t,widgetId:n,prevState:s,newState:o})},Ps=async e=>{const{thingId:t,widgetId:n,error:r}=e,i=Cs(t,n),s=ks(t,n),o=Es({thingId:t,widgetId:n}),a={isProcessing:!1,isPaused:!1,startTime:o.startTime,endTime:Date.now(),error:r};gs[i]=a,await fs.emit(s,{thingId:t,widgetId:n,prevState:o,newState:a}),r&&(bs=r,await fs.emit(Is,r)),ms&&0===Object.values(gs).filter((e=>e.isProcessing)).length&&(ms=!1,vs=!1,xs(),await $s({isProcessing:!1,isPaused:!1}))},Os=()=>{ms=!1;for(const e in gs)delete gs[e];_s.abortRequested=!1,_s.isPaused=!1,_s.pausePromise=null,_s.pausePromiseResolve=null,_s.lastPausedWidgetId=null,fs.clearListeners()},Ts=()=>_s.abortRequested,Ls=e=>{_s.lastPausedWidgetId=e,_s.isPaused=!0,$s({isProcessing:!0,isPaused:!0,pauseTrapWidgetId:e})},Bs=()=>vs||ys?null:_s.pausePromise,Ds=e=>ys?null:hs[e]??null,js=()=>vs,Us=e=>As(e);let Rs={},Fs={},Ms=null;const Ws=(e,t)=>{const n=(()=>{if(null===Ms)throw new Error("Recipe execution type not set, please set the execution type using `setRecipeExecutionType`");return Ms===Un.Desktop})();let r=n?Fs[e]:void 0;return r||(r=(e=>{const{widgets:t,targetId:n,allowedTypes:r}=e;if(!t[n])return[];const i=new Set;Object.values(t).forEach((e=>{e.children?.forEach((e=>i.add(e.childId)))}));const s=Object.keys(t).filter((e=>!i.has(e))),o=s.length>0?s:Object.keys(t),a=[],c=(e,i,s)=>{if(s.has(e))return;s.add(e);const o=t[e],l=!r||r.includes(o.type),d=[...i];l&&d.push(e),e===n?a.push(d.join("/")):o.children?.forEach((e=>c(e.childId,d,s))),s.delete(e)};return o.forEach((e=>c(e,[],new Set))),[...new Set(a)]})({widgets:t,targetId:e,allowedTypes:[ze.hubService]}),n&&(Fs[e]=r)),r},Gs=(e,t,n)=>{Ws(t,n).forEach((n=>{Rs[n]={eventContext:e,widgetId:t}}))},Vs=(e,t)=>{const n=t[e].state,r=n.service?.name;if(!r)return[];const i=Ws(e,t),s=new Map;for(const e of i){const n=e.split("/");let i="";for(let e=0;e<n.length-1;e++){i=0===e?n[e]:`${i}/${n[e]}`;const o=Rs[i];if(o&&!s.has(o.widgetId)){const e=t[o.widgetId].state;e.service?.name===r&&s.set(o.widgetId,{path:i,data:o,pathSegments:i.split("/").length})}}}return Array.from(s.values())},Hs=()=>{Rs={}},zs=e=>{Ms=e},qs=()=>{Rs={},Fs={}};let Ks,Js,Ys,Xs=!1,Zs=0;const Qs=async e=>{const{widgetId:t,thingId:n,recipeId:r,targetPortName:i,data:s}=e,o=se(r,n);if(!o)return;const a=o.gates[t];if(!a||a.disabled)return;const c={...s,timestamp:Date.now()},l=ts(a.type),d=ro({gateId:t,originalEvent:c,blockRecipeId:o.recipeId,blockDbId:o.id,blockVersion:o.version,recipeId:r});if(d&&l.onParentEvent){const e={name:i};return Ks&&await Ks({recipeId:r,blockId:o.recipeId,gateId:t,targetPort:e.name,data:s}),l.onParentEvent(null,e,{originalEvent:c,data:{...c}},d)}},eo=async e=>{const{interruptDriven:t,childGateId:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c}=e;let{originalEvent:l,block:d}=e;if(!t&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!t&&!l)throw new Error("Missing parameter ['originalEvent']");t&&(l={timestamp:Date.now(),type:fe.Boolean,value:!0});const u=l;if("string"==typeof d){const e=se(r,d);if(!e)return;d=e}const p=d.gates[n];if(!p||p.disabled)return;const g=a.findIndex((e=>e.name===i)),h=ts(p.type),f=ro({gateId:n,originalEvent:u,blockRecipeId:d.recipeId,blockDbId:d.id,blockVersion:d.version,recipeId:r});if(f&&h.onParentEvent&&-1!==g){Ks&&await Ks({recipeId:r,blockId:d.recipeId,gateId:n,targetPort:s.name,data:o,sourceGate:t?"interrupt_widget":c,sourcePort:t?ce:i});const e={name:a[g].name,type:a[g].type,...a[g].jsonShape?{jsonShape:a[g].jsonShape}:void 0};return us(d.recipeId,n,s.name,o,c?{widgetId:c,portName:i}:void 0),h.onParentEvent(e,s,{originalEvent:u,data:o},f)}},to=async e=>{const{portName:t,originalEvent:n,data:r,currentGateId:i,blockRecipeId:s,thingDbId:o,thingVersion:a,recipeId:c,eventContext:l}=e,d=ie(c);if(!d)throw new Error(`Failed to find recipe "${c}" in cache`);const u=d.dbInfo.recipeType,p=oe(c,s,i);if(!p)return;const g={...r,timestamp:n.timestamp},h=ts(p.type);let f;f=p.type===ze.input?h.getOutputNames(p.state,{thingRecipeId:s,thingDbId:o,thingVersion:a,id:i,recipeId:c,recipeType:u,recipePoolId:c}):await h.getOutputNames(p.state,{recipePoolId:c,recipeType:u,thingRecipeId:s,widgetId:i});const m=f.findIndex((e=>e.name===t));if(-1!==m){const e=se(c,s);if(!e)return;ds(s,i,t,g);let r=null;const o=p.children.length;if(p.type===ze.hubService&&l){const t=p.state,n=t.service?.name;n&&Gs(l,p.id,e.gates)}try{for(let a=0;a<o;a++){const o=e.gates[p.children[a].childId];if(o?.disabled)continue;const l=Ge(p.children[a]?.sourcePort),d=Ge(p.children[a]?.targetPort);if(l.portName===t&&o&&!o.disabled){if(Xs&&Bs()&&(Ls(o.id),await Bs()),Ds(o.id)&&!js()&&"innerInput"!==d?.portType){const e=Us(o.id);await e}if(Xs&&Ts())break;const a=ts(o.type);let l;const h={recipePoolId:c,recipeType:u,thingRecipeId:s,widgetId:i};l=o.type===ze.hubService?await a.getInputNames(o.state,h):a.getInputNames(o.state,h);const m=l.find((e=>e.name===d.portName));if(m){Xs&&await Ns({thingId:s,widgetId:o.id}),Zs++;if(!await eo({interruptDriven:!1,childGateId:o.id,block:e,recipeId:c,sourcePortName:t,targetPort:{name:m.name},data:p.returnOriginalEvent?n:g,sourceOutputNames:f,sourceGateId:p.id,originalEvent:n}).then((()=>!0)).catch((e=>{const n=o.type===ze.hubService&&"CHILD_WIDGET_ERROR"===e.errCode;if(e instanceof Yn)throw e;if(n&&e.errData){const t=e.errData;throw new Yn(e.error||e.message||("string"==typeof e?e:JSON.stringify(e)),{targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType})}if(!r){const n="string"==typeof e?e:e.message||JSON.stringify(e);r={targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,error:n}}throw new Yn(e.message||("string"==typeof e?e:JSON.stringify(e)),{stack:e.stack,targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,sourceWidgetId:p.id,targetWidgetType:o.type,sourceWidgetType:p.type})})).finally((()=>{if(Zs--,Xs)return Ps({thingId:s,widgetId:o.id,error:r})})))break}}}}catch(e){if(e instanceof Yn)throw e;console.error(`Error processing next widget [${i}]: ${e}`)}finally{Zs<0&&(console.warn("Active execution counter is negative, this should never happen"),Zs=0),0===Zs&&Hs()}}},no=async(e,t,n,r)=>{const i=ie(r);if(!i)return null;const s=se(r,n);if(!s)return s;const o=s.gates,a=s.gates[t],c=ts(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),d=l.findIndex((t=>t.name===e));if(-1!==d){const e=((e,t,n)=>{for(const r in n){const i=n[r],s=i.children.length;for(let n=0;n<s;n++){const r=i.children[n],s=Ge(r.targetPort);if(r.childId===e&&s.portName===t)return i}}return null})(t,l[d].name,o);if(e){const t=ts(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},ro=e=>{const{gateId:t,originalEvent:n,blockRecipeId:r,blockDbId:i,blockVersion:s,recipeId:o}=e,a=ie(o);if(!a)throw new Error(`Failed to find recipe "${o}" in cache`);const c=oe(o,r,t);if(!c)return console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),null;const l=async(e,a)=>to({portName:e,originalEvent:n,data:a,currentGateId:t,blockRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}),d=c.type===ze.hubService,u=d?Vs(t,a.blocks[r].gates):[],p=u.reduce(((e,t)=>e.pathSegments>t.pathSegments?e:t),u[0]),g={id:t,type:c.type,recipePoolId:o,thingRecipeId:r,recipeType:a.dbInfo.recipeType,returnOriginalEvent:!!c.returnOriginalEvent,registerInterrupt:(e,n,i,s,a)=>Xe.createInterrupt(e,o,r,t,n,i,s,a),cancelInterrupt:e=>Xe.destroyInterrupt(e),nextWidget:l,nextGate:l,getParentAtPort:e=>no(e,t,r,o),getState:()=>Object.freeze({...c.state,...c.type===ze.input&&{customInputs:[]}}),setState:e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const n={...e,...c.type===ze.input&&!e.customInputs&&{customInputs:[]}},i={...c.state};c.state=n,Js&&Js({blockId:r,gateId:t,prevState:i,newState:{...n},recipeId:o})},...d&&p&&{eventContext:p.data.eventContext}};return g};Xe.setInvokeChildGateCb((async(e,t,n,r,i,s,o,a,c,l)=>eo({interruptDriven:e,childGateId:t,block:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c,originalEvent:l})));const io=new a,so="invoked",oo="state",ao=()=>{Xe.destroyAllInterrupts()},co=async(e,t,n)=>{const r=ie(e),i=oe(e,t,n);if(i&&r){const s=ts(i.type);if(s&&"function"==typeof s.terminate){const i=((e,t,n,r)=>Ze(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)}}}},lo=async(e,t,n,r)=>{const i=ie(e),s=oe(e,t,n);if(s&&i){const o=ts(s.type);if(o&&"function"==typeof o.initialize){const s=((e,t,n,r)=>Ze(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}}}}},uo=(e,t)=>{const n=ie(t);if(n)for(const t in n.blocks){const r=n.blocks[t];for(const t in r.gates)if(t===e)return{widget:r.gates[t],thing:r}}return null},po=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,go=e=>{io.emit(po(oo),e),io.emit(po(oo,e.blockId,e.gateId),e)};Ks=async e=>{await io.emit(po(so),e),await io.emit(po(so,e.blockId,e.gateId),e)},(e=>{Js=e})(go);var ho,fo,mo,vo,yo,bo,wo,So,Io,_o,$o,Co,ko,Eo=async(e,t,n,r,i)=>{const s=ae(e,{id:t,authorId:r,version:n,recipeType:i});ps(),qs(),zs(i);const o=ie(s);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=X.STARTING,o.addLog("recipe registered")),s},xo=async e=>{const t=ie(e);var n;if(!t)return null;t.addLog("terminating recipe"),ao(),Os();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await co(e,n,t)}te[n=e]&&delete te[n]},Ao=async(e,t)=>{const n=ie(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===Un.Desktop){const e=o.gates[t];if(e.type===ze.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===ze.recipeLoad&&i.push(e)}await lo(e,s,t,{keepCurrentState:!0})}catch(e){r.push({widgetId:t,error:e.message})}}return{failed:r,sendToInputWidget:(t,n,r=ge)=>(async(e,t,n,r)=>{const i=ie(n),s=se(n,r),o=Date.now();if(s&&i)for(const i in s.gates){const a=s.gates[i];if(a.type===ze.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=ts(a.type),l={...t,timestamp:o},d=ro({gateId:i,originalEvent:l,blockRecipeId:r,blockDbId:s.id,blockVersion:s.version,recipeId:n});if(d&&e.processEvent){const s={...d,getState:d.getState};Ks&&await Ks({recipeId:n,blockId:r,gateId:i,targetPort:it,data:t}),Ys?await Ys(r,n,c,t):await e.processEvent(l,s)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of i)await Qs({widgetId:t.id,thingId:ge,recipeId:e,targetPortName:qi,data:{type:fe.Boolean,value:!0}})}}},No=e=>{Fi(e)},Po=(e,t,n,r=!1)=>{const i=uo(t,e);if(i){const{widget:s,thing:o}=i,a={...s.state};s.state=n,r&&go({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},Oo=(e,t)=>{const n=uo(t,e);return n?n.widget.state:null},To=async e=>{const{recipePoolId:t,currentGateId:n,sourcePortName:r,originalEvent:i,data:s,eventContext:o}=e,a=uo(n,t);if(a)return to({portName:r,originalEvent:i,data:s,currentGateId:n,blockRecipeId:a.thing.recipeId,thingDbId:a.thing.id,thingVersion:a.thing.version,recipeId:t,eventContext:o})};!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(ho||(ho={})),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"}(fo||(fo={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(mo||(mo={})),function(e){e.Bundle="bundle",e.Group="group"}(vo||(vo={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(yo||(yo={})),function(e){e.Cloud="cloud",e.Web="web"}(bo||(bo={})),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"}(wo||(wo={})),function(e){e.Gateway="gateway",e.Timer="timer"}(So||(So={})),function(e){e.InstallInProgress="installation-in-progress"}(Io||(Io={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(_o||(_o={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}($o||($o={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Co||(Co={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.UninstallHubService="uninstall_hub_service",e.ExportRecipe="export_recipe"}(ko||(ko={}));const Lo=(e,t)=>((e,t,n)=>{const r=Buffer.from(n,"base64"),i=r.subarray(0,16),s=r.subarray(16).toString("base64"),o=u(e,t,32),a=p("aes-256-cbc",o,i);let c=a.update(s,"base64","utf8");return c+=a.final("utf8"),c})(e.id||"recipe.kemu","kemu",t),Bo=e=>{try{return JSON.parse(e)}catch(e){return null}},Do="undefined"!=typeof window,jo={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Uo={protocolPrefix:4,txtLength:4},Ro=Object.values(jo).reduce(((e,t)=>e+t),0),Fo=Object.values(Uo).reduce(((e,t)=>e+t),0),Mo=["width","height","colorSpace"],Wo=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)Object.hasOwn(e,n)||Mo.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},Go=(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},Vo=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(Object.hasOwn(n,s)){const{index:o,length:a,binaryType:c}=n[s];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&Go(e,s,l)}return e},Ho=e=>f(e),zo="KMSG",qo="KCMD",Ko=Ho("klProtocol");var Jo={encode:(e,t,n)=>{const r={json:e.json},i=Wo(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,d=jo.protocolPrefix+jo.protocolVersion+jo.jsonLength+jo.binaryLength+jo.fromServiceId+jo.toServiceId+jo.sentAt+l+o,u=Buffer.alloc(d),p=Date.now();let g=0;return u.write(zo,g),g+=jo.protocolPrefix,u.writeUInt8(1,g),g+=jo.protocolVersion,u.writeUInt32LE(l,g),g+=jo.jsonLength,u.writeUInt32LE(o,g),g+=jo.binaryLength,u.writeUInt32LE(t,g),g+=jo.fromServiceId,u.writeUInt32LE(n,g),g+=jo.toServiceId,u.writeBigInt64LE(BigInt(p),g),g+=jo.sentAt,c.copy(u,g),g+=l,s&&o&&s.copy(u,g),u},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,jo.protocolPrefix);if(t+=jo.protocolPrefix,n!==zo)return null;if(e.byteLength<Ro)return Ko(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=jo.protocolVersion;const i=e.readUInt32LE(t);t+=jo.jsonLength;const s=e.readUInt32LE(t);t+=jo.binaryLength;const o=e.readUInt32LE(t);t+=jo.fromServiceId;const a=e.readUInt32LE(t);t+=jo.toServiceId;const c=e.readBigInt64LE(t);t+=jo.sentAt;const l=i+s,d=e.subarray(t,t+l),u=e.subarray(0,Ro);let p=null;return e.byteLength-Ro-i-s>0&&(p=e.subarray(Ro+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[d],headerPackage:u},remaining:p}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),i=Bo(n);if(!i?.json)return Ko("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Vo(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=Ro+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<Ro)return Ko("Invalid Header Size"),e;let n=0;return n+=jo.protocolPrefix,n+=jo.protocolVersion,n+=jo.jsonLength,n+=jo.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=jo.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=Fo+r,s=Buffer.alloc(i);return s.write(qo,t),t+=Uo.protocolPrefix,s.writeUint32LE(r,t),t+=Uo.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<Fo)return{command:null};const n=e.toString("utf-8",t,Uo.protocolPrefix);if(t+=Uo.protocolPrefix,n!==qo)return{command:null};const r=e.readUInt32LE(t);t+=Uo.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-Fo-r;let o=null;s>0&&(o=e.subarray(Fo+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Yo="KMSG",Xo="KCMD",Zo=Ho("klProtocol"),Qo=new TextEncoder;var ea={encode:(e,t,n)=>{const r={json:e.json},i=Wo(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=Qo.encode(a),l=c.byteLength,d=new ArrayBuffer(jo.protocolPrefix+jo.protocolVersion+jo.jsonLength+jo.binaryLength+jo.fromServiceId+jo.toServiceId+jo.sentAt+l+o),u=new DataView(d),p=new Uint8Array(d),g=Date.now();let h=0;for(let e=0;e<4;++e)p[h++]=Yo.charCodeAt(e);return u.setUint8(h,1),h+=jo.protocolVersion,u.setUint32(h,l,!0),h+=jo.jsonLength,u.setUint32(h,o,!0),h+=jo.binaryLength,u.setUint32(h,t,!0),h+=jo.fromServiceId,u.setUint32(h,n,!0),h+=jo.toServiceId,u.setBigInt64(h,BigInt(g),!0),h+=jo.sentAt,p.set(c,h),h+=l,s&&o&&p.set(new Uint8Array(s),h),d},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<jo.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Yo)return null;if(e.byteLength<Ro)return Zo.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=jo.protocolVersion;const s=t.getUint32(n,!0);n+=jo.jsonLength;const o=t.getUint32(n,!0);n+=jo.binaryLength;const a=t.getUint32(n,!0);n+=jo.fromServiceId;const c=t.getUint32(n,!0);n+=jo.toServiceId;const l=t.getBigInt64(n,!0);n+=jo.sentAt;const d=s+o,u=e.slice(n,n+d),p=new Uint8Array(e,0,Ro);let g=null;if(e.byteLength-Ro-s-o>0){g=new Uint8Array(e,Ro+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[u],headerPackage:p.slice().buffer},remaining:g}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Bo(s);if(!a?.json)return Zo.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Vo(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,d=null;const u=Ro+e.jsonLength+e.binaryLength;return c.byteLength>u&&(d=c.subarray(u),l=c.subarray(0,u)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:d?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Ro)return Zo("Invalid Header Size"),e;let n=0;n+=jo.protocolPrefix,n+=jo.protocolVersion,n+=jo.jsonLength,n+=jo.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=jo.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Qo.encode(e),r=n.byteLength,i=new ArrayBuffer(Fo+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=Xo.charCodeAt(e);return s.setUint32(t,r,!0),t+=Uo.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Fo)return{command:null};let r="";for(let e=0;e<Uo.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Xo)return{command:null};const i=t.getUint32(n,!0);n+=Uo.txtLength;const s=e.byteLength-Fo-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-Fo)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(Fo+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};let ta=Jo;Do&&(ta=ea);var na,ra=ta;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(na||(na={}));let ia=Math.ceil(Date.now()/1e3);let sa,oa,aa,ca,la,da=!1;var ua=()=>{da=!0},pa=(e,t)=>{if(!sa)throw new Error("Memory connection not set.");sa.sendBuf(e,t)},ga=e=>oa=e,ha=e=>la=e,fa=e=>aa=e,ma=e=>ca=e;const va=async(e,t=2)=>{const n=async(e,r)=>{if(Array.isArray(e))for(let i=0;i<e.length;i++){const s=e[i];if(s&&"object"==typeof s)if(Array.isArray(s))await n(s,r+1);else{const o=s._kemuType;void 0!==o?o===fe.ImageData&&(e[i]=await Ve(s)):r<t&&await n(s,r+1)}}else if("object"==typeof e&&null!==e){const i=Object.keys(e);for(const s of i){const i=e[s];if(i&&"object"==typeof i){const o=i._kemuType;void 0!==o?o===fe.ImageData&&(e[s]=await Ve(i)):r<t&&await n(i,r+1)}}}};return await n(e,1),e};Ho("klTransmissionManager"),Ho("ipcClient");Ho("kemuWidgetService"),k(process.argv.slice(2));const ya=e=>f(`runner:${e}`),ba=ya("connectionManager"),wa=ya("remoteInvoke"),Sa=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=Do?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return o(r)&&(a=ra.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,i,s,o)=>{if(!o)return!1;const c=o;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=r[c.functionName];if(t){const n=e=>{a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:s.sourceServiceId,send:i})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,s,a,c,l)=>{if(!s){const e="No send buffer function provided.";throw n&&n(e),e}ia+=1;const d=`${i}-${ia}-exec-${e.substring(0,10)}`,u={messageId:d,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};u.promise=new Promise(((e,t)=>{u.resolve=e,u.reject=t}));let p=Do?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:r,messageId:d,type:"execute"}};o(c)&&(p=ra.encode(g,a,c)),t[d]=u,n&&n(`Calling remote function "${e}" with message id "${d}"`);const h="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(u.fulfilled=!0,u.resolve([void 0]),delete t[d]):0===l?.timeout||h||(u.timer=setTimeout((()=>{n&&n(`Remote function ${d} timed out`);const r=t[d];r&&!r.fulfilled&&(r.fulfilled=!0,u.reject(`Function ${e} Timed out`)),delete t[d]}),l?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:g}),u.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,s)=>{ia+=1;const a=`${i}-${ia}-multicast-${e.substring(0,10)}`;let c=Do?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let d=o(r[0].serviceId);d&&(c=ra.encode(l,s,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(d=o(i.serviceId),d&&(c=ra.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:s,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("kweb");Sa.setLogger(wa);const Ia=new a,_a=new a;let $a,Ca=null,ka=null,Ea=null,xa=null;const Aa={},Na=()=>{if(!Ea)throw new Error("API key is required to interact with the hub");return Ea},Pa=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return Aa[r]=i,i},Oa=(e,t)=>Aa[`${e}_${t}`]||null,Ta=async(e,t)=>{if(!Ca)return ba("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await Sa.execute(be.GetServiceContents,n,Ba,Ca,0))[0]},La=async(e,t,n=!1)=>{if(!e||!t)return null;const r=Oa(e,t);if(!r||n){const n=r||Pa(e,t);try{const r=await Ta(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){ba(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},Ba=pa,Da=()=>{ba("Disconnected from the server"),Ca=null,xa=null,Sa.rejectAllPending("Disconnected from the server"),Ia.emit("disconnected")},ja=()=>{ba("Connected to the server"),Ia.emit("connected")},Ua=()=>ka,Ra=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,Fa=async()=>{const e=Ua();if(e){const t=ie(e)?.blocks;if(t){const n={};for(const r in t){const i=t[r];for(const t in i.gates){const r=i.gates[t];if(r.type===ze.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{ba(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await tc({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){ba(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},Ma=async e=>{if(!e)return void ba("Hub sent ACK request without service id");const t={apiKey:Na(),ackSessionId:e};await Sa.execute(be.SocketAckResponse,[t],Ba,e,0),ba("Hub Link acknowledged"),Ca=e,Ia.emit("acknowledged"),Fa()},Wa=async e=>{const t=e.args[0],n=Ra("broadcast",`hub_${t.type}`,(0).toString(),"");await _a.emit(n,t)},Ga=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===fe.ImageData&&je(e.value)&&(e.value=await Ve(e.value));const n=Ua();if(n){const r=ie(n);if(r){const i=async e=>{const n=Ra("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await _a.emit(n,t)}catch(t){ba(`Failed to emit broadcast event for target ${e}`,t)}};await i("app");for(const s in r.blocks){const o=r.blocks[s];for(const r in o.gates){const s=o.gates[r];if(s.disabled)continue;const a=s.state;if(s.type===ze.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await i(r);const s=a?.service?.name&&t.eventContext?{[a.service.name]:t.eventContext}:void 0;for(const i of t.outputs||[])if(null!==i.value&&void 0!==i.value){const t={type:i.type,value:i.value,timestamp:Date.now()};ba(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await To({recipePoolId:n,currentGateId:r,sourcePortName:i.name,originalEvent:t,data:t,eventContext:s})}}}}}}},Va=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,s=Oo(r,i);let o=s;if(n&&o&&s&&(o={...s,customState:n},Po(r,i,o,!0)),o?.service)try{const e=Ra("setOutputs",o.service.name,o.service.version,i);await _a.emit(e,t.outputs)}catch(e){ba(`Failed to emit setOutputs event for widget ${i}`,e)}let a=null;for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===fe.ImageData){if(!je(n.value)){ba(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=await Ve(n.value)}else n.type!==fe.JsonObj&&n.type!==fe.Array||await va(n.value);const s={type:n.type,value:n.value,timestamp:Date.now()};ba(`Sending data to output ${n.name} requested by messageId ${e.messageId}`);const c=o?.service?.name&&t.eventContext?{[o.service.name]:t.eventContext}:void 0;try{await To({recipePoolId:r,currentGateId:i,sourcePortName:n.name,originalEvent:s,data:s,eventContext:c})}catch(e){ba(`Failed to trigger next global widget for output ${n.name}`,e),a=e;break}}if(a){const t=a instanceof Yn,n=a;e.reply({error:a.message,errCode:t?"CHILD_WIDGET_ERROR":"INVOKING_ERROR",errData:{targetWidgetId:n.targetWidgetId,targetPortName:n.targetPortName,sourcePortName:n.sourcePortName,sourceWidgetId:n.sourceWidgetId,targetWidgetType:n.targetWidgetType,sourceWidgetType:n.sourceWidgetType}})}else e.reply({success:[]})},Ha=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,s=Oo(r,i);if(s){const t={...s,customState:{...s.customState,...n}};return Po(r,i,t,!0),e.reply({success:[]})}},za=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:s,key:o}=n;ba(`Received request to set a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const a=Oo(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:s},Po(r,i,e,!0)}return t({success:[]})},qa=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:s}=n;ba(`Received request to get a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const o=Oo(r,i);if(o){const e=o.dependencies?.[s]?.path;return ba(`Returning dependency path for "${s}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},Ka=async()=>{if(ba(`Requesting services on ${(new Date).toISOString()}`),!Ca)return ba("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await Sa.execute(be.GetServices,[],Ba,Ca,0);$a=e;for(const t of e.available){if(t.internal)continue;const e=Oa(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||Pa(t.name,t.version);ba(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await Ta(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){ba(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},Ja=()=>$a||{available:[],installed:[],failed:[]},Ya=()=>!!$a,Xa=async e=>{const{targetServiceSessionId:t}=e;if(!Ca)return void ba("No target service session id provided");ba(`Forwarding "onParentEvent" to service ${t}`);return await Sa.execute(be.OnParentEvent,[e],Ba,Ca,t,e.config).catch((e=>{throw ba(`Error invoking onParentEvent callback: ${e}`),e.errCode===na.ParentEventCallbackError?e.error:e}))},Za=async e=>{if(!Ca)return ba("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await Sa.execute(be.GetDefaultState,[],Ba,Ca,e);return t},Qa=async(e,t,n,r)=>{if(!Ca)return ba("Hub Link has not been acknowledged. Cannot get services."),null;const[i]=await Sa.execute(be.UIEvent,[t,n],Ba,Ca,e,r);return i},ec=(e,t)=>{const n=()=>{t()};return Ia.on(e,n),()=>Ia.off(e,n)},tc=async e=>{if(Ca)return Sa.execute(be.SubscribeToService,[e],Ba,Ca,0);ba("Hub Link has not been acknowledged. Cannot subscribe to services.")},nc=async e=>{if(Ca)return Sa.execute(be.UnsubscribeFromService,[e],Ba,Ca,0);ba("Hub Link has not been acknowledged. Cannot subscribe to services.")},rc=(e,t,n,r)=>{const i=Ra("broadcast",t,n,e);return _a.on(i,r)},ic=(e,t,n,r)=>{const i=Ra("setOutputs",t,n,e);return _a.on(i,r)},sc=async(e,t,n)=>Ca?Sa.execute(e,t,Ba,Ca,0,n):(ba("Hub Link has not been acknowledged. Cannot execute function."),null),oc=async e=>{if(!Ca)return void ba("Hub Link has not been acknowledged. Cannot execute function.");const t=Oo(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 Sa.execute(be.InitializeInstance,r,Ba,Ca,e.sessionId);if(i){const t=Oo(e.recipeId,e.widgetId);if(t){const n={...t,customState:i};Po(e.recipeId,e.widgetId,n,!0)}}},ac=async(e,t,n,r)=>{if(!Ca)return void ba("Hub Link has not been acknowledged. Cannot execute function.");const i=Oo(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 Sa.execute(be.TerminateInstance,s,Ba,Ca,e)},cc=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=Ya(),o=r||!s?await Ka():Ja();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},lc=async()=>{if(!Ca)return ba("Hub Link has not been acknowledged. Cannot get services."),null;if(xa)return xa;const[e]=await Sa.execute(be.GetSystemInfo,[],Ba,Ca,0).catch((e=>(ba("Failed to get system info",e),[null])));return xa=e,e};var dc,uc,pc,gc,hc,fc,mc,vc,yc=async e=>{fa(ja),ma(Da),Ea=e,ha((({json:e,transmission:t})=>{Sa.processMessage("websocket",Ba,t,e)})),Sa.registerFunction(be.SetState,Ha),Sa.registerFunction(be.SetOutputs,Va),Sa.registerFunction(be.BroadcastEvent,Ga),Sa.registerFunction(be.HubBroadcastEvent,Wa),Sa.registerFunction(we.SetDependencyPath,za),Sa.registerFunction(we.GetDependencyPath,qa),ga((e=>{((e,t)=>{const n=ye.SocketAcknowledge,r=ye.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,Ma),((e,t)=>{e===ye.ServicesListChanged&&(t&&t())})(e,(()=>{ba("Services list changed"),Ia.emit("services-changed")}))})),await ua()},bc=(e,t)=>{Ia.on(e,t)},wc=()=>({getServices:Ka,getServiceContents:La,onParentEvent:Xa,onCommand:ec,getDefaultState:Za,getCachedServices:Ja,areServicesCached:Ya,subscribeToServiceEvents:tc,unsubscribeFromServiceEvents:nc,callProcessorHandler:Qa,onBroadcastEvent:rc,onSetOutputsEvent:ic,executeHubFunction:sc,initializeServiceInstance:oc,terminateServiceInstance:ac,getCompatibleService:cc,getHubSystemInfo:lc}),Sc=e=>{ka=e},Ic=()=>Sa;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(dc||(dc={})),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"}(uc||(uc={})),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"}(pc||(pc={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(gc||(gc={})),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:"}(hc||(hc={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(fc||(fc={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(mc||(mc={})),function(e){e.IPC="ipc",e.WS="ws"}(vc||(vc={}));const _c=e=>{try{return JSON.parse(e)}catch(e){return null}},$c=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Cc=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match($c);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},kc=e=>"*"===e||"x"===e||"X"===e,Ec=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},xc=(e,t)=>{if(kc(e)||kc(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(Ec(e),Ec(t));return n>r?1:n<r?-1:0},Ac=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=xc(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},Nc=(e,t,n)=>{Tc(n);const r=((e,t)=>{const n=Cc(e),r=Cc(t),i=n.pop(),s=r.pop(),o=Ac(n,r);return 0!==o?o:i&&s?Ac(i.split("."),s.split(".")):i||s?i?-1:1:0})(e,t);return Pc[n].includes(r)},Pc={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},Oc=Object.keys(Pc),Tc=e=>{if(-1===Oc.indexOf(e))throw new Error(`Invalid operator, expected one of ${Oc.join("|")}`)};var Lc="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Bc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Dc,jc,Uc,Rc,Fc,Mc={exports:{}},Wc={exports:{}};function Gc(){if(jc)return Dc;jc=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 Dc=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 Vc(){if(Rc)return Uc;return Rc=1,Uc=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=Gc(),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},Uc}var Hc,zc,qc,Kc,Jc,Yc={exports:{}};function Xc(){return zc||(zc=1,Hc=(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)}),Hc}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?Mc.exports=(Fc||(Fc=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=Vc()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Wc,Wc.exports)),Wc.exports):Mc.exports=(Jc||(Jc=1,function(e,t){const n=E,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(Kc)return qc;Kc=1;const e=x,t=E,n=Xc(),{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)),qc={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=Vc()(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)}}(Yc,Yc.exports)),Yc.exports);var Zc=Bc(Mc.exports);const Qc=e=>Zc(e),el=Date.now();let tl=Math.ceil(el/1e3);var nl=()=>tl+=1;const rl=v(A(),"kemu-user-services"),il=v(A(),"kemu-test-services"),sl="KMU-CB-v1",ol=process.env.HUB_PKG_VERSION||'"1.3.5"';var al;!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"}(al||(al={}));const cl=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>uc[e])):uc[e.type]}),ll=async e=>{try{return await S(e,"utf-8")}catch(e){return null}},dl=e=>{if(e&&e.startsWith(sl)){const t=e.slice(9),n=decodeURI(t);return _c(n)}return null},ul=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(cl)}:{},...e.outputs?{outputs:e.outputs.map(cl)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(cl)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(cl)}:{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 ll(v(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const s=t.startsWith(sl)?t:`${sl}${t}`,o=dl(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===al.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${i}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${i}" does not contain a top level widgetGroup`);continue}const l=c.state,d={name:l.name,color:l.color,description:l.description,contents:s,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(d)}return r})(t,e,n?.log);if(s.length?i.customWidgets=s:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await S(v(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},pl=async e=>{try{return await I(e,_.F_OK),!0}catch{return!1}};let gl=null,hl=null;const fl=()=>gl||rl,ml=Qc("servicesManager"),vl={};let yl=null,bl=null,wl=null;class Sl extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const Il=async e=>{try{return await I(e),!0}catch{return!1}},_l=async e=>{if(!yl)throw new Error('IPC config not set, call "setHubIpcConfig" first.');try{if(e.processor===gc.Javascript){ml(`Spawning service ${e.name} with sessionId ${e.sessionId}`);const t=m.join(e.path,"processor.js"),n=m.join(e.path,"processor.mjs"),r=await Il(t)?t:n,i=[`--sessionId=${e.sessionId.toString()}`,`--ipcSpace=${yl.appSpace}`,`--ipcId=${yl?.id}`,`--recipePath=${yl.recipePath||""}`];if(e.internal&&i.push("--internal=true"),!wl)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const s=await wl({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 Sl(`Missing required environment variables: ${o.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,n)=>{if(!bl)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const o=bl({args:[r,...i],serviceInfo:{name:e.name,version:e.version},options:{env:s}});o.stdout.on("data",(t=>{ml(`[${e.name}] - stdout: ${t}`)})),o.stderr.on("data",(t=>{ml(`[${e.name}] - stderr: ${t}`)})),o.on("exit",(t=>{ml(`[${e.name}] exited with code ${t}`)})),o.on("spawn",(()=>{ml(`[${e.name}] spawned with PID ${o.pid}`),t(o)})),o.on("error",(t=>{ml(`[${e.name}] error: ${t}`),n(new Sl(`Error spawning service ${e.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.processor}`}catch(t){if(t instanceof Sl)throw t;throw`Error spawning service ${e.name}: ${t}`}},$l=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[gc.Javascript,gc.Executable,gc.Python].includes(e?.processor)?null:"Invalid processor"},Cl=async(e,t)=>{const n=m.join(e,"manifest.json");if(!await Il(n)){const t=`Missing manifest for service ${e}. Aborting.`;return ml(t),{error:t}}const r=await S(n,"utf-8"),i=_c(r),s=$l(i);if(!i||s){const t=`Invalid service manifest [${e}]: ${s}. Aborting.`;return ml(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(m.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return ml(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await ll(m.join(e,i.svgIcon));if(!t){return{error:`Error loading icon for service ${i.name}`}}i.svgIcon=t}})(),(async()=>{if(i.subServices?.length)for(const t of i.subServices){const n=m.join(e,t),{error:r,service:s}=await Cl(n);r?ml(`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(m.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){ml(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=nl(),c=t?.fixedSession||a;ml(`Loaded service ${i.name} with sessionId ${c}`);const l=await ul(i,e,{widgetUIContents:o});return kl(l),vl[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null},{service:vl[c]}},kl=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=g("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},El=async e=>{try{return e.childProcess=await _l(e.info),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return ml(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof Sl?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},xl=e=>{const{path:t,...n}=e.info;return{...n}},Al=()=>Object.values(vl).filter((e=>"running"===e.status)).map(xl),Nl=e=>{const{serviceName:t,version:n,force:r}=e,i=Object.values(vl).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){ml(`Stopping service "${t} (v${n})"`);i.childProcess.kill("SIGINT")||ml(`Failed to stop service ${t}`)}return i.status="stopped",ml(`Service ${t} stopped`),i},Pl=e=>e.info.internal?e.info.path:m.join(e.info.path,".."),Ol=e=>!!e.internal;var Tl={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await pl(e))return void ml(`Failed to load services from "${e}". Directory does not exist.`);const n=(await $(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));ml(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],s=m.join(e,i),{error:o,service:a}=await Cl(`${s}${t?.internalServices?"":"/dist"}`,t);o&&ml(`Failed to load service ${s}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(ml("Initializing services"),!yl)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in vl){const n=vl[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?ml(`Service ${n.info.name} is in the noSpawningList. Skipping.`):El(n)}ml("Services initialized")},setServiceStatus:(e,t)=>{const n=vl[e];return n?(n.status=t,!0):(ml(`Service with serviceId ${e} not found`),!1)},getActiveServices:Al,getMatchingService:(e,t)=>{const n=Object.values(vl).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(Nc(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>vl[e]||null,killAllServices:()=>{for(const e in vl){const t=vl[e];if(t.childProcess)try{ml(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){ml(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await ul(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};vl[e]=r,kl(vl[e].info)},setServiceManifest:(e,t,n)=>{const r=vl[e];if(!r)return ml(`Service with sessionId ${e} not found`),!1;const i=$l(t);if(i)return ml(`Invalid manifest for service ${r.info.name}: ${i}`),!1;kl(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(vl).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:()=>Al().filter((e=>e.internal)),getAllServices:()=>Object.values(vl),stopService:Nl,uninstallService:async(e,t)=>{ml(`Uninstalling service ${e} v${t}`);const n=Nl({serviceName:e,version:t});if(!n)return!1;ml(`Service ${e} stopped. Removing from disk...`);const r=Pl(n),i=fl();return r.startsWith(i)?(await C(r,{recursive:!0,force:!0}),ml(`Service ${e} successfully removed from disk`),(e=>{const t=vl[e];delete vl[e]})(n.info.sessionId),!0):(ml(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(vl).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{yl={...e}},loadAndLaunch:async(e,t,n)=>{const r=b(e,t),{error:i,service:s}=await Cl(r);if(i||!s)return{errorMsg:i};try{s.info.internal=!!n,s.childProcess=await _l(s.info),s.status="started"}catch(e){s.status="error",e instanceof Sl?(ml(`Service spawning error: ${e.message} (${e.code})`),s.errorMsg=e.message,s.errorCode=e.code):(ml(`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:Pl,setSpawnNodeFunction:e=>{bl=e},setGetSecretsFunction:e=>{wl=e},restartService:async(e,t)=>{ml(`Restarting service ${e} v${t}`);const n=Nl({serviceName:e,version:t,force:!0});return!!n&&El(n)},getFailedServices:()=>Object.values(vl).filter((e=>"error"===e.status)).map((e=>({...xl(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Ol,isNotInternalKemuService:e=>!Ol(e),isNotDevService:e=>!e.devMode};class Ll{constructor(){}appspace="app.";socketRoot="/tmp/";id=x.hostname();encoding="utf8";rawBuffer=!1;sync=!1;unlink=!0;delimiter="\f";silent=!1;logDepth=5;logInColor=!0;logger=console.log.bind(console);maxConnections=100;retry=500;maxRetries=1/0;stopRetrying=!1;IPType=function(){const e=x.networkInterfaces();let t="";e&&Array.isArray(e)&&e.length>0&&(t=e[Object.keys(e)[0]][0].family);return t}();tls=!1;networkHost="IPv6"==this.IPType?"::1":"127.0.0.1";networkPort=8e3;readableAll=!1;writableAll=!1;interface={localAddress:!1,localPort:!1,family:!1,hints:!1,lookup:!1}}class Bl{constructor(e){e||(e=new Ll),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 Dl=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={}},jl=Bc(Dl);var Ul=Bc((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 Rl{}class Fl{}const Ml=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 Rl,t=Fl){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 Rl}}())}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 Wl{constructor(){}on(e,t,n=!1){return Ml.string(e),Ml.function(t),Ml.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(Ml.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Ml.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){Ml.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)=>{Ml.string(e),Ml.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 Gl=new Bl;class Vl extends Wl{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Gl=new Bl(this.config)}Client=Vl;queue=new Ul;socket=!1;connect=ql;emit=Hl;retriesRemaining=0;explicitlyDisconnected=!1}function Hl(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new jl;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Gl.format(n),this.config.sync?this.queue.add(zl.bind(this,n)):this.socket.write(n)}function zl(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function ql(){let e=this;if(e.log("requested connection to ",e.id,e.path),!this.path)return void e.log("\n\n######\nerror: ",e.id," client has not specified socket path it wishes to connect to.");const t={};if(e.port)if(t.host=e.path,t.port=e.port,e.config.interface.localAddress&&(t.localAddress=e.config.interface.localAddress),e.config.interface.localPort&&(t.localPort=e.config.interface.localPort),e.config.interface.family&&(t.family=e.config.interface.family),e.config.interface.hints&&(t.hints=e.config.interface.hints),e.config.interface.lookup&&(t.lookup=e.config.interface.lookup),e.config.tls){if(e.log("Connecting client via TLS to",e.path,e.port,e.config.tls),e.config.tls.private&&(e.config.tls.key=O.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=O.readFileSync(e.config.tls.public)),e.config.tls.trustedConnections){"string"==typeof e.config.tls.trustedConnections&&(e.config.tls.trustedConnections=[e.config.tls.trustedConnections]),e.config.tls.ca=[];for(let t=0;t<e.config.tls.trustedConnections.length;t++)e.config.tls.ca.push(O.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=P.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=N.connect(t);else e.log("Connecting client on Unix Socket :",e.path),t.path=e.path,"win32"!==process.platform||e.path.startsWith("\\\\.\\pipe\\")||(t.path=t.path.replace(/^\//,""),t.path=t.path.replace(/\//g,"-"),t.path=`\\\\.\\pipe\\${t.path}`),e.socket=N.connect(t);e.socket.setEncoding(this.config.encoding),e.socket.on("error",(function(t){e.log("\n\n######\nerror: ",t),e.publish("error",t)})),e.socket.on("connect",(function(){e.publish("connect"),e.retriesRemaining=e.config.maxRetries,e.log("retrying reset")})),e.socket.on("close",(function(){if(e.log("connection closed",e.id,e.path,e.retriesRemaining,"tries remaining of",e.config.maxRetries),e.config.stopRetrying||e.retriesRemaining<1||e.explicitlyDisconnected)return e.publish("disconnect"),e.log(e.config.id,"exceeded connection rety amount of"," or stopRetrying flag set."),e.socket.destroy(),e.publish("destroy"),void(e=void 0);setTimeout(function(){e.explicitlyDisconnected||(e.retriesRemaining--,e.connect())}.bind(null,e),e.config.retry),e.publish("disconnect")})),e.socket.on("data",(function(t){if(e.log("## received events ##"),e.config.rawBuffer){if(e.publish("data",Buffer.from(t,e.config.encoding)),!e.config.sync)return;return void e.queue.next()}if(this.ipcBuffer||(this.ipcBuffer=""),(t=this.ipcBuffer+=t).slice(-1)!=Gl.delimiter||-1==t.indexOf(Gl.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Gl.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new jl;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 Kl=new Bl;class Jl extends Wl{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Kl=new Bl(this.config),this.on("close",Zl.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Yl;broadcast=Xl;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?O.unlink(this.path,nd.bind(this)):nd.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Yl(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new jl;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Kl.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 Xl(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new jl;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Kl.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 Zl(){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 Ql(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)==Kl.delimiter&&-1!=t.indexOf(Kl.delimiter))for(r.ipcBuffer="",t=Kl.parse(t);t.length>0;){let e=new jl;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 ed(e){this.publish("close",e)}function td(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",ed.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",Ql.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 nd(){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=id.bind(this),this.server.on("listening",function(){td.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?rd.bind(this)():this.server=N.createServer(td.bind(this))),this.server.on("error",function(e){this.log("server error",e),this.publish("error",e)}.bind(this)),this.server.maxConnections=this.config.maxConnections,this.port?this.udp4||this.udp6?(this.log("starting server as",this.udp4?"udp4":"udp6"),this.server.bind(this.port,this.path),void this.onStart({address:this.path,port:this.port})):(this.log("starting server as",this.config.tls?"TLS":"TCP"),void this.server.listen(this.port,this.path,this.onStart.bind(this))):(this.log("starting server as","Unix || Windows Socket"),"win32"===process.platform&&(this.path=this.path.replace(/^\//,""),this.path=this.path.replace(/\//g,"-"),this.path=`\\\\.\\pipe\\${this.path}`),void this.server.listen({path:this.path,readableAll:this.config.readableAll,writableAll:this.config.writableAll},this.onStart.bind(this)))}function rd(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=O.readFileSync(this.config.tls.private):this.config.tls.key=O.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=O.readFileSync(this.config.tls.public):this.config.tls.cert=O.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=O.readFileSync(this.config.tls.dhparam)),this.config.tls.trustedConnections){"string"==typeof this.config.tls.trustedConnections&&(this.config.tls.trustedConnections=[this.config.tls.trustedConnections]),this.config.tls.ca=[];for(let e=0;e<this.config.tls.trustedConnections.length;e++)this.config.tls.ca.push(O.readFileSync(this.config.tls.trustedConnections[e]))}this.server=P.createServer(this.config.tls,td.bind(this))}function id(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 sd{constructor(){}config=new Ll;of={};server=!1;get connectTo(){return ud}get connectToNet(){return pd}get disconnect(){return ad}get serve(){return cd}get serveNet(){return dd}get log(){return od}set connectTo(e){return ud}set connectToNet(e){return pd}set disconnect(e){return ad}set serve(e){return cd}set serveNet(e){return dd}set log(e){return od}}function od(...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 ad(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 cd(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=ld),this.server=new Jl(e,this.config,od),this.server.on("start",t)}function ld(){}function dd(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=ld),this.server=new Jl(e,this.config,od,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function ud(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=ld),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 Vl(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 pd(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=ld),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 Vl(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 gd=new class extends sd{constructor(){super()}IPC=sd};var hd={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const fd=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),md=e=>{try{return JSON.parse(e)}catch(e){return null}},vd="undefined"!=typeof window,yd={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},bd={protocolPrefix:4,txtLength:4},wd=Object.values(yd).reduce(((e,t)=>e+t),0),Sd=Object.values(bd).reduce(((e,t)=>e+t),0),Id=["width","height","colorSpace"],_d=(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)||Id.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},$d=(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},Cd=(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&&$d(e,s,l)}return e},kd=e=>Zc(e),Ed="KMSG",xd="KCMD",Ad=kd("klProtocol");var Nd={encode:(e,t,n)=>{const r={json:e.json},i=_d(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,d=yd.protocolPrefix+yd.protocolVersion+yd.jsonLength+yd.binaryLength+yd.fromServiceId+yd.toServiceId+yd.sentAt+l+o,u=Buffer.alloc(d),p=Date.now();let g=0;return u.write(Ed,g),g+=yd.protocolPrefix,u.writeUInt8(1,g),g+=yd.protocolVersion,u.writeUInt32LE(l,g),g+=yd.jsonLength,u.writeUInt32LE(o,g),g+=yd.binaryLength,u.writeUInt32LE(t,g),g+=yd.fromServiceId,u.writeUInt32LE(n,g),g+=yd.toServiceId,u.writeBigInt64LE(BigInt(p),g),g+=yd.sentAt,c.copy(u,g),g+=l,s&&o&&s.copy(u,g),u},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,yd.protocolPrefix);if(t+=yd.protocolPrefix,n!==Ed)return null;if(e.byteLength<wd)return Ad(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=yd.protocolVersion;const i=e.readUInt32LE(t);t+=yd.jsonLength;const s=e.readUInt32LE(t);t+=yd.binaryLength;const o=e.readUInt32LE(t);t+=yd.fromServiceId;const a=e.readUInt32LE(t);t+=yd.toServiceId;const c=e.readBigInt64LE(t);t+=yd.sentAt;const l=i+s,d=e.subarray(t,t+l),u=e.subarray(0,wd);let p=null;return e.byteLength-wd-i-s>0&&(p=e.subarray(wd+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[d],headerPackage:u},remaining:p}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),i=md(n);if(!i?.json)return Ad("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Cd(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=wd+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<wd)return Ad("Invalid Header Size"),e;let n=0;return n+=yd.protocolPrefix,n+=yd.protocolVersion,n+=yd.jsonLength,n+=yd.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=yd.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=Sd+r,s=Buffer.alloc(i);return s.write(xd,t),t+=bd.protocolPrefix,s.writeUint32LE(r,t),t+=bd.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<Sd)return{command:null};const n=e.toString("utf-8",t,bd.protocolPrefix);if(t+=bd.protocolPrefix,n!==xd)return{command:null};const r=e.readUInt32LE(t);t+=bd.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-Sd-r;let o=null;s>0&&(o=e.subarray(Sd+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Pd="KMSG",Od="KCMD",Td=kd("klProtocol"),Ld=new TextEncoder;var Bd={encode:(e,t,n)=>{const r={json:e.json},i=_d(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=Ld.encode(a),l=c.byteLength,d=new ArrayBuffer(yd.protocolPrefix+yd.protocolVersion+yd.jsonLength+yd.binaryLength+yd.fromServiceId+yd.toServiceId+yd.sentAt+l+o),u=new DataView(d),p=new Uint8Array(d),g=Date.now();let h=0;for(let e=0;e<4;++e)p[h++]=Pd.charCodeAt(e);return u.setUint8(h,1),h+=yd.protocolVersion,u.setUint32(h,l,!0),h+=yd.jsonLength,u.setUint32(h,o,!0),h+=yd.binaryLength,u.setUint32(h,t,!0),h+=yd.fromServiceId,u.setUint32(h,n,!0),h+=yd.toServiceId,u.setBigInt64(h,BigInt(g),!0),h+=yd.sentAt,p.set(c,h),h+=l,s&&o&&p.set(new Uint8Array(s),h),d},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<yd.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Pd)return null;if(e.byteLength<wd)return Td.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=yd.protocolVersion;const s=t.getUint32(n,!0);n+=yd.jsonLength;const o=t.getUint32(n,!0);n+=yd.binaryLength;const a=t.getUint32(n,!0);n+=yd.fromServiceId;const c=t.getUint32(n,!0);n+=yd.toServiceId;const l=t.getBigInt64(n,!0);n+=yd.sentAt;const d=s+o,u=e.slice(n,n+d),p=new Uint8Array(e,0,wd);let g=null;if(e.byteLength-wd-s-o>0){g=new Uint8Array(e,wd+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[u],headerPackage:p.slice().buffer},remaining:g}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=md(s);if(!a?.json)return Td.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Cd(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,d=null;const u=wd+e.jsonLength+e.binaryLength;return c.byteLength>u&&(d=c.subarray(u),l=c.subarray(0,u)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:d?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<wd)return Td("Invalid Header Size"),e;let n=0;n+=yd.protocolPrefix,n+=yd.protocolVersion,n+=yd.jsonLength,n+=yd.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=yd.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Ld.encode(e),r=n.byteLength,i=new ArrayBuffer(Sd+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=Od.charCodeAt(e);return s.setUint32(t,r,!0),t+=bd.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Sd)return{command:null};let r="";for(let e=0;e<bd.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Od)return{command:null};const i=t.getUint32(n,!0);n+=bd.txtLength;const s=e.byteLength-Sd-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-Sd)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(Sd+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};const Dd=kd("klTransmissionManager"),jd=()=>{const e=(t,n,r,i)=>{let s=n,o=null;const a=t instanceof ArrayBuffer;if(Dd(`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=Bd.decodeHeader(c)):(c=s?.partialHeaderData?Buffer.concat([s.partialHeaderData,t]):t,o=Nd.decodeHeader(c)),!o){const{command:t,missing:s,remainingData:o}=a?Bd.decodeCommand(c):Nd.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):Dd(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?(Dd(`${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 Dd(`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;Dd(`Received ${s.header.totalBytesReceived} of ${s.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?Bd.decodeFullKlMessage(s.header):Nd.decodeFullKlMessage(s.header),c=s.header.totalBytesReceived,l=s.header.remaining;r(null),o&&i({klMessage:o.message,complete:!0,sourceServiceId:s.header.fromServiceId,targetServiceId:s.header.toServiceId,rawMessage:o.message.rawMessage});let d=l;if(o?.remaining&&(d=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),s=new Uint8Array(t),o=new Uint8Array(r);return o.set(i),o.set(s,i.length),r})(l,o.remaining):o.remaining:l?Buffer.concat([l,o.remaining]):o.remaining),d)return Dd(`${d.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(d,null,r,i)}};return e};gd.config={...gd.config,...hd};const Ud={info:Qc("ipcServer:info"),data:Qc("ipcServer:data")};let Rd,Fd,Md,Wd,Gd={};const Vd=jd(),Hd=e=>{Gd[e]&&(Ud.info(`Client disconnected [${e}]`),delete Gd[e],Fd&&Fd(e))};var zd=e=>(e?.ipcId&&(gd.config.id=e.ipcId),e?.ipcAppSpace&&(gd.config.appspace=e.ipcAppSpace),new Promise((e=>{gd.serve((()=>{Ud.info("IPC Server Initiated"),gd.server.on("data",((e,t)=>{const n=Gd[t.id];n?(Ud.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Vd(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Ud.data(`Received command from client [${t.id}]: ${e.command}`),void(Md&&Md(t.id,e.command,n));e.klMessage&&Wd&&Wd({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Ud.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),gd.server.on("connect",(e=>{const t=nl();Ud.info(`New client connected. Registered as "${t}"`),e.id=t,Gd[t]={socket:e,activeMessage:null,disconnectHandler:()=>Hd(t)},e.on("close",Gd[t].disconnectHandler),Rd&&Rd(t)})),gd.server.on("disconnect",(e=>{Hd(e.id)})),gd.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),gd.server.start()}))),qd=e=>{Rd=e},Kd=e=>{Fd=e},Jd=e=>Wd=e,Yd=(e,t)=>{const n=Gd[e];if(!n)return Ud.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=fd)return Ud.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=Nd.encodeCommand(t);return n.socket.write(r),!0},Xd=(e,t)=>{const n=Gd[e];return!!n&&(Ud.info(`Renaming socket id [${e}] to [${t}]`),delete Gd[e],n.socket.id=t,Gd[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Hd(t),n.socket.on("close",n.disconnectHandler),!0)},Zd=e=>{Md=e};let Qd=Nd;vd&&(Qd=Bd);var eu,tu=Qd;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(eu||(eu={}));let nu=Math.ceil(Date.now()/1e3);var ru={exports:{}};const iu=["nodebuffer","arraybuffer","fragments"],su="undefined"!=typeof Blob;su&&iu.push("blob");var ou={BINARY_TYPES:iu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:su,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:au}=ou,cu=Buffer[Symbol.species];function lu(e,t,n,r,i){for(let s=0;s<i;s++)n[r+s]=e[s]^t[3&s]}function du(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(ru.exports={concat:function(e,t){if(0===e.length)return au;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 cu(n.buffer,n.byteOffset,r):n},mask:lu,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 cu(t):ArrayBuffer.isView(t)?n=new cu(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:du},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");ru.exports.mask=function(t,n,r,i,s){s<48?lu(t,n,r,i,s):e.mask(t,n,r,i,s)},ru.exports.unmask=function(t,n){t.length<32?du(t,n):e.unmask(t,n)}}catch(e){}var uu=ru.exports;const pu=Symbol("kDone"),gu=Symbol("kRun");const hu=D,fu=uu,mu=class{constructor(e){this[pu]=()=>{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[pu])}}},{kStatusCode:vu}=ou,yu=Buffer[Symbol.species],bu=Buffer.from([0,0,255,255]),wu=Symbol("permessage-deflate"),Su=Symbol("total-length"),Iu=Symbol("callback"),_u=Symbol("buffers"),$u=Symbol("error");let Cu;var ku=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,!Cu){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Cu=new mu(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[Iu];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){Cu.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){Cu.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]?hu.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=hu.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[wu]=this,this._inflate[Su]=0,this._inflate[_u]=[],this._inflate.on("error",Au),this._inflate.on("data",xu)}this._inflate[Iu]=n,this._inflate.write(e),t&&this._inflate.write(bu),this._inflate.flush((()=>{const e=this._inflate[$u];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=fu.concat(this._inflate[_u],this._inflate[Su]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Su]=0,this._inflate[_u]=[],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]?hu.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=hu.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[Su]=0,this._deflate[_u]=[],this._deflate.on("data",Eu)}this._deflate[Iu]=n,this._deflate.write(e),this._deflate.flush(hu.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=fu.concat(this._deflate[_u],this._deflate[Su]);t&&(e=new yu(e.buffer,e.byteOffset,e.length-4)),this._deflate[Iu]=null,this._deflate[Su]=0,this._deflate[_u]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function Eu(e){this[_u].push(e),this[Su]+=e.length}function xu(e){this[Su]+=e.length,this[wu]._maxPayload<1||this[Su]<=this[wu]._maxPayload?this[_u].push(e):(this[$u]=new RangeError("Max payload size exceeded"),this[$u].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[$u][vu]=1009,this.removeListener("data",xu),this.reset())}function Au(e){this[wu]._inflate=null,e[vu]=1007,this[Iu](e)}var Nu={exports:{}};const{isUtf8:Pu}=j,{hasBlob:Ou}=ou;function Tu(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(Nu.exports={isBlob:function(e){return Ou&&"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:Tu,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]},Pu)Nu.exports.isValidUTF8=function(e){return e.length<24?Tu(e):Pu(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Nu.exports.isValidUTF8=function(t){return t.length<32?Tu(t):e(t)}}catch(e){}var Lu=Nu.exports;const{Writable:Bu}=B,Du=ku,{BINARY_TYPES:ju,EMPTY_BUFFER:Uu,kStatusCode:Ru,kWebSocket:Fu}=ou,{concat:Mu,toArrayBuffer:Wu,unmask:Gu}=uu,{isValidStatusCode:Vu,isValidUTF8:Hu}=Lu,zu=Buffer[Symbol.species];var qu=class extends Bu{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||ju[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Fu]=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 zu(t.buffer,t.byteOffset+e,t.length-e),new zu(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 zu(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[Du.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=Uu;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]&&Gu(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[Du.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?Mu(n,t):"arraybuffer"===this._binaryType?Wu(Mu(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=Mu(n,t);if(!this._skipUTF8Validation&&!Hu(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,Uu),this.end();else{const n=e.readUInt16BE(0);if(!Vu(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new zu(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Hu(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:Ku}=d,Ju=ku,{EMPTY_BUFFER:Yu,kWebSocket:Xu,NOOP:Zu}=ou,{isBlob:Qu,isValidStatusCode:ep}=Lu,{mask:tp,toBuffer:np}=uu,rp=Symbol("kByteLength"),ip=Buffer.alloc(4),sp=8192;let op,ap=sp;var cp=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=Zu,this[Xu]=void 0}static frame(e,t){let n,r,i=!1,s=2,o=!1;t.mask&&(n=t.maskBuffer||ip,t.generateMask?t.generateMask(n):(ap===sp&&(void 0===op&&(op=Buffer.alloc(sp)),Ku(op,0,sp),ap=0),n[0]=op[ap++],n[1]=op[ap++],n[2]=op[ap++],n[3]=op[ap++]),o=!(n[0]|n[1]|n[2]|n[3]),s=6),"string"==typeof e?r=t.mask&&!o||void 0===t[rp]?(e=Buffer.from(e)).length:t[rp]:(r=e.length,i=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(s+=8,a=127):r>125&&(s+=2,a=126);const c=Buffer.allocUnsafe(i?r+s:s);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(r,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(r,4,6)),t.mask?(c[1]|=128,c[s-4]=n[0],c[s-3]=n[1],c[s-2]=n[2],c[s-1]=n[3],o?[c,e]:i?(tp(e,n,c,s,r),[c]):(tp(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let s;if(void 0===t)s=Yu;else{if("number"!=typeof t||!ep(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==n&&n.length){const e=Buffer.byteLength(n);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+e),s.writeUInt16BE(t,0),"string"==typeof n?s.write(n,2):s.set(n,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0)}const o={[rp]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(e.frame(s,o),i)}ping(t,n,r){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):Qu(t)?(i=t.size,s=!1):(i=(t=np(t)).length,s=np.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[rp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};Qu(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):Qu(t)?(i=t.size,s=!1):(i=(t=np(t)).length,s=np.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[rp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};Qu(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[Ju.extensionName];let i,s,o=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):Qu(e)?(i=e.size,s=!1):(i=(e=np(e)).length,s=np.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=i>=r._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0);const c={[rp]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:s,rsv1:a};Qu(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):0!==this._state?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(t,n,r,i){this._bufferedBytes+=r[rp],this._state=2,t.arrayBuffer().then((t=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(lp,this,e,i)}this._bufferedBytes-=r[rp];const s=np(t);n?this.dispatch(s,n,r,i):(this._state=0,this.sendFrame(e.frame(s,r),i),this.dequeue())})).catch((e=>{process.nextTick(dp,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const s=this._extensions[Ju.extensionName];this._bufferedBytes+=r[rp],this._state=1,s.compress(t,r.fin,((t,n)=>{if(this._socket.destroyed){lp(this,new Error("The socket was closed while data was being compressed"),i)}else this._bufferedBytes-=r[rp],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][rp],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][rp],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function lp(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 dp(e,t,n){lp(e,t,n),e.onerror(t)}const{kForOnEventAttribute:up,kListener:pp}=ou,gp=Symbol("kCode"),hp=Symbol("kData"),fp=Symbol("kError"),mp=Symbol("kMessage"),vp=Symbol("kReason"),yp=Symbol("kTarget"),bp=Symbol("kType"),wp=Symbol("kWasClean");class Sp{constructor(e){this[yp]=null,this[bp]=e}get target(){return this[yp]}get type(){return this[bp]}}Object.defineProperty(Sp.prototype,"target",{enumerable:!0}),Object.defineProperty(Sp.prototype,"type",{enumerable:!0});class Ip extends Sp{constructor(e,t={}){super(e),this[gp]=void 0===t.code?0:t.code,this[vp]=void 0===t.reason?"":t.reason,this[wp]=void 0!==t.wasClean&&t.wasClean}get code(){return this[gp]}get reason(){return this[vp]}get wasClean(){return this[wp]}}Object.defineProperty(Ip.prototype,"code",{enumerable:!0}),Object.defineProperty(Ip.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ip.prototype,"wasClean",{enumerable:!0});class _p extends Sp{constructor(e,t={}){super(e),this[fp]=void 0===t.error?null:t.error,this[mp]=void 0===t.message?"":t.message}get error(){return this[fp]}get message(){return this[mp]}}Object.defineProperty(_p.prototype,"error",{enumerable:!0}),Object.defineProperty(_p.prototype,"message",{enumerable:!0});class $p extends Sp{constructor(e,t={}){super(e),this[hp]=void 0===t.data?null:t.data}get data(){return this[hp]}}Object.defineProperty($p.prototype,"data",{enumerable:!0});const Cp={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[up]&&r[pp]===t&&!r[up])return;let r;if("message"===e)r=function(e,n){const r=new $p("message",{data:n?e:e.toString()});r[yp]=this,Ep(t,this,r)};else if("close"===e)r=function(e,n){const r=new Ip("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[yp]=this,Ep(t,this,r)};else if("error"===e)r=function(e){const n=new _p("error",{error:e,message:e.message});n[yp]=this,Ep(t,this,n)};else{if("open"!==e)return;r=function(){const e=new Sp("open");e[yp]=this,Ep(t,this,e)}}r[up]=!!n[up],r[pp]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[pp]===t&&!n[up]){this.removeListener(e,n);break}}};var kp={CloseEvent:Ip,ErrorEvent:_p,Event:Sp,EventTarget:Cp,MessageEvent:$p};function Ep(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:xp}=Lu;function Ap(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var Np={format:function(e){return Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>[t].concat(Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let n,r,i=Object.create(null),s=!1,o=!1,a=!1,c=-1,l=-1,d=-1,u=0;for(;u<e.length;u++)if(l=e.charCodeAt(u),void 0===n)if(-1===d&&1===xp[l])-1===c&&(c=u);else if(0===u||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u);const r=e.slice(c,d);44===l?(Ap(t,r,i),i=Object.create(null)):n=r,c=d=-1}}else-1===d&&-1!==c&&(d=u);else if(void 0===r)if(-1===d&&1===xp[l])-1===c&&(c=u);else if(32===l||9===l)-1===d&&-1!==c&&(d=u);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u),Ap(i,e.slice(c,d),!0),44===l&&(Ap(t,n,i),i=Object.create(null),n=void 0),c=d=-1}else{if(61!==l||-1===c||-1!==d)throw new SyntaxError(`Unexpected character at index ${u}`);r=e.slice(c,u),c=d=-1}else if(o){if(1!==xp[l])throw new SyntaxError(`Unexpected character at index ${u}`);-1===c?c=u:s||(s=!0),o=!1}else if(a)if(1===xp[l])-1===c&&(c=u);else if(34===l&&-1!==c)a=!1,d=u;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${u}`);o=!0}else if(34===l&&61===e.charCodeAt(u-1))a=!0;else if(-1===d&&1===xp[l])-1===c&&(c=u);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u);let o=e.slice(c,d);s&&(o=o.replace(/\\/g,""),s=!1),Ap(i,r,o),44===l&&(Ap(t,n,i),i=Object.create(null),n=void 0),r=void 0,c=d=-1}}else-1===d&&(d=u);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===d&&(d=u);const p=e.slice(c,d);return void 0===n?Ap(t,p,i):(void 0===r?Ap(i,p,!0):Ap(i,r,s?p.replace(/\\/g,""):p),Ap(t,n,i)),t}};const Pp=U,Op=R,Tp=F,Lp=N,Bp=P,{randomBytes:Dp,createHash:jp}=d,{URL:Up}=M,Rp=ku,Fp=qu,Mp=cp,{isBlob:Wp}=Lu,{BINARY_TYPES:Gp,EMPTY_BUFFER:Vp,GUID:Hp,kForOnEventAttribute:zp,kListener:qp,kStatusCode:Kp,kWebSocket:Jp,NOOP:Yp}=ou,{EventTarget:{addEventListener:Xp,removeEventListener:Zp}}=kp,{format:Qp,parse:eg}=Np,{toBuffer:tg}=uu,ng=3e4,rg=Symbol("kAborted"),ig=[8,13],sg=["CONNECTING","OPEN","CLOSING","CLOSED"],og=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let ag=class e extends Pp{constructor(t,n,r){super(),this._binaryType=Gp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Vp,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]),lg(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Gp.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 Fp({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Mp(t,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=t,i[Jp]=this,s[Jp]=this,t[Jp]=this,i.on("conclude",fg),i.on("drain",mg),i.on("error",vg),i.on("message",bg),i.on("ping",wg),i.on("pong",Sg),s.onerror=_g,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",Cg),t.on("data",kg),t.on("end",Eg),t.on("error",xg),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[Rp.extensionName]&&this._extensions[Rp.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())})),$g(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";gg(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||Vp,n,r)):hg(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||Vp,n,r)):hg(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 hg(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Rp.extensionName]||(i.compress=!1),this._sender.send(t||Vp,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";gg(this,this._req,e)}}};Object.defineProperty(ag,"CONNECTING",{enumerable:!0,value:sg.indexOf("CONNECTING")}),Object.defineProperty(ag.prototype,"CONNECTING",{enumerable:!0,value:sg.indexOf("CONNECTING")}),Object.defineProperty(ag,"OPEN",{enumerable:!0,value:sg.indexOf("OPEN")}),Object.defineProperty(ag.prototype,"OPEN",{enumerable:!0,value:sg.indexOf("OPEN")}),Object.defineProperty(ag,"CLOSING",{enumerable:!0,value:sg.indexOf("CLOSING")}),Object.defineProperty(ag.prototype,"CLOSING",{enumerable:!0,value:sg.indexOf("CLOSING")}),Object.defineProperty(ag,"CLOSED",{enumerable:!0,value:sg.indexOf("CLOSED")}),Object.defineProperty(ag.prototype,"CLOSED",{enumerable:!0,value:sg.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(ag.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(ag.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[zp])return t[qp];return null},set(t){for(const t of this.listeners(e))if(t[zp]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[zp]:!0})}})})),ag.prototype.addEventListener=Xp,ag.prototype.removeEventListener=Zp;var cg=ag;function lg(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:ig[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,!ig.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${ig.join(", ")})`);let s;if(t instanceof Up)s=t;else try{s=new Up(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 dg(e,t)}const l=o?443:80,d=Dp(16).toString("base64"),u=o?Op.request:Tp.request,p=new Set;let g,h;if(i.createConnection=i.createConnection||(o?pg:ug),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(g=new Rp(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Qp({[Rp.extensionName]:g.offer()})),n.length){for(const e of n){if("string"!=typeof e||!og.test(e)||p.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(e)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?i.socketPath:s.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),h=e._req=u(i),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=u(i);i.timeout&&h.on("timeout",(()=>{gg(e,h,"Opening handshake has timed out")})),h.on("error",(t=>{null===h||h[rg]||(h=e._req=null,dg(e,t))})),h.on("response",(s=>{const o=s.headers.location,a=s.statusCode;if(o&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void gg(e,h,"Maximum redirects exceeded");let s;h.abort();try{s=new Up(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void dg(e,n)}lg(e,s,n,r)}else e.emit("unexpected-response",h,s)||gg(e,h,`Unexpected server response: ${s.statusCode}`)})),h.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==ag.CONNECTING)return;h=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void gg(e,n,"Invalid Upgrade header");const o=jp("sha1").update(d+Hp).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void gg(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 gg(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!g){return void gg(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=eg(l)}catch(t){return void gg(e,n,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==Rp.extensionName){return void gg(e,n,"Server indicated an extension that was not requested")}try{g.accept(t[Rp.extensionName])}catch(t){return void gg(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Rp.extensionName]=g}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(h,e):h.end()}function dg(e,t){e._readyState=ag.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function ug(e){return e.path=e.socketPath,Lp.connect(e)}function pg(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Lp.isIP(e.host)?"":e.host),Bp.connect(e)}function gg(e,t,n){e._readyState=ag.CLOSING;const r=new Error(n);Error.captureStackTrace(r,gg),t.setHeader?(t[rg]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(dg,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function hg(e,t,n){if(t){const n=Wp(t)?t.size:tg(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${sg[e.readyState]})`);process.nextTick(n,t)}}function fg(e,t){const n=this[Jp];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[Jp]&&(n._socket.removeListener("data",kg),process.nextTick(Ig,n._socket),1005===e?n.close():n.close(e,t))}function mg(){const e=this[Jp];e.isPaused||e._socket.resume()}function vg(e){const t=this[Jp];void 0!==t._socket[Jp]&&(t._socket.removeListener("data",kg),process.nextTick(Ig,t._socket),t.close(e[Kp])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function yg(){this[Jp].emitClose()}function bg(e,t){this[Jp].emit("message",e,t)}function wg(e){const t=this[Jp];t._autoPong&&t.pong(e,!this._isServer,Yp),t.emit("ping",e)}function Sg(e){this[Jp].emit("pong",e)}function Ig(e){e.resume()}function _g(e){const t=this[Jp];t.readyState!==ag.CLOSED&&(t.readyState===ag.OPEN&&(t._readyState=ag.CLOSING,$g(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function $g(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),ng)}function Cg(){const e=this[Jp];let t;this.removeListener("close",Cg),this.removeListener("data",kg),this.removeListener("end",Eg),e._readyState=ag.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Jp]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",yg),e._receiver.on("finish",yg))}function kg(e){this[Jp]._receiver.write(e)||this.pause()}function Eg(){const e=this[Jp];e._readyState=ag.CLOSING,e._receiver.end(),this.end()}function xg(){const e=this[Jp];this.removeListener("error",xg),this.on("error",Yp),e&&(e._readyState=ag.CLOSING,this.destroy())}const{tokenChars:Ag}=Lu;var Ng={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===Ag[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 Pg=U,Og=F,{createHash:Tg}=d,Lg=Np,Bg=ku,Dg=Ng,jg=cg,{GUID:Ug,kWebSocket:Rg}=ou,Fg=/^[+/0-9A-Za-z]{22}==$/;var Mg=class extends Pg{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:jg,...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=Og.createServer(((e,t)=>{const n=Og.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(Wg,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(Wg,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Wg(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",Gg);const i=e.headers["sec-websocket-key"],s=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Hg(this,e,t,405,"Invalid HTTP method")}if(void 0===s||"websocket"!==s.toLowerCase()){return void Hg(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!Fg.test(i)){return void Hg(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void Hg(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Vg(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=Dg.parse(a)}catch(n){return void Hg(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&void 0!==l){const n=new Bg(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Lg.parse(l);e[Bg.extensionName]&&(n.accept(e[Bg.extensionName]),d[Bg.extensionName]=n)}catch(n){return void Hg(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 Vg(t,o||401,a,l);this.completeUpgrade(d,i,c,e,t,n,r)}));if(!this.options.verifyClient(s))return Vg(t,401)}this.completeUpgrade(d,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,s,o){if(!i.readable||!i.writable)return i.destroy();if(i[Rg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Vg(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Tg("sha1").update(t+Ug).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[Bg.extensionName]){const t=e[Bg.extensionName].params,n=Lg.format({[Bg.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",Gg),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(Wg,this)}))),o(c,r)}};function Wg(e){e._state=2,e.emit("close")}function Gg(){this.destroy()}function Vg(e,t,n,r){n=n||Og.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} ${Og.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function Hg(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,Hg),e.emit("wsClientError",r,n,t)}else Vg(n,r,i)}var zg=Bc(Mg);const qg=Qc("websocketServer"),Kg={},Jg=jd();let Yg,Xg,Zg,Qg,eh;const th=e=>{const t=Kg[e];t&&t.socket.close()};var nh={startServer:e=>{eh=new zg({port:e,maxPayload:1048576e3}),eh.on("connection",(e=>{const t=nl();qg(`New client connected. Registered as "${t}"`),e.id=t,Kg[t]={socket:e,activeMessage:null},Yg&&Yg(t),e.on("message",(t=>{if(t instanceof Buffer){const n=Kg[e.id];Jg(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),qg(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{th(n.socket.id)};if(t.command)return qg(`Received command from client [${n.socket.id}]: ${t.command}`),void(Zg&&Zg(n.socket.id,t.command,r,i));t.klMessage&&Qg&&Qg({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",(()=>{qg(`Client disconnected: ${e.id}`),Xg&&Xg(e.id),delete Kg[e.id]})),e.on("error",(()=>{qg(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},stopServer:()=>{eh.close((()=>{console.log("WebSocket server stopped")}))},onClientConnected:e=>{Yg=e},onClientDisconnected:e=>{Xg=e},onClientCommand:e=>{Zg=e},sendCommand:(e,t)=>{const n=Kg[e];if(!n)return qg(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=fd)return qg("Message is too long to be a command. Use sendMessage instead."),!1;const r=Nd.encodeCommand(t);return n.socket.send(r),!0},onMessageReceived:e=>Qg=e,terminateConnection:th};const rh=Qc("stopService"),ih=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Tl.getAllServiceVersions(t);rh(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Tl.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},sh=Qc("removeService"),oh=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Tl.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),sh(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Tl.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},ah=Qc("launchService"),ch=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=fl();ah(`Loading service ${t}@${n} from ${i}`);const{errorMsg:s,service:o,errorCode:a}=await Tl.loadAndLaunch(i,r,!1);if(s||"started"!==o?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${s||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,d=async()=>{const r=o.status;return"running"===r?(ah(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(ah(`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"}):(ah("Retrying in 1 second..."),void setTimeout(d,1e3)))};d()}catch(r){return ah(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},lh=Qc("getMatchingServices"),dh=async e=>{const t=e.args[0],n=[],r=[];lh(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=Tl.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:Tl.getServiceRootDirectory(t)}):r.push({name:e,version:i})}lh(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},uh=Qc("getSecretsValues");let ph;var gh=async e=>{const t=e.args[0].services;if(!ph)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");uh(`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 ph({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})},hh=e=>{ph=e};const fh=Qc("getMappedSecrets");let mh;var vh=async e=>{const t=e.args[0].services;fh(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await mh(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})},yh=e=>{mh=e};const bh=Qc("getServiceContents"),wh=({reply:e,args:t})=>{const[n]=t;bh(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Tl.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}]})}bh(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let Sh={globalApiKey:void 0};const Ih=()=>({...Sh}),_h=()=>{const e=Ih();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},$h=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}}},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(async e=>{const{data:t,error:n}=await $h(`${_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"}})(e);return n&&(Ch[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}},Eh=Qc("activeClients");let xh={},Ah={};const Nh=(e,t)=>`${e}_${t}`,Ph=e=>xh[e]||null,Oh=(e,t)=>{const n=Nh(e,t);return Ah[n]||[]},Th=()=>{for(const e in xh){const t=xh[e];if(t?.transport===vc.WS){const e=Nd.encodeCommand(hc.ServicesListChanged);t.send(e)}}},Lh=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===vc.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=Tl.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=Ph(t.info.sessionId);e?.extraInfo.ipcSocketId&&Yd(e?.extraInfo.ipcSocketId,hc.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===vc.IPC&&(Th(),Dh(n))},Bh=()=>{const e=Object.values(xh);for(const t of e)if(t.transport===vc.IPC){const e=t.extraInfo.ipcSocketId,n=Tl.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){Oh(n.info.name,n.info.version).length||e&&Yd(e,hc.BroadcastEnd)}}},Dh=e=>{const t=Tl.getServiceBySessionId(e);if(t?.info.eventEmitter){if(Oh(t.info.name,t.info.version).length){const t=Ph(e);t?.extraInfo.ipcSocketId&&Yd(t?.extraInfo.ipcSocketId,hc.BroadcastStart)}}},jh=e=>{const t=xh[e];delete xh[e],t?.transport===vc.IPC?Th():(t?.removeAllSubscriptions(),Bh())},Uh=Qc("ipc:handleIpcClientCommand"),Rh=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(hc.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&&(Xd(e,t),r=t);let i=!1;t&&(i=Tl.setServiceStatus(t,"running")),i?Lh({serviceSessionId:t||e,transport:vc.IPC,send:n,extraInfo:{ipcSocketId:t}}):Yd(r,hc.SendManifest)}));!r&&Uh(`Received unknown command [${t}] from service ${e}`)};let Fh={};G.platform();const Mh=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 df=(e,t,n)=>e>>>n|t<<32-n;tf.rotrSH=df;const uf=(e,t,n)=>e<<32-n|t>>>n;tf.rotrSL=uf;const pf=(e,t,n)=>e<<64-n|t>>>n-32;tf.rotrBH=pf;const gf=(e,t,n)=>e>>>n-32|t<<64-n;tf.rotrBL=gf;const hf=(e,t)=>t;tf.rotr32H=hf;const ff=e=>e;tf.rotr32L=ff;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 wf(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=wf;const Sf=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);tf.add3L=Sf;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:df,rotrSL:uf,rotrBH:pf,rotrBL:gf,rotr32H:hf,rotr32L:ff,rotlSH:mf,rotlSL:vf,rotlBH:yf,rotlBL:bf,add:wf,add3L:Sf,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"emittery";import"axios";import a from"jszip";import c from"util";import l from"mustache";import d,{scryptSync as u,createDecipheriv as p,createHash as g}from"crypto";import{satisfies as h}from"compare-versions";import f from"debug";import m,{join as y,dirname as v,resolve as b}from"path";import"node-ipc";import{mkdir as w,readFile as S,access as I,constants as $,readdir as _,rm as C}from"fs/promises";import k from"minimist";import E from"tty";import x,{homedir as N}from"os";import A from"net";import P from"tls";import O,{promises as T}from"fs";import L from"dgram";import B from"stream";import D from"zlib";import j from"buffer";import U from"events";import R from"https";import F from"http";import M,{fileURLToPath as W}from"url";import G from"node:os";import{spawn as V}from"child_process";import{join as H,resolve as z,dirname as q}from"node:path";import{ImageData as K,loadImage as J,createCanvas as Y}from"@napi-rs/canvas";var X;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(X=X||(X={}));const Z="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,Q="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,ee="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,te={};let ne=0,re="";const ie=e=>te[e]?te[e]:null,se=(e,t)=>{const n=ie(e);if(!n)return n;return n.blocks[t]||null},oe=(e,t,n)=>{const r=se(e,t);if(!r)return r;return r.gates[n]},ae=(e,t)=>{let n=r(4);for(;te[n];)n=r(4);const i=(s=e,JSON.parse(JSON.stringify(s)));var s;return i.logs="",i.addLog=e=>{i.logs+=`${(()=>{const e=Date.now();if(e!==ne){const t=new Date;ne=e,re=t.toJSON()}return re})()}:: ${e}\n`},i.dbInfo={...t},te[n]=i,n},ce="interrupt_port",le="main.js",de="state.json",ue="{#}",pe="UI:",ge="default";var he,fe,me,ye,ve,be,we,Se;let Ie;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(he||(he={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(fe||(fe={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(me||(me={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ye||(ye={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(ve||(ve={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(be||(be={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(we||(we={})),function(e){e.IPC="ipc",e.WS="ws"}(Se||(Se={}));const $e=()=>{if(!Ie)throw new Error("CanvasManager not set");return Ie},_e=e=>{Ie=e},Ce=(e,t)=>$e().createCanvas(e,t),ke=e=>Z?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Ee=e=>$e().loadImage(e),xe="-",Ne=`inner${xe}`,Ae=`outer${xe}`,Pe=`${Ae}input${xe}`,Oe=`${Ae}output${xe}`,Te=`${Ne}input${xe}`,Le=`${Ne}output${xe}`,Be=e=>(new TextEncoder).encode(e),De=e=>e===ce,je=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Ue=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.top&&void 0!==e.left&&"number"==typeof e.width&&"number"==typeof e.height&&"number"==typeof e.top&&"number"==typeof e.left,Re=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Fe=e=>"number"==typeof e?fe.Number:"string"==typeof e?fe.String:"boolean"==typeof e?fe.Boolean:Array.isArray(e)?fe.Array:je(e)?fe.ImageData:e&&void 0!==e.duration&&void 0!==e.length&&void 0!==e.numberOfChannels&&void 0!==e.sampleRate&&"function"==typeof e.getChannelData&&"AudioBuffer"===e.constructor.name?fe.AudioBuffer:e&&void 0!==e.byteLength?fe.ArrayBuffer:Ue(e)?fe.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?fe.Point:(e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer)(e)?fe.BinaryFile:fe.JsonObj,Me=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Fe(n[e]);t[e]=r}return t},We=(e,t,n)=>"inner"===e?"input"===t?`${Te}${n}`:`${Le}${n}`:"input"===t?`${Pe}${n}`:`${Oe}${n}`,Ge=e=>{const t=(e||"")?.split("_");if(t.length<3)throw new Error(`Unknown child identifier format [${e}]`);const n=t[0];return{portType:t[1],widgetId:n,portName:t[2]}},Ve=async e=>{try{return new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace})}catch(t){console.warn("Failed to create ImageData from info, assuming raw image data",t);return await Ee(e.data)}};var He,ze;!function(e){e.Action="action",e.CustomInput="customInput"}(He=He||(He={})),function(e){e.input="input",e.counter="counter",e.play="play",e.elapsed="elapsed",e.ifGate="ifGate",e.skipEvent="skipEvent",e.between="between",e.map="map",e.parser="parser",e.slider="slider",e.suspend="suspend",e.display="display",e.json="json",e.arrayItem="arrayItem",e.extractImage="extractImage",e.imageConvolution="imageConvolution",e.firstEvent="firstEvent",e.pixelDraw="pixelDraw",e.randomBetween="randomBetween",e.arrayCombine="arrayCombine",e.clock="clock",e.multiplication="multiplication",e.object="object",e.widgetGroup="widgetGroup",e.script="script",e.base64ToImageData="base64ToImageData",e.jsonParse="jsonParse",e.text="text",e.imageCrop="imageCrop",e.imageResize="imageResize",e.value="value",e.imageWarp="imageWarp",e.widgetBundle="widgetBundle",e.sequence="sequence",e.variable="variable",e.hubService="hubService",e.imageFilter="imageFilter",e.recipeLoad="recipeLoad",e.note="note",e.stringify="stringify",e.templateString="templateString",e.expressionEval="expressionEval",e.rescue="rescue"}(ze=ze||(ze={}));const qe={};let Ke;const Je=async e=>{const t=qe[e],n={name:ce,type:fe.Boolean};if(t){const r={name:t.portName},i=t.data||{type:fe.Boolean,value:!0};Ke?(await Ke(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...i,timestamp:Date.now()},[n]),"timeout"===t.type&&Ye(e)):console.warn("Interrupt service has not been initialized")}},Ye=e=>{const t=qe[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete qe[e],!0)};var Xe={interruptHandler:Je,createInterrupt:(e,t,n,i,s,o,a,c)=>{if(c&&qe[c])throw new Error("The given interrupt id already exists");const l=c||r().replace(/_/g,"-");if("interval"===e&&!o.interval)throw new Error(`Invalid interval. Expected a number greater than 0, but got '${o.interval}'`);if("timeout"===e&&!o.timeout)throw new Error(`Invalid timeout. Expected a number greater than 0, but got '${o.timeout}'`);if(qe[l]={data:a,portName:s,recipePoolId:t,targetWidgetId:i,thingId:n,type:e},"interval"===e)qe[l].timerRef=setInterval((async()=>await Je(l)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);qe[l].timerRef=setTimeout((async()=>await Je(l)),o.timeout)}return l},destroyInterrupt:Ye,destroyAllInterrupts:()=>{Object.keys(qe).forEach(Ye)},setInvokeChildGateCb:e=>{Ke=e}};const Ze=[10001,"Invalid `sourcePort` parameter"],Qe=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],et=[10110,"No storage medium has been loaded, call `loadMedium()` first"],tt=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?c.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),nt=()=>({inputName:"",dataType:fe.Anything}),rt="output",it={processEvent:async(e,t)=>{const n=t.getState(),r={...nt(),...n};if(e.type===r.dataType||r.dataType===fe.Anything)return t.nextWidget(rt,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...nt(),...e};return[{name:rt,type:t.dataType}]},getInputNames:()=>[]},st=Object.freeze({in:"in",reset:"reset",increment:"increment"}),ot="output";var at={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(tt(Ze));const i={currentValue:0,increment:1,...r.getState()};let s=i.increment,o=i.currentValue;const a=await r.getParentAtPort(st.increment);if(t.name===st.increment)return void(n.data.type===fe.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(s=e)}if(t.name===st.reset)return r.setState({...i,currentValue:0});o+=s,r.setState({currentValue:o,increment:s});const c={type:fe.Number,value:o};return r.nextGate(ot,c)},getInputNames:()=>[{name:st.in,type:fe.Anything},{name:st.reset,type:fe.Anything},{name:st.increment,type:fe.Number}],getOutputNames:()=>[{name:ot,type:fe.Number}]};const ct=Object.freeze({in:"in",reset:"reset"}),lt="output";var dt={onParentEvent:async(e,t,n,r)=>{const i={updatedAt:0,elapsed:0,...r.getState()},s=Date.now(),o=s-(i.updatedAt||s);return t.name===ct.reset?r.setState({...i,updatedAt:s,elapsed:0}):(r.setState({updatedAt:s,elapsed:o}),r.nextGate(lt,{type:fe.Number,value:o}))},getInputNames:()=>[{name:ct.in,type:fe.Anything},{name:ct.reset,type:fe.Anything}],getOutputNames:()=>[{name:lt,type:fe.Number}]};const ut=Object.freeze({data:"data",evaluation:"evaluation"}),pt="then",gt="else";var ht={onParentEvent:async(e,t,n,r)=>{const i={value:5,condition:"Equal",useDataPort:!1,...r.getState()},s=n.data.value,o=!isNaN(Number(s)),a="string"==typeof s;if(!i.useDataPort&&(n.data.type===fe.Number||n.data.type===fe.String||n.data.type===fe.Boolean||n.data.type===fe.Anything&&o||n.data.type===fe.Anything&&a)){let e=!1;return("Equal"===i.condition&&(n.data.value==i.value||n.data.type===fe.Boolean&&n.data.value.toString()===i.value.toString())||"Not Equal"===i.condition&&(n.data.value!==i.value||n.data.type===fe.Boolean&&n.data.value!==i.value.toString())||"Greater"===i.condition&&n.data.type===fe.Number&&n.data.value>Number(i.value)||"Less"===i.condition&&n.data.type===fe.Number&&n.data.value<Number(i.value)||"Starts With"===i.condition&&String(n.data.value).startsWith(String(i.value))||"Ends With"===i.condition&&String(n.data.value).endsWith(String(i.value))||"Includes"===i.condition&&String(n.data.value).includes(String(i.value))||"Matches"===i.condition&&String(n.data.value).match(String(i.value)))&&(e=!0),e?r.nextGate(pt,n.data):r.nextGate(gt,n.data)}if(t.name===ut.evaluation&&(n.data.type===fe.Number||n.data.type===fe.String||n.data.type===fe.Boolean||n.data.type===fe.Anything&&(o||a))&&(i.$lastValue=n.data.value,i.$lastInputDataType=n.data.type,r.setState({...i})),t.name===ut.data){let e=!1;return("Equal"===i.condition&&(i.$lastValue==i.value||i.$lastInputDataType===fe.Boolean&&i.$lastValue?.toString()===i.value.toString())||"Not Equal"===i.condition&&(i.$lastValue!==i.value||i.$lastInputDataType===fe.Boolean&&i.$lastValue!==i.value.toString())||"Greater"===i.condition&&i.$lastInputDataType===fe.Number&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&i.$lastInputDataType===fe.Number&&Number(i.$lastValue)<Number(i.value)||"Starts With"===i.condition&&String(i.$lastValue).startsWith(String(i.value))||"Ends With"===i.condition&&String(i.$lastValue).endsWith(String(i.value))||"Includes"===i.condition&&String(i.$lastValue).includes(String(i.value))||"Matches"===i.condition&&String(i.$lastValue).match(String(i.value)))&&(e=!0),r.setState({...i,$lastValue:void 0,$lastInputDataType:void 0}),e?r.nextGate(pt,n.data):r.nextGate(gt,n.data)}},getInputNames:e=>e.useDataPort?[{name:ut.data,type:fe.Anything,triggerPort:!0},{name:ut.evaluation,type:[fe.Number,fe.String,fe.Boolean]}]:[{name:"in",type:[fe.Number,fe.String,fe.Boolean]}],getOutputNames:e=>e.$lastOutputDataType?[{name:pt,type:e.$lastOutputDataType},{name:gt,type:e.$lastOutputDataType}]:[{name:pt,type:[fe.Number,fe.String]},{name:gt,type:[fe.Number,fe.String]}]};const ft=Object.freeze({in:"in",reset:"reset"}),mt="out";var yt={onParentEvent:async(e,t,n,r)=>{const i={totalCalls:0,callsLimit:1,...r.getState()};return t.name===ft.reset?r.setState({...i,totalCalls:0}):(i.totalCalls=i.totalCalls+1,i.totalCalls>i.callsLimit?(i.totalCalls=0,r.setState(i),r.nextGate(mt,n.data)):void r.setState(i))},getInputNames:()=>[{name:ft.in,type:fe.Anything},{name:ft.reset,type:fe.Anything}],getOutputNames:()=>[{name:mt,type:fe.Anything}]};const vt=Object.freeze({in:"in"}),bt="then",wt="else";var St={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:10,...r.getState()};if(n.data.type===fe.Number)return n.data.value>=i.min&&n.data.value<=i.max?r.nextGate(bt,n.data):r.nextGate(wt,n.data)},getInputNames:()=>[{name:vt.in,type:fe.Number}],getOutputNames:()=>[{name:bt,type:fe.Number},{name:wt,type:fe.Number}]};const It=Object.freeze({in:"in"}),$t="out";var _t={onParentEvent:async(e,t,n,r)=>{const i={clamp:!0,...r.getState()},s=Number(n.data.value);if(void 0!==i.fromMax&&void 0!==i.fromMin&&void 0!==i.toMax&&void 0!==i.toMin&&""!==i.fromMax&&""!==i.fromMin&&""!==i.toMax&&""!==i.toMin&&(n.data.type===fe.Number||n.data.type===fe.Anything&&!isNaN(Number(s)))){let e=((e,t,n,r,i)=>(e-t)*(i-r)/(n-t)+r)(s,Number(i.fromMin),Number(i.fromMax),Number(i.toMin),Number(i.toMax));if(isNaN(e))return;return i.clamp&&(e<Number(i.toMin)&&(e=Number(i.toMin)),e>Number(i.toMax)&&(e=Number(i.toMax))),r.nextGate($t,{type:fe.Number,value:Number(e)})}},getInputNames:()=>[{name:It.in,type:fe.Number}],getOutputNames:()=>[{name:$t,type:fe.Number}]};const Ct=Object.freeze({in:"in"}),kt="out";var Et={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let s=n.data.value;if(n.data.type===fe.Number||n.data.type===fe.Anything||n.data.type===fe.String){if((!isNaN(Number(s))||"string"==typeof s)&&!Array.isArray(s))return"Integer"===i.convertTo?s=parseInt(s):"Decimal"===i.convertTo?s=parseFloat(Number(s).toFixed(i.floatPlaces)):"String"===i.convertTo?s=String(s):"Abs"===i.convertTo?s=Math.abs(Number(s)):"Round"===i.convertTo&&(s=Math.round(Number(s))),r.nextGate(kt,{type:"String"===i.convertTo?fe.String:fe.Number,value:s})}},getInputNames:()=>[{name:Ct.in,type:fe.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?fe.String:fe.Number;return[{name:kt,type:t}]}};const xt=Object.freeze({in:"in"}),Nt="out";var At={onParentEvent:async(e,t,n,r)=>{const i={currentValue:50,min:0,max:100,...r.getState()};let s=!1;return i.currentValue<i.min&&(i.currentValue=i.min,s=!0),i.currentValue>i.max&&(i.currentValue=i.max,s=!0),s&&r.setState(i),r.nextWidget(Nt,{type:fe.Number,value:i.currentValue})},getInputNames:()=>[{name:xt.in,type:fe.Anything}],getOutputNames:()=>[{name:Nt,type:fe.Number}]};const Pt=Object.freeze({in:"in",reset:"reset"}),Ot="out";var Tt={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},s={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Pt.reset)return r.setState({...s,lastCalledAt:0});const o=Date.now(),a=o-s.lastCalledAt;return s.lastCalledAt===i.lastCalledAt||a>=s.delayMs&&s.delayMs>0?(s.lastCalledAt=o,r.setState(s),r.nextGate(Ot,n.data)):void 0},getInputNames:()=>[{name:Pt.in,type:fe.Anything},{name:Pt.reset,type:fe.Anything}],getOutputNames:()=>[{name:Ot,type:fe.Anything}]};const Lt="in";var Bt={onParentEvent:async()=>{},getInputNames:()=>[{name:Lt,type:[fe.ImageData,fe.Number]}],getOutputNames:()=>[]};const Dt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),jt=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var Ut={onParentEvent:async(e,t,n,r)=>{const i={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},s=n?.data?.value,o=Array.isArray(s);if(n.data.type===fe.JsonObj||n.data.type===fe.Rect||n.data.type===fe.Point||n.data.type===fe.BinaryFile||n.data.type===fe.Anything||o){let e=!1;for(const t in s){const n=Fe(s[t]),r=!!i.detectedProperties[t],o=i.detectedProperties[t]?.type!==n;if(!r||o){const r=n===fe.JsonObj||n===fe.Rect||n===fe.Point||n===fe.Array;i.detectedProperties[t]={type:n,...r?{shape:Me(s[t])}:void 0},e=!0}}if(o&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:fe.Number}),e&&r.setState(i),s){const e=[];for(const t of i.properties||[]){const n=jt(s,t.label),o=t.label.includes(".");if(void 0!==n){const s=o?Fe(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:fe.Anything;e.push(r.nextGate(t.name,{type:s,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:fe.JsonObj}],getOutputNames:e=>{const t={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...e};return t.properties.map((e=>{const n=void 0!==t.detectedProperties[e.label]?t.detectedProperties[e.label]?.type:fe.Anything,r=t.detectedProperties[e.label]?.shape||void 0,i="string"==typeof e;return{name:i?e:e.name,label:i?e:e.label,type:n,jsonShape:r}}))},getDefaultState:Dt};const Rt="output",Ft="noItem";var Mt={onParentEvent:async(e,t,n,r)=>{const i={index:0,...r.getState()};let s=i.index;const o=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===fe.Anything&&(c||a)||n.data.type===fe.String&&a||n.data.type===fe.Array&&c){s<0&&(s=o.length+s);const e=a?fe.String:Fe(o[s]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==o[s]?r.nextGate(Rt,{value:o[s],type:e}):r.nextGate(Ft,{value:!0,type:fe.Boolean})}},getInputNames:()=>[{name:"in",type:[fe.Array,fe.String]}],getOutputNames:e=>[{name:Rt,type:e.$$lastDetectedType??fe.Anything},{name:Ft,type:fe.Boolean}]};const Wt=Object.freeze({image:"image",rect:"rect"}),Gt="image";var Vt={onParentEvent:async(e,t,n,r)=>{const i={offset:{height:0,left:0,top:0,width:0},...r.getState()},s=await r.getParentAtPort(Wt.rect),o=[fe.Anything,fe.Rect,fe.JsonObj];if(t.name!==Wt.rect){if(s){const e=s.getValue();null!==e&&(i.rect={...e},r.setState(i))}if(!Z)return n.data.type===fe.ImageData?r.nextGate(Gt,n.data):void 0;if(i.$$canvasFrom&&i.$$canvasFrom.getContext||(i.$$canvasFrom=Ce(320,240)),i.$$canvasTo&&i.$$canvasTo.getContext||(i.$$canvasTo=Ce(320,240)),(n.data.type===fe.ImageData||n.data.type===fe.Anything&&je(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(Gt,{type:fe.ImageData,value:e})}}else Ue(n.data.value)&&o.includes(n.data.type)&&r.setState({...i,rect:n.data.value})},getInputNames:()=>[{name:Wt.image,type:fe.ImageData},{name:Wt.rect,type:[fe.Rect,fe.JsonObj]}],getOutputNames:()=>[{name:Gt,type:fe.ImageData}]};const Ht=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),i=e.data,s=e.width,o=e.height,a=s,c=o,l=((e,t,n)=>{if(Z)return new ImageData(t,n);return console.warn("Node environment detected. Aborting new ImageData creation"),e})(e,a,c),d=l.data;for(let e=0;e<c;e++)for(let c=0;c<a;c++){const l=e,u=c,p=4*(e*a+c);let g=0,h=0,f=0,m=0;for(let e=0;e<n;e++)for(let a=0;a<n;a++){const c=l+e-r,d=u+a-r;if(c>=0&&c<o&&d>=0&&d<s){const r=4*(c*s+d),o=t[e*n+a];g+=i[r]*o,h+=i[r+1]*o,f+=i[r+2]*o,m+=i[r+3]*o}}d[p]=g,d[p+1]=h,d[p+2]=f,d[p+3]=m+1*(255-m)}return l},zt=[-1,0,1,-2,0,2,1,0,1],qt=Object.freeze({image:"image"}),Kt="image";var Jt={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={matrix:[...zt],...i};if(n.data.type===fe.ImageData||n.data.type===fe.Anything&&je(n.data.value)){const e=Ht(n.data.value,s.matrix);return r.nextGate(Kt,{type:fe.ImageData,value:e})}},getInputNames:()=>[{name:qt.image,type:fe.ImageData}],getOutputNames:()=>[{name:Kt,type:fe.ImageData}]};const Yt=Object.freeze({output:"output",aborted:"aborted"}),Xt=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),Zt=e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e},n=Array(t.inputs).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:"reset",type:fe.Anything}),n};var Qt={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(Yt.aborted,n.data);{i.triggeredAt=s;const e=Zt(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(Yt.output,n.data),r.setState(i)}},getInputNames:Zt,getOutputNames:e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e};if(e.matchingOutputs){const e=Array(t.inputs).fill(0).map(((e,t)=>({name:`output${t+1}`,type:fe.Anything})));return e.push({name:Yt.aborted,type:fe.Anything}),e}return[{name:Yt.output,type:fe.Anything},{name:Yt.aborted,type:fe.Anything}]},getDefaultState:Xt};const en=(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)}},tn=(e,t,n,r,i,s,o)=>{e.fillStyle=i,e.fillRect(t,n,r,r),en(e,t,n,i,s,o)},nn=(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;en(e,t.left-o,t.top-o,r,i,s)},rn=Object.freeze({image:"image",pixels:"pixels"}),sn="image";var on={onParentEvent:async(e,t,n,r)=>{const i={fontSize:12,color:"#00ff00",size:2,...r.getState()},s=n.data.type===fe.ImageData||n.data.type===fe.Anything&&je(n.data.value);if(t.name===rn.pixels){const e=(e=>Re(e)||Ue(e)||Array.isArray(e)&&e[0]&&(Re(e[0])||Ue(e[0])))(n.data.value);if(!e)return;i.$$pixels=n.data.value}if(t.name===rn.image&&s){const e=n.data.value;i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(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=ke(r);if(e){r.width!==t.width&&(r.width=t.width),r.height!==t.height&&(r.height=t.height),e.putImageData(t,0,0);const c=Array.isArray(n)?n:[n];for(let t=0;t<c.length;t++){const n=c[t],r=o?n[o]:"";Ue(n)?nn(e,n,i,s,r,a):Re(n)&&tn(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(sn,{type:fe.ImageData,value:e})}r.setState(i)},getInputNames:()=>[{name:rn.image,type:fe.ImageData},{name:rn.pixels,type:[fe.Rect,fe.Point,fe.Array,fe.JsonObj]}],getOutputNames:()=>[{name:sn,type:fe.ImageData}]};const an=Object.freeze({in:"in"}),cn="output",ln=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var dn={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:100,...r.getState()},s=!Number.isInteger(i.min),o=!Number.isInteger(i.max),a=s||o;let c=(l=i.min,d=i.max,Math.random()*(d-l)+l);var l,d;if(a){let e=0;if(s&&(e=ln(i.min)),o){const t=ln(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(cn,{type:fe.Number,value:c})},getInputNames:()=>[{name:an.in,type:fe.Anything}],getOutputNames:()=>[{name:cn,type:fe.Number}]};const un=Object.freeze({output:"output",totalItems:"totalItems"}),pn=Object.freeze({trigger:"trigger",clear:"clear"}),gn=()=>({$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),hn=async(e,t)=>t.nextGate(un.totalItems,{type:fe.Number,value:e});var fn={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===pn.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),hn(i.$$list.length,r);const s=t.name===pn.trigger;if(!s)if(Array.isArray(n.data.value))n.data.type!==fe.Array&&n.data.type!==fe.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await hn(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===fe.JsonObj?i.$$outputShape={...i.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:i.$$outputShape={...i.$$outputShape,[t]:n.data.type},i.$$list.push(n.data.value),r.setState({...i}),await hn(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 hn(e,r),r.nextGate(un.output,{type:fe.Array,value:t})}},getInputNames:e=>{const t={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:pn.clear,type:fe.Anything},{name:pn.trigger,type:fe.Anything}),n},getOutputNames:e=>[{name:un.output,type:fe.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:un.totalItems,label:"Total Items",type:fe.Number}],getDefaultState:gn};const mn=Object.freeze({start:"start",stop:"stop"}),yn="output",vn="clock_interrupt";var bn={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(De(e?.name||"")&&t.name===vn)return r.nextGate(yn,{type:fe.Boolean,value:!0});if(t.name===mn.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!==mn.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt("interval",vn,{interval:i.interval}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:mn.start,type:fe.Anything},{name:mn.stop,type:fe.Anything}],getOutputNames:()=>[{name:yn,type:fe.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",vn,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const wn=Object.freeze({in:"in"}),Sn="output",In=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var $n={onParentEvent:async(e,t,n,r)=>{const i={userProperties:[],factor:2,decimalPoints:2,...r.getState()},s=n.data.type;let o=n.data.value,a=!1;return e?.jsonShape&&(i.detectedInputJson={...i.detectedInputJson,...e?.jsonShape},a=!0),i.detectedInputType||(i.detectedInputType=s,a=!0),n.data.type===fe.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>In(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]=In(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===fe.Number&&(o=In(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(Sn,{type:s,value:o})},getInputNames:()=>[{name:wn.in,type:[fe.Array,fe.Number]}],getOutputNames:e=>[{name:Sn,type:e.detectedInputType||fe.Number,jsonShape:e.detectedInputJson}]};const _n={},Cn=Object.freeze({output:"output"}),kn=Object.freeze({trigger:"trigger"}),En=e=>e===fe.ArrayBuffer||e===fe.AudioBuffer||e===fe.BinaryFile||e===fe.ImageData||e===fe.ImageBitmap||e===fe.Array||e===fe.JsonObj,xn=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:fe.Number,value:10},{name:"y",label:"y",type:fe.Number,value:20}]}),Nn=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},An=(e,t)=>{const n={};for(let r=0;r<e.properties.length;r++){let i=e.properties[r].value;const s=e.properties[r].type;En(s)&&(i=_n[t][e.properties[r].name]),s===fe.Number?i=Number(i):s===fe.String&&(i=String(i)),n[e.properties[r].label]=i}return n};var Pn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s=structuredClone(i),o={...xn(),...s};if(t.name===kn.trigger){const e=An(o,r.id);return r.nextWidget(Cn.output,{type:fe.JsonObj,value:e})}const a=o.properties.findIndex((e=>e.name===t.name));if(-1!==a){const e=o.properties[a];let t=n.data.type===e.type;if(!t&&n.data.type===fe.Anything){t=Fe(n.data.type)===e.type}if(t){En(n.data.type)?(_n[r.id][e.name]=n.data.value,o.properties[a].value=void 0):o.properties[a].value=n.data.value,o.properties[a].$$invalidInputType=!1}else o.properties[a].$$invalidInputType=!0;if(r.setState(o),!o.useTriggerPort){const e=An(o,r.id);return r.nextWidget(Cn.output,{type:fe.JsonObj,value:e})}}},getInputNames:e=>{const t={...xn(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:kn.trigger,label:kn.trigger,type:fe.Anything}),n},getOutputNames:e=>[{name:Cn.output,label:Cn.output,type:fe.JsonObj,jsonShape:Nn(e)}],getDefaultState:xn,initialize:async e=>{_n[e.widgetId]={}},terminate:async e=>{delete _n[e.widgetId]}};const On=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(Pe)){const n=t(e,Pe);return We("inner","input",n)}if(e.startsWith(Le)){const n=t(e,Le);return We("outer","output",n)}return null},Tn=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[fe.Anything],index:0}],outputs:[{name:"output",type:[fe.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Ln=e=>{const t={...Tn(),...e},n=t.inputs.map(((e,t)=>({name:We("outer","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t}))),r=t.outputs.map(((e,t)=>({name:We("inner","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:n.length+t})));return[...n,...r]};var Bn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Tn(),...i},o=Ln(s,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const i=o[e];if(t.name===i.name&&(i.type.includes(fe.Anything)||i.type.includes(n.data.type))){const e=await On(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Ln,getOutputNames:e=>{const t={...Tn(),...e},n=t.outputs.map(((e,t)=>({name:We("outer","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t})));return[...t.inputs.map(((e,t)=>({name:We("inner","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:t+n.length}))),...n]},getDefaultState:Tn};const Dn=(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 jn={getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,i=n[t+1]||0,s=n[t+2]||0;return{avr:(r+i+s)/3,r:r,g:i,b:s}},getBoundingBox:(e,t,n)=>{const r=e.width,i=e.height,s=new Set,o=Number(n.threshold||0),a=isNaN(o)?10:o,c=(n,o)=>{const c=[[n,o]];let l=n,d=n,u=o,p=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,g]=n;o<0||g<0||o>=r||g>=i||s.has(`${o},${g}`)||!Dn(o,g,e,t,a||0)||(s.add(`${o},${g}`),l=Math.min(l,o),d=Math.max(d,o),u=Math.min(u,g),p=Math.max(p,g),c.push([o+1,g],[o-1,g],[o,g+1],[o,g-1]))}return{minX:l,maxX:d,minY:u,maxY:p}},l=[];for(let o=0;o<i;o+=4)for(let i=0;i<r;i+=4)if(!s.has(`${i},${o}`)&&Dn(i,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:s}=c(i,o),a=t-e,d=s-r;if(a>=(n.minWidth||1)&&d>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:d}),n.maxBoxes&&l.length>=n.maxBoxes)return l}return l},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,i="object"==typeof n,s=i?n.r:n,o=i?n.g:n,a=i?n.b:n;r[t]=s,r[t+1]=o,r[t+2]=a,r[t+3]=255}};const Un=e=>Fe(e);var Rn,Fn,Mn,Wn,Gn,Vn,Hn,zn,qn,Kn;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Rn||(Rn={})),function(e){e.Bundle="bundle",e.Group="group"}(Fn||(Fn={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Mn||(Mn={})),function(e){e.Cloud="cloud",e.Web="web"}(Wn||(Wn={})),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"}(Gn||(Gn={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Vn||(Vn={})),(Hn||(Hn={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(zn||(zn={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(qn||(qn={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Kn||(Kn={}));let Jn=null;var Yn=()=>{if(!Jn)throw new Error("Required function is not set");return Jn};class Xn extends Error{targetWidgetId;targetPortName;sourcePortName;sourceWidgetId;targetWidgetType;sourceWidgetType;constructor(e,t){super(e),this.name="ChildWidgetError",t.stack&&(this.stack=t.stack),this.targetWidgetId=t.targetWidgetId,this.targetPortName=t.targetPortName,this.sourcePortName=t.sourcePortName,this.sourceWidgetId=t.sourceWidgetId,this.targetWidgetType=t.targetWidgetType,this.sourceWidgetType=t.sourceWidgetType}}class 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===Rn.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar console = this.console;\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\n\t\t\tvar Kemu = {\n\t\t\t\tservices: {\n\t\t\t\t\thttp: { ...this.httpWebService },\n\t\t\t\t\tdynamoDb: { ...this.dynamoService },\n\t\t\t\t\tgoogleSheets: {\n\t\t\t\t\t\t...this.googleSheetsService,\n\t\t\t\t\t}\n\t\t\t\t},\n\n\t\t\t\timage: this.imageHelpers,\n\t\t\t\tvariable: this.variablesManager,\n\n\t\t\t\thelpers: {\n\t\t\t\t\tdecodeDataType: this.decodeDataType,\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\tjsonp: this.jsonp,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tvar sendToPort;\n\n\t\t\t// --- User Methods Start ---\n\t\t\t${e||""};\n\t\t\t// --- User Methods End ---\n\t\t\t\n\t\t\t// Processes the user code asynchronously.\n\t\t\tconst asyncProcessEvent = async (targetPort, sourcePort, event) => {\n\t\t\t\tconst userProcessEvent = typeof processEvent === 'undefined' ? undefined : processEvent;\n\t\t\t\tif(userProcessEvent) {\n\t\t\t\t\ttry{\n\t\t\t\t\t\treturn await userProcessEvent(targetPort, sourcePort, event, sendToPort);\n\t\t\t\t\t}catch(e){\n\t\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked the very first time the recipe is initialized */\n\t\t\tconst asyncRecipeInit = async (context, logger) => {\n\t\t\t\ttry {\n\t\t\t\t\t${t===Rn.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`,er=(e,t,n,r)=>{const o=Qn(e,n),a={...t,document:{},__errorTracer:e=>{if(e instanceof Xn)throw 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:jn,...n===Rn.Cloud?{require:Yn(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:i,CryptoJS:s,decodeDataType:Un,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(Z)return"browser";if(ee)return"node";if(Q)return"worker";throw new Error("Unsupported environment")})()?(e=>e.replace(/[//]{2}[ ]*@kemu-cloud[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-cloud[ \t]*\}/gim,""))(o):(e=>e.replace(/[//]{2}[ ]*@kemu-browser[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-browser[ \t]*\}/gim,""))(o),t=new Function(e);return{compiledModule:t()(a)}}catch(e){return{error:{name:"CompileError",message:e.message,stack:e.stack}}}},tr="main",nr="My Script",rr="This is a test script.",ir=`\n/**\n * Name: ${nr}\n * Description: ${rr}\n */\n\nconst getWidgetInputs = () => [\n\t{ name: 'Input 1', type: DataType.Number }\n];\n\nconst getWidgetOutputs = () => [\n\t{ name: 'Output 1', type: DataType.Number }\n]\n\nlet counter = 0;\n\nconst processEvent = async (targetPort, sourceWidget, event) => {\n\tif(targetPort.name === 'Input 1'){\n\t\treturn sendToPort('Output 1', {\n\t\t\ttype: DataType.Number,\n\t\t\tvalue: counter++,\n\t\t});\n\t}\n}\n`.trim(),sr=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},version:2,metadata:{name:nr,description:rr},pages:{[tr]:{code:ir,language:"javascript",name:"My First Script"}}}),or=(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},ar=(e,t)=>{const n={...{...sr(),...t.getState()},$$error:e||void 0};e&&console.error(e.message),t.setState(n)},cr=new o;let lr,dr,ur={},pr={};const gr=e=>{const t=oe(lr,dr,e);if(!t)throw new Error(`Widget ${e} not found in thing ${dr}`);return t},hr=(e,t)=>`${e}:${t}`,fr=e=>`${gr(e.createdByWidgetId).id}::${e.variableName}`,mr=e=>`${pe}${e}`;var yr=e=>{const t=gr(e.createdByWidgetId),n=fr({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});pr[n]={type:e.type,subscriberWidgetId:t.id,subscriberWidgetType:t.type}},vr=e=>{const t=fr({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});delete pr[t]},br=async e=>{const t=gr(e.setByWidgetId);if(!t)throw new Error(`Widget ${e.setByWidgetId} not found in thing ${dr} in recipe ${lr}`);const n=e.variableName.startsWith(pe)?fr({variableName:e.variableName,createdByWidgetId:e.setByWidgetId}):e.variableName;ur[n]={value:e.value,type:e.type};const r={value:e.value,type:e.type,varName:e.variableName,isUIElement:e.variableName.startsWith(pe),setByWidgetType:t.type,setByWidgetId:e.setByWidgetId};await cr.emit(hr(e.variableName,e.type),r),e.type!==fe.Anything&&await cr.emit(hr(e.variableName,fe.Anything),r)},wr=e=>{const{readerWidgetId:t,variableName:n}=e;if(!gr(t))throw new Error(`Widget ${t} not found in thing ${dr} in recipe ${lr}`);const r=n.startsWith(pe)?fr({variableName:e.variableName,createdByWidgetId:e.readerWidgetId}):n,i=ur[r];if(i)return{type:i.type,value:i.value}},Sr=e=>{const{widgetId:t,variableName:n,type:r}=e;if(!gr(t))throw new Error(`Widget ${t} not found in thing ${dr} in recipe ${lr}`);const i=hr(n,r);let s;return s=cr.on(i,(async r=>{oe(lr,dr,t)?await e.onValueChange(r):(console.warn(`Zombie widget ${t} detected, unsubscribing from variable events "${n}"`),s?.())})),s},Ir=(e,t)=>{const n=hr(e,fe.Anything);return cr.on(n,(async e=>{const{isUIElement:n,...r}=e;await t(r)}))},$r=e=>{pr={},ur={},lr=e.recipePoolId,dr=e.thingId};const _r="setTimeout",Cr="variableChanged",kr=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=oe(t,n,r);if(!i)throw new Error(`Widget "${r}" not found in recipe "${t}"`);const s=(e,t)=>{const n=wr({readerWidgetId:r,variableName:e});if(n||t)return void 0===n?{value:t?.value??t,type:t?.type??Fe(t)}:{value:n.value,type:n.type}},o=(t,n,s)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");const o={...sr(),...e.getState()},a=Sr({variableName:t,type:fe.Anything,widgetId:r,onValueChange:async e=>{n?e.setByWidgetType===ze.widgetGroup&&e.setByWidgetId===i.groupId&&await s(e):s(e)}});delete o.$$eventListeners[t],o.$$eventListeners[t]={handler:s,abort:async()=>{a()},name:Cr},e.setState(o)};return{get:s,set:async(e,t,n)=>{await br({variableName:e,type:n||Fe(t),setByWidgetId:r,value:t})},onValueChange:(e,t)=>{o(e,!1,t)},onUIValueChange:(e,t)=>{const n=mr(e);o(n,!0,t)},getUIValue:e=>{const r=mr(e),o=s(r);if(o)return{value:o.value,type:o.type};const a=i.groupId;if(!a)throw new Error("You can only read UI variables from inside a widgetGroup");const c=oe(t,n,a);if(!c)throw new Error(`Widget "${a}" not found in recipe "${t}"`);const l=c.state,d=(l.settings||[]).find((t=>t.variableName===e));if(!d)throw new Error(`Field "${e}" not found in widgetGroup "${l.name}"`);const u=d.config.defaultValue;if(!u)throw new Error(`Field "${e}" in widgetGroup "${l.name}" has no default value`);return{value:u,type:Fe(u)}}}},Er="__command-compile__";let xr;const Nr=()=>{throw new Error("Method not implemented")},Ar=(e,t,n)=>{const i=(e,...n)=>{const r={...sr(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},s={};return Object.keys(fe).forEach((e=>{s[e]=fe[e]})),{dataTypesEnum:s,notify:{success:e=>{t.getState()?.$$managedUI?.notify?.success(e)},error:e=>{t.getState()?.$$managedUI?.notify?.error(e)},info:e=>{t.getState()?.$$managedUI?.notify?.info(e)}},variablesManager:e.variablesManager?kr({recipePoolId:n.recipePoolId,scriptWidgetId:n.widgetId,thingId:n.thingId,getState:t.getState,setState:t.setState}):{get:Nr,set:async()=>Nr(),onValueChange:Nr,onUIValueChange:Nr,getUIValue:Nr},setTimeout:(n,i,s)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=r(),o={...sr(),...t.getState()};o.$$eventListeners[e]={handler:n,rejectHandler:s,name:_r},t.setState(o),t.registerInterrupt("timeout",e,{timeout:i},void 0,e)}},addEventListener:(e,n)=>{if(t.setState){const s=r(),o={...sr(),...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={...sr(),...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.`)}}},Pr=(e,t,n,r)=>{const i={...sr(),...n.getState()},s=i.pages[tr].$$compiledCode;if(s)return{compiledModule:s};{const s=Ar(e,n,t);return er(i.pages[tr].code,s,n.recipeType,r)}},Or=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),Tr=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===_r){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},Lr=async e=>{const t={...e};for(const n in e){if(e[n].name===Cr){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},Br=async(e,t,n)=>{let r={...sr(),...e.getState()};if(void 0!==n){r.pages[tr]?.$$compiledCode?.onTerminate&&await(r.pages[tr].$$compiledCode?.onTerminate());let t=await Tr(r.$$eventListeners,e);t=await Lr(t),r.$$eventListeners=t,r.pages[tr].$$compiledCode=void 0,r.pages[tr].code=n,e.setState({...r})}const i=!r.pages[tr].$$compiledCode,{compiledModule:s,error:o}=Pr({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=or(o,e.recipeType);return ar(t,e),null}if(s){const n=(()=>{const e=(e,...t)=>{if(xr)try{return xr[e](...t)}catch(e){return void console.log("Error in custom logger: ",e)}console[e](...t)};return{log:(...t)=>{e("log",...t)},error:(...t)=>{e("error",...t)},warn:(...t)=>{e("warn",...t)},info:(...t)=>{e("info",...t)}}})();let o;r={...e.getState()},r.pages[tr].$$compiledCode=s;const a=jr(r.pages[tr].code);a?.name===r.metadata?.name&&a?.description===r.metadata?.description||(r.metadata=a||void 0);const c=e.nextWidget||e.nextGate;if(c&&s.setSendToPortFun(c),t)try{await s.recipeInit({setState:e.setState,getState:e.getState},n)}catch(t){o=or(t,e.recipeType)}if(c&&i)try{await s.main(c,n)}catch(t){o=or(t,e.recipeType)}r.$$lastInputs=s.getWidgetInputs?s.getWidgetInputs():[],r.$$lastOutputs=s.getWidgetOutputs?s.getWidgetOutputs():[],e.setState(r),ar(o,e)}};var Dr={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...sr(),...i};if(!s.pages[tr])return console.warn("Missing default page");if(De(e?.name||""))return s.$$eventListeners[t.name]?(await s.$$eventListeners[t.name].handler(),s.$$eventListeners[t.name].name===_r&&delete s.$$eventListeners[t.name],void r.setState({...s})):void console.log(`Unknown interrupt id [${t.name}] `);const o=t.name===Er;await Br(r,!1,o?n.data.value:void 0);const a=s.pages[tr].$$compiledCode;if(e&&e.name!==Er&&a)try{await a.asyncProcessEvent(t,e,n)}catch(e){if("UserCodeError"===e.name){const t=or(e,r.recipeType);throw ar(t,r),t}throw e}},getInputNames:(e,t)=>{const n={...sr(),...e},{compiledModule:r}=Pr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return Or(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...sr(),...e},{compiledModule:r}=Pr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return Or(e)}return e.$$lastOutputs||[]},getDefaultState:sr,initialize:async e=>{const t=e.getState(),n={...sr(),...t};n.pages[tr].code&&await Br({getState:e.getState,id:e.widgetId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,nextWidget:e.nextWidget,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[tr].code)},terminate:async e=>{try{const t=e.getState();t.pages[tr].$$compiledCode?.onTerminate&&await t.pages[tr].$$compiledCode.onTerminate();const n=e=>Xe.destroyInterrupt(e),r=await Tr(t.$$eventListeners,{cancelInterrupt:n});await Lr(r)}catch(t){console.warn(`Error terminating script widget ${e.widgetId}: `,t)}}};const jr=e=>{const t=e.trimStart().match(/^(?:\/\*\*(?:[^*]|\*(?!\/))*\*\/|\/\*(?:[^*]|\*(?!\/))*\*\/)/);if(!t)return null;const n=t[0].replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map((e=>e.replace(/^\s*\*?\s?/,"").trim())).join("\n"),r=n.match(/Name\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),i=n.match(/Description\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),s={};return r&&r[1]&&(s.name=r[1].trim()),i&&i[1]&&(s.description=i[1].trim()),Object.keys(s).length>0?s:null},Ur=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const i=await Rr(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)},Rr=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),Fr=Object.freeze({image:"image"}),Mr=Object.freeze({base64:"base64"}),Wr=()=>({});var Gr={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===Mr.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==fe.String&&n.data.type!==fe.Anything)return;const e=n.data.value;Z&&(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240)));try{const t=await Ur(e,i.$$memCanvas,i.resize?.width,i.resize?.height);return r.setState(i),r.nextGate(Fr.image,{type:fe.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:Mr.base64,type:fe.String}],getOutputNames:()=>[{name:Fr.image,type:fe.ImageData}],getDefaultState:Wr};const Vr=Object.freeze({object:"object",error:"error"}),Hr=Object.freeze({string:"string"}),zr=()=>({outputIsArray:!1});var qr={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===fe.String||n.data.type===fe.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!i.outputIsArray?r.setState({...i,outputIsArray:!0}):!t&&i.outputIsArray&&r.setState({...i,outputIsArray:!1}),r.nextGate("object",{type:t?fe.Array:fe.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:fe.Boolean,value:!0})}},getInputNames:()=>[{name:Hr.string,type:fe.String}],getOutputNames:e=>[{name:Vr.object,type:[fe.JsonObj,fe.Array],label:e.outputIsArray?"array":Vr.object},{name:Vr.error,type:fe.Boolean}],getDefaultState:zr};const Kr=Object.freeze({string:"string",length:"length"}),Jr=Object.freeze({trigger:"trigger",setText:"setText"}),Yr=()=>({text:"",dispatchOnSet:!1});var Xr={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===Jr.setText){if(!((n.data.type===fe.String||n.data.type===fe.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(i.text=n.data.value,r.setState(i)),!i.dispatchOnSet)return}const s=r.nextGate(Kr.length,{type:fe.Number,value:i.text.length}),o=r.nextGate(Kr.string,{type:fe.String,value:i.text});await Promise.all([s,o])},getInputNames:e=>{const t=[{name:Jr.setText,type:fe.String}];return e.dispatchOnSet||t.push({name:Jr.trigger,type:fe.Anything}),t},getOutputNames:()=>[{name:Kr.string,type:fe.String},{name:Kr.length,type:fe.Number}],getDefaultState:Yr};const Zr=Object.freeze({image:"image"}),Qr=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),ei=()=>({showInputPorts:!1});var ti={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Qr.x&&(i.cropX=n.data.value),t.name===Qr.y&&(i.cropY=n.data.value),t.name===Qr.width&&(i.cropWidth=n.data.value),t.name===Qr.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===Qr.image){if(n.data.type!==fe.ImageData&&n.data.type!==fe.Anything)return;if(!je(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$memCanvasContext=ke(i.$$memCanvas),r.setState(i)),!i.$$memCanvas||!i.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return i.$$memCanvas.width=e.width,i.$$memCanvas.height=e.height,(i.cropX||i.cropY||i.cropWidth||i.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const i=Math.max(r.x||0,0),s=Math.max(r.y||0,0),o=e.width,a=e.height,c=Math.min(Math.ceil(r.width||o),o),l=Math.min(Math.ceil(r.height||a),a);return t.width=e.width,t.height=e.height,n.putImageData(e,0,0),n.drawImage(t,i,s,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,i.$$memCanvas,i.$$memCanvasContext,{x:i.cropX,y:i.cropY,width:i.cropWidth,height:i.cropHeight})),r.nextGate(Zr.image,{type:fe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Qr.image,type:[fe.ImageData]}];return e.showInputPorts&&(t.push({name:Qr.x,type:fe.Number}),t.push({name:Qr.y,type:fe.Number}),t.push({name:Qr.width,type:fe.Number}),t.push({name:Qr.height,type:fe.Number})),t},getOutputNames:()=>[{name:Zr.image,type:fe.ImageData}],getDefaultState:ei};const ni=Object.freeze({image:"image"}),ri=Object.freeze({image:"image",width:"width",height:"height"}),ii=()=>({showInputPorts:!1});var si={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===ri.width&&(i.width=n.data.value),t.name===ri.height&&(i.height=n.data.value),void r.setState(i);if(t.name===ri.image){if(n.data.type!==fe.ImageData&&n.data.type!==fe.Anything)return;if(!je(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$tempCanvas=Ce(320,240),r.setState(i)),!i.$$memCanvas||!i.$$tempCanvas)return;let t=e;return(i.width||i.height)&&(t=((e,t,n,r,i)=>{if(!r&&!i)return e;r&&!i?i=r*(e.height/e.width):!r&&i&&(r=i*(e.width/e.height));const s=Math.max(1,r||e.width),o=Math.max(1,i||e.height);n.width===e.width&&n.height===e.height||(n.width=e.width,n.height=e.height),t.width=s,t.height=o;const a=ke(t),c=ke(n);if(!a||!c)throw new Error("Failed to get canvas context");return c.putImageData(e,0,0),a.drawImage(n,0,0,e.width,e.height,0,0,s,o),a.getImageData(0,0,s,o)})(e,i.$$memCanvas,i.$$tempCanvas,i.width,i.height)),r.nextGate(ni.image,{type:fe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:ri.image,type:fe.ImageData}];return e.showInputPorts&&(t.push({name:ri.width,type:fe.Number}),t.push({name:ri.height,type:fe.Number})),t},getOutputNames:()=>[{name:ni.image,type:fe.ImageData}],getDefaultState:ii};const oi=Object.freeze({value:"value"}),ai=Object.freeze({trigger:"trigger",setValue:"setValue"}),ci=()=>({value:0,dispatchOnSet:!1});var li={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===ai.setValue){const e=n.data.type===fe.Number||n.data.type===fe.Anything||n.data.type===fe.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(i.value=Number(n.data.value),r.setState(i),!i.dispatchOnSet)return}return r.nextGate(oi.value,{type:fe.Number,value:i.value})},getInputNames:e=>{const t=[{name:ai.setValue,type:fe.Number}];return e.dispatchOnSet||t.push({name:ai.trigger,type:fe.Anything}),t},getOutputNames:()=>[{name:oi.value,type:fe.Number}],getDefaultState:ci};const di=Object.freeze({image:"image"}),ui=Object.freeze({image:"image"}),pi=()=>({anchors:[],vertices:[],matrix:[]}),gi={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},s=window,o=n.data.type===fe.ImageData;if(s.Speedy&&o){const e=s.Speedy,t=n.data.value;let o,d,u,p=i.$$private?.canvas,g=i.$$private?.context,h={...i};const f=4===i.anchors.length;if(i.$$private?.pipeline)o=i.$$private?.pipeline,d=i.$$private?.source;else{o=e.Pipeline(),d=e.Image.Source();const n=e.Image.Sink();u=e.Transform.PerspectiveWarp(),p?p.width===t.width&&p.height===t.height||(p.width=t.width,p.height=t.height,g=p.getContext("2d")):(c=t.width,l=t.height,p=Ce(c,l),g=p.getContext("2d")),d.output().connectTo(u.input()),u.output().connectTo(n.input()),o.init(d,n,u);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===i.anchors.length){const t=e.Matrix(2,4,[(a=i.anchors)[0].x,a[0].y,a[1].x,a[1].y,a[2].x,a[2].y,a[3].x,a[3].y]),n=e.Matrix(2,4,i.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),s=e.Matrix.Zeros(3,3);await e.Matrix.perspective(s,t,n);const o=s.read();r=e.Matrix(3,3,o)}u.transform=r,h={...h,$$private:{...h.$$private,canvas:p,context:g,perspective:u,pipeline:o,source:d}}}let m=t;if(f){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,i=e.$$private?.pipeline;if(n.Speedy&&r&&i){const e=n.Speedy,s=await createImageBitmap(t),o=await e.load(s);return r.media=o,(await i.run()).image.source}return null})(h,m);e&&(p&&g&&(m=((e,t,n)=>(t.width=e.width,t.height=e.height,n.drawImage(e,0,0),n.getImageData(0,0,e.width,e.height)))(e,p,g)),h.$$private&&r.setState({...h,$$private:{...h.$$private,lastInputImage:t}}))}else h.$$private&&r.setState({...h,$$private:{...h.$$private,lastInputImage:t}});return r.nextGate(di.image,{type:fe.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:ui.image,type:fe.ImageData}],getOutputNames:()=>[{name:di.image,type:fe.ImageData}],getDefaultState:pi,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},hi=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[fe.Anything],name:"input"}],outputs:[{dataType:[fe.Anything],name:"output"}]});let fi;const mi=()=>{if(!fi)throw new Error(tt(et));return fi};const yi=async e=>{const t=new a,n=await t.loadAsync(e),r={};for(const e in n.files)if(!n.files[e].dir){const t=await n.file(e);t&&(r[e]=await t.async("uint8array"))}return r},vi={};var bi=e=>vi[e]||null;const wi=async(e,t,n)=>{try{const r=mi(),i=n?r.loadBlobAsString:r.loadBlob;return await i(e,t)}catch(e){return null}},Si=async e=>{const t=le;try{const n=await wi(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},Ii=async e=>{const t=de;try{const n=await wi(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}},$i=(e,t)=>`${e.replace(ue,"")}_${t}`,_i=(e,t)=>`widget/${e.replace(ue,"")}/v/${t}`,Ci=async(e,t)=>{const n=mi(),[r]=await Promise.all([yi(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},ki=(e,t)=>{const n=$i(e,t),r=bi(n);return r?{...r}:null},Ei=(e,t,n)=>{const r=`${`widget/${e.replace(ue,"")}/tmp`}/${t}`;if(n){return mi().getCacheLocation(r)}return r};var xi=ki,Ni=async(e,t,n)=>{const r=Ei(t,n);await Ci(e,r);const i=Si(r),s=Ii(r),o=mi(),a=o.getCacheLocation(r),[c,l]=await Promise.all([i,s]);if(!c)return null;let d=l;if(!l){const e=hi(),t=JSON.stringify(e);await o.saveBlob(r,de,Be(t)),d=e}return{cachePath:a,processor:c,storedState:Object.freeze(d)}},Ai=(e,t,n)=>{if(n.isTempStorage)return Ei(e,t,n.fullStorageRoot);const r=mi(),i=_i(e,t);return n.fullStorageRoot?r.getCacheLocation(i):i};const Pi=()=>hi();var Oi={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={...Pi(),...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={...Pi(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:Pi,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetId;const i=n.$$cacheInfo?.version.toString()||n.collectionInfo?.version.toString()||1;if(n.$$cacheInfo={...n.$$cacheInfo,version:Number(i),widgetThingId:r},!r||!i)throw new Error("Widget bundle state is missing cache id or version");console.log("Loading state from cache");const s=xi(r,i);let o=!s;if(!n.$$processor)if(n.storageUnitId&&!s){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetId;const s=await Ni(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=Ai(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 Ti=Object.freeze({event:"event"}),Li="1",Bi="2",Di="3";var ji={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate(Li,n.data),await r.nextGate(Bi,n.data),await r.nextGate(Di,n.data)},getInputNames:()=>[{name:Ti.event,type:fe.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??fe.Anything};return[{name:Li,...t},{name:Bi,...t},{name:Di,...t}]}};const Ui=()=>({name:"myVar",type:fe.Anything,reactive:!0,defaultValue:""}),Ri=Object.freeze({set:"set",read:"read"}),Fi="value";var Mi={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Ui(),...i};if(t.name!==Ri.set){if(t.name===Ri.read){const e=wr({variableName:s.name,readerWidgetId:r.id}),t=e?e.value:s.defaultValue;await r.nextWidget(Fi,{type:s.type,value:t})}}else{if(n.data.type!==s.type&&s.type!==fe.Anything)return;await br({variableName:s.name,value:n.data.value,setByWidgetId:r.id,type:s.type})}},getInputNames:e=>{const t={...e};return[{name:Ri.set,type:t.type||fe.Anything},{name:Ri.read,type:fe.Anything}]},getOutputNames:e=>{const t={...e};return[{name:Fi,type:t.type||fe.Anything}]},initialize:async e=>{const t=e.getState(),n={...Ui(),...t};if(n.$$abortListener)try{n.$$abortListener()}catch(t){console.warn(`Error aborting variable listener for widget ${e.widgetId}: `,t)}yr({variableName:n.name,type:n.type,createdByWidgetId:e.widgetId});const r=Sr({variableName:n.name,type:n.type,widgetId:e.widgetId,onValueChange:async t=>{const n=e.getState();void 0!==t.value&&(n.type!==fe.Anything&&t.type!==n.type||n.reactive&&await e.nextWidget(Fi,{type:t.type,value:t.value}))}});e.setState({...n,$$abortListener:r})},terminate:async e=>{const t=e.getState(),n={...Ui(),...t};n.$$abortListener&&n.$$abortListener(),vr({variableName:n.name,createdByWidgetId:e.widgetId})}};let Wi;var Gi=e=>{Wi=e},Vi=()=>{if(!Wi)throw new Error("Hub Connector not set");return Wi};const Hi=async(e,t=!1)=>{const n=Vi();let r=e.$$$serviceId;if(!e.service)return console.log("Aborting service initialization, missing property `service` in state."),null;if(!r||t){const t=await n.getCompatibleService(e.service.name,e.service.version,"^");if(!t)return null;r=t.sessionId}return r};var zi={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const s=Vi();let o=i.$$$serviceId;if(!o){const e=s.getCachedServices().available.find((e=>e.name===i.service?.name&&e.version===i.service?.version));if(!e)return;o=e.sessionId,i.$$$serviceId=o,r.setState(i)}const a=i.service?.variants?.find((e=>e.id===i.variantId)),c=a?i.dynamicInputs[a.id]||a?.inputs||[]:i.service?.inputs||[];if(!c?.length)return;if(!a&&i.service?.ignoreParentEvents)return;const l=i.service?.processingTimeoutSec,d=i.service?.name&&r.eventContext?.[i.service?.name];return s.onParentEvent({recipeId:r.recipePoolId,data:n.data,targetServiceSessionId:o,currentState:i.customState,targetVariantId:i.variantId,target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:l?1e3*l:0,async:i.service?.asyncParentEvents},eventContext:d})},getInputNames:async e=>{const t=e.variantId;if(t&&e.dynamicInputs?.[t])return[...e.dynamicInputs[t]||[]];if(!t)return e.service?.inputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.inputs||[]}return[]},getOutputNames:async e=>{const t=e.variantId;if(t&&e.dynamicOutputs?.[t])return[...e.dynamicOutputs[t]||[]];if(!t)return e.service?.outputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.outputs||[]}return[]},initialize:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=Vi(),r=await Hi(t);if(r)try{return await n.initializeServiceInstance({recipeId:e.recipePoolId,sessionId:r,widgetId:e.widgetId,recipeType:e.recipeType,variantId:t.variantId})}catch(t){if("FNC_NOT_FOUND"!==t?.errCode){if(!!("string"!=typeof t||!t.match('^Function ".*" not found.$')))throw t;console.warn(`Widget [${e.widgetId}] does not have an init function.`)}}else console.log(`Aborting service initialization, "${t.service?.name}" was not found in the current Hub.`)},terminate:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=Vi(),r=await Hi(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const qi=Object.freeze({Image:"image"}),Ki=Object.freeze({Image:"image"}),Ji=()=>({filters:[{name:"grayscale",value:"0.5",id:"d-1"}]});const Yi="loaded";var Xi={onParentEvent:async(e,t,n,r)=>{try{const e=((e,t)=>{switch(t){case fe.Number:case fe.Boolean:case fe.String:return String(e);case fe.Array:case fe.JsonObj:case fe.Rect:case fe.Point:return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));case fe.ArrayBuffer:if(e instanceof ArrayBuffer){if(ee)return Buffer.from(e).toString("base64");{const t=new Uint8Array(e),n=t.length,r=new Array(n);for(let e=0;e<n;e++)r[e]=String.fromCharCode(t[e]);return btoa(r.join(""))}}throw new Error("Type is ArrayBuffer but value is not an ArrayBuffer");case fe.ImageData:{if(!je(e))throw new Error("Expected ImageData");const t=e,n=Ce(t.width,t.height),r=ke(n);if(!r)throw new Error("Failed to get canvas context");r.putImageData(t,0,0);const i=n.toDataURL("image/png");if(!i)throw new Error("Failed to convert canvas to data URL");return i.split(",")[1]}default:return String(e)}})(n.data.value,n.data.type);return r.nextWidget("text",{type:fe.String,value:e})}catch(e){return r.nextWidget("error",{type:fe.String,value:e instanceof Error?e.message:"Failed to stringify object"})}},getInputNames:()=>[{name:"object",type:[fe.Number,fe.String,fe.ArrayBuffer,fe.Array,fe.Boolean,fe.JsonObj,fe.Rect,fe.Point,fe.ImageData]}],getOutputNames:()=>[{name:"text",type:fe.String},{name:"error",type:fe.String}],getDefaultState:()=>({})};const Zi=(e,t)=>{const n=(e=>{const t=new Date;return{input:"object"==typeof e&&null!==e?e:{value:e},date:{year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hours:t.getHours(),minutes:t.getMinutes(),seconds:t.getSeconds(),milliseconds:t.getMilliseconds(),time:t.getTime(),dayOfWeek:t.getDay(),dayName:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()],shortDayName:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getDay()],date:t.getDate(),fullYear:t.getFullYear(),timezoneOffset:t.getTimezoneOffset(),UTCDate:t.getUTCDate(),UTCDay:t.getUTCDay(),UTCFullYear:t.getUTCFullYear(),UTCHours:t.getUTCHours(),UTCMilliseconds:t.getUTCMilliseconds(),UTCMonth:t.getUTCMonth()+1,UTCMinutes:t.getUTCMinutes(),UTCSeconds:t.getUTCSeconds(),isoString:t.toISOString(),localeString:t.toLocaleString()}}})(t);return l.render(e,n)},Qi=()=>({text:"",format:"Text"});const es=()=>({expression:""});const ts={input:it,counter:at,elapsed:dt,ifGate:ht,skipEvent:yt,between:St,map:_t,parser:Et,slider:At,suspend:Tt,display:Bt,json:Ut,arrayItem:Mt,extractImage:Vt,imageConvolution:Jt,firstEvent:Qt,pixelDraw:on,randomBetween:dn,arrayCombine:fn,clock:bn,multiplication:$n,object:Pn,widgetGroup:Bn,script:Dr,base64ToImageData:Gr,jsonParse:qr,text:Xr,imageCrop:ti,imageResize:si,value:li,imageWarp:gi,widgetBundle:Oi,sequence:ji,variable:Mi,hubService:zi,imageFilter:{onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:"0.5",id:"d-1"}],...r.getState()};if(t.name===qi.Image&&n.data.type===fe.ImageData){if(!je(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas?.getContext||(i.$$memCanvas=Ce(e.width,e.height)),i.$$context?.drawImage||(i.$$context=i.$$memCanvas.getContext("2d")),i.$$memCanvas.width!==e.width&&(i.$$memCanvas.width=e.width),i.$$memCanvas.height!==e.height&&(i.$$memCanvas.height=e.height),r.setState(i),i.$$context.putImageData(e,0,0),i.filters.length?i.$$context.filter=i.filters.map((e=>{let t="";return"blur"===e.name?t="px":"hue-rotate"===e.name&&(t="deg"),`${e.name}(${parseFloat(e.value)}${t})`})).join(" "):i.$$context.filter="none",i.$$context.drawImage(i.$$memCanvas,0,0);const t=i.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(Ki.Image,{type:fe.ImageData,value:t})}},getInputNames:()=>[{name:qi.Image,type:fe.ImageData}],getOutputNames:()=>[{name:Ki.Image,type:fe.ImageData}],getDefaultState:Ji},recipeLoad:{onParentEvent:async(e,t,n,r)=>r.nextWidget(Yi,{value:!0,type:fe.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:Yi,type:fe.Boolean,description:"Triggered when the recipe is fully loaded"}]},note:{onParentEvent:async()=>{},getInputNames:()=>[],getOutputNames:()=>[],getDefaultState:()=>({text:"",color:"#eac43e",size:{width:300,height:200}})},stringify:Xi,templateString:{onParentEvent:async(e,t,n,r)=>{const i={text:"",format:"Text",...r.getState()},s=Zi(i.text,n.data.value);return r.nextWidget("text",{type:fe.String,value:s})},getInputNames:()=>[{name:"input",type:fe.Anything}],getOutputNames:()=>[{name:"text",type:fe.String}],getDefaultState:Qi},expressionEval:{onParentEvent:async(e,t,n,r)=>{const i={expression:"",...r.getState()},s=((e,t)=>{const n=Symbol("error"),r=`\n // 'data' is an argument to this function, passed by new Function call.\n // 'SError' is also an argument, providing the error symbol.\n // 'this' inside this function (created by new Function) is the global object.\n\n\t\t// Shadow eval and Function in this non-strict scope.\n\t\tvar eval = undefined;\n\t\tvar Function = undefined;\n\n // Define the sandbox environment\n const sandboxEnvironment = {\n // Make input 'data' accessible\n data: data,\n \n // Safe console (bind methods to the original console)\n console: undefined,\n\n // Mocked/disabled globals\n process: undefined,\n document: undefined,\n navigator: undefined,\n \n require: undefined,\n // eval and Function are shadowed by var declarations above\n \n // Allowed safe globals (pointing to the real ones, accessed via 'this')\n Math: this.Math,\n Date: this.Date,\n JSON: this.JSON,\n Array: this.Array,\n Object: this.Object,\n String: this.String,\n Number: this.Number,\n Boolean: this.Boolean,\n RegExp: this.RegExp,\n // Error: this.Error, // Not Allow Error constructor\n Symbol: this.Symbol, // Allow Symbol constructor\n Map: this.Map,\n Set: this.Set,\n Promise: this.Promise, // Allow Promise if async expressions are intended\n // setTimeout, setInterval, fetch, etc., are deliberately omitted\n };\n\n // Assign the sandboxEnvironment to act as the 'global' context variables\n const global = sandboxEnvironment;\n const window = sandboxEnvironment;\n const globalThis = sandboxEnvironment;\n\n // Shadow top-level variables that might be accessed directly,\n // ensuring they use the sandboxed versions.\n const process = sandboxEnvironment.process;\n const document = sandboxEnvironment.document;\n const navigator = sandboxEnvironment.navigator;\n const console = sandboxEnvironment.console; // Use the sandboxed console for the expression\n const require = sandboxEnvironment.require;\n // 'eval' and 'Function' are already shadowed by var declarations\n\n // The expression will be evaluated in this scope.\n // 'data' is available as it's an argument to the outer function.\n // 'global.xxx' will resolve to 'sandboxEnvironment.xxx'.\n // 'process.yyy' will resolve to 'sandboxEnvironment.process.yyy'.\n \n return () => {\n "use strict"; // Apply strict mode only to the expression evaluation scope\n const abort = Symbol('abort'); // Local symbol for the expression's optional special return value\n\n let result;\n try {\n // Strict mode can add a layer of security and prevent some common errors.\n // It also changes 'this' binding within the expression if it uses 'this'.\n // If the expression uses 'this', under strict mode it would be undefined unless explicitly set.\n // For expressions not using 'this', strict mode is generally safer.\n result = (() => { return ${t}; })();\n } catch(e) {\n // Log the error using the sandboxed console\n // Use 'instanceof Error' to ensure 'e' has a message property.\n const errorMessage = e instanceof Error ? e.message : String(e);\n return {\n\t\t\t\t\terror: 'Error during expression execution: ' + errorMessage, \n\t\t\t\t\tvalue: null\n\t\t\t\t}; // Return the SError symbol passed into this function's scope\n }\n \n\t\t\t// allows ternary expressions that return 'abort' to cancel the evaluation\n if (result !== abort) {\n // Original logic: if result is strictly true, and expression wasn't literally "true", return original data.\n if (result === true && String(expression).trim() !== 'true') {\n return {value: data, error: null}; \n } else {\n return {value: result, error: null};\n }\n }\n \n // If the expression explicitly returned the 'abort' symbol\n return {value: abort, error: null}; \n }\n // End of functionBody template literal\n `;try{return new Function("data","SError",r)(e,n).call({})}catch(e){return{error:e.message,value:null}}})(n.data.value,i.expression);if("symbol"==typeof s.value)return;if(s.error)throw new Error(s.error);if(Number.isNaN(s.value))throw new Error("Expression resulted in NaN");if(void 0===s.value||null===s.value)return;const o=Fe(s.value);return o!==i.$$lastResultType&&r.setState({...i,$$lastResultType:o}),r.nextWidget("result",{type:o,value:s.value})},getInputNames:()=>[{name:"data",type:fe.Anything}],getOutputNames:e=>[{name:"result",type:e.$$lastResultType||fe.Anything}],getDefaultState:es},rescue:{onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type});try{await r.nextWidget("event",n.data)}catch(e){const t=e;await r.nextWidget("error",{type:fe.JsonObj,value:{error:{message:e.message,targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType,stack:e.stack},inputEvent:{type:n.data.type,data:n.data.value}}})}},getInputNames:()=>[{name:"event",type:fe.Anything}],getOutputNames:e=>[{name:"event",type:{...e}.$$lastEventType??fe.Anything},{name:"error",type:fe.JsonObj,jsonShape:{error:fe.JsonObj,inputEvent:fe.JsonObj}}]},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:fe.Boolean}]}},ns={},rs=async()=>{if(!Object.keys(ns).length)for(const e in ts){const t=ts[e];ns[e]=Object.freeze({...t})}};var is=e=>{if(ns[e])return ns[e];throw new Error(tt(Qe,e))},ss=rs;const os=new o,as="invoked";let cs={},ls={},ds={},us={};const ps=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var gs=(e,t,n,r,i)=>{const s=ps(e,t,n),o=ps(e,t),a=ps(e,t,"produced"),c=ds[o],l=Date.now();us[o]=l,cs[s]={data:r,sourcePortName:n,...i?{target:{widgetId:i.widgetId,portName:i.portName}}:{}},os.emit(a,{currentTime:l,prevTime:c,...i?{targetPort:i?.portName}:{}})},hs=(e,t,n,r,i)=>{const s=ps(e,t,n),o=ps(e,t),a=ps(e,t,as),c=ds[o],l=Date.now();ds[o]=l,ls[s]={data:r,sourcePortName:n,...i?{source:{widgetId:i.widgetId,portName:i.portName}}:{}},os.emit(a,{prevTime:c,currentTime:l,targetPort:n,sourceInfo:i})},fs=()=>{cs={},ls={},ds={},us={},os.clearListeners()};const ms={};let ys={};const vs=new o;let bs=!1,ws=!1,Ss=!1,Is=null,$s=null;const _s="processing-state-change",Cs="error-event",ks={abortRequested:!1,isPaused:!1,pausePromise:null,pausePromiseResolve:null,lastPausedWidgetId:null},Es=e=>($s=e,vs.emit(_s,e)),xs=(e,t)=>`${e}-${t}`,Ns=(e,t)=>`state-change:${xs(e,t)}`,As=e=>{const{thingId:t,widgetId:n}=e,r=xs(t,n);return ms[r]||{isProcessing:!1}},Ps=()=>{ks.abortRequested=!1,ks.isPaused=!1},Os=e=>(ks.pausePromise||(ks.isPaused=!0,ks.pausePromise=new Promise((e=>{ks.pausePromiseResolve=e})),e&&(ks.lastPausedWidgetId=e),Es({isProcessing:!0,isPaused:!0,...e?{pauseTrapWidgetId:e}:{}})),ks.pausePromise);var Ts,Ls,Bs=async e=>{const{thingId:t,widgetId:n}=e,r=xs(t,n),i=Ns(t,n),s=As({thingId:t,widgetId:n});if(s.isProcessing)return;const o={isProcessing:!0,isPaused:!1,startTime:Date.now()};ms[r]=o,bs||(bs=!0,Is=null,await Es({isProcessing:!0,isPaused:!1})),await vs.emit(i,{thingId:t,widgetId:n,prevState:s,newState:o})},Ds=async e=>{const{thingId:t,widgetId:n,error:r}=e,i=xs(t,n),s=Ns(t,n),o=As({thingId:t,widgetId:n}),a={isProcessing:!1,isPaused:!1,startTime:o.startTime,endTime:Date.now(),error:r};ms[i]=a,await vs.emit(s,{thingId:t,widgetId:n,prevState:o,newState:a}),r&&(Is=r,await vs.emit(Cs,r)),bs&&0===Object.values(ms).filter((e=>e.isProcessing)).length&&(bs=!1,ws=!1,Ps(),await Es({isProcessing:!1,isPaused:!1}))},js=()=>{bs=!1;for(const e in ms)delete ms[e];ks.abortRequested=!1,ks.isPaused=!1,ks.pausePromise=null,ks.pausePromiseResolve=null,ks.lastPausedWidgetId=null,vs.clearListeners()},Us=()=>ks.abortRequested,Rs=e=>{ks.lastPausedWidgetId=e,ks.isPaused=!0,Es({isProcessing:!0,isPaused:!0,pauseTrapWidgetId:e})},Fs=()=>ws||Ss?null:ks.pausePromise,Ms=e=>Ss?null:ys[e]??null,Ws=()=>ws,Gs=e=>Os(e);!function(e){e.ServiceCreationLog="service-creation-log"}(Ts=Ts||(Ts={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(Ls=Ls||(Ls={}));let Vs={},Hs={},zs=null;const qs=(e,t)=>{const n=(()=>{if(null===zs)throw new Error("Recipe execution type not set, please set the execution type using `setRecipeExecutionType`");return zs===Rn.Desktop})();let r=n?Hs[e]:void 0;return r||(r=(e=>{const{widgets:t,targetId:n,allowedTypes:r}=e;if(!t[n])return[];const i=new Set;Object.values(t).forEach((e=>{e.children?.forEach((e=>i.add(e.childId)))}));const s=Object.keys(t).filter((e=>!i.has(e))),o=s.length>0?s:Object.keys(t),a=[],c=(e,i,s)=>{if(s.has(e))return;s.add(e);const o=t[e],l=!r||r.includes(o.type),d=[...i];l&&d.push(e),e===n?a.push(d.join("/")):o.children?.forEach((e=>c(e.childId,d,s))),s.delete(e)};return o.forEach((e=>c(e,[],new Set))),[...new Set(a)]})({widgets:t,targetId:e,allowedTypes:[ze.hubService]}),n&&(Hs[e]=r)),r},Ks=(e,t,n)=>{qs(t,n).forEach((n=>{Vs[n]={eventContext:e,widgetId:t}}))},Js=(e,t)=>{const n=t[e].state,r=n.service?.name;if(!r)return[];const i=qs(e,t),s=new Map;for(const e of i){const n=e.split("/");let i="";for(let e=0;e<n.length-1;e++){i=0===e?n[e]:`${i}/${n[e]}`;const o=Vs[i];if(o&&!s.has(o.widgetId)){const e=t[o.widgetId].state;e.service?.name===r&&s.set(o.widgetId,{path:i,data:o,pathSegments:i.split("/").length})}}}return Array.from(s.values())},Ys=()=>{Vs={}},Xs=e=>{zs=e},Zs=()=>{Vs={},Hs={}};let Qs,eo,to,no=!1,ro=0;const io=async e=>{const{widgetId:t,thingId:n,recipeId:r,targetPortName:i,data:s}=e,o=se(r,n);if(!o)return;const a=o.gates[t];if(!a||a.disabled)return;const c={...s,timestamp:Date.now()},l=is(a.type),d=lo({gateId:t,originalEvent:c,blockRecipeId:o.recipeId,blockDbId:o.id,blockVersion:o.version,recipeId:r});if(d&&l.onParentEvent){const e={name:i};return Qs&&await Qs({recipeId:r,blockId:o.recipeId,gateId:t,targetPort:e.name,data:s}),l.onParentEvent(null,e,{originalEvent:c,data:{...c}},d)}},so=async e=>{const{interruptDriven:t,childGateId:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c}=e;let{originalEvent:l,block:d}=e;if(!t&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!t&&!l)throw new Error("Missing parameter ['originalEvent']");t&&(l={timestamp:Date.now(),type:fe.Boolean,value:!0});const u=l;if("string"==typeof d){const e=se(r,d);if(!e)return;d=e}const p=d.gates[n];if(!p||p.disabled)return;const g=a.findIndex((e=>e.name===i)),h=is(p.type),f=lo({gateId:n,originalEvent:u,blockRecipeId:d.recipeId,blockDbId:d.id,blockVersion:d.version,recipeId:r});if(f&&h.onParentEvent&&-1!==g){Qs&&await Qs({recipeId:r,blockId:d.recipeId,gateId:n,targetPort:s.name,data:o,sourceGate:t?"interrupt_widget":c,sourcePort:t?ce:i});const e={name:a[g].name,type:a[g].type,...a[g].jsonShape?{jsonShape:a[g].jsonShape}:void 0};return hs(d.recipeId,n,s.name,o,c?{widgetId:c,portName:i}:void 0),h.onParentEvent(e,s,{originalEvent:u,data:o},f)}},oo=async e=>{const{portName:t,originalEvent:n,data:r,currentGateId:i,blockRecipeId:s,thingDbId:o,thingVersion:a,recipeId:c,eventContext:l}=e,d=ie(c);if(!d)throw new Error(`Failed to find recipe "${c}" in cache`);const u=d.dbInfo.recipeType,p=oe(c,s,i);if(!p)return;const g={...r,timestamp:n.timestamp},h=is(p.type);let f;f=p.type===ze.input?h.getOutputNames(p.state,{thingRecipeId:s,thingDbId:o,thingVersion:a,id:i,recipeId:c,recipeType:u,recipePoolId:c}):await h.getOutputNames(p.state,{recipePoolId:c,recipeType:u,thingRecipeId:s,widgetId:i});const m=f.findIndex((e=>e.name===t));if(-1!==m){const e=se(c,s);if(!e)return;gs(s,i,t,g);let r=null;const o=p.children.length;if(p.type===ze.hubService&&l){const t=p.state,n=t.service?.name;n&&Ks(l,p.id,e.gates)}try{for(let a=0;a<o;a++){const o=e.gates[p.children[a].childId];if(o?.disabled)continue;const l=Ge(p.children[a]?.sourcePort),d=Ge(p.children[a]?.targetPort);if(l.portName===t&&o&&!o.disabled){if(no&&Fs()&&(Rs(o.id),await Fs()),Ms(o.id)&&!Ws()&&"innerInput"!==d?.portType){const e=Gs(o.id);await e}if(no&&Us())break;const a=is(o.type);let l;const h={recipePoolId:c,recipeType:u,thingRecipeId:s,widgetId:i};l=o.type===ze.hubService?await a.getInputNames(o.state,h):a.getInputNames(o.state,h);const m=l.find((e=>e.name===d.portName));if(m){no&&await Bs({thingId:s,widgetId:o.id}),ro++;if(!await so({interruptDriven:!1,childGateId:o.id,block:e,recipeId:c,sourcePortName:t,targetPort:{name:m.name},data:p.returnOriginalEvent?n:g,sourceOutputNames:f,sourceGateId:p.id,originalEvent:n}).then((()=>!0)).catch((e=>{const n=o.type===ze.hubService&&"CHILD_WIDGET_ERROR"===e.errCode;if(e instanceof Xn)throw e;if(n&&e.errData){const t=e.errData;throw new Xn(e.error||e.message||("string"==typeof e?e:JSON.stringify(e)),{targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType})}if(!r){const n="string"==typeof e?e:e.message||JSON.stringify(e);r={targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,error:n}}throw new Xn(e.message||("string"==typeof e?e:JSON.stringify(e)),{stack:e.stack,targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,sourceWidgetId:p.id,targetWidgetType:o.type,sourceWidgetType:p.type})})).finally((()=>{if(ro--,no)return Ds({thingId:s,widgetId:o.id,error:r})})))break}}}}catch(e){if(e instanceof Xn)throw e;console.error(`Error processing next widget [${i}]: ${e}`)}finally{ro<0&&(console.warn("Active execution counter is negative, this should never happen"),ro=0),0===ro&&Ys()}}},ao=async(e,t,n,r)=>{const i=ie(r);if(!i)return null;const s=se(r,n);if(!s)return s;const o=s.gates,a=s.gates[t],c=is(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),d=l.findIndex((t=>t.name===e));if(-1!==d){const e=((e,t,n)=>{for(const r in n){const i=n[r],s=i.children.length;for(let n=0;n<s;n++){const r=i.children[n],s=Ge(r.targetPort);if(r.childId===e&&s.portName===t)return i}}return null})(t,l[d].name,o);if(e){const t=is(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},co=e=>{const{gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}=e;if(!ie(o))throw new Error(`Failed to find recipe "${o}" in cache`);if(!oe(o,r,t))throw console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),new Error(`Gate ${t} not found in block ${r} for recipe ${o}`);return async(e,a)=>oo({portName:e,originalEvent:n||{timestamp:Date.now(),type:a.type,value:a.value},data:a,currentGateId:t,blockRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o})},lo=e=>{const{gateId:t,originalEvent:n,blockRecipeId:r,blockDbId:i,blockVersion:s,recipeId:o}=e,a=ie(o);if(!a)throw new Error(`Failed to find recipe "${o}" in cache`);const c=oe(o,r,t);if(!c)return console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),null;const l=co({gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}),d=c.type===ze.hubService,u=d?Js(t,a.blocks[r].gates):[],p=u.reduce(((e,t)=>e.pathSegments>t.pathSegments?e:t),u[0]),g={id:t,type:c.type,recipePoolId:o,thingRecipeId:r,recipeType:a.dbInfo.recipeType,returnOriginalEvent:!!c.returnOriginalEvent,registerInterrupt:(e,n,i,s,a)=>Xe.createInterrupt(e,o,r,t,n,i,s,a),cancelInterrupt:e=>Xe.destroyInterrupt(e),nextWidget:l,nextGate:l,getParentAtPort:e=>ao(e,t,r,o),getState:()=>Object.freeze({...c.state,...c.type===ze.input&&{customInputs:[]}}),setState:e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const n={...e,...c.type===ze.input&&!e.customInputs&&{customInputs:[]}},i={...c.state};c.state=n,eo&&eo({blockId:r,gateId:t,prevState:i,newState:{...n},recipeId:o})},...d&&p&&{eventContext:p.data.eventContext}};return g};Xe.setInvokeChildGateCb((async(e,t,n,r,i,s,o,a,c,l)=>so({interruptDriven:e,childGateId:t,block:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c,originalEvent:l})));const uo=(e,t,n,r,i)=>{const s=oe(e,n,r);if(!s)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=(t,i,s,o)=>Xe.createInterrupt(t,e,n,r,i,s,o),a=()=>Object.freeze({...s.state,...s.type===ze.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...s.type===ze.input&&!e.customInputs&&{customInputs:[]}};s.state=t},l=async t=>{const r=((e,t,n)=>{const r=ie(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=se(e,t);if(!i)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(i.storageUnits||[]).includes(n))throw new Error(`The Thing "${t}" has no access to storage unit "${n}"`);return r.storage[n]||null})(e,n,t);return r};if(i){return{getState:a,setState:c,registerInterrupt:o,getStorageData:l,nextWidget:co({gateId:r,thingRecipeId:n,thingDbId:s.id,thingVersion:"default",recipeId:e}),recipePoolId:e,recipeType:t,thingRecipeId:n,widgetId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r}},po=new o,go="invoked",ho="state",fo=()=>{Xe.destroyAllInterrupts()},mo=async(e,t,n)=>{const r=ie(e),i=oe(e,t,n);if(i&&r){const s=is(i.type);if(s&&"function"==typeof s.terminate){const i=((e,t,n,r)=>uo(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)}}}},yo=async e=>{const{recipePoolId:t,thingRecipeId:n,widgetRecipeId:r,options:i}=e,s=ie(t),o=oe(t,n,r);if(o&&s){const e=is(o.type);if(e&&"function"==typeof e.initialize){const a=((e,t,n,r)=>uo(e,t,n,r,!0))(t,s.dbInfo.recipeType,n,r);if(a){const t=e.initialize;try{(e=>{if(e.type===ze.script){const t=e.state;if((t.version||0)<2){const n=Object.keys(e.variablesListener||{});for(const t of n)if(e.variablesListener){const n=mr(t);e.variablesListener[n]=e.variablesListener[t],delete e.variablesListener[t],delete e.variables}t.version=2}}})(o),await t(a,i||{})}catch(e){throw console.warn(`Error initializing widget "${r}" in thing "${n}": `,e),e}}}}},vo=(e,t)=>{const n=ie(t);if(n)for(const t in n.blocks){const r=n.blocks[t];for(const t in r.gates)if(t===e)return{widget:r.gates[t],thing:r}}return null},bo=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,wo=e=>{po.emit(bo(ho),e),po.emit(bo(ho,e.blockId,e.gateId),e)};Qs=async e=>{await po.emit(bo(go),e),await po.emit(bo(go,e.blockId,e.gateId),e)},(e=>{eo=e})(wo);var So,Io,$o,_o,Co,ko,Eo,xo,No,Ao,Po,Oo,To,Lo=async(e,t,n,r,i)=>{const s=ae(e,{id:t,authorId:r,version:n,recipeType:i});fs(),Zs(),Xs(i);const o=ie(s);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=X.STARTING,o.addLog("recipe registered")),s},Bo=async e=>{const t=ie(e);var n;if(!t)return null;t.addLog("terminating recipe"),fo(),js();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await mo(e,n,t)}te[n=e]&&delete te[n]},Do=async(e,t)=>{const n=ie(e),r=[],i=[];if(n){$r({recipePoolId:e,thingId:ge});for(const s in n.blocks){const o=n.blocks[s];if(!t||!Array.isArray(t)||t.includes(s))for(const t in o.gates)try{if(n.dbInfo?.recipeType===Rn.Desktop){const e=o.gates[t];if(e.type===ze.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===ze.recipeLoad&&i.push(e)}await yo({recipePoolId:e,thingRecipeId:s,widgetRecipeId:t,options:{keepCurrentState:!0}})}catch(e){r.push({widgetId:t,error:e.message})}}}return{failed:r,sendToInputWidget:(t,n,r=ge)=>(async(e,t,n,r)=>{const i=ie(n),s=se(n,r),o=Date.now();if(s&&i)for(const i in s.gates){const a=s.gates[i];if(a.type===ze.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=is(a.type),l={...t,timestamp:o},d=lo({gateId:i,originalEvent:l,blockRecipeId:r,blockDbId:s.id,blockVersion:s.version,recipeId:n});if(d&&e.processEvent){const s={...d,getState:d.getState};Qs&&await Qs({recipeId:n,blockId:r,gateId:i,targetPort:rt,data:t}),to?await to(r,n,c,t):await e.processEvent(l,s)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of i)await io({widgetId:t.id,thingId:ge,recipeId:e,targetPortName:Yi,data:{type:fe.Boolean,value:!0}})}}},jo=e=>{Gi(e)},Uo=(e,t,n,r=!1)=>{const i=vo(t,e);if(i){const{widget:s,thing:o}=i,a={...s.state};s.state=n,r&&wo({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},Ro=(e,t)=>{const n=vo(t,e);return n?n.widget.state:null},Fo=async e=>{const{recipePoolId:t,currentGateId:n,sourcePortName:r,originalEvent:i,data:s,eventContext:o}=e,a=vo(n,t);if(a)return oo({portName:r,originalEvent:i,data:s,currentGateId:n,blockRecipeId:a.thing.recipeId,thingDbId:a.thing.id,thingVersion:a.thing.version,recipeId:t,eventContext:o})};!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(So||(So={})),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"}(Io||(Io={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}($o||($o={})),function(e){e.Bundle="bundle",e.Group="group"}(_o||(_o={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Co||(Co={})),function(e){e.Cloud="cloud",e.Web="web"}(ko||(ko={})),function(e){e.Cpu_128M="kmu-cpu-128m",e.Cpu_256M="kmu-cpu-256m",e.Cpu_512M="kmu-cpu-512m",e.Cpu_1024M="kmu-cpu-1024m",e.Cpu_2048M="kmu-cpu-2048m",e.Cpu_4096M="kmu-cpu-4096m"}(Eo||(Eo={})),function(e){e.Gateway="gateway",e.Timer="timer"}(xo||(xo={})),function(e){e.InstallInProgress="installation-in-progress"}(No||(No={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Ao||(Ao={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Po||(Po={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Oo||(Oo={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.UninstallHubService="uninstall_hub_service",e.ExportRecipe="export_recipe"}(To||(To={}));const Mo=(e,t)=>((e,t,n)=>{const r=Buffer.from(n,"base64"),i=r.subarray(0,16),s=r.subarray(16).toString("base64"),o=u(e,t,32),a=p("aes-256-cbc",o,i);let c=a.update(s,"base64","utf8");return c+=a.final("utf8"),c})(e.id||"recipe.kemu","kemu",t),Wo=e=>{try{return JSON.parse(e)}catch(e){return null}},Go="undefined"!=typeof window,Vo={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Ho={protocolPrefix:4,txtLength:4},zo=Object.values(Vo).reduce(((e,t)=>e+t),0),qo=Object.values(Ho).reduce(((e,t)=>e+t),0),Ko=["width","height","colorSpace"],Jo=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)Object.hasOwn(e,n)||Ko.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},Yo=(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},Xo=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(Object.hasOwn(n,s)){const{index:o,length:a,binaryType:c}=n[s];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&Yo(e,s,l)}return e},Zo=e=>f(e),Qo="KMSG",ea="KCMD",ta=Zo("klProtocol");var na={encode:(e,t,n)=>{const r={json:e.json},i=Jo(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,d=Vo.protocolPrefix+Vo.protocolVersion+Vo.jsonLength+Vo.binaryLength+Vo.fromServiceId+Vo.toServiceId+Vo.sentAt+l+o,u=Buffer.alloc(d),p=Date.now();let g=0;return u.write(Qo,g),g+=Vo.protocolPrefix,u.writeUInt8(1,g),g+=Vo.protocolVersion,u.writeUInt32LE(l,g),g+=Vo.jsonLength,u.writeUInt32LE(o,g),g+=Vo.binaryLength,u.writeUInt32LE(t,g),g+=Vo.fromServiceId,u.writeUInt32LE(n,g),g+=Vo.toServiceId,u.writeBigInt64LE(BigInt(p),g),g+=Vo.sentAt,c.copy(u,g),g+=l,s&&o&&s.copy(u,g),u},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Vo.protocolPrefix);if(t+=Vo.protocolPrefix,n!==Qo)return null;if(e.byteLength<zo)return ta(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Vo.protocolVersion;const i=e.readUInt32LE(t);t+=Vo.jsonLength;const s=e.readUInt32LE(t);t+=Vo.binaryLength;const o=e.readUInt32LE(t);t+=Vo.fromServiceId;const a=e.readUInt32LE(t);t+=Vo.toServiceId;const c=e.readBigInt64LE(t);t+=Vo.sentAt;const l=i+s,d=e.subarray(t,t+l),u=e.subarray(0,zo);let p=null;return e.byteLength-zo-i-s>0&&(p=e.subarray(zo+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[d],headerPackage:u},remaining:p}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),i=Wo(n);if(!i?.json)return ta("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Xo(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=zo+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<zo)return ta("Invalid Header Size"),e;let n=0;return n+=Vo.protocolPrefix,n+=Vo.protocolVersion,n+=Vo.jsonLength,n+=Vo.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Vo.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=qo+r,s=Buffer.alloc(i);return s.write(ea,t),t+=Ho.protocolPrefix,s.writeUint32LE(r,t),t+=Ho.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<qo)return{command:null};const n=e.toString("utf-8",t,Ho.protocolPrefix);if(t+=Ho.protocolPrefix,n!==ea)return{command:null};const r=e.readUInt32LE(t);t+=Ho.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-qo-r;let o=null;s>0&&(o=e.subarray(qo+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const ra="KMSG",ia="KCMD",sa=Zo("klProtocol"),oa=new TextEncoder;var aa={encode:(e,t,n)=>{const r={json:e.json},i=Jo(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=oa.encode(a),l=c.byteLength,d=new ArrayBuffer(Vo.protocolPrefix+Vo.protocolVersion+Vo.jsonLength+Vo.binaryLength+Vo.fromServiceId+Vo.toServiceId+Vo.sentAt+l+o),u=new DataView(d),p=new Uint8Array(d),g=Date.now();let h=0;for(let e=0;e<4;++e)p[h++]=ra.charCodeAt(e);return u.setUint8(h,1),h+=Vo.protocolVersion,u.setUint32(h,l,!0),h+=Vo.jsonLength,u.setUint32(h,o,!0),h+=Vo.binaryLength,u.setUint32(h,t,!0),h+=Vo.fromServiceId,u.setUint32(h,n,!0),h+=Vo.toServiceId,u.setBigInt64(h,BigInt(g),!0),h+=Vo.sentAt,p.set(c,h),h+=l,s&&o&&p.set(new Uint8Array(s),h),d},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Vo.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==ra)return null;if(e.byteLength<zo)return sa.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Vo.protocolVersion;const s=t.getUint32(n,!0);n+=Vo.jsonLength;const o=t.getUint32(n,!0);n+=Vo.binaryLength;const a=t.getUint32(n,!0);n+=Vo.fromServiceId;const c=t.getUint32(n,!0);n+=Vo.toServiceId;const l=t.getBigInt64(n,!0);n+=Vo.sentAt;const d=s+o,u=e.slice(n,n+d),p=new Uint8Array(e,0,zo);let g=null;if(e.byteLength-zo-s-o>0){g=new Uint8Array(e,zo+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[u],headerPackage:p.slice().buffer},remaining:g}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Wo(s);if(!a?.json)return sa.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Xo(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,d=null;const u=zo+e.jsonLength+e.binaryLength;return c.byteLength>u&&(d=c.subarray(u),l=c.subarray(0,u)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:d?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<zo)return sa("Invalid Header Size"),e;let n=0;n+=Vo.protocolPrefix,n+=Vo.protocolVersion,n+=Vo.jsonLength,n+=Vo.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Vo.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=oa.encode(e),r=n.byteLength,i=new ArrayBuffer(qo+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=ia.charCodeAt(e);return s.setUint32(t,r,!0),t+=Ho.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<qo)return{command:null};let r="";for(let e=0;e<Ho.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==ia)return{command:null};const i=t.getUint32(n,!0);n+=Ho.txtLength;const s=e.byteLength-qo-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-qo)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(qo+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};let ca=na;Go&&(ca=aa);var la,da=ca;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(la||(la={}));let ua=Math.ceil(Date.now()/1e3);let pa,ga,ha,fa,ma,ya=!1;var va=()=>{ya=!0},ba=(e,t)=>{if(!pa)throw new Error("Memory connection not set.");pa.sendBuf(e,t)},wa=e=>ga=e,Sa=e=>ma=e,Ia=e=>ha=e,$a=e=>fa=e;const _a=async(e,t=2)=>{const n=async(e,r)=>{if(Array.isArray(e))for(let i=0;i<e.length;i++){const s=e[i];if(s&&"object"==typeof s)if(Array.isArray(s))await n(s,r+1);else{const o=s._kemuType;void 0!==o?o===fe.ImageData&&(e[i]=await Ve(s)):r<t&&await n(s,r+1)}}else if("object"==typeof e&&null!==e){const i=Object.keys(e);for(const s of i){const i=e[s];if(i&&"object"==typeof i){const o=i._kemuType;void 0!==o?o===fe.ImageData&&(e[s]=await Ve(i)):r<t&&await n(i,r+1)}}}};return await n(e,1),e};Zo("klTransmissionManager"),Zo("ipcClient");Zo("kemuWidgetService"),k(process.argv.slice(2));const Ca=e=>f(`runner:${e}`),ka=Ca("connectionManager"),Ea=Ca("remoteInvoke"),xa=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=Go?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=da.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}ua+=1;const d=`${i}-${ua}-exec-${e.substring(0,10)}`,u={messageId:d,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};u.promise=new Promise(((e,t)=>{u.resolve=e,u.reject=t}));let p=Go?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:r,messageId:d,type:"execute"}};o(c)&&(p=da.encode(g,a,c)),t[d]=u,n&&n(`Calling remote function "${e}" with message id "${d}"`);const h="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(u.fulfilled=!0,u.resolve([void 0]),delete t[d]):0===l?.timeout||h||(u.timer=setTimeout((()=>{n&&n(`Remote function ${d} timed out`);const r=t[d];r&&!r.fulfilled&&(r.fulfilled=!0,u.reject(`Function ${e} Timed out`)),delete t[d]}),l?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:g}),u.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,s)=>{ua+=1;const a=`${i}-${ua}-multicast-${e.substring(0,10)}`;let c=Go?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let d=o(r[0].serviceId);d&&(c=da.encode(l,s,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(d=o(i.serviceId),d&&(c=da.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");xa.setLogger(Ea);const Na=new o,Aa=new o;let Pa,Oa=null,Ta=null,La=null,Ba=null;const Da={},ja=()=>{if(!La)throw new Error("API key is required to interact with the hub");return La},Ua=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return Da[r]=i,i},Ra=(e,t)=>Da[`${e}_${t}`]||null,Fa=async(e,t)=>{if(!Oa)return ka("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await xa.execute(be.GetServiceContents,n,Wa,Oa,0))[0]},Ma=async(e,t,n=!1)=>{if(!e||!t)return null;const r=Ra(e,t);if(!r||n){const n=r||Ua(e,t);try{const r=await Fa(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){ka(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},Wa=ba,Ga=()=>{ka("Disconnected from the server"),Oa=null,Ba=null,xa.rejectAllPending("Disconnected from the server"),Na.emit("disconnected")},Va=()=>{ka("Connected to the server"),Na.emit("connected")},Ha=()=>Ta,za=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,qa=async()=>{const e=Ha();if(e){const t=ie(e)?.blocks;if(t){const n={};for(const r in t){const i=t[r];for(const t in i.gates){const r=i.gates[t];if(r.type===ze.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{ka(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await cc({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){ka(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},Ka=async e=>{if(!e)return void ka("Hub sent ACK request without service id");const t={apiKey:ja(),ackSessionId:e};await xa.execute(be.SocketAckResponse,[t],Wa,e,0),ka("Hub Link acknowledged"),Oa=e,Na.emit("acknowledged"),qa()},Ja=async e=>{const t=e.args[0],n=za("broadcast",`hub_${t.type}`,(0).toString(),"");await Aa.emit(n,t)},Ya=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===fe.ImageData&&je(e.value)&&(e.value=await Ve(e.value));const n=Ha();if(n){const r=ie(n);if(r){const i=async e=>{const n=za("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await Aa.emit(n,t)}catch(t){ka(`Failed to emit broadcast event for target ${e}`,t)}};await i("app");for(const s in r.blocks){const o=r.blocks[s];for(const r in o.gates){const s=o.gates[r];if(s.disabled)continue;const a=s.state;if(s.type===ze.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await i(r);const s=a?.service?.name&&t.eventContext?{[a.service.name]:t.eventContext}:void 0;for(const i of t.outputs||[])if(null!==i.value&&void 0!==i.value){const t={type:i.type,value:i.value,timestamp:Date.now()};ka(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await Fo({recipePoolId:n,currentGateId:r,sourcePortName:i.name,originalEvent:t,data:t,eventContext:s})}}}}}}},Xa=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,s=Ro(r,i);let o=s;if(n&&o&&s&&(o={...s,customState:n},Uo(r,i,o,!0)),o?.service)try{const e=za("setOutputs",o.service.name,o.service.version,i);await Aa.emit(e,t.outputs)}catch(e){ka(`Failed to emit setOutputs event for widget ${i}`,e)}let a=null;for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===fe.ImageData){if(!je(n.value)){ka(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=await Ve(n.value)}else n.type!==fe.JsonObj&&n.type!==fe.Array||await _a(n.value);const s={type:n.type,value:n.value,timestamp:Date.now()};ka(`Sending data to output ${n.name} requested by messageId ${e.messageId}`);const c=o?.service?.name&&t.eventContext?{[o.service.name]:t.eventContext}:void 0;try{await Fo({recipePoolId:r,currentGateId:i,sourcePortName:n.name,originalEvent:s,data:s,eventContext:c})}catch(e){ka(`Failed to trigger next global widget for output ${n.name}`,e),a=e;break}}if(a){const t=a instanceof Xn,n=a;e.reply({error:a.message,errCode:t?"CHILD_WIDGET_ERROR":"INVOKING_ERROR",errData:{targetWidgetId:n.targetWidgetId,targetPortName:n.targetPortName,sourcePortName:n.sourcePortName,sourceWidgetId:n.sourceWidgetId,targetWidgetType:n.targetWidgetType,sourceWidgetType:n.sourceWidgetType}})}else e.reply({success:[]})},Za=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,s=Ro(r,i);if(s){const t={...s,customState:{...s.customState,...n}};return Uo(r,i,t,!0),e.reply({success:[]})}},Qa=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:s,key:o}=n;ka(`Received request to set a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const a=Ro(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:s},Uo(r,i,e,!0)}return t({success:[]})},ec=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:s}=n;ka(`Received request to get a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const o=Ro(r,i);if(o){const e=o.dependencies?.[s]?.path;return ka(`Returning dependency path for "${s}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},tc=async()=>{if(ka(`Requesting services on ${(new Date).toISOString()}`),!Oa)return ka("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await xa.execute(be.GetServices,[],Wa,Oa,0);Pa=e;for(const t of e.available){if(t.internal)continue;const e=Ra(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||Ua(t.name,t.version);ka(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await Fa(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){ka(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},nc=()=>Pa||{available:[],installed:[],failed:[]},rc=()=>!!Pa,ic=async e=>{const{targetServiceSessionId:t}=e;if(!Oa)return void ka("No target service session id provided");ka(`Forwarding "onParentEvent" to service ${t}`);return await xa.execute(be.OnParentEvent,[e],Wa,Oa,t,e.config).catch((e=>{throw ka(`Error invoking onParentEvent callback: ${e}`),e.errCode===la.ParentEventCallbackError?e.error:e}))},sc=async e=>{if(!Oa)return ka("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await xa.execute(be.GetDefaultState,[],Wa,Oa,e);return t},oc=async(e,t,n,r)=>{if(!Oa)return ka("Hub Link has not been acknowledged. Cannot get services."),null;const[i]=await xa.execute(be.UIEvent,[t,n],Wa,Oa,e,r);return i},ac=(e,t)=>{const n=()=>{t()};return Na.on(e,n),()=>Na.off(e,n)},cc=async e=>{if(Oa)return xa.execute(be.SubscribeToService,[e],Wa,Oa,0);ka("Hub Link has not been acknowledged. Cannot subscribe to services.")},lc=async e=>{if(Oa)return xa.execute(be.UnsubscribeFromService,[e],Wa,Oa,0);ka("Hub Link has not been acknowledged. Cannot subscribe to services.")},dc=(e,t,n,r)=>{const i=za("broadcast",t,n,e);return Aa.on(i,r)},uc=(e,t,n,r)=>{const i=za("setOutputs",t,n,e);return Aa.on(i,r)},pc=async(e,t,n)=>Oa?xa.execute(e,t,Wa,Oa,0,n):(ka("Hub Link has not been acknowledged. Cannot execute function."),null),gc=async e=>{if(!Oa)return void ka("Hub Link has not been acknowledged. Cannot execute function.");const t=Ro(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 xa.execute(be.InitializeInstance,r,Wa,Oa,e.sessionId);if(i){const t=Ro(e.recipeId,e.widgetId);if(t){const n={...t,customState:i};Uo(e.recipeId,e.widgetId,n,!0)}}},hc=async(e,t,n,r)=>{if(!Oa)return void ka("Hub Link has not been acknowledged. Cannot execute function.");const i=Ro(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 xa.execute(be.TerminateInstance,s,Wa,Oa,e)},fc=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=rc(),o=r||!s?await tc():nc();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},mc=async()=>{if(!Oa)return ka("Hub Link has not been acknowledged. Cannot get services."),null;if(Ba)return Ba;const[e]=await xa.execute(be.GetSystemInfo,[],Wa,Oa,0).catch((e=>(ka("Failed to get system info",e),[null])));return Ba=e,e};var yc,vc,bc,wc,Sc,Ic,$c,_c,Cc=async e=>{Ia(Va),$a(Ga),La=e,Sa((({json:e,transmission:t})=>{xa.processMessage("websocket",Wa,t,e)})),xa.registerFunction(be.SetState,Za),xa.registerFunction(be.SetOutputs,Xa),xa.registerFunction(be.BroadcastEvent,Ya),xa.registerFunction(be.HubBroadcastEvent,Ja),xa.registerFunction(we.SetDependencyPath,Qa),xa.registerFunction(we.GetDependencyPath,ec),wa((e=>{((e,t)=>{const n=ve.SocketAcknowledge,r=ve.IpcAcknowledge,i=e.startsWith(n);if(e===r)return t&&t(),0;if(i){const s=e.split(i?n:r),o=parseInt(s[1]);return t&&t(o),o}})(e,Ka),((e,t)=>{e===ve.ServicesListChanged&&(t&&t())})(e,(()=>{ka("Services list changed"),Na.emit("services-changed")}))})),await va()},kc=(e,t)=>{Na.on(e,t)},Ec=()=>({getServices:tc,getServiceContents:Ma,onParentEvent:ic,onCommand:ac,getDefaultState:sc,getCachedServices:nc,areServicesCached:rc,subscribeToServiceEvents:cc,unsubscribeFromServiceEvents:lc,callProcessorHandler:oc,onBroadcastEvent:dc,onSetOutputsEvent:uc,executeHubFunction:pc,initializeServiceInstance:gc,terminateServiceInstance:hc,getCompatibleService:fc,getHubSystemInfo:mc}),xc=e=>{Ta=e},Nc=()=>xa;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(yc||(yc={})),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"}(vc||(vc={})),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"}(bc||(bc={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(wc||(wc={})),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:"}(Sc||(Sc={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(Ic||(Ic={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}($c||($c={})),function(e){e.IPC="ipc",e.WS="ws"}(_c||(_c={}));const Ac=e=>{try{return JSON.parse(e)}catch(e){return null}},Pc=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Oc=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(Pc);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},Tc=e=>"*"===e||"x"===e||"X"===e,Lc=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},Bc=(e,t)=>{if(Tc(e)||Tc(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(Lc(e),Lc(t));return n>r?1:n<r?-1:0},Dc=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=Bc(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},jc=(e,t,n)=>{Fc(n);const r=((e,t)=>{const n=Oc(e),r=Oc(t),i=n.pop(),s=r.pop(),o=Dc(n,r);return 0!==o?o:i&&s?Dc(i.split("."),s.split(".")):i||s?i?-1:1:0})(e,t);return Uc[n].includes(r)},Uc={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},Rc=Object.keys(Uc),Fc=e=>{if(-1===Rc.indexOf(e))throw new Error(`Invalid operator, expected one of ${Rc.join("|")}`)};var Mc="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Wc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Gc,Vc,Hc,zc,qc,Kc={exports:{}},Jc={exports:{}};function Yc(){if(Vc)return Gc;Vc=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 Gc=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 Xc(){if(zc)return Hc;return zc=1,Hc=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=Yc(),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},Hc}var Zc,Qc,el,tl,nl,rl={exports:{}};function il(){return Qc||(Qc=1,Zc=(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)}),Zc}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?Kc.exports=(qc||(qc=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=Xc()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Jc,Jc.exports)),Jc.exports):Kc.exports=(nl||(nl=1,function(e,t){const n=E,r=c;t.init=function(e){e.inspectOpts={};const n=Object.keys(t.inspectOpts);for(let r=0;r<n.length;r++)e.inspectOpts[n[r]]=t.inspectOpts[n[r]]},t.log=function(...e){return process.stderr.write(r.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(n){const{namespace:r,useColors:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),s=` ${i};1m${r} [0m`;n[0]=s+n[0].split("\n").join("\n"+s),n.push(i+"m+"+e.exports.humanize(this.diff)+"[0m")}else n[0]=(t.inspectOpts.hideDate?"":(new Date).toISOString()+" ")+r+" "+n[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)},t.destroy=r.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if(tl)return el;tl=1;const e=x,t=E,n=il(),{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)),el={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=Xc()(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)}}(rl,rl.exports)),rl.exports);var sl=Wc(Kc.exports);const ol=e=>sl(e),al=Date.now();let cl=Math.ceil(al/1e3);var ll=()=>cl+=1;const dl=y(N(),"kemu-user-services"),ul=y(N(),"kemu-test-services"),pl="KMU-CB-v1",gl=process.env.HUB_PKG_VERSION||'"1.3.5"';var hl;!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"}(hl||(hl={}));const fl=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>vc[e])):vc[e.type]}),ml=async e=>{try{return await S(e,"utf-8")}catch(e){return null}},yl=e=>{if(e&&e.startsWith(pl)){const t=e.slice(9),n=decodeURI(t);return Ac(n)}return null},vl=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(fl)}:{},...e.outputs?{outputs:e.outputs.map(fl)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(fl)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(fl)}:{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 ml(y(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const s=t.startsWith(pl)?t:`${pl}${t}`,o=yl(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===hl.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${i}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${i}" does not contain a top level widgetGroup`);continue}const l=c.state,d={name:l.name,color:l.color,description:l.description,contents:s,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(d)}return r})(t,e,n?.log);if(s.length?i.customWidgets=s:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await S(y(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},bl=async e=>{try{return await I(e,$.F_OK),!0}catch{return!1}};let wl=null,Sl=null;const Il=()=>wl||dl,$l=ol("servicesManager"),_l={};let Cl=null,kl=null,El=null;class xl extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const Nl=async e=>{try{return await I(e),!0}catch{return!1}},Al=async e=>{if(!Cl)throw new Error('IPC config not set, call "setHubIpcConfig" first.');try{if(e.processor===wc.Javascript){$l(`Spawning service ${e.name} with sessionId ${e.sessionId}`);const t=m.join(e.path,"processor.js"),n=m.join(e.path,"processor.mjs"),r=await Nl(t)?t:n,i=[`--sessionId=${e.sessionId.toString()}`,`--ipcSpace=${Cl.appSpace}`,`--ipcId=${Cl?.id}`,`--recipePath=${Cl.recipePath||""}`];if(e.internal&&i.push("--internal=true"),!El)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const s=await El({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 xl(`Missing required environment variables: ${o.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,n)=>{if(!kl)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const o=kl({args:[r,...i],serviceInfo:{name:e.name,version:e.version},options:{env:s}});o.stdout.on("data",(t=>{$l(`[${e.name}] - stdout: ${t}`)})),o.stderr.on("data",(t=>{$l(`[${e.name}] - stderr: ${t}`)})),o.on("exit",(t=>{$l(`[${e.name}] exited with code ${t}`)})),o.on("spawn",(()=>{$l(`[${e.name}] spawned with PID ${o.pid}`),t(o)})),o.on("error",(t=>{$l(`[${e.name}] error: ${t}`),n(new xl(`Error spawning service ${e.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.processor}`}catch(t){if(t instanceof xl)throw t;throw`Error spawning service ${e.name}: ${t}`}},Pl=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[wc.Javascript,wc.Executable,wc.Python].includes(e?.processor)?null:"Invalid processor"},Ol=async(e,t)=>{const n=m.join(e,"manifest.json");if(!await Nl(n)){const t=`Missing manifest for service ${e}. Aborting.`;return $l(t),{error:t}}const r=await S(n,"utf-8"),i=Ac(r),s=Pl(i);if(!i||s){const t=`Invalid service manifest [${e}]: ${s}. Aborting.`;return $l(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(m.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return $l(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await ml(m.join(e,i.svgIcon));if(!t){return{error:`Error loading icon for service ${i.name}`}}i.svgIcon=t}})(),(async()=>{if(i.subServices?.length)for(const t of i.subServices){const n=m.join(e,t),{error:r,service:s}=await Ol(n);r?$l(`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(m.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){$l(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=ll(),c=t?.fixedSession||a;$l(`Loaded service ${i.name} with sessionId ${c}`);const l=await vl(i,e,{widgetUIContents:o});return Tl(l),_l[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null},{service:_l[c]}},Tl=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=g("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},Ll=async e=>{try{return e.childProcess=await Al(e.info),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return $l(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof xl?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},Bl=e=>{const{path:t,...n}=e.info;return{...n}},Dl=()=>Object.values(_l).filter((e=>"running"===e.status)).map(Bl),jl=e=>{const{serviceName:t,version:n,force:r}=e,i=Object.values(_l).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){$l(`Stopping service "${t} (v${n})"`);i.childProcess.kill("SIGINT")||$l(`Failed to stop service ${t}`)}return i.status="stopped",$l(`Service ${t} stopped`),i},Ul=e=>e.info.internal?e.info.path:m.join(e.info.path,".."),Rl=e=>!!e.internal;var Fl={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await bl(e))return void $l(`Failed to load services from "${e}". Directory does not exist.`);const n=(await _(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));$l(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],s=m.join(e,i),{error:o,service:a}=await Ol(`${s}${t?.internalServices?"":"/dist"}`,t);o&&$l(`Failed to load service ${s}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if($l("Initializing services"),!Cl)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in _l){const n=_l[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?$l(`Service ${n.info.name} is in the noSpawningList. Skipping.`):Ll(n)}$l("Services initialized")},setServiceStatus:(e,t)=>{const n=_l[e];return n?(n.status=t,!0):($l(`Service with serviceId ${e} not found`),!1)},getActiveServices:Dl,getMatchingService:(e,t)=>{const n=Object.values(_l).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(jc(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>_l[e]||null,killAllServices:()=>{for(const e in _l){const t=_l[e];if(t.childProcess)try{$l(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){$l(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await vl(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};_l[e]=r,Tl(_l[e].info)},setServiceManifest:(e,t,n)=>{const r=_l[e];if(!r)return $l(`Service with sessionId ${e} not found`),!1;const i=Pl(t);if(i)return $l(`Invalid manifest for service ${r.info.name}: ${i}`),!1;Tl(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(_l).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:()=>Dl().filter((e=>e.internal)),getAllServices:()=>Object.values(_l),stopService:jl,uninstallService:async(e,t)=>{$l(`Uninstalling service ${e} v${t}`);const n=jl({serviceName:e,version:t});if(!n)return!1;$l(`Service ${e} stopped. Removing from disk...`);const r=Ul(n),i=Il();return r.startsWith(i)?(await C(r,{recursive:!0,force:!0}),$l(`Service ${e} successfully removed from disk`),(e=>{const t=_l[e];delete _l[e]})(n.info.sessionId),!0):($l(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(_l).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{Cl={...e}},loadAndLaunch:async(e,t,n)=>{const r=b(e,t),{error:i,service:s}=await Ol(r);if(i||!s)return{errorMsg:i};try{s.info.internal=!!n,s.childProcess=await Al(s.info),s.status="started"}catch(e){s.status="error",e instanceof xl?($l(`Service spawning error: ${e.message} (${e.code})`),s.errorMsg=e.message,s.errorCode=e.code):($l(`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:Ul,setSpawnNodeFunction:e=>{kl=e},setGetSecretsFunction:e=>{El=e},restartService:async(e,t)=>{$l(`Restarting service ${e} v${t}`);const n=jl({serviceName:e,version:t,force:!0});return!!n&&Ll(n)},getFailedServices:()=>Object.values(_l).filter((e=>"error"===e.status)).map((e=>({...Bl(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Rl,isNotInternalKemuService:e=>!Rl(e),isNotDevService:e=>!e.devMode};class Ml{constructor(){}appspace="app.";socketRoot="/tmp/";id=x.hostname();encoding="utf8";rawBuffer=!1;sync=!1;unlink=!0;delimiter="\f";silent=!1;logDepth=5;logInColor=!0;logger=console.log.bind(console);maxConnections=100;retry=500;maxRetries=1/0;stopRetrying=!1;IPType=function(){const e=x.networkInterfaces();let t="";e&&Array.isArray(e)&&e.length>0&&(t=e[Object.keys(e)[0]][0].family);return t}();tls=!1;networkHost="IPv6"==this.IPType?"::1":"127.0.0.1";networkPort=8e3;readableAll=!1;writableAll=!1;interface={localAddress:!1,localPort:!1,family:!1,hints:!1,lookup:!1}}class Wl{constructor(e){e||(e=new Ml),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 Gl=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={}},Vl=Wc(Gl);var Hl=Wc((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 zl{}class ql{}const Kl=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 zl,t=ql){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 zl}}())}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 Jl{constructor(){}on(e,t,n=!1){return Kl.string(e),Kl.function(t),Kl.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(Kl.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Kl.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){Kl.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)=>{Kl.string(e),Kl.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 Yl=new Wl;class Xl extends Jl{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Yl=new Wl(this.config)}Client=Xl;queue=new Hl;socket=!1;connect=ed;emit=Zl;retriesRemaining=0;explicitlyDisconnected=!1}function Zl(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Vl;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Yl.format(n),this.config.sync?this.queue.add(Ql.bind(this,n)):this.socket.write(n)}function Ql(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function ed(){let e=this;if(e.log("requested connection to ",e.id,e.path),!this.path)return void e.log("\n\n######\nerror: ",e.id," client has not specified socket path it wishes to connect to.");const t={};if(e.port)if(t.host=e.path,t.port=e.port,e.config.interface.localAddress&&(t.localAddress=e.config.interface.localAddress),e.config.interface.localPort&&(t.localPort=e.config.interface.localPort),e.config.interface.family&&(t.family=e.config.interface.family),e.config.interface.hints&&(t.hints=e.config.interface.hints),e.config.interface.lookup&&(t.lookup=e.config.interface.lookup),e.config.tls){if(e.log("Connecting client via TLS to",e.path,e.port,e.config.tls),e.config.tls.private&&(e.config.tls.key=O.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=O.readFileSync(e.config.tls.public)),e.config.tls.trustedConnections){"string"==typeof e.config.tls.trustedConnections&&(e.config.tls.trustedConnections=[e.config.tls.trustedConnections]),e.config.tls.ca=[];for(let t=0;t<e.config.tls.trustedConnections.length;t++)e.config.tls.ca.push(O.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=P.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=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)!=Yl.delimiter||-1==t.indexOf(Yl.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Yl.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Vl;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 td=new Wl;class nd extends Jl{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,td=new Wl(this.config),this.on("close",sd.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=rd;broadcast=id;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?O.unlink(this.path,ld.bind(this)):ld.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function rd(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Vl;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=td.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 id(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Vl;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):td.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 sd(){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 od(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)==td.delimiter&&-1!=t.indexOf(td.delimiter))for(r.ipcBuffer="",t=td.parse(t);t.length>0;){let e=new Vl;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 ad(e){this.publish("close",e)}function cd(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",ad.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",od.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 ld(){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=ud.bind(this),this.server.on("listening",function(){cd.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?dd.bind(this)():this.server=A.createServer(cd.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 dd(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=O.readFileSync(this.config.tls.private):this.config.tls.key=O.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=O.readFileSync(this.config.tls.public):this.config.tls.cert=O.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=O.readFileSync(this.config.tls.dhparam)),this.config.tls.trustedConnections){"string"==typeof this.config.tls.trustedConnections&&(this.config.tls.trustedConnections=[this.config.tls.trustedConnections]),this.config.tls.ca=[];for(let e=0;e<this.config.tls.trustedConnections.length;e++)this.config.tls.ca.push(O.readFileSync(this.config.tls.trustedConnections[e]))}this.server=P.createServer(this.config.tls,cd.bind(this))}function ud(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 pd{constructor(){}config=new Ml;of={};server=!1;get connectTo(){return vd}get connectToNet(){return bd}get disconnect(){return hd}get serve(){return fd}get serveNet(){return yd}get log(){return gd}set connectTo(e){return vd}set connectToNet(e){return bd}set disconnect(e){return hd}set serve(e){return fd}set serveNet(e){return yd}set log(e){return gd}}function gd(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=c.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function hd(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 fd(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=md),this.server=new nd(e,this.config,gd),this.server.on("start",t)}function md(){}function yd(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=md),this.server=new nd(e,this.config,gd,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function vd(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=md),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 Xl(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 bd(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=md),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 Xl(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 wd=new class extends pd{constructor(){super()}IPC=pd};var Sd={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const Id=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),$d=e=>{try{return JSON.parse(e)}catch(e){return null}},_d="undefined"!=typeof window,Cd={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},kd={protocolPrefix:4,txtLength:4},Ed=Object.values(Cd).reduce(((e,t)=>e+t),0),xd=Object.values(kd).reduce(((e,t)=>e+t),0),Nd=["width","height","colorSpace"],Ad=(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)||Nd.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},Pd=(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},Od=(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&&Pd(e,s,l)}return e},Td=e=>sl(e),Ld="KMSG",Bd="KCMD",Dd=Td("klProtocol");var jd={encode:(e,t,n)=>{const r={json:e.json},i=Ad(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,d=Cd.protocolPrefix+Cd.protocolVersion+Cd.jsonLength+Cd.binaryLength+Cd.fromServiceId+Cd.toServiceId+Cd.sentAt+l+o,u=Buffer.alloc(d),p=Date.now();let g=0;return u.write(Ld,g),g+=Cd.protocolPrefix,u.writeUInt8(1,g),g+=Cd.protocolVersion,u.writeUInt32LE(l,g),g+=Cd.jsonLength,u.writeUInt32LE(o,g),g+=Cd.binaryLength,u.writeUInt32LE(t,g),g+=Cd.fromServiceId,u.writeUInt32LE(n,g),g+=Cd.toServiceId,u.writeBigInt64LE(BigInt(p),g),g+=Cd.sentAt,c.copy(u,g),g+=l,s&&o&&s.copy(u,g),u},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Cd.protocolPrefix);if(t+=Cd.protocolPrefix,n!==Ld)return null;if(e.byteLength<Ed)return Dd(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Cd.protocolVersion;const i=e.readUInt32LE(t);t+=Cd.jsonLength;const s=e.readUInt32LE(t);t+=Cd.binaryLength;const o=e.readUInt32LE(t);t+=Cd.fromServiceId;const a=e.readUInt32LE(t);t+=Cd.toServiceId;const c=e.readBigInt64LE(t);t+=Cd.sentAt;const l=i+s,d=e.subarray(t,t+l),u=e.subarray(0,Ed);let p=null;return e.byteLength-Ed-i-s>0&&(p=e.subarray(Ed+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[d],headerPackage:u},remaining:p}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),i=$d(n);if(!i?.json)return Dd("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Od(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=Ed+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<Ed)return Dd("Invalid Header Size"),e;let n=0;return n+=Cd.protocolPrefix,n+=Cd.protocolVersion,n+=Cd.jsonLength,n+=Cd.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Cd.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=xd+r,s=Buffer.alloc(i);return s.write(Bd,t),t+=kd.protocolPrefix,s.writeUint32LE(r,t),t+=kd.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<xd)return{command:null};const n=e.toString("utf-8",t,kd.protocolPrefix);if(t+=kd.protocolPrefix,n!==Bd)return{command:null};const r=e.readUInt32LE(t);t+=kd.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-xd-r;let o=null;s>0&&(o=e.subarray(xd+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Ud="KMSG",Rd="KCMD",Fd=Td("klProtocol"),Md=new TextEncoder;var Wd={encode:(e,t,n)=>{const r={json:e.json},i=Ad(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=Md.encode(a),l=c.byteLength,d=new ArrayBuffer(Cd.protocolPrefix+Cd.protocolVersion+Cd.jsonLength+Cd.binaryLength+Cd.fromServiceId+Cd.toServiceId+Cd.sentAt+l+o),u=new DataView(d),p=new Uint8Array(d),g=Date.now();let h=0;for(let e=0;e<4;++e)p[h++]=Ud.charCodeAt(e);return u.setUint8(h,1),h+=Cd.protocolVersion,u.setUint32(h,l,!0),h+=Cd.jsonLength,u.setUint32(h,o,!0),h+=Cd.binaryLength,u.setUint32(h,t,!0),h+=Cd.fromServiceId,u.setUint32(h,n,!0),h+=Cd.toServiceId,u.setBigInt64(h,BigInt(g),!0),h+=Cd.sentAt,p.set(c,h),h+=l,s&&o&&p.set(new Uint8Array(s),h),d},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Cd.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ud)return null;if(e.byteLength<Ed)return Fd.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Cd.protocolVersion;const s=t.getUint32(n,!0);n+=Cd.jsonLength;const o=t.getUint32(n,!0);n+=Cd.binaryLength;const a=t.getUint32(n,!0);n+=Cd.fromServiceId;const c=t.getUint32(n,!0);n+=Cd.toServiceId;const l=t.getBigInt64(n,!0);n+=Cd.sentAt;const d=s+o,u=e.slice(n,n+d),p=new Uint8Array(e,0,Ed);let g=null;if(e.byteLength-Ed-s-o>0){g=new Uint8Array(e,Ed+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[u],headerPackage:p.slice().buffer},remaining:g}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=$d(s);if(!a?.json)return Fd.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Od(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,d=null;const u=Ed+e.jsonLength+e.binaryLength;return c.byteLength>u&&(d=c.subarray(u),l=c.subarray(0,u)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:d?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Ed)return Fd("Invalid Header Size"),e;let n=0;n+=Cd.protocolPrefix,n+=Cd.protocolVersion,n+=Cd.jsonLength,n+=Cd.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Cd.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Md.encode(e),r=n.byteLength,i=new ArrayBuffer(xd+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=Rd.charCodeAt(e);return s.setUint32(t,r,!0),t+=kd.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<xd)return{command:null};let r="";for(let e=0;e<kd.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Rd)return{command:null};const i=t.getUint32(n,!0);n+=kd.txtLength;const s=e.byteLength-xd-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-xd)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(xd+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};const Gd=Td("klTransmissionManager"),Vd=()=>{const e=(t,n,r,i)=>{let s=n,o=null;const a=t instanceof ArrayBuffer;if(Gd(`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=Wd.decodeHeader(c)):(c=s?.partialHeaderData?Buffer.concat([s.partialHeaderData,t]):t,o=jd.decodeHeader(c)),!o){const{command:t,missing:s,remainingData:o}=a?Wd.decodeCommand(c):jd.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):Gd(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?(Gd(`${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 Gd(`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;Gd(`Received ${s.header.totalBytesReceived} of ${s.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?Wd.decodeFullKlMessage(s.header):jd.decodeFullKlMessage(s.header),c=s.header.totalBytesReceived,l=s.header.remaining;r(null),o&&i({klMessage:o.message,complete:!0,sourceServiceId:s.header.fromServiceId,targetServiceId:s.header.toServiceId,rawMessage:o.message.rawMessage});let d=l;if(o?.remaining&&(d=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),s=new Uint8Array(t),o=new Uint8Array(r);return o.set(i),o.set(s,i.length),r})(l,o.remaining):o.remaining:l?Buffer.concat([l,o.remaining]):o.remaining),d)return Gd(`${d.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(d,null,r,i)}};return e};wd.config={...wd.config,...Sd};const Hd={info:ol("ipcServer:info"),data:ol("ipcServer:data")};let zd,qd,Kd,Jd,Yd={};const Xd=Vd(),Zd=e=>{Yd[e]&&(Hd.info(`Client disconnected [${e}]`),delete Yd[e],qd&&qd(e))};var Qd=e=>(e?.ipcId&&(wd.config.id=e.ipcId),e?.ipcAppSpace&&(wd.config.appspace=e.ipcAppSpace),new Promise((e=>{wd.serve((()=>{Hd.info("IPC Server Initiated"),wd.server.on("data",((e,t)=>{const n=Yd[t.id];n?(Hd.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Xd(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Hd.data(`Received command from client [${t.id}]: ${e.command}`),void(Kd&&Kd(t.id,e.command,n));e.klMessage&&Jd&&Jd({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Hd.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),wd.server.on("connect",(e=>{const t=ll();Hd.info(`New client connected. Registered as "${t}"`),e.id=t,Yd[t]={socket:e,activeMessage:null,disconnectHandler:()=>Zd(t)},e.on("close",Yd[t].disconnectHandler),zd&&zd(t)})),wd.server.on("disconnect",(e=>{Zd(e.id)})),wd.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),wd.server.start()}))),eu=e=>{zd=e},tu=e=>{qd=e},nu=e=>Jd=e,ru=(e,t)=>{const n=Yd[e];if(!n)return Hd.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=Id)return Hd.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=jd.encodeCommand(t);return n.socket.write(r),!0},iu=(e,t)=>{const n=Yd[e];return!!n&&(Hd.info(`Renaming socket id [${e}] to [${t}]`),delete Yd[e],n.socket.id=t,Yd[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Zd(t),n.socket.on("close",n.disconnectHandler),!0)},su=e=>{Kd=e};let ou=jd;_d&&(ou=Wd);var au,cu=ou;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(au||(au={}));let lu=Math.ceil(Date.now()/1e3);var du={exports:{}};const uu=["nodebuffer","arraybuffer","fragments"],pu="undefined"!=typeof Blob;pu&&uu.push("blob");var gu={BINARY_TYPES:uu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:pu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:hu}=gu,fu=Buffer[Symbol.species];function mu(e,t,n,r,i){for(let s=0;s<i;s++)n[r+s]=e[s]^t[3&s]}function yu(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(du.exports={concat:function(e,t){if(0===e.length)return hu;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 fu(n.buffer,n.byteOffset,r):n},mask:mu,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 fu(t):ArrayBuffer.isView(t)?n=new fu(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:yu},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");du.exports.mask=function(t,n,r,i,s){s<48?mu(t,n,r,i,s):e.mask(t,n,r,i,s)},du.exports.unmask=function(t,n){t.length<32?yu(t,n):e.unmask(t,n)}}catch(e){}var vu=du.exports;const bu=Symbol("kDone"),wu=Symbol("kRun");const Su=D,Iu=vu,$u=class{constructor(e){this[bu]=()=>{this.pending--,this[wu]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[wu]()}[wu](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[bu])}}},{kStatusCode:_u}=gu,Cu=Buffer[Symbol.species],ku=Buffer.from([0,0,255,255]),Eu=Symbol("permessage-deflate"),xu=Symbol("total-length"),Nu=Symbol("callback"),Au=Symbol("buffers"),Pu=Symbol("error");let Ou;var Tu=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,!Ou){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Ou=new $u(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[Nu];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){Ou.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){Ou.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]?Su.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Su.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Eu]=this,this._inflate[xu]=0,this._inflate[Au]=[],this._inflate.on("error",Du),this._inflate.on("data",Bu)}this._inflate[Nu]=n,this._inflate.write(e),t&&this._inflate.write(ku),this._inflate.flush((()=>{const e=this._inflate[Pu];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=Iu.concat(this._inflate[Au],this._inflate[xu]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[xu]=0,this._inflate[Au]=[],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]?Su.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Su.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[xu]=0,this._deflate[Au]=[],this._deflate.on("data",Lu)}this._deflate[Nu]=n,this._deflate.write(e),this._deflate.flush(Su.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Iu.concat(this._deflate[Au],this._deflate[xu]);t&&(e=new Cu(e.buffer,e.byteOffset,e.length-4)),this._deflate[Nu]=null,this._deflate[xu]=0,this._deflate[Au]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function Lu(e){this[Au].push(e),this[xu]+=e.length}function Bu(e){this[xu]+=e.length,this[Eu]._maxPayload<1||this[xu]<=this[Eu]._maxPayload?this[Au].push(e):(this[Pu]=new RangeError("Max payload size exceeded"),this[Pu].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Pu][_u]=1009,this.removeListener("data",Bu),this.reset())}function Du(e){this[Eu]._inflate=null,e[_u]=1007,this[Nu](e)}var ju={exports:{}};const{isUtf8:Uu}=j,{hasBlob:Ru}=gu;function Fu(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(ju.exports={isBlob:function(e){return Ru&&"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:Fu,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]},Uu)ju.exports.isValidUTF8=function(e){return e.length<24?Fu(e):Uu(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");ju.exports.isValidUTF8=function(t){return t.length<32?Fu(t):e(t)}}catch(e){}var Mu=ju.exports;const{Writable:Wu}=B,Gu=Tu,{BINARY_TYPES:Vu,EMPTY_BUFFER:Hu,kStatusCode:zu,kWebSocket:qu}=gu,{concat:Ku,toArrayBuffer:Ju,unmask:Yu}=vu,{isValidStatusCode:Xu,isValidUTF8:Zu}=Mu,Qu=Buffer[Symbol.species];var ep=class extends Wu{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Vu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[qu]=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 Qu(t.buffer,t.byteOffset+e,t.length-e),new Qu(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 Qu(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[Gu.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=Hu;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]&&Yu(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[Gu.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?Ku(n,t):"arraybuffer"===this._binaryType?Ju(Ku(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=Ku(n,t);if(!this._skipUTF8Validation&&!Zu(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,Hu),this.end();else{const n=e.readUInt16BE(0);if(!Xu(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Qu(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Zu(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[zu]=r,s}};const{randomFillSync:tp}=d,np=Tu,{EMPTY_BUFFER:rp,kWebSocket:ip,NOOP:sp}=gu,{isBlob:op,isValidStatusCode:ap}=Mu,{mask:cp,toBuffer:lp}=vu,dp=Symbol("kByteLength"),up=Buffer.alloc(4),pp=8192;let gp,hp=pp;var fp=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=sp,this[ip]=void 0}static frame(e,t){let n,r,i=!1,s=2,o=!1;t.mask&&(n=t.maskBuffer||up,t.generateMask?t.generateMask(n):(hp===pp&&(void 0===gp&&(gp=Buffer.alloc(pp)),tp(gp,0,pp),hp=0),n[0]=gp[hp++],n[1]=gp[hp++],n[2]=gp[hp++],n[3]=gp[hp++]),o=!(n[0]|n[1]|n[2]|n[3]),s=6),"string"==typeof e?r=t.mask&&!o||void 0===t[dp]?(e=Buffer.from(e)).length:t[dp]:(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?(cp(e,n,c,s,r),[c]):(cp(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let s;if(void 0===t)s=rp;else{if("number"!=typeof t||!ap(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={[dp]: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):op(t)?(i=t.size,s=!1):(i=(t=lp(t)).length,s=lp.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[dp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};op(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):op(t)?(i=t.size,s=!1):(i=(t=lp(t)).length,s=lp.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[dp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};op(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[np.extensionName];let i,s,o=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):op(e)?(i=e.size,s=!1):(i=(e=lp(e)).length,s=lp.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={[dp]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:s,rsv1:a};op(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[dp],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(mp,this,e,i)}this._bufferedBytes-=r[dp];const s=lp(t);n?this.dispatch(s,n,r,i):(this._state=0,this.sendFrame(e.frame(s,r),i),this.dequeue())})).catch((e=>{process.nextTick(yp,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const s=this._extensions[np.extensionName];this._bufferedBytes+=r[dp],this._state=1,s.compress(t,r.fin,((t,n)=>{if(this._socket.destroyed){mp(this,new Error("The socket was closed while data was being compressed"),i)}else this._bufferedBytes-=r[dp],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][dp],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][dp],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 mp(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 yp(e,t,n){mp(e,t,n),e.onerror(t)}const{kForOnEventAttribute:vp,kListener:bp}=gu,wp=Symbol("kCode"),Sp=Symbol("kData"),Ip=Symbol("kError"),$p=Symbol("kMessage"),_p=Symbol("kReason"),Cp=Symbol("kTarget"),kp=Symbol("kType"),Ep=Symbol("kWasClean");class xp{constructor(e){this[Cp]=null,this[kp]=e}get target(){return this[Cp]}get type(){return this[kp]}}Object.defineProperty(xp.prototype,"target",{enumerable:!0}),Object.defineProperty(xp.prototype,"type",{enumerable:!0});class Np extends xp{constructor(e,t={}){super(e),this[wp]=void 0===t.code?0:t.code,this[_p]=void 0===t.reason?"":t.reason,this[Ep]=void 0!==t.wasClean&&t.wasClean}get code(){return this[wp]}get reason(){return this[_p]}get wasClean(){return this[Ep]}}Object.defineProperty(Np.prototype,"code",{enumerable:!0}),Object.defineProperty(Np.prototype,"reason",{enumerable:!0}),Object.defineProperty(Np.prototype,"wasClean",{enumerable:!0});class Ap extends xp{constructor(e,t={}){super(e),this[Ip]=void 0===t.error?null:t.error,this[$p]=void 0===t.message?"":t.message}get error(){return this[Ip]}get message(){return this[$p]}}Object.defineProperty(Ap.prototype,"error",{enumerable:!0}),Object.defineProperty(Ap.prototype,"message",{enumerable:!0});class Pp extends xp{constructor(e,t={}){super(e),this[Sp]=void 0===t.data?null:t.data}get data(){return this[Sp]}}Object.defineProperty(Pp.prototype,"data",{enumerable:!0});const Op={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[vp]&&r[bp]===t&&!r[vp])return;let r;if("message"===e)r=function(e,n){const r=new Pp("message",{data:n?e:e.toString()});r[Cp]=this,Lp(t,this,r)};else if("close"===e)r=function(e,n){const r=new Np("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[Cp]=this,Lp(t,this,r)};else if("error"===e)r=function(e){const n=new Ap("error",{error:e,message:e.message});n[Cp]=this,Lp(t,this,n)};else{if("open"!==e)return;r=function(){const e=new xp("open");e[Cp]=this,Lp(t,this,e)}}r[vp]=!!n[vp],r[bp]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[bp]===t&&!n[vp]){this.removeListener(e,n);break}}};var Tp={CloseEvent:Np,ErrorEvent:Ap,Event:xp,EventTarget:Op,MessageEvent:Pp};function Lp(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:Bp}=Mu;function Dp(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var jp={format:function(e){return Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>[t].concat(Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let n,r,i=Object.create(null),s=!1,o=!1,a=!1,c=-1,l=-1,d=-1,u=0;for(;u<e.length;u++)if(l=e.charCodeAt(u),void 0===n)if(-1===d&&1===Bp[l])-1===c&&(c=u);else if(0===u||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u);const r=e.slice(c,d);44===l?(Dp(t,r,i),i=Object.create(null)):n=r,c=d=-1}}else-1===d&&-1!==c&&(d=u);else if(void 0===r)if(-1===d&&1===Bp[l])-1===c&&(c=u);else if(32===l||9===l)-1===d&&-1!==c&&(d=u);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u),Dp(i,e.slice(c,d),!0),44===l&&(Dp(t,n,i),i=Object.create(null),n=void 0),c=d=-1}else{if(61!==l||-1===c||-1!==d)throw new SyntaxError(`Unexpected character at index ${u}`);r=e.slice(c,u),c=d=-1}else if(o){if(1!==Bp[l])throw new SyntaxError(`Unexpected character at index ${u}`);-1===c?c=u:s||(s=!0),o=!1}else if(a)if(1===Bp[l])-1===c&&(c=u);else if(34===l&&-1!==c)a=!1,d=u;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${u}`);o=!0}else if(34===l&&61===e.charCodeAt(u-1))a=!0;else if(-1===d&&1===Bp[l])-1===c&&(c=u);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u);let o=e.slice(c,d);s&&(o=o.replace(/\\/g,""),s=!1),Dp(i,r,o),44===l&&(Dp(t,n,i),i=Object.create(null),n=void 0),r=void 0,c=d=-1}}else-1===d&&(d=u);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===d&&(d=u);const p=e.slice(c,d);return void 0===n?Dp(t,p,i):(void 0===r?Dp(i,p,!0):Dp(i,r,s?p.replace(/\\/g,""):p),Dp(t,n,i)),t}};const Up=U,Rp=R,Fp=F,Mp=A,Wp=P,{randomBytes:Gp,createHash:Vp}=d,{URL:Hp}=M,zp=Tu,qp=ep,Kp=fp,{isBlob:Jp}=Mu,{BINARY_TYPES:Yp,EMPTY_BUFFER:Xp,GUID:Zp,kForOnEventAttribute:Qp,kListener:eg,kStatusCode:tg,kWebSocket:ng,NOOP:rg}=gu,{EventTarget:{addEventListener:ig,removeEventListener:sg}}=Tp,{format:og,parse:ag}=jp,{toBuffer:cg}=vu,lg=3e4,dg=Symbol("kAborted"),ug=[8,13],pg=["CONNECTING","OPEN","CLOSING","CLOSED"],gg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let hg=class e extends Up{constructor(t,n,r){super(),this._binaryType=Yp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xp,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]),mg(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yp.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 qp({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Kp(t,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=t,i[ng]=this,s[ng]=this,t[ng]=this,i.on("conclude",Ig),i.on("drain",$g),i.on("error",_g),i.on("message",kg),i.on("ping",Eg),i.on("pong",xg),s.onerror=Ag,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",Og),t.on("data",Tg),t.on("end",Lg),t.on("error",Bg),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[zp.extensionName]&&this._extensions[zp.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())})),Pg(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";wg(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||Xp,n,r)):Sg(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||Xp,n,r)):Sg(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 Sg(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[zp.extensionName]||(i.compress=!1),this._sender.send(t||Xp,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";wg(this,this._req,e)}}};Object.defineProperty(hg,"CONNECTING",{enumerable:!0,value:pg.indexOf("CONNECTING")}),Object.defineProperty(hg.prototype,"CONNECTING",{enumerable:!0,value:pg.indexOf("CONNECTING")}),Object.defineProperty(hg,"OPEN",{enumerable:!0,value:pg.indexOf("OPEN")}),Object.defineProperty(hg.prototype,"OPEN",{enumerable:!0,value:pg.indexOf("OPEN")}),Object.defineProperty(hg,"CLOSING",{enumerable:!0,value:pg.indexOf("CLOSING")}),Object.defineProperty(hg.prototype,"CLOSING",{enumerable:!0,value:pg.indexOf("CLOSING")}),Object.defineProperty(hg,"CLOSED",{enumerable:!0,value:pg.indexOf("CLOSED")}),Object.defineProperty(hg.prototype,"CLOSED",{enumerable:!0,value:pg.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(hg.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(hg.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[Qp])return t[eg];return null},set(t){for(const t of this.listeners(e))if(t[Qp]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[Qp]:!0})}})})),hg.prototype.addEventListener=ig,hg.prototype.removeEventListener=sg;var fg=hg;function mg(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:ug[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,!ug.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${ug.join(", ")})`);let s;if(t instanceof Hp)s=t;else try{s=new Hp(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 yg(e,t)}const l=o?443:80,d=Gp(16).toString("base64"),u=o?Rp.request:Fp.request,p=new Set;let g,h;if(i.createConnection=i.createConnection||(o?bg:vg),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(g=new zp(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=og({[zp.extensionName]:g.offer()})),n.length){for(const e of n){if("string"!=typeof e||!gg.test(e)||p.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(e)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?i.socketPath:s.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),h=e._req=u(i),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=u(i);i.timeout&&h.on("timeout",(()=>{wg(e,h,"Opening handshake has timed out")})),h.on("error",(t=>{null===h||h[dg]||(h=e._req=null,yg(e,t))})),h.on("response",(s=>{const o=s.headers.location,a=s.statusCode;if(o&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void wg(e,h,"Maximum redirects exceeded");let s;h.abort();try{s=new Hp(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void yg(e,n)}mg(e,s,n,r)}else e.emit("unexpected-response",h,s)||wg(e,h,`Unexpected server response: ${s.statusCode}`)})),h.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==hg.CONNECTING)return;h=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void wg(e,n,"Invalid Upgrade header");const o=Vp("sha1").update(d+Zp).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void wg(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 wg(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!g){return void wg(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=ag(l)}catch(t){return void wg(e,n,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==zp.extensionName){return void wg(e,n,"Server indicated an extension that was not requested")}try{g.accept(t[zp.extensionName])}catch(t){return void wg(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[zp.extensionName]=g}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(h,e):h.end()}function yg(e,t){e._readyState=hg.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function vg(e){return e.path=e.socketPath,Mp.connect(e)}function bg(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Mp.isIP(e.host)?"":e.host),Wp.connect(e)}function wg(e,t,n){e._readyState=hg.CLOSING;const r=new Error(n);Error.captureStackTrace(r,wg),t.setHeader?(t[dg]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(yg,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Sg(e,t,n){if(t){const n=Jp(t)?t.size:cg(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${pg[e.readyState]})`);process.nextTick(n,t)}}function Ig(e,t){const n=this[ng];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[ng]&&(n._socket.removeListener("data",Tg),process.nextTick(Ng,n._socket),1005===e?n.close():n.close(e,t))}function $g(){const e=this[ng];e.isPaused||e._socket.resume()}function _g(e){const t=this[ng];void 0!==t._socket[ng]&&(t._socket.removeListener("data",Tg),process.nextTick(Ng,t._socket),t.close(e[tg])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Cg(){this[ng].emitClose()}function kg(e,t){this[ng].emit("message",e,t)}function Eg(e){const t=this[ng];t._autoPong&&t.pong(e,!this._isServer,rg),t.emit("ping",e)}function xg(e){this[ng].emit("pong",e)}function Ng(e){e.resume()}function Ag(e){const t=this[ng];t.readyState!==hg.CLOSED&&(t.readyState===hg.OPEN&&(t._readyState=hg.CLOSING,Pg(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Pg(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),lg)}function Og(){const e=this[ng];let t;this.removeListener("close",Og),this.removeListener("data",Tg),this.removeListener("end",Lg),e._readyState=hg.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[ng]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Cg),e._receiver.on("finish",Cg))}function Tg(e){this[ng]._receiver.write(e)||this.pause()}function Lg(){const e=this[ng];e._readyState=hg.CLOSING,e._receiver.end(),this.end()}function Bg(){const e=this[ng];this.removeListener("error",Bg),this.on("error",rg),e&&(e._readyState=hg.CLOSING,this.destroy())}const{tokenChars:Dg}=Mu;var jg={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===Dg[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 Ug=U,Rg=F,{createHash:Fg}=d,Mg=jp,Wg=Tu,Gg=jg,Vg=fg,{GUID:Hg,kWebSocket:zg}=gu,qg=/^[+/0-9A-Za-z]{22}==$/;var Kg=class extends Ug{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:Vg,...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=Rg.createServer(((e,t)=>{const n=Rg.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(Jg,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(Jg,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Jg(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",Yg);const i=e.headers["sec-websocket-key"],s=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Zg(this,e,t,405,"Invalid HTTP method")}if(void 0===s||"websocket"!==s.toLowerCase()){return void Zg(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!qg.test(i)){return void Zg(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void Zg(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Xg(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=Gg.parse(a)}catch(n){return void Zg(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&void 0!==l){const n=new Wg(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Mg.parse(l);e[Wg.extensionName]&&(n.accept(e[Wg.extensionName]),d[Wg.extensionName]=n)}catch(n){return void Zg(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 Xg(t,o||401,a,l);this.completeUpgrade(d,i,c,e,t,n,r)}));if(!this.options.verifyClient(s))return Xg(t,401)}this.completeUpgrade(d,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,s,o){if(!i.readable||!i.writable)return i.destroy();if(i[zg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Xg(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Fg("sha1").update(t+Hg).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[Wg.extensionName]){const t=e[Wg.extensionName].params,n=Mg.format({[Wg.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",Yg),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(Jg,this)}))),o(c,r)}};function Jg(e){e._state=2,e.emit("close")}function Yg(){this.destroy()}function Xg(e,t,n,r){n=n||Rg.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} ${Rg.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function Zg(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,Zg),e.emit("wsClientError",r,n,t)}else Xg(n,r,i)}var Qg=Wc(Kg);const eh=ol("websocketServer"),th={},nh=Vd();let rh,ih,sh,oh,ah;const ch=e=>{const t=th[e];t&&t.socket.close()};var lh={startServer:e=>{ah=new Qg({port:e,maxPayload:1048576e3}),ah.on("connection",(e=>{const t=ll();eh(`New client connected. Registered as "${t}"`),e.id=t,th[t]={socket:e,activeMessage:null},rh&&rh(t),e.on("message",(t=>{if(t instanceof Buffer){const n=th[e.id];nh(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),eh(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{ch(n.socket.id)};if(t.command)return eh(`Received command from client [${n.socket.id}]: ${t.command}`),void(sh&&sh(n.socket.id,t.command,r,i));t.klMessage&&oh&&oh({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",(()=>{eh(`Client disconnected: ${e.id}`),ih&&ih(e.id),delete th[e.id]})),e.on("error",(()=>{eh(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},stopServer:()=>{ah.close((()=>{console.log("WebSocket server stopped")}))},onClientConnected:e=>{rh=e},onClientDisconnected:e=>{ih=e},onClientCommand:e=>{sh=e},sendCommand:(e,t)=>{const n=th[e];if(!n)return eh(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=Id)return eh("Message is too long to be a command. Use sendMessage instead."),!1;const r=jd.encodeCommand(t);return n.socket.send(r),!0},onMessageReceived:e=>oh=e,terminateConnection:ch};const dh=ol("stopService"),uh=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Fl.getAllServiceVersions(t);dh(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Fl.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},ph=ol("removeService"),gh=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Fl.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),ph(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Fl.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},hh=ol("launchService"),fh=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=Il();hh(`Loading service ${t}@${n} from ${i}`);const{errorMsg:s,service:o,errorCode:a}=await Fl.loadAndLaunch(i,r,!1);if(s||"started"!==o?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${s||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,d=async()=>{const r=o.status;return"running"===r?(hh(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(hh(`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"}):(hh("Retrying in 1 second..."),void setTimeout(d,1e3)))};d()}catch(r){return hh(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},mh=ol("getMatchingServices"),yh=async e=>{const t=e.args[0],n=[],r=[];mh(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=Fl.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:Fl.getServiceRootDirectory(t)}):r.push({name:e,version:i})}mh(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},vh=ol("getSecretsValues");let bh;var wh=async e=>{const t=e.args[0].services;if(!bh)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");vh(`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 bh({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})},Sh=e=>{bh=e};const Ih=ol("getMappedSecrets");let $h;var _h=async e=>{const t=e.args[0].services;Ih(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await $h(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})},Ch=e=>{$h=e};const kh=ol("getServiceContents"),Eh=({reply:e,args:t})=>{const[n]=t;kh(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Fl.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}]})}kh(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let xh={globalApiKey:void 0};const Nh=()=>({...xh}),Ah=()=>{const e=Nh();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},Ph=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}}},Oh={},Th=async e=>{const t=(e=>{const t=Oh[e],n=Date.now()-(t?.lastCheckedAt.getTime()??0);return t&&n<3e5?t.features:null})(e);if(t)return{valid:!0,features:t,error:null};const{valid:n,features:r,error:i}=await(async e=>{const{data:t,error:n}=await Ph(`${Ah()}/v1/validate/validate_key`,{apiKey:e});return n?(console.warn(`Error validating Kemu API key: ${n}`),{valid:!1,features:{},error:n}):t?.features?{valid:!0,features:t.features,error:null}:{valid:!1,features:{},error:"No features returned from the server"}})(e);return n&&(Oh[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}},Lh=ol("activeClients");let Bh={},Dh={};const jh=(e,t)=>`${e}_${t}`,Uh=e=>Bh[e]||null,Rh=(e,t)=>{const n=jh(e,t);return Dh[n]||[]},Fh=()=>{for(const e in Bh){const t=Bh[e];if(t?.transport===_c.WS){const e=jd.encodeCommand(Sc.ServicesListChanged);t.send(e)}}},Mh=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===_c.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 Th(o.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&Lh(`Unable to validate API Key, usage will be limited. SessionId: ${n}`)}Bh[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=jh(e.serviceName,e.version);Dh[r]=Dh[r]||[];return Dh[r].some((e=>e.serviceId===n))||Dh[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=jh(e.serviceName,e.version),s=Dh[i]?.findIndex((e=>e.serviceId===n));if(-1!==s&&(Dh[i]?.splice(s,1),!Dh[i]?.length)){const t=Fl.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=Uh(t.info.sessionId);e?.extraInfo.ipcSocketId&&ru(e?.extraInfo.ipcSocketId,Sc.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=jh(e.targetService.serviceName,e.targetService.version),r=Dh[t]?.findIndex((e=>e.serviceId===n));-1!==r&&Dh[t]?.splice(r,1)}t.length=0}},r===_c.IPC&&(Fh(),Gh(n))},Wh=()=>{const e=Object.values(Bh);for(const t of e)if(t.transport===_c.IPC){const e=t.extraInfo.ipcSocketId,n=Fl.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){Rh(n.info.name,n.info.version).length||e&&ru(e,Sc.BroadcastEnd)}}},Gh=e=>{const t=Fl.getServiceBySessionId(e);if(t?.info.eventEmitter){if(Rh(t.info.name,t.info.version).length){const t=Uh(e);t?.extraInfo.ipcSocketId&&ru(t?.extraInfo.ipcSocketId,Sc.BroadcastStart)}}},Vh=e=>{const t=Bh[e];delete Bh[e],t?.transport===_c.IPC?Fh():(t?.removeAllSubscriptions(),Wh())},Hh=ol("ipc:handleIpcClientCommand"),zh=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(Sc.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 Hh(`Ignoring ACK response from IPC service ${e} with no service id`);Hh(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(iu(e,t),r=t);let i=!1;t&&(i=Fl.setServiceStatus(t,"running")),i?Mh({serviceSessionId:t||e,transport:_c.IPC,send:n,extraInfo:{ipcSocketId:t}}):ru(r,Sc.SendManifest)}));!r&&Hh(`Received unknown command [${t}] from service ${e}`)};let qh={};G.platform();const Kh=async e=>{const t=e.args[0];if(qh.chooseDirectory)try{const n=await qh.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"})},Jh=async e=>{const t=e.args[0];if(qh.chooseFile)try{const n=await qh.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"})},Yh=e=>{qh=e};var Xh={},Zh={},Qh={};function ef(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function tf(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function nf(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function rf(e,...t){if(!nf(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 sf(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");ef(e.outputLen),ef(e.blockLen)}function of(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 af(e,t){rf(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(Qh,"__esModule",{value:!0}),Qh.output=Qh.exists=Qh.hash=Qh.bytes=Qh.bool=Qh.number=Qh.isBytes=void 0,Qh.number=ef,Qh.bool=tf,Qh.isBytes=nf,Qh.bytes=rf,Qh.hash=sf,Qh.exists=of,Qh.output=af;const cf={number:ef,bool:tf,bytes:rf,hash:sf,exists:of,output:af};Qh.default=cf;var lf={};Object.defineProperty(lf,"__esModule",{value:!0}),lf.add5L=lf.add5H=lf.add4H=lf.add4L=lf.add3H=lf.add3L=lf.add=lf.rotlBL=lf.rotlBH=lf.rotlSL=lf.rotlSH=lf.rotr32L=lf.rotr32H=lf.rotrBL=lf.rotrBH=lf.rotrSL=lf.rotrSH=lf.shrSL=lf.shrSH=lf.toBig=lf.split=lf.fromBig=void 0;const df=BigInt(2**32-1),uf=BigInt(32);function pf(e,t=!1){return t?{h:Number(e&df),l:Number(e>>uf&df)}:{h:0|Number(e>>uf&df),l:0|Number(e&df)}}function gf(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=pf(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}lf.fromBig=pf,lf.split=gf;const hf=(e,t)=>BigInt(e>>>0)<<uf|BigInt(t>>>0);lf.toBig=hf;const ff=(e,t,n)=>e>>>n;lf.shrSH=ff;const mf=(e,t,n)=>e<<32-n|t>>>n;lf.shrSL=mf;const yf=(e,t,n)=>e>>>n|t<<32-n;lf.rotrSH=yf;const vf=(e,t,n)=>e<<32-n|t>>>n;lf.rotrSL=vf;const bf=(e,t,n)=>e<<64-n|t>>>n-32;lf.rotrBH=bf;const wf=(e,t,n)=>e>>>n-32|t<<64-n;lf.rotrBL=wf;const Sf=(e,t)=>t;lf.rotr32H=Sf;const If=e=>e;lf.rotr32L=If;const $f=(e,t,n)=>e<<n|t>>>32-n;lf.rotlSH=$f;const _f=(e,t,n)=>t<<n|e>>>32-n;lf.rotlSL=_f;const Cf=(e,t,n)=>t<<n-32|e>>>64-n;lf.rotlBH=Cf;const kf=(e,t,n)=>e<<n-32|t>>>64-n;function Ef(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}lf.rotlBL=kf,lf.add=Ef;const xf=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);lf.add3L=xf;const Nf=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;lf.add3H=Nf;const Af=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);lf.add4L=Af;const Pf=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;lf.add4H=Pf;const Of=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);lf.add5L=Of;const Tf=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0;lf.add5H=Tf;const Lf={fromBig:pf,split:gf,toBig:hf,shrSH:ff,shrSL:mf,rotrSH:yf,rotrSL:vf,rotrBH:bf,rotrBL:wf,rotr32H:Sf,rotr32L:If,rotlSH:$f,rotlSL:_f,rotlBH:Cf,rotlBL:kf,add:Ef,add3L:xf,add3H:Nf,add4L:Af,add4H:Pf,add5H:Tf,add5L:Of};lf.default=Lf;var Bf={},Df={};Object.defineProperty(Df,"__esModule",{value:!0}),Df.crypto=void 0,Df.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
|
|
2
2
|
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3
|
-
Object.defineProperty(e,"__esModule",{value:!0}),e.randomBytes=e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.checkOpts=e.Hash=e.concatBytes=e.toBytes=e.utf8ToBytes=e.asyncLoop=e.nextTick=e.hexToBytes=e.bytesToHex=e.byteSwap32=e.byteSwapIfBE=e.byteSwap=e.isLE=e.rotl=e.rotr=e.createView=e.u32=e.u8=e.isBytes=void 0;const t=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,Pf=tf,Of=xf,Tf=[],Lf=[],Bf=[],Df=BigInt(0),jf=BigInt(1),Uf=BigInt(2),Rf=BigInt(7),Ff=BigInt(256),Mf=BigInt(113);for(let e=0,t=jf,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Tf.push(2*(5*r+n)),Lf.push((e+1)*(e+2)/2%64);let i=Df;for(let e=0;e<7;e++)t=(t<<jf^(t>>Rf)*Mf)%Ff,t&Uf&&(i^=jf<<(jf<<BigInt(e))-jf);Bf.push(i)}const[Wf,Gf]=(0,Pf.split)(Bf,!0),Vf=(e,t,n)=>n>32?(0,Pf.rotlBH)(e,t,n):(0,Pf.rotlSH)(e,t,n),Hf=(e,t,n)=>n>32?(0,Pf.rotlBL)(e,t,n):(0,Pf.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=Lf[n],s=Vf(t,i,r),o=Hf(t,i,r),a=Tf[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 Of.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,Of.u32)(this.state)}keccak(){Of.isLE||(0,Of.byteSwap32)(this.state32),zf(this.state32,this.rounds),Of.isLE||(0,Of.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,Nf.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,Of.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,Of.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,Of.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),em=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),tm=({globalObj:e=(void 0!==Lc?Lc:"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)},nm=e=>()=>e++,rm=({random:e=Math.random,counter:t=nm(Math.floor(476782367*e())),length:n=24,fingerprint:r=tm({random:e})}={})=>function(){const i=(e=>em[Math.floor(e()*em.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)}`},im=rm();Vh.getConstants=()=>({defaultLength:24,bigLength:32}),Vh.init=rm,Vh.createId=im,Vh.bufToBigInt=Zf,Vh.createCounter=nm,Vh.createFingerprint=tm,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:sm,init:om,getConstants:am,isCuid:cm}=Vh;var lm=sm;const dm=Qc("getUniqueId"),um=({reply:e,sourceServiceId:t})=>{dm(`Generating unique id for service "${t}"`);return e({success:[lm()]})},pm=Qc("getActiveServices"),gm=async({transport:e,sourceServiceId:t,reply:n})=>{if(pm(`Received GetServices request from ${e} [${t}]`),e===vc.WS){let e=Tl.getActiveServices();const r=Ph(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===vc.WS){if(!r?.extraInfo.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(Tl.isInternalKemuService),s=e.filter((e=>e.devMode&&Tl.isNotInternalKemuService(e))),o=e.filter((e=>Tl.isOfficialKemuService(e)&&Tl.isNotInternalKemuService(e)&&Tl.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=Tl.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:Tl.isInternalKemuService(e),svgIcon:e.svgIcon,color:e.color,shortTitle:e.shortTitle})));n({success:[{available:e.map((e=>{const{widgetUIContents:t,...n}=e;return{...n}})),failed:s,installed:i}]})}};let hm="runtime",fm=null;const mm=()=>hm,vm=Qc("getSystemInfo"),ym=async({reply:e})=>{vm("Received GetSystemInfo request");e({success:[await(async()=>({platformArch:`${"win32"===process.platform?"win":"darwin"===process.platform?"osx":""}-${(()=>{switch(process.arch){case"x64":return"x64";case"ia32":return"x86";case"arm":return"arm";case"arm64":return"arm64";default:return""}})()}`,isDesktopHub:"desktop"===mm(),isRuntimeHub:"runtime"===mm(),hubVersion:ol,...fm?{updateAvailable:fm}:{}}))()]})},bm=Qc("removeService"),wm=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,s=r.version;if(!i)return n({error:"No service name provided"});if(!s)return n({error:"No service version provided"});const o=Tl.getAllServiceVersions(i),a=o.find((e=>e.info.version===s));if(!a)return n({error:"Service not found"});bm(`Removing ${o.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await Tl.uninstallService(a.info.name,a.info.version),c){const e=Ph(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});bm(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await $h(`${_h()}/v1/validate/uninstall_hub_service`,e);if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(bm(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:s}}]})},Sm=Qc("getDecryptedEdgeApiKey"),Im=({reply:e})=>{Sm("Getting decrypted edge API key");return e({success:[Ih().globalApiKey]})},_m=y(W(import.meta.url)),$m=Qc("hub"),Cm=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=vd?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=tu.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}nu+=1;const d=`${i}-${nu}-exec-${e.substring(0,10)}`,u={messageId:d,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};u.promise=new Promise(((e,t)=>{u.resolve=e,u.reject=t}));let p=vd?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:r,messageId:d,type:"execute"}};o(c)&&(p=tu.encode(g,a,c)),t[d]=u,n&&n(`Calling remote function "${e}" with message id "${d}"`);const h="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(u.fulfilled=!0,u.resolve([void 0]),delete t[d]):0===l?.timeout||h||(u.timer=setTimeout((()=>{n&&n(`Remote function ${d} timed out`);const r=t[d];r&&!r.fulfilled&&(r.fulfilled=!0,u.reject(`Function ${e} Timed out`)),delete t[d]}),l?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:g}),u.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,s)=>{nu+=1;const a=`${i}-${nu}-multicast-${e.substring(0,10)}`;let c=vd?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let d=o(r[0].serviceId);d&&(c=tu.encode(l,s,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(d=o(i.serviceId),d&&(c=tu.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");Cm.setLogger($m);const km={[fc.RebootToInstallUpdate]:null,[fc.GetFileContentFromCacheId]:null},Em=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=Ph(n.targetServiceId);if(!r)return $m(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,vc.IPC;const i=t.json?.messageId;return $m(`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},xm=({sourceServiceId:e,args:t})=>{const n=Tl.getServiceBySessionId(e);if(n){const r=Oh(n.info.name,n.info.version),i=Oh(n.info.name,"*");if(!r.length&&!i.length)return;const s=[...r,...i],o={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};Cm.broadcast(fc.BroadcastEvent,[o],s,0)}},Am=e=>{const{send:t,transmission:n,json:r}=e;$m(`Raw message Id received from WS: ${r?.messageId}`);Em(vc.WS,e)||Cm.processMessage(vc.WS,t,n,r)},Nm=e=>{const t=(n=e,`${hc.SocketAcknowledge}${n}`);var n;nh.sendCommand(e,t)},Pm=(e,t)=>{$m(`Received unknown command [${t}] from service ${e}`)},Om=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,s=n,o=Ih().globalApiKey||t[0]?.apiKey;await Lh({serviceSessionId:n,transport:vc.WS,send:r,terminateFn:()=>{nh.terminateConnection(n)},extraInfo:{websocketId:s,wsApiKey:o}}),i({success:[]})},Tm=e=>{$m(`WS Client ${e} disconnected`),jh(e)},Lm=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==vc.IPC){var i;$m(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Tl.getMatchingDevService(n.name,n.version,"stopped");if(t){$m(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const s=Ph(t.info.sessionId);if(!s)return void $m(`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}`),Xd(e,t.info.sessionId);const o=await ul(n,n.path);t.info={...t.info,...o},$m(`Updating manifest for dev service ${t.info.sessionId}`),Tl.setServiceManifest(t.info.sessionId,o,"running"),$m(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Yd(t.info.sessionId,(e=>`${hc.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=xh[e];t?t.isDevClient?(t.disconnected=!1,t.transport===vc.IPC&&(Th(),Dh(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{Tl.addDevService(e,n,"running");const t=Ph(e);t?t.isDevClient=!0:Lh({serviceSessionId:e,transport:vc.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}$m(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var Bm=async e=>{var t;$m("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",hm=t;const n=e?.ipc?.appSpace||"kemu.",r=e?.ipc?.id||"widgets";if(!e.serviceUrl)throw new Error("Missing service url, please set the `apiUrl` option.");(e=>{Sh={...Sh,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey}),Cm.registerFunction(fc.GetServiceContents,wh),Cm.registerFunction(fc.GetServices,gm),Cm.registerFunction(fc.GetSystemInfo,ym),Cm.registerFunction(fc.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"})})),Cm.registerFunction(fc.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===vc.WS){const[e]=n,i=Ph(r);if(!i)return t({error:`Session id "${r}" not found`});$m(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),Cm.registerFunction(fc.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===vc.WS){const[e]=n,i=Ph(r),s=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if($m(`Service ${r} subscribing to "${s.serviceName} (${s.version})"`),"hub"===s.serviceName)return i.addSubscription(s),void t({success:[]});if(!i.addSubscription(s))return $m(`Service ${r} already subscribed to "${s.serviceName} (${s.version})", ignoring request.`),t({success:[]});const o=Tl.getMatchingService(s.serviceName,s.version);if(!o)return $m(`Service ${s.serviceName} ${s.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return $m(`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=Ph(o.info.sessionId);return a?.extraInfo.ipcSocketId&&($m(`Sending Broadcast START command to service ${o.info.sessionId}`),Yd(a?.extraInfo.ipcSocketId,hc.BroadcastStart)),t({success:[]})}})),Cm.registerFunction("stopService",ih),Cm.registerFunction("removeService",oh),Cm.registerFunction("launchService",ch),Cm.registerFunction("getMatchingServices",dh),Cm.registerFunction("getSecretsValues",gh),Cm.registerFunction(fc.GetMappedSecrets,vh),Cm.registerFunction(fc.BroadcastEvent,xm),Cm.registerFunction(fc.ServiceManifest,Lm),Cm.registerFunction(fc.ChooseDirectoryDialog,Mh),Cm.registerFunction(fc.ChooseFileDialog,Wh),Cm.registerFunction(fc.GetUniqueId,um),Cm.registerFunction(fc.GetDecryptedEdgeApiKey,Im),Cm.registerFunction(fc.SocketAckResponse,Om),Cm.registerFunction(fc.UninstallService,wm),Object.entries(km).forEach((([e,t])=>{t?Cm.registerFunction(e,t):($m(`Skipping registration of "${e}" because it's not implemented`),Cm.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),Jd((e=>{const{send:t,transmission:n,json:r}=e;$m(`Raw message Id received from IPC: ${r?.messageId}`);Em(vc.IPC,e)||Cm.processMessage(vc.IPC,t,n,r)})),nh.onMessageReceived(Am),nh.onClientConnected(Nm),nh.onClientCommand(Pm),nh.onClientDisconnected(Tm),Zd(Rh),qd((e=>{const t=(e=>`${hc.IpcAcknowledge}${e}`)(e);Yd(e,t)})),Kd((e=>{$m(`IPC socket [${e}] disconnected`);const t=Ph(e);if(t){$m(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Tl.getServiceBySessionId(t.serviceSessionId);Tl.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,Th()):jh(t.serviceSessionId)}})),await zd({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await nh.startServer(e?.ws?.port||5368);const i=e?.defaultServicesPath||m.resolve(_m,"defaultServices"),s=process.env.DEV_SESSION_ID;Tl.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),e?.servicesInstallPath&&(e=>{gl=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{hl=e})(e.testServicesInstallPath);const o=fl(),a=hl||il,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=Ih().serviceUrl,t},l=async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{});e?.getServiceSecretsFn?(Tl.setGetSecretsFunction(e.getServiceSecretsFn),hh(e.getServiceSecretsFn)):(Tl.setGetSecretsFunction(c),hh(c)),yh(e?.getMappedSecretsFn?e.getMappedSecretsFn:l),Tl.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return V("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await Tl.loadServices(i,{fixedSession:s?parseInt(s):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0}),null!==e?.servicesInstallPath&&(await pl(o)||await w(o,{recursive:!0}),await Tl.loadServices(o,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME}));const d=process.env.DEV_NO_SPAWN_LIST?.split(",");await Tl.launchServices({noSpawningList:d||[]}),$m("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&Gh({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},Dm=e=>{if(e===vc.WS)return{handleWebsocketConnectionEvent:Nm,handleWebsocketClientDisconnectionEvent:Tm,handleWebsocketMessage:Am,handleWebsocketClientCommand:Pm,getRemoteInvoke:()=>Cm}},jm=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Tl.getAllServices().every((e=>"running"===e.status))){if(e.every((e=>"running"===Tl.getMatchingService(e.name,e.version)?.status)))return n()}t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let Um;const Rm=ya("run"),Fm=wc(),Mm=1e3,Wm=k(process.argv.slice(2));global.ImageData=K,$e({createCanvas:(e,t)=>Y(e,t),loadImage:async e=>{const t=await J(e),n=Y(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}});const Gm={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:fe.ImageData}},loadImageFile:async e=>{const t=await J(e),n=Y(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)},encodeImageData:async(e,t="jpeg",n)=>{const r=Y(e.width,e.height);let i;return r.getContext("2d").putImageData(e,0,0),i="png"===t?await r.encode(t):await r.encode(t,n),i}};var Vm={start:async r=>{r=r||{};const i=r?.recipePath||Wm.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!i)throw new Error("`recipePath` not provided. Please specify it in the config object, via a command line argument [--recipePath] or as an environment variable [KEMU_EDGE_RECIPE_PATH].");e({path:H(z(i),".env")});const s=r.apiKey||process.env.KEMU_API_KEY;if(!s)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");const o=i.endsWith(".json")||i.endsWith(".kemu"),a=o?q(i):i,c=o?i:H(a,"recipe.kemu"),l=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(z(c),"utf-8"));if(!l)throw new Error("Failed to parse recipe file");const{serviceUrl:d,apiKey:u}=((e,t)=>{const n=Lo(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 ns();const p={id:l.id||String(Date.now()),version:1,author:""};(e=>{xr=e})(console);const g=Dm(Se.WS),h=(e,t)=>{if(t)g?.handleWebsocketMessage({send:m,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;g?.handleWebsocketClientCommand(Mm,t)}},f=(sa={instanceServiceId:Mm,sendBuf:h,sendCmd:h,triggerOnCommand:(...e)=>oa(...e),triggerOnConnected:()=>aa(),triggerOnDisconnected:()=>ca(),triggerOnMessageReceived:(...e)=>la(...e)},sa);const m=(e,t)=>{if(t)f.triggerOnMessageReceived({send:h,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;f.triggerOnCommand(t)}},v=Ic(),y=g.getRemoteInvoke();v.disableServiceEncoding(0,!0),y.disableServiceEncoding(Mm,!0);const b=Object.values(l.blocks[ge].gates).filter((e=>e.type===ze.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),w=b.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),S=H(a,"services"),I=await n(S).then((()=>!0)).catch((()=>!1));await Bm({globalApiKey:u,serviceUrl:d,recipeRootPath:a,servicesInstallPath:I?H(a,"services"):null,noDefaultServices:!0,ws:{disabled:!0},ipc:{appSpace:"kemu-runner.",id:p.id}}),Rm("Waiting for services to run"),await jm(w),Rm("All services are running"),No(Fm);const _=await Eo(l,"runner",p.version,p.author,mo.Desktop);return Um=_,Sc(_),await yc(u),new Promise(((e,t)=>{var n;bc("acknowledged",(async()=>{await Fm.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Ao(_);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)})),Rm("Recipe started"),e({sendToInputWidget:(e,t)=>"number"==typeof t?r(e,{type:fe.Number,value:t}):"string"==typeof t?r(e,{type:fe.String,value:t}):"boolean"==typeof t?r(e,{type:fe.Boolean,value:t}):Array.isArray(t)?r(e,{type:fe.Array,value:t}):r(e,t)})})),f.triggerOnConnected(),f.triggerOnCommand((n=Mm,`${ye.SocketAcknowledge}${n}`))}))},terminate:async()=>{Um&&await xo(Um)},onVariableChange:(e,t)=>_r(e,t)};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{fe as DataType,Vm as default,Gm as utils};
|
|
3
|
+
Object.defineProperty(e,"__esModule",{value:!0}),e.randomBytes=e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.checkOpts=e.Hash=e.concatBytes=e.toBytes=e.utf8ToBytes=e.asyncLoop=e.nextTick=e.hexToBytes=e.bytesToHex=e.byteSwap32=e.byteSwapIfBE=e.byteSwap=e.isLE=e.rotl=e.rotr=e.createView=e.u32=e.u8=e.isBytes=void 0;const t=Df,n=Qh;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")}}(Bf),Object.defineProperty(Zh,"__esModule",{value:!0}),Zh.shake256=Zh.shake128=Zh.keccak_512=Zh.keccak_384=Zh.keccak_256=Zh.keccak_224=Zh.sha3_512=Zh.sha3_384=Zh.sha3_256=Zh.sha3_224=Zh.Keccak=Zh.keccakP=void 0;const jf=Qh,Uf=lf,Rf=Bf,Ff=[],Mf=[],Wf=[],Gf=BigInt(0),Vf=BigInt(1),Hf=BigInt(2),zf=BigInt(7),qf=BigInt(256),Kf=BigInt(113);for(let e=0,t=Vf,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Ff.push(2*(5*r+n)),Mf.push((e+1)*(e+2)/2%64);let i=Gf;for(let e=0;e<7;e++)t=(t<<Vf^(t>>zf)*Kf)%qf,t&Hf&&(i^=Vf<<(Vf<<BigInt(e))-Vf);Wf.push(i)}const[Jf,Yf]=(0,Uf.split)(Wf,!0),Xf=(e,t,n)=>n>32?(0,Uf.rotlBH)(e,t,n):(0,Uf.rotlSH)(e,t,n),Zf=(e,t,n)=>n>32?(0,Uf.rotlBL)(e,t,n):(0,Uf.rotlSL)(e,t,n);function Qf(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=Xf(s,o,1)^n[r],c=Zf(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=Mf[n],s=Xf(t,i,r),o=Zf(t,i,r),a=Ff[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]^=Jf[r],e[1]^=Yf[r]}n.fill(0)}Zh.keccakP=Qf;class em extends Rf.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,jf.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,Rf.u32)(this.state)}keccak(){Rf.isLE||(0,Rf.byteSwap32)(this.state32),Qf(this.state32,this.rounds),Rf.isLE||(0,Rf.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,jf.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,Rf.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,jf.exists)(this,!1),(0,jf.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,jf.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,jf.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 em(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}}Zh.Keccak=em;const tm=(e,t,n)=>(0,Rf.wrapConstructor)((()=>new em(t,e,n)));Zh.sha3_224=tm(6,144,28),Zh.sha3_256=tm(6,136,32),Zh.sha3_384=tm(6,104,48),Zh.sha3_512=tm(6,72,64),Zh.keccak_224=tm(1,144,28),Zh.keccak_256=tm(1,136,32),Zh.keccak_384=tm(1,104,48),Zh.keccak_512=tm(1,72,64);const nm=(e,t,n)=>(0,Rf.wrapXOFConstructorWithOpts)(((r={})=>new em(t,e,void 0===r.dkLen?n:r.dkLen,!0)));Zh.shake128=nm(31,168,16),Zh.shake256=nm(31,136,32);const{sha3_512:rm}=Zh,im=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function sm(e){let t=0n;for(const n of e.values()){t=(t<<8n)+BigInt(n)}return t}const om=(e="")=>sm(rm(e)).toString(36).slice(1),am=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),cm=({globalObj:e=(void 0!==Mc?Mc:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+im(32,t):im(32,t);return om(r).substring(0,32)},lm=e=>()=>e++,dm=({random:e=Math.random,counter:t=lm(Math.floor(476782367*e())),length:n=24,fingerprint:r=cm({random:e})}={})=>function(){const i=(e=>am[Math.floor(e()*am.length)])(e),s=Date.now().toString(36),o=t().toString(36),a=im(n,e);return`${i+om(`${s+a+o+r}`).substring(1,n)}`},um=dm();Xh.getConstants=()=>({defaultLength:24,bigLength:32}),Xh.init=dm,Xh.createId=um,Xh.bufToBigInt=sm,Xh.createCounter=lm,Xh.createFingerprint=cm,Xh.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:pm,init:gm,getConstants:hm,isCuid:fm}=Xh;var mm=pm;const ym=ol("getUniqueId"),vm=({reply:e,sourceServiceId:t})=>{ym(`Generating unique id for service "${t}"`);return e({success:[mm()]})},bm=ol("getActiveServices"),wm=async({transport:e,sourceServiceId:t,reply:n})=>{if(bm(`Received GetServices request from ${e} [${t}]`),e===_c.WS){let e=Fl.getActiveServices();const r=Uh(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===_c.WS){if(!r?.extraInfo.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(Fl.isInternalKemuService),s=e.filter((e=>e.devMode&&Fl.isNotInternalKemuService(e))),o=e.filter((e=>Fl.isOfficialKemuService(e)&&Fl.isNotInternalKemuService(e)&&Fl.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=await(async e=>{const{features:t}=await Th(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=Fl.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:Fl.isInternalKemuService(e),svgIcon:e.svgIcon,color:e.color,shortTitle:e.shortTitle})));n({success:[{available:e.map((e=>{const{widgetUIContents:t,...n}=e;return{...n}})),failed:s,installed:i}]})}};let Sm="runtime",Im=null;const $m=()=>Sm,_m=ol("getSystemInfo"),Cm=async({reply:e})=>{_m("Received GetSystemInfo request");e({success:[await(async()=>({platformArch:`${"win32"===process.platform?"win":"darwin"===process.platform?"osx":""}-${(()=>{switch(process.arch){case"x64":return"x64";case"ia32":return"x86";case"arm":return"arm";case"arm64":return"arm64";default:return""}})()}`,isDesktopHub:"desktop"===$m(),isRuntimeHub:"runtime"===$m(),hubVersion:gl,...Im?{updateAvailable:Im}:{}}))()]})},km=ol("removeService"),Em=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,s=r.version;if(!i)return n({error:"No service name provided"});if(!s)return n({error:"No service version provided"});const o=Fl.getAllServiceVersions(i),a=o.find((e=>e.info.version===s));if(!a)return n({error:"Service not found"});km(`Removing ${o.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await Fl.uninstallService(a.info.name,a.info.version),c){const e=Uh(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});km(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await Ph(`${Ah()}/v1/validate/uninstall_hub_service`,e);if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(km(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:s}}]})},xm=ol("getDecryptedEdgeApiKey"),Nm=({reply:e})=>{xm("Getting decrypted edge API key");return e({success:[Nh().globalApiKey]})},Am=v(W(import.meta.url)),Pm=ol("hub"),Om=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=_d?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=cu.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}lu+=1;const d=`${i}-${lu}-exec-${e.substring(0,10)}`,u={messageId:d,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};u.promise=new Promise(((e,t)=>{u.resolve=e,u.reject=t}));let p=_d?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:r,messageId:d,type:"execute"}};o(c)&&(p=cu.encode(g,a,c)),t[d]=u,n&&n(`Calling remote function "${e}" with message id "${d}"`);const h="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(u.fulfilled=!0,u.resolve([void 0]),delete t[d]):0===l?.timeout||h||(u.timer=setTimeout((()=>{n&&n(`Remote function ${d} timed out`);const r=t[d];r&&!r.fulfilled&&(r.fulfilled=!0,u.reject(`Function ${e} Timed out`)),delete t[d]}),l?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:g}),u.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,s)=>{lu+=1;const a=`${i}-${lu}-multicast-${e.substring(0,10)}`;let c=_d?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let d=o(r[0].serviceId);d&&(c=cu.encode(l,s,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(d=o(i.serviceId),d&&(c=cu.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");Om.setLogger(Pm);const Tm={[Ic.RebootToInstallUpdate]:null,[Ic.GetFileContentFromCacheId]:null},Lm=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=Uh(n.targetServiceId);if(!r)return Pm(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,_c.IPC;const i=t.json?.messageId;return Pm(`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},Bm=({sourceServiceId:e,args:t})=>{const n=Fl.getServiceBySessionId(e);if(n){const r=Rh(n.info.name,n.info.version),i=Rh(n.info.name,"*");if(!r.length&&!i.length)return;const s=[...r,...i],o={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};Om.broadcast(Ic.BroadcastEvent,[o],s,0)}},Dm=e=>{const{send:t,transmission:n,json:r}=e;Pm(`Raw message Id received from WS: ${r?.messageId}`);Lm(_c.WS,e)||Om.processMessage(_c.WS,t,n,r)},jm=e=>{const t=(n=e,`${Sc.SocketAcknowledge}${n}`);var n;lh.sendCommand(e,t)},Um=(e,t)=>{Pm(`Received unknown command [${t}] from service ${e}`)},Rm=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,s=n,o=Nh().globalApiKey||t[0]?.apiKey;await Mh({serviceSessionId:n,transport:_c.WS,send:r,terminateFn:()=>{lh.terminateConnection(n)},extraInfo:{websocketId:s,wsApiKey:o}}),i({success:[]})},Fm=e=>{Pm(`WS Client ${e} disconnected`),Vh(e)},Mm=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==_c.IPC){var i;Pm(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Fl.getMatchingDevService(n.name,n.version,"stopped");if(t){Pm(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const s=Uh(t.info.sessionId);if(!s)return void Pm(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);s.send=r,Bh[i=e]?delete Bh[i]:Lh(`Could not find source client with session id ${i}`),iu(e,t.info.sessionId);const o=await vl(n,n.path);t.info={...t.info,...o},Pm(`Updating manifest for dev service ${t.info.sessionId}`),Fl.setServiceManifest(t.info.sessionId,o,"running"),Pm(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),ru(t.info.sessionId,(e=>`${Sc.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=Bh[e];t?t.isDevClient?(t.disconnected=!1,t.transport===_c.IPC&&(Fh(),Gh(e))):Lh(`Client with session id ${e} is not a dev client`):Lh(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{Fl.addDevService(e,n,"running");const t=Uh(e);t?t.isDevClient=!0:Mh({serviceSessionId:e,transport:_c.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}Pm(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var Wm=async e=>{var t;Pm("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",Sm=t;const n=e?.ipc?.appSpace||"kemu.",r=e?.ipc?.id||"widgets";if(!e.serviceUrl)throw new Error("Missing service url, please set the `apiUrl` option.");(e=>{xh={...xh,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey}),Om.registerFunction(Ic.GetServiceContents,Eh),Om.registerFunction(Ic.GetServices,wm),Om.registerFunction(Ic.GetSystemInfo,Cm),Om.registerFunction(Ic.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"})})),Om.registerFunction(Ic.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===_c.WS){const[e]=n,i=Uh(r);if(!i)return t({error:`Session id "${r}" not found`});Pm(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),Om.registerFunction(Ic.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===_c.WS){const[e]=n,i=Uh(r),s=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(Pm(`Service ${r} subscribing to "${s.serviceName} (${s.version})"`),"hub"===s.serviceName)return i.addSubscription(s),void t({success:[]});if(!i.addSubscription(s))return Pm(`Service ${r} already subscribed to "${s.serviceName} (${s.version})", ignoring request.`),t({success:[]});const o=Fl.getMatchingService(s.serviceName,s.version);if(!o)return Pm(`Service ${s.serviceName} ${s.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return Pm(`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=Uh(o.info.sessionId);return a?.extraInfo.ipcSocketId&&(Pm(`Sending Broadcast START command to service ${o.info.sessionId}`),ru(a?.extraInfo.ipcSocketId,Sc.BroadcastStart)),t({success:[]})}})),Om.registerFunction("stopService",uh),Om.registerFunction("removeService",gh),Om.registerFunction("launchService",fh),Om.registerFunction("getMatchingServices",yh),Om.registerFunction("getSecretsValues",wh),Om.registerFunction(Ic.GetMappedSecrets,_h),Om.registerFunction(Ic.BroadcastEvent,Bm),Om.registerFunction(Ic.ServiceManifest,Mm),Om.registerFunction(Ic.ChooseDirectoryDialog,Kh),Om.registerFunction(Ic.ChooseFileDialog,Jh),Om.registerFunction(Ic.GetUniqueId,vm),Om.registerFunction(Ic.GetDecryptedEdgeApiKey,Nm),Om.registerFunction(Ic.SocketAckResponse,Rm),Om.registerFunction(Ic.UninstallService,Em),Object.entries(Tm).forEach((([e,t])=>{t?Om.registerFunction(e,t):(Pm(`Skipping registration of "${e}" because it's not implemented`),Om.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),nu((e=>{const{send:t,transmission:n,json:r}=e;Pm(`Raw message Id received from IPC: ${r?.messageId}`);Lm(_c.IPC,e)||Om.processMessage(_c.IPC,t,n,r)})),lh.onMessageReceived(Dm),lh.onClientConnected(jm),lh.onClientCommand(Um),lh.onClientDisconnected(Fm),su(zh),eu((e=>{const t=(e=>`${Sc.IpcAcknowledge}${e}`)(e);ru(e,t)})),tu((e=>{Pm(`IPC socket [${e}] disconnected`);const t=Uh(e);if(t){Pm(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Fl.getServiceBySessionId(t.serviceSessionId);Fl.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,Fh()):Vh(t.serviceSessionId)}})),await Qd({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await lh.startServer(e?.ws?.port||5368);const i=e?.defaultServicesPath||m.resolve(Am,"defaultServices"),s=process.env.DEV_SESSION_ID;Fl.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),e?.servicesInstallPath&&(e=>{wl=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Sl=e})(e.testServicesInstallPath);const o=Il(),a=Sl||ul,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=Nh().serviceUrl,t},l=async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{});e?.getServiceSecretsFn?(Fl.setGetSecretsFunction(e.getServiceSecretsFn),Sh(e.getServiceSecretsFn)):(Fl.setGetSecretsFunction(c),Sh(c)),Ch(e?.getMappedSecretsFn?e.getMappedSecretsFn:l),Fl.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return V("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await Fl.loadServices(i,{fixedSession:s?parseInt(s):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0}),null!==e?.servicesInstallPath&&(await bl(o)||await w(o,{recursive:!0}),await Fl.loadServices(o,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME}));const d=process.env.DEV_NO_SPAWN_LIST?.split(",");await Fl.launchServices({noSpawningList:d||[]}),Pm("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&Yh({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},Gm=e=>{if(e===_c.WS)return{handleWebsocketConnectionEvent:jm,handleWebsocketClientDisconnectionEvent:Fm,handleWebsocketMessage:Dm,handleWebsocketClientCommand:Um,getRemoteInvoke:()=>Om}},Vm=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Fl.getAllServices().every((e=>"running"===e.status))){if(e.every((e=>"running"===Fl.getMatchingService(e.name,e.version)?.status)))return n()}t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let Hm;const zm=Ca("run"),qm=Ec(),Km=1e3,Jm=k(process.argv.slice(2));global.ImageData=K,_e({createCanvas:(e,t)=>Y(e,t),loadImage:async e=>{const t=await J(e),n=Y(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}});const Ym={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:fe.ImageData}},loadImageFile:async e=>{const t=await J(e),n=Y(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)},encodeImageData:async(e,t="jpeg",n)=>{const r=Y(e.width,e.height);let i;return r.getContext("2d").putImageData(e,0,0),i="png"===t?await r.encode(t):await r.encode(t,n),i}};var Xm={start:async r=>{r=r||{};const i=r?.recipePath||Jm.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!i)throw new Error("`recipePath` not provided. Please specify it in the config object, via a command line argument [--recipePath] or as an environment variable [KEMU_EDGE_RECIPE_PATH].");e({path:H(z(i),".env")});const s=r.apiKey||process.env.KEMU_API_KEY;if(!s)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");const o=i.endsWith(".json")||i.endsWith(".kemu"),a=o?q(i):i,c=o?i:H(a,"recipe.kemu"),l=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(z(c),"utf-8"));if(!l)throw new Error("Failed to parse recipe file");const{serviceUrl:d,apiKey:u}=((e,t)=>{const n=Mo(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 ss();const p={id:l.id||String(Date.now()),version:1,author:""};(e=>{xr=e})(console);const g=Gm(Se.WS),h=(e,t)=>{if(t)g?.handleWebsocketMessage({send:m,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;g?.handleWebsocketClientCommand(Km,t)}},f=(pa={instanceServiceId:Km,sendBuf:h,sendCmd:h,triggerOnCommand:(...e)=>ga(...e),triggerOnConnected:()=>ha(),triggerOnDisconnected:()=>fa(),triggerOnMessageReceived:(...e)=>ma(...e)},pa);const m=(e,t)=>{if(t)f.triggerOnMessageReceived({send:h,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;f.triggerOnCommand(t)}},y=Nc(),v=g.getRemoteInvoke();y.disableServiceEncoding(0,!0),v.disableServiceEncoding(Km,!0);const b=Object.values(l.blocks[ge].gates).filter((e=>e.type===ze.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),w=b.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),S=H(a,"services"),I=await n(S).then((()=>!0)).catch((()=>!1));await Wm({globalApiKey:u,serviceUrl:d,recipeRootPath:a,servicesInstallPath:I?H(a,"services"):null,noDefaultServices:!0,ws:{disabled:!0},ipc:{appSpace:"kemu-runner.",id:p.id}}),zm("Waiting for services to run"),await Vm(w),zm("All services are running"),jo(qm);const $=await Lo(l,"runner",p.version,p.author,$o.Desktop);return Hm=$,xc($),await Cc(u),new Promise(((e,t)=>{var n;kc("acknowledged",(async()=>{await qm.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Do($);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)})),zm("Recipe started"),e({sendToInputWidget:(e,t)=>"number"==typeof t?r(e,{type:fe.Number,value:t}):"string"==typeof t?r(e,{type:fe.String,value:t}):"boolean"==typeof t?r(e,{type:fe.Boolean,value:t}):Array.isArray(t)?r(e,{type:fe.Array,value:t}):r(e,t)})})),f.triggerOnConnected(),f.triggerOnCommand((n=Km,`${ve.SocketAcknowledge}${n}`))}))},terminate:async()=>{Hm&&await Bo(Hm)},onVariableChange:(e,t)=>Ir(e,t)};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{fe as DataType,Xm as default,Ym as utils};
|