@kemu-io/edge-runtime 0.1.7 → 0.1.10

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kemu-io/edge-runtime",
3
3
  "type": "module",
4
- "version": "0.1.7",
4
+ "version": "0.1.10",
5
5
  "description": "Kemu Edge runtime for running Kemu recipes",
6
6
  "author": "Kemu Pty Ltd",
7
7
  "main": "runner.js",
@@ -23,6 +23,7 @@
23
23
  "dependencies": {
24
24
  "@napi-rs/canvas": "^0.1.53",
25
25
  "debug": "^4.3.5",
26
+ "dotenv": "^16.4.5",
26
27
  "emittery": "^1.0.3",
27
28
  "minimist": "^1.2.8",
28
29
  "compare-versions": "^6.1.1",
package/runner.d.ts CHANGED
@@ -85,9 +85,11 @@ export declare const utils: {
85
85
  loadImageFile: (filePath: string | URL | Buffer | ArrayBufferLike | Uint8Array | Readable) => Promise<ImageData$1>;
86
86
  };
87
87
  declare const _default: {
88
- start: (config?: {
88
+ start: (config: {
89
89
  /** path to the recipe file or containing directory */
90
90
  recipePath?: string;
91
+ /** API key to use when connecting to the hub */
92
+ apiKey: string;
91
93
  }) => Promise<{
92
94
  /** use it to send data to input widgets */
93
95
  sendToInputWidget: (inputName: string, data: PartialData, thingId?: string | undefined) => Promise<void>;
package/runner.js CHANGED
@@ -1 +1,3 @@
1
- import{readFile as e,access as t}from"node:fs/promises";import{nanoid as n}from"nanoid";import r from"jsonp";import a from"crypto-js";import i from"util";import o from"emittery";import"axios";import s from"jszip";import{satisfies as c,compare as u}from"compare-versions";import d from"debug";import l,{join as p,resolve as g,dirname as m}from"path";import v from"node-ipc";import{readFile as f,access as y,constants as h,rm as I,mkdir as S}from"fs/promises";import $ from"minimist";import w,{promises as b}from"fs";import{spawn as N}from"child_process";import{createHash as A}from"crypto";import{homedir as x}from"os";import{WebSocketServer as C}from"ws";import{fileURLToPath as P}from"url";import E from"node:os";import{exec as j}from"node:child_process";import{createId as D}from"@paralleldrive/cuid2";import{dirname as k,join as O,resolve as T}from"node:path";import{ImageData as L,loadImage as M,createCanvas as B}from"@napi-rs/canvas";var R;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(R=R||(R={}));const W={};let U=0,F="";const _=e=>W[e]?W[e]:null,G=(e,t)=>{const n=_(e);if(!n)return n;return n.blocks[t]||null},z=(e,t,n)=>{const r=G(e,t);if(!r)return r;return r.gates[n]},V=(e,t)=>{let r=n(4);for(;W[r];)r=n(4);const a=(i=e,JSON.parse(JSON.stringify(i)));var i;return a.logs="",a.addLog=e=>{a.logs+=`${(()=>{const e=Date.now();if(e!==U){const t=new Date;U=e,F=t.toJSON()}return F})()}:: ${e}\n`},a.dbInfo={...t},W[r]=a,r},H="interrupt_port",J="main.js",q="state.json",K="{#}",X="$var_",Y="default";var Z,Q,ee,te,ne,re,ae,ie;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Z||(Z={})),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"}(Q||(Q={})),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"}(ee||(ee={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(te||(te={})),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:"}(ne||(ne={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId"}(re||(re={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(ae||(ae={})),function(e){e.IPC="ipc",e.WS="ws"}(ie||(ie={}));const oe="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,se="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,ce="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,ue="-",de=`inner${ue}`,le=`outer${ue}`,pe=`${le}input${ue}`,ge=`${le}output${ue}`,me=`${de}input${ue}`,ve=`${de}output${ue}`,fe=e=>(new TextEncoder).encode(e),ye=e=>e===H,he=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Ie=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,Se=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,$e=e=>"number"==typeof e?Q.Number:"string"==typeof e?Q.String:"boolean"==typeof e?Q.Boolean:Array.isArray(e)?Q.Array:he(e)?Q.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?Q.AudioBuffer:e&&void 0!==e.byteLength?Q.ArrayBuffer:Ie(e)?Q.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?Q.Point:Q.JsonObj,we=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=$e(n[e]);t[e]=r}return t},be=(e,t,n)=>"inner"===e?"input"===t?`${me}${n}`:`${ve}${n}`:"input"===t?`${pe}${n}`:`${ge}${n}`,Ne=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]}},Ae=e=>new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace});var xe,Ce;!function(e){e.Action="action",e.CustomInput="customInput"}(xe=xe||(xe={})),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"}(Ce=Ce||(Ce={}));const Pe={};let Ee;const je=async e=>{const t=Pe[e],n={name:H,type:Q.Boolean};if(t){const r={name:t.portName},a=t.data||{type:Q.Boolean,value:!0};Ee?(await Ee(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...a,timestamp:Date.now()},[n]),"timeout"===t.type&&De(e)):console.warn("Interrupt service has not been initialized")}},De=e=>{const t=Pe[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete Pe[e],!0)};var ke={interruptHandler:je,createInterrupt:(e,t,r,a,i,o,s,c)=>{if(c&&Pe[c])throw new Error("The given interrupt id already exists");const u=c||n().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(Pe[u]={data:s,portName:i,recipePoolId:t,targetWidgetId:a,thingId:r,type:e},"interval"===e)Pe[u].timerRef=setInterval((async()=>await je(u)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);Pe[u].timerRef=setTimeout((async()=>await je(u)),o.timeout)}return u},destroyInterrupt:De,destroyAllInterrupts:()=>{Object.keys(Pe).forEach(De)},setInvokeChildGateCb:e=>{Ee=e}};const Oe=(e,t,n,r,a)=>{const i=z(e,n,r);if(!i)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=(t,a,i,o)=>ke.createInterrupt(t,e,n,r,a,i,o),s=()=>Object.freeze({...i.state,...i.type===Ce.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...i.type===Ce.input&&!e.customInputs&&{customInputs:[]}};i.state=t};if(a){return{getState:s,setState:c,registerInterrupt:o,getStorageData:async t=>{const r=((e,t,n)=>{const r=_(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const a=G(e,t);if(!a)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(a.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:s,setState:c,recipePoolId:e,widgetId:r}},Te=[10001,"Invalid `sourcePort` parameter"],Le=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],Me=[10110,"No storage medium has been loaded, call `loadMedium()` first"],Be=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?i.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),Re=()=>({inputName:"",dataType:Q.Anything}),We="output",Ue={processEvent:async(e,t)=>{const n=t.getState(),r={...Re(),...n};if(e.type===r.dataType||r.dataType===Q.Anything)return t.nextWidget(We,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...Re(),...e};return[{name:We,type:t.dataType}]},getInputNames:()=>[]},Fe=Object.freeze({in:"in",reset:"reset",increment:"increment"}),_e="output";var Ge={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(Be(Te));const a={currentValue:0,increment:1,...r.getState()};let i=a.increment,o=a.currentValue;const s=await r.getParentAtPort(Fe.increment);if(t.name===Fe.increment)return void(n.data.type===Q.Number&&r.setState({...a,increment:Number(n.data.value)}));if(s){const e=s.getValue();null!==e&&(i=e)}if(t.name===Fe.reset)return r.setState({...a,currentValue:0});o+=i,r.setState({currentValue:o,increment:i});const c={type:Q.Number,value:o};return r.nextGate(_e,c)},getInputNames:()=>[{name:Fe.in,type:Q.Anything},{name:Fe.reset,type:Q.Anything},{name:Fe.increment,type:Q.Number}],getOutputNames:()=>[{name:_e,type:Q.Number}]};const ze=Object.freeze({in:"in",reset:"reset"}),Ve="output";var He={onParentEvent:async(e,t,n,r)=>{const a={updatedAt:0,elapsed:0,...r.getState()},i=Date.now(),o=i-(a.updatedAt||i);return t.name===ze.reset?r.setState({...a,updatedAt:i,elapsed:0}):(r.setState({updatedAt:i,elapsed:o}),r.nextGate(Ve,{type:Q.Number,value:o}))},getInputNames:()=>[{name:ze.in,type:Q.Anything},{name:ze.reset,type:Q.Anything}],getOutputNames:()=>[{name:Ve,type:Q.Number}]};const Je=Object.freeze({data:"data",evaluation:"evaluation"}),qe="then",Ke="else";var Xe={onParentEvent:async(e,t,n,r)=>{const a={value:5,condition:"Equal",useDataPort:!1,...r.getState()},i=n.data.value,o=!isNaN(Number(i)),s="string"==typeof i;if(!a.useDataPort&&(n.data.type===Q.Number||n.data.type===Q.String||n.data.type===Q.Anything&&o||n.data.type===Q.Anything&&s)){let e=!1;return("Equal"===a.condition&&n.data.value==a.value||"Not Equal"===a.condition&&n.data.value!==a.value||"Greater"===a.condition&&n.data.value>Number(a.value)||"Less"===a.condition&&n.data.value<Number(a.value)||"Starts With"===a.condition&&String(n.data.value).startsWith(String(a.value))||"Ends With"===a.condition&&String(n.data.value).endsWith(String(a.value))||"Includes"===a.condition&&String(n.data.value).includes(String(a.value))||"Matches"===a.condition&&String(n.data.value).match(String(a.value)))&&(e=!0),e?r.nextGate(qe,n.data):r.nextGate(Ke,n.data)}if((t.name===Je.evaluation&&n.data.type===Q.Number||n.data.type===Q.String||n.data.type===Q.Anything&&(o||s))&&(a.$lastValue=n.data.value,r.setState({...a})),t.name===Je.data){let e=!1;return("Equal"===a.condition&&a.$lastValue==a.value||"Not Equal"===a.condition&&a.$lastValue!==a.value||"Greater"===a.condition&&Number(a.$lastValue)>Number(a.value)||"Less"===a.condition&&Number(a.$lastValue)<Number(a.value)||"Starts With"===a.condition&&String(a.$lastValue).startsWith(String(a.value))||"Ends With"===a.condition&&String(a.$lastValue).endsWith(String(a.value))||"Includes"===a.condition&&String(a.$lastValue).includes(String(a.value))||"Matches"===a.condition&&String(a.$lastValue).match(String(a.value)))&&(e=!0),r.setState({...a,$lastValue:void 0,$lastDataType:n.data.type}),e?r.nextGate(qe,n.data):r.nextGate(Ke,n.data)}},getInputNames:e=>e.useDataPort?[{name:Je.data,type:Q.Anything},{name:Je.evaluation,type:[Q.Number,Q.String]}]:[{name:"in",type:[Q.Number,Q.String]}],getOutputNames:e=>e.$lastDataType?[{name:qe,type:e.$lastDataType},{name:Ke,type:e.$lastDataType}]:[{name:qe,type:[Q.Number,Q.String]},{name:Ke,type:[Q.Number,Q.String]}]};const Ye=Object.freeze({in:"in",reset:"reset"}),Ze="out";var Qe={onParentEvent:async(e,t,n,r)=>{const a={totalCalls:0,callsLimit:1,...r.getState()};return t.name===Ye.reset?r.setState({...a,totalCalls:0}):(a.totalCalls=a.totalCalls+1,a.totalCalls>a.callsLimit?(a.totalCalls=0,r.setState(a),r.nextGate(Ze,n.data)):void r.setState(a))},getInputNames:()=>[{name:Ye.in,type:Q.Anything},{name:Ye.reset,type:Q.Anything}],getOutputNames:()=>[{name:Ze,type:Q.Anything}]};const et=Object.freeze({in:"in"}),tt="then",nt="else";var rt={onParentEvent:async(e,t,n,r)=>{const a={min:1,max:10,...r.getState()};if(n.data.type===Q.Number)return n.data.value>=a.min&&n.data.value<=a.max?r.nextGate(tt,n.data):r.nextGate(nt,n.data)},getInputNames:()=>[{name:et.in,type:Q.Number}],getOutputNames:()=>[{name:tt,type:Q.Number},{name:nt,type:Q.Number}]};const at=Object.freeze({in:"in"}),it="out";var ot={onParentEvent:async(e,t,n,r)=>{const a={clamp:!0,...r.getState()},i=Number(n.data.value);if(void 0!==a.fromMax&&void 0!==a.fromMin&&void 0!==a.toMax&&void 0!==a.toMin&&""!==a.fromMax&&""!==a.fromMin&&""!==a.toMax&&""!==a.toMin&&(n.data.type===Q.Number||n.data.type===Q.Anything&&!isNaN(Number(i)))){let e=((e,t,n,r,a)=>(e-t)*(a-r)/(n-t)+r)(i,Number(a.fromMin),Number(a.fromMax),Number(a.toMin),Number(a.toMax));if(isNaN(e))return;return a.clamp&&(e<Number(a.toMin)&&(e=Number(a.toMin)),e>Number(a.toMax)&&(e=Number(a.toMax))),r.nextGate(it,{type:Q.Number,value:Number(e)})}},getInputNames:()=>[{name:at.in,type:Q.Number}],getOutputNames:()=>[{name:it,type:Q.Number}]};const st=Object.freeze({in:"in"}),ct="out";var ut={onParentEvent:async(e,t,n,r)=>{const a={convertTo:"Integer",floatPlaces:2,...r.getState()};let i=n.data.value;if(n.data.type===Q.Number||n.data.type===Q.Anything||n.data.type===Q.String){if((!isNaN(Number(i))||"string"==typeof i)&&!Array.isArray(i))return"Integer"===a.convertTo?i=parseInt(i):"Decimal"===a.convertTo?i=parseFloat(Number(i).toFixed(a.floatPlaces)):"String"===a.convertTo?i=String(i):"Abs"===a.convertTo?i=Math.abs(Number(i)):"Round"===a.convertTo&&(i=Math.round(Number(i))),r.nextGate(ct,{type:"String"===a.convertTo?Q.String:Q.Number,value:i})}},getInputNames:()=>[{name:st.in,type:Q.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?Q.String:Q.Number;return[{name:ct,type:t}]}};const dt=Object.freeze({in:"in"}),lt="out";var pt={onParentEvent:async(e,t,n,r)=>{const a={currentValue:50,min:0,max:100,...r.getState()};let i=!1;return a.currentValue<a.min&&(a.currentValue=a.min,i=!0),a.currentValue>a.max&&(a.currentValue=a.max,i=!0),i&&r.setState(a),r.nextGate(lt,{type:Q.Number,value:a.currentValue})},getInputNames:()=>[{name:dt.in,type:Q.Anything}],getOutputNames:()=>[{name:lt,type:Q.Number}]};const gt=Object.freeze({in:"in",reset:"reset"}),mt="out";var vt={onParentEvent:async(e,t,n,r)=>{const a={lastCalledAt:0,delayMs:500},i={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===gt.reset)return r.setState({...i,lastCalledAt:0});const o=Date.now(),s=o-i.lastCalledAt;return i.lastCalledAt===a.lastCalledAt||s>=i.delayMs&&i.delayMs>0?(i.lastCalledAt=o,r.setState(i),r.nextGate(mt,n.data)):void 0},getInputNames:()=>[{name:gt.in,type:Q.Anything},{name:gt.reset,type:Q.Anything}],getOutputNames:()=>[{name:mt,type:Q.Anything}]};const ft="in";var yt={onParentEvent:async()=>{},getInputNames:()=>[{name:ft,type:[Q.ImageData,Q.Number]}],getOutputNames:()=>[]};const ht=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),It=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var St={onParentEvent:async(e,t,n,r)=>{const a={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},i=n?.data?.value,o=Array.isArray(i);if(n.data.type===Q.JsonObj||n.data.type===Q.Rect||n.data.type===Q.Anything||o){let e=!1;for(const t in i){const n=$e(i[t]),r=!!a.detectedProperties[t],o=a.detectedProperties[t]?.type!==n;if(!r||o){const r=n===Q.JsonObj||n===Q.Rect||n===Q.Array;a.detectedProperties[t]={type:n,...r?{shape:we(i[t])}:void 0},e=!0}}if(o&&void 0===a.detectedProperties.length&&(a.detectedProperties.length={type:Q.Number}),e&&r.setState(a),i){const e=[];for(const t of a.properties||[]){const n=It(i,t.label),o=t.label.includes(".");if(void 0!==n){const i=o?$e(n):void 0!==a.detectedProperties[t.label]?.type?a.detectedProperties[t.label].type:Q.Anything;e.push(r.nextGate(t.name,{type:i,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:Q.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:Q.Anything,r=t.detectedProperties[e.label]?.shape||void 0,a="string"==typeof e;return{name:a?e:e.name,label:a?e:e.label,type:n,jsonShape:r}}))},getDefaultState:ht};const $t="output",wt="noItem";var bt={onParentEvent:async(e,t,n,r)=>{const a={index:0,...r.getState()};let i=a.index;const o=n.data.value,s="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===Q.Anything&&(c||s)||n.data.type===Q.String&&s||n.data.type===Q.Array&&c){i<0&&(i=o.length+i);const e=s?Q.String:$e(o[i]);return e!==a.$$lastDetectedType&&r.setState({...a,$$lastDetectedType:e}),void 0!==o[i]?r.nextGate($t,{value:o[i],type:e}):r.nextGate(wt,{value:!0,type:Q.Boolean})}},getInputNames:()=>[{name:"in",type:[Q.Array,Q.String]}],getOutputNames:e=>[{name:$t,type:e.$$lastDetectedType??Q.Anything},{name:wt,type:Q.Boolean}]};let Nt;const At=e=>{Nt=e},xt=(e,t)=>(()=>{if(!Nt)throw new Error("CanvasManager not set");return Nt})().createCanvas(e,t),Ct=e=>oe?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Pt=Object.freeze({image:"image",rect:"rect"}),Et="image";var jt={onParentEvent:async(e,t,n,r)=>{const a={offset:{height:0,left:0,top:0,width:0},...r.getState()},i=await r.getParentAtPort(Pt.rect),o=[Q.Anything,Q.Rect,Q.JsonObj];if(t.name!==Pt.rect){if(i){const e=i.getValue();null!==e&&(a.rect={...e},r.setState(a))}if(!oe)return n.data.type===Q.ImageData?r.nextGate(Et,n.data):void 0;if(a.$$canvasFrom&&a.$$canvasFrom.getContext||(a.$$canvasFrom=xt(320,240)),a.$$canvasTo&&a.$$canvasTo.getContext||(a.$$canvasTo=xt(320,240)),(n.data.type===Q.ImageData||n.data.type===Q.Anything&&he(n.data.value))&&!a.$$processing&&a.$$canvasFrom&&a.rect){const e=((e,t,n,r,a)=>{if(r&&r.getContext){const i=r.getContext("2d"),o=n.getContext("2d");if(i&&o){n.width=e.width,n.height=e.height,o.putImageData(e,0,0);const s={...a};a&&(s.height=Number(a.height),s.width=Number(a.width),s.left=Number(a.left),s.top=Number(a.top));const c={top:0,width:0,left:0,height:0,...s};return a&&(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,i.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),i.getImageData(0,0,r.width||1,r.height||1)}}return e})(n.data.value,a.rect,a.$$canvasFrom,a.$$canvasTo,a.offset);return r.nextGate(Et,{type:Q.ImageData,value:e})}}else Ie(n.data.value)&&o.includes(n.data.type)&&r.setState({...a,rect:n.data.value})},getInputNames:()=>[{name:Pt.image,type:Q.ImageData},{name:Pt.rect,type:[Q.Rect,Q.JsonObj]}],getOutputNames:()=>[{name:Et,type:Q.ImageData}]};const Dt=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),a=e.data,i=e.width,o=e.height,s=i,c=o,u=((e,t,n)=>{if(oe)return new ImageData(t,n);return console.warn("Node environment detected. Aborting new ImageData creation"),e})(e,s,c),d=u.data;for(let e=0;e<c;e++)for(let c=0;c<s;c++){const u=e,l=c,p=4*(e*s+c);let g=0,m=0,v=0,f=0;for(let e=0;e<n;e++)for(let s=0;s<n;s++){const c=u+e-r,d=l+s-r;if(c>=0&&c<o&&d>=0&&d<i){const r=4*(c*i+d),o=t[e*n+s];g+=a[r]*o,m+=a[r+1]*o,v+=a[r+2]*o,f+=a[r+3]*o}}d[p]=g,d[p+1]=m,d[p+2]=v,d[p+3]=f+1*(255-f)}return u},kt=[-1,0,1,-2,0,2,1,0,1],Ot=Object.freeze({image:"image"}),Tt="image";var Lt={onParentEvent:async(e,t,n,r)=>{const a=r.getState(),i={matrix:[...kt],...a};if(n.data.type===Q.ImageData||n.data.type===Q.Anything&&he(n.data.value)){const e=Dt(n.data.value,i.matrix);return r.nextGate(Tt,{type:Q.ImageData,value:e})}},getInputNames:()=>[{name:Ot.image,type:Q.ImageData}],getOutputNames:()=>[{name:Tt,type:Q.ImageData}]};const Mt=Object.freeze({output:"output",aborted:"aborted"}),Bt=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),Rt=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:Q.Anything})));return n.push({name:"reset",type:Q.Anything}),n};var Wt={onParentEvent:async(e,t,n,r)=>{const a={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...a,triggeredAt:0});const i=Date.now(),o=i-a.triggeredAt;if(a.triggeredAt&&!(o>=a.delayMs&&a.delayMs>0)&&a.delayMs)return r.nextGate(Mt.aborted,n.data);{a.triggeredAt=i;const e=Rt(a,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id)).findIndex((e=>e.name===t.name));-1!==e&&(a.lastInputIndex=e),a.matchingOutputs?-1!==e&&await r.nextGate(`output${e+1}`,n.data):await r.nextGate(Mt.output,n.data),r.setState(a)}},getInputNames:Rt,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:Q.Anything})));return e.push({name:Mt.aborted,type:Q.Anything}),e}return[{name:Mt.output,type:Q.Anything},{name:Mt.aborted,type:Q.Anything}]},getDefaultState:Bt};const Ut=(e,t,n,r,a,i)=>{if(a){const o=e.measureText(a),s=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-i,1.1*o.width,s),e.font=`${i}px Arial`,e.fillStyle="black",e.fillText(a,t,n)}},Ft=(e,t,n,r,a,i,o)=>{e.fillStyle=a,e.fillRect(t,n,r,r),Ut(e,t,n,a,i,o)},_t=(e,t,n,r,a,i)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const o=n/2;Ut(e,t.left-o,t.top-o,r,a,i)},Gt=Object.freeze({image:"image",pixels:"pixels"}),zt="image";var Vt={onParentEvent:async(e,t,n,r)=>{const a={fontSize:12,color:"#00ff00",size:2,...r.getState()},i=n.data.type===Q.ImageData||n.data.type===Q.Anything&&he(n.data.value);if(t.name===Gt.pixels){const e=((e,t)=>t===Q.Anything&&(he(e)||Se(e)||Ie(e)||Array.isArray(e))||t===Q.Array||t===Q.Rect||t===Q.Point)(n.data.value,n.data.type);if(!e)return;a.$$pixels=n.data.value}if(t.name===Gt.image&&i){const e=n.data.value;a.$$memCanvas&&a.$$memCanvas.getContext||(a.$$memCanvas=xt(e.width||1,e.height||1)),a.$$lastFrame=e}if(a.$$lastFrame&&a.$$pixels&&a.$$memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:a,color:i,labelProp:o,fontSize:s}=e;if(r){const e=Ct(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]:"";Ie(n)?_t(e,n,a,i,r,s):Se(n)&&Ft(e,n.x,n.y,a,i,r,s)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:a.$$lastFrame,pixels:a.$$pixels||[],memCanvas:a.$$memCanvas,size:a.size,color:a.color,labelProp:a.labelProp,fontSize:a.fontSize});return r.setState({...a,$$lastFrame:void 0,$$pixels:void 0}),r.nextWidget(zt,{type:Q.ImageData,value:e})}r.setState(a)},getInputNames:()=>[{name:Gt.image,type:Q.ImageData},{name:Gt.pixels,type:[Q.Rect,Q.Point,Q.Array]}],getOutputNames:()=>[{name:zt,type:Q.ImageData}]};const Ht=Object.freeze({in:"in"}),Jt="output",qt=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var Kt={onParentEvent:async(e,t,n,r)=>{const a={min:1,max:100,...r.getState()},i=!Number.isInteger(a.min),o=!Number.isInteger(a.max),s=i||o;let c=(u=a.min,d=a.max,Math.random()*(d-u)+u);var u,d;if(s){let e=0;if(i&&(e=qt(a.min)),o){const t=qt(a.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(Jt,{type:Q.Number,value:c})},getInputNames:()=>[{name:Ht.in,type:Q.Anything}],getOutputNames:()=>[{name:Jt,type:Q.Number}]};const Xt=Object.freeze({output:"output",totalItems:"totalItems"}),Yt=Object.freeze({trigger:"trigger",clear:"clear"}),Zt=()=>({totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),Qt=async(e,t)=>t.nextGate(Xt.totalItems,{type:Q.Number,value:e});var en={onParentEvent:async(e,t,n,r)=>{const a={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===Yt.clear)return a.$$list=[],a.properties?.autoFilled&&delete a.properties,r.setState(a),Qt(a.$$list.length,r);const i=t.name===Yt.trigger;if(!i)if(Array.isArray(n.data.value))n.data.type!==Q.Array&&n.data.type!==Q.Anything||(a.$$outputShape={...a.$$outputShape,...e?.jsonShape},a.$$list=a.$$list.concat(n.data.value),r.setState({...a}),await Qt(a.$$list.length,r));else{const t=`$$primitive_${Object.keys(a.$$outputShape).length}`;n.data.type===Q.JsonObj?a.$$outputShape={...a.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:a.$$outputShape={...a.$$outputShape,[t]:n.data.type},a.$$list.push(n.data.value),r.setState({...a}),await Qt(a.$$list.length,r)}if(i){Object.keys(a.$$outputShape).length&&(a.properties={autoFilled:!0,jsonShape:{...a.$$outputShape}});const e=a.$$list.length,t=[...a.$$list];return a.$$list=[],r.setState({...a}),await Qt(e,r),r.nextGate(Xt.output,{type:Q.Array,value:t})}},getInputNames:e=>{const t={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`array${t+1}`,type:Q.Array})));return n.push({name:Yt.clear,type:Q.Anything},{name:Yt.trigger,type:Q.Anything}),n},getOutputNames:e=>[{name:Xt.output,type:Q.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:Xt.totalItems,label:"Total Items",type:Q.Number}],getDefaultState:Zt};const tn=Object.freeze({start:"start",stop:"stop"}),nn="output",rn="clock_interrupt";var an={onParentEvent:async(e,t,n,r)=>{const a={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(ye(e?.name||"")&&t.name===rn)return r.nextGate(nn,{type:Q.Boolean,value:!0});if(t.name===tn.stop&&a.enabled&&a.$$interruptId){r.cancelInterrupt(a.$$interruptId)?(a.enabled=!1,a.$$interruptId=void 0,r.setState(a)):console.warn(`Failed to cancel interrupt [${a.$$interruptId}]`)}else t.name!==tn.start||a.enabled||a.$$interruptId||(a.$$interruptId=r.registerInterrupt("interval",rn,{interval:a.interval}),a.enabled=!0,r.setState(a))},getInputNames:()=>[{name:tn.start,type:Q.Anything},{name:tn.stop,type:Q.Anything}],getOutputNames:()=>[{name:nn,type:Q.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",rn,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const on=Object.freeze({in:"in"}),sn="output",cn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var un={onParentEvent:async(e,t,n,r)=>{const a={userProperties:[],factor:2,decimalPoints:2,...r.getState()},i=n.data.type;let o=n.data.value,s=!1;return e?.jsonShape&&(a.detectedInputJson={...a.detectedInputJson,...e?.jsonShape},s=!0),a.detectedInputType||(a.detectedInputType=i,s=!0),n.data.type===Q.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>cn(e,t,n)));return r})(n.data.value,a.factor,a.decimalPoints):"object"==typeof n.data.value?.[0]&&(o=((e,t,n,r)=>{const a=(e||[]).map((e=>{const a={...e};return Object.keys(a).forEach((e=>{r?.length&&!r?.includes(e)||(a[e]=cn(a[e],t,n))})),a}));return a})(n.data.value,a.factor,a.decimalPoints,a.userProperties))),n.data.type===Q.Number&&(o=cn(n.data.value,a.factor,a.decimalPoints)),s&&r.setState(a),r.nextGate(sn,{type:i,value:o})},getInputNames:()=>[{name:on.in,type:[Q.Array,Q.Number]}],getOutputNames:e=>[{name:sn,type:e.detectedInputType||Q.Number,jsonShape:e.detectedInputJson}]};const dn=Object.freeze({output:"output"}),ln=Object.freeze({trigger:"trigger"}),pn=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:Q.Number,value:10},{name:"y",label:"y",type:Q.Number,value:20}]}),gn=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},mn=e=>{const t={};for(let n=0;n<e.properties.length;n++){let r=e.properties[n].value;const a=e.properties[n].type;a===Q.Number?r=Number(r):a===Q.String&&(r=String(r)),t[e.properties[n].label]=r}return t};var vn={onParentEvent:async(e,t,n,r)=>{const a=r.getState(),i=structuredClone(a),o={...pn(),...i};if(t.name===ln.trigger){const e=mn(o);return r.nextGate(dn.output,{type:Q.JsonObj,value:e})}const s=o.properties.findIndex((e=>e.name===t.name));if(-1!==s){let e=n.data.type===o.properties[s].type;if(!e&&n.data.type===Q.Anything){e=$e(n.data.type)===o.properties[s].type}if(e?(o.properties[s].value=n.data.value,o.properties[s].$$invalidInputType=!1):o.properties[s].$$invalidInputType=!0,r.setState(o),!o.useTriggerPort){const e=mn(o);return r.nextGate(dn.output,{type:Q.JsonObj,value:e})}}},getInputNames:e=>{const t={...pn(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:ln.trigger,label:ln.trigger,type:Q.Anything}),n},getOutputNames:e=>[{name:dn.output,label:dn.output,type:Q.JsonObj,jsonShape:gn(e)}],getDefaultState:pn};const fn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(pe)){const n=t(e,pe);return be("inner","input",n)}if(e.startsWith(ve)){const n=t(e,ve);return be("outer","output",n)}return null},yn=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[Q.Anything],index:0}],outputs:[{name:"output",type:[Q.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),hn=e=>{const t={...yn(),...e},n=t.inputs.map(((e,t)=>({name:be("outer","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t}))),r=t.outputs.map(((e,t)=>({name:be("inner","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:n.length+t})));return[...n,...r]};var In={onParentEvent:async(e,t,n,r)=>{const a=r.getState(),i={...yn(),...a},o=hn(i,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const a=o[e];if(t.name===a.name&&(a.type.includes(Q.Anything)||a.type.includes(n.data.type))){const e=await fn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:hn,getOutputNames:e=>{const t={...yn(),...e},n=t.outputs.map(((e,t)=>({name:be("outer","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t})));return[...t.inputs.map(((e,t)=>({name:be("inner","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:t+n.length}))),...n]},getDefaultState:yn};const Sn=(e,t,n,r,a)=>{const i=4*(t*n.width+e),o=n.data[i],s=n.data[i+1],c=n.data[i+2];return Math.abs(o-r.r)<=a&&Math.abs(s-r.g)<=a&&Math.abs(c-r.b)<=a};var $n,wn,bn,Nn,An,xn,Cn,Pn,En,jn,Dn={getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,a=n[t+1]||0,i=n[t+2]||0;return{avr:(r+a+i)/3,r:r,g:a,b:i}},getBoundingBox:(e,t,n)=>{const r=e.width,a=e.height,i=new Set,o=Number(n.threshold||0),s=isNaN(o)?10:o,c=(n,o)=>{const c=[[n,o]];let u=n,d=n,l=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>=a||i.has(`${o},${g}`)||!Sn(o,g,e,t,s||0)||(i.add(`${o},${g}`),u=Math.min(u,o),d=Math.max(d,o),l=Math.min(l,g),p=Math.max(p,g),c.push([o+1,g],[o-1,g],[o,g+1],[o,g-1]))}return{minX:u,maxX:d,minY:l,maxY:p}},u=[];for(let o=0;o<a;o+=4)for(let a=0;a<r;a+=4)if(!i.has(`${a},${o}`)&&Sn(a,o,e,t,s)){const{minX:e,maxX:t,minY:r,maxY:i}=c(a,o),s=t-e,d=i-r;if(s>=(n.minWidth||1)&&d>=(n.minHeight||1)&&u.push({left:e,top:r,width:s,height:d}),n.maxBoxes&&u.length>=n.maxBoxes)return u}return u},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,a="object"==typeof n,i=a?n.r:n,o=a?n.g:n,s=a?n.b:n;r[t]=i,r[t+1]=o,r[t+2]=s,r[t+3]=255}};!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}($n||($n={})),function(e){e.Bundle="bundle",e.Group="group"}(wn||(wn={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(bn||(bn={})),function(e){e.Cloud="cloud",e.Web="web"}(Nn||(Nn={})),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"}(An||(An={})),function(e){e.Gateway="gateway",e.Timer="timer"}(xn||(xn={})),function(e){e.InstallInProgress="installation-in-progress"}(Cn||(Cn={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Pn||(Pn={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(En||(En={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(jn||(jn={}));let kn=null;var On=()=>{if(!kn)throw new Error("Required function is not set");return kn};class Tn extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const Ln=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===$n.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar console = this.console;\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\n\t\t\tvar Kemu = {\n\t\t\t\tservices: {\n\t\t\t\t\thttp: { ...this.httpWebService },\n\t\t\t\t\tdynamoDb: { ...this.dynamoService },\n\t\t\t\t\tgoogleSheets: {\n\t\t\t\t\t\t...this.googleSheetsService,\n\t\t\t\t\t}\n\t\t\t\t},\n\n\t\t\t\timage: this.imageHelpers,\n\t\t\t\tvariable: this.variablesManager,\n\n\t\t\t\thelpers: {\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\tjsonp: this.jsonp,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tvar sendToPort;\n\n\t\t\t// --- User Methods Start ---\n\t\t\t${e||""};\n\t\t\t// --- User Methods End ---\n\t\t\t\n\t\t\t// Processes the user code asynchronously.\n\t\t\tconst asyncProcessEvent = async (targetPort, sourcePort, event) => {\n\t\t\t\tconst userProcessEvent = typeof processEvent === 'undefined' ? undefined : processEvent;\n\t\t\t\tif(userProcessEvent) {\n\t\t\t\t\ttry{\n\t\t\t\t\t\treturn await userProcessEvent(targetPort, sourcePort, event, sendToPort);\n\t\t\t\t\t}catch(e){\n\t\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked the very first time the recipe is initialized */\n\t\t\tconst asyncRecipeInit = async (context, logger) => {\n\t\t\t\ttry {\n\t\t\t\t\t${t===$n.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`,Mn=(e,t,n,i)=>{const o=Ln(e,n),s={...t,document:{},__errorTracer:e=>{throw new Tn(e.message,e.stack)},__jest:void 0===globalThis.__jest?void 0:globalThis.__jest,___notSupportedMethod:()=>i?.error("This method is not supported."),console:console,setInterval:()=>i?.error("'setInterval' is not supported. Please use a \"Timer\" widget instead."),setTimeout:t?.setTimeout,imageHelpers:Dn,...n===$n.Cloud?{require:On(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:r,CryptoJS:a,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(oe)return"browser";if(ce)return"node";if(se)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()(s)}}catch(e){return{error:{name:"CompileError",message:e.message,stack:e.stack}}}},Bn="main",Rn=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},pages:{[Bn]:{code:"\nconst getWidgetInputs = () => [\n\t{ name: 'Input 1', type: DataType.Number }\n];\n\nconst getWidgetOutputs = () => [\n\t{ name: 'Output 1', type: DataType.Number }\n]\n\nlet counter = 0;\n\nconst processEvent = async (targetPort, sourceWidget, event) => {\n\tif(targetPort.name === 'Input 1'){\n\t\treturn sendToPort('Output 1', {\n\t\t\ttype: DataType.Number,\n\t\t\tvalue: counter++,\n\t\t});\n\t}\n}\n",language:"javascript",name:"My First Script"}},consoleVisible:!1,$$consoleLines:[]}),Wn=(e,t)=>{const n={message:"Unknown Error"};if(e?.stack){const r=e?.stack?.split(":")[0].trim();n.type=r;const a=(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);a&&(n.line=a.line-(e=>{const t="___user_code_section___";return Ln(t,e).split(t)[0].split("\n").length+2})(t),n.column=a.column)}return e.message&&(n.message=e.message),n},Un=(e,t)=>{const n={...Rn(),...t.getState()},r={...n,...e?{$$error:e}:void 0,...n.autoPauseOnError&&e?{pauseExecution:!0}:void 0};e&&(r.$$consoleLines=[...r.$$consoleLines,{type:"error",text:e.message,timestamp:Date.now(),fileName:Bn}]),t.setState(r)};var Fn,_n;!function(e){e.ServiceCreationLog="service-creation-log"}(Fn=Fn||(Fn={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(_n=_n||(_n={}));const Gn=new o,zn=(e,t,n)=>{const r=G(e,t);if(!r)throw new Error(`Thing ${t} not found in recipe ${e}`);const a=r.gates[n];if(!a)throw new Error(`Widget ${n} not found in thing ${t}`);return a},Vn=(e,t,n)=>`${t}:${n}:${e}`,Hn=e=>`${e}:new-var`,Jn=async(e,t,n,r,a,i,o)=>{const s={...o},c={thingId:n,recipeId:t,variableName:e,changes:i,ownerId:r,callerWidgetId:a,varDefinition:Object.freeze(s)};if(i.includes("added")){const e=Hn(n);return Gn.emit(e,c)}{const t=Vn(e,n,r);return Gn.emit(t,c)}},qn=(e,t,n,r)=>{const a=zn(e,t,r);a.variablesListener={...a.variablesListener,[n]:0},Xn(e,t)},Kn=(e,t,n,r)=>{const a=zn(e,t,r),i={...a.variablesListener};void 0!==a.variablesListener?.[n]&&(delete i[n],a.variablesListener=i)},Xn=async(e,t)=>{const n=G(e,t);if(!n)throw new Error(`Thing "${t}" not found in recipe "${e}"`);const r={...n.variables},a=Object.keys(r);for(const i of a){const a=r[i],o=Object.keys(a);for(const a of o){!n.gates[a]&&(delete r[i][a],await Jn(i,e,t,a,void 0,["removed"],null))}0===Object.keys(r[i]).length&&delete r[i]}n.variables=r},Yn=(e,t,n)=>{for(const r in t){const a=t[r];if(a.createdByWidgetId===e.id)return a;if(e.type===Ce.variable&&a.ownerType===Ce.variable)return a;if(e.type===Ce.script){const t=a.createdByWidgetId===e.groupId,r=n[a.createdByWidgetId];if(!r)continue;const i=r.groupId===e.groupId;if(t||r.type===Ce.variable&&i)return a}}return null};var Zn=async(e,t,n,r,a,i)=>{const o=G(e,t);if(!o)throw new Error(`Thing ${t} not found in recipe ${e}`);const s={...o.variables};s[r]=s[r]||{};const c=s[r],u=o.gates[n];if(!u)throw new Error(`Widget ${n} not found in thing ${t}`);const d=Object.values(c);let l=!1,p=!1;const g=async a=>Jn(r,e,t,a.createdByWidgetId,n,["value"],a);if(u.type===Ce.variable){l=!0;for(const e of d)e.ownerType===Ce.variable&&e.type===a.type&&(e.value=a.value,p=!0,await g(e))}if(u.type===Ce.script){l=!0;for(const e of d){const t=e.createdByWidgetId===u.groupId,n=o.gates[e.createdByWidgetId],r=n?.type===Ce.variable,i=n?.groupId===u.groupId;(t||r&&i)&&e.type===a.type&&(e.value=a.value,p=!0,await g(e))}}if(!l){l=!0;for(const e of d){e.createdByWidgetId===n&&e.type===a.type&&(e.value=a.value,p=!0,await g(e))}}if(!i?.skipNotifications&&p){const s=Object.values(o.gates);for(const o of s){if(o.id===n&&i?.skipCallerNotification)continue;const s=o.variablesListener?.[r];void 0!==s&&await Ga(o.id,t,e,`${X}${r}`,a)}}},Qn=(e,t,n,r)=>{const a=G(e,t);if(!a)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 i={...a.variables}[n];if(!i)return;if(r.ownerWidgetId){const e=i[r.ownerWidgetId];return e?.value}const o=a.gates[r.readerWidgetId];if(!o)throw new Error(`Widget ${r.readerWidgetId} not found in thing ${t}`);const s=Yn(o,i,a.gates);return s?s.value:null},er=qn,tr=Kn;const nr="setTimeout",rr="variableChanged",ar=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e;if(!z(t,n,r))throw new Error(`Widget "${r}" not found in recipe "${t}"`);return{get:(e,a)=>{const i=Qn(t,n,e,{readerWidgetId:r});if(null===i){if(void 0===a)throw new Error(`Variable "${e}" is not defined`);return a}return i},set:async(e,a)=>{await Zn(t,n,r,e,{type:$e(a),value:a})},onValueChange:(a,i)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");er(t,n,a,r);const o={...Rn(),...e.getState()};o.$$eventListeners[a]={handler:i,abort:async()=>{tr(t,n,a,r)},name:rr},e.setState(o)}}},ir="__command-compile__";let or;const sr=()=>{console.log("Method not implemented")},cr=(e,t,r)=>{const a=(e,...n)=>{const r={...Rn(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},i={};return Object.keys(Q).forEach((e=>{i[e]=Q[e]})),{dataTypesEnum:i,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?ar({recipePoolId:r.recipePoolId,scriptWidgetId:r.widgetId,thingId:r.thingId,getState:t.getState,setState:t.setState}):{get:sr,set:async()=>sr(),onValueChange:sr},setTimeout:(r,a,i)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=n(),o={...Rn(),...t.getState()};o.$$eventListeners[e]={handler:r,rejectHandler:i,name:nr},t.setState(o),t.registerInterrupt("timeout",e,{timeout:a},void 0,e)}},addEventListener:(e,r)=>{if(t.setState){const i=n(),o={...Rn(),...t.getState()};o.$$eventListeners[i]={handler:r,name:e},t.setState(o),window.addEventListener(e,a.bind(i))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,n)=>{if(t.setState){const r={...Rn(),...t.getState()},a=Object.keys(r.$$eventListeners).find((t=>r.$$eventListeners[t].name===e&&r.$$eventListeners[t].handler===n));t.setState(r),a&&removeEventListener(r.$$eventListeners[a].name,r.$$eventListeners[a].handler)}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)}}},ur=(e,t,n,r)=>{const a={...Rn(),...n.getState()},i=a.pages[Bn].$$compiledCode;if(i)return{compiledModule:i};{const i=cr(e,n,t);return Mn(a.pages[Bn].code,i,n.recipeType,r)}},dr=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),lr=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===nr){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},pr=async(e,t,n)=>{let r={...Rn(),...e.getState()};if(void 0!==n){r.pages[Bn]?.$$compiledCode?.onTerminate&&await(r.pages[Bn].$$compiledCode?.onTerminate());let t=await lr(r.$$eventListeners,e);t=await(async e=>{const t={...e};for(const n in e)if(e[n].name===rr){const r=e[n]?.abort;if("function"==typeof r)try{await r()}catch(e){console.log("Error in abort interrupt handler: ",e)}delete t[n]}return t})(t),r.$$eventListeners=t,r.$$error=void 0,r.pages[Bn].$$compiledCode=void 0,r.pages[Bn].code=n,e.setState({...r})}const a=!r.pages[Bn].$$compiledCode,{compiledModule:i,error:o}=ur({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=Wn(o,e.recipeType);return Un(t,e),null}if(i){const n=(e=>{const t=(t,n)=>{if(or)try{return or[t](n)}catch(e){return void console.log("Error in custom logger: ",e)}const r={...Rn(),...e.getState()},a=[...r.$$consoleLines||[]];a.push({fileName:Bn,text:n,type:t,timestamp:Date.now()}),a.length>100&&a.splice(0,30),e.setState({...r,$$consoleLines:a})},n={log:e=>{t("log",e)},error:e=>{t("error",e)},warn:e=>{t("warn",e)},info:e=>{t("info",e)}};return n})(e);let o;if(r={...e.getState()},r.pages[Bn].$$compiledCode=i,e.nextGate&&i.setSendToPortFun(e.nextGate),t)try{await i.recipeInit({setState:e.setState,getState:e.getState},n)}catch(t){o=Wn(t,e.recipeType)}if(e.nextGate&&a)try{await i.main(e.nextGate,n)}catch(t){o=Wn(t,e.recipeType)}r.$$lastInputs=i.getWidgetInputs?i.getWidgetInputs():[],r.$$lastOutputs=i.getWidgetOutputs?i.getWidgetOutputs():[],e.setState(r),Un(o,e)}};var gr={onParentEvent:async(e,t,n,r)=>{const a=r.getState(),i={...Rn(),...a};if(!i.pages[Bn])return console.warn("Missing default page");if(i.pauseExecution){if(Object.keys(i.$$eventListeners).length){const e=await lr(i.$$eventListeners,r);r.setState({...i,$$eventListeners:e})}return}if(ye(e?.name||""))return i.$$eventListeners[t.name]?(await i.$$eventListeners[t.name].handler(),i.$$eventListeners[t.name].name===nr&&delete i.$$eventListeners[t.name],void r.setState({...i})):void console.log(`Unknown interrupt id [${t.name}] `);if(t.name.startsWith(X)){const e=t.name.replace(X,""),r=n.data.value,a=i.$$eventListeners[e];return void(a?.handler&&await a.handler(r))}const o=t.name===ir;await pr(r,!1,o?n.data.value:void 0);const s=i.pages[Bn].$$compiledCode;if(e&&e.name!==ir&&s){let a;try{await s.asyncProcessEvent(t,e,n)}catch(e){"UserCodeError"===e.name&&(a=Wn(e,r.recipeType))}Un(a,r)}},getInputNames:(e,t)=>{const n={...Rn(),...e},{compiledModule:r}=ur({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return dr(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...Rn(),...e},{compiledModule:r}=ur({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return dr(e)}return e.$$lastOutputs||[]},getDefaultState:Rn,initialize:async e=>{const t=e.getState(),n={...Rn(),...t};n.pages[Bn].code&&await pr({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[Bn].code)}};const mr=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const a=await vr(e);return((e,t,n,r)=>{const a=r.getContext("2d");if(!a)throw new Error("Failed to get canvas context");const i=e.width,o=e.height;return r.width=t,r.height=n,a.drawImage(e,0,0,i,o,0,0,t,n),a.getImageData(0,0,t,n)})(a,n||a.naturalWidth,r||a.naturalHeight,t)},vr=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"}),yr=Object.freeze({base64:"base64"}),hr=()=>({});var Ir={onParentEvent:async(e,t,n,r)=>{const a={...r.getState()};if(t.name===yr.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==Q.String&&n.data.type!==Q.Anything)return;const e=n.data.value;oe&&(a.$$memCanvas&&a.$$memCanvas.getContext||(a.$$memCanvas=xt(320,240)));try{const t=await mr(e,a.$$memCanvas,a.resize?.width,a.resize?.height);return r.setState(a),r.nextGate(fr.image,{type:Q.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:yr.base64,type:Q.String}],getOutputNames:()=>[{name:fr.image,type:Q.ImageData}],getDefaultState:hr};const Sr=Object.freeze({object:"object",error:"error"}),$r=Object.freeze({string:"string"}),wr=()=>({outputIsArray:!1});var br={onParentEvent:async(e,t,n,r)=>{const a={outputIsArray:!1,...r.getState()};if((n.data.type===Q.String||n.data.type===Q.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!a.outputIsArray?r.setState({...a,outputIsArray:!0}):!t&&a.outputIsArray&&r.setState({...a,outputIsArray:!1}),r.nextGate("object",{type:t?Q.Array:Q.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:Q.Boolean,value:!0})}},getInputNames:()=>[{name:$r.string,type:Q.String}],getOutputNames:e=>[{name:Sr.object,type:[Q.JsonObj,Q.Array],label:e.outputIsArray?"array":Sr.object},{name:Sr.error,type:Q.Boolean}],getDefaultState:wr};const Nr=Object.freeze({string:"string",length:"length"}),Ar=Object.freeze({trigger:"trigger",setText:"setText"}),xr=()=>({text:"",dispatchOnSet:!1});var Cr={onParentEvent:async(e,t,n,r)=>{const a={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===Ar.setText){if(!((n.data.type===Q.String||n.data.type===Q.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(a.text=n.data.value,r.setState(a)),!a.dispatchOnSet)return}const i=r.nextGate(Nr.length,{type:Q.Number,value:a.text.length}),o=r.nextGate(Nr.string,{type:Q.String,value:a.text});await Promise.all([i,o])},getInputNames:e=>{const t=[{name:Ar.setText,type:Q.String}];return e.dispatchOnSet||t.push({name:Ar.trigger,type:Q.Anything}),t},getOutputNames:()=>[{name:Nr.string,type:Q.String},{name:Nr.length,type:Q.Number}],getDefaultState:xr};const Pr=Object.freeze({image:"image"}),Er=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),jr=()=>({showInputPorts:!1});var Dr={onParentEvent:async(e,t,n,r)=>{const a={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Er.x&&(a.cropX=n.data.value),t.name===Er.y&&(a.cropY=n.data.value),t.name===Er.width&&(a.cropWidth=n.data.value),t.name===Er.height&&(a.cropHeight=n.data.value),void r.setState(a);if(t.name===Er.image){if(n.data.type!==Q.ImageData&&n.data.type!==Q.Anything)return;if(!he(n.data.value))return;const e=n.data.value;if(a.$$memCanvas&&a.$$memCanvas.getContext||(a.$$memCanvas=xt(320,240),a.$$memCanvasContext=Ct(a.$$memCanvas),r.setState(a)),!a.$$memCanvas||!a.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return a.$$memCanvas.width=e.width,a.$$memCanvas.height=e.height,(a.cropX||a.cropY||a.cropWidth||a.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const a=Math.max(r.x||0,0),i=Math.max(r.y||0,0),o=e.width,s=e.height,c=Math.min(Math.ceil(r.width||o),o),u=Math.min(Math.ceil(r.height||s),s);return t.width=e.width,t.height=e.height,n.putImageData(e,0,0),n.drawImage(t,a,i,c,u,0,0,c,u),n.getImageData(0,0,c,u)})(e,a.$$memCanvas,a.$$memCanvasContext,{x:a.cropX,y:a.cropY,width:a.cropWidth,height:a.cropHeight})),r.nextGate(Pr.image,{type:Q.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Er.image,type:[Q.ImageData]}];return e.showInputPorts&&(t.push({name:Er.x,type:Q.Number}),t.push({name:Er.y,type:Q.Number}),t.push({name:Er.width,type:Q.Number}),t.push({name:Er.height,type:Q.Number})),t},getOutputNames:()=>[{name:Pr.image,type:Q.ImageData}],getDefaultState:jr};const kr=Object.freeze({image:"image"}),Or=Object.freeze({image:"image",width:"width",height:"height"}),Tr=()=>({showInputPorts:!1});var Lr={onParentEvent:async(e,t,n,r)=>{const a={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Or.width&&(a.width=n.data.value),t.name===Or.height&&(a.height=n.data.value),void r.setState(a);if(t.name===Or.image){if(n.data.type!==Q.ImageData&&n.data.type!==Q.Anything)return;if(!he(n.data.value))return;const e=n.data.value;if(a.$$memCanvas&&a.$$memCanvas.getContext||(a.$$memCanvas=xt(320,240),r.setState(a)),!a.$$memCanvas)return;let t=e;return(a.width||a.height)&&(t=((e,t,n,r)=>{if(!n&&!r)return e;n&&!r?r=n*(e.height/e.width):!n&&r&&(n=r*(e.width/e.height));const a=Math.max(1,n||e.width),i=Math.max(1,r||e.height);t.width=Math.max(e.width,a),t.height=Math.max(e.height,i);const o=Ct(t);if(!o)throw new Error("Failed to get canvas context");return o.putImageData(e,0,0),o.drawImage(t,0,0,e.width,e.height,0,0,a,i),o.getImageData(0,0,a,i)})(e,a.$$memCanvas,a.width,a.height)),r.nextGate(kr.image,{type:Q.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Or.image,type:Q.ImageData}];return e.showInputPorts&&(t.push({name:Or.width,type:Q.Number}),t.push({name:Or.height,type:Q.Number})),t},getOutputNames:()=>[{name:kr.image,type:Q.ImageData}],getDefaultState:Tr};const Mr=Object.freeze({value:"value"}),Br=Object.freeze({trigger:"trigger",setValue:"setValue"}),Rr=()=>({value:0,dispatchOnSet:!1});var Wr={onParentEvent:async(e,t,n,r)=>{const a={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===Br.setValue){const e=n.data.type===Q.Number||n.data.type===Q.Anything||n.data.type===Q.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(a.value=Number(n.data.value),r.setState(a),!a.dispatchOnSet)return}return r.nextGate(Mr.value,{type:Q.Number,value:a.value})},getInputNames:e=>{const t=[{name:Br.setValue,type:Q.Number}];return e.dispatchOnSet||t.push({name:Br.trigger,type:Q.Anything}),t},getOutputNames:()=>[{name:Mr.value,type:Q.Number}],getDefaultState:Rr};const Ur=Object.freeze({image:"image"}),Fr=Object.freeze({image:"image"}),_r=()=>({anchors:[],vertices:[],matrix:[]}),Gr={onParentEvent:async(e,t,n,r)=>{const a={anchors:[],vertices:[],matrix:[],...r.getState()},i=window,o=n.data.type===Q.ImageData;if(i.Speedy&&o){const e=i.Speedy,t=n.data.value;let o,d,l,p=a.$$private?.canvas,g=a.$$private?.context,m={...a};const v=4===a.anchors.length;if(a.$$private?.pipeline)o=a.$$private?.pipeline,d=a.$$private?.source;else{o=e.Pipeline(),d=e.Image.Source();const n=e.Image.Sink();l=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,u=t.height,p=xt(c,u),g=p.getContext("2d")),d.output().connectTo(l.input()),l.output().connectTo(n.input()),o.init(d,n,l);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===a.anchors.length){const t=e.Matrix(2,4,[(s=a.anchors)[0].x,s[0].y,s[1].x,s[1].y,s[2].x,s[2].y,s[3].x,s[3].y]),n=e.Matrix(2,4,a.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),i=e.Matrix.Zeros(3,3);await e.Matrix.perspective(i,t,n);const o=i.read();r=e.Matrix(3,3,o)}l.transform=r,m={...m,$$private:{...m.$$private,canvas:p,context:g,perspective:l,pipeline:o,source:d}}}let f=t;if(v){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,a=e.$$private?.pipeline;if(n.Speedy&&r&&a){const e=n.Speedy,i=await createImageBitmap(t),o=await e.load(i);return r.media=o,(await a.run()).image.source}return null})(m,f);e&&(p&&g&&(f=((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)),m.$$private&&r.setState({...m,$$private:{...m.$$private,lastInputImage:t}}))}else m.$$private&&r.setState({...m,$$private:{...m.$$private,lastInputImage:t}});return r.nextGate(Ur.image,{type:Q.ImageData,value:f})}var s,c,u;console.log("Environment not supported")},getInputNames:()=>[{name:Fr.image,type:Q.ImageData}],getOutputNames:()=>[{name:Ur.image,type:Q.ImageData}],getDefaultState:_r,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},zr=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[Q.Anything],name:"input"}],outputs:[{dataType:[Q.Anything],name:"output"}]});let Vr;const Hr=()=>{if(!Vr)throw new Error(Be(Me));return Vr};const Jr=async e=>{const t=new s,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},qr={};var Kr=e=>qr[e]||null;const Xr=async(e,t,n)=>{try{const r=Hr(),a=n?r.loadBlobAsString:r.loadBlob;return await a(e,t)}catch(e){return null}},Yr=async e=>{const t=J;try{const n=await Xr(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},Zr=async e=>{const t=q;try{const n=await Xr(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}},Qr=(e,t)=>`${e.replace(K,"")}_${t}`,ea=(e,t)=>`widget/${e.replace(K,"")}/v/${t}`,ta=async(e,t)=>{const n=Hr(),[r]=await Promise.all([Jr(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},na=(e,t)=>{const n=Qr(e,t),r=Kr(n);return r?{...r}:null},ra=(e,t,n)=>{const r=`${`widget/${e.replace(K,"")}/tmp`}/${t}`;if(n){return Hr().getCacheLocation(r)}return r};var aa=na,ia=async(e,t,n)=>{const r=ra(t,n);await ta(e,r);const a=Yr(r),i=Zr(r),o=Hr(),s=o.getCacheLocation(r),[c,u]=await Promise.all([a,i]);if(!c)return null;let d=u;if(!u){const e=zr(),t=JSON.stringify(e);await o.saveBlob(r,q,fe(t)),d=e}return{cachePath:s,processor:c,storedState:Object.freeze(d)}},oa=(e,t,n)=>{if(n.isTempStorage)return ra(e,t,n.fullStorageRoot);const r=Hr(),a=ea(e,t);return n.fullStorageRoot?r.getCacheLocation(a):a};const sa=()=>zr();var ca={onParentEvent:async(e,t,n,r)=>{const a=r.getState();return a.$$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={...sa(),...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={...sa(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:sa,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetThingId;const a=n.$$cacheInfo?.version.toString()||n.collectionInfo?.version.toString()||1;if(n.$$cacheInfo={...n.$$cacheInfo,version:Number(a),widgetThingId:r},!r||!a)throw new Error("Widget bundle state is missing cache id or version");console.log("Loading state from cache");const i=aa(r,a);let o=!i;if(!n.$$processor)if(n.storageUnitId&&!i){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetThingId;const i=await ia(t,r,a);o=!0,i&&(n={...n,$$processor:i.processor,$$cacheInfo:{...n.$$cacheInfo,widgetThingId:r,version:Number(a)}},e.setState(n))}}else if(i){o=!1;const r=n.collectionInfo?{...n.collectionInfo}:void 0;n={...n,...!t.keepCurrentState&&i.storedState?{...i.storedState,...r?{collectionInfo:r}:{}}:{},$$processor:i.processor},e.setState(n)}const s=oa(r,a,{fullStorageRoot:!0,isTempStorage:o});console.log("Invoking bundle initialize with cache: ",s);try{await(n.$$processor?.initialize({cacheLocation:s,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 ua=Object.freeze({event:"event"}),da="1",la="2",pa="3";var ga={onParentEvent:async(e,t,n,r)=>{const a={...r.getState()};r.setState({...a,$$lastEventType:n.data.type}),await r.nextGate(da,n.data),await r.nextGate(la,n.data),await r.nextGate(pa,n.data)},getInputNames:()=>[{name:ua.event,type:Q.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??Q.Anything};return[{name:da,...t},{name:la,...t},{name:pa,...t}]}};const ma=Object.freeze({set:"set",trigger:"trigger"}),va="value";var fa={onParentEvent:async(e,t,n,r)=>{const a=r.getState(),i={name:"myVar",type:Q.String,reactive:!0,defaultValue:"",...a};if(t.name.startsWith(X)){if(!i.reactive)return;if(n.data.type!==i.type)return;return r.nextWidget(va,n.data)}if(t.name!==ma.set){if(t.name===ma.trigger){const e=Qn(r.recipePoolId,r.thingRecipeId,i.name,{ownerWidgetId:r.id}),t=e||i.defaultValue;await r.nextWidget(va,{type:i.type,value:t})}}else await Zn(r.recipePoolId,r.thingRecipeId,r.id,i.name,n.data,{skipCallerNotification:!i.reactive})},getInputNames:e=>{const t={...e};return[{name:ma.set,type:t.type||Q.Anything},{name:ma.trigger,type:Q.Anything}]},getOutputNames:e=>{const t={...e};return[{name:va,type:t.type||Q.Anything}]}};let ya;var ha=e=>{ya=e},Ia=()=>{if(!ya)throw new Error("Hub Connector not set");return ya};const Sa=async(e,t=!1)=>{const n=Ia();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 $a={onParentEvent:async(e,t,n,r)=>{const a={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const i=Ia();let o=a.$$$serviceId;if(!o){const e=i.getCachedServices().find((e=>e.name===a.service?.name&&e.version===a.service?.version));if(!e)return;o=e.sessionId,a.$$$serviceId=o,r.setState(a)}const s=a.service?.variants?.find((e=>e.id===a.variantId)),c=s?a.dynamicInputs[s.id]||s?.inputs||[]:a.service?.inputs||[];if(!c?.length)return;if(!s&&a.service?.ignoreParentEvents)return;const u=a.service?.processingTimeoutSec;return i.onParentEvent({recipeId:r.recipePoolId,data:n.data,targetServiceSessionId:o,currentState:a.customState,targetVariantId:a.variantId,target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:u?1e3*u:0,async:a.service?.asyncParentEvents}})},getInputNames:async e=>{const t=e.variantId;if(t&&e.dynamicInputs?.[t])return[...e.dynamicInputs[t]||[]];if(!t)return e.service?.inputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.inputs||[]}return[]},getOutputNames:async e=>{const t=e.variantId;if(t&&e.dynamicOutputs?.[t])return[...e.dynamicOutputs[t]||[]];if(!t)return e.service?.outputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.outputs||[]}return[]},initialize:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=Ia(),r=await Sa(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=Ia(),r=await Sa(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const wa=Object.freeze({Image:"image"}),ba=Object.freeze({Image:"image"}),Na=()=>({filters:[{name:"grayscale",value:.5,id:"d-1"}]});const Aa={input:Ue,counter:Ge,elapsed:He,ifGate:Xe,skipEvent:Qe,between:rt,map:ot,parser:ut,slider:pt,suspend:vt,display:yt,json:St,arrayItem:bt,extractImage:jt,imageConvolution:Lt,firstEvent:Wt,pixelDraw:Vt,randomBetween:Kt,arrayCombine:en,clock:an,multiplication:un,object:vn,widgetGroup:In,script:gr,base64ToImageData:Ir,jsonParse:br,text:Cr,imageCrop:Dr,imageResize:Lr,value:Wr,imageWarp:Gr,widgetBundle:ca,sequence:ga,variable:fa,hubService:$a,imageFilter:{onParentEvent:async(e,t,n,r)=>{const a={filters:[{name:"grayscale",value:.5,id:"d-1"}],...r.getState()};if(t.name===wa.Image&&n.data.type===Q.ImageData){if(!he(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;a.$$memCanvas||(a.$$memCanvas=xt(e.width,e.height)),a.$$context||(a.$$context=a.$$memCanvas.getContext("2d")),a.$$memCanvas.width!==e.width&&(a.$$memCanvas.width=e.width),a.$$memCanvas.height!==e.height&&(a.$$memCanvas.height=e.height),r.setState(a),a.$$context.putImageData(e,0,0),a.filters.length?a.$$context.filter=a.filters.map((e=>`${e.name}(${e.value}${"blur"===e.name?"px":""})`)).join(" "):a.$$context.filter="none",a.$$context.drawImage(a.$$memCanvas,0,0);const t=a.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(ba.Image,{type:Q.ImageData,value:t})}},getInputNames:()=>[{name:wa.Image,type:Q.ImageData}],getOutputNames:()=>[{name:ba.Image,type:Q.ImageData}],getDefaultState:Na},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:Q.Boolean}]}},xa={},Ca=async()=>{if(!Object.keys(xa).length)for(const e in Aa){const t=Aa[e];xa[e]=Object.freeze({...t})}};var Pa=e=>{if(xa[e])return xa[e];throw new Error(Be(Le,e))},Ea=Ca;const ja=new o,Da="invoked";let ka={},Oa={},Ta={},La={};const Ma=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var Ba=(e,t,n,r,a)=>{const i=Ma(e,t,n),o=Ma(e,t),s=Ma(e,t,"produced"),c=Ta[o],u=Date.now();La[o]=u,ka[i]={data:r,sourcePortName:n,...a?{target:{widgetId:a.widgetId,portName:a.portName}}:{}},ja.emit(s,{currentTime:u,prevTime:c,...a?{targetPort:a?.portName}:{}})},Ra=(e,t,n,r,a)=>{const i=Ma(e,t,n),o=Ma(e,t),s=Ma(e,t,Da),c=Ta[o],u=Date.now();Ta[o]=u,Oa[i]={data:r,sourcePortName:n,...a?{source:{widgetId:a.widgetId,portName:a.portName}}:{}},ja.emit(s,{prevTime:c,currentTime:u,targetPort:n,sourceInfo:a})},Wa=()=>{ka={},Oa={},Ta={},La={},ja.clearListeners()};let Ua,Fa,_a;const Ga=async(e,t,n,r,a)=>{const i=G(n,t);if(!i)return;const o=i.gates[e];if(!o||o.disabled)return;const s={...a,timestamp:Date.now()},c=Pa(o.type),u=Ja(e,s,i.recipeId,i.id,i.version,n);if(u&&c.onParentEvent){const t={name:r};return Ua&&await Ua({recipeId:n,blockId:i.recipeId,gateId:e,targetPort:t.name,data:a}),c.onParentEvent(null,t,{originalEvent:s,data:{...s}},u)}},za=async(e,t,n,r,a,i,o,s,c,u)=>{if(!e&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!e&&!u)throw new Error("Missing parameter ['originalEvent']");e&&(u={timestamp:Date.now(),type:Q.Boolean,value:!0});const d=u;if("string"==typeof n){const e=G(r,n);if(!e)return;n=e}const l=n.gates[t];if(!l||l.disabled)return;const p=s.findIndex((e=>e.name===a)),g=Pa(l.type),m=Ja(t,d,n.recipeId,n.id,n.version,r);if(m&&g.onParentEvent&&-1!==p){Ua&&await Ua({recipeId:r,blockId:n.recipeId,gateId:t,targetPort:i.name,data:o,sourceGate:e?"interrupt_widget":c,sourcePort:e?H:a});const u={name:s[p].name,type:s[p].type,...s[p].jsonShape?{jsonShape:s[p].jsonShape}:void 0};return Ra(n.recipeId,t,i.name,o,c?{widgetId:c,portName:a}:void 0),g.onParentEvent(u,i,{originalEvent:d,data:o},m)}},Va=async(e,t,n,r,a,i,o,s)=>{const c=_(s);if(!c)throw new Error(`Failed to find recipe "${s}" in cache`);const u=c.dbInfo.recipeType,d=z(s,a,r);if(!d)return;const l={...n,timestamp:t.timestamp},p=Pa(d.type);let g;g=d.type===Ce.input?p.getOutputNames(d.state,{thingRecipeId:a,thingDbId:i,thingVersion:o,id:r,recipeId:s,recipeType:u,recipePoolId:s}):await p.getOutputNames(d.state,{recipePoolId:s,recipeType:u,thingRecipeId:a,widgetId:r});if(-1!==g.findIndex((t=>t.name===e))){const n=G(s,a);if(!n)return;Ba(a,r,e,l);const i=d.children.length;for(let o=0;o<i;o++){if(Ne(d.children[o]?.sourcePort).portName===e){const i=n.gates[d.children[o].childId];if(i&&!i.disabled){const c=Pa(i.type);let p;const m={recipePoolId:s,recipeType:u,thingRecipeId:a,widgetId:r};p=i.type===Ce.hubService?await c.getInputNames(i.state,m):c.getInputNames(i.state,m);const v=Ne(d.children[o].targetPort),f=p.find((e=>e.name===v.portName));f&&await za(!1,i.id,n,s,e,{name:f.name},d.returnOriginalEvent?t:l,g,d.id,t)}}}}},Ha=async(e,t,n,r)=>{const a=_(r);if(!a)return null;const i=G(r,n);if(!i)return i;const o=i.gates,s=i.gates[t],c=Pa(s.type),u=await c.getInputNames(s.state,{recipePoolId:r,recipeType:a.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),d=u.findIndex((t=>t.name===e));if(-1!==d){const e=((e,t,n)=>{for(const r in n){const a=n[r],i=a.children.length;for(let n=0;n<i;n++){const r=a.children[n],i=Ne(r.targetPort);if(r.childId===e&&i.portName===t)return a}}return null})(t,u[d].name,o);if(e){const t=Pa(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},Ja=(e,t,n,r,a,i)=>{const o=_(i);if(!o)throw new Error(`Failed to find recipe "${i}" in cache`);const s=z(i,n,e);if(!s)return console.warn(`Gate ${e} not found in block ${n} for recipe ${i}`),null;const c=async(o,s)=>Va(o,t,s,e,n,r,a,i),u={id:e,type:s.type,recipePoolId:i,thingRecipeId:n,recipeType:o.dbInfo.recipeType,returnOriginalEvent:!!s.returnOriginalEvent,registerInterrupt:(t,r,a,o,s)=>ke.createInterrupt(t,i,n,e,r,a,o,s),cancelInterrupt:e=>ke.destroyInterrupt(e),nextWidget:c,nextGate:c,getParentAtPort:t=>Ha(t,e,n,i),getState:()=>Object.freeze({...s.state,...s.type===Ce.input&&{customInputs:[]}}),setState:t=>{if("object"!=typeof t)return void console.warn(`Invalid state type [${typeof t}]. Expected an 'object'`);const r={...t,...s.type===Ce.input&&!t.customInputs&&{customInputs:[]}},a={...s.state};s.state=r,Fa&&Fa({blockId:n,gateId:e,prevState:a,newState:{...r},recipeId:i})}};return u};ke.setInvokeChildGateCb(za);const qa=new o,Ka="invoked",Xa="state",Ya=()=>{ke.destroyAllInterrupts()},Za=async(e,t,n)=>{const r=_(e),a=z(e,t,n);if(a&&r){const i=Pa(a.type);if(i&&"function"==typeof i.terminate){const a=((e,t,n,r)=>Oe(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(a)try{await i.terminate(a)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},Qa=async(e,t,n,r)=>{const a=_(e),i=z(e,t,n);if(i&&a){const o=Pa(i.type);if(o&&"function"==typeof o.initialize){const i=((e,t,n,r)=>Oe(e,t,n,r,!0))(e,a.dbInfo.recipeType,t,n);if(i){const e=o.initialize;try{await e(i,r||{})}catch(e){throw console.warn(`Error initializing widget "${n}" in thing "${t}": `,e),e}}}}},ei=(e,t)=>{const n=_(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},ti=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,ni=e=>{qa.emit(ti(Xa),e),qa.emit(ti(Xa,e.blockId,e.gateId),e)};Ua=async e=>{await qa.emit(ti(Ka),e),await qa.emit(ti(Ka,e.blockId,e.gateId),e)},(e=>{Fa=e})(ni);var ri=async(e,t,n,r,a)=>{const i=V(e,{id:t,authorId:r,version:n,recipeType:a});Wa();const o=_(i);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=R.STARTING,o.addLog("recipe registered")),i},ai=async e=>{const t=_(e);var n;if(!t)return null;t.addLog("terminating recipe"),Ya();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await Za(e,n,t)}W[n=e]&&delete W[n]},ii=async(e,t)=>{const n=_(e),r=[];if(n)for(const a in n.blocks){const i=n.blocks[a];if(!t||!Array.isArray(t)||t.includes(a))for(const t in i.gates)try{if(n.dbInfo?.recipeType===$n.Desktop){const e=i.gates[t];if(e.type===Ce.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}}await Qa(e,a,t,{keepCurrentState:!0})}catch(e){r.push({widgetId:t,error:e.message})}}return{failed:r,sendToInputWidget:(t,n,r=Y)=>(async(e,t,n,r)=>{const a=_(n),i=G(n,r),o=Date.now();if(i&&a)for(const a in i.gates){const s=i.gates[a];if(s.type===Ce.input&&!s.disabled){const c=s.state.inputName||"";if(c===e){const e=Pa(s.type),u={...t,timestamp:o},d=Ja(a,u,r,i.id,i.version,n);if(d&&e.processEvent){const i={...d,getState:d.getState};Ua&&await Ua({recipeId:n,blockId:r,gateId:a,targetPort:We,data:t}),_a?await _a(r,n,c,t):await e.processEvent(u,i)}}}}})(t,n,e,r)}},oi=e=>{ha(e)},si=(e,t,n,r=!1)=>{const a=ei(t,e);if(a){const{widget:i,thing:o}=a,s={...i.state};i.state=n,r&&ni({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:s})}},ci=(e,t)=>{const n=ei(t,e);return n?n.widget.state:null},ui=async(e,t,n,r,a)=>{const i=ei(t,e);if(i)return Va(n,r,a,t,i.thing.recipeId,i.thing.id,i.thing.version,e)};const di=e=>{try{return JSON.parse(e)}catch(e){return null}},li="undefined"!=typeof window,pi={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},gi={protocolPrefix:4,txtLength:4},mi=Object.values(pi).reduce(((e,t)=>e+t),0),vi=Object.values(gi).reduce(((e,t)=>e+t),0),fi=["width","height","colorSpace"],yi=(e,t)=>{const n={},r=[];let a=0,i=Array.isArray(e)?[]:{};const o=(e,i)=>{const s=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,a=e instanceof Uint8Array,i=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":a?"Uint8Array":i?"Int8Array":null})(e);if(!s){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${i}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,a=e instanceof Uint32Array,i=e instanceof Float32Array,o=e instanceof Float64Array,s=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":a?"Uint32Array":i?"Float32Array":o?"Float64Array":s?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${i}"`);for(const n in e)e.hasOwnProperty(n)||fi.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${i}`),t[n]=o(e[n],`${i.length?`${i}.`:""}${n}`);return t}return e}n[i]={index:a,length:e.byteLength,binaryType:s},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===s?r.push(e):r.push(e.buffer),a+=e.byteLength};i=o(e,"");let s=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;s=t.buffer}else{s=Buffer.concat(r)}else 1===r.length&&(s=r[0]);return s?{map:n,combinedData:s,sourceCopy:i}:null},hi=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let a=e;for(let e=0;e<r.length;e++){let t=r[e];const i=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(i){t=t.slice(1,-1);const i=parseInt(t,10);if(!Array.isArray(a))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?a[i]=n:(a[i]||(a[i]=r[e+1].startsWith("[")?[]:{}),a=a[i])}else o?a[t]=n:(a[t]||(a[t]=r[e+1].startsWith("[")?[]:{}),a=a[t])}return e},Ii=(e,t,n)=>{const r="undefined"!=typeof Buffer,a=t instanceof Uint8Array;for(const i in n)if(n.hasOwnProperty(i)){const{index:o,length:s,binaryType:c}=n[i];let u=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":u=t.subarray(o,o+s);break;case"ArrayBuffer":u=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+s);break;case"Uint8Array":u=new Uint8Array(t.subarray(o,o+s));break;case"Uint8ClampedArray":u=new Uint8ClampedArray(t.subarray(o,o+s));break;case"Int8Array":u=new Int8Array(t.subarray(o,o+s))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){u=Buffer.from(t.slice(o,o+s));break}case"ArrayBuffer":u=a?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+s):t.slice(o,o+s);break;case"Uint8Array":u=a?t.slice(o,o+s):new Uint8Array(t.slice(o,o+s));break;case"Uint8ClampedArray":u=new Uint8ClampedArray(t.slice(o,o+s));break;case"Int8Array":u=new Int8Array(t.slice(o,o+s))}u&&hi(e,i,u)}return e},Si=e=>d(e),$i="KMSG",wi="KCMD",bi=Si("klProtocol");var Ni={encode:(e,t,n)=>{const r={json:e.json},a=yi(r.json,"Buffer"),i=a?.combinedData;a&&(r.jsonBinaryMap=a.map,r.json=a.sourceCopy);const o=i?i.byteLength:0,s=JSON.stringify(r),c=Buffer.from(s),u=c.byteLength,d=pi.protocolPrefix+pi.protocolVersion+pi.jsonLength+pi.binaryLength+pi.fromServiceId+pi.toServiceId+pi.sentAt+u+o,l=Buffer.alloc(d),p=Date.now();let g=0;return l.write($i,g),g+=pi.protocolPrefix,l.writeUInt8(1,g),g+=pi.protocolVersion,l.writeUInt32LE(u,g),g+=pi.jsonLength,l.writeUInt32LE(o,g),g+=pi.binaryLength,l.writeUInt32LE(t,g),g+=pi.fromServiceId,l.writeUInt32LE(n,g),g+=pi.toServiceId,l.writeBigInt64LE(BigInt(p),g),g+=pi.sentAt,c.copy(l,g),g+=u,i&&o&&i.copy(l,g),l},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,pi.protocolPrefix);if(t+=pi.protocolPrefix,n!==$i)return null;if(e.byteLength<mi)return bi(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=pi.protocolVersion;const a=e.readUInt32LE(t);t+=pi.jsonLength;const i=e.readUInt32LE(t);t+=pi.binaryLength;const o=e.readUInt32LE(t);t+=pi.fromServiceId;const s=e.readUInt32LE(t);t+=pi.toServiceId;const c=e.readBigInt64LE(t);t+=pi.sentAt;const u=a+i,d=e.subarray(t,t+u),l=e.subarray(0,mi);let p=null;return e.byteLength-mi-a-i>0&&(p=e.subarray(mi+a+i)),{header:{protocolVersion:r,jsonLength:a,binaryLength:i,fromServiceId:o,toServiceId:s,sentAt:new Date(Number(c)),packages:[d],headerPackage:l},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),a=di(n);if(!a?.json)return bi("Invalid JSON in KL message"),null;a.jsonBinaryMap&&r.byteLength&&Ii(a.json,r,a.jsonBinaryMap);const i=Buffer.concat([e.headerPackage,t]);let o=i,s=null;const c=mi+e.jsonLength+e.binaryLength;return i.byteLength>c&&(s=i.subarray(c),o=i.subarray(0,c)),{message:{json:a.json,rawMessage:o},remaining:s}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<mi)return bi("Invalid Header Size"),e;let n=0;return n+=pi.protocolPrefix,n+=pi.protocolVersion,n+=pi.jsonLength,n+=pi.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=pi.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,a=vi+r,i=Buffer.alloc(a);return i.write(wi,t),t+=gi.protocolPrefix,i.writeUint32LE(r,t),t+=gi.txtLength,n.copy(i,t),i},decodeCommand:e=>{let t=0;if(e.byteLength<vi)return{command:null};const n=e.toString("utf-8",t,gi.protocolPrefix);if(t+=gi.protocolPrefix,n!==wi)return{command:null};const r=e.readUInt32LE(t);t+=gi.txtLength;const a=e.toString("utf-8",t,t+r),i=e.byteLength-vi-r;let o=null;i>0&&(o=e.subarray(vi+r));let s=0;return i<0&&(s=Math.abs(i)),{command:a,remainingData:o,missing:s}}};const Ai="KMSG",xi="KCMD",Ci=Si("klProtocol"),Pi=new TextEncoder;var Ei={encode:(e,t,n)=>{const r={json:e.json},a=yi(e.json,"ArrayBuffer"),i=a?.combinedData;a&&(r.jsonBinaryMap=a.map,r.json=a.sourceCopy);const o=i?i.byteLength:0,s=JSON.stringify(r),c=Pi.encode(s),u=c.byteLength,d=new ArrayBuffer(pi.protocolPrefix+pi.protocolVersion+pi.jsonLength+pi.binaryLength+pi.fromServiceId+pi.toServiceId+pi.sentAt+u+o),l=new DataView(d),p=new Uint8Array(d),g=Date.now();let m=0;for(let e=0;e<4;++e)p[m++]=Ai.charCodeAt(e);return l.setUint8(m,1),m+=pi.protocolVersion,l.setUint32(m,u,!0),m+=pi.jsonLength,l.setUint32(m,o,!0),m+=pi.binaryLength,l.setUint32(m,t,!0),m+=pi.fromServiceId,l.setUint32(m,n,!0),m+=pi.toServiceId,l.setBigInt64(m,BigInt(g),!0),m+=pi.sentAt,p.set(c,m),m+=u,i&&o&&p.set(new Uint8Array(i),m),d},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<pi.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ai)return null;if(e.byteLength<mi)return Ci.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const a=t.getUint8(n);n+=pi.protocolVersion;const i=t.getUint32(n,!0);n+=pi.jsonLength;const o=t.getUint32(n,!0);n+=pi.binaryLength;const s=t.getUint32(n,!0);n+=pi.fromServiceId;const c=t.getUint32(n,!0);n+=pi.toServiceId;const u=t.getBigInt64(n,!0);n+=pi.sentAt;const d=i+o,l=e.slice(n,n+d),p=new Uint8Array(e,0,mi);let g=null;if(e.byteLength-mi-i-o>0){g=new Uint8Array(e,mi+i+o).slice().buffer}return{header:{protocolVersion:a,jsonLength:i,binaryLength:o,fromServiceId:s,toServiceId:c,sentAt:new Date(Number(u)),packages:[l],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,a=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,a),a+=r.byteLength;const i=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),s=di(i);if(!s?.json)return Ci.log("Invalid JSON in KL message"),null;s.jsonBinaryMap&&o.byteLength&&Ii(s.json,o,s.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let u=c,d=null;const l=mi+e.jsonLength+e.binaryLength;return c.byteLength>l&&(d=c.subarray(l),u=c.subarray(0,l)),{message:{json:s.json,...o.length?{binaryData:o.buffer}:{},rawMessage:u.buffer},remaining:d?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<mi)return Ci("Invalid Header Size"),e;let n=0;n+=pi.protocolPrefix,n+=pi.protocolVersion,n+=pi.jsonLength,n+=pi.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=pi.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Pi.encode(e),r=n.byteLength,a=new ArrayBuffer(vi+r),i=new DataView(a),o=new Uint8Array(a);for(let e=0;e<4;++e)o[t++]=xi.charCodeAt(e);return i.setUint32(t,r,!0),t+=gi.txtLength,o.set(n,t),a},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<vi)return{command:null};let r="";for(let e=0;e<gi.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==xi)return{command:null};const a=t.getUint32(n,!0);n+=gi.txtLength;const i=e.byteLength-vi-a,o=new Uint8Array(e,n,Math.min(a,e.byteLength-vi)),s=(new TextDecoder).decode(o);let c=null;i>0&&(c=e.slice(vi+a));let u=0;return i<0&&(u=Math.abs(i)),{command:s,remainingData:c,missing:u}}};let ji=Ni;li&&(ji=Ei);var Di,ki=ji;!function(e){e.FunctionNotFound="FNC_NOT_FOUND"}(Di||(Di={}));let Oi=Math.ceil(Date.now()/1e3);function Ti(e){const t={};let n=console.log;const r={};let a=e||String(Date.now());const i={},o=e=>!i[e],s=(e,t,n,r,a,i)=>{let s=li?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:i.success?i.success:[i],messageId:t,type:i.success?"response":"error"}};return o(r)&&(s=ki.encode(c,n,r)),a(s,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,a,i,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=>{s(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,a,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:i.sourceServiceId,send:a})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),s(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,a,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,i,s,c,u)=>{if(!i){const e="No send buffer function provided.";throw n&&n(e),e}Oi+=1;const d=`${a}-${Oi}-exec-${e.substring(0,10)}`,l={messageId:d,functionName:e,send:i,sourceServiceId:s,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};l.promise=new Promise(((e,t)=>{l.resolve=e,l.reject=t}));let p=li?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:r,messageId:d,type:"execute"}};o(c)&&(p=ki.encode(g,s,c)),t[d]=l,n&&n(`Calling remote function "${e}" with message id "${d}"`);const m="true"===process.env.NO_INVOKE_TIMEOUT;return u?.async?(l.fulfilled=!0,l.resolve([void 0]),delete t[d]):0===u?.timeout||m||(l.timer=setTimeout((()=>{n&&n(`Remote function ${d} timed out`);const r=t[d];r&&!r.fulfilled&&(r.fulfilled=!0,l.reject(`Function ${e} Timed out`)),delete t[d]}),u?.timeout||3e4)),i(p,{sourceServiceId:s,targetServiceId:c,msg:g}),l.promise},sendResponse:s,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{a=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,i)=>{Oi+=1;const s=`${a}-${Oi}-multicast-${e.substring(0,10)}`;let c=li?new ArrayBuffer(0):Buffer.alloc(0);const u={json:{functionName:e,args:t,messageId:s,type:"execute"}};let d=o(r[0].serviceId);d&&(c=ki.encode(u,i,r[0].serviceId));for(let t=0;t<r.length;t++)try{const a=r[t];n&&n(`Broadcasting function "${e}" with message id "${s}" to client [${a.serviceId}]`),0!==t&&(d=o(a.serviceId),d&&(c=ki.patchEncodedHeader(c,{toServiceId:a.serviceId}))),a.sendFn(c,{msg:u,sourceServiceId:i,targetServiceId:a.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{i[e]=t}}}let Li,Mi,Bi,Ri,Wi,Ui=!1;var Fi=()=>{Ui=!0},_i=(e,t)=>{if(!Li)throw new Error("Memory connection not set.");Li.sendBuf(e,t)},Gi=e=>Mi=e,zi=e=>Wi=e,Vi=e=>Bi=e,Hi=e=>Ri=e,Ji=e=>(Li.sendCmd(e),!0);const qi=(e,t=2)=>{const n=(e,r)=>{if("object"==typeof e){const a=Object.keys(e);for(const i of a){const a=e[i];if(a&&"object"==typeof a){const o=a._kemuType;if(void 0!==o){if(o===Q.ImageData){const t=e[i];e[i]=Ae(t)}}else r<t&&n(a,++r)}}}};return n(e,1),e},Ki=Si("klTransmissionManager"),Xi=()=>{const e=(t,n,r,a)=>{let i=n,o=null;const s=t instanceof ArrayBuffer;if(Ki(`RAW: ${t.toString()}`),!i||i.partialHeaderData){let c;if(s?(c=i?.partialHeaderData?new Uint8Array([...new Uint8Array(i.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=Ei.decodeHeader(c)):(c=i?.partialHeaderData?Buffer.concat([i.partialHeaderData,t]):t,o=Ni.decodeHeader(c)),!o){const{command:t,missing:i,remainingData:o}=s?Ei.decodeCommand(c):Ni.decodeCommand(c);return t?a({command:t,complete:!0,rawMessage:c}):Ki(i?`ERROR: Missing ${i} 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?(Ki(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,n,r,a)):void 0}if(o.partialHeader)return i={firstPackageAt:Date.now(),partialHeaderData:c},r(i);if(!o.header)return Ki(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const u=o.header;i={firstPackageAt:Date.now(),header:{...u,totalBytesReceived:u.packages[0].byteLength,totalBytesExpected:u.binaryLength+u.jsonLength,remaining:o.remaining}},r(i)}else i.header&&i.header.totalBytesReceived<i.header.totalBytesExpected&&(i.header.packages.push(t),i.header.totalBytesReceived+=t.byteLength,r(i));if(i.header&&i.header.totalBytesReceived>=i.header.totalBytesExpected){const t=Date.now()-i.header.sentAt.getTime(),n=Date.now()-i.firstPackageAt;Ki(`Received ${i.header.totalBytesReceived} of ${i.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=s?Ei.decodeFullKlMessage(i.header):Ni.decodeFullKlMessage(i.header),c=i.header.totalBytesReceived,u=i.header.remaining;r(null),o&&a({klMessage:o.message,complete:!0,sourceServiceId:i.header.fromServiceId,targetServiceId:i.header.toServiceId,rawMessage:o.message.rawMessage});let d=u;if(o?.remaining&&(d=s?u?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),a=new Uint8Array(e),i=new Uint8Array(t),o=new Uint8Array(r);return o.set(a),o.set(i,a.length),r})(u,o.remaining):o.remaining:u?Buffer.concat([u,o.remaining]):o.remaining),d)return Ki(`${d.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(d,null,r,a)}};return e};Si("ipcClient");Si("kemuWidgetService"),$(process.argv.slice(2));const Yi=e=>d(`runner:${e}`),Zi=Yi("connectionManager"),Qi=Yi("remoteInvoke"),eo=new Ti("kweb");eo.setLogger(Qi);const to=new o,no=new o;let ro,ao=null,io=null;const oo={},so=(e,t,n)=>{const r=`${e}_${t}`,a={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return oo[r]=a,a},co=(e,t)=>oo[`${e}_${t}`]||null,uo=async(e,t)=>{if(!ao)return Zi("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await eo.execute(re.GetServiceContents,n,po,ao,0))[0]},lo=async(e,t,n=!1)=>{if(!e||!t)return null;const r=co(e,t);if(!r||n){const n=r||so(e,t);try{const r=await uo(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){Zi(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},po=_i,go=()=>{Zi("Disconnected from the server"),ao=null,eo.rejectAllPending("Disconnected from the server"),to.emit("disconnected")},mo=()=>{Zi("Connected to the server"),to.emit("connected")},vo=()=>io,fo=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,yo=async()=>{const e=vo();if(e){const t=_(e)?.blocks;if(t){const n={};for(const r in t){const a=t[r];for(const t in a.gates){const r=a.gates[t];if(r.type===Ce.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{Zi(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await Do({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){Zi(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},ho=async e=>{const t=e.args[0],n=fo("broadcast",`hub_${t.type}`,(0).toString(),"");await no.emit(n,t)},Io=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===Q.ImageData&&he(e.value)&&(e.value=Ae(e.value));const n=vo();if(n){const r=_(n);if(r){const a=async e=>{const n=fo("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await no.emit(n,t)}catch(t){Zi(`Failed to emit broadcast event for target ${e}`,t)}};await a("app");for(const i in r.blocks){const o=r.blocks[i];for(const r in o.gates){const i=o.gates[r];if(i.disabled)continue;const s=i.state;if(i.type===Ce.hubService&&s.service?.name===t.source.serviceName&&s.service?.version===t.source.serviceVersion&&s.variantId===t.variantId){await a(r);for(const a of t.outputs||[])if(null!==a.value&&void 0!==a.value){const t={type:a.type,value:a.value,timestamp:Date.now()};Zi(`Sending data to output ${a.name} requested by messageId ${e.messageId}`),await ui(n,r,a.name,t,t)}}}}}}},So=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:a}=t,i=ci(r,a);let o=i;if(n&&o&&i&&(o={...i,customState:n},si(r,a,o,!0)),o?.service)try{const e=fo("setOutputs",o.service.name,o.service.version,a);await no.emit(e,t.outputs)}catch(e){Zi(`Failed to emit setOutputs event for widget ${a}`,e)}for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===Q.ImageData){if(!he(n.value)){Zi(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=Ae(n.value)}else n.type===Q.JsonObj&&qi(n.value);const t={type:n.type,value:n.value,timestamp:Date.now()};Zi(`Sending data to output ${n.name} requested by messageId ${e.messageId}`),await ui(r,a,n.name,t,t)}e.reply({success:[]})},$o=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:a}=t,i=ci(r,a);if(i){const t={...i,customState:{...i.customState,...n}};return si(r,a,t,!0),e.reply({success:[]})}},wo=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:a,path:i,key:o}=n;Zi(`Received request to set a dependency path for "${o}" on widget "${a}" in recipe "${r}"`);const s=ci(r,a);if(s){const e={...s};e.dependencies=e.dependencies||{},e.dependencies[o]={path:i},si(r,a,e,!0)}return t({success:[]})},bo=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:a,key:i}=n;Zi(`Received request to get a dependency path for "${i}" on widget "${a}" in recipe "${r}"`);const o=ci(r,a);if(o){const e=o.dependencies?.[i]?.path;return Zi(`Returning dependency path for "${i}" on widget "${a}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},No=async()=>{if(Zi(`Requesting services on ${(new Date).toISOString()}`),!ao)return Zi("Hub Link has not been acknowledged. Cannot get services."),[];const e=await eo.execute(re.GetServices,[],po,ao,0);ro=e;for(const t of e){if(t.internal)continue;const e=co(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||so(t.name,t.version);Zi(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await uo(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){Zi(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},Ao=()=>[...ro||[]],xo=()=>!!ro,Co=async e=>{const{targetServiceSessionId:t}=e;if(!ao)return void Zi("No target service session id provided");Zi(`Forwarding "onParentEvent" to service ${t}`);return await eo.execute(re.OnParentEvent,[e],po,ao,t,e.config)},Po=async e=>{if(!ao)return Zi("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await eo.execute(re.GetDefaultState,[],po,ao,e);return t},Eo=async(e,t,n,r)=>{if(!ao)return Zi("Hub Link has not been acknowledged. Cannot get services."),null;const[a]=await eo.execute(re.UIEvent,[t,n],po,ao,e,r);return a},jo=(e,t)=>{const n=()=>{t()};return to.on(e,n),()=>to.off(e,n)},Do=async e=>{if(ao)return eo.execute(re.SubscribeToService,[e],po,ao,0);Zi("Hub Link has not been acknowledged. Cannot subscribe to services.")},ko=async e=>{if(ao)return eo.execute(re.UnsubscribeFromService,[e],po,ao,0);Zi("Hub Link has not been acknowledged. Cannot subscribe to services.")},Oo=(e,t,n,r)=>{const a=fo("broadcast",t,n,e);return no.on(a,r)},To=(e,t,n,r)=>{const a=fo("setOutputs",t,n,e);return no.on(a,r)},Lo=async(e,t,n)=>ao?eo.execute(e,t,po,ao,0,n):(Zi("Hub Link has not been acknowledged. Cannot execute function."),null),Mo=async e=>{if(!ao)return void Zi("Hub Link has not been acknowledged. Cannot execute function.");const t=ci(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}],[a]=await eo.execute(re.InitializeInstance,r,po,ao,e.sessionId);if(a){const t=ci(e.recipeId,e.widgetId);if(t){const n={...t,customState:a};si(e.recipeId,e.widgetId,n,!0)}}},Bo=async(e,t,n,r)=>{if(!ao)return void Zi("Hub Link has not been acknowledged. Cannot execute function.");const a=ci(n,t);if(!a)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const i=[{currentState:a.customState,recipeId:n,widgetId:t,variantId:r}];await eo.execute(re.TerminateInstance,i,po,ao,e)},Ro=async(e,t,n="^",r)=>{const a=["^","~",">=",">","<=","<","="];if(!a.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${a.join(", ")}`);const i=xo(),o=r||!i?await No():Ao();for(const r of o)if(r.name===e){if(r.version===t)return r;if(c(r.version,`${n}${t}`))return r}return null};var Wo=async()=>{Vi(mo),Hi(go),zi((({json:e,transmission:t})=>{eo.processMessage("websocket",po,t,e)})),eo.registerFunction(re.SetState,$o),eo.registerFunction(re.SetOutputs,So),eo.registerFunction(re.BroadcastEvent,Io),eo.registerFunction(re.HubBroadcastEvent,ho),eo.registerFunction(ae.SetDependencyPath,wo),eo.registerFunction(ae.GetDependencyPath,bo),Gi((e=>{((e,t)=>{const n=ne.SocketAcknowledge,r=ne.IpcAcknowledge,a=e.startsWith(n);if(e===r)return t&&t(),0;if(a){const i=e.split(a?n:r),o=parseInt(i[1]);return t&&t(o),o}})(e,(e=>{e?(Ji((e=>`${ne.AcknowledgeResponse}${e}`)(e)),Zi("Hub Link acknowledged"),ao=e,to.emit("acknowledged"),yo()):Zi("Hub sent ACK request without service id")})),((e,t)=>{e===ne.ServicesListChanged&&(t&&t())})(e,(()=>{Zi("Services list changed"),to.emit("services-changed")}))})),await Fi()},Uo=(e,t)=>{to.on(e,t)},Fo=()=>({getServices:No,getServiceContents:lo,onParentEvent:Co,onCommand:jo,getDefaultState:Po,getCachedServices:Ao,areServicesCached:xo,subscribeToServiceEvents:Do,unsubscribeFromServiceEvents:ko,callProcessorHandler:Eo,onBroadcastEvent:Oo,onSetOutputsEvent:To,executeHubFunction:Lo,initializeServiceInstance:Mo,terminateServiceInstance:Bo,getCompatibleService:Ro}),_o=e=>{io=e},Go=()=>eo;const zo=e=>{try{return JSON.parse(e)}catch(e){return null}},Vo=(e,t)=>{if(e.startsWith(ne.AcknowledgeResponse)){const n=e.split(":"),r=parseInt(n[1]),a=parseInt(n[2]);return t&&t(r,isNaN(a)?void 0:a),!0}return!1},Ho=e=>d(e),Jo=Date.now();let qo=Math.ceil(Jo/1e3);var Ko=()=>qo+=1;const Xo=p(x(),"kemu-user-services"),Yo="KMU-CB-v1";var Zo;!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"}(Zo||(Zo={}));const Qo=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>Q[e])):Q[e.type]}),es=async e=>{try{return await f(e,"utf-8")}catch(e){return null}},ts=e=>{if(e&&e.startsWith(Yo)){const t=e.slice(9),n=decodeURI(t);return zo(n)}return null},ns=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(Qo)}:{},...e.outputs?{outputs:e.outputs.map(Qo)}:{}}))));const a={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(Qo)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(Qo)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},i=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const a of t.customWidgets){const t=await es(p(e,a));if(!t){n(`Error loading custom widget file ${a}`);continue}const i=t.startsWith(Yo)?t:`${Yo}${t}`,o=ts(i);if(!o){n(`Custom widget file "${a}" is not a valid Kemu Clipboard item`);continue}const s=Object.values(o).filter((e=>e.type===Zo.widgetGroup&&!e.groupId));if(s.length>1){n(`Custom widget file "${a}" contains more than one top level widgetGroup`);continue}const c=s[0];if(!c){n(`Custom widget file "${a}" does not contain a top level widgetGroup`);continue}const u=c.state,d={name:u.name,color:u.color,description:u.description,contents:i,rootGroupId:c.id,icon:u.icon,protocolVersion:u.protocolVersion||"2"};r.push(d)}return r})(t,e,n?.log);if(i.length?a.customWidgets=i:delete a.customWidgets,a.variants?.length)for(const e of a.variants)if(e.svgIcon)try{const n=await f(p(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return a},rs=async e=>{try{return await y(e,h.F_OK),!0}catch{return!1}},as=Ho("serviceManager"),is={};let os=null;const ss=e=>{if(!os)throw new Error('IPC config not set, call "setHubIpcConfig" first.');try{if(e.processor===te.Javascript){as(`Spawning service ${e.name} with sessionId ${e.sessionId}`);const t=l.join(e.path,"processor.js"),n=[`--sessionId=${e.sessionId.toString()}`,`--ipcSpace=${os.appSpace}`,`--ipcId=${os?.id}`,`--recipePath=${os.recipePath||""}`];e.internal&&n.push("--internal=true");const r=N("node",[t,...n]);return r.stdout.on("data",(t=>{as(`[Service ${e.name}] - stdout: ${t}`)})),r.stderr.on("data",(t=>{as(`[Service ${e.name}] - stderr: ${t}`)})),as(`[Service ${e.name}] spawned with PID ${r.pid}`),r}throw`Unsupported processor type ${e.processor}`}catch(t){throw`Error spawning service ${e.name}: ${t}`}},cs=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[te.Javascript,te.Executable,te.Python].includes(e?.processor)?null:"Invalid processor"},us=async(e,t)=>{const n=l.join(e,"manifest.json");if(!w.existsSync(n)){const t=`Missing manifest for service ${e}. Aborting.`;return as(t),{error:t}}const r=await f(n,"utf-8"),a=zo(r),i=cs(a);if(!a||i){const t=`Invalid service manifest [${e}]: ${i}. Aborting.`;return as(t),{error:t}}let o;if(delete a.internal,t?.singleServiceName&&a.name!==t.singleServiceName){return{error:`Skipping service ${a.name} as it does not match the singleServiceName option`}}await Promise.all([(async()=>{if(a.widgetUI)try{o=await f(l.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${a.name}: ${e}`;return as(t),{error:t}}})(),(async()=>{if(a.svgIcon){const t=await es(l.join(e,a.svgIcon));if(!t){return{error:`Error loading icon for service ${a.name}`}}a.svgIcon=t}})(),(async()=>{if(a.subServices?.length)for(const t of a.subServices){const n=l.join(e,t),{error:r,service:i}=await us(n);r?as(`Error loading sub-service ${t}: ${r}`):i&&(i.info.parentService={name:a.name,version:a.version})}delete a.subServices})(),(async()=>{if(a.variants?.length)for(const t of a.variants)if(t.svgIcon)try{const n=await f(l.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){as(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const s=Ko(),c=t?.fixedSession||s;as(`Loaded service ${a.name} with sessionId ${c}`);const u=await ns(a,e,{widgetUIContents:o});return ds(u),is[c]={info:{...u,path:e,sessionId:c},status:"loaded",childProcess:null},{service:is[c]}},ds=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=A("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},ls=e=>{try{return e.childProcess=ss(e.info),e.status="started",!0}catch(t){return as(`Service [${e.info.name}] error: ${t}`),e.status="error",e.errorMsg="string"==typeof t?t:JSON.stringify(t),!1}},ps=()=>Object.values(is).filter((e=>"running"===e.status)).map((e=>{const{path:t,...n}=e.info;return{...n}})),gs=(e,t)=>{const n=Object.values(is).find((n=>n.info.name===e&&n.info.version===t));if(!n)return null;if(n.info.internal)throw`Cannot stop internal service ${e}`;if(n.childProcess){as(`Stopping service "${e} (v${t})"`);n.childProcess.kill("SIGINT")||as(`Failed to stop service ${e}`)}return n.status="stopped",as(`Service ${e} stopped`),n},ms=e=>e.info.internal?e.info.path:l.join(e.info.path,"..");var vs={loadServices:async(e,t)=>{if(!await rs(e))return void as(`Failed to load services from "${e}". Directory does not exist.`);const n=w.readdirSync(e,{withFileTypes:!0}).filter((e=>e.isDirectory())).map((e=>e.name));as(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const a=n[r],i=l.join(e,a),{error:o,service:s}=await us(`${i}${t?.internalServices?"":"/dist"}`,t);o&&as(`Failed to load service ${i}. Please check logs`),s&&t?.internalServices&&(s.info.internal=!0)}},launchServices:async e=>{if(as("Initializing services"),!os)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in is){const n=is[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?as(`Service ${n.info.name} is in the noSpawningList. Skipping.`):ls(n)}as("Services initialized")},setServiceStatus:(e,t)=>{const n=is[e];return n?(n.status=t,!0):(as(`Service with serviceId ${e} not found`),!1)},getActiveServices:ps,getMatchingService:(e,t)=>{const n=Object.values(is).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(u(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>is[e]||null,killAllServices:()=>{for(const e in is){const t=is[e];if(t.childProcess)try{as(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){as(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await ns(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};is[e]=r,ds(is[e].info)},setServiceManifest:(e,t,n)=>{const r=is[e];if(!r)return as(`Service with sessionId ${e} not found`),!1;const a=cs(t);if(a)return as(`Invalid manifest for service ${r.info.name}: ${a}`),!1;ds(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(is).filter((e=>e.devMode));for(const a of r)if(a.info.name===e&&a.status===n&&a.info.version===t)return a;return null},getInternalServices:()=>ps().filter((e=>e.internal)),getAllServices:()=>Object.values(is),stopService:gs,uninstallService:async(e,t)=>{as(`Uninstalling service ${e} v${t}`);const n=gs(e,t);if(!n)return!1;as(`Service ${e} stopped. Removing from disk...`);const r=ms(n),a=Xo;return r.startsWith(a)?(await I(r,{recursive:!0,force:!0}),as(`Service ${e} successfully removed from disk`),(e=>{const t=is[e];delete is[e]})(n.info.sessionId),!0):(as(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(is).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{os={...e}},loadAndLaunch:async(e,t,n)=>{const r=g(e,t),{error:a,service:i}=await us(r);if(a||!i)return{error:a};try{i.info.internal=!!n,i.childProcess=ss(i.info),i.status="started"}catch(e){as(`Error launching service ${i.info.name}: ${e}`),i.status="error",i.errorMsg="string"==typeof e?e:JSON.stringify(e)}return{service:i}},getServiceRootDirectory:ms};var fs={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const ys=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0);v.config={...v.config,...fs};const hs=Ho("ipcServer");let Is,Ss,$s,ws,bs={};const Ns=Xi(),As=e=>{bs[e]&&(hs(`Client disconnected [${e}]`),delete bs[e],Ss&&Ss(e))};var xs=e=>(e?.ipcId&&(v.config.id=e.ipcId),e?.ipcAppSpace&&(v.config.appspace=e.ipcAppSpace),new Promise((e=>{v.serve((()=>{hs("IPC Server Initiated"),v.server.on("data",((e,t)=>{const n=bs[t.id];n?(hs(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Ns(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return hs(`Received command from client [${t.id}]: ${e.command}`),void($s&&$s(t.id,e.command,n));e.klMessage&&ws&&ws({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):hs(`Received data from unknown client [${t.id}]. Ignoring.`)})),v.server.on("connect",(e=>{const t=Ko();hs(`New client connected. Registered as "${t}"`),e.id=t,bs[t]={socket:e,activeMessage:null,disconnectHandler:()=>As(t)},e.on("close",bs[t].disconnectHandler),Is&&Is(t)})),v.server.on("disconnect",(e=>{As(e.id)})),v.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),v.server.start()}))),Cs=e=>{Is=e},Ps=e=>{Ss=e},Es=e=>ws=e,js=(e,t)=>{const n=bs[e];if(!n)return hs(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=ys)return hs("Message is too long to be a command. Use sendMessage instead."),!1;const r=Ni.encodeCommand(t);return n.socket.write(r),!0},Ds=(e,t)=>{const n=bs[e];return!!n&&(delete bs[e],n.socket.id=t,bs[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>As(t),n.socket.on("close",n.disconnectHandler),!0)},ks=e=>{$s=e};const Os=Ho("websocketServer"),Ts={},Ls=Xi();let Ms,Bs,Rs,Ws,Us;var Fs=e=>{Us=new C({port:e,maxPayload:104857600}),Us.on("connection",(e=>{const t=Ko();Os(`New client connected. Registered as "${t}"`),e.id=t,Ts[t]={socket:e,activeMessage:null},Ms&&Ms(t),e.on("message",(t=>{if(t instanceof Buffer){const n=Ts[e.id];Ls(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),Os(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)};if(t.command)return Os(`Received command from client [${n.socket.id}]: ${t.command}`),void(Rs&&Rs(n.socket.id,t.command,r));t.klMessage&&Ws&&Ws({send:r,transmission:{sourceServiceId:t.sourceServiceId??-1,targetServiceId:t.targetServiceId??-1,rawMessage:t.rawMessage},json:t.klMessage.json})}))}})),e.on("close",(()=>{Os(`Client disconnected: ${e.id}`),Bs&&Bs(e.id),delete Ts[e.id]})),e.on("error",(()=>{Os(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},_s=e=>{Ms=e},Gs=e=>{Bs=e},zs=e=>{Rs=e},Vs=(e,t)=>{const n=Ts[e];if(!n)return Os(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=ys)return Os("Message is too long to be a command. Use sendMessage instead."),!1;const r=Ni.encodeCommand(t);return n.socket.send(r),!0},Hs=e=>Ws=e;const Js=Ho("stopService"),qs=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=vs.getAllServiceVersions(t);Js(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await vs.stopService(e.info.name,e.info.version);const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},Ks=Ho("removeService"),Xs=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=vs.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),Ks(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await vs.uninstallService(e.info.name,e.info.version);const a=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[a]})},Ys=Ho("launchService"),Zs=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{Ys(`Loading service ${t}@${n} from ${Xo}`);const{error:a,service:i}=await vs.loadAndLaunch(Xo,r,!1);if(a||!i)return e.reply({error:`Failed to launch service ${t}@${n}: ${a||"error-not-provided"}`});if("error"===i.status)return e.reply({error:`Error launching service: "${i.errorMsg||"unknown-error"}"`});const o=Date.now(),s=3e4,c=async()=>{const r=i.status;return"running"===r?(Ys(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(Ys(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${i.errorMsg||"failed to initiate"}"`}):Date.now()-o>s?e.reply({error:"Timeout waiting for service to start"}):(Ys("Retrying in 1 second..."),void setTimeout(c,1e3)))};c()}catch(r){return Ys(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},Qs=Ho("getMatchingServices"),ec=async e=>{const t=e.args[0],n=[],r=[];Qs(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:a}of t){const t=vs.getMatchingService(e,a);t?n.push({name:e,version:a,installationPath:vs.getServiceRootDirectory(t)}):r.push({name:e,version:a})}Qs(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},tc=Ho("getServiceContents"),nc=({reply:e,args:t})=>{const[n]=t;tc(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=vs.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}]})}tc(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})},rc=Ho("activeClients");let ac={},ic={};const oc=(e,t)=>`${e}_${t}`,sc=e=>ac[e]||null,cc=(e,t)=>{const n=oc(e,t);return ic[n]||[]},uc=()=>{for(const e in ac){const t=ac[e];if(t.transport===ie.WS){const e=Ni.encodeCommand(ne.ServicesListChanged);t.send(e)}}},dc=(e,t,n,r,a)=>{const i=[];ac[e]={serviceSessionId:e,transport:t,isDevClient:!!a,broadcastSubscriptions:i,send:n,extraInfo:r,addSubscription:t=>{if(!i.some((e=>e.targetService.serviceName===t.serviceName&&e.targetService.version===t.version))){i.push({targetService:t});const r=oc(t.serviceName,t.version);ic[r]=ic[r]||[];return ic[r].some((t=>t.serviceId===e))||ic[r].push({sendFn:n,serviceId:e}),!0}return!1},removeSubscription:t=>{const n=i.findIndex((e=>e.targetService.serviceName===t.serviceName));if(-1!==n){i.splice(n,1);const r=oc(t.serviceName,t.version),a=ic[r]?.findIndex((t=>t.serviceId===e));if(-1!==a&&(ic[r].splice(a,1),!ic[r].length)){const e=vs.getMatchingService(t.serviceName,t.version);if(e?.info.eventEmitter&&"running"===e.status){const t=sc(e.info.sessionId);t?.extraInfo.ipcSocketId&&js(t?.extraInfo.ipcSocketId,ne.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const t of i){const n=oc(t.targetService.serviceName,t.targetService.version),r=ic[n].findIndex((t=>t.serviceId===e));-1!==r&&ic[n].splice(r,1)}i.length=0}},t===ie.IPC&&(uc(),pc(e))},lc=()=>{const e=Object.values(ac);for(const t of e)if(t.transport===ie.IPC){const e=t.extraInfo.ipcSocketId,n=vs.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){cc(n.info.name,n.info.version).length||e&&js(e,ne.BroadcastEnd)}}},pc=e=>{const t=vs.getServiceBySessionId(e);if(t?.info.eventEmitter){if(cc(t.info.name,t.info.version).length){const t=sc(e);t?.extraInfo.ipcSocketId&&js(t?.extraInfo.ipcSocketId,ne.BroadcastStart)}}},gc=e=>{const t=ac[e];delete ac[e],t.transport===ie.IPC?uc():(t.removeAllSubscriptions(),lc())},mc=Ho("ipc:handleIpcClientCommand"),vc=(e,t,n)=>{!Vo(t,((t,r)=>{if(!t)return void mc(`Ignoring ACK response from IPC service ${e} with no service id`);mc(`Received ACK from IPC service ${t}. Marking as running.`);const a=vs.setServiceStatus(r||t,"running");r&&t&&e!==r&&Ds(e,r),a?dc(r||t,ie.IPC,n,{ipcSocketId:r}):js(e,ne.SendManifest)}))&&mc(`Received unknown command [${t}] from service ${e}`)},fc=Ho("nativeApi"),yc=e=>new Promise(((t,n)=>{j(e,((e,r,a)=>{const i=a.includes("User cancelled")||a.includes("User canceled");if(a&&!i)return n(a);t(r)}))})),hc={chooseDirectoryDialog:async e=>{const t=`\n var app = Application.currentApplication(); \n app.includeStandardAdditions = true; \n var chosenFolder = app.chooseFolder({ \n withPrompt: "${e.args[0].title||"Please select a directory"}" \n }); \n\n chosenFolder.toString();\n `;fc("Showing chooseDirectoryDialog");const n=await yc(`osascript -l JavaScript -e '${t.trim()}'`);return fc(`Chosen directory: ${n}`),e.reply({success:[String(n).trim()]})},chooseFileDialog:async e=>{const t=e.args[0],n=`\n var app = Application.currentApplication(); \n app.includeStandardAdditions = true; \n var chosenFile = app.chooseFile({ \n withPrompt: "${t.title||"Please select a file"}",\n multipleSelectionsAllowed: ${t.allowMultiple?"true":"false"},\n }); \n\n chosenFile.toString();\n `;fc("Showing chooseFileDialog");const r=await yc(`osascript -l JavaScript -e '${n.trim()}'`);return fc(`Chosen file: ${r}`),e.reply({success:[String(r).trim()]})}},Ic={chooseDirectoryDialog:async e=>{e.reply({error:"Not Supported"})},chooseFileDialog:async e=>{e.reply({error:"Not Supported"})}};let Sc;Sc="win32"===E.platform()?Ic:hc;var $c=Sc;const wc=Ho("getUniqueId"),bc=({reply:e,sourceServiceId:t})=>{wc(`Generating unique id for service "${t}"`);return e({success:[D()]})},Nc=m(P(import.meta.url)),Ac=Ho("hub"),xc=new Ti("hub");xc.setLogger(Ac);const Cc=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=sc(n.targetServiceId);if(!r)return Ac(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,ie.IPC;const a=t.json?.messageId;return Ac(`Forwarding message from ${n.sourceServiceId} to ${n.targetServiceId}, msgId: ${a}`),r.send(n.rawMessage,{sourceServiceId:n.sourceServiceId,targetServiceId:n.targetServiceId,msg:{json:t.json}}),!0}return!1},Pc=({sourceServiceId:e,args:t})=>{const n=vs.getServiceBySessionId(e);if(n){const r=cc(n.info.name,n.info.version),a=cc(n.info.name,"*");if(!r.length&&!a.length)return;const i=[...r,...a],o=t[0],s={outputs:o.outputs,variantId:o.variantId,source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};xc.broadcast(re.BroadcastEvent,[s],i,0)}},Ec=e=>{const{send:t,transmission:n,json:r}=e;Ac(`Raw message Id received from WS: ${r?.messageId}`);Cc(ie.WS,e)||xc.processMessage(ie.WS,t,n,r)},jc=e=>{const t=(n=e,`${ne.SocketAcknowledge}${n}`);var n;Vs(e,t)},Dc=(e,t,n)=>{!Vo(t,(t=>{if(Ac(`Received ACK from WS service ${t}. Marking as running.`),e!==t)throw new Error(`Received ACK from service ${t} but expected ${e}`);dc(t,ie.WS,n,{websocketId:e})}))&&Ac(`Received unknown command [${t}] from service ${e}`)},kc=e=>{Ac(`WS Client ${e} disconnected`),gc(e)},Oc=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==ie.IPC){var a;Ac(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=vs.getMatchingDevService(n.name,n.version,"stopped");if(t){Ac(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const i=sc(t.info.sessionId);if(!i)return void Ac(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);i.send=r,ac[a=e]?delete ac[a]:rc(`Could not find source client with session id ${a}`),Ds(e,t.info.sessionId);const o=await ns(n,n.path);t.info={...t.info,...o},Ac(`Updating manifest for dev service ${t.info.sessionId}`),vs.setServiceManifest(t.info.sessionId,o,"running"),Ac(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),js(t.info.sessionId,(e=>`${ne.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=ac[e];t?t.isDevClient?(t.disconnected=!1,t.transport===ie.IPC&&(uc(),pc(e))):rc(`Client with session id ${e} is not a dev client`):rc(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{vs.addDevService(e,n,"running");const t=sc(e);t?t.isDevClient=!0:dc(e,ie.IPC,r,{ipcSocketId:e},!0)}return}Ac(`Received manifest from non dev service ${e}. Ignoring...`)}};var Tc=async e=>{Ac("Starting Kemu Hub...");const t=e?.ipc?.appSpace||"kemu.",n=e?.ipc?.id||"widgets";xc.registerFunction(re.GetServiceContents,nc),xc.registerFunction(re.GetServices,(({transport:e,sourceServiceId:t,reply:n})=>{if(Ac(`Received GetServices request from ${e} [${t}]`),e===ie.WS){n({success:vs.getActiveServices().map((e=>{const{widgetUIContents:t,...n}=e;return{...n}}))})}})),xc.registerFunction(re.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ie.WS){const[e]=n,a=sc(r);if(!a)return t({error:`Session id "${r}" not found`});Ac(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),a?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),xc.registerFunction(re.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ie.WS){const[e]=n,a=sc(r),i=e.targetService;if(!a)return t({error:`Session id "${r}" not found`});if(Ac(`Service ${r} subscribing to "${i.serviceName} (${i.version})"`),"hub"===i.serviceName)return a.addSubscription(i),void t({success:[]});if(!a.addSubscription(i))return Ac(`Service ${r} already subscribed to "${i.serviceName} (${i.version})", ignoring request.`),t({success:[]});const o=vs.getMatchingService(i.serviceName,i.version);if(!o)return Ac(`Service ${i.serviceName} ${i.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return Ac(`Service ${i.serviceName} ${i.version} does not have an event emitter, removing subscription`),a.removeSubscription(i),t({error:`Service "${i.serviceName} (${i.version})" does not produce events`});const s=sc(o.info.sessionId);return s?.extraInfo.ipcSocketId&&(Ac(`Sending Broadcast START command to service ${o.info.sessionId}`),js(s?.extraInfo.ipcSocketId,ne.BroadcastStart)),t({success:[]})}})),xc.registerFunction(re.BroadcastEvent,Pc),xc.registerFunction(re.ServiceManifest,Oc),xc.registerFunction("stopService",qs),xc.registerFunction("removeService",Xs),xc.registerFunction("launchService",Zs),xc.registerFunction("getMatchingServices",ec),xc.registerFunction(re.ChooseDirectoryDialog,$c.chooseDirectoryDialog),xc.registerFunction(re.ChooseFileDialog,$c.chooseFileDialog),xc.registerFunction(re.GetUniqueId,bc),Es((e=>{const{send:t,transmission:n,json:r}=e;Ac(`Raw message Id received from IPC: ${r?.messageId}`);Cc(ie.IPC,e)||xc.processMessage(ie.IPC,t,n,r)})),Hs(Ec),_s(jc),zs(Dc),Gs(kc),ks(vc),Cs((e=>{const t=(n=e,`${ne.IpcAcknowledge}${n}`);var n;js(e,t)})),Ps((e=>{Ac(`IPC socket [${e}] disconnected`);const t=sc(e);if(t){Ac(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=vs.getServiceBySessionId(t.serviceSessionId);vs.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,uc()):gc(t.serviceSessionId)}})),await xs({ipcAppSpace:t,ipcId:n}),e?.ws?.disabled||await Fs(e?.ws?.port||8080);const r=l.resolve(Nc,"defaultServices"),a=process.env.DEV_SESSION_ID;vs.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:t,id:n}),e?.noDefaultServices||await vs.loadServices(r,{fixedSession:a?parseInt(a):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0}),await rs(Xo)||await S(Xo,{recursive:!0}),null!==e?.servicesInstallPath&&await vs.loadServices(e?.servicesInstallPath||Xo,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME});const i=process.env.DEV_NO_SPAWN_LIST?.split(",");await vs.launchServices({noSpawningList:i||[]}),Ac("Kemu Hub started")},Lc=e=>{if(e===ie.WS)return{handleWebsocketConnectionEvent:jc,handleWebsocketClientDisconnectionEvent:kc,handleWebsocketMessage:Ec,handleWebsocketClientCommand:Dc,getRemoteInvoke:()=>xc}},Mc=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(vs.getAllServices().every((e=>"running"===e.status))){if(e.every((e=>"running"===vs.getMatchingService(e.name,e.version)?.status)))return n()}t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let Bc;const Rc=Yi("run"),Wc=Fo(),Uc=1e3,Fc=$(process.argv.slice(2));global.ImageData=L,At({createCanvas:(e,t)=>B(e,t)});const _c={createImageDataLike:(e,t,n,r="srgb")=>{let a;return a=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:a,width:t,height:n,colorSpace:r,_kemuType:Q.ImageData}},loadImageFile:async e=>{const t=await M(e),n=B(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}};var Gc={start:async n=>{const r=n?.recipePath||Fc.recipePath||process.env.KEMU_EDGE_RECIPE_PATH;if(!r)throw new Error("`recipePath` not provided. Please specify it in the config object, via a command line argument [--recipePath] or as an environment variable [KEMU_EDGE_RECIPE_PATH].");const a=r.endsWith(".json"),i=a?k(r):r,o=a?r:O(i,"recipe.json"),s=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await e(T(o),"utf-8"));if(!s)throw new Error("Failed to parse recipe file");await Ea();const c={id:s.id||String(Date.now()),version:1,author:""};(e=>{or=e})(console);const u=Lc(ie.WS),d=(e,t)=>{if(t)u?.handleWebsocketMessage({send:p,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;u?.handleWebsocketClientCommand(Uc,t,p)}},l=(Li={instanceServiceId:Uc,sendBuf:d,sendCmd:d,triggerOnCommand:(...e)=>Mi(...e),triggerOnConnected:()=>Bi(),triggerOnDisconnected:()=>Ri(),triggerOnMessageReceived:(...e)=>Wi(...e)},Li);const p=(e,t)=>{if(t)l.triggerOnMessageReceived({send:d,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;l.triggerOnCommand(t)}},g=Go(),m=u.getRemoteInvoke();g.disableServiceEncoding(0,!0),m.disableServiceEncoding(Uc,!0);const v=Object.values(s.blocks[Y].gates).filter((e=>e.type===Ce.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),f=v.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),y=O(i,"services"),h=await t(y).then((()=>!0)).catch((()=>!1));await Tc({recipeRootPath:i,servicesInstallPath:h?O(i,"services"):null,noDefaultServices:!0,ws:{disabled:!0},ipc:{appSpace:"kemu-runner.",id:c.id}}),Rc("Waiting for services to run"),await Mc(f),Rc("All services are running"),oi(Wc);const I=await ri(s,"runner",c.version,c.author,$n.Desktop);return Bc=I,_o(I),await Wo(),new Promise(((e,t)=>{var n;Uo("acknowledged",(async()=>{await Wc.getServices();const{failed:n,sendToInputWidget:r}=await ii(I);if(n.length>0){const e=`Some widgets failed to initialize: ${n.join(", ")}`;return t(e)}Rc("Recipe started"),e({sendToInputWidget:r})})),l.triggerOnConnected(),l.triggerOnCommand((n=Uc,`${ne.SocketAcknowledge}${n}`))}))},terminate:async()=>{Bc&&await ai(Bc)}};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{Q as DataType,Gc as default,_c as utils};
1
+ import"dotenv/config";import{readFile as e,access as t}from"node:fs/promises";import{nanoid as n}from"nanoid";import r from"jsonp";import s from"crypto-js";import i from"util";import o from"emittery";import"axios";import a from"jszip";import{satisfies as c}from"compare-versions";import l from"debug";import u,{join as d,dirname as p,resolve as h}from"path";import"node-ipc";import{mkdir as f,readFile as g,access as m,constants as v,readdir as y,rm as b}from"fs/promises";import S from"minimist";import w from"tty";import I,{homedir as _}from"os";import $,{createHash as C}from"crypto";import k from"net";import E from"tls";import x,{promises as A}from"fs";import N from"dgram";import O from"stream";import L from"zlib";import P from"buffer";import T from"events";import B from"https";import j from"http";import D,{fileURLToPath as M}from"url";import U from"node:os";import{spawn as F}from"child_process";import{dirname as R,join as W,resolve as G}from"node:path";import{ImageData as V,loadImage as H,createCanvas as z}from"@napi-rs/canvas";var q;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(q=q||(q={}));const K={};let J=0,Y="";const X=e=>K[e]?K[e]:null,Z=(e,t)=>{const n=X(e);if(!n)return n;return n.blocks[t]||null},Q=(e,t,n)=>{const r=Z(e,t);if(!r)return r;return r.gates[n]},ee=(e,t)=>{let r=n(4);for(;K[r];)r=n(4);const s=(i=e,JSON.parse(JSON.stringify(i)));var i;return s.logs="",s.addLog=e=>{s.logs+=`${(()=>{const e=Date.now();if(e!==J){const t=new Date;J=e,Y=t.toJSON()}return Y})()}:: ${e}\n`},s.dbInfo={...t},K[r]=s,r},te="interrupt_port",ne="main.js",re="state.json",se="{#}",ie="$var_",oe="default";var ae,ce,le,ue,de,pe,he,fe;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(ae||(ae={})),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"}(ce||(ce={})),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"}(le||(le={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ue||(ue={})),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:"}(de||(de={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId"}(pe||(pe={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(he||(he={})),function(e){e.IPC="ipc",e.WS="ws"}(fe||(fe={}));const ge="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,me="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,ve="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,ye="-",be=`inner${ye}`,Se=`outer${ye}`,we=`${Se}input${ye}`,Ie=`${Se}output${ye}`,_e=`${be}input${ye}`,$e=`${be}output${ye}`,Ce=e=>(new TextEncoder).encode(e),ke=e=>e===te,Ee=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,xe=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,Ae=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Ne=e=>"number"==typeof e?ce.Number:"string"==typeof e?ce.String:"boolean"==typeof e?ce.Boolean:Array.isArray(e)?ce.Array:Ee(e)?ce.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?ce.AudioBuffer:e&&void 0!==e.byteLength?ce.ArrayBuffer:xe(e)?ce.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?ce.Point:ce.JsonObj,Oe=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Ne(n[e]);t[e]=r}return t},Le=(e,t,n)=>"inner"===e?"input"===t?`${_e}${n}`:`${$e}${n}`:"input"===t?`${we}${n}`:`${Ie}${n}`,Pe=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]}},Te=e=>new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace});var Be,je;!function(e){e.Action="action",e.CustomInput="customInput"}(Be=Be||(Be={})),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"}(je=je||(je={}));const De={};let Me;const Ue=async e=>{const t=De[e],n={name:te,type:ce.Boolean};if(t){const r={name:t.portName},s=t.data||{type:ce.Boolean,value:!0};Me?(await Me(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...s,timestamp:Date.now()},[n]),"timeout"===t.type&&Fe(e)):console.warn("Interrupt service has not been initialized")}},Fe=e=>{const t=De[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete De[e],!0)};var Re={interruptHandler:Ue,createInterrupt:(e,t,r,s,i,o,a,c)=>{if(c&&De[c])throw new Error("The given interrupt id already exists");const l=c||n().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(De[l]={data:a,portName:i,recipePoolId:t,targetWidgetId:s,thingId:r,type:e},"interval"===e)De[l].timerRef=setInterval((async()=>await Ue(l)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);De[l].timerRef=setTimeout((async()=>await Ue(l)),o.timeout)}return l},destroyInterrupt:Fe,destroyAllInterrupts:()=>{Object.keys(De).forEach(Fe)},setInvokeChildGateCb:e=>{Me=e}};const We=(e,t,n,r,s)=>{const i=Q(e,n,r);if(!i)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=(t,s,i,o)=>Re.createInterrupt(t,e,n,r,s,i,o),a=()=>Object.freeze({...i.state,...i.type===je.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...i.type===je.input&&!e.customInputs&&{customInputs:[]}};i.state=t};if(s){return{getState:a,setState:c,registerInterrupt:o,getStorageData:async t=>{const r=((e,t,n)=>{const r=X(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const s=Z(e,t);if(!s)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(s.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}},Ge=[10001,"Invalid `sourcePort` parameter"],Ve=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],He=[10110,"No storage medium has been loaded, call `loadMedium()` first"],ze=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?i.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),qe=()=>({inputName:"",dataType:ce.Anything}),Ke="output",Je={processEvent:async(e,t)=>{const n=t.getState(),r={...qe(),...n};if(e.type===r.dataType||r.dataType===ce.Anything)return t.nextWidget(Ke,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...qe(),...e};return[{name:Ke,type:t.dataType}]},getInputNames:()=>[]},Ye=Object.freeze({in:"in",reset:"reset",increment:"increment"}),Xe="output";var Ze={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(ze(Ge));const s={currentValue:0,increment:1,...r.getState()};let i=s.increment,o=s.currentValue;const a=await r.getParentAtPort(Ye.increment);if(t.name===Ye.increment)return void(n.data.type===ce.Number&&r.setState({...s,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(i=e)}if(t.name===Ye.reset)return r.setState({...s,currentValue:0});o+=i,r.setState({currentValue:o,increment:i});const c={type:ce.Number,value:o};return r.nextGate(Xe,c)},getInputNames:()=>[{name:Ye.in,type:ce.Anything},{name:Ye.reset,type:ce.Anything},{name:Ye.increment,type:ce.Number}],getOutputNames:()=>[{name:Xe,type:ce.Number}]};const Qe=Object.freeze({in:"in",reset:"reset"}),et="output";var tt={onParentEvent:async(e,t,n,r)=>{const s={updatedAt:0,elapsed:0,...r.getState()},i=Date.now(),o=i-(s.updatedAt||i);return t.name===Qe.reset?r.setState({...s,updatedAt:i,elapsed:0}):(r.setState({updatedAt:i,elapsed:o}),r.nextGate(et,{type:ce.Number,value:o}))},getInputNames:()=>[{name:Qe.in,type:ce.Anything},{name:Qe.reset,type:ce.Anything}],getOutputNames:()=>[{name:et,type:ce.Number}]};const nt=Object.freeze({data:"data",evaluation:"evaluation"}),rt="then",st="else";var it={onParentEvent:async(e,t,n,r)=>{const s={value:5,condition:"Equal",useDataPort:!1,...r.getState()},i=n.data.value,o=!isNaN(Number(i)),a="string"==typeof i;if(!s.useDataPort&&(n.data.type===ce.Number||n.data.type===ce.String||n.data.type===ce.Anything&&o||n.data.type===ce.Anything&&a)){let e=!1;return("Equal"===s.condition&&n.data.value==s.value||"Not Equal"===s.condition&&n.data.value!==s.value||"Greater"===s.condition&&n.data.value>Number(s.value)||"Less"===s.condition&&n.data.value<Number(s.value)||"Starts With"===s.condition&&String(n.data.value).startsWith(String(s.value))||"Ends With"===s.condition&&String(n.data.value).endsWith(String(s.value))||"Includes"===s.condition&&String(n.data.value).includes(String(s.value))||"Matches"===s.condition&&String(n.data.value).match(String(s.value)))&&(e=!0),e?r.nextGate(rt,n.data):r.nextGate(st,n.data)}if((t.name===nt.evaluation&&n.data.type===ce.Number||n.data.type===ce.String||n.data.type===ce.Anything&&(o||a))&&(s.$lastValue=n.data.value,r.setState({...s})),t.name===nt.data){let e=!1;return("Equal"===s.condition&&s.$lastValue==s.value||"Not Equal"===s.condition&&s.$lastValue!==s.value||"Greater"===s.condition&&Number(s.$lastValue)>Number(s.value)||"Less"===s.condition&&Number(s.$lastValue)<Number(s.value)||"Starts With"===s.condition&&String(s.$lastValue).startsWith(String(s.value))||"Ends With"===s.condition&&String(s.$lastValue).endsWith(String(s.value))||"Includes"===s.condition&&String(s.$lastValue).includes(String(s.value))||"Matches"===s.condition&&String(s.$lastValue).match(String(s.value)))&&(e=!0),r.setState({...s,$lastValue:void 0,$lastDataType:n.data.type}),e?r.nextGate(rt,n.data):r.nextGate(st,n.data)}},getInputNames:e=>e.useDataPort?[{name:nt.data,type:ce.Anything},{name:nt.evaluation,type:[ce.Number,ce.String]}]:[{name:"in",type:[ce.Number,ce.String]}],getOutputNames:e=>e.$lastDataType?[{name:rt,type:e.$lastDataType},{name:st,type:e.$lastDataType}]:[{name:rt,type:[ce.Number,ce.String]},{name:st,type:[ce.Number,ce.String]}]};const ot=Object.freeze({in:"in",reset:"reset"}),at="out";var ct={onParentEvent:async(e,t,n,r)=>{const s={totalCalls:0,callsLimit:1,...r.getState()};return t.name===ot.reset?r.setState({...s,totalCalls:0}):(s.totalCalls=s.totalCalls+1,s.totalCalls>s.callsLimit?(s.totalCalls=0,r.setState(s),r.nextGate(at,n.data)):void r.setState(s))},getInputNames:()=>[{name:ot.in,type:ce.Anything},{name:ot.reset,type:ce.Anything}],getOutputNames:()=>[{name:at,type:ce.Anything}]};const lt=Object.freeze({in:"in"}),ut="then",dt="else";var pt={onParentEvent:async(e,t,n,r)=>{const s={min:1,max:10,...r.getState()};if(n.data.type===ce.Number)return n.data.value>=s.min&&n.data.value<=s.max?r.nextGate(ut,n.data):r.nextGate(dt,n.data)},getInputNames:()=>[{name:lt.in,type:ce.Number}],getOutputNames:()=>[{name:ut,type:ce.Number},{name:dt,type:ce.Number}]};const ht=Object.freeze({in:"in"}),ft="out";var gt={onParentEvent:async(e,t,n,r)=>{const s={clamp:!0,...r.getState()},i=Number(n.data.value);if(void 0!==s.fromMax&&void 0!==s.fromMin&&void 0!==s.toMax&&void 0!==s.toMin&&""!==s.fromMax&&""!==s.fromMin&&""!==s.toMax&&""!==s.toMin&&(n.data.type===ce.Number||n.data.type===ce.Anything&&!isNaN(Number(i)))){let e=((e,t,n,r,s)=>(e-t)*(s-r)/(n-t)+r)(i,Number(s.fromMin),Number(s.fromMax),Number(s.toMin),Number(s.toMax));if(isNaN(e))return;return s.clamp&&(e<Number(s.toMin)&&(e=Number(s.toMin)),e>Number(s.toMax)&&(e=Number(s.toMax))),r.nextGate(ft,{type:ce.Number,value:Number(e)})}},getInputNames:()=>[{name:ht.in,type:ce.Number}],getOutputNames:()=>[{name:ft,type:ce.Number}]};const mt=Object.freeze({in:"in"}),vt="out";var yt={onParentEvent:async(e,t,n,r)=>{const s={convertTo:"Integer",floatPlaces:2,...r.getState()};let i=n.data.value;if(n.data.type===ce.Number||n.data.type===ce.Anything||n.data.type===ce.String){if((!isNaN(Number(i))||"string"==typeof i)&&!Array.isArray(i))return"Integer"===s.convertTo?i=parseInt(i):"Decimal"===s.convertTo?i=parseFloat(Number(i).toFixed(s.floatPlaces)):"String"===s.convertTo?i=String(i):"Abs"===s.convertTo?i=Math.abs(Number(i)):"Round"===s.convertTo&&(i=Math.round(Number(i))),r.nextGate(vt,{type:"String"===s.convertTo?ce.String:ce.Number,value:i})}},getInputNames:()=>[{name:mt.in,type:ce.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?ce.String:ce.Number;return[{name:vt,type:t}]}};const bt=Object.freeze({in:"in"}),St="out";var wt={onParentEvent:async(e,t,n,r)=>{const s={currentValue:50,min:0,max:100,...r.getState()};let i=!1;return s.currentValue<s.min&&(s.currentValue=s.min,i=!0),s.currentValue>s.max&&(s.currentValue=s.max,i=!0),i&&r.setState(s),r.nextGate(St,{type:ce.Number,value:s.currentValue})},getInputNames:()=>[{name:bt.in,type:ce.Anything}],getOutputNames:()=>[{name:St,type:ce.Number}]};const It=Object.freeze({in:"in",reset:"reset"}),_t="out";var $t={onParentEvent:async(e,t,n,r)=>{const s={lastCalledAt:0,delayMs:500},i={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===It.reset)return r.setState({...i,lastCalledAt:0});const o=Date.now(),a=o-i.lastCalledAt;return i.lastCalledAt===s.lastCalledAt||a>=i.delayMs&&i.delayMs>0?(i.lastCalledAt=o,r.setState(i),r.nextGate(_t,n.data)):void 0},getInputNames:()=>[{name:It.in,type:ce.Anything},{name:It.reset,type:ce.Anything}],getOutputNames:()=>[{name:_t,type:ce.Anything}]};const Ct="in";var kt={onParentEvent:async()=>{},getInputNames:()=>[{name:Ct,type:[ce.ImageData,ce.Number]}],getOutputNames:()=>[]};const Et=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),xt=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var At={onParentEvent:async(e,t,n,r)=>{const s={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},i=n?.data?.value,o=Array.isArray(i);if(n.data.type===ce.JsonObj||n.data.type===ce.Rect||n.data.type===ce.Anything||o){let e=!1;for(const t in i){const n=Ne(i[t]),r=!!s.detectedProperties[t],o=s.detectedProperties[t]?.type!==n;if(!r||o){const r=n===ce.JsonObj||n===ce.Rect||n===ce.Array;s.detectedProperties[t]={type:n,...r?{shape:Oe(i[t])}:void 0},e=!0}}if(o&&void 0===s.detectedProperties.length&&(s.detectedProperties.length={type:ce.Number}),e&&r.setState(s),i){const e=[];for(const t of s.properties||[]){const n=xt(i,t.label),o=t.label.includes(".");if(void 0!==n){const i=o?Ne(n):void 0!==s.detectedProperties[t.label]?.type?s.detectedProperties[t.label].type:ce.Anything;e.push(r.nextGate(t.name,{type:i,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:ce.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:ce.Anything,r=t.detectedProperties[e.label]?.shape||void 0,s="string"==typeof e;return{name:s?e:e.name,label:s?e:e.label,type:n,jsonShape:r}}))},getDefaultState:Et};const Nt="output",Ot="noItem";var Lt={onParentEvent:async(e,t,n,r)=>{const s={index:0,...r.getState()};let i=s.index;const o=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===ce.Anything&&(c||a)||n.data.type===ce.String&&a||n.data.type===ce.Array&&c){i<0&&(i=o.length+i);const e=a?ce.String:Ne(o[i]);return e!==s.$$lastDetectedType&&r.setState({...s,$$lastDetectedType:e}),void 0!==o[i]?r.nextGate(Nt,{value:o[i],type:e}):r.nextGate(Ot,{value:!0,type:ce.Boolean})}},getInputNames:()=>[{name:"in",type:[ce.Array,ce.String]}],getOutputNames:e=>[{name:Nt,type:e.$$lastDetectedType??ce.Anything},{name:Ot,type:ce.Boolean}]};let Pt;const Tt=e=>{Pt=e},Bt=(e,t)=>(()=>{if(!Pt)throw new Error("CanvasManager not set");return Pt})().createCanvas(e,t),jt=e=>ge?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Dt=Object.freeze({image:"image",rect:"rect"}),Mt="image";var Ut={onParentEvent:async(e,t,n,r)=>{const s={offset:{height:0,left:0,top:0,width:0},...r.getState()},i=await r.getParentAtPort(Dt.rect),o=[ce.Anything,ce.Rect,ce.JsonObj];if(t.name!==Dt.rect){if(i){const e=i.getValue();null!==e&&(s.rect={...e},r.setState(s))}if(!ge)return n.data.type===ce.ImageData?r.nextGate(Mt,n.data):void 0;if(s.$$canvasFrom&&s.$$canvasFrom.getContext||(s.$$canvasFrom=Bt(320,240)),s.$$canvasTo&&s.$$canvasTo.getContext||(s.$$canvasTo=Bt(320,240)),(n.data.type===ce.ImageData||n.data.type===ce.Anything&&Ee(n.data.value))&&!s.$$processing&&s.$$canvasFrom&&s.rect){const e=((e,t,n,r,s)=>{if(r&&r.getContext){const i=r.getContext("2d"),o=n.getContext("2d");if(i&&o){n.width=e.width,n.height=e.height,o.putImageData(e,0,0);const a={...s};s&&(a.height=Number(s.height),a.width=Number(s.width),a.left=Number(s.left),a.top=Number(s.top));const c={top:0,width:0,left:0,height:0,...a};return s&&(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,i.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),i.getImageData(0,0,r.width||1,r.height||1)}}return e})(n.data.value,s.rect,s.$$canvasFrom,s.$$canvasTo,s.offset);return r.nextGate(Mt,{type:ce.ImageData,value:e})}}else xe(n.data.value)&&o.includes(n.data.type)&&r.setState({...s,rect:n.data.value})},getInputNames:()=>[{name:Dt.image,type:ce.ImageData},{name:Dt.rect,type:[ce.Rect,ce.JsonObj]}],getOutputNames:()=>[{name:Mt,type:ce.ImageData}]};const Ft=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),s=e.data,i=e.width,o=e.height,a=i,c=o,l=((e,t,n)=>{if(ge)return new ImageData(t,n);return console.warn("Node environment detected. Aborting new ImageData creation"),e})(e,a,c),u=l.data;for(let e=0;e<c;e++)for(let c=0;c<a;c++){const l=e,d=c,p=4*(e*a+c);let h=0,f=0,g=0,m=0;for(let e=0;e<n;e++)for(let a=0;a<n;a++){const c=l+e-r,u=d+a-r;if(c>=0&&c<o&&u>=0&&u<i){const r=4*(c*i+u),o=t[e*n+a];h+=s[r]*o,f+=s[r+1]*o,g+=s[r+2]*o,m+=s[r+3]*o}}u[p]=h,u[p+1]=f,u[p+2]=g,u[p+3]=m+1*(255-m)}return l},Rt=[-1,0,1,-2,0,2,1,0,1],Wt=Object.freeze({image:"image"}),Gt="image";var Vt={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={matrix:[...Rt],...s};if(n.data.type===ce.ImageData||n.data.type===ce.Anything&&Ee(n.data.value)){const e=Ft(n.data.value,i.matrix);return r.nextGate(Gt,{type:ce.ImageData,value:e})}},getInputNames:()=>[{name:Wt.image,type:ce.ImageData}],getOutputNames:()=>[{name:Gt,type:ce.ImageData}]};const Ht=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:ce.Anything})));return n.push({name:"reset",type:ce.Anything}),n};var Kt={onParentEvent:async(e,t,n,r)=>{const s={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...s,triggeredAt:0});const i=Date.now(),o=i-s.triggeredAt;if(s.triggeredAt&&!(o>=s.delayMs&&s.delayMs>0)&&s.delayMs)return r.nextGate(Ht.aborted,n.data);{s.triggeredAt=i;const e=qt(s,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id)).findIndex((e=>e.name===t.name));-1!==e&&(s.lastInputIndex=e),s.matchingOutputs?-1!==e&&await r.nextGate(`output${e+1}`,n.data):await r.nextGate(Ht.output,n.data),r.setState(s)}},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:ce.Anything})));return e.push({name:Ht.aborted,type:ce.Anything}),e}return[{name:Ht.output,type:ce.Anything},{name:Ht.aborted,type:ce.Anything}]},getDefaultState:zt};const Jt=(e,t,n,r,s,i)=>{if(s){const o=e.measureText(s),a=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-i,1.1*o.width,a),e.font=`${i}px Arial`,e.fillStyle="black",e.fillText(s,t,n)}},Yt=(e,t,n,r,s,i,o)=>{e.fillStyle=s,e.fillRect(t,n,r,r),Jt(e,t,n,s,i,o)},Xt=(e,t,n,r,s,i)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const o=n/2;Jt(e,t.left-o,t.top-o,r,s,i)},Zt=Object.freeze({image:"image",pixels:"pixels"}),Qt="image";var en={onParentEvent:async(e,t,n,r)=>{const s={fontSize:12,color:"#00ff00",size:2,...r.getState()},i=n.data.type===ce.ImageData||n.data.type===ce.Anything&&Ee(n.data.value);if(t.name===Zt.pixels){const e=((e,t)=>t===ce.Anything&&(Ee(e)||Ae(e)||xe(e)||Array.isArray(e))||t===ce.Array||t===ce.Rect||t===ce.Point)(n.data.value,n.data.type);if(!e)return;s.$$pixels=n.data.value}if(t.name===Zt.image&&i){const e=n.data.value;s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=Bt(e.width||1,e.height||1)),s.$$lastFrame=e}if(s.$$lastFrame&&s.$$pixels&&s.$$memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:s,color:i,labelProp:o,fontSize:a}=e;if(r){const e=jt(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]:"";xe(n)?Xt(e,n,s,i,r,a):Ae(n)&&Yt(e,n.x,n.y,s,i,r,a)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:s.$$lastFrame,pixels:s.$$pixels||[],memCanvas:s.$$memCanvas,size:s.size,color:s.color,labelProp:s.labelProp,fontSize:s.fontSize});return r.setState({...s,$$lastFrame:void 0,$$pixels:void 0}),r.nextWidget(Qt,{type:ce.ImageData,value:e})}r.setState(s)},getInputNames:()=>[{name:Zt.image,type:ce.ImageData},{name:Zt.pixels,type:[ce.Rect,ce.Point,ce.Array]}],getOutputNames:()=>[{name:Qt,type:ce.ImageData}]};const tn=Object.freeze({in:"in"}),nn="output",rn=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var sn={onParentEvent:async(e,t,n,r)=>{const s={min:1,max:100,...r.getState()},i=!Number.isInteger(s.min),o=!Number.isInteger(s.max),a=i||o;let c=(l=s.min,u=s.max,Math.random()*(u-l)+l);var l,u;if(a){let e=0;if(i&&(e=rn(s.min)),o){const t=rn(s.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(nn,{type:ce.Number,value:c})},getInputNames:()=>[{name:tn.in,type:ce.Anything}],getOutputNames:()=>[{name:nn,type:ce.Number}]};const on=Object.freeze({output:"output",totalItems:"totalItems"}),an=Object.freeze({trigger:"trigger",clear:"clear"}),cn=()=>({totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),ln=async(e,t)=>t.nextGate(on.totalItems,{type:ce.Number,value:e});var un={onParentEvent:async(e,t,n,r)=>{const s={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===an.clear)return s.$$list=[],s.properties?.autoFilled&&delete s.properties,r.setState(s),ln(s.$$list.length,r);const i=t.name===an.trigger;if(!i)if(Array.isArray(n.data.value))n.data.type!==ce.Array&&n.data.type!==ce.Anything||(s.$$outputShape={...s.$$outputShape,...e?.jsonShape},s.$$list=s.$$list.concat(n.data.value),r.setState({...s}),await ln(s.$$list.length,r));else{const t=`$$primitive_${Object.keys(s.$$outputShape).length}`;n.data.type===ce.JsonObj?s.$$outputShape={...s.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:s.$$outputShape={...s.$$outputShape,[t]:n.data.type},s.$$list.push(n.data.value),r.setState({...s}),await ln(s.$$list.length,r)}if(i){Object.keys(s.$$outputShape).length&&(s.properties={autoFilled:!0,jsonShape:{...s.$$outputShape}});const e=s.$$list.length,t=[...s.$$list];return s.$$list=[],r.setState({...s}),await ln(e,r),r.nextGate(on.output,{type:ce.Array,value:t})}},getInputNames:e=>{const t={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`array${t+1}`,type:ce.Array})));return n.push({name:an.clear,type:ce.Anything},{name:an.trigger,type:ce.Anything}),n},getOutputNames:e=>[{name:on.output,type:ce.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:on.totalItems,label:"Total Items",type:ce.Number}],getDefaultState:cn};const dn=Object.freeze({start:"start",stop:"stop"}),pn="output",hn="clock_interrupt";var fn={onParentEvent:async(e,t,n,r)=>{const s={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(ke(e?.name||"")&&t.name===hn)return r.nextGate(pn,{type:ce.Boolean,value:!0});if(t.name===dn.stop&&s.enabled&&s.$$interruptId){r.cancelInterrupt(s.$$interruptId)?(s.enabled=!1,s.$$interruptId=void 0,r.setState(s)):console.warn(`Failed to cancel interrupt [${s.$$interruptId}]`)}else t.name!==dn.start||s.enabled||s.$$interruptId||(s.$$interruptId=r.registerInterrupt("interval",hn,{interval:s.interval}),s.enabled=!0,r.setState(s))},getInputNames:()=>[{name:dn.start,type:ce.Anything},{name:dn.stop,type:ce.Anything}],getOutputNames:()=>[{name:pn,type:ce.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",hn,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const gn=Object.freeze({in:"in"}),mn="output",vn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var yn={onParentEvent:async(e,t,n,r)=>{const s={userProperties:[],factor:2,decimalPoints:2,...r.getState()},i=n.data.type;let o=n.data.value,a=!1;return e?.jsonShape&&(s.detectedInputJson={...s.detectedInputJson,...e?.jsonShape},a=!0),s.detectedInputType||(s.detectedInputType=i,a=!0),n.data.type===ce.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>vn(e,t,n)));return r})(n.data.value,s.factor,s.decimalPoints):"object"==typeof n.data.value?.[0]&&(o=((e,t,n,r)=>{const s=(e||[]).map((e=>{const s={...e};return Object.keys(s).forEach((e=>{r?.length&&!r?.includes(e)||(s[e]=vn(s[e],t,n))})),s}));return s})(n.data.value,s.factor,s.decimalPoints,s.userProperties))),n.data.type===ce.Number&&(o=vn(n.data.value,s.factor,s.decimalPoints)),a&&r.setState(s),r.nextGate(mn,{type:i,value:o})},getInputNames:()=>[{name:gn.in,type:[ce.Array,ce.Number]}],getOutputNames:e=>[{name:mn,type:e.detectedInputType||ce.Number,jsonShape:e.detectedInputJson}]};const bn=Object.freeze({output:"output"}),Sn=Object.freeze({trigger:"trigger"}),wn=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:ce.Number,value:10},{name:"y",label:"y",type:ce.Number,value:20}]}),In=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},_n=e=>{const t={};for(let n=0;n<e.properties.length;n++){let r=e.properties[n].value;const s=e.properties[n].type;s===ce.Number?r=Number(r):s===ce.String&&(r=String(r)),t[e.properties[n].label]=r}return t};var $n={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i=structuredClone(s),o={...wn(),...i};if(t.name===Sn.trigger){const e=_n(o);return r.nextGate(bn.output,{type:ce.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===ce.Anything){e=Ne(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=_n(o);return r.nextGate(bn.output,{type:ce.JsonObj,value:e})}}},getInputNames:e=>{const t={...wn(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:Sn.trigger,label:Sn.trigger,type:ce.Anything}),n},getOutputNames:e=>[{name:bn.output,label:bn.output,type:ce.JsonObj,jsonShape:In(e)}],getDefaultState:wn};const Cn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(we)){const n=t(e,we);return Le("inner","input",n)}if(e.startsWith($e)){const n=t(e,$e);return Le("outer","output",n)}return null},kn=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[ce.Anything],index:0}],outputs:[{name:"output",type:[ce.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),En=e=>{const t={...kn(),...e},n=t.inputs.map(((e,t)=>({name:Le("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:Le("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 xn={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={...kn(),...s},o=En(i,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const s=o[e];if(t.name===s.name&&(s.type.includes(ce.Anything)||s.type.includes(n.data.type))){const e=await Cn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:En,getOutputNames:e=>{const t={...kn(),...e},n=t.outputs.map(((e,t)=>({name:Le("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:Le("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:kn};const An=(e,t,n,r,s)=>{const i=4*(t*n.width+e),o=n.data[i],a=n.data[i+1],c=n.data[i+2];return Math.abs(o-r.r)<=s&&Math.abs(a-r.g)<=s&&Math.abs(c-r.b)<=s};var Nn,On,Ln,Pn,Tn,Bn,jn,Dn,Mn,Un,Fn={getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,s=n[t+1]||0,i=n[t+2]||0;return{avr:(r+s+i)/3,r:r,g:s,b:i}},getBoundingBox:(e,t,n)=>{const r=e.width,s=e.height,i=new Set,o=Number(n.threshold||0),a=isNaN(o)?10:o,c=(n,o)=>{const c=[[n,o]];let l=n,u=n,d=o,p=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,h]=n;o<0||h<0||o>=r||h>=s||i.has(`${o},${h}`)||!An(o,h,e,t,a||0)||(i.add(`${o},${h}`),l=Math.min(l,o),u=Math.max(u,o),d=Math.min(d,h),p=Math.max(p,h),c.push([o+1,h],[o-1,h],[o,h+1],[o,h-1]))}return{minX:l,maxX:u,minY:d,maxY:p}},l=[];for(let o=0;o<s;o+=4)for(let s=0;s<r;s+=4)if(!i.has(`${s},${o}`)&&An(s,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:i}=c(s,o),a=t-e,u=i-r;if(a>=(n.minWidth||1)&&u>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:u}),n.maxBoxes&&l.length>=n.maxBoxes)return l}return l},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,s="object"==typeof n,i=s?n.r:n,o=s?n.g:n,a=s?n.b:n;r[t]=i,r[t+1]=o,r[t+2]=a,r[t+3]=255}};!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Nn||(Nn={})),function(e){e.Bundle="bundle",e.Group="group"}(On||(On={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Ln||(Ln={})),function(e){e.Cloud="cloud",e.Web="web"}(Pn||(Pn={})),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"}(Tn||(Tn={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Bn||(Bn={})),(jn||(jn={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Dn||(Dn={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Mn||(Mn={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Un||(Un={}));let Rn=null;var Wn=()=>{if(!Rn)throw new Error("Required function is not set");return Rn};class Gn extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const Vn=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===Nn.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar console = this.console;\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\n\t\t\tvar Kemu = {\n\t\t\t\tservices: {\n\t\t\t\t\thttp: { ...this.httpWebService },\n\t\t\t\t\tdynamoDb: { ...this.dynamoService },\n\t\t\t\t\tgoogleSheets: {\n\t\t\t\t\t\t...this.googleSheetsService,\n\t\t\t\t\t}\n\t\t\t\t},\n\n\t\t\t\timage: this.imageHelpers,\n\t\t\t\tvariable: this.variablesManager,\n\n\t\t\t\thelpers: {\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\tjsonp: this.jsonp,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tvar sendToPort;\n\n\t\t\t// --- User Methods Start ---\n\t\t\t${e||""};\n\t\t\t// --- User Methods End ---\n\t\t\t\n\t\t\t// Processes the user code asynchronously.\n\t\t\tconst asyncProcessEvent = async (targetPort, sourcePort, event) => {\n\t\t\t\tconst userProcessEvent = typeof processEvent === 'undefined' ? undefined : processEvent;\n\t\t\t\tif(userProcessEvent) {\n\t\t\t\t\ttry{\n\t\t\t\t\t\treturn await userProcessEvent(targetPort, sourcePort, event, sendToPort);\n\t\t\t\t\t}catch(e){\n\t\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked the very first time the recipe is initialized */\n\t\t\tconst asyncRecipeInit = async (context, logger) => {\n\t\t\t\ttry {\n\t\t\t\t\t${t===Nn.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`,Hn=(e,t,n,i)=>{const o=Vn(e,n),a={...t,document:{},__errorTracer:e=>{throw new Gn(e.message,e.stack)},__jest:void 0===globalThis.__jest?void 0:globalThis.__jest,___notSupportedMethod:()=>i?.error("This method is not supported."),console:console,setInterval:()=>i?.error("'setInterval' is not supported. Please use a \"Timer\" widget instead."),setTimeout:t?.setTimeout,imageHelpers:Fn,...n===Nn.Cloud?{require:Wn(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:r,CryptoJS:s,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(ge)return"browser";if(ve)return"node";if(me)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}}}},zn="main",qn=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},pages:{[zn]:{code:"\nconst getWidgetInputs = () => [\n\t{ name: 'Input 1', type: DataType.Number }\n];\n\nconst getWidgetOutputs = () => [\n\t{ name: 'Output 1', type: DataType.Number }\n]\n\nlet counter = 0;\n\nconst processEvent = async (targetPort, sourceWidget, event) => {\n\tif(targetPort.name === 'Input 1'){\n\t\treturn sendToPort('Output 1', {\n\t\t\ttype: DataType.Number,\n\t\t\tvalue: counter++,\n\t\t});\n\t}\n}\n",language:"javascript",name:"My First Script"}},consoleVisible:!1,$$consoleLines:[]}),Kn=(e,t)=>{const n={message:"Unknown Error"};if(e?.stack){const r=e?.stack?.split(":")[0].trim();n.type=r;const s=(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);s&&(n.line=s.line-(e=>{const t="___user_code_section___";return Vn(t,e).split(t)[0].split("\n").length+2})(t),n.column=s.column)}return e.message&&(n.message=e.message),n},Jn=(e,t)=>{const n={...qn(),...t.getState()},r={...n,...e?{$$error:e}:void 0,...n.autoPauseOnError&&e?{pauseExecution:!0}:void 0};e&&(r.$$consoleLines=[...r.$$consoleLines,{type:"error",text:e.message,timestamp:Date.now(),fileName:zn}]),t.setState(r)};var Yn,Xn;!function(e){e.ServiceCreationLog="service-creation-log"}(Yn=Yn||(Yn={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(Xn=Xn||(Xn={}));const Zn=new o,Qn=(e,t,n)=>{const r=Z(e,t);if(!r)throw new Error(`Thing ${t} not found in recipe ${e}`);const s=r.gates[n];if(!s)throw new Error(`Widget ${n} not found in thing ${t}`);return s},er=(e,t,n)=>`${t}:${n}:${e}`,tr=e=>`${e}:new-var`,nr=async(e,t,n,r,s,i,o)=>{const a={...o},c={thingId:n,recipeId:t,variableName:e,changes:i,ownerId:r,callerWidgetId:s,varDefinition:Object.freeze(a)};if(i.includes("added")){const e=tr(n);return Zn.emit(e,c)}{const t=er(e,n,r);return Zn.emit(t,c)}},rr=(e,t,n,r)=>{const s=Qn(e,t,r);s.variablesListener={...s.variablesListener,[n]:0},ir(e,t)},sr=(e,t,n,r)=>{const s=Qn(e,t,r),i={...s.variablesListener};void 0!==s.variablesListener?.[n]&&(delete i[n],s.variablesListener=i)},ir=async(e,t)=>{const n=Z(e,t);if(!n)throw new Error(`Thing "${t}" not found in recipe "${e}"`);const r={...n.variables},s=Object.keys(r);for(const i of s){const s=r[i],o=Object.keys(s);for(const s of o){!n.gates[s]&&(delete r[i][s],await nr(i,e,t,s,void 0,["removed"],null))}0===Object.keys(r[i]).length&&delete r[i]}n.variables=r},or=(e,t,n)=>{for(const r in t){const s=t[r];if(s.createdByWidgetId===e.id)return s;if(e.type===je.variable&&s.ownerType===je.variable)return s;if(e.type===je.script){const t=s.createdByWidgetId===e.groupId,r=n[s.createdByWidgetId];if(!r)continue;const i=r.groupId===e.groupId;if(t||r.type===je.variable&&i)return s}}return null};var ar=async(e,t,n,r,s,i)=>{const o=Z(e,t);if(!o)throw new Error(`Thing ${t} not found in recipe ${e}`);const a={...o.variables};a[r]=a[r]||{};const c=a[r],l=o.gates[n];if(!l)throw new Error(`Widget ${n} not found in thing ${t}`);const u=Object.values(c);let d=!1,p=!1;const h=async s=>nr(r,e,t,s.createdByWidgetId,n,["value"],s);if(l.type===je.variable){d=!0;for(const e of u)e.ownerType===je.variable&&e.type===s.type&&(e.value=s.value,p=!0,await h(e))}if(l.type===je.script){d=!0;for(const e of u){const t=e.createdByWidgetId===l.groupId,n=o.gates[e.createdByWidgetId],r=n?.type===je.variable,i=n?.groupId===l.groupId;(t||r&&i)&&e.type===s.type&&(e.value=s.value,p=!0,await h(e))}}if(!d){d=!0;for(const e of u){e.createdByWidgetId===n&&e.type===s.type&&(e.value=s.value,p=!0,await h(e))}}if(!i?.skipNotifications&&p){const a=Object.values(o.gates);for(const o of a){if(o.id===n&&i?.skipCallerNotification)continue;const a=o.variablesListener?.[r];void 0!==a&&await Qs(o.id,t,e,`${ie}${r}`,s)}}},cr=(e,t,n,r)=>{const s=Z(e,t);if(!s)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 i={...s.variables}[n];if(!i)return;if(r.ownerWidgetId){const e=i[r.ownerWidgetId];return e?.value}const o=s.gates[r.readerWidgetId];if(!o)throw new Error(`Widget ${r.readerWidgetId} not found in thing ${t}`);const a=or(o,i,s.gates);return a?a.value:null},lr=rr,ur=sr;const dr="setTimeout",pr="variableChanged",hr=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e;if(!Q(t,n,r))throw new Error(`Widget "${r}" not found in recipe "${t}"`);return{get:(e,s)=>{const i=cr(t,n,e,{readerWidgetId:r});if(null===i){if(void 0===s)throw new Error(`Variable "${e}" is not defined`);return s}return i},set:async(e,s)=>{await ar(t,n,r,e,{type:Ne(s),value:s})},onValueChange:(s,i)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");lr(t,n,s,r);const o={...qn(),...e.getState()};o.$$eventListeners[s]={handler:i,abort:async()=>{ur(t,n,s,r)},name:pr},e.setState(o)}}},fr="__command-compile__";let gr;const mr=()=>{console.log("Method not implemented")},vr=(e,t,r)=>{const s=(e,...n)=>{const r={...qn(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},i={};return Object.keys(ce).forEach((e=>{i[e]=ce[e]})),{dataTypesEnum:i,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?hr({recipePoolId:r.recipePoolId,scriptWidgetId:r.widgetId,thingId:r.thingId,getState:t.getState,setState:t.setState}):{get:mr,set:async()=>mr(),onValueChange:mr},setTimeout:(r,s,i)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=n(),o={...qn(),...t.getState()};o.$$eventListeners[e]={handler:r,rejectHandler:i,name:dr},t.setState(o),t.registerInterrupt("timeout",e,{timeout:s},void 0,e)}},addEventListener:(e,r)=>{if(t.setState){const i=n(),o={...qn(),...t.getState()};o.$$eventListeners[i]={handler:r,name:e},t.setState(o),window.addEventListener(e,s.bind(i))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,n)=>{if(t.setState){const r={...qn(),...t.getState()},s=Object.keys(r.$$eventListeners).find((t=>r.$$eventListeners[t].name===e&&r.$$eventListeners[t].handler===n));t.setState(r),s&&removeEventListener(r.$$eventListeners[s].name,r.$$eventListeners[s].handler)}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)}}},yr=(e,t,n,r)=>{const s={...qn(),...n.getState()},i=s.pages[zn].$$compiledCode;if(i)return{compiledModule:i};{const i=vr(e,n,t);return Hn(s.pages[zn].code,i,n.recipeType,r)}},br=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),Sr=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===dr){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},wr=async(e,t,n)=>{let r={...qn(),...e.getState()};if(void 0!==n){r.pages[zn]?.$$compiledCode?.onTerminate&&await(r.pages[zn].$$compiledCode?.onTerminate());let t=await Sr(r.$$eventListeners,e);t=await(async e=>{const t={...e};for(const n in e)if(e[n].name===pr){const r=e[n]?.abort;if("function"==typeof r)try{await r()}catch(e){console.log("Error in abort interrupt handler: ",e)}delete t[n]}return t})(t),r.$$eventListeners=t,r.$$error=void 0,r.pages[zn].$$compiledCode=void 0,r.pages[zn].code=n,e.setState({...r})}const s=!r.pages[zn].$$compiledCode,{compiledModule:i,error:o}=yr({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=Kn(o,e.recipeType);return Jn(t,e),null}if(i){const n=(e=>{const t=(t,n)=>{if(gr)try{return gr[t](n)}catch(e){return void console.log("Error in custom logger: ",e)}const r={...qn(),...e.getState()},s=[...r.$$consoleLines||[]];s.push({fileName:zn,text:n,type:t,timestamp:Date.now()}),s.length>100&&s.splice(0,30),e.setState({...r,$$consoleLines:s})},n={log:e=>{t("log",e)},error:e=>{t("error",e)},warn:e=>{t("warn",e)},info:e=>{t("info",e)}};return n})(e);let o;if(r={...e.getState()},r.pages[zn].$$compiledCode=i,e.nextGate&&i.setSendToPortFun(e.nextGate),t)try{await i.recipeInit({setState:e.setState,getState:e.getState},n)}catch(t){o=Kn(t,e.recipeType)}if(e.nextGate&&s)try{await i.main(e.nextGate,n)}catch(t){o=Kn(t,e.recipeType)}r.$$lastInputs=i.getWidgetInputs?i.getWidgetInputs():[],r.$$lastOutputs=i.getWidgetOutputs?i.getWidgetOutputs():[],e.setState(r),Jn(o,e)}};var Ir={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={...qn(),...s};if(!i.pages[zn])return console.warn("Missing default page");if(i.pauseExecution){if(Object.keys(i.$$eventListeners).length){const e=await Sr(i.$$eventListeners,r);r.setState({...i,$$eventListeners:e})}return}if(ke(e?.name||""))return i.$$eventListeners[t.name]?(await i.$$eventListeners[t.name].handler(),i.$$eventListeners[t.name].name===dr&&delete i.$$eventListeners[t.name],void r.setState({...i})):void console.log(`Unknown interrupt id [${t.name}] `);if(t.name.startsWith(ie)){const e=t.name.replace(ie,""),r=n.data.value,s=i.$$eventListeners[e];return void(s?.handler&&await s.handler(r))}const o=t.name===fr;await wr(r,!1,o?n.data.value:void 0);const a=i.pages[zn].$$compiledCode;if(e&&e.name!==fr&&a){let s;try{await a.asyncProcessEvent(t,e,n)}catch(e){"UserCodeError"===e.name&&(s=Kn(e,r.recipeType))}Jn(s,r)}},getInputNames:(e,t)=>{const n={...qn(),...e},{compiledModule:r}=yr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return br(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...qn(),...e},{compiledModule:r}=yr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return br(e)}return e.$$lastOutputs||[]},getDefaultState:qn,initialize:async e=>{const t=e.getState(),n={...qn(),...t};n.pages[zn].code&&await wr({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[zn].code)}};const _r=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const s=await $r(e);return((e,t,n,r)=>{const s=r.getContext("2d");if(!s)throw new Error("Failed to get canvas context");const i=e.width,o=e.height;return r.width=t,r.height=n,s.drawImage(e,0,0,i,o,0,0,t,n),s.getImageData(0,0,t,n)})(s,n||s.naturalWidth,r||s.naturalHeight,t)},$r=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),Cr=Object.freeze({image:"image"}),kr=Object.freeze({base64:"base64"}),Er=()=>({});var xr={onParentEvent:async(e,t,n,r)=>{const s={...r.getState()};if(t.name===kr.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==ce.String&&n.data.type!==ce.Anything)return;const e=n.data.value;ge&&(s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=Bt(320,240)));try{const t=await _r(e,s.$$memCanvas,s.resize?.width,s.resize?.height);return r.setState(s),r.nextGate(Cr.image,{type:ce.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:kr.base64,type:ce.String}],getOutputNames:()=>[{name:Cr.image,type:ce.ImageData}],getDefaultState:Er};const Ar=Object.freeze({object:"object",error:"error"}),Nr=Object.freeze({string:"string"}),Or=()=>({outputIsArray:!1});var Lr={onParentEvent:async(e,t,n,r)=>{const s={outputIsArray:!1,...r.getState()};if((n.data.type===ce.String||n.data.type===ce.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!s.outputIsArray?r.setState({...s,outputIsArray:!0}):!t&&s.outputIsArray&&r.setState({...s,outputIsArray:!1}),r.nextGate("object",{type:t?ce.Array:ce.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:ce.Boolean,value:!0})}},getInputNames:()=>[{name:Nr.string,type:ce.String}],getOutputNames:e=>[{name:Ar.object,type:[ce.JsonObj,ce.Array],label:e.outputIsArray?"array":Ar.object},{name:Ar.error,type:ce.Boolean}],getDefaultState:Or};const Pr=Object.freeze({string:"string",length:"length"}),Tr=Object.freeze({trigger:"trigger",setText:"setText"}),Br=()=>({text:"",dispatchOnSet:!1});var jr={onParentEvent:async(e,t,n,r)=>{const s={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===Tr.setText){if(!((n.data.type===ce.String||n.data.type===ce.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(s.text=n.data.value,r.setState(s)),!s.dispatchOnSet)return}const i=r.nextGate(Pr.length,{type:ce.Number,value:s.text.length}),o=r.nextGate(Pr.string,{type:ce.String,value:s.text});await Promise.all([i,o])},getInputNames:e=>{const t=[{name:Tr.setText,type:ce.String}];return e.dispatchOnSet||t.push({name:Tr.trigger,type:ce.Anything}),t},getOutputNames:()=>[{name:Pr.string,type:ce.String},{name:Pr.length,type:ce.Number}],getDefaultState:Br};const Dr=Object.freeze({image:"image"}),Mr=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),Ur=()=>({showInputPorts:!1});var Fr={onParentEvent:async(e,t,n,r)=>{const s={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Mr.x&&(s.cropX=n.data.value),t.name===Mr.y&&(s.cropY=n.data.value),t.name===Mr.width&&(s.cropWidth=n.data.value),t.name===Mr.height&&(s.cropHeight=n.data.value),void r.setState(s);if(t.name===Mr.image){if(n.data.type!==ce.ImageData&&n.data.type!==ce.Anything)return;if(!Ee(n.data.value))return;const e=n.data.value;if(s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=Bt(320,240),s.$$memCanvasContext=jt(s.$$memCanvas),r.setState(s)),!s.$$memCanvas||!s.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return s.$$memCanvas.width=e.width,s.$$memCanvas.height=e.height,(s.cropX||s.cropY||s.cropWidth||s.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const s=Math.max(r.x||0,0),i=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,s,i,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,s.$$memCanvas,s.$$memCanvasContext,{x:s.cropX,y:s.cropY,width:s.cropWidth,height:s.cropHeight})),r.nextGate(Dr.image,{type:ce.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Mr.image,type:[ce.ImageData]}];return e.showInputPorts&&(t.push({name:Mr.x,type:ce.Number}),t.push({name:Mr.y,type:ce.Number}),t.push({name:Mr.width,type:ce.Number}),t.push({name:Mr.height,type:ce.Number})),t},getOutputNames:()=>[{name:Dr.image,type:ce.ImageData}],getDefaultState:Ur};const Rr=Object.freeze({image:"image"}),Wr=Object.freeze({image:"image",width:"width",height:"height"}),Gr=()=>({showInputPorts:!1});var Vr={onParentEvent:async(e,t,n,r)=>{const s={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Wr.width&&(s.width=n.data.value),t.name===Wr.height&&(s.height=n.data.value),void r.setState(s);if(t.name===Wr.image){if(n.data.type!==ce.ImageData&&n.data.type!==ce.Anything)return;if(!Ee(n.data.value))return;const e=n.data.value;if(s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=Bt(320,240),r.setState(s)),!s.$$memCanvas)return;let t=e;return(s.width||s.height)&&(t=((e,t,n,r)=>{if(!n&&!r)return e;n&&!r?r=n*(e.height/e.width):!n&&r&&(n=r*(e.width/e.height));const s=Math.max(1,n||e.width),i=Math.max(1,r||e.height);t.width=Math.max(e.width,s),t.height=Math.max(e.height,i);const o=jt(t);if(!o)throw new Error("Failed to get canvas context");return o.putImageData(e,0,0),o.drawImage(t,0,0,e.width,e.height,0,0,s,i),o.getImageData(0,0,s,i)})(e,s.$$memCanvas,s.width,s.height)),r.nextGate(Rr.image,{type:ce.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Wr.image,type:ce.ImageData}];return e.showInputPorts&&(t.push({name:Wr.width,type:ce.Number}),t.push({name:Wr.height,type:ce.Number})),t},getOutputNames:()=>[{name:Rr.image,type:ce.ImageData}],getDefaultState:Gr};const Hr=Object.freeze({value:"value"}),zr=Object.freeze({trigger:"trigger",setValue:"setValue"}),qr=()=>({value:0,dispatchOnSet:!1});var Kr={onParentEvent:async(e,t,n,r)=>{const s={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===zr.setValue){const e=n.data.type===ce.Number||n.data.type===ce.Anything||n.data.type===ce.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(s.value=Number(n.data.value),r.setState(s),!s.dispatchOnSet)return}return r.nextGate(Hr.value,{type:ce.Number,value:s.value})},getInputNames:e=>{const t=[{name:zr.setValue,type:ce.Number}];return e.dispatchOnSet||t.push({name:zr.trigger,type:ce.Anything}),t},getOutputNames:()=>[{name:Hr.value,type:ce.Number}],getDefaultState:qr};const Jr=Object.freeze({image:"image"}),Yr=Object.freeze({image:"image"}),Xr=()=>({anchors:[],vertices:[],matrix:[]}),Zr={onParentEvent:async(e,t,n,r)=>{const s={anchors:[],vertices:[],matrix:[],...r.getState()},i=window,o=n.data.type===ce.ImageData;if(i.Speedy&&o){const e=i.Speedy,t=n.data.value;let o,u,d,p=s.$$private?.canvas,h=s.$$private?.context,f={...s};const g=4===s.anchors.length;if(s.$$private?.pipeline)o=s.$$private?.pipeline,u=s.$$private?.source;else{o=e.Pipeline(),u=e.Image.Source();const n=e.Image.Sink();d=e.Transform.PerspectiveWarp(),p?p.width===t.width&&p.height===t.height||(p.width=t.width,p.height=t.height,h=p.getContext("2d")):(c=t.width,l=t.height,p=Bt(c,l),h=p.getContext("2d")),u.output().connectTo(d.input()),d.output().connectTo(n.input()),o.init(u,n,d);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===s.anchors.length){const t=e.Matrix(2,4,[(a=s.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,s.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),i=e.Matrix.Zeros(3,3);await e.Matrix.perspective(i,t,n);const o=i.read();r=e.Matrix(3,3,o)}d.transform=r,f={...f,$$private:{...f.$$private,canvas:p,context:h,perspective:d,pipeline:o,source:u}}}let m=t;if(g){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,s=e.$$private?.pipeline;if(n.Speedy&&r&&s){const e=n.Speedy,i=await createImageBitmap(t),o=await e.load(i);return r.media=o,(await s.run()).image.source}return null})(f,m);e&&(p&&h&&(m=((e,t,n)=>(t.width=e.width,t.height=e.height,n.drawImage(e,0,0),n.getImageData(0,0,e.width,e.height)))(e,p,h)),f.$$private&&r.setState({...f,$$private:{...f.$$private,lastInputImage:t}}))}else f.$$private&&r.setState({...f,$$private:{...f.$$private,lastInputImage:t}});return r.nextGate(Jr.image,{type:ce.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:Yr.image,type:ce.ImageData}],getOutputNames:()=>[{name:Jr.image,type:ce.ImageData}],getDefaultState:Xr,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},Qr=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[ce.Anything],name:"input"}],outputs:[{dataType:[ce.Anything],name:"output"}]});let es;const ts=()=>{if(!es)throw new Error(ze(He));return es};const ns=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},rs={};var ss=e=>rs[e]||null;const is=async(e,t,n)=>{try{const r=ts(),s=n?r.loadBlobAsString:r.loadBlob;return await s(e,t)}catch(e){return null}},os=async e=>{const t=ne;try{const n=await is(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},as=async e=>{const t=re;try{const n=await is(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}},cs=(e,t)=>`${e.replace(se,"")}_${t}`,ls=(e,t)=>`widget/${e.replace(se,"")}/v/${t}`,us=async(e,t)=>{const n=ts(),[r]=await Promise.all([ns(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},ds=(e,t)=>{const n=cs(e,t),r=ss(n);return r?{...r}:null},ps=(e,t,n)=>{const r=`${`widget/${e.replace(se,"")}/tmp`}/${t}`;if(n){return ts().getCacheLocation(r)}return r};var hs=ds,fs=async(e,t,n)=>{const r=ps(t,n);await us(e,r);const s=os(r),i=as(r),o=ts(),a=o.getCacheLocation(r),[c,l]=await Promise.all([s,i]);if(!c)return null;let u=l;if(!l){const e=Qr(),t=JSON.stringify(e);await o.saveBlob(r,re,Ce(t)),u=e}return{cachePath:a,processor:c,storedState:Object.freeze(u)}},gs=(e,t,n)=>{if(n.isTempStorage)return ps(e,t,n.fullStorageRoot);const r=ts(),s=ls(e,t);return n.fullStorageRoot?r.getCacheLocation(s):s};const ms=()=>Qr();var vs={onParentEvent:async(e,t,n,r)=>{const s=r.getState();return s.$$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={...ms(),...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={...ms(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:ms,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetThingId;const s=n.$$cacheInfo?.version.toString()||n.collectionInfo?.version.toString()||1;if(n.$$cacheInfo={...n.$$cacheInfo,version:Number(s),widgetThingId:r},!r||!s)throw new Error("Widget bundle state is missing cache id or version");console.log("Loading state from cache");const i=hs(r,s);let o=!i;if(!n.$$processor)if(n.storageUnitId&&!i){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetThingId;const i=await fs(t,r,s);o=!0,i&&(n={...n,$$processor:i.processor,$$cacheInfo:{...n.$$cacheInfo,widgetThingId:r,version:Number(s)}},e.setState(n))}}else if(i){o=!1;const r=n.collectionInfo?{...n.collectionInfo}:void 0;n={...n,...!t.keepCurrentState&&i.storedState?{...i.storedState,...r?{collectionInfo:r}:{}}:{},$$processor:i.processor},e.setState(n)}const a=gs(r,s,{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 ys=Object.freeze({event:"event"}),bs="1",Ss="2",ws="3";var Is={onParentEvent:async(e,t,n,r)=>{const s={...r.getState()};r.setState({...s,$$lastEventType:n.data.type}),await r.nextGate(bs,n.data),await r.nextGate(Ss,n.data),await r.nextGate(ws,n.data)},getInputNames:()=>[{name:ys.event,type:ce.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??ce.Anything};return[{name:bs,...t},{name:Ss,...t},{name:ws,...t}]}};const _s=Object.freeze({set:"set",trigger:"trigger"}),$s="value";var Cs={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={name:"myVar",type:ce.String,reactive:!0,defaultValue:"",...s};if(t.name.startsWith(ie)){if(!i.reactive)return;if(n.data.type!==i.type)return;return r.nextWidget($s,n.data)}if(t.name!==_s.set){if(t.name===_s.trigger){const e=cr(r.recipePoolId,r.thingRecipeId,i.name,{ownerWidgetId:r.id}),t=e||i.defaultValue;await r.nextWidget($s,{type:i.type,value:t})}}else await ar(r.recipePoolId,r.thingRecipeId,r.id,i.name,n.data,{skipCallerNotification:!i.reactive})},getInputNames:e=>{const t={...e};return[{name:_s.set,type:t.type||ce.Anything},{name:_s.trigger,type:ce.Anything}]},getOutputNames:e=>{const t={...e};return[{name:$s,type:t.type||ce.Anything}]}};let ks;var Es=e=>{ks=e},xs=()=>{if(!ks)throw new Error("Hub Connector not set");return ks};const As=async(e,t=!1)=>{const n=xs();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 Ns={onParentEvent:async(e,t,n,r)=>{const s={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const i=xs();let o=s.$$$serviceId;if(!o){const e=i.getCachedServices().available.find((e=>e.name===s.service?.name&&e.version===s.service?.version));if(!e)return;o=e.sessionId,s.$$$serviceId=o,r.setState(s)}const a=s.service?.variants?.find((e=>e.id===s.variantId)),c=a?s.dynamicInputs[a.id]||a?.inputs||[]:s.service?.inputs||[];if(!c?.length)return;if(!a&&s.service?.ignoreParentEvents)return;const l=s.service?.processingTimeoutSec;return i.onParentEvent({recipeId:r.recipePoolId,data:n.data,targetServiceSessionId:o,currentState:s.customState,targetVariantId:s.variantId,target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:l?1e3*l:0,async:s.service?.asyncParentEvents}})},getInputNames:async e=>{const t=e.variantId;if(t&&e.dynamicInputs?.[t])return[...e.dynamicInputs[t]||[]];if(!t)return e.service?.inputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.inputs||[]}return[]},getOutputNames:async e=>{const t=e.variantId;if(t&&e.dynamicOutputs?.[t])return[...e.dynamicOutputs[t]||[]];if(!t)return e.service?.outputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.outputs||[]}return[]},initialize:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=xs(),r=await As(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=xs(),r=await As(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const Os=Object.freeze({Image:"image"}),Ls=Object.freeze({Image:"image"}),Ps=()=>({filters:[{name:"grayscale",value:.5,id:"d-1"}]});const Ts="loaded";const Bs={input:Je,counter:Ze,elapsed:tt,ifGate:it,skipEvent:ct,between:pt,map:gt,parser:yt,slider:wt,suspend:$t,display:kt,json:At,arrayItem:Lt,extractImage:Ut,imageConvolution:Vt,firstEvent:Kt,pixelDraw:en,randomBetween:sn,arrayCombine:un,clock:fn,multiplication:yn,object:$n,widgetGroup:xn,script:Ir,base64ToImageData:xr,jsonParse:Lr,text:jr,imageCrop:Fr,imageResize:Vr,value:Kr,imageWarp:Zr,widgetBundle:vs,sequence:Is,variable:Cs,hubService:Ns,imageFilter:{onParentEvent:async(e,t,n,r)=>{const s={filters:[{name:"grayscale",value:.5,id:"d-1"}],...r.getState()};if(t.name===Os.Image&&n.data.type===ce.ImageData){if(!Ee(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;s.$$memCanvas||(s.$$memCanvas=Bt(e.width,e.height)),s.$$context||(s.$$context=s.$$memCanvas.getContext("2d")),s.$$memCanvas.width!==e.width&&(s.$$memCanvas.width=e.width),s.$$memCanvas.height!==e.height&&(s.$$memCanvas.height=e.height),r.setState(s),s.$$context.putImageData(e,0,0),s.filters.length?s.$$context.filter=s.filters.map((e=>`${e.name}(${e.value}${"blur"===e.name?"px":""})`)).join(" "):s.$$context.filter="none",s.$$context.drawImage(s.$$memCanvas,0,0);const t=s.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(Ls.Image,{type:ce.ImageData,value:t})}},getInputNames:()=>[{name:Os.Image,type:ce.ImageData}],getOutputNames:()=>[{name:Ls.Image,type:ce.ImageData}],getDefaultState:Ps},recipeLoad:{onParentEvent:async(e,t,n,r)=>r.nextWidget(Ts,{value:!0,type:ce.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:Ts,type:ce.Boolean,description:"Triggered when the recipe is fully loaded"}]},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:ce.Boolean}]}},js={},Ds=async()=>{if(!Object.keys(js).length)for(const e in Bs){const t=Bs[e];js[e]=Object.freeze({...t})}};var Ms=e=>{if(js[e])return js[e];throw new Error(ze(Ve,e))},Us=Ds;const Fs=new o,Rs="invoked";let Ws={},Gs={},Vs={},Hs={};const zs=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var qs=(e,t,n,r,s)=>{const i=zs(e,t,n),o=zs(e,t),a=zs(e,t,"produced"),c=Vs[o],l=Date.now();Hs[o]=l,Ws[i]={data:r,sourcePortName:n,...s?{target:{widgetId:s.widgetId,portName:s.portName}}:{}},Fs.emit(a,{currentTime:l,prevTime:c,...s?{targetPort:s?.portName}:{}})},Ks=(e,t,n,r,s)=>{const i=zs(e,t,n),o=zs(e,t),a=zs(e,t,Rs),c=Vs[o],l=Date.now();Vs[o]=l,Gs[i]={data:r,sourcePortName:n,...s?{source:{widgetId:s.widgetId,portName:s.portName}}:{}},Fs.emit(a,{prevTime:c,currentTime:l,targetPort:n,sourceInfo:s})},Js=()=>{Ws={},Gs={},Vs={},Hs={},Fs.clearListeners()};let Ys,Xs,Zs;const Qs=async(e,t,n,r,s)=>{const i=Z(n,t);if(!i)return;const o=i.gates[e];if(!o||o.disabled)return;const a={...s,timestamp:Date.now()},c=Ms(o.type),l=ri(e,a,i.recipeId,i.id,i.version,n);if(l&&c.onParentEvent){const t={name:r};return Ys&&await Ys({recipeId:n,blockId:i.recipeId,gateId:e,targetPort:t.name,data:s}),c.onParentEvent(null,t,{originalEvent:a,data:{...a}},l)}},ei=async(e,t,n,r,s,i,o,a,c,l)=>{if(!e&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!e&&!l)throw new Error("Missing parameter ['originalEvent']");e&&(l={timestamp:Date.now(),type:ce.Boolean,value:!0});const u=l;if("string"==typeof n){const e=Z(r,n);if(!e)return;n=e}const d=n.gates[t];if(!d||d.disabled)return;const p=a.findIndex((e=>e.name===s)),h=Ms(d.type),f=ri(t,u,n.recipeId,n.id,n.version,r);if(f&&h.onParentEvent&&-1!==p){Ys&&await Ys({recipeId:r,blockId:n.recipeId,gateId:t,targetPort:i.name,data:o,sourceGate:e?"interrupt_widget":c,sourcePort:e?te:s});const l={name:a[p].name,type:a[p].type,...a[p].jsonShape?{jsonShape:a[p].jsonShape}:void 0};return Ks(n.recipeId,t,i.name,o,c?{widgetId:c,portName:s}:void 0),h.onParentEvent(l,i,{originalEvent:u,data:o},f)}},ti=async(e,t,n,r,s,i,o,a)=>{const c=X(a);if(!c)throw new Error(`Failed to find recipe "${a}" in cache`);const l=c.dbInfo.recipeType,u=Q(a,s,r);if(!u)return;const d={...n,timestamp:t.timestamp},p=Ms(u.type);let h;h=u.type===je.input?p.getOutputNames(u.state,{thingRecipeId:s,thingDbId:i,thingVersion:o,id:r,recipeId:a,recipeType:l,recipePoolId:a}):await p.getOutputNames(u.state,{recipePoolId:a,recipeType:l,thingRecipeId:s,widgetId:r});const f=h.findIndex((t=>t.name===e));if(-1!==f){const n=Z(a,s);if(!n)return;qs(s,r,e,d);const i=u.children.length;for(let o=0;o<i;o++){if(Pe(u.children[o]?.sourcePort).portName===e){const i=n.gates[u.children[o].childId];if(i&&!i.disabled){const c=Ms(i.type);let p;const f={recipePoolId:a,recipeType:l,thingRecipeId:s,widgetId:r};p=i.type===je.hubService?await c.getInputNames(i.state,f):c.getInputNames(i.state,f);const g=Pe(u.children[o].targetPort),m=p.find((e=>e.name===g.portName));m&&await ei(!1,i.id,n,a,e,{name:m.name},u.returnOriginalEvent?t:d,h,u.id,t)}}}}},ni=async(e,t,n,r)=>{const s=X(r);if(!s)return null;const i=Z(r,n);if(!i)return i;const o=i.gates,a=i.gates[t],c=Ms(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:s.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),u=l.findIndex((t=>t.name===e));if(-1!==u){const e=((e,t,n)=>{for(const r in n){const s=n[r],i=s.children.length;for(let n=0;n<i;n++){const r=s.children[n],i=Pe(r.targetPort);if(r.childId===e&&i.portName===t)return s}}return null})(t,l[u].name,o);if(e){const t=Ms(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},ri=(e,t,n,r,s,i)=>{const o=X(i);if(!o)throw new Error(`Failed to find recipe "${i}" in cache`);const a=Q(i,n,e);if(!a)return console.warn(`Gate ${e} not found in block ${n} for recipe ${i}`),null;const c=async(o,a)=>ti(o,t,a,e,n,r,s,i),l={id:e,type:a.type,recipePoolId:i,thingRecipeId:n,recipeType:o.dbInfo.recipeType,returnOriginalEvent:!!a.returnOriginalEvent,registerInterrupt:(t,r,s,o,a)=>Re.createInterrupt(t,i,n,e,r,s,o,a),cancelInterrupt:e=>Re.destroyInterrupt(e),nextWidget:c,nextGate:c,getParentAtPort:t=>ni(t,e,n,i),getState:()=>Object.freeze({...a.state,...a.type===je.input&&{customInputs:[]}}),setState:t=>{if("object"!=typeof t)return void console.warn(`Invalid state type [${typeof t}]. Expected an 'object'`);const r={...t,...a.type===je.input&&!t.customInputs&&{customInputs:[]}},s={...a.state};a.state=r,Xs&&Xs({blockId:n,gateId:e,prevState:s,newState:{...r},recipeId:i})}};return l};Re.setInvokeChildGateCb(ei);const si=new o,ii="invoked",oi="state",ai=()=>{Re.destroyAllInterrupts()},ci=async(e,t,n)=>{const r=X(e),s=Q(e,t,n);if(s&&r){const i=Ms(s.type);if(i&&"function"==typeof i.terminate){const s=((e,t,n,r)=>We(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(s)try{await i.terminate(s)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},li=async(e,t,n,r)=>{const s=X(e),i=Q(e,t,n);if(i&&s){const o=Ms(i.type);if(o&&"function"==typeof o.initialize){const i=((e,t,n,r)=>We(e,t,n,r,!0))(e,s.dbInfo.recipeType,t,n);if(i){const e=o.initialize;try{await e(i,r||{})}catch(e){throw console.warn(`Error initializing widget "${n}" in thing "${t}": `,e),e}}}}},ui=(e,t)=>{const n=X(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},di=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,pi=e=>{si.emit(di(oi),e),si.emit(di(oi,e.blockId,e.gateId),e)};Ys=async e=>{await si.emit(di(ii),e),await si.emit(di(ii,e.blockId,e.gateId),e)},(e=>{Xs=e})(pi);var hi,fi,gi,mi,vi,yi,bi,Si,wi,Ii,_i,$i,Ci,ki=async(e,t,n,r,s)=>{const i=ee(e,{id:t,authorId:r,version:n,recipeType:s});Js();const o=X(i);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=q.STARTING,o.addLog("recipe registered")),i},Ei=async e=>{const t=X(e);var n;if(!t)return null;t.addLog("terminating recipe"),ai();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await ci(e,n,t)}K[n=e]&&delete K[n]},xi=async(e,t)=>{const n=X(e),r=[],s=[];if(n)for(const i in n.blocks){const o=n.blocks[i];if(!t||!Array.isArray(t)||t.includes(i))for(const t in o.gates)try{if(n.dbInfo?.recipeType===Nn.Desktop){const e=o.gates[t];if(e.type===je.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===je.recipeLoad&&s.push(e)}await li(e,i,t,{keepCurrentState:!0})}catch(e){r.push({widgetId:t,error:e.message})}}return{failed:r,sendToInputWidget:(t,n,r=oe)=>(async(e,t,n,r)=>{const s=X(n),i=Z(n,r),o=Date.now();if(i&&s)for(const s in i.gates){const a=i.gates[s];if(a.type===je.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=Ms(a.type),l={...t,timestamp:o},u=ri(s,l,r,i.id,i.version,n);if(u&&e.processEvent){const i={...u,getState:u.getState};Ys&&await Ys({recipeId:n,blockId:r,gateId:s,targetPort:Ke,data:t}),Zs?await Zs(r,n,c,t):await e.processEvent(l,i)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of s)await Qs(t.id,oe,e,Ts,{type:ce.Boolean,value:!0})}}},Ai=e=>{Es(e)},Ni=(e,t,n,r=!1)=>{const s=ui(t,e);if(s){const{widget:i,thing:o}=s,a={...i.state};i.state=n,r&&pi({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},Oi=(e,t)=>{const n=ui(t,e);return n?n.widget.state:null},Li=async(e,t,n,r,s)=>{const i=ui(t,e);if(i)return ti(n,r,s,t,i.thing.recipeId,i.thing.id,i.thing.version,e)};!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(hi||(hi={})),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"}(fi||(fi={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(gi||(gi={})),function(e){e.Bundle="bundle",e.Group="group"}(mi||(mi={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(vi||(vi={})),function(e){e.Cloud="cloud",e.Web="web"}(yi||(yi={})),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"}(bi||(bi={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Si||(Si={})),function(e){e.InstallInProgress="installation-in-progress"}(wi||(wi={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Ii||(Ii={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(_i||(_i={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}($i||($i={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.ExportRecipe="export_recipe"}(Ci||(Ci={}));const Pi=e=>{try{return JSON.parse(e)}catch(e){return null}},Ti="undefined"!=typeof window,Bi={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},ji={protocolPrefix:4,txtLength:4},Di=Object.values(Bi).reduce(((e,t)=>e+t),0),Mi=Object.values(ji).reduce(((e,t)=>e+t),0),Ui=["width","height","colorSpace"],Fi=(e,t)=>{const n={},r=[];let s=0,i=Array.isArray(e)?[]:{};const o=(e,i)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,s=e instanceof Uint8Array,i=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":s?"Uint8Array":i?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${i}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,s=e instanceof Uint32Array,i=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":s?"Uint32Array":i?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${i}"`);for(const n in e)e.hasOwnProperty(n)||Ui.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${i}`),t[n]=o(e[n],`${i.length?`${i}.`:""}${n}`);return t}return e}n[i]={index:s,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),s+=e.byteLength};i=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:i}:null},Ri=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let s=e;for(let e=0;e<r.length;e++){let t=r[e];const i=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(i){t=t.slice(1,-1);const i=parseInt(t,10);if(!Array.isArray(s))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?s[i]=n:(s[i]||(s[i]=r[e+1].startsWith("[")?[]:{}),s=s[i])}else o?s[t]=n:(s[t]||(s[t]=r[e+1].startsWith("[")?[]:{}),s=s[t])}return e},Wi=(e,t,n)=>{const r="undefined"!=typeof Buffer,s=t instanceof Uint8Array;for(const i in n)if(n.hasOwnProperty(i)){const{index:o,length:a,binaryType:c}=n[i];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=s?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=s?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&&Ri(e,i,l)}return e},Gi=e=>l(e),Vi="KMSG",Hi="KCMD",zi=Gi("klProtocol");var qi={encode:(e,t,n)=>{const r={json:e.json},s=Fi(r.json,"Buffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=Bi.protocolPrefix+Bi.protocolVersion+Bi.jsonLength+Bi.binaryLength+Bi.fromServiceId+Bi.toServiceId+Bi.sentAt+l+o,d=Buffer.alloc(u),p=Date.now();let h=0;return d.write(Vi,h),h+=Bi.protocolPrefix,d.writeUInt8(1,h),h+=Bi.protocolVersion,d.writeUInt32LE(l,h),h+=Bi.jsonLength,d.writeUInt32LE(o,h),h+=Bi.binaryLength,d.writeUInt32LE(t,h),h+=Bi.fromServiceId,d.writeUInt32LE(n,h),h+=Bi.toServiceId,d.writeBigInt64LE(BigInt(p),h),h+=Bi.sentAt,c.copy(d,h),h+=l,i&&o&&i.copy(d,h),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Bi.protocolPrefix);if(t+=Bi.protocolPrefix,n!==Vi)return null;if(e.byteLength<Di)return zi(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Bi.protocolVersion;const s=e.readUInt32LE(t);t+=Bi.jsonLength;const i=e.readUInt32LE(t);t+=Bi.binaryLength;const o=e.readUInt32LE(t);t+=Bi.fromServiceId;const a=e.readUInt32LE(t);t+=Bi.toServiceId;const c=e.readBigInt64LE(t);t+=Bi.sentAt;const l=s+i,u=e.subarray(t,t+l),d=e.subarray(0,Di);let p=null;return e.byteLength-Di-s-i>0&&(p=e.subarray(Di+s+i)),{header:{protocolVersion:r,jsonLength:s,binaryLength:i,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:p}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),s=Pi(n);if(!s?.json)return zi("Invalid JSON in KL message"),null;s.jsonBinaryMap&&r.byteLength&&Wi(s.json,r,s.jsonBinaryMap);const i=Buffer.concat([e.headerPackage,t]);let o=i,a=null;const c=Di+e.jsonLength+e.binaryLength;return i.byteLength>c&&(a=i.subarray(c),o=i.subarray(0,c)),{message:{json:s.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Di)return zi("Invalid Header Size"),e;let n=0;return n+=Bi.protocolPrefix,n+=Bi.protocolVersion,n+=Bi.jsonLength,n+=Bi.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Bi.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,s=Mi+r,i=Buffer.alloc(s);return i.write(Hi,t),t+=ji.protocolPrefix,i.writeUint32LE(r,t),t+=ji.txtLength,n.copy(i,t),i},decodeCommand:e=>{let t=0;if(e.byteLength<Mi)return{command:null};const n=e.toString("utf-8",t,ji.protocolPrefix);if(t+=ji.protocolPrefix,n!==Hi)return{command:null};const r=e.readUInt32LE(t);t+=ji.txtLength;const s=e.toString("utf-8",t,t+r),i=e.byteLength-Mi-r;let o=null;i>0&&(o=e.subarray(Mi+r));let a=0;return i<0&&(a=Math.abs(i)),{command:s,remainingData:o,missing:a}}};const Ki="KMSG",Ji="KCMD",Yi=Gi("klProtocol"),Xi=new TextEncoder;var Zi={encode:(e,t,n)=>{const r={json:e.json},s=Fi(e.json,"ArrayBuffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=Xi.encode(a),l=c.byteLength,u=new ArrayBuffer(Bi.protocolPrefix+Bi.protocolVersion+Bi.jsonLength+Bi.binaryLength+Bi.fromServiceId+Bi.toServiceId+Bi.sentAt+l+o),d=new DataView(u),p=new Uint8Array(u),h=Date.now();let f=0;for(let e=0;e<4;++e)p[f++]=Ki.charCodeAt(e);return d.setUint8(f,1),f+=Bi.protocolVersion,d.setUint32(f,l,!0),f+=Bi.jsonLength,d.setUint32(f,o,!0),f+=Bi.binaryLength,d.setUint32(f,t,!0),f+=Bi.fromServiceId,d.setUint32(f,n,!0),f+=Bi.toServiceId,d.setBigInt64(f,BigInt(h),!0),f+=Bi.sentAt,p.set(c,f),f+=l,i&&o&&p.set(new Uint8Array(i),f),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Bi.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ki)return null;if(e.byteLength<Di)return Yi.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const s=t.getUint8(n);n+=Bi.protocolVersion;const i=t.getUint32(n,!0);n+=Bi.jsonLength;const o=t.getUint32(n,!0);n+=Bi.binaryLength;const a=t.getUint32(n,!0);n+=Bi.fromServiceId;const c=t.getUint32(n,!0);n+=Bi.toServiceId;const l=t.getBigInt64(n,!0);n+=Bi.sentAt;const u=i+o,d=e.slice(n,n+u),p=new Uint8Array(e,0,Di);let h=null;if(e.byteLength-Di-i-o>0){h=new Uint8Array(e,Di+i+o).slice().buffer}return{header:{protocolVersion:s,jsonLength:i,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:p.slice().buffer},remaining:h}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,s=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,s),s+=r.byteLength;const i=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Pi(i);if(!a?.json)return Yi.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Wi(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=Di+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Di)return Yi("Invalid Header Size"),e;let n=0;n+=Bi.protocolPrefix,n+=Bi.protocolVersion,n+=Bi.jsonLength,n+=Bi.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Bi.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Xi.encode(e),r=n.byteLength,s=new ArrayBuffer(Mi+r),i=new DataView(s),o=new Uint8Array(s);for(let e=0;e<4;++e)o[t++]=Ji.charCodeAt(e);return i.setUint32(t,r,!0),t+=ji.txtLength,o.set(n,t),s},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Mi)return{command:null};let r="";for(let e=0;e<ji.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ji)return{command:null};const s=t.getUint32(n,!0);n+=ji.txtLength;const i=e.byteLength-Mi-s,o=new Uint8Array(e,n,Math.min(s,e.byteLength-Mi)),a=(new TextDecoder).decode(o);let c=null;i>0&&(c=e.slice(Mi+s));let l=0;return i<0&&(l=Math.abs(i)),{command:a,remainingData:c,missing:l}}};let Qi=qi;Ti&&(Qi=Zi);var eo,to=Qi;(eo||(eo={})).FunctionNotFound="FNC_NOT_FOUND";let no=Math.ceil(Date.now()/1e3);let ro,so,io,oo,ao,co=!1;var lo=()=>{co=!0},uo=(e,t)=>{if(!ro)throw new Error("Memory connection not set.");ro.sendBuf(e,t)},po=e=>so=e,ho=e=>ao=e,fo=e=>io=e,go=e=>oo=e;const mo=(e,t=2)=>{const n=(e,r)=>{if("object"==typeof e){const s=Object.keys(e);for(const i of s){const s=e[i];if(s&&"object"==typeof s){const o=s._kemuType;if(void 0!==o){if(o===ce.ImageData){const t=e[i];e[i]=Te(t)}}else r<t&&n(s,++r)}}}};return n(e,1),e};Gi("klTransmissionManager"),Gi("ipcClient");Gi("kemuWidgetService"),S(process.argv.slice(2));const vo=e=>l(`runner:${e}`),yo=vo("connectionManager"),bo=vo("remoteInvoke"),So=new function(e){const t={};let n=console.log;const r={};let s=e||String(Date.now());const i={},o=e=>!i[e],a=(e,t,n,r,s,i)=>{let a=Ti?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:i.success?i.success:[i],messageId:t,type:i.success?"response":"error"}};return o(r)&&(a=to.encode(c,n,r)),s(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,s,i,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,i.targetServiceId,i.sourceServiceId,s,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:i.sourceServiceId,send:s})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,s,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,i,a,c,l)=>{if(!i){const e="No send buffer function provided.";throw n&&n(e),e}no+=1;const u=`${s}-${no}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:i,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let p=Ti?new ArrayBuffer(0):Buffer.alloc(0);const h={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(p=to.encode(h,a,c)),t[u]=d,n&&n(`Calling remote function "${e}" with message id "${u}"`);const f="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||f||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=t[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),i(p,{sourceServiceId:a,targetServiceId:c,msg:h}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{s=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,i)=>{no+=1;const a=`${s}-${no}-multicast-${e.substring(0,10)}`;let c=Ti?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=o(r[0].serviceId);u&&(c=to.encode(l,i,r[0].serviceId));for(let t=0;t<r.length;t++)try{const s=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${s.serviceId}]`),0!==t&&(u=o(s.serviceId),u&&(c=to.patchEncodedHeader(c,{toServiceId:s.serviceId}))),s.sendFn(c,{msg:l,sourceServiceId:i,targetServiceId:s.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{i[e]=t}}}("kweb");So.setLogger(bo);const wo=new o,Io=new o;let _o,$o=null,Co=null,ko=null;const Eo={},xo=()=>{if(!ko)throw new Error("API key is required to interact with the hub");return ko},Ao=(e,t,n)=>{const r=`${e}_${t}`,s={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return Eo[r]=s,s},No=(e,t)=>Eo[`${e}_${t}`]||null,Oo=async(e,t)=>{if(!$o)return yo("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await So.execute(pe.GetServiceContents,n,Po,$o,0))[0]},Lo=async(e,t,n=!1)=>{if(!e||!t)return null;const r=No(e,t);if(!r||n){const n=r||Ao(e,t);try{const r=await Oo(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){yo(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},Po=uo,To=()=>{yo("Disconnected from the server"),$o=null,So.rejectAllPending("Disconnected from the server"),wo.emit("disconnected")},Bo=()=>{yo("Connected to the server"),wo.emit("connected")},jo=()=>Co,Do=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,Mo=async()=>{const e=jo();if(e){const t=X(e)?.blocks;if(t){const n={};for(const r in t){const s=t[r];for(const t in s.gates){const r=s.gates[t];if(r.type===je.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{yo(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await Qo({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){yo(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},Uo=async e=>{if(!e)return void yo("Hub sent ACK request without service id");const t={apiKey:xo(),ackSessionId:e};await So.execute(pe.SocketAckResponse,[t],Po,e,0),yo("Hub Link acknowledged"),$o=e,wo.emit("acknowledged"),Mo()},Fo=async e=>{const t=e.args[0],n=Do("broadcast",`hub_${t.type}`,(0).toString(),"");await Io.emit(n,t)},Ro=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===ce.ImageData&&Ee(e.value)&&(e.value=Te(e.value));const n=jo();if(n){const r=X(n);if(r){const s=async e=>{const n=Do("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await Io.emit(n,t)}catch(t){yo(`Failed to emit broadcast event for target ${e}`,t)}};await s("app");for(const i in r.blocks){const o=r.blocks[i];for(const r in o.gates){const i=o.gates[r];if(i.disabled)continue;const a=i.state;if(i.type===je.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await s(r);for(const s of t.outputs||[])if(null!==s.value&&void 0!==s.value){const t={type:s.type,value:s.value,timestamp:Date.now()};yo(`Sending data to output ${s.name} requested by messageId ${e.messageId}`),await Li(n,r,s.name,t,t)}}}}}}},Wo=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:s}=t,i=Oi(r,s);let o=i;if(n&&o&&i&&(o={...i,customState:n},Ni(r,s,o,!0)),o?.service)try{const e=Do("setOutputs",o.service.name,o.service.version,s);await Io.emit(e,t.outputs)}catch(e){yo(`Failed to emit setOutputs event for widget ${s}`,e)}for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===ce.ImageData){if(!Ee(n.value)){yo(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=Te(n.value)}else n.type===ce.JsonObj&&mo(n.value);const t={type:n.type,value:n.value,timestamp:Date.now()};yo(`Sending data to output ${n.name} requested by messageId ${e.messageId}`),await Li(r,s,n.name,t,t)}e.reply({success:[]})},Go=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:s}=t,i=Oi(r,s);if(i){const t={...i,customState:{...i.customState,...n}};return Ni(r,s,t,!0),e.reply({success:[]})}},Vo=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:s,path:i,key:o}=n;yo(`Received request to set a dependency path for "${o}" on widget "${s}" in recipe "${r}"`);const a=Oi(r,s);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:i},Ni(r,s,e,!0)}return t({success:[]})},Ho=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:s,key:i}=n;yo(`Received request to get a dependency path for "${i}" on widget "${s}" in recipe "${r}"`);const o=Oi(r,s);if(o){const e=o.dependencies?.[i]?.path;return yo(`Returning dependency path for "${i}" on widget "${s}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},zo=async()=>{if(yo(`Requesting services on ${(new Date).toISOString()}`),!$o)return yo("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await So.execute(pe.GetServices,[],Po,$o,0);_o=e;for(const t of e.available){if(t.internal)continue;const e=No(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||Ao(t.name,t.version);yo(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await Oo(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){yo(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},qo=()=>_o||{available:[],installed:[],failed:[]},Ko=()=>!!_o,Jo=async e=>{const{targetServiceSessionId:t}=e;if(!$o)return void yo("No target service session id provided");yo(`Forwarding "onParentEvent" to service ${t}`);return await So.execute(pe.OnParentEvent,[e],Po,$o,t,e.config)},Yo=async e=>{if(!$o)return yo("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await So.execute(pe.GetDefaultState,[],Po,$o,e);return t},Xo=async(e,t,n,r)=>{if(!$o)return yo("Hub Link has not been acknowledged. Cannot get services."),null;const[s]=await So.execute(pe.UIEvent,[t,n],Po,$o,e,r);return s},Zo=(e,t)=>{const n=()=>{t()};return wo.on(e,n),()=>wo.off(e,n)},Qo=async e=>{if($o)return So.execute(pe.SubscribeToService,[e],Po,$o,0);yo("Hub Link has not been acknowledged. Cannot subscribe to services.")},ea=async e=>{if($o)return So.execute(pe.UnsubscribeFromService,[e],Po,$o,0);yo("Hub Link has not been acknowledged. Cannot subscribe to services.")},ta=(e,t,n,r)=>{const s=Do("broadcast",t,n,e);return Io.on(s,r)},na=(e,t,n,r)=>{const s=Do("setOutputs",t,n,e);return Io.on(s,r)},ra=async(e,t,n)=>$o?So.execute(e,t,Po,$o,0,n):(yo("Hub Link has not been acknowledged. Cannot execute function."),null),sa=async e=>{if(!$o)return void yo("Hub Link has not been acknowledged. Cannot execute function.");const t=Oi(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}],[s]=await So.execute(pe.InitializeInstance,r,Po,$o,e.sessionId);if(s){const t=Oi(e.recipeId,e.widgetId);if(t){const n={...t,customState:s};Ni(e.recipeId,e.widgetId,n,!0)}}},ia=async(e,t,n,r)=>{if(!$o)return void yo("Hub Link has not been acknowledged. Cannot execute function.");const s=Oi(n,t);if(!s)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const i=[{currentState:s.customState,recipeId:n,widgetId:t,variantId:r}];await So.execute(pe.TerminateInstance,i,Po,$o,e)},oa=async(e,t,n="^",r)=>{const s=["^","~",">=",">","<=","<","="];if(!s.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${s.join(", ")}`);const i=Ko(),o=r||!i?await zo():qo();for(const r of o.available)if(r.name===e){if(r.version===t)return r;if(c(r.version,`${n}${t}`))return r}return null};var aa,ca,la,ua,da,pa,ha,fa,ga=async e=>{fo(Bo),go(To),ko=e,ho((({json:e,transmission:t})=>{So.processMessage("websocket",Po,t,e)})),So.registerFunction(pe.SetState,Go),So.registerFunction(pe.SetOutputs,Wo),So.registerFunction(pe.BroadcastEvent,Ro),So.registerFunction(pe.HubBroadcastEvent,Fo),So.registerFunction(he.SetDependencyPath,Vo),So.registerFunction(he.GetDependencyPath,Ho),po((e=>{((e,t)=>{const n=de.SocketAcknowledge,r=de.IpcAcknowledge,s=e.startsWith(n);if(e===r)return t&&t(),0;if(s){const i=e.split(s?n:r),o=parseInt(i[1]);return t&&t(o),o}})(e,Uo),((e,t)=>{e===de.ServicesListChanged&&(t&&t())})(e,(()=>{yo("Services list changed"),wo.emit("services-changed")}))})),await lo()},ma=(e,t)=>{wo.on(e,t)},va=()=>({getServices:zo,getServiceContents:Lo,onParentEvent:Jo,onCommand:Zo,getDefaultState:Yo,getCachedServices:qo,areServicesCached:Ko,subscribeToServiceEvents:Qo,unsubscribeFromServiceEvents:ea,callProcessorHandler:Xo,onBroadcastEvent:ta,onSetOutputsEvent:na,executeHubFunction:ra,initializeServiceInstance:sa,terminateServiceInstance:ia,getCompatibleService:oa}),ya=e=>{Co=e},ba=()=>So;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(aa||(aa={})),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"}(ca||(ca={})),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"}(la||(la={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ua||(ua={})),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:"}(da||(da={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId"}(pa||(pa={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(ha||(ha={})),function(e){e.IPC="ipc",e.WS="ws"}(fa||(fa={}));const Sa=e=>{try{return JSON.parse(e)}catch(e){return null}},wa=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Ia=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(wa);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},_a=e=>"*"===e||"x"===e||"X"===e,$a=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},Ca=(e,t)=>{if(_a(e)||_a(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])($a(e),$a(t));return n>r?1:n<r?-1:0},ka=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=Ca(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},Ea=(e,t,n)=>{Na(n);const r=((e,t)=>{const n=Ia(e),r=Ia(t),s=n.pop(),i=r.pop(),o=ka(n,r);return 0!==o?o:s&&i?ka(s.split("."),i.split(".")):s||i?s?-1:1:0})(e,t);return xa[n].includes(r)},xa={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},Aa=Object.keys(xa),Na=e=>{if(-1===Aa.indexOf(e))throw new Error(`Invalid operator, expected one of ${Aa.join("|")}`)};var Oa="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function La(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Pa,Ta,Ba,ja,Da,Ma={exports:{}},Ua={exports:{}};function Fa(){if(Ta)return Pa;Ta=1;var e=1e3,t=60*e,n=60*t,r=24*n,s=7*r,i=365.25*r;function o(e,t,n,r){var s=t>=1.5*n;return Math.round(e/n)+" "+r+(s?"s":"")}return Pa=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*i;case"weeks":case"week":case"w":return c*s;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(s){var i=Math.abs(s);if(i>=r)return o(s,i,r,"day");if(i>=n)return o(s,i,n,"hour");if(i>=t)return o(s,i,t,"minute");if(i>=e)return o(s,i,e,"second");return s+" ms"}(a):function(s){var i=Math.abs(s);if(i>=r)return Math.round(s/r)+"d";if(i>=n)return Math.round(s/n)+"h";if(i>=t)return Math.round(s/t)+"m";if(i>=e)return Math.round(s/e)+"s";return s+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}function Ra(){if(ja)return Ba;return ja=1,Ba=function(e){function t(e){let r,s,i,o=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),i=s-(r||s);n.diff=i,n.prev=r,n.curr=s,r=s,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,s)=>{if("%%"===r)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];r=i.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:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),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,]+/),s=r.length;for(n=0;n<s;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=Fa(),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},Ba}var Wa,Ga,Va,Ha,za,qa={exports:{}};function Ka(){return Ga||(Ga=1,Wa=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),s=t.indexOf("--");return-1!==r&&(-1===s||r<s)}),Wa}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?Ma.exports=(Da||(Da=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,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(s=r))})),t.splice(s,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=Ra()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Ua,Ua.exports)),Ua.exports):Ma.exports=(za||(za=1,function(e,t){const n=w,r=i;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:s}=this;if(s){const t=this.color,s="[3"+(t<8?t:"8;5;"+t),i=` ${s};1m${r} `;n[0]=i+n[0].split("\n").join("\n"+i),n.push(s+"m+"+e.exports.humanize(this.diff)+"")}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(Ha)return Va;Ha=1;const e=I,t=w,n=Ka(),{env:r}=process;let s;function i(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function o(t,i){if(0===s)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!i&&void 0===s)return 0;const o=s||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")?s=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(s=1),"FORCE_COLOR"in r&&(s="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),Va={supportsColor:function(e){return i(o(e,e&&e.isTTY))},stdout:i(o(!0,t.isatty(1))),stderr:i(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=Ra()(t);const{formatters:s}=e.exports;s.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},s.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(qa,qa.exports)),qa.exports);var Ja=La(Ma.exports);const Ya=e=>Ja(e),Xa=Date.now();let Za=Math.ceil(Xa/1e3);var Qa=()=>Za+=1;const ec=d(_(),"kemu-user-services"),tc=d(_(),"kemu-test-services"),nc="KMU-CB-v1";var rc;!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"}(rc||(rc={}));const sc=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>ca[e])):ca[e.type]}),ic=async e=>{try{return await g(e,"utf-8")}catch(e){return null}},oc=e=>{if(e&&e.startsWith(nc)){const t=e.slice(9),n=decodeURI(t);return Sa(n)}return null},ac=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(sc)}:{},...e.outputs?{outputs:e.outputs.map(sc)}:{}}))));const s={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(sc)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(sc)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},i=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const s of t.customWidgets){const t=await ic(d(e,s));if(!t){n(`Error loading custom widget file ${s}`);continue}const i=t.startsWith(nc)?t:`${nc}${t}`,o=oc(i);if(!o){n(`Custom widget file "${s}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(o).filter((e=>e.type===rc.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${s}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${s}" does not contain a top level widgetGroup`);continue}const l=c.state,u={name:l.name,color:l.color,description:l.description,contents:i,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}return r})(t,e,n?.log);if(i.length?s.customWidgets=i:delete s.customWidgets,s.variants?.length)for(const e of s.variants)if(e.svgIcon)try{const n=await g(d(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return s},cc=async e=>{try{return await m(e,v.F_OK),!0}catch{return!1}};let lc=null,uc=null;const dc=()=>lc||ec,pc=Ya("servicesManager"),hc={};let fc=null,gc=null,mc=null;class vc extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const yc=async e=>{try{return await m(e),!0}catch{return!1}},bc=async e=>{if(!fc)throw new Error('IPC config not set, call "setHubIpcConfig" first.');try{if(e.processor===ua.Javascript){pc(`Spawning service ${e.name} with sessionId ${e.sessionId}`);const t=u.join(e.path,"processor.js"),n=u.join(e.path,"processor.mjs"),r=await yc(t)?t:n,s=[`--sessionId=${e.sessionId.toString()}`,`--ipcSpace=${fc.appSpace}`,`--ipcId=${fc?.id}`,`--recipePath=${fc.recipePath||""}`];if(e.internal&&s.push("--internal=true"),!mc)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const i=await mc({name:e.name,version:e.version,requiredSecrets:e.requiredSecrets||{}}),o=Object.entries(e.requiredSecrets||{}).filter((([e,t])=>{const n=i[e];return null==n&&!t.optional})).map((([e])=>e));if(o?.length)throw new vc(`Missing required environment variables: ${o.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,n)=>{if(!gc)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const o=gc({args:[r,...s],options:{env:i}});o.stdout.on("data",(t=>{pc(`[${e.name}] - stdout: ${t}`)})),o.stderr.on("data",(t=>{pc(`[${e.name}] - stderr: ${t}`)})),o.on("exit",(t=>{pc(`[${e.name}] exited with code ${t}`)})),o.on("spawn",(()=>{pc(`[${e.name}] spawned with PID ${o.pid}`),t(o)})),o.on("error",(t=>{pc(`[${e.name}] error: ${t}`),n(new vc(`Error spawning service ${e.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.processor}`}catch(t){if(t instanceof vc)throw t;throw`Error spawning service ${e.name}: ${t}`}},Sc=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[ua.Javascript,ua.Executable,ua.Python].includes(e?.processor)?null:"Invalid processor"},wc=async(e,t)=>{const n=u.join(e,"manifest.json");if(!await yc(n)){const t=`Missing manifest for service ${e}. Aborting.`;return pc(t),{error:t}}const r=await g(n,"utf-8"),s=Sa(r),i=Sc(s);if(!s||i){const t=`Invalid service manifest [${e}]: ${i}. Aborting.`;return pc(t),{error:t}}let o;if(delete s.internal,t?.singleServiceName&&s.name!==t.singleServiceName){return{error:`Skipping service ${s.name} as it does not match the singleServiceName option`}}await Promise.all([(async()=>{if(s.widgetUI)try{o=await g(u.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${s.name}: ${e}`;return pc(t),{error:t}}})(),(async()=>{if(s.svgIcon){const t=await ic(u.join(e,s.svgIcon));if(!t){return{error:`Error loading icon for service ${s.name}`}}s.svgIcon=t}})(),(async()=>{if(s.subServices?.length)for(const t of s.subServices){const n=u.join(e,t),{error:r,service:i}=await wc(n);r?pc(`Error loading sub-service ${t}: ${r}`):i&&(i.info.parentService={name:s.name,version:s.version})}delete s.subServices})(),(async()=>{if(s.variants?.length)for(const t of s.variants)if(t.svgIcon)try{const n=await g(u.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){pc(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=Qa(),c=t?.fixedSession||a;pc(`Loaded service ${s.name} with sessionId ${c}`);const l=await ac(s,e,{widgetUIContents:o});return Ic(l),hc[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null},{service:hc[c]}},Ic=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=C("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},_c=async e=>{try{return e.childProcess=await bc(e.info),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return pc(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof vc?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},$c=e=>{const{path:t,...n}=e.info;return{...n}},Cc=()=>Object.values(hc).filter((e=>"running"===e.status)).map($c),kc=(e,t)=>{const n=Object.values(hc).find((n=>n.info.name===e&&n.info.version===t));if(!n)return null;if(n.info.internal)throw`Cannot stop internal service ${e}`;if(n.childProcess){pc(`Stopping service "${e} (v${t})"`);n.childProcess.kill("SIGINT")||pc(`Failed to stop service ${e}`)}return n.status="stopped",pc(`Service ${e} stopped`),n},Ec=e=>e.info.internal?e.info.path:u.join(e.info.path,".."),xc=e=>!!e.internal;var Ac={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await cc(e))return void pc(`Failed to load services from "${e}". Directory does not exist.`);const n=(await y(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));pc(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const s=n[r],i=u.join(e,s),{error:o,service:a}=await wc(`${i}${t?.internalServices?"":"/dist"}`,t);o&&pc(`Failed to load service ${i}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(pc("Initializing services"),!fc)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in hc){const n=hc[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?pc(`Service ${n.info.name} is in the noSpawningList. Skipping.`):_c(n)}pc("Services initialized")},setServiceStatus:(e,t)=>{const n=hc[e];return n?(n.status=t,!0):(pc(`Service with serviceId ${e} not found`),!1)},getActiveServices:Cc,getMatchingService:(e,t)=>{const n=Object.values(hc).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(Ea(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>hc[e]||null,killAllServices:()=>{for(const e in hc){const t=hc[e];if(t.childProcess)try{pc(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){pc(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await ac(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};hc[e]=r,Ic(hc[e].info)},setServiceManifest:(e,t,n)=>{const r=hc[e];if(!r)return pc(`Service with sessionId ${e} not found`),!1;const s=Sc(t);if(s)return pc(`Invalid manifest for service ${r.info.name}: ${s}`),!1;Ic(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(hc).filter((e=>e.devMode));for(const s of r)if(s.info.name===e&&s.status===n&&s.info.version===t)return s;return null},getInternalServices:()=>Cc().filter((e=>e.internal)),getAllServices:()=>Object.values(hc),stopService:kc,uninstallService:async(e,t)=>{pc(`Uninstalling service ${e} v${t}`);const n=kc(e,t);if(!n)return!1;pc(`Service ${e} stopped. Removing from disk...`);const r=Ec(n),s=dc();return r.startsWith(s)?(await b(r,{recursive:!0,force:!0}),pc(`Service ${e} successfully removed from disk`),(e=>{const t=hc[e];delete hc[e]})(n.info.sessionId),!0):(pc(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(hc).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{fc={...e}},loadAndLaunch:async(e,t,n)=>{const r=h(e,t),{error:s,service:i}=await wc(r);if(s||!i)return{errorMsg:s};try{i.info.internal=!!n,i.childProcess=await bc(i.info),i.status="started"}catch(e){i.status="error",e instanceof vc?(pc(`Service spawning error: ${e.message} (${e.code})`),i.errorMsg=e.message,i.errorCode=e.code):(pc(`Error launching service ${i.info.name}: ${e}`),i.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:i,errorCode:i.errorCode,errorMsg:i.errorMsg}},getServiceRootDirectory:Ec,setSpawnNodeFunction:e=>{gc=e},setGetSecretsFunction:e=>{mc=e},restartService:async(e,t)=>{pc(`Restarting service ${e} v${t}`);const n=kc(e,t);return!!n&&_c(n)},getFailedServices:()=>Object.values(hc).filter((e=>"error"===e.status)).map((e=>({...$c(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:xc,isNotInternalKemuService:e=>!xc(e),isNotDevService:e=>!e.devMode};class Nc{constructor(){}appspace="app.";socketRoot="/tmp/";id=I.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=I.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 Oc{constructor(e){e||(e=new Nc),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 Lc=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={}},Pc=La(Lc);var Tc=La((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 Bc{}class jc{}const Dc=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 Bc,t=jc){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 Bc}}())}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 Mc{constructor(){}on(e,t,n=!1){return Dc.string(e),Dc.function(t),Dc.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(Dc.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Dc.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){Dc.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)=>{Dc.string(e),Dc.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 Uc=new Oc;class Fc extends Mc{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Uc=new Oc(this.config)}Client=Fc;queue=new Tc;socket=!1;connect=Gc;emit=Rc;retriesRemaining=0;explicitlyDisconnected=!1}function Rc(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Pc;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Uc.format(n),this.config.sync?this.queue.add(Wc.bind(this,n)):this.socket.write(n)}function Wc(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Gc(){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=x.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=x.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(x.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=E.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=k.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=k.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)!=Uc.delimiter||-1==t.indexOf(Uc.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Uc.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Pc;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 Vc=new Oc;class Hc extends Mc{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Vc=new Oc(this.config),this.on("close",Kc.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=zc;broadcast=qc;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?x.unlink(this.path,Zc.bind(this)):Zc.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function zc(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Pc;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Vc.format(r),this.udp4||this.udp6)return e.address&&e.port?void this.server.write(r,e):(this.log("Attempting to emit to a single UDP socket without supplying socket address or port. Redispatching event as broadcast to all connected sockets"),void this.broadcast(t,n));e.write(r)}function qc(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Pc;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Vc.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 Kc(){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 Jc(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)==Vc.delimiter&&-1!=t.indexOf(Vc.delimiter))for(r.ipcBuffer="",t=Vc.parse(t);t.length>0;){let e=new Pc;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 Yc(e){this.publish("close",e)}function Xc(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",Yc.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",Jc.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 Zc(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=N.createSocket(this.udp4?"udp4":"udp6"),this.server.write=el.bind(this),this.server.on("listening",function(){Xc.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?Qc.bind(this)():this.server=k.createServer(Xc.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 Qc(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=x.readFileSync(this.config.tls.private):this.config.tls.key=x.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=x.readFileSync(this.config.tls.public):this.config.tls.cert=x.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=x.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(x.readFileSync(this.config.tls.trustedConnections[e]))}this.server=E.createServer(this.config.tls,Xc.bind(this))}function el(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 tl{constructor(){}config=new Nc;of={};server=!1;get connectTo(){return al}get connectToNet(){return cl}get disconnect(){return rl}get serve(){return sl}get serveNet(){return ol}get log(){return nl}set connectTo(e){return al}set connectToNet(e){return cl}set disconnect(e){return rl}set serve(e){return sl}set serveNet(e){return ol}set log(e){return nl}}function nl(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=i.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function rl(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 sl(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=il),this.server=new Hc(e,this.config,nl),this.server.on("start",t)}function il(){}function ol(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=il),this.server=new Hc(e,this.config,nl,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function al(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=il),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 Fc(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 cl(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=il),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 Fc(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 ll=new class extends tl{constructor(){super()}IPC=tl};var ul={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const dl=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),pl=e=>{try{return JSON.parse(e)}catch(e){return null}},hl="undefined"!=typeof window,fl={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},gl={protocolPrefix:4,txtLength:4},ml=Object.values(fl).reduce(((e,t)=>e+t),0),vl=Object.values(gl).reduce(((e,t)=>e+t),0),yl=["width","height","colorSpace"],bl=(e,t)=>{const n={},r=[];let s=0,i=Array.isArray(e)?[]:{};const o=(e,i)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,s=e instanceof Uint8Array,i=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":s?"Uint8Array":i?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${i}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,s=e instanceof Uint32Array,i=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":s?"Uint32Array":i?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${i}"`);for(const n in e)e.hasOwnProperty(n)||yl.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${i}`),t[n]=o(e[n],`${i.length?`${i}.`:""}${n}`);return t}return e}n[i]={index:s,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),s+=e.byteLength};i=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:i}:null},Sl=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let s=e;for(let e=0;e<r.length;e++){let t=r[e];const i=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(i){t=t.slice(1,-1);const i=parseInt(t,10);if(!Array.isArray(s))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?s[i]=n:(s[i]||(s[i]=r[e+1].startsWith("[")?[]:{}),s=s[i])}else o?s[t]=n:(s[t]||(s[t]=r[e+1].startsWith("[")?[]:{}),s=s[t])}return e},wl=(e,t,n)=>{const r="undefined"!=typeof Buffer,s=t instanceof Uint8Array;for(const i in n)if(n.hasOwnProperty(i)){const{index:o,length:a,binaryType:c}=n[i];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=s?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=s?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&&Sl(e,i,l)}return e},Il=e=>Ja(e),_l="KMSG",$l="KCMD",Cl=Il("klProtocol");var kl={encode:(e,t,n)=>{const r={json:e.json},s=bl(r.json,"Buffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=fl.protocolPrefix+fl.protocolVersion+fl.jsonLength+fl.binaryLength+fl.fromServiceId+fl.toServiceId+fl.sentAt+l+o,d=Buffer.alloc(u),p=Date.now();let h=0;return d.write(_l,h),h+=fl.protocolPrefix,d.writeUInt8(1,h),h+=fl.protocolVersion,d.writeUInt32LE(l,h),h+=fl.jsonLength,d.writeUInt32LE(o,h),h+=fl.binaryLength,d.writeUInt32LE(t,h),h+=fl.fromServiceId,d.writeUInt32LE(n,h),h+=fl.toServiceId,d.writeBigInt64LE(BigInt(p),h),h+=fl.sentAt,c.copy(d,h),h+=l,i&&o&&i.copy(d,h),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,fl.protocolPrefix);if(t+=fl.protocolPrefix,n!==_l)return null;if(e.byteLength<ml)return Cl(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=fl.protocolVersion;const s=e.readUInt32LE(t);t+=fl.jsonLength;const i=e.readUInt32LE(t);t+=fl.binaryLength;const o=e.readUInt32LE(t);t+=fl.fromServiceId;const a=e.readUInt32LE(t);t+=fl.toServiceId;const c=e.readBigInt64LE(t);t+=fl.sentAt;const l=s+i,u=e.subarray(t,t+l),d=e.subarray(0,ml);let p=null;return e.byteLength-ml-s-i>0&&(p=e.subarray(ml+s+i)),{header:{protocolVersion:r,jsonLength:s,binaryLength:i,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:p}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),s=pl(n);if(!s?.json)return Cl("Invalid JSON in KL message"),null;s.jsonBinaryMap&&r.byteLength&&wl(s.json,r,s.jsonBinaryMap);const i=Buffer.concat([e.headerPackage,t]);let o=i,a=null;const c=ml+e.jsonLength+e.binaryLength;return i.byteLength>c&&(a=i.subarray(c),o=i.subarray(0,c)),{message:{json:s.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<ml)return Cl("Invalid Header Size"),e;let n=0;return n+=fl.protocolPrefix,n+=fl.protocolVersion,n+=fl.jsonLength,n+=fl.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=fl.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,s=vl+r,i=Buffer.alloc(s);return i.write($l,t),t+=gl.protocolPrefix,i.writeUint32LE(r,t),t+=gl.txtLength,n.copy(i,t),i},decodeCommand:e=>{let t=0;if(e.byteLength<vl)return{command:null};const n=e.toString("utf-8",t,gl.protocolPrefix);if(t+=gl.protocolPrefix,n!==$l)return{command:null};const r=e.readUInt32LE(t);t+=gl.txtLength;const s=e.toString("utf-8",t,t+r),i=e.byteLength-vl-r;let o=null;i>0&&(o=e.subarray(vl+r));let a=0;return i<0&&(a=Math.abs(i)),{command:s,remainingData:o,missing:a}}};const El="KMSG",xl="KCMD",Al=Il("klProtocol"),Nl=new TextEncoder;var Ol={encode:(e,t,n)=>{const r={json:e.json},s=bl(e.json,"ArrayBuffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=Nl.encode(a),l=c.byteLength,u=new ArrayBuffer(fl.protocolPrefix+fl.protocolVersion+fl.jsonLength+fl.binaryLength+fl.fromServiceId+fl.toServiceId+fl.sentAt+l+o),d=new DataView(u),p=new Uint8Array(u),h=Date.now();let f=0;for(let e=0;e<4;++e)p[f++]=El.charCodeAt(e);return d.setUint8(f,1),f+=fl.protocolVersion,d.setUint32(f,l,!0),f+=fl.jsonLength,d.setUint32(f,o,!0),f+=fl.binaryLength,d.setUint32(f,t,!0),f+=fl.fromServiceId,d.setUint32(f,n,!0),f+=fl.toServiceId,d.setBigInt64(f,BigInt(h),!0),f+=fl.sentAt,p.set(c,f),f+=l,i&&o&&p.set(new Uint8Array(i),f),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<fl.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==El)return null;if(e.byteLength<ml)return Al.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const s=t.getUint8(n);n+=fl.protocolVersion;const i=t.getUint32(n,!0);n+=fl.jsonLength;const o=t.getUint32(n,!0);n+=fl.binaryLength;const a=t.getUint32(n,!0);n+=fl.fromServiceId;const c=t.getUint32(n,!0);n+=fl.toServiceId;const l=t.getBigInt64(n,!0);n+=fl.sentAt;const u=i+o,d=e.slice(n,n+u),p=new Uint8Array(e,0,ml);let h=null;if(e.byteLength-ml-i-o>0){h=new Uint8Array(e,ml+i+o).slice().buffer}return{header:{protocolVersion:s,jsonLength:i,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:p.slice().buffer},remaining:h}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,s=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,s),s+=r.byteLength;const i=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=pl(i);if(!a?.json)return Al.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&wl(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=ml+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<ml)return Al("Invalid Header Size"),e;let n=0;n+=fl.protocolPrefix,n+=fl.protocolVersion,n+=fl.jsonLength,n+=fl.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=fl.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Nl.encode(e),r=n.byteLength,s=new ArrayBuffer(vl+r),i=new DataView(s),o=new Uint8Array(s);for(let e=0;e<4;++e)o[t++]=xl.charCodeAt(e);return i.setUint32(t,r,!0),t+=gl.txtLength,o.set(n,t),s},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<vl)return{command:null};let r="";for(let e=0;e<gl.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==xl)return{command:null};const s=t.getUint32(n,!0);n+=gl.txtLength;const i=e.byteLength-vl-s,o=new Uint8Array(e,n,Math.min(s,e.byteLength-vl)),a=(new TextDecoder).decode(o);let c=null;i>0&&(c=e.slice(vl+s));let l=0;return i<0&&(l=Math.abs(i)),{command:a,remainingData:c,missing:l}}};const Ll=Il("klTransmissionManager"),Pl=()=>{const e=(t,n,r,s)=>{let i=n,o=null;const a=t instanceof ArrayBuffer;if(Ll(`RAW: ${t.toString()}`),!i||i.partialHeaderData){let c;if(a?(c=i?.partialHeaderData?new Uint8Array([...new Uint8Array(i.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=Ol.decodeHeader(c)):(c=i?.partialHeaderData?Buffer.concat([i.partialHeaderData,t]):t,o=kl.decodeHeader(c)),!o){const{command:t,missing:i,remainingData:o}=a?Ol.decodeCommand(c):kl.decodeCommand(c);return t?s({command:t,complete:!0,rawMessage:c}):Ll(i?`ERROR: Missing ${i} 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?(Ll(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,n,r,s)):void 0}if(o.partialHeader)return i={firstPackageAt:Date.now(),partialHeaderData:c},r(i);if(!o.header)return Ll(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=o.header;i={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:o.remaining}},r(i)}else i.header&&i.header.totalBytesReceived<i.header.totalBytesExpected&&(i.header.packages.push(t),i.header.totalBytesReceived+=t.byteLength,r(i));if(i.header&&i.header.totalBytesReceived>=i.header.totalBytesExpected){const t=Date.now()-i.header.sentAt.getTime(),n=Date.now()-i.firstPackageAt;Ll(`Received ${i.header.totalBytesReceived} of ${i.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?Ol.decodeFullKlMessage(i.header):kl.decodeFullKlMessage(i.header),c=i.header.totalBytesReceived,l=i.header.remaining;r(null),o&&s({klMessage:o.message,complete:!0,sourceServiceId:i.header.fromServiceId,targetServiceId:i.header.toServiceId,rawMessage:o.message.rawMessage});let u=l;if(o?.remaining&&(u=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),s=new Uint8Array(e),i=new Uint8Array(t),o=new Uint8Array(r);return o.set(s),o.set(i,s.length),r})(l,o.remaining):o.remaining:l?Buffer.concat([l,o.remaining]):o.remaining),u)return Ll(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,s)}};return e};ll.config={...ll.config,...ul};const Tl={info:Ya("ipcServer:info"),data:Ya("ipcServer:data")};let Bl,jl,Dl,Ml,Ul={};const Fl=Pl(),Rl=e=>{Ul[e]&&(Tl.info(`Client disconnected [${e}]`),delete Ul[e],jl&&jl(e))};var Wl=e=>(e?.ipcId&&(ll.config.id=e.ipcId),e?.ipcAppSpace&&(ll.config.appspace=e.ipcAppSpace),new Promise((e=>{ll.serve((()=>{Tl.info("IPC Server Initiated"),ll.server.on("data",((e,t)=>{const n=Ul[t.id];n?(Tl.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Fl(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Tl.data(`Received command from client [${t.id}]: ${e.command}`),void(Dl&&Dl(t.id,e.command,n));e.klMessage&&Ml&&Ml({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Tl.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),ll.server.on("connect",(e=>{const t=Qa();Tl.info(`New client connected. Registered as "${t}"`),e.id=t,Ul[t]={socket:e,activeMessage:null,disconnectHandler:()=>Rl(t)},e.on("close",Ul[t].disconnectHandler),Bl&&Bl(t)})),ll.server.on("disconnect",(e=>{Rl(e.id)})),ll.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),ll.server.start()}))),Gl=e=>{Bl=e},Vl=e=>{jl=e},Hl=e=>Ml=e,zl=(e,t)=>{const n=Ul[e];if(!n)return Tl.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=dl)return Tl.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=kl.encodeCommand(t);return n.socket.write(r),!0},ql=(e,t)=>{const n=Ul[e];return!!n&&(Tl.info(`Renaming socket id [${e}] to [${t}]`),delete Ul[e],n.socket.id=t,Ul[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Rl(t),n.socket.on("close",n.disconnectHandler),!0)},Kl=e=>{Dl=e};let Jl=kl;hl&&(Jl=Ol);var Yl,Xl=Jl;!function(e){e.FunctionNotFound="FNC_NOT_FOUND"}(Yl||(Yl={}));let Zl=Math.ceil(Date.now()/1e3);var Ql={exports:{}};const eu=["nodebuffer","arraybuffer","fragments"],tu="undefined"!=typeof Blob;tu&&eu.push("blob");var nu={BINARY_TYPES:eu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:ru}=nu,su=Buffer[Symbol.species];function iu(e,t,n,r,s){for(let i=0;i<s;i++)n[r+i]=e[i]^t[3&i]}function ou(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(Ql.exports={concat:function(e,t){if(0===e.length)return ru;if(1===e.length)return e[0];const n=Buffer.allocUnsafe(t);let r=0;for(let t=0;t<e.length;t++){const s=e[t];n.set(s,r),r+=s.length}return r<t?new su(n.buffer,n.byteOffset,r):n},mask:iu,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 su(t):ArrayBuffer.isView(t)?n=new su(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:ou},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Ql.exports.mask=function(t,n,r,s,i){i<48?iu(t,n,r,s,i):e.mask(t,n,r,s,i)},Ql.exports.unmask=function(t,n){t.length<32?ou(t,n):e.unmask(t,n)}}catch(e){}var au=Ql.exports;const cu=Symbol("kDone"),lu=Symbol("kRun");const uu=L,du=au,pu=class{constructor(e){this[cu]=()=>{this.pending--,this[lu]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[lu]()}[lu](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[cu])}}},{kStatusCode:hu}=nu,fu=Buffer[Symbol.species],gu=Buffer.from([0,0,255,255]),mu=Symbol("permessage-deflate"),vu=Symbol("total-length"),yu=Symbol("callback"),bu=Symbol("buffers"),Su=Symbol("error");let wu;var Iu=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,!wu){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;wu=new pu(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[yu];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){wu.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){wu.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]?uu.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=uu.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[mu]=this,this._inflate[vu]=0,this._inflate[bu]=[],this._inflate.on("error",Cu),this._inflate.on("data",$u)}this._inflate[yu]=n,this._inflate.write(e),t&&this._inflate.write(gu),this._inflate.flush((()=>{const e=this._inflate[Su];if(e)return this._inflate.close(),this._inflate=null,void n(e);const s=du.concat(this._inflate[bu],this._inflate[vu]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[vu]=0,this._inflate[bu]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),n(null,s)}))}_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]?uu.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=uu.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[vu]=0,this._deflate[bu]=[],this._deflate.on("data",_u)}this._deflate[yu]=n,this._deflate.write(e),this._deflate.flush(uu.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=du.concat(this._deflate[bu],this._deflate[vu]);t&&(e=new fu(e.buffer,e.byteOffset,e.length-4)),this._deflate[yu]=null,this._deflate[vu]=0,this._deflate[bu]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function _u(e){this[bu].push(e),this[vu]+=e.length}function $u(e){this[vu]+=e.length,this[mu]._maxPayload<1||this[vu]<=this[mu]._maxPayload?this[bu].push(e):(this[Su]=new RangeError("Max payload size exceeded"),this[Su].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Su][hu]=1009,this.removeListener("data",$u),this.reset())}function Cu(e){this[mu]._inflate=null,e[hu]=1007,this[yu](e)}var ku={exports:{}};const{isUtf8:Eu}=P,{hasBlob:xu}=nu;function Au(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(ku.exports={isBlob:function(e){return xu&&"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:Au,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]},Eu)ku.exports.isValidUTF8=function(e){return e.length<24?Au(e):Eu(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");ku.exports.isValidUTF8=function(t){return t.length<32?Au(t):e(t)}}catch(e){}var Nu=ku.exports;const{Writable:Ou}=O,Lu=Iu,{BINARY_TYPES:Pu,EMPTY_BUFFER:Tu,kStatusCode:Bu,kWebSocket:ju}=nu,{concat:Du,toArrayBuffer:Mu,unmask:Uu}=au,{isValidStatusCode:Fu,isValidUTF8:Ru}=Nu,Wu=Buffer[Symbol.species];var Gu=class extends Ou{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Pu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ju]=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 Wu(t.buffer,t.byteOffset+e,t.length-e),new Wu(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 Wu(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[Lu.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=Tu;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]&&Uu(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[Lu.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?Du(n,t):"arraybuffer"===this._binaryType?Mu(Du(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=Du(n,t);if(!this._skipUTF8Validation&&!Ru(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,Tu),this.end();else{const n=e.readUInt16BE(0);if(!Fu(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Wu(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ru(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,s){this._loop=!1,this._errored=!0;const i=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,this.createError),i.code=s,i[Bu]=r,i}};const{randomFillSync:Vu}=$,Hu=Iu,{EMPTY_BUFFER:zu,kWebSocket:qu,NOOP:Ku}=nu,{isBlob:Ju,isValidStatusCode:Yu}=Nu,{mask:Xu,toBuffer:Zu}=au,Qu=Symbol("kByteLength"),ed=Buffer.alloc(4),td=8192;let nd,rd=td;var sd=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=Ku,this[qu]=void 0}static frame(e,t){let n,r,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||ed,t.generateMask?t.generateMask(n):(rd===td&&(void 0===nd&&(nd=Buffer.alloc(td)),Vu(nd,0,td),rd=0),n[0]=nd[rd++],n[1]=nd[rd++],n[2]=nd[rd++],n[3]=nd[rd++]),o=!(n[0]|n[1]|n[2]|n[3]),i=6),"string"==typeof e?r=t.mask&&!o||void 0===t[Qu]?(e=Buffer.from(e)).length:t[Qu]:(r=e.length,s=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(i+=8,a=127):r>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(s?r+i:i);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[i-4]=n[0],c[i-3]=n[1],c[i-2]=n[2],c[i-1]=n[3],o?[c,e]:s?(Xu(e,n,c,i,r),[c]):(Xu(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,s){let i;if(void 0===t)i=zu;else{if("number"!=typeof t||!Yu(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");i=Buffer.allocUnsafe(2+e),i.writeUInt16BE(t,0),"string"==typeof n?i.write(n,2):i.set(n,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(t,0)}const o={[Qu]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(e.frame(i,o),s)}ping(t,n,r){let s,i;if("string"==typeof t?(s=Buffer.byteLength(t),i=!1):Ju(t)?(s=t.size,i=!1):(s=(t=Zu(t)).length,i=Zu.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Qu]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Ju(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 s,i;if("string"==typeof t?(s=Buffer.byteLength(t),i=!1):Ju(t)?(s=t.size,i=!1):(s=(t=Zu(t)).length,i=Zu.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Qu]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Ju(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[Hu.extensionName];let s,i,o=t.binary?2:1,a=t.compress;"string"==typeof e?(s=Buffer.byteLength(e),i=!1):Ju(e)?(s=e.size,i=!1):(s=(e=Zu(e)).length,i=Zu.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=r._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0);const c={[Qu]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:a};Ju(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,s){this._bufferedBytes+=r[Qu],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(id,this,e,s)}this._bufferedBytes-=r[Qu];const i=Zu(t);n?this.dispatch(i,n,r,s):(this._state=0,this.sendFrame(e.frame(i,r),s),this.dequeue())})).catch((e=>{process.nextTick(od,this,e,s)}))}dispatch(t,n,r,s){if(!n)return void this.sendFrame(e.frame(t,r),s);const i=this._extensions[Hu.extensionName];this._bufferedBytes+=r[Qu],this._state=1,i.compress(t,r.fin,((t,n)=>{if(this._socket.destroyed){id(this,new Error("The socket was closed while data was being compressed"),s)}else this._bufferedBytes-=r[Qu],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),s),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Qu],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Qu],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 id(e,t,n){"function"==typeof n&&n(t);for(let n=0;n<e._queue.length;n++){const r=e._queue[n],s=r[r.length-1];"function"==typeof s&&s(t)}}function od(e,t,n){id(e,t,n),e.onerror(t)}const{kForOnEventAttribute:ad,kListener:cd}=nu,ld=Symbol("kCode"),ud=Symbol("kData"),dd=Symbol("kError"),pd=Symbol("kMessage"),hd=Symbol("kReason"),fd=Symbol("kTarget"),gd=Symbol("kType"),md=Symbol("kWasClean");class vd{constructor(e){this[fd]=null,this[gd]=e}get target(){return this[fd]}get type(){return this[gd]}}Object.defineProperty(vd.prototype,"target",{enumerable:!0}),Object.defineProperty(vd.prototype,"type",{enumerable:!0});class yd extends vd{constructor(e,t={}){super(e),this[ld]=void 0===t.code?0:t.code,this[hd]=void 0===t.reason?"":t.reason,this[md]=void 0!==t.wasClean&&t.wasClean}get code(){return this[ld]}get reason(){return this[hd]}get wasClean(){return this[md]}}Object.defineProperty(yd.prototype,"code",{enumerable:!0}),Object.defineProperty(yd.prototype,"reason",{enumerable:!0}),Object.defineProperty(yd.prototype,"wasClean",{enumerable:!0});class bd extends vd{constructor(e,t={}){super(e),this[dd]=void 0===t.error?null:t.error,this[pd]=void 0===t.message?"":t.message}get error(){return this[dd]}get message(){return this[pd]}}Object.defineProperty(bd.prototype,"error",{enumerable:!0}),Object.defineProperty(bd.prototype,"message",{enumerable:!0});class Sd extends vd{constructor(e,t={}){super(e),this[ud]=void 0===t.data?null:t.data}get data(){return this[ud]}}Object.defineProperty(Sd.prototype,"data",{enumerable:!0});const wd={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[ad]&&r[cd]===t&&!r[ad])return;let r;if("message"===e)r=function(e,n){const r=new Sd("message",{data:n?e:e.toString()});r[fd]=this,_d(t,this,r)};else if("close"===e)r=function(e,n){const r=new yd("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[fd]=this,_d(t,this,r)};else if("error"===e)r=function(e){const n=new bd("error",{error:e,message:e.message});n[fd]=this,_d(t,this,n)};else{if("open"!==e)return;r=function(){const e=new vd("open");e[fd]=this,_d(t,this,e)}}r[ad]=!!n[ad],r[cd]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[cd]===t&&!n[ad]){this.removeListener(e,n);break}}};var Id={CloseEvent:yd,ErrorEvent:bd,Event:vd,EventTarget:wd,MessageEvent:Sd};function _d(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:$d}=Nu;function Cd(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var kd={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,s=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,u=-1,d=0;for(;d<e.length;d++)if(l=e.charCodeAt(d),void 0===n)if(-1===u&&1===$d[l])-1===c&&(c=d);else if(0===d||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);const r=e.slice(c,u);44===l?(Cd(t,r,s),s=Object.create(null)):n=r,c=u=-1}}else-1===u&&-1!==c&&(u=d);else if(void 0===r)if(-1===u&&1===$d[l])-1===c&&(c=d);else if(32===l||9===l)-1===u&&-1!==c&&(u=d);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d),Cd(s,e.slice(c,u),!0),44===l&&(Cd(t,n,s),s=Object.create(null),n=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${d}`);r=e.slice(c,d),c=u=-1}else if(o){if(1!==$d[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:i||(i=!0),o=!1}else if(a)if(1===$d[l])-1===c&&(c=d);else if(34===l&&-1!==c)a=!1,u=d;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${d}`);o=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===$d[l])-1===c&&(c=d);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);let o=e.slice(c,u);i&&(o=o.replace(/\\/g,""),i=!1),Cd(s,r,o),44===l&&(Cd(t,n,s),s=Object.create(null),n=void 0),r=void 0,c=u=-1}}else-1===u&&(u=d);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===u&&(u=d);const p=e.slice(c,u);return void 0===n?Cd(t,p,s):(void 0===r?Cd(s,p,!0):Cd(s,r,i?p.replace(/\\/g,""):p),Cd(t,n,s)),t}};const Ed=T,xd=B,Ad=j,Nd=k,Od=E,{randomBytes:Ld,createHash:Pd}=$,{URL:Td}=D,Bd=Iu,jd=Gu,Dd=sd,{isBlob:Md}=Nu,{BINARY_TYPES:Ud,EMPTY_BUFFER:Fd,GUID:Rd,kForOnEventAttribute:Wd,kListener:Gd,kStatusCode:Vd,kWebSocket:Hd,NOOP:zd}=nu,{EventTarget:{addEventListener:qd,removeEventListener:Kd}}=Id,{format:Jd,parse:Yd}=kd,{toBuffer:Xd}=au,Zd=3e4,Qd=Symbol("kAborted"),ep=[8,13],tp=["CONNECTING","OPEN","CLOSING","CLOSED"],np=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let rp=class e extends Ed{constructor(t,n,r){super(),this._binaryType=Ud[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Fd,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]),ip(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ud.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 s=new jd({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Dd(t,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=t,s[Hd]=this,i[Hd]=this,t[Hd]=this,s.on("conclude",dp),s.on("drain",pp),s.on("error",hp),s.on("message",gp),s.on("ping",mp),s.on("pong",vp),i.onerror=bp,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",wp),t.on("data",Ip),t.on("end",_p),t.on("error",$p),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[Bd.extensionName]&&this._extensions[Bd.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())})),Sp(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";lp(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||Fd,n,r)):up(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||Fd,n,r)):up(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 up(this,t,r);const s={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Bd.extensionName]||(s.compress=!1),this._sender.send(t||Fd,s,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";lp(this,this._req,e)}}};Object.defineProperty(rp,"CONNECTING",{enumerable:!0,value:tp.indexOf("CONNECTING")}),Object.defineProperty(rp.prototype,"CONNECTING",{enumerable:!0,value:tp.indexOf("CONNECTING")}),Object.defineProperty(rp,"OPEN",{enumerable:!0,value:tp.indexOf("OPEN")}),Object.defineProperty(rp.prototype,"OPEN",{enumerable:!0,value:tp.indexOf("OPEN")}),Object.defineProperty(rp,"CLOSING",{enumerable:!0,value:tp.indexOf("CLOSING")}),Object.defineProperty(rp.prototype,"CLOSING",{enumerable:!0,value:tp.indexOf("CLOSING")}),Object.defineProperty(rp,"CLOSED",{enumerable:!0,value:tp.indexOf("CLOSED")}),Object.defineProperty(rp.prototype,"CLOSED",{enumerable:!0,value:tp.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(rp.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(rp.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[Wd])return t[Gd];return null},set(t){for(const t of this.listeners(e))if(t[Wd]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[Wd]:!0})}})})),rp.prototype.addEventListener=qd,rp.prototype.removeEventListener=Kd;var sp=rp;function ip(e,t,n,r){const s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:ep[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=s.autoPong,!ep.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${ep.join(", ")})`);let i;if(t instanceof Td)i=t;else try{i=new Td(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===i.protocol?i.protocol="ws:":"https:"===i.protocol&&(i.protocol="wss:"),e._url=i.href;const o="wss:"===i.protocol,a="ws+unix:"===i.protocol;let c;if("ws:"===i.protocol||o||a?a&&!i.pathname?c="The URL's pathname is empty":i.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 op(e,t)}const l=o?443:80,u=Ld(16).toString("base64"),d=o?xd.request:Ad.request,p=new Set;let h,f;if(s.createConnection=s.createConnection||(o?cp:ap),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(h=new Bd(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Jd({[Bd.extensionName]:h.offer()})),n.length){for(const e of n){if("string"!=typeof e||!np.test(e)||p.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(e)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?s.socketPath:i.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&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),f=e._req=d(s),e._redirects&&e.emit("redirect",e.url,f)}else f=e._req=d(s);s.timeout&&f.on("timeout",(()=>{lp(e,f,"Opening handshake has timed out")})),f.on("error",(t=>{null===f||f[Qd]||(f=e._req=null,op(e,t))})),f.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void lp(e,f,"Maximum redirects exceeded");let i;f.abort();try{i=new Td(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void op(e,n)}ip(e,i,n,r)}else e.emit("unexpected-response",f,i)||lp(e,f,`Unexpected server response: ${i.statusCode}`)})),f.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==rp.CONNECTING)return;f=e._req=null;const i=t.headers.upgrade;if(void 0===i||"websocket"!==i.toLowerCase())return void lp(e,n,"Invalid Upgrade header");const o=Pd("sha1").update(u+Rd).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void lp(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 lp(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!h){return void lp(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Yd(l)}catch(t){return void lp(e,n,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==Bd.extensionName){return void lp(e,n,"Server indicated an extension that was not requested")}try{h.accept(t[Bd.extensionName])}catch(t){return void lp(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Bd.extensionName]=h}e.setSocket(n,r,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),s.finishRequest?s.finishRequest(f,e):f.end()}function op(e,t){e._readyState=rp.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function ap(e){return e.path=e.socketPath,Nd.connect(e)}function cp(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Nd.isIP(e.host)?"":e.host),Od.connect(e)}function lp(e,t,n){e._readyState=rp.CLOSING;const r=new Error(n);Error.captureStackTrace(r,lp),t.setHeader?(t[Qd]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(op,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function up(e,t,n){if(t){const n=Md(t)?t.size:Xd(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${tp[e.readyState]})`);process.nextTick(n,t)}}function dp(e,t){const n=this[Hd];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[Hd]&&(n._socket.removeListener("data",Ip),process.nextTick(yp,n._socket),1005===e?n.close():n.close(e,t))}function pp(){const e=this[Hd];e.isPaused||e._socket.resume()}function hp(e){const t=this[Hd];void 0!==t._socket[Hd]&&(t._socket.removeListener("data",Ip),process.nextTick(yp,t._socket),t.close(e[Vd])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function fp(){this[Hd].emitClose()}function gp(e,t){this[Hd].emit("message",e,t)}function mp(e){const t=this[Hd];t._autoPong&&t.pong(e,!this._isServer,zd),t.emit("ping",e)}function vp(e){this[Hd].emit("pong",e)}function yp(e){e.resume()}function bp(e){const t=this[Hd];t.readyState!==rp.CLOSED&&(t.readyState===rp.OPEN&&(t._readyState=rp.CLOSING,Sp(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Sp(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),Zd)}function wp(){const e=this[Hd];let t;this.removeListener("close",wp),this.removeListener("data",Ip),this.removeListener("end",_p),e._readyState=rp.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Hd]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",fp),e._receiver.on("finish",fp))}function Ip(e){this[Hd]._receiver.write(e)||this.pause()}function _p(){const e=this[Hd];e._readyState=rp.CLOSING,e._receiver.end(),this.end()}function $p(){const e=this[Hd];this.removeListener("error",$p),this.on("error",zd),e&&(e._readyState=rp.CLOSING,this.destroy())}const{tokenChars:Cp}=Nu;var kp={parse:function(e){const t=new Set;let n=-1,r=-1,s=0;for(;s<e.length;s++){const i=e.charCodeAt(s);if(-1===r&&1===Cp[i])-1===n&&(n=s);else if(0===s||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${s}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${s}`);-1===r&&(r=s);const i=e.slice(n,r);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),n=r=-1}}else-1===r&&-1!==n&&(r=s)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const i=e.slice(n,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const Ep=T,xp=j,{createHash:Ap}=$,Np=kd,Op=Iu,Lp=kp,Pp=sp,{GUID:Tp,kWebSocket:Bp}=nu,jp=/^[+/0-9A-Za-z]{22}==$/;var Dp=class extends Ep{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:Pp,...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=xp.createServer(((e,t)=>{const n=xp.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(Mp,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(Mp,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Mp(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",Up);const s=e.headers["sec-websocket-key"],i=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Rp(this,e,t,405,"Invalid HTTP method")}if(void 0===i||"websocket"!==i.toLowerCase()){return void Rp(this,e,t,400,"Invalid Upgrade header")}if(void 0===s||!jp.test(s)){return void Rp(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void Rp(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Fp(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=Lp.parse(a)}catch(n){return void Rp(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&void 0!==l){const n=new Op(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Np.parse(l);e[Op.extensionName]&&(n.accept(e[Op.extensionName]),u[Op.extensionName]=n)}catch(n){return void Rp(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const i={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(i,((i,o,a,l)=>{if(!i)return Fp(t,o||401,a,l);this.completeUpgrade(u,s,c,e,t,n,r)}));if(!this.options.verifyClient(i))return Fp(t,401)}this.completeUpgrade(u,s,c,e,t,n,r)}completeUpgrade(e,t,n,r,s,i,o){if(!s.readable||!s.writable)return s.destroy();if(s[Bp])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Fp(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ap("sha1").update(t+Tp).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[Op.extensionName]){const t=e[Op.extensionName].params,n=Np.format({[Op.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${n}`),c._extensions=e}this.emit("headers",a,r),s.write(a.concat("\r\n").join("\r\n")),s.removeListener("error",Up),c.setSocket(s,i,{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(Mp,this)}))),o(c,r)}};function Mp(e){e._state=2,e.emit("close")}function Up(){this.destroy()}function Fp(e,t,n,r){n=n||xp.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} ${xp.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function Rp(e,t,n,r,s){if(e.listenerCount("wsClientError")){const r=new Error(s);Error.captureStackTrace(r,Rp),e.emit("wsClientError",r,n,t)}else Fp(n,r,s)}var Wp=La(Dp);const Gp=Ya("websocketServer"),Vp={},Hp=Pl();let zp,qp,Kp,Jp,Yp;const Xp=e=>{const t=Vp[e];t&&t.socket.close()};var Zp={startServer:e=>{Yp=new Wp({port:e,maxPayload:104857600}),Yp.on("connection",(e=>{const t=Qa();Gp(`New client connected. Registered as "${t}"`),e.id=t,Vp[t]={socket:e,activeMessage:null},zp&&zp(t),e.on("message",(t=>{if(t instanceof Buffer){const n=Vp[e.id];Hp(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),Gp(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},s=()=>{Xp(n.socket.id)};if(t.command)return Gp(`Received command from client [${n.socket.id}]: ${t.command}`),void(Kp&&Kp(n.socket.id,t.command,r,s));t.klMessage&&Jp&&Jp({send:r,terminateWebsocket:s,websocketId:n.socket.id,transmission:{sourceServiceId:t.sourceServiceId??-1,targetServiceId:t.targetServiceId??-1,rawMessage:t.rawMessage},json:t.klMessage.json})}))}})),e.on("close",(()=>{Gp(`Client disconnected: ${e.id}`),qp&&qp(e.id),delete Vp[e.id]})),e.on("error",(()=>{Gp(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},stopServer:()=>{Yp.close((()=>{console.log("WebSocket server stopped")}))},onClientConnected:e=>{zp=e},onClientDisconnected:e=>{qp=e},onClientCommand:e=>{Kp=e},sendCommand:(e,t)=>{const n=Vp[e];if(!n)return Gp(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=dl)return Gp("Message is too long to be a command. Use sendMessage instead."),!1;const r=kl.encodeCommand(t);return n.socket.send(r),!0},onMessageReceived:e=>Jp=e,terminateConnection:Xp};const Qp=Ya("stopService"),eh=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Ac.getAllServiceVersions(t);Qp(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Ac.stopService(e.info.name,e.info.version);const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},th=Ya("removeService"),nh=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Ac.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),th(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Ac.uninstallService(e.info.name,e.info.version);const s=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[s]})},rh=Ya("launchService"),sh=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 s=dc();rh(`Loading service ${t}@${n} from ${s}`);const{errorMsg:i,service:o,errorCode:a}=await Ac.loadAndLaunch(s,r,!1);if(i||"started"!==o?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${i||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,u=async()=>{const r=o.status;return"running"===r?(rh(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(rh(`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"}):(rh("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return rh(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},ih=Ya("getMatchingServices"),oh=async e=>{const t=e.args[0],n=[],r=[];ih(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:s}of t){const t=Ac.getMatchingService(e,s);t?n.push({name:e,version:s,installationPath:Ac.getServiceRootDirectory(t)}):r.push({name:e,version:s})}ih(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},ah=Ya("getSecretsValues");let ch;var lh=async e=>{const t=e.args[0].services;if(!ch)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");ah(`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 ch({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})},uh=e=>{ch=e};const dh=Ya("getMappedSecrets");let ph;var hh=async e=>{const t=e.args[0].services;dh(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await ph(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})},fh=e=>{ph=e};const gh=Ya("getServiceContents"),mh=({reply:e,args:t})=>{const[n]=t;gh(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Ac.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}]})}gh(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})},vh=process.env.KEMU_API_URL;if(!vh)throw new Error("Invalid build configuration, missing KEMU_API_URL");const yh=async e=>{const{data:t,error:n}=await(async(e,t)=>{try{const n=await fetch(e,{method:"POST",body:JSON.stringify(t)});return n.ok?{data:await n.json(),statusCode:n.status,success:!0}:{statusCode:n.status,error:await n.text(),success:!1}}catch(e){return{statusCode:500,error:e instanceof Error?e.message:"Internal server error",success:!1}}})(`${vh}/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"}},bh={},Sh=async e=>{const t=(e=>{const t=bh[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:s}=await yh(e);return n&&(bh[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:s}},wh=Ya("activeClients");let Ih={},_h={};const $h=(e,t)=>`${e}_${t}`,Ch=e=>Ih[e]||null,kh=(e,t)=>{const n=$h(e,t);return _h[n]||[]},Eh=()=>{for(const e in Ih){const t=Ih[e];if(t?.transport===fa.WS){const e=kl.encodeCommand(da.ServicesListChanged);t.send(e)}}},xh=async e=>{const t=[],{serviceSessionId:n,transport:r,send:s,terminateFn:i,extraInfo:o,isDevClient:a}=e,c=e=>{console.warn(e),i&&i()};if(r===fa.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 Sh(o.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&wh(`Unable to validate API Key, usage will be limited. SessionId: ${n}`)}Ih[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:s,extraInfo:o,terminate:()=>{i&&i()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=$h(e.serviceName,e.version);_h[r]=_h[r]||[];return _h[r].some((e=>e.serviceId===n))||_h[r].push({sendFn:s,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 s=$h(e.serviceName,e.version),i=_h[s]?.findIndex((e=>e.serviceId===n));if(-1!==i&&(_h[s].splice(i,1),!_h[s].length)){const t=Ac.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=Ch(t.info.sessionId);e?.extraInfo.ipcSocketId&&zl(e?.extraInfo.ipcSocketId,da.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=$h(e.targetService.serviceName,e.targetService.version),r=_h[t].findIndex((e=>e.serviceId===n));-1!==r&&_h[t].splice(r,1)}t.length=0}},r===fa.IPC&&(Eh(),Nh(n))},Ah=()=>{const e=Object.values(Ih);for(const t of e)if(t.transport===fa.IPC){const e=t.extraInfo.ipcSocketId,n=Ac.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){kh(n.info.name,n.info.version).length||e&&zl(e,da.BroadcastEnd)}}},Nh=e=>{const t=Ac.getServiceBySessionId(e);if(t?.info.eventEmitter){if(kh(t.info.name,t.info.version).length){const t=Ch(e);t?.extraInfo.ipcSocketId&&zl(t?.extraInfo.ipcSocketId,da.BroadcastStart)}}},Oh=e=>{const t=Ih[e];delete Ih[e],t.transport===fa.IPC?Eh():(t.removeAllSubscriptions(),Ah())},Lh=Ya("ipc:handleIpcClientCommand"),Ph=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(da.AcknowledgeResponse)){const n=e.split(":"),r=parseInt(n[1]),s=parseInt(n[2]);return t&&t(r,isNaN(s)?void 0:s),!0}return!1})(t,((e,t)=>{if(!e)return void Lh(`Ignoring ACK response from IPC service ${e} with no service id`);Lh(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(ql(e,t),r=t);let s=!1;t&&(s=Ac.setServiceStatus(t,"running")),s?xh({serviceSessionId:t||e,transport:fa.IPC,send:n,extraInfo:{ipcSocketId:t}}):zl(r,da.SendManifest)}));!r&&Lh(`Received unknown command [${t}] from service ${e}`)};let Th={};U.platform();const Bh=async e=>{const t=e.args[0];if(Th.chooseDirectory)try{const n=await Th.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(Th.chooseFile)try{const n=await Th.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"})},Dh=e=>{Th=e};var Mh={},Uh={},Fh={};function Rh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Wh(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Gh(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Vh(e,...t){if(!Gh(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 Hh(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Rh(e.outputLen),Rh(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){Vh(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(Fh,"__esModule",{value:!0}),Fh.output=Fh.exists=Fh.hash=Fh.bytes=Fh.bool=Fh.number=Fh.isBytes=void 0,Fh.number=Rh,Fh.bool=Wh,Fh.isBytes=Gh,Fh.bytes=Vh,Fh.hash=Hh,Fh.exists=zh,Fh.output=qh;const Kh={number:Rh,bool:Wh,bytes:Vh,hash:Hh,exists:zh,output:qh};Fh.default=Kh;var Jh={};Object.defineProperty(Jh,"__esModule",{value:!0}),Jh.add5L=Jh.add5H=Jh.add4H=Jh.add4L=Jh.add3H=Jh.add3L=Jh.add=Jh.rotlBL=Jh.rotlBH=Jh.rotlSL=Jh.rotlSH=Jh.rotr32L=Jh.rotr32H=Jh.rotrBL=Jh.rotrBH=Jh.rotrSL=Jh.rotrSH=Jh.shrSL=Jh.shrSH=Jh.toBig=Jh.split=Jh.fromBig=void 0;const Yh=BigInt(2**32-1),Xh=BigInt(32);function Zh(e,t=!1){return t?{h:Number(e&Yh),l:Number(e>>Xh&Yh)}:{h:0|Number(e>>Xh&Yh),l:0|Number(e&Yh)}}function Qh(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let s=0;s<e.length;s++){const{h:i,l:o}=Zh(e[s],t);[n[s],r[s]]=[i,o]}return[n,r]}Jh.fromBig=Zh,Jh.split=Qh;const ef=(e,t)=>BigInt(e>>>0)<<Xh|BigInt(t>>>0);Jh.toBig=ef;const tf=(e,t,n)=>e>>>n;Jh.shrSH=tf;const nf=(e,t,n)=>e<<32-n|t>>>n;Jh.shrSL=nf;const rf=(e,t,n)=>e>>>n|t<<32-n;Jh.rotrSH=rf;const sf=(e,t,n)=>e<<32-n|t>>>n;Jh.rotrSL=sf;const of=(e,t,n)=>e<<64-n|t>>>n-32;Jh.rotrBH=of;const af=(e,t,n)=>e>>>n-32|t<<64-n;Jh.rotrBL=af;const cf=(e,t)=>t;Jh.rotr32H=cf;const lf=e=>e;Jh.rotr32L=lf;const uf=(e,t,n)=>e<<n|t>>>32-n;Jh.rotlSH=uf;const df=(e,t,n)=>t<<n|e>>>32-n;Jh.rotlSL=df;const pf=(e,t,n)=>t<<n-32|e>>>64-n;Jh.rotlBH=pf;const hf=(e,t,n)=>e<<n-32|t>>>64-n;function ff(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}}Jh.rotlBL=hf,Jh.add=ff;const gf=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);Jh.add3L=gf;const mf=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;Jh.add3H=mf;const vf=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);Jh.add4L=vf;const yf=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0;Jh.add4H=yf;const bf=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0);Jh.add5L=bf;const Sf=(e,t,n,r,s,i)=>t+n+r+s+i+(e/2**32|0)|0;Jh.add5H=Sf;const wf={fromBig:Zh,split:Qh,toBig:ef,shrSH:tf,shrSL:nf,rotrSH:rf,rotrSL:sf,rotrBH:of,rotrBL:af,rotr32H:cf,rotr32L:lf,rotlSH:uf,rotlSL:df,rotlBH:pf,rotlBL:hf,add:ff,add3L:gf,add3H:mf,add4L:vf,add4H:yf,add5H:Sf,add5L:bf};Jh.default=wf;var If={},_f={};Object.defineProperty(_f,"__esModule",{value:!0}),_f.crypto=void 0,_f.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
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=_f,n=Fh;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 s={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function i(e){return e>=s._0&&e<=s._9?e-s._0:e>=s._A&&e<=s._F?e-(s._A-10):e>=s._a&&e<=s._f?e-(s._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,s=0;t<n;t++,s+=2){const n=i(e.charCodeAt(s)),o=i(e.charCodeAt(s+1));if(void 0===n||void 0===o){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}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 s=Date.now();for(let i=0;i<t;i++){r(i);const t=Date.now()-s;t>=0&&t<n||(await(0,e.nextTick)(),s+=t)}},e.utf8ToBytes=o,e.toBytes=a,e.concatBytes=function(...e){let t=0;for(let r=0;r<e.length;r++){const s=e[r];(0,n.bytes)(s),t+=s.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.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")}}(If),Object.defineProperty(Uh,"__esModule",{value:!0}),Uh.shake256=Uh.shake128=Uh.keccak_512=Uh.keccak_384=Uh.keccak_256=Uh.keccak_224=Uh.sha3_512=Uh.sha3_384=Uh.sha3_256=Uh.sha3_224=Uh.Keccak=Uh.keccakP=void 0;const $f=Fh,Cf=Jh,kf=If,Ef=[],xf=[],Af=[],Nf=BigInt(0),Of=BigInt(1),Lf=BigInt(2),Pf=BigInt(7),Tf=BigInt(256),Bf=BigInt(113);for(let e=0,t=Of,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Ef.push(2*(5*r+n)),xf.push((e+1)*(e+2)/2%64);let s=Nf;for(let e=0;e<7;e++)t=(t<<Of^(t>>Pf)*Bf)%Tf,t&Lf&&(s^=Of<<(Of<<BigInt(e))-Of);Af.push(s)}const[jf,Df]=(0,Cf.split)(Af,!0),Mf=(e,t,n)=>n>32?(0,Cf.rotlBH)(e,t,n):(0,Cf.rotlSH)(e,t,n),Uf=(e,t,n)=>n>32?(0,Cf.rotlBL)(e,t,n):(0,Cf.rotlSL)(e,t,n);function Ff(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,s=(t+2)%10,i=n[s],o=n[s+1],a=Mf(i,o,1)^n[r],c=Uf(i,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],s=e[3];for(let n=0;n<24;n++){const r=xf[n],i=Mf(t,s,r),o=Uf(t,s,r),a=Ef[n];t=e[a],s=e[a+1],e[a]=i,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]^=Df[r]}n.fill(0)}Uh.keccakP=Ff;class Rf extends kf.Hash{constructor(e,t,n,r=!1,s=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,$f.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,kf.u32)(this.state)}keccak(){kf.isLE||(0,kf.byteSwap32)(this.state32),Ff(this.state32,this.rounds),kf.isLE||(0,kf.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,$f.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,kf.toBytes)(e)).length;for(let s=0;s<r;){const i=Math.min(t-this.pos,r-s);for(let t=0;t<i;t++)n[this.pos++]^=e[s++];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,$f.exists)(this,!1),(0,$f.bytes)(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,s=e.length;r<s;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,s-r);e.set(t.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=i}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,$f.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,$f.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:s,enableXOF:i}=this;return e||(e=new Rf(t,n,r,i,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=r,e.enableXOF=i,e.destroyed=this.destroyed,e}}Uh.Keccak=Rf;const Wf=(e,t,n)=>(0,kf.wrapConstructor)((()=>new Rf(t,e,n)));Uh.sha3_224=Wf(6,144,28),Uh.sha3_256=Wf(6,136,32),Uh.sha3_384=Wf(6,104,48),Uh.sha3_512=Wf(6,72,64),Uh.keccak_224=Wf(1,144,28),Uh.keccak_256=Wf(1,136,32),Uh.keccak_384=Wf(1,104,48),Uh.keccak_512=Wf(1,72,64);const Gf=(e,t,n)=>(0,kf.wrapXOFConstructorWithOpts)(((r={})=>new Rf(t,e,void 0===r.dkLen?n:r.dkLen,!0)));Uh.shake128=Gf(31,168,16),Uh.shake256=Gf(31,136,32);const{sha3_512:Vf}=Uh,Hf=(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(Vf(e)).toString(36).slice(1),Kf=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),Jf=({globalObj:e=(void 0!==Oa?Oa:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Hf(32,t):Hf(32,t);return qf(r).substring(0,32)},Yf=e=>()=>e++,Xf=({random:e=Math.random,counter:t=Yf(Math.floor(476782367*e())),length:n=24,fingerprint:r=Jf({random:e})}={})=>function(){const s=(e=>Kf[Math.floor(e()*Kf.length)])(e),i=Date.now().toString(36),o=t().toString(36),a=Hf(n,e);return`${s+qf(`${i+a+o+r}`).substring(1,n)}`},Zf=Xf();Mh.getConstants=()=>({defaultLength:24,bigLength:32}),Mh.init=Xf,Mh.createId=Zf,Mh.bufToBigInt=zf,Mh.createCounter=Yf,Mh.createFingerprint=Jf,Mh.isCuid=(e,{minLength:t=2,maxLength:n=32}={})=>{const r=e.length,s=/^[0-9a-z]+$/;try{if("string"==typeof e&&r>=t&&r<=n&&s.test(e))return!0}finally{}return!1};const{createId:Qf,init:eg,getConstants:tg,isCuid:ng}=Mh;var rg=Qf;const sg=Ya("getUniqueId"),ig=({reply:e,sourceServiceId:t})=>{sg(`Generating unique id for service "${t}"`);return e({success:[rg()]})},og=Ya("getActiveServices"),ag=async({transport:e,sourceServiceId:t,reply:n})=>{if(og(`Received GetServices request from ${e} [${t}]`),e===fa.WS){let e=Ac.getActiveServices();const r=Ch(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let s=[];if(r.transport===fa.WS){if(!r?.extraInfo.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(Ac.isInternalKemuService),i=e.filter((e=>e.devMode&&Ac.isNotInternalKemuService(e))),o=e.filter((e=>Ac.isOfficialKemuService(e)&&Ac.isNotInternalKemuService(e)&&Ac.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=await(async e=>{const{features:t}=await Sh(e);return t})(r.extraInfo.wsApiKey),c=a?.hub_services??0,l=o.slice(0,c);s=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,...i,...l]}const i=Ac.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:Ac.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:i,installed:s}]})}},cg=p(M(import.meta.url)),lg=Ya("hub"),ug=new function(e){const t={};let n=console.log;const r={};let s=e||String(Date.now());const i={},o=e=>!i[e],a=(e,t,n,r,s,i)=>{let a=hl?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:i.success?i.success:[i],messageId:t,type:i.success?"response":"error"}};return o(r)&&(a=Xl.encode(c,n,r)),s(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,s,i,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,i.targetServiceId,i.sourceServiceId,s,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:i.sourceServiceId,send:s})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,s,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,i,a,c,l)=>{if(!i){const e="No send buffer function provided.";throw n&&n(e),e}Zl+=1;const u=`${s}-${Zl}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:i,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let p=hl?new ArrayBuffer(0):Buffer.alloc(0);const h={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(p=Xl.encode(h,a,c)),t[u]=d,n&&n(`Calling remote function "${e}" with message id "${u}"`);const f="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||f||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=t[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),i(p,{sourceServiceId:a,targetServiceId:c,msg:h}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{s=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,i)=>{Zl+=1;const a=`${s}-${Zl}-multicast-${e.substring(0,10)}`;let c=hl?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=o(r[0].serviceId);u&&(c=Xl.encode(l,i,r[0].serviceId));for(let t=0;t<r.length;t++)try{const s=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${s.serviceId}]`),0!==t&&(u=o(s.serviceId),u&&(c=Xl.patchEncodedHeader(c,{toServiceId:s.serviceId}))),s.sendFn(c,{msg:l,sourceServiceId:i,targetServiceId:s.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{i[e]=t}}}("hub");ug.setLogger(lg);const dg=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=Ch(n.targetServiceId);if(!r)return lg(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,fa.IPC;const s=t.json?.messageId;return lg(`Forwarding message from ${n.sourceServiceId} to ${n.targetServiceId}, msgId: ${s}`),r.send(n.rawMessage,{sourceServiceId:n.sourceServiceId,targetServiceId:n.targetServiceId,msg:{json:t.json}}),!0}return!1},pg=({sourceServiceId:e,args:t})=>{const n=Ac.getServiceBySessionId(e);if(n){const r=kh(n.info.name,n.info.version),s=kh(n.info.name,"*");if(!r.length&&!s.length)return;const i=[...r,...s],o=t[0],a={outputs:o.outputs,variantId:o.variantId,source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};ug.broadcast(pa.BroadcastEvent,[a],i,0)}},hg=e=>{const{send:t,transmission:n,json:r}=e;lg(`Raw message Id received from WS: ${r?.messageId}`);dg(fa.WS,e)||ug.processMessage(fa.WS,t,n,r)},fg=e=>{const t=(n=e,`${da.SocketAcknowledge}${n}`);var n;Zp.sendCommand(e,t)},gg=(e,t)=>{lg(`Received unknown command [${t}] from service ${e}`)},mg=async e=>{const{args:t,sourceServiceId:n,send:r,reply:s}=e,{apiKey:i}=t[0],o=n;await xh({serviceSessionId:n,transport:fa.WS,send:r,terminateFn:()=>{Zp.terminateConnection(n)},extraInfo:{websocketId:o,wsApiKey:i}}),s({success:[]})},vg=e=>{lg(`WS Client ${e} disconnected`),Oh(e)},yg=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==fa.IPC){var s;lg(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Ac.getMatchingDevService(n.name,n.version,"stopped");if(t){lg(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const i=Ch(t.info.sessionId);if(!i)return void lg(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);i.send=r,Ih[s=e]?delete Ih[s]:wh(`Could not find source client with session id ${s}`),ql(e,t.info.sessionId);const o=await ac(n,n.path);t.info={...t.info,...o},lg(`Updating manifest for dev service ${t.info.sessionId}`),Ac.setServiceManifest(t.info.sessionId,o,"running"),lg(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),zl(t.info.sessionId,(e=>`${da.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=Ih[e];t?t.isDevClient?(t.disconnected=!1,t.transport===fa.IPC&&(Eh(),Nh(e))):wh(`Client with session id ${e} is not a dev client`):wh(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{Ac.addDevService(e,n,"running");const t=Ch(e);t?t.isDevClient=!0:xh({serviceSessionId:e,transport:fa.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}lg(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var bg=async e=>{lg("Starting Kemu Hub...");const t=e?.ipc?.appSpace||"kemu.",n=e?.ipc?.id||"widgets";ug.registerFunction(pa.GetServiceContents,mh),ug.registerFunction(pa.GetServices,ag),ug.registerFunction(pa.ShowSecretsConfigScreen,(async({args:t,reply:n})=>{const[{name:r,version:s}]=t;e?.onShowSecretsScreen?(await e.onShowSecretsScreen(r,s),n({success:[]})):n({error:"This hub does not support showing secrets configuration screens",errCode:"GUI_NOT_SUPPORTED"})})),ug.registerFunction(pa.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===fa.WS){const[e]=n,s=Ch(r);if(!s)return t({error:`Session id "${r}" not found`});lg(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),s?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),ug.registerFunction(pa.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===fa.WS){const[e]=n,s=Ch(r),i=e.targetService;if(!s)return t({error:`Session id "${r}" not found`});if(lg(`Service ${r} subscribing to "${i.serviceName} (${i.version})"`),"hub"===i.serviceName)return s.addSubscription(i),void t({success:[]});if(!s.addSubscription(i))return lg(`Service ${r} already subscribed to "${i.serviceName} (${i.version})", ignoring request.`),t({success:[]});const o=Ac.getMatchingService(i.serviceName,i.version);if(!o)return lg(`Service ${i.serviceName} ${i.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return lg(`Service ${i.serviceName} ${i.version} does not have an event emitter, removing subscription`),s.removeSubscription(i),t({error:`Service "${i.serviceName} (${i.version})" does not produce events`});const a=Ch(o.info.sessionId);return a?.extraInfo.ipcSocketId&&(lg(`Sending Broadcast START command to service ${o.info.sessionId}`),zl(a?.extraInfo.ipcSocketId,da.BroadcastStart)),t({success:[]})}})),ug.registerFunction("stopService",eh),ug.registerFunction("removeService",nh),ug.registerFunction("launchService",sh),ug.registerFunction("getMatchingServices",oh),ug.registerFunction("getSecretsValues",lh),ug.registerFunction(pa.GetMappedSecrets,hh),ug.registerFunction(pa.BroadcastEvent,pg),ug.registerFunction(pa.ServiceManifest,yg),ug.registerFunction(pa.ChooseDirectoryDialog,Bh),ug.registerFunction(pa.ChooseFileDialog,jh),ug.registerFunction(pa.GetUniqueId,ig),ug.registerFunction(pa.SocketAckResponse,mg),Hl((e=>{const{send:t,transmission:n,json:r}=e;lg(`Raw message Id received from IPC: ${r?.messageId}`);dg(fa.IPC,e)||ug.processMessage(fa.IPC,t,n,r)})),Zp.onMessageReceived(hg),Zp.onClientConnected(fg),Zp.onClientCommand(gg),Zp.onClientDisconnected(vg),Kl(Ph),Gl((e=>{const t=(e=>`${da.IpcAcknowledge}${e}`)(e);zl(e,t)})),Vl((e=>{lg(`IPC socket [${e}] disconnected`);const t=Ch(e);if(t){lg(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Ac.getServiceBySessionId(t.serviceSessionId);Ac.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,Eh()):Oh(t.serviceSessionId)}})),await Wl({ipcAppSpace:t,ipcId:n}),e?.ws?.disabled||await Zp.startServer(e?.ws?.port||5368);const r=e?.defaultServicesPath||u.resolve(cg,"defaultServices"),s=process.env.DEV_SESSION_ID;Ac.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:t,id:n}),e?.servicesInstallPath&&(e=>{lc=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{uc=e})(e.testServicesInstallPath);const i=dc(),o=uc||tc,a=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=i,t.__KEMU_USER_TEST_SERVICES_PATH=o,t},c=async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{});e?.getServiceSecretsFn?(Ac.setGetSecretsFunction(e.getServiceSecretsFn),uh(e.getServiceSecretsFn)):(Ac.setGetSecretsFunction(a),uh(a)),fh(e?.getMappedSecretsFn?e.getMappedSecretsFn:c),Ac.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return F("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await Ac.loadServices(r,{fixedSession:s?parseInt(s):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0}),null!==e?.servicesInstallPath&&(await cc(i)||await f(i,{recursive:!0}),await Ac.loadServices(i,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await Ac.launchServices({noSpawningList:l||[]}),lg("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&Dh({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},Sg=e=>{if(e===fa.WS)return{handleWebsocketConnectionEvent:fg,handleWebsocketClientDisconnectionEvent:vg,handleWebsocketMessage:hg,handleWebsocketClientCommand:gg,getRemoteInvoke:()=>ug}},wg=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Ac.getAllServices().every((e=>"running"===e.status))){if(e.every((e=>"running"===Ac.getMatchingService(e.name,e.version)?.status)))return n()}t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let Ig;const _g=vo("run"),$g=va(),Cg=1e3,kg=S(process.argv.slice(2));global.ImageData=V,Tt({createCanvas:(e,t)=>z(e,t)});const Eg={createImageDataLike:(e,t,n,r="srgb")=>{let s;return s=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:s,width:t,height:n,colorSpace:r,_kemuType:ce.ImageData}},loadImageFile:async e=>{const t=await H(e),n=z(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}};var xg={start:async n=>{const r=n?.recipePath||kg.recipePath||process.env.KEMU_EDGE_RECIPE_PATH;if(!r)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].");if(!n.apiKey)throw new Error("`apiKey` not provided. Please specify it in the config object with the `apiKey` property.");const s=r.endsWith(".json"),i=s?R(r):r,o=s?r:W(i,"recipe.json"),a=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await e(G(o),"utf-8"));if(!a)throw new Error("Failed to parse recipe file");await Us();const c={id:a.id||String(Date.now()),version:1,author:""};(e=>{gr=e})(console);const l=Sg(fe.WS),u=(e,t)=>{if(t)l?.handleWebsocketMessage({send:p,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;l?.handleWebsocketClientCommand(Cg,t)}},d=(ro={instanceServiceId:Cg,sendBuf:u,sendCmd:u,triggerOnCommand:(...e)=>so(...e),triggerOnConnected:()=>io(),triggerOnDisconnected:()=>oo(),triggerOnMessageReceived:(...e)=>ao(...e)},ro);const p=(e,t)=>{if(t)d.triggerOnMessageReceived({send:u,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;d.triggerOnCommand(t)}},h=ba(),f=l.getRemoteInvoke();h.disableServiceEncoding(0,!0),f.disableServiceEncoding(Cg,!0);const g=Object.values(a.blocks[oe].gates).filter((e=>e.type===je.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),m=g.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),v=W(i,"services"),y=await t(v).then((()=>!0)).catch((()=>!1));await bg({recipeRootPath:i,servicesInstallPath:y?W(i,"services"):null,noDefaultServices:!0,ws:{disabled:!0},ipc:{appSpace:"kemu-runner.",id:c.id}}),_g("Waiting for services to run"),await wg(m),_g("All services are running"),Ai($g);const b=await ki(a,"runner",c.version,c.author,gi.Desktop);return Ig=b,ya(b),await ga(n.apiKey),new Promise(((e,t)=>{var n;ma("acknowledged",(async()=>{await $g.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:s}=await xi(b);if(n.length>0){const e=`Some widgets failed to initialize: ${n.join(", ")}`;return t(e)}await s().catch((e=>{console.error("Error invoking recipe loaded widgets: ",e)})),_g("Recipe started"),e({sendToInputWidget:r})})),d.triggerOnConnected(),d.triggerOnCommand((n=Cg,`${de.SocketAcknowledge}${n}`))}))},terminate:async()=>{Ig&&await Ei(Ig)}};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{ce as DataType,xg as default,Eg as utils};